具体例子:
#模块级别的setup_module ,teardown_module 开始于模块始末 全局的
import pytest
#模块级别的setup_module ,teardown_module 开始于模块始末 全局的
def setup_module():
print("setup_module")
def test01():
print('test01')
def teardown_module():
print("teardown_module")
if __name__ == '__main__':
pytest.main(['-sv','test07.py'])
运行结果:
test07.py::test01 setup_module
PASSED [100%]test01
teardown_module
============================== 1 passed in 0.17s ==============================
Process finished with exit code 0
二,#函数级别的 setup_function teardown_function执行每一个函数时都会执行
import pytest
#函数级别的 setup_function teardown_function执行每一个函数时都会执行
def setup_function():
print("setup_function")
def teardown_function():
print("teardown_function")
#模块级别的setup_module ,teardown_module 开始于模块始末 全局的
def setup_module():
print("setup_module")
def test01():
print('test01')
def test02():
print('test02')
def teardown_module():
print("teardown_module")
if __name__ == '__main__':
pytest.main(['-sv','test07.py'])
运行结果:
test07.py::test01 setup_module
setup_function
PASSED [ 50%]test01
teardown_function
test07.py::test02 setup_function
PASSED [100%]test02
teardown_function
teardown_module
============================== 2 passed in 0.09s ==============================
Process finished with exit code 0
三,#在类中只执行一次的 setup_class,teardown_class 注意类名上要加@classmethod
import pytest
#在类中只执行一次的 setup_class,teardown_class 注意类名上要加@classmethod
class TestCase01(object):
@classmethod
def setup_class(cls):
print("setup_class")
def test001(self):
print("test001")
def test002(self):
print("test002")
@classmethod
def teardown_class(cls):
print("teardown_class")
if __name__ == '__main__':
pytest.main(['-sv','test07.py'])
运行结果:
test07.py::TestCase01::test001 setup_class
PASSED [ 50%]test001
test07.py::TestCase01::test002 PASSED [100%]test002
teardown_class
============================== 2 passed in 0.16s ==============================
四,类中方法级的(setup_method、teardown_method)在每一个方法之前执行一次,在每一个方法之后执行一次
"""
开始于方法始末(在类中)
setup_method
teardown_method
"""
import pytest
class TestMethod(object):
def setup_class(self):
print "setup_class(self):每个类之前执行一次\n"
def teardown_class(self):
print "teardown_class(self):每个类之后执行一次"
def setup_method(self):
print "setup_method(self):在每个方法之前执行"
def teardown_method(self):
print "teardown_method(self):在每个方法之后执行\n"
def add(self,a,b):
print "这是加法运算"
return a+b
def test_01(self):
print "正在执行test1"
x = "this"
assert 'h' in x
def test_add(self):
print "正在执行test_add()"
assert self.add(3, 4) == 7
执行结果:
执行结果: setup_class --》 setup_method -->test1 -->teardown_method --》setup_method --> test_add()–》teardown_method --> teardown_class