code:
# Author : Michael
# Date : 24/9/21 12:35 PM
# File : setup_teardown.py
import pytest
def setup_module():
print("=====整个.py模块开始前只执行一次:setup module=====")
def teardown_module():
print("=====整个.py模块结束后只执行一次:teardown module=====")
def setup_function():
print("===每个函数级别用例开始前都执行setup_function===")
def teardown_function():
print("===每个函数级别用例结束后都执行teardown_function====")
def test_one():
print("the first test case")
def test_two():
print("the second test case")
class TestCase():
def setup_class(self):
print("====整个测试类开始前只执行一次setup_class====")
def teardown_class(self):
print("====整个测试类结束后只执行一次teardown_class====")
def setup_method(self):
print("==类里面每个用例执行前都会执行setup_method==")
def teardown_method(self):
print("==类里面每个用例结束后都会执行teardown_method==")
def setup(self):
print("=类里面每个用例执行前都会执行setup=")
def teardown(self):
print("=类里面每个用例结束后都会执行teardown=")
def test_three(self):
print("the third testcase")
def test_four(self):
print("the forth testcase")
if __name__ == '__main__':
pytest.main(["-q", "-s", "-ra", "setup_teardown.py"])
console:
============================ test session starts ==============================
collecting ... collected 4 items
setup_teardown.py::test_one =====整个.py模块开始前只执行一次:setup module=====
===每个函数级别用例开始前都执行setup_function===
PASSED [ 25%]the first test case
===每个函数级别用例结束后都执行teardown_function====
setup_teardown.py::test_two ===每个函数级别用例开始前都执行setup_function===
PASSED [ 50%]the second test case
===每个函数级别用例结束后都执行teardown_function====
setup_teardown.py::TestCase::test_three ====整个测试类开始前只执行一次setup_class====
==类里面每个用例执行前都会执行setup_method==
=类里面每个用例执行前都会执行setup=
PASSED [ 75%]the third testcase
=类里面每个用例结束后都会执行teardown=
==类里面每个用例结束后都会执行teardown_method==
setup_teardown.py::TestCase::test_four ==类里面每个用例执行前都会执行setup_method==
=类里面每个用例执行前都会执行setup=
PASSED [100%]the forth testcase
=类里面每个用例结束后都会执行teardown=
==类里面每个用例结束后都会执行teardown_method==
====整个测试类结束后只执行一次teardown_class====
=====整个.py模块结束后只执行一次:teardown module=====
======================== 4 passed, 2 warnings in 0.04s =========================