1

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

1 回答 1

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

于 2020-08-25T18:20:44.500 回答