【问题标题】:How do I pass a parameterized value to a pytest fixture?如何将参数化值传递给 pytest 夹具?
【发布时间】:2020-08-25 17:18:03
【问题描述】:

我正在使用 pytest 运行测试,每个测试都有一个唯一的帐户 ID。每个测试功能都需要一些设置和拆卸,我根据之前的建议切换到使用夹具。但是现在我需要使用与每个测试关联的唯一帐户 ID 来正确设置和拆除测试。有没有办法做到这一点?

另外,我需要在会话级别和类级别进行一些设置,这可能是不相关的,但 create_and_destroy_test 函数需要这些设置。


@pytest.fixture(scope="session")
def test_env(request):
    test_env = "hello"
    return test_env

class TestClass:
    @pytest.fixture(scope='class')
    def parameters(self, test_env):
        print("============Class Level============)")
        print("Received test environment, ", test_env)
        parameters = [1, 2, 3, 4, 5]
        return parameters

    @pytest.fixture(scope='function')
    def create_and_destroy_test(self, parameters, test_env):
        print("============Function Level=============")
        print("Posting data") # Needs an account id
        print(test_env)
        print(parameters)
        yield parameters
        print("Performing teardown") # Needs an account id

    @pytest.mark.parametrize("account_id", [1111, 2222])
    def test_one(self, create_and_destroy_test, account_id):
        assert 0

    @pytest.mark.parametrize("account_id", [3333, 4444])
    def test_two(self, create_and_destroy_test, account_id):
        assert 0

【问题讨论】:

    标签: python pytest xunit fixtures parameterized-tests


    【解决方案1】:

    您可以从夹具中的 request 对象访问测试 ID 或测试名称。虽然无法直接访问参数值,但您可以通过解析 id 或名称来访问它,因为它以参数值结尾。所以你可以这样做:

    import re
    ...
        @pytest.fixture
        def create_and_destroy_test(self, request, parameters, test_env):
            match = re.match(r".*\[(.*)\]", request.node.nodeid)
            if match:
                account_id = match.group(1)
                # do something with the ID
    

    您的测试 ID 类似于some_path/test.py::TestClass::test_one[2222],通过使用正则表达式,您可以从括号中的表达式中获取所需的参数,例如2222.

    【讨论】:

      猜你喜欢
      • 2020-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-04
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      相关资源
      最近更新 更多