在實際使用pytest編寫測試用例腳本時,會需要用到兩個或多個測試用例依賴運行,就比如登錄的時候我們需要先注冊,那登錄的用例就需要依賴注冊的用例。我們想要登錄條件很簡單可直接通過pytest.mark.skip裝飾器完成。但是想要判斷注冊用例是否通過,根據是否通過執行登錄的用例就要將兩個用例之間建立依賴關系。
將兩個或多個用例之間建立依賴關系,我們需要用到一個pytest的第三方插件:pytest-dependency
官網:https://pytest-dependency.readthedocs.io/en/latest/usage.html#basic-usage
# 下載插件
pip install pytest-depends
實際使用
1 import pytest 2 3 4 def test_01(): 5 print("用戶注冊") 6 assert 1 == 0 7 8 9 def test_02(): 10 print("用戶登錄") 11 12 13 if __name__ == '__main__': 14 pytest.main(["test_demo.py"])
這樣肯定會在執行完第一個用例后報錯,那如果第二個用例需要依賴注冊,那肯定登錄的用例以及后面的用例全部執行失敗;
添加依賴關系
1 import pytest 2 3 4 @pytest.mark.dependency() # 被依賴的用例同樣需要裝飾 5 def test_01(): 6 print("用戶注冊") 7 assert 1 == 0 8 9 10 @pytest.mark.depends(on=["test_01"]) # depends 列表中接收需要依賴的用例名稱,如果依賴多個,則直接將用例名稱寫入到列表即可 11 def test_02(): 12 print("用戶登錄") 13 14 15 if __name__ == '__main__': 16 pytest.main(["test_demo.py"])
=========================== short test summary info =========================== FAILED test_demo.py::test_01 - assert 1 == 0 ================== 1 failed, 1 skipped in 0.23s ===================
執行結果為一個失敗,一個跳過;
第二種用法通過給用例設立別名盡心依賴;
1 import pytest 2 3 4 @pytest.mark.depends(name='test') # name 設置別名 5 def test_01(): 6 print("用戶注冊") 7 assert 1 == 0 8 9 10 @pytest.mark.depends(on=["test"]) # depends 填寫依賴的別名 11 def test_02(): 12 print("用戶登錄") 13 14 15 if __name__ == '__main__': 16 pytest.main(["test_demo.py"])
=========================== short test summary info =========================== FAILED test_demo.py::test_01 - assert 1 == 0 ================== 1 failed, 1 skipped in 0.23s ===============================
執行結果與上面一樣
第三種用法,通過pytest對方法的完全限定名進行依賴,怎么知道完全限定名是什么?
test_demo.py::test_01 FAILED [ 50%] # 加粗部分就是pytest對用例的完全限定名
test_demo.py::test_02 SKIPPED (test_02 depends on test) [100%]
import pytest def test_01(): print("用戶注冊") assert 1 == 0 @pytest.mark.depends(on=["test_demo.py::test_01"]) def test_02(): print("用戶登錄") if __name__ == '__main__': pytest.main(["test_demo.py"])
=========================== short test summary info =========================== FAILED test_demo.py::test_01 - assert 1 == 0 ================== 1 failed, 1 skipped in 0.23s ===============================
插件依賴的應用很靈活,一個用例可以依賴其他用例也可以被其他用例依賴。很多使用的方法可以在操作中進行嘗試。