简体   繁体   English

pytest:通过夹具参数化测试用例

[英]pytest: Parameterized test cases via fixtures

How do you write a fixture (a method) that yields/returns parameterized test parameters?你如何编写一个产生/返回参数化测试参数的夹具(一种方法)?

For instance, I have a test as the following:例如,我有一个测试如下:

@pytest.mark.parametrize(
    "input,expected", 
    [("hello", "hello"),
    ("world", "world")])
def test_get_message(self, input, expected):
    assert expected == MyClass.get_message(input)

Instead of having input and expected to be passed via @pytest.mark.parametrize , I am interested in an approach as the following:我没有inputexpected通过@pytest.mark.parametrize传递,而是对以下方法感兴趣:

@pytest.fixture(scope="session")
def test_messages(self):
    # what should I write here to return multiple 
    # test case with expected value for each?
    pass

def test_get_message(self, test_messages):
    expected = test_messages["expected"] # somehow extracted from test_messages?
    input = test_messages["input"]       # somehow extracted from test message?
    assert expected == MyClass.get_message(input)

To move the parameters into a fixture, you can use fixture params:要将参数移动到夹具中,您可以使用夹具参数:

@pytest.fixture(params=[("hello", "hello"),
    ("world", "world")], scope="session")
def test_messages(self, request):
    return request.param

def test_get_message(self, test_messages):
    input = test_messages[0]   
    expected = test_messages[1]
    assert expected == MyClass.get_message(input)

You can also put the params into a separate function (same as wih parametrize ), eg您还可以将参数放入单独的 function (与parametrize相同),例如

def get_test_messages():
    return [("hello", "hello"), ("world", "world")]

@pytest.fixture(params=get_test_messages(), scope="session")
def test_messages(self, request):
    return request.param

To me, it seems you want to return an array of dicts:对我来说,您似乎想返回一个字典数组:

@pytest.fixture(scope="session")
def test_messages():
    return [
        {
            "input": "hello",
            "expected": "world"
        },
        {
            "input": "hello",
            "expected": "hello"
        }
    ]

To use it in a test case, you would need to iterate over the array:要在测试用例中使用它,您需要遍历数组:

def test_get_message(self, test_messages):
    for test_data in test_messages:
        input = test_data["input"]
        expected = test_data["expected"]
        assert input == expected

But I not sure if this is the best approach, because it's still considered as only one test case, and so it will show up as only one test case in the output/report.但我不确定这是否是最好的方法,因为它仍然被认为只是一个测试用例,所以它只会在输出/报告中显示为一个测试用例。

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

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