Pytest的setup和teardown函数
- 4.2.1。概述
1.setup和teardown主要分为:模块级,类级,功能级,函数级。 2.存在于测试类内部 -
4.2.2.函数级别setup()/teardown()
运行于测试方法的始末,即:运行一次测试函数会运行一次setup和teardown代码示例: import pytest class Test_ABC: # 函数级开始 def setup(self): print("------->setup_method") # 函数级结束 def teardown(self): print("------->teardown_method") def test_a(self): print("------->test_a") def test_b(self): print("------->test_b") if __name__ == '__main__': pytest.main(["-s","test_abc.py"])执行结果: test_abc.py ------->setup_method # 第一次 setup() ------->test_a . ------->teardown_method # 第一次 teardown() ------->setup_method # 第二次 setup() ------->test_b . ------->teardown_method # 第二次 teardown() -
4.2.3.类级别
运行于测试类的始末,即:在一个测试内只运行一次setup_class和teardown_class,不关心测试类内有多少个测试函数。代码示例: import pytest class Test_ABC: # 测试类级开始 def setup_class(self): print("------->setup_class") # 测试类级结束 def teardown_class(self): print("------->teardown_class") def test_a(self): print("------->test_a") def test_b(self): print("------->test_b") if __name__ == '__main_': pytest.main(["-s","test_abc.py"])执行结果: test_abc.py ------->setup_class # 第一次 setup_class() ------->test_a . ------->test_b F ------->teardown_class # 第一次 teardown_class()
本文详细介绍了Pytest框架中setup与teardown函数的使用方法,包括它们的不同级别(模块级、类级、功能级、函数级)及运行时机。通过代码示例展示了函数级与类级别的具体应用,帮助读者理解如何在测试前后进行资源的准备与清理。
789

被折叠的 条评论
为什么被折叠?



