2017-03-13 67 views
3

我正在運行一個測試,它使用隨機選擇的兩個變量。但是,如果兩個變量不同,那麼測試只會「有效」。如果它們相同,我想'重新啓動'測試。是否有命令讓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_recursiveword1word2是不同的。但是,在if __name__ == "__main__"塊中,如果我用pytest.main調用替換簡單函數調用,則測試將失敗(一半時間),因爲遞歸不起作用。

我該如何讓測試'重新啓動'本身,以便該示例適用於Pytest?

+1

爲什麼輸入必須是隨機的? –

回答

5

您應該爲測試獲得正確的設置,而不是試圖將流量控制添加到測試運行器。 避免測試代碼中的邏輯,因爲那樣你就有義務測試測試。

你可以使用random.sample,而不是使用random.choice

word1, word2 = random.sample(WORDS, 2) 

假設有在WORDS沒有重複,他們保證是從人口唯一的選擇。

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 
相關問題