【问题标题】:Pytest does not display tuple values in test reportPytest 不在测试报告中显示元组值
【发布时间】:2021-10-20 22:28:35
【问题描述】:

我有一个参数化的 pytest 测试并使用元组作为预期值。

如果我运行测试,这些值不会显示,自动生成的值 (expected0...expectedN) 会显示在报告中。

是否可以在输出中显示元组值?

测试样本:

@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

输出:

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

【问题讨论】:

  • 也许看看这个:stackoverflow.com/a/37591040/8763097。此答案显示了如何自定义格式参数。您可能需要更改 item.name = '{func}[{params}]'.format(func=item.name.split('[')[0], params=format_string.format(**params)) 行以适应将元组输出为字符串。
  • 是的,它有帮助,但代码看起来有点过于复杂,我认为 pytest 可以自行格式化

标签: python pytest


【解决方案1】:

应用这个answer,可以自定义ids属性:

PARAMS = [
    ('12:00 AM', (0, 0)),
    ('12:01 AM', (0, 1)),
    ('11:59 AM', (11, 58))
]

def get_ids(params):
    return [f'{a}-{b}' for a, b in params]

@pytest.mark.parametrize('test_input, expected', PARAMS, ids=get_ids(PARAMS))
def test_params_format(test_input, expected):
    assert expected != (11, 58)

另一种选择,虽然不是很优雅,但是将元组定义为字符串并将它们设为indirect parameters。这会在conftest.py 中调用一个简单的fixture,它可以eval 在将字符串传递给测试函数之前将它们重新转换为元组。

@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:

from ast import literal_eval

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

literal_evaleval 更安全。见here

输出(两种解决方案):

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-05
    • 2018-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-19
    相关资源
    最近更新 更多