简体   繁体   中英

Pytest does not display tuple values in test report

I have a parametrized pytest test and use tuples as expected values.

If I run the tests, these values are not displayed and autogenerated ones (expected1...expected) are shown in the report.

Is it possible to have tuple values displayed in the output?

Test sample:

@pytest.mark.parametrize('test_input, expected',
                         [
                             ('12:00 AM', (0, 0)),
                             ('12:01 AM', (0, 1)),
                             ('11:59 AM', (11, 58))
                         ])
def test_params(test_input, expected):
    assert time_calculator.convert_12h_to_24(test_input) == expected

Output:

 test_time_converter.py::test_params[12:00 AM-expected0] PASSED test_time_converter.py::test_params[12:01 AM-expected1] PASSED test_time_converter.py::test_params[11:59 AM-expected2] FAILED

If you want to see the tuples, you can define the tuples as indirect parameter strings. This calls a fixture in conftest.py that can eval the strings back into tuples before they are passed to the test function.

It's not perfect, but it's fairly non-invasive and easy to understand.

@pytest.mark.parametrize(
    'test_input, expected',
    [
        ('12:00 AM', '(0, 0)'),
        ('12:01 AM', '(0, 1)'),
        ('11:59 AM', '(11, 58)')
    ],
    indirect=["expected"])
def test_params(test_input, expected):
    assert expected != (11, 58)

conftest.py:

@pytest.fixture
def expected(request):
    return eval(request.param)

Output:

test_print_tuples.py::test_params[12:00 AM-(0, 0)] PASSED
test_print_tuples.py::test_params[12:01 AM-(0, 1)] PASSED 
test_print_tuples.py::test_params[11:59 AM-(11, 58)] FAILED

Some purists may argue that using eval is bad practice. If you want, you can use literal_eval instead. See here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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