pytest---用例失敗重跑


前言

  以前出去面試的時候,經常會遇到一個問題,你的自動化如果根據一些網絡原因,環境問題導致的用例失敗,怎么進行失敗重跑呢?以前用的unittest,沒有自動的失敗重跑內容,但是強大的pytest中有一個插件功能就能輕松幫助我們解決這個問題。

pytest-rerunfailures

pytest-rerunfailures是屬於pytest的插件,通常用來執行用例失敗后重新執行。

安裝: pip install pytest-rerunfailures 

源碼:https://github.com/pytest-dev/pytest-rerunfailures

其中pytest-rerunfailures有2種用法,一種是裝飾器的方法,另一種是命令行參數的方法。

裝飾器

首先介紹下,如何通過裝飾器的方法進行用例失敗重跑。

格式: @pytest.mark.flaky(reruns=3, reruns_delay=2)  

使用方法和前面介紹的一些基本相似通過pytest.mark的形式加上flakey方法。我們看到其中有2個參數,其中reruns表示失敗后執行幾次,reruns_delay表示失敗后等待幾秒后,在重新執行

裝飾器的方法不僅可以加到用例上,也可以加入到類上。

裝飾器在用例上

import pytest
import random

class Test01:

    @pytest.mark.flaky(reruns=3, reruns_delay=2)
    def test_01(self):
        a = random.randint(0, 3)
        print('---用例01---')
        print(a)
        assert a == 2

    def test_02(self):
        print('---用例02---')
        assert 1 == 1

if __name__ == '__main__':
    pytest.main(['-vs'])

通過下圖可以看到,我們執行用例1一共執行了3次,第一次設置的隨機值為1和斷言2不一致,進行重新跑,第2次隨機值為0和斷言2也不一樣,第3次的時候斷言相同了,用例通過

裝飾器在類上

import pytest
import random

@pytest.mark.flaky(reruns=3, reruns_delay=2)
class Test01:

    def test_01(self):
        a = random.randint(0, 2)
        print('---用例01---')
        print('用例01中的a:%s'%a)
        assert a == 2

    def test_02(self):
        c = random.randint(0, 2)
        print('---用例02---')
        print('用例02中的c:%s'%c)
        assert c == 1

if __name__ == '__main__':
    pytest.main(['-vs'])

通過下方執行結果可以很清楚的看到,我們class下的用例都進行了失敗重跑。

 

 

命令行參數

上述方法介紹了如何通過裝飾器的方法進行用例失敗重跑,下面介紹如何通過命令行的參數進行失敗重跑。

格式: pytest --reruns 3 --reruns-delay 2 或 pytest -vs --reruns=3 --reruns-delay=2 

參數詳解:其中reruns空格3 表示失敗重新運行3次,reruns-delay空格2 表示重新執行需要等待2秒。這里也可以使用等於來進行表示

import pytest
import random

class Test01:

    def test_01(self):
        a = random.randint(0, 2)
        print('---用例01---')
        print('用例01中的a:%s'%a)
        assert a == 2

    def test_02(self):
        c = random.randint(0, 2)
        print('---用例02---')
        print('用例02中的c:%s'%c)
        assert c == 1

if __name__ == '__main__':
    pytest.main(['-vs'])

通過下圖執行結果可以看出來,失敗重跑已經生效。

注意事項:裝飾器的方法和命令行的方法不能一起使用,不然的話會報錯!!!

 

簡單的通過實例介紹了用例失敗重跑的兩種方法,具體哪種方法好用,這個要看個人的喜好了。不過安靜還是推薦使用命令行參數。

 


免責聲明!

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



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