如何将参数化的值传递给pytest固定装置?

问题描述

我正在使用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,account_id):
        assert 0

解决方法

您可以从灯具中的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