如何为pytest parametriz给定的每个输入按顺序运行方法

2024-05-23 22:32:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个方法edit_configget_config,我通过pytest参数化传递参数。问题是,首先对所有输入执行edit config,然后获取\ config。但是我想先运行edit\u config,然后像循环一样为每个输入获取\u 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

实际-首先对所有参数化输入运行edit config,然后运行get config

预期的-应该运行编辑配置,然后获得配置像一个周期为每个输入


Tags: testselfconfig参数getpytestmodedef
2条回答

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

测试彼此独立运行。你知道吗

如果您希望某些操作/测试一起运行,那么它们应该是一个测试的一部分(如果您需要设置和拆卸操作,答案是不同的)

您可以将其组织到子函数中,然后由测试调用这些子函数(正如我在编写答案的第二部分时看到Guy所建议的):

@pytest.mark.parametrize("interval, lacp_mode", [("fast", "active"), ("fast", "passive"), ("slow", "active"),
                                                 ("slow", "passive")])
class Example:
    def test_config(self, interval, mode):
        self.do_get_config_test(interval, mode)
        self.do_edit_config_test(interval, mode)

    def do_get_config_test(self, interval, mode):
        pass
    def do_edit_config_test(self, interval, mode):
        pass

但我首先要问,你为什么这样做?这将更有意义,他们将是单独的测试。也许您真正想要的是单独的测试,但是通过在之前运行代码,可以使用“编辑”测试来设置所需的内容(由get\u config测试设置的内容)。我发现最好的方法是使用固定装置。你知道吗

你可以有这样的东西:

import pytest

@pytest.fixture(params=['fast', 'slow'])
def interval(request):
    return request.param

@pytest.fixture(params=['active', 'passive'])
def mode(request):
    return request.param

@pytest.fixture
def config(interval, mode):
    # set up and return the config for the edit test
    pass

def test_edit_config(config):
    pass
def test_get_config(interval, mode):
    pass

然后,“config”fixture可以执行编辑配置测试所需的任何设置,使其独立于get config测试。那么顺序就无关紧要了。你知道吗

相关问题 更多 >