pytest的一些實用插件實踐


1.多重校驗 pytest-assume

簡單的校驗assert,雖然可以寫多個assert

    def test_add1(self): assert add(2,3)==5 assert add(1,3)==3 assert add(2,5)==7 

由於第二個斷言失敗,那么下面的斷言就不會執行。
所以如果需要多個斷言,都執行就需要第三方插件 pytest-assume
安裝命令:

pip install pytest-assume

示例:

    def test_add2(self): pytest.assume(add(1,2)==3) pytest.assume(add(1,4)==3) pytest.assume(add(2,2)==4) 

這邊即使第二個斷言失敗了,第三個斷言還是會繼續執行。

 

2.設定執行順序 pytest-ordering

對於一些上下文依賴的,有時候可能需要設定一些特定執行順序,pytest的ordering插件,就很好的解決了這個問題
安裝命令

pip  install  pytest-ordering

示例腳本如下:

def test_order1(): print ("first test") assert True def test_order2(): print ("second test") assert True 

沒有加上ordering,執行順序是 test_order1----test_order2,如圖:

 

 
before.png

加上順序之后

@pytest.mark.run(order=2) def test_order1(): print ("first test") assert True @pytest.mark.run(order=1) def test_order2(): print ("second test") assert True 

結果如下:

 

 
after.png

5.失敗重跑 pytest-rerunfailures

失敗用例重跑,個人覺得這個是非常實用的插件。
舉個例子:
在做UI自動化,如selenuim或者appium時,遇到某些元素未能及時顯示,導致點擊失敗,如果加上重跑,那么將有效提高報告的准確性。
安裝命令:

pip install pytest-rerunfailures 

示例腳本

class TestRerun(): @pytest.mark.run(order=2) @pytest.mark.flaky(reruns=5) def test_random(self): print(1) pytest.assume((random.randint(0,4)+3)==5) @pytest.mark.run(order=3) def test_random2(self): ''' 不加mark 命令行中 pytest -sq demo_rerun.py --reruns 5 :return: ''' print(2) pytest.assume((random.randint(0,4)+3)==5) @pytest.mark.run(order=1) @pytest.mark.flaky(reruns=6, reruns_delay=2) def test_example(self): print(3) assert random.choice([True, False])

執行命令:

pytest -sq demo_rerun.py --reruns 5
pytest -sq demo_rerun.py --reruns 5  --reruns-delay 1

二者的區別是,下面在每次重跑之前會等待 1 s
同時也可以在腳本中指定定義重跑的次數,這個時候在運行的時候,就無需加上 --reruns 這個參數

@pytest.mark.flaky(reruns=6, reruns_delay=2) def test_example(self): print(3) assert random.choice([True, False]) 
 

對比可以看出,執行順序發生了變化


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM