Pytest는 풍부한 플러그인 아키텍처, 800개 이상의 외부 플러그인 및 활발한 커뮤니티를 갖추고 있으며 PyPI 프로젝트에서 "pytest-*"로 식별됩니다.
이 기사에서는 실제 데모를 위해 200개 이상의 github 스타가 포함된 일부 플러그인을 나열합니다.
플러그인 라이브러리 주소: http://plugincompat.herokuapp.com/
1. pytest-html: HTML 보고서를 생성하는 데 사용됩니다.
완전한 테스트를 위해서는 테스트 보고서가 필수인데, pytest 자체의 테스트 결과가 너무 단순해서 pytest-html이 명확한 보고서를 제공할 수 있다.
설치하다:
pip 설치 -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 스타일 폴더 자산이 생성됩니다. 브라우저에서 html을 열어 명확한 테스트 결과를 확인하세요.
추후에 더욱 명확하고 아름다운 테스트 리포트 플러그인을 업데이트하겠습니다: allure-python
2. pytest-cov: 적용 범위 보고서를 생성하는 데 사용됩니다.
단위 테스트를 할 때 코드 커버리지는 테스트 품질을 측정하는 지표로 자주 사용되며, 코드 커버리지는 테스트 작업의 완료 여부를 평가하는 데에도 사용됩니다.
설치하다:
pip 설치 -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 설치 -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: 실패한 테스트 사례 재실행 구현
인터페이스 테스트의 네트워크 변동, 웹 테스트의 개별 플러그인 새로 고침 지연 등 테스트 중에 간접적인 오류가 발생할 수 있습니다. 이때 다시 실행하면 이러한 오류를 제거하는 데 도움이 될 수 있습니다.
설치하다:
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(): 무작위로 가져오기 random.choice([True, False])를 주장하십시오.
5. pytest-randomly: 무작위 정렬 테스트 구현
테스트의 무작위성이 매우 높으면 테스트 자체에서 숨겨진 결함을 더 쉽게 찾고 시스템에 더 많은 적용 범위를 제공할 수 있습니다.
설치하다:
pip install -U pytest-무작위로
달리다:
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 아니오:무작위로
무작위 순서를 지정하려면 --randomly-send 매개변수를 통해 지정하거나 마지막 값을 사용하여 마지막 실행 순서가 사용되도록 지정할 수 있습니다.
pytest --randomly-seed=4321
pytest --randomly-seed=마지막
6. 기타 활성 플러그인
또한 좀 더 활성화된 다른 기능도 있는데, 일부는 개별 프레임워크에 특별히 맞춤화되고 다른 테스트 프레임워크와 호환되기 위해 사용됩니다. 당분간 여기서는 설명하지 않겠습니다. 간단히 나열하겠습니다.
pytest-django : Django 애플리케이션(Python 웹 프레임워크)을 테스트하기 위한 것입니다.
pytest-flask : Flask 애플리케이션(Python 웹 프레임워크)을 테스트하기 위한 것입니다.
pytest-splinter : Splinter 웹 자동화 테스트 도구와 호환됩니다.
pytest-selenium : Selenium 웹 자동화 테스트 도구와 호환됩니다.
pytest-testinfra : Salt, Ansible, Puppet, Chef 등의 관리 도구로 구성된 서버의 실제 상태를 테스트합니다.
pytest-mock : 테스트에서 개별 종속성을 구현하기 위해 가상 객체를 생성하는 모의 펌웨어를 제공합니다.
pytest-factoryboy : 다양한 데이터를 생성하기 위해 Factoryboy 도구와 함께 사용됩니다.
pytest-qt : PyQt5 및 PySide2 애플리케이션에 대한 작성 테스트를 제공합니다.
pytest-asyncio : pytest를 사용하여 비동기 코드를 테스트합니다.
pytest-bdd : 자동화된 프로젝트 요구 사항 테스트를 활성화하고 동작 중심 개발을 촉진하기 위해 Gherkin 언어의 하위 집합을 구현합니다.
pytest-watch : pytest를 위한 빠른 CLI 도구 세트를 제공합니다.
pytest-testmon : 최근 변경 사항에만 영향을 받는 테스트를 자동으로 선택하고 다시 실행할 수 있습니다.
pytest-assume : 테스트당 여러 번의 실패를 허용하는 데 사용됩니다.
pytest-ordering : 테스트 케이스의 주문 기능입니다.
pytest-sugar : 진행률 표시줄을 통해 실패와 오류를 즉시 표시합니다.
pytest-dev / pytest-repeat : 단일 또는 다중 테스트를 반복적으로(지정 가능한 횟수) 실행할 수 있습니다.
이것은 100시간의 실제 연습이 포함된 Bilibili를 위한 가장 상세한 pytest 자동화 테스트 프레임워크 튜토리얼일 것입니다! ! !