今天来看下pytest的运行次序
(1)准备这样一个测试脚本,test_py_01.py
import pytest
class Test01:
def setup_class(self):
print('setup_class')
def teardown_class(self):
print('teardown_class')
def setup(self):
print('setup')
def teardown(self):
print('teardown')
def test_a(self):
print('aaaa')
assert 'a' == 'a'
@pytest.mark.flaky(reruns=1, reruns_delay=2)
def test_b(self):
print('bbbb')
assert 'b' == 'b1'
def test_c(self):
print('cccc')
assert 'c' == 'c1'
if __name__ == '__main__':
pytest.main(["-s"])
(2)准备一个pytest的配置文件 pytest.ini
[pytest]
addopts = --html=./report/res.html --reruns 2 --reruns-delay=2
(3)运行一下
C:\PycharmProjects\First\venv\Scripts\python.exe C:/InterfaceTest_01/testcase/pytest_demo/test_py_1.py
============================= test session starts =============================
platform win32 -- Python 3.6.5, pytest-5.3.5, py-1.8.1, pluggy-0.13.1
rootdir: C:\InterfaceTest_01, inifile: pytest.ini
plugins: aoc-1.1, html-2.0.1, metadata-1.8.0, rerunfailures-8.0
collected 3 items
test_py_1.py setup_class
setup
aaaa
teardown
.setup
bbbb
teardown
Rsetup
bbbb
teardown
Fsetup
cccc
teardown
teardown_class
Rsetup_class
setup
cccc
teardown
teardown_class
Rsetup_class
setup
cccc
teardown
teardown_class
F
================================== FAILURES ===================================
________________________________ Test01.test_b ________________________________
self = <testcase.pytest_demo.test_py_1.Test01 object at 0x04A355D0>
@pytest.mark.flaky(reruns=1, reruns_delay=2)
def test_b(self):
print('bbbb')
> assert 'b' == 'b1'
E AssertionError: assert 'b' == 'b1'
E - b
E + b1
test_py_1.py:23: AssertionError
________________________________ Test01.test_c ________________________________
self = <testcase.pytest_demo.test_py_1.Test01 object at 0x04A6FD90>
def test_c(self):
print('cccc')
> assert 'c' == 'c1'
E AssertionError: assert 'c' == 'c1'
E - c
E + c1
test_py_1.py:27: AssertionError
- generated html file: file://C:\InterfaceTest_01\testcase\pytest_demo\report\res.html -
==================== 2 failed, 1 passed, 3 rerun in 6.20s =====================
Process finished with exit code 0
分析一下哈
优先使用脚本中的错误重试规则,然后使用pytest.ini文件中的规则。
第一遍执行
setup_class 一遍只运行一次
setup 每个函数前运行一次
aaaa 第一个函数,断言成功,执行一次
teardown 每个函数结束后运行一次
.setup 每个函数前运行一次
bbbb 第二个函数,断言失败
teardown
Rsetup R rerun
bbbb 第二个函数运行失败,根据规则,重试1次
teardown
Fsetup F 第一轮的第三个函数
cccc 第三个函数 失败,要重试
teardown
teardown_class 第一遍结束
Rsetup_class
setup
cccc 根据统一配置规则,重新运行第3个函数,第一次
teardown
teardown_class
Rsetup_class
setup
cccc 根据统一配置规则,重新运行第3个函数,第二次
teardown
teardown_class
F