setup和teardown主要分为:
模块级、类级
功能级、函数级
1、模块级、类级 setup_class/teardown_class
运行于测试类的始末,即:在一个测试内只运行一次setup_class和teardown_class,不关心测试类内有多少个测试函数。
#enconding:utf-8
import pytest
class Test_Class:
def setup_class(self):
print('\nstart')
def teardown_class(self):
print('\nend')
def test_1(self):
print('111')
assert 1
def test_2(self):
print('222')
assert 1
if __name__=='__main__':
pytest.main(['-s','-v','test_3.py'])
执行结果:
test_3.py::Test_Class::test_1
start
111
PASSED
test_3.py::Test_Class::test_2 222
PASSED
end
2、功能级、函数级 setup()/teardown()
运行于测试方法的始末,即:运行一次测试函数会运行一次setup和teardown
import pytest
class Test_Class:
def setup(self):
print('\nstart')
def teardown(self):
print('\nend')
def test_1(self):
print('111')
assert 1
def test_2(self):
print('222')
assert 1
if __name__=='__main__':
pytest.main(['-s','-v','test_2.py'])
执行结果:
test_2.py::Test_Class::test_1
start
111
PASSED
end
test_2.py::Test_Class::test_2
start
222
PASSED
end