求助:调整pytest嵌套类中fixture的测试执行流程
解决方案
问题根源
你当前的写法中,TestClass1和TestClass2作为TestParentClass1的内部类,会被pytest识别为独立的顶层测试类,不会继承父类的fixture,因此无法实现你想要的参数化执行流程。
可行方案
以下两种方案都能满足你的需求(保留两个测试类,按指定流程执行):
方案1:使用模块级自动执行fixture(推荐)
将公共配置fixture提升到模块级别,设置scope="module"并开启autouse=True,这样每个参数值会触发一次全局配置,随后执行模块内所有测试用例。
import pytest data_arg = ["arg1", "arg2"] @pytest.fixture(scope="module", params=data_arg, autouse=True) def common_setup(request): print(f'Configure the system according to {request.param}') # 如需清理操作,可添加yield和清理代码 # yield # print(f'Clean up system configured with {request.param}') class TestClass1: def test_class1_test1(self): print("Executing test1 of class1") def test_class1_test2(self): print("Executing test2 of class1") class TestClass2: def test_class2_test1(self): print("Executing test1 of class2") def test_class2_test2(self): print("Executing test2 of class2")
执行流程验证(运行pytest -s):
Configure the system according to arg1 Executing test1 of class1 Executing test2 of class1 Executing test1 of class2 Executing test2 of class2 Configure the system according to arg2 Executing test1 of class1 Executing test2 of class1 Executing test1 of class2 Executing test2 of class2
方案2:保留父类结构,通过继承传递fixture
如果需要保留TestParentClass1的结构,让TestClass1和TestClass2继承父类,并将父类的fixture改为模块级作用域:
import pytest data_arg = ["arg1", "arg2"] class TestParentClass1: @pytest.fixture(scope="module", params=data_arg, autouse=True) def common_setup(self, request): print(f'Configure the system according to {request.param}') class TestClass1(TestParentClass1): def test_class1_test1(self): print("Executing test1 of class1") def test_class1_test2(self): print("Executing test2 of class1") class TestClass2(TestParentClass1): def test_class2_test1(self): print("Executing test1 of class2") def test_class2_test2(self): print("Executing test2 of class2")
这个方案的执行流程和方案1完全一致,只是保留了父类的结构。
关键说明
scope="module"确保每个参数值对应的fixture只执行一次,覆盖模块内所有测试用例autouse=True让fixture自动执行,无需在测试方法中显式调用- 内部测试类改为顶层类或继承父类,才能让fixture作用到目标测试用例
内容的提问来源于stack exchange,提问作者Shreyansh Jain
相关产品推荐
相关产品推荐

