pytest---用例的執行順序


前言

  安靜以前出去面試的時候遇到過這樣一個問題:你怎么保證你的自動化用例的執行順序。當時安靜的回答是用例通過數字的形式進行標記,因為unittest執行是按照ascII碼的順序執行的。當時回答比較low。那我們看看如果用pytest怎么控制用例的執行順序。

 

pytest-ordering

pytest-ordering屬於pytest的一個插件,它可以控制pytest的執行順序。

安裝:  pip install pytest-ordering 

源碼:https://github.com/ftobia/pytest-ordering

pytest執行順序

pytest的執行順序是根據代碼編寫的順序進行執行的。

import pytest

class Test01():
    
    def test_02(self):
        print('\n---用例02---')

    def test_01(self):
        print('\n---用例01---')
    
    def test_03(self):
        print('\n---用例03---')

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

通過下圖可以看出來,我們執行的順序是先執行了用例2,然后用例1,最后用例3,所以說pytest的執行順序是默認編寫的順序來執行的。

 

定制用例執行順序

如果在特定一些自動化中,想要定制用例的操作步驟來執行,這個時候就用到了上面介紹的插件pytest-ordering來執行,具體插件怎么用呢?

這里還是需要前面介紹的mark的方法來執行。 @pytest.mark.run(order=X) x:表示執行順序 

import pytest

class Test01():

    @pytest.mark.run(order=3)
    def test_02(self):
        print('\n---用例02---')

    @pytest.mark.run(order=2)
    def test_01(self):
        print('\n---用例01---')

    @pytest.mark.run(order=1)
    def test_03(self):
        print('\n---用例03---')

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

通過下圖可以看出來,用例已經按照我們的要求,先執行用例3,在執行用例1,最后執行用例2的方法來的

 

這里需要注意的是,如果你在那個用例上面沒有添加執行順序要求的話,他會先執行帶有標記的用例,然后根據未標記的用例順序進行執行

import pytest

class Test01():

    def test_02(self):
        print('\n---用例02---')

    @pytest.mark.run(order=2)
    def test_01(self):
        print('\n---用例01---')

    @pytest.mark.run(order=1)
    def test_03(self):
        print('\n---用例03---')

    def test_04(self):
        print('\n---用例04---')


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

這里執行順序:先執行用例3然后在是用例1,最后按照順利順序執行用例2和用例4。

 

 

好了,pytest的用例執行順序,就是這么簡單,只要通過mark的方法進行標記就行了,但是千萬不要忘記了需要安裝插件

 


免責聲明!

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



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