用例运行级别
- 函数级:
setup_function
/teardown_module
,只对函数用例生效(不在类中) - 类级:
setup_class
/teardown_class
,只在类中前后运行一次(在类中) - 方法级:
setup_method
/teardown_method
,开始于方法始末(在类中) - 类里面的
setup
/teardown
运行在调用方法的前后 - 模块级:
setup_module
/teardown_module
,开始于模块始末,全局的
setup_function&teardown_function
import pytest
def setup_function():
# 非类中函数执行前执行
print("setup_function")
def teardown_function():
# 非类中函数执行后执行
print("teardown_function")
def test_1():
print("----开始执行test_1---")
assert 1==1
def test_2():
print("----开始执行test_2---")
assert 2==2
if __name__ == "__main__":
pytest.main(["-s","test_2.py"])
setup_function&teardown_function
setup_module&teardown_module
所有用例执行前执行一次setup_module
,所有用例执行后执行一次teardown_module
setup_module&teardown_module
setup_class&teardown_class
等价于unittest中的setupClass和teardownClass
#添加类
class TestPytest:
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 test_class_3(self):
print("----开始执行test_class_3---")
def test_class_4(self):
print("----开始执行test_class_4---")
3者执行结果
注:
setup_module
/teardown_module
的优先级是最大的,然后函数里面用到的setup_function
/teardown_function
与类里面的setup_class
/teardown_class
互不干涉