尝试避免 pytest 测试中的代码重复

问题描述 投票:0回答:1

我有这样的结构:

@pytest.fixture(scope='session')
def load_config() -> dict:
    with open(r"test_plan_1.yaml") as f:
        data = yaml.safe_load(f)
    return data

class TestBase:
    def calculate_mape_range(self, test_path_1: str, test_path_2: str, window_size: int, threshold: float) -> int:
       
class TestMapeHealthy(TestMapeBase):
    @pytest.mark.parametrize("threshold", THRESHOLD_COMPREHENSION)
    @pytest.mark.parametrize("window_size", WINDOW_SIZE_COMPREHENSION)
    def test_MAPE_for_healthy_(self, threshold: float, window_size: int, load_config: dict) -> str:

        try:
            consecutive_failures = super().calculate_mape_range(
                load_config['test_plan']['test_ids'][VERSION_TAG]['tools']['test_file_ids']['healthy_test_list'][0],
                load_config['test_plan']['test_ids'][VERSION_TAG]['tools']['test_file_ids']['healthy_test_list'][1],
                window_size,
                threshold
            )
            assert consecutive_failures == 0

class TestMapeFaulty(TestMapeBase):
    @pytest.mark.parametrize("threshold", THRESHOLD_COMPREHENSION)
    @pytest.mark.parametrize("window_size", WINDOW_SIZE_COMPREHENSION)
    def test_MAPE_for_faulty_(self, threshold: float, window_size: int, load_config: dict) -> str:

        try:
            consecutive_failures = super().calculate_mape_range(
                load_config['test_plan']['test_ids'][VERSION_TAG]['tools']['test_file_ids']['faulty_test_list'][0],
                load_config['test_plan']['test_ids'][VERSION_TAG]['tools']['test_file_ids']['faulty_test_list'][1],
                window_size,
                threshold
            )
            assert consecutive_failures == 0

我在两个测试用例中基本上使用相同的代码(不同之处在于我将 YAML 中的不同标签传递给calculate_mape_range,并且断言语句不同,如何避免在优雅的 Pytest 中重复代码-方式?

python automation pytest
1个回答
0
投票

您可以向测试函数添加几个附加参数,并且您应该能够使用单个函数涵盖这两种情况:

@pytest.mark.parametrize("threshold", THRESHOLD_COMPREHENSION)
@pytest.mark.parametrize("window_size", WINDOW_SIZE_COMPREHENSION)
@pytest.mark.parametrize("final_key", ...)
@pytest.mark.parametrize("should_pass", ...)
def test_MAPE(threshold: float, window_size: int, final_key: str, should_pass: bool, load_config: dict):

    consecutive_failures = super().calculate_mape_range(
        load_config['test_plan']['test_ids'][VERSION_TAG]['tools']['test_file_ids'][final_key][0],
        load_config['test_plan']['test_ids'][VERSION_TAG]['tools']['test_file_ids'][final_key][1],
        window_size,
        threshold
    )

    if should_pass:
      assert consecutive_failures == 0
    else:
      assert consecutive_failures > 0
© www.soinside.com 2019 - 2024. All rights reserved.