Pytest自動化測試 – 必知必會的一些插件

Pytest擁有豐富的插件架構,超過800個以上的外部插件和活躍的社區,在PyPI項目中以「 pytest- *」為標識。

本篇將列舉github標星超過兩百的一些插件進行實戰演示。

插件庫地址://plugincompat.herokuapp.com/

 


1、pytest-html:用於生成HTML報告

一次完整的測試,測試報告是必不可少的,但是pytest自身的測試結果過於簡單,而pytest-html正好可以給你提供一份清晰報告。

安裝:

pip install -U pytest-html

用例:

# test_sample.py
import pytest
# import time

# 被測功能
def add(x, y):
    # time.sleep(1)
    return x + y

# 測試類
class TestLearning:
    data = [
        [3, 4, 7],
        [-3, 4, 1],
        [3, -4, -1],
        [-3, -4, 7],
    ]
    @pytest.mark.parametrize("data", data)
    def test_add(self, data):
        assert add(data[0], data[1]) == data[2]

運行:

E:\workspace-py\Pytest>pytest test_sample.py --html=report/index.html
========================================================================== test session starts ==========================================================================
platform win32 -- Python 3.7.3, pytest-6.0.2, py-1.9.0, pluggy-0.13.0
rootdir: E:\workspace-py\Pytest
plugins: allure-pytest-2.8.18, cov-2.10.1, html-3.0.0, rerunfailures-9.1.1, xdist-2.1.0
collected 4 items                                                                                                                                                        

test_sample.py ...F                                                                                                                                                [100%]

=============================================================================== FAILURES ================================================================================
_____________________________________________________________________ TestLearning.test_add[data3] ______________________________________________________________________

self = <test_sample.TestLearning object at 0x00000000036B6AC8>, data = [-3, -4, 7]

    @pytest.mark.parametrize("data", data)
    def test_add(self, data):
>       assert add(data[0], data[1]) == data[2]
E       assert -7 == 7
E        +  where -7 = add(-3, -4)

test_sample.py:20: AssertionError
------------------------------------------------- generated html file: file://E:\workspace-py\Pytest\report\index.html --------------------------------------------------
======================================================================== short test summary info ========================================================================
FAILED test_sample.py::TestLearning::test_add[data3] - assert -7 == 7
====================================================================== 1 failed, 3 passed in 0.14s ======================================================================

 

運行完,會生產一個html文件 和 css樣式文件夾assets,用瀏覽器打開html即可查看清晰的測試結果。

 

後面我將會更新更加清晰美觀的測試報告插件: allure-pytest

 


2、pytest-cov:用於生成覆蓋率報告

在做單元測試時,程式碼覆蓋率常常被拿來作為衡量測試好壞的指標,甚至,用程式碼覆蓋率來考核測試任務完成情況。

安裝:

pip install -U pytest-cov

 運行:

E:\workspace-py\Pytest>pytest --cov=.
========================================================================== test session starts ==========================================================================
platform win32 -- Python 3.7.3, pytest-6.0.2, py-1.9.0, pluggy-0.13.0
rootdir: E:\workspace-py\Pytest
plugins: allure-pytest-2.8.18, cov-2.10.1, html-3.0.0, rerunfailures-9.1.1, xdist-2.1.0
collected 4 items                                                                                                                                                        

test_sample.py ....                                                                                                                                                [100%]

----------- coverage: platform win32, python 3.7.3-final-0 -----------
Name             Stmts   Miss  Cover
------------------------------------
conftest.py          5      3    40%
test_sample.py       7      0   100%
------------------------------------
TOTAL               12      3    75%


=========================================================================== 4 passed in 0.06s ===========================================================================

 


3、pytest-xdist:實現多執行緒、多平台執行

通過將測試發送到多個CPU來加速運行,可以使用-n NUMCPUS指定具體CPU數量,或者使用-n auto自動識別CPU數量並全部使用。

安裝:

pip install -U pytest-xdist

用例:

# test_sample.py
import pytest
import time

# 被測功能
def add(x, y):
    time.sleep(3)
    return x + y

# 測試類
class TestAdd:
    def test_first(self):
        assert add(3, 4) == 7

    def test_second(self):
        assert add(-3, 4) == 1

    def test_three(self):
        assert add(3, -4) == -1

    def test_four(self):
        assert add(-3, -4) == 7

 運行:

E:\workspace-py\Pytest>pytest test_sample.py
========================================================================== test session starts ==========================================================================
platform win32 -- Python 3.7.3, pytest-6.0.2, py-1.9.0, pluggy-0.13.0
rootdir: E:\workspace-py\Pytest
plugins: allure-pytest-2.8.18, cov-2.10.1, html-3.0.0, rerunfailures-9.1.1, xdist-2.1.0
collected 4 items                                                                                                                                                        

test_sample.py ....                                                                                                                                                [100%]

========================================================================== 4 passed in 12.05s ===========================================================================

E:\workspace-py\Pytest>pytest test_sample.py -n auto
========================================================================== test session starts ==========================================================================
platform win32 -- Python 3.7.3, pytest-6.0.2, py-1.9.0, pluggy-0.13.0
rootdir: E:\workspace-py\Pytest
plugins: allure-pytest-2.8.18, assume-2.3.3, cov-2.10.1, forked-1.3.0, html-3.0.0, rerunfailures-9.1.1, xdist-2.1.0
gw0 [4] / gw1 [4] / gw2 [4] / gw3 [4]
....                                                                                                                                                               [100%]
=========================================================================== 4 passed in 5.35s ===========================================================================

E:\workspace-py\Pytest>pytest test_sample.py -n 2
========================================================================== test session starts ==========================================================================
platform win32 -- Python 3.7.3, pytest-6.0.2, py-1.9.0, pluggy-0.13.0
rootdir: E:\workspace-py\Pytest
plugins: allure-pytest-2.8.18, assume-2.3.3, cov-2.10.1, forked-1.3.0, html-3.0.0, rerunfailures-9.1.1, xdist-2.1.0
gw0 [4] / gw1 [4]
....                                                                                                                                                               [100%]
=========================================================================== 4 passed in 7.65s ===========================================================================

上述分別進行了未開多並發、開啟4個cpu、開啟2個cpu,從運行耗時結果來看,很明顯多並發可以大大縮減你的測試用例運行耗時。

 


4、pytest-rerunfailures:實現重新運行失敗用例

 我們在測試時可能會出現一些間接性故障,比如介面測試遇到網路波動,web測試遇到個別插件刷新不及時等,這時重新運行則可以幫忙我們消除這些故障。

 安裝:

pip install -U pytest-rerunfailures

運行:

E:\workspace-py\Pytest>pytest test_sample.py --reruns 3
========================================================================== test session starts ==========================================================================
platform win32 -- Python 3.7.3, pytest-6.0.2, py-1.9.0, pluggy-0.13.0
rootdir: E:\workspace-py\Pytest
plugins: allure-pytest-2.8.18, cov-2.10.1, html-3.0.0, rerunfailures-9.1.1, xdist-2.1.0
collected 4 items                                                                                                                                                        

test_sample.py ...R                                                                                                                                                [100%]R
 [100%]R [100%]F [100%]

=============================================================================== FAILURES ================================================================================
___________________________________________________________________________ TestAdd.test_four ___________________________________________________________________________

self = <test_sample.TestAdd object at 0x00000000045FBF98>

    def test_four(self):
>       assert add(-3, -4) == 7
E       assert -7 == 7
E        +  where -7 = add(-3, -4)

test_sample.py:22: AssertionError
======================================================================== short test summary info ========================================================================
FAILED test_sample.py::TestAdd::test_four - assert -7 == 7
================================================================= 1 failed, 3 passed, 3 rerun in 0.20s ==================================================================

 

如果你想設定重試間隔,可以使用 –rerun-delay 參數指定延遲時長(單位秒); 

如果你想重新運行指定錯誤,可以使用 –only-rerun 參數指定正則表達式匹配,並且可以使用多次來匹配多個。

pytest --reruns 5 --reruns-delay 1 --only-rerun AssertionError --only-rerun ValueError

如果你只想標記單個測試失敗時自動重新運行,可以添加 pytest.mark.flaky() 並指定重試次數以及延遲間隔。

@pytest.mark.flaky(reruns=5, reruns_delay=2)
def test_example():
    import random
    assert random.choice([True, False])

 


5、pytest-randomly:實現隨機排序測試

測試中的隨機性非常越大越容易發現測試本身中隱藏的缺陷,並為你的系統提供更多的覆蓋範圍。

安裝:

pip install -U pytest-randomly

運行:

E:\workspace-py\Pytest>pytest test_sample.py
========================================================================== test session starts ==========================================================================
platform win32 -- Python 3.7.3, pytest-6.0.2, py-1.9.0, pluggy-0.13.0
Using --randomly-seed=3687888105
rootdir: E:\workspace-py\Pytest
plugins: allure-pytest-2.8.18, cov-2.10.1, html-3.0.0, randomly-3.5.0, rerunfailures-9.1.1, xdist-2.1.0
collected 4 items                                                                                                                                                        

test_sample.py F...                                                                                                                                                [100%]

=============================================================================== FAILURES ================================================================================
___________________________________________________________________________ TestAdd.test_four ___________________________________________________________________________

self = <test_sample.TestAdd object at 0x000000000567AD68>

    def test_four(self):
>       assert add(-3, -4) == 7
E       assert -7 == 7
E        +  where -7 = add(-3, -4)

test_sample.py:22: AssertionError
======================================================================== short test summary info ========================================================================
FAILED test_sample.py::TestAdd::test_four - assert -7 == 7
====================================================================== 1 failed, 3 passed in 0.13s ======================================================================

E:\workspace-py\Pytest>pytest test_sample.py
========================================================================== test session starts ==========================================================================
platform win32 -- Python 3.7.3, pytest-6.0.2, py-1.9.0, pluggy-0.13.0
Using --randomly-seed=3064422675
rootdir: E:\workspace-py\Pytest
plugins: allure-pytest-2.8.18, assume-2.3.3, cov-2.10.1, forked-1.3.0, html-3.0.0, randomly-3.5.0, rerunfailures-9.1.1, xdist-2.1.0
collected 4 items                                                                                                                                                        

test_sample.py ...F                                                                                                                                                [100%]

=============================================================================== FAILURES ================================================================================
___________________________________________________________________________ TestAdd.test_four ___________________________________________________________________________

self = <test_sample.TestAdd object at 0x00000000145EA940>

    def test_four(self):
>       assert add(-3, -4) == 7
E       assert -7 == 7
E        +  where -7 = add(-3, -4)

test_sample.py:22: AssertionError
======================================================================== short test summary info ========================================================================
FAILED test_sample.py::TestAdd::test_four - assert -7 == 7
====================================================================== 1 failed, 3 passed in 0.12s ======================================================================

 

這功能默認情況下處於啟用狀態,但可以通過標誌禁用(假如你並不需要這個模組,建議就不要安裝)。

pytest -p no:randomly

如果你想指定隨機順序,可以通過 –randomly-send 參數來指定,也可以使用 last 值來指定沿用上次的運行順序。

pytest --randomly-seed=4321
pytest --randomly-seed=last

 

 


6、其他活躍的插件

還有一些其他功能性比較活躍的、一些專門為個別框架所訂製的、以及為了兼容其他測試框架,這裡暫不做演示,我就簡單的做個列舉:

pytest-django:用於測試Django應用程式(Python Web框架)。

pytest-flask:用於測試Flask應用程式(Python Web框架)。

pytest-splinter:兼容Splinter Web自動化測試工具。

pytest-selenium:兼容Selenium Web自動化測試工具。

 

pytest-testinfra:測試由Salt,Ansible,Puppet, Chef等管理工具配置的伺服器的實際狀態。

pytest-mock:提供一個mock韌體,創建虛擬的對象來實現測試中個別依賴點。

pytest-factoryboy:結合factoryboy工具用於生成各式各樣的數據。

pytest-qt:提供PyQt5PySide2應用程式編寫測試。

pytest-asyncio:用於使用pytest測試非同步程式碼。

pytest-bdd:實現了Gherkin語言的子集,以實現自動化項目需求測試並促進行為驅動的開發。

pytest-watch:為pytest提供一套快捷CLI工具。

 

pytest-testmon:可以自動選擇並重新執行僅受最近更改影響的測試。

pytest-assume:用於每個測試允許多次失敗。

pytest-ordering:用於測試用例的排序功能。

pytest-sugar:可立即顯示失敗和錯誤並顯示進度條。

 

作者:Leozhanggg

出處://www.cnblogs.com/leozhanggg/p/14041556.html

本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。