[Python] 在 pytest 中,在 fixture 條件滿足時跳過 test case 不執行

[Python] 在 pytest 中,在 fixture 條件滿足時跳過 test case 不執行

今天在用 pytest 寫一個測試程式,用到了一個 fixture 類似像下面這樣:

@pytest.fixture(scope='module')
def ca():
wrapper = Wrapper()
return wrapper if wrapper.initialize() else None

 

這個名叫 ca 的 fixture 有可能是 None,或者是一個 Wrapper 物件~

我想作的事情是當這個 fixture 是 None 的時候,就跳過某些 test case 不要執行~

可是如果直接用 pytest.mark.skipif(ca is None) 的話,會說 ca 這個名字找不到…

ca/test_ca.py:5: in <module>
>   @pytest.mark.skipif(ca is None)
E       NameError: name 'ca' is not defined

 

查了一下,似乎 pytest 目錄還不能在 skipif() 裡面使用 fixture,不過也是有解法…

可以改在 test case 裡面先對 fixture 作判斷之後,再直接用 pytest.skip() 來跳過 test case~

舉例來說,下面的程式會在 ca 是 None 的時候,跳過這個 test case 不執行:

def test_verify(ca):
if ca is None:
pytest.skip()
assert ca.verify() == True

 

這個方法是醜了一些,不過也是可以運作啦~

 

參考資料:Imperative xfail from within a test or setup function

 

(本頁面已被瀏覽過 408 次)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料