Pytest之Setup/Teardown
一、说明:
setup和teardown主要分为:
-
函数级 (setup_function、teardown_function), 只对函数用例生效,而且不在类中使用
-
功能级(setup_method、teardown_method),类中方法级
-
类级(setup_class、teardown_class)
-
模块级 (setup_module、teardown_module)
二、示例
1、函数级 (setup_function、teardown_function), 只对函数用例生效,而且不在类中使用
运行于测试方法的始末,即:运行一次测试函数会运行一次setup和teardown
代码示例:
import pytest def setup_function(): print("this is setup_function") def teardown_function(): print("this is teardown_function") def test_1(): print("this is test_1") assert 1 def test_2(): print("this is test_2") assert 1 def test_3(): print("this is test_3") assert 1 if __name__ == '__main__': pytest.main(['-s','test_demo.py'])
执行结果:
2、功能级(setup_method、teardown_method),类中方法级 , 在每一个方法之前执行一次,在每一个方法之后执行一次
import pytest class Test_123: def setup_method(self): print("this is setup") def teardown_method(self): print("this is teardown") def test_1(self): print("this is test_1") assert 1 def test_2(self): print("this is test_2") assert 1 def test_3(self): print("this is test_3") assert 1 if __name__ == '__main__': pytest.main("['test_123.py']")
执行结果:
3、类级别
运行于测试类的始末,在一个测试类内只运行一次setup_class和teardown_class, 类执行之前运行一次,类执行之后运行一次,不关心测试类内有多少个测试函数
代码示例:
import pytest class Test_123: def setup_class(self): print("this is setup") def teardown_class(self): print("this is teardown") def test_1(self): print("this is test_1") assert 1 def test_2(self): print("this is test_2") assert 1 def test_3(self): print("this is test_3") assert 1 if __name__ == '__main__': pytest.main("['test_123.py']")
运行结果如下:
4、模块级 setup_module、teardown_module是 全局的,在模块执行前运行一遍,在模块执行后运行一遍
代码示例:
import pytest def setup_module(): print("this is setup_module") def teardown_module(): print("this is teardown_module") def setup_function(): print("this is setup_function") def teardown_function(): print("this is teardown_function") def test_1(): print("this is test_1") assert 1 def test_2(): print("this is test_2") assert 1 def test_3(): print("this is test_3") assert 1 if __name__ == '__main__': pytest.main(['-s','test_demo.py'])
执行结果: