1、pytest中的前置处理和后置处理
- 模块级别
setup_module 整个.py模块开始执行前,执行一次(全程只一次)teardown_module 整个.py模块结束后,执行一次(全程只一次) - 函数级别
setup_function 每次函数级别的用例执行前,执行一次(可能多次)teardown_function 每次函数级别的用例执行后,执行一次(可能多次) - 类级别
setup_class 整个测试类开始前,执行一次(全程只一次)teardown_function 整个测试类结束后,执行一次(全程只一次) - 类中方法级别
setup_method 类中的每个用例执行前,都会执行一次(可能多次)teardown_function 类中的每个用例执行后,都会执行一次(可能多次)
2、详见以下代码及执行结果
- 代码
def setup_module():
print(f"=========this is setup_module")
def teardown_module():
print(f"=========this is teardown_module")
def setup_function():
print("=========this is setup_function")
def teardown_function():
print("=========this is teardown_function")
def test_one():
print("=========this is test_one")
def test_tow():
print("=========this is test_two")
class TestCase():
def setup_class(self):
print("=========this is setup_class")
def teardown_class(self):
print("=========this is teardown_class")
def setup_method(self):
print("=========this is setup_method")
def teardown_method(self):
print("=========this is teardown_method")
def setup(self):
print("=========this is setup")
def teardown(self):
print("=========this is teardown")
def test_three(self):
print("=========this is test_three")
def test_four(self):
print("=========this is test_four")
- 结果
============================= test session starts ==============================
platform darwin -- Python 3.9.2, pytest-7.1.1, pluggy-1.0.0 -- /Users/chenbinhao/Desktop/Sunnada-work/learnPytest/venv/bin/python
cachedir: .pytest_cache
rootdir: /Users/chenbinhao/Desktop/Sunnada-work/learnPytest/demo
collecting ... collected 4 items
test_demo.py::test_one
=========this is setup_module
=========this is setup_function
PASSED [ 25%]
=========this is test_one
=========this is teardown_function
test_demo.py::test_tow
=========this is setup_function
PASSED [ 50%]
=========this is test_two
=========this is teardown_function
test_demo.py::TestCase::test_three
=========this is setup_class
=========this is setup_method
PASSED [ 75%]
=========this is test_three
=========this is teardown_method
test_demo.py::TestCase::test_four
=========this is setup_method
PASSED [100%]
=========this is four
=========this is teardown_method
=========this is teardown_class
=========this is teardown_module
============================== 4 passed in 0.04s ===============================
参考文章:https://www.cnblogs.com/poloyy/p/12641991.html
|