是否有命令使Pytest重启?

时间:2017-03-13 17:04:02

标签: python pytest

我正在运行一个使用随机选择的两个变量的测试。但是,该测试仅适用于'如果两个变量不同。如果它们是相同的,我想重新启动'测试。

基本上我尝试做类似以下的事情:

import random
import pytest

WORDS = ["foo", "bar"]

def test_maybe_recursive():
    word1 = random.choice(WORDS)
    word2 = random.choice(WORDS)

    # Ensure that 'word1' and 'word2' are different
    if word1 == word2:
        print("The two words are the same. Re-running the test...")
        test_maybe_recursive()

    assert word1 != word2       # The actual test, which requires 'word1' and 'word2' to be different

if __name__ == "__main__":
    test_maybe_recursive()
    # pytest.main([__file__, "-s"])     # This sometimes fails

在此示例中,我使用递归来确保test_maybe_recursive内,word1word2不同。但是,在if __name__ == "__main__"块中,如果我用pytest.main调用替换简单函数调用,则测试失败(一半时间),因为递归不起作用。

如何让测试重启'本身,以便该示例适用于Pytest?

2 个答案:

答案 0 :(得分:5)

您应该解决为测试设置正确的问题,而不是尝试将流量控制添加到测试运行器。 避免使用测试代码中的逻辑,因为那时您必须测试测试。

您可以使用The requested url does not exist(22): 'https://cache.ruby-lang.org/pub/ruby/4.2/ruby-4.2.7.tar.bz2' 代替random.sample

random.choice

假设word1, word2 = random.sample(WORDS, 2) 中没有重复项,则保证它们是人口中的唯一选择。

答案 1 :(得分:2)

不要重新调用该函数,只需让函数生成一些新单词:

import random
import pytest

WORDS = ["foo", "bar"]

def test_maybe_recursive():
    word1 = random.choice(WORDS)
    word2 = random.choice(WORDS)

    # Ensure that 'word1' and 'word2' are different
    while word1 == word2:
        print("The two words are the same. Re-running the test...")
        word1 = random.choice(WORDS)
        word2 = random.choice(WORDS)

    assert word1 != word2       # The actual test, which requires 'word1' and 'word2' to be different

if __name__ == "__main__":
    test_maybe_recursive()
    # pytest.main([__file__, "-s"])     # This sometimes fails