首页 > 解决方案 > 如何为 pytest 参数化给出的每个输入按顺序运行方法

问题描述

我有两种方法edit_configget_config我通过 pytest 参数化传递参数。问题是首先编辑配置将对所有输入执行,然后执行 get_config。但我想先为每个输入运行 edit_config 然后 get_config 像一个循环一样。我怎样才能与 pytest 参数化一起做到这一点?

@pytest.mark.parametrize("interval, lacp_mode", [("fast", "active"), ("fast", "passive"), ("slow", "active"),
                                                 ("slow", "passive")])
class Example:
    def test_edit_config(self, interval, mode):
        pass
    def test_get_config(self, interval, mode):
        pass

实际 - 首先为所有参数化输入运行编辑配置,然后运行 ​​get-config

预期 - 应该运行 edit-config 然后 get-config 像每个输入的循环一样

标签: pythonpytest

解决方案


pytest 创建测试并按字母顺序运行它们(默认行为),因此四个test_edit_config测试将在test_get_config测试之前运行。

您可以创建一个调用其他测试功能的测试

@pytest.mark.parametrize("interval, lacp_mode", [("fast", "active"), ("fast", "passive"), ("slow", "active"), ("slow", "passive")])
class TestExample:

    def test_config(self, interval, lacp_mode):
        self.__edit_config(interval, lacp_mode)
        self.__get_config(interval, lacp_mode)

    def __edit_config(self, interval, lacp_mode):
        pass

    def __get_config(self, interval, lacp_mode):
        pass

另一种选择是使用pytest-ordering插件并动态添加订单

def data_provider():
    i = 0
    for data in [("fast", "active"), ("fast", "passive"), ("slow", "active"), ("slow", "passive")]:
        i += 1
        yield pytest.param(data[0], data[1], marks=pytest.mark.run(order=i))


class TestExample:

    @pytest.mark.parametrize('interval, lacp_mode', data_provider())
    def test_edit_config(self, interval, lacp_mode):
        pass

    @pytest.mark.parametrize('interval, lacp_mode', data_provider())
    def test_get_config(self, interval, lacp_mode):
        pass

推荐阅读