我有一个加载 yaml 文件的装置, 我有基础测试课 测试库A 一个继承自它的子类 TestB(TestBaseA ) 在 TestB 中,我有函数 test_values(): 我想用从夹具获得的配置值对 test_values() 进行参数化。我该怎么做? 代码如下所示:
import pytest
import yaml
from
@pytest.fixture(scope='session')
def load_config():
with open(r"\test_plan_1.yaml") as f:
data = yaml.safe_load(f)
return data
class TestBase:
def calculate_(self, test_path_1, test_path_2, window_size, threshold):
return consecutive_failures
class TestB(TestBase):
@pytest.mark.parametrize("threshold", //I want to read these values from the yaml loaded in the fixture)
@pytest.mark.parametrize("window_size", //I want to read these values from the yaml loaded in the fixture)
def test_resulty(self, threshold, window_size,load_config):
try:
consecutive_failures = self.calculate_
)
assert consecutive_failures == 0
您可以按照如何参数化夹具和测试功能
中的描述进行操作您不能直接使用夹具来参数化带有
@pytest.mark.parametrize
的测试函数,因为它是为静态值设计的。但是您可以通过使用 pytest_generate_tests
钩子来根据 YAML 文件的内容动态地参数化您的测试来实现类似的效果。
您无需直接使用固定装置将参数传递给测试,而是将 YAML 配置加载到会话范围的固定装置中(即固定装置在测试会话结束时被销毁。),或者直接在
pytest_generate_tests
中加载。
如果配置仅用于参数化并且在测试主体中不需要,则挂钩。
在
pytest_generate_tests
或测试模块中实现 conftest.py
挂钩来读取 YAML 数据并使用它来动态生成具有所需参数的测试:
# conftest.py or within your test module
import pytest
import yaml
def pytest_generate_tests(metafunc):
if 'threshold' in metafunc.fixturenames or 'window_size' in metafunc.fixturenames:
with open(r"\test_plan_1.yaml") as f:
data = yaml.safe_load(f)
# Assuming your YAML file structure allows direct extraction of values for parametrization
thresholds = data['thresholds']
window_sizes = data['window_sizes']
if 'threshold' in metafunc.fixturenames:
metafunc.parametrize('threshold', thresholds)
if 'window_size' in metafunc.fixturenames:
metafunc.parametrize('window_size', window_sizes)
# Your test module
class TestB(TestBase):
def test_resulty(self, threshold, window_size):
# Your test implementation
pytest_generate_tests
钩子读取您的 YAML 配置并根据内容动态地将参数化应用于您的测试。