繁体   English   中英

如何将参数化值传递给 pytest 夹具?

[英]How do I pass a parameterized value to a pytest fixture?

我正在使用 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

您可以从您的装置中的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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM