Pytest提供了类似unittest的setup、teardown的方法,并且还超过四个,一共有十种
示例:
import pytest
def setup_module():
print("=====整个.py模块开始前只执行一次: 脚本开始执行脚本=====")
def teardown_module():
print("=====整个.py模块结束后只执行一次: 脚本执行结束===")
def setup_function():
print("===每个函数级别用例开始前都执行,不在类中, setup_function===")
def teardown_function():
print("===每个函数级别用例结束后都执行,不在类中, teardown_function====")
def test_one():
print("one")
def test_two():
print("two")
class Testcaselist():
# 类里面的
def setup(self):
print(‘setup: 每个用例前开始执行‘)
def teardown(self):
print(‘teardown: 每个用例后开始执行‘)
def setup_method(self):
print(‘setup: 每个类方法用例前开始执行‘)
def teardown_method(self):
print(‘teardown: 每个类方法用例后开始执行‘)
# 测试用例
def test_001(self):
print("正在执行test_001用例")
p = "Python"
assert "h" in p
def test_002(self):
print("正在执行test_002用例")
p = ‘test‘
assert ‘t‘ in p
if __name__ == ‘__main__‘:
pytest.main([‘-s‘, ‘test_hello.py‘])
输出:
=====整个.py模块开始前只执行一次: 脚本开始执行脚本=====
===每个函数级别用例开始前都执行,不在类中, setup_function===
one
.===每个函数级别用例结束后都执行,不在类中, teardown_function====
===每个函数级别用例开始前都执行,不在类中, setup_function===
two
.===每个函数级别用例结束后都执行,不在类中, teardown_function====
setup: 每个类方法用例前开始执行
setup: 每个用例前开始执行
正在执行test_001用例
.teardown: 每个用例后开始执行
teardown: 每个类方法用例后开始执行
setup: 每个类方法用例前开始执行
setup: 每个用例前开始执行
正在执行test_002用例
.teardown: 每个用例后开始执行
teardown: 每个类方法用例后开始执行
=====整个.py模块结束后只执行一次: 脚本执行结束===
原文:https://www.cnblogs.com/saryli/p/14648879.html