【问题标题】:Dynamic pytest method generation with only custom name只有自定义名称的动态 pytest 方法生成
【发布时间】:2016-03-05 08:16:09
【问题描述】:

您好,我正在尝试 pytest 文档中提到的后续示例,

# content of test_expectation.py
@pytest.mark.parametrize("test_input,expected", [
("3+5", 8),
("2+4", 6),
("6*9", 42),
])
def test_eval(test_input, expected):
    assert eval(test_input) == expected

当我使用 py.test -v 运行时,它会给出如下输出,

test_code.py::test_eval[3+5-8] PASSED
test_code.py::test_eval[2+4-6] PASSED
test_code.py::test_eval[6*9-42] FAILED

这里当我生成 html 报告时,当我使用很长的输入数据时,名称太长了。

在上面的例子中,为了避免第一个结果,方法的名称是 [3+5-8]。即它采用元组 (3+5,8) 并将其附加到实际的测试用例方法名称。

现在在我的情况下,元组是 ("short name", "very long string") 而不是 (3+5,8) 所以在我的 html 报告中显示很长。是否可以只显示“短名称”而不显示第二个值?

【问题讨论】:

    标签: python pytest python-unittest pytest-django


    【解决方案1】:

    能否请您粘贴当前显示的长名称和您预期的短名称,以便您的问题变得清晰。以防万一,如果它有帮助,您可以使用 @pytest.mark.parametrize 中的“ids”字段来自定义带有参数化值的显示测试名称。

    例如,g

    @pytest.mark.parametrize("test_input,expected", [
    ("3+5", 8), 
    ("2+4", 6),
    ("6*9", 42),
    ], ids=['cust_name_1', 'cust_name_2', 'cust_name_3'])
    def test_eval(test_input, expected):
    ...
    

    会将您的测试名称显示为

    test_code.py::test_eval[cust_name_1] PASSED
    test_code.py::test_eval[cust_name_1] PASSED
    test_code.py::test_eval[cust_name_1] FAILED
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-14
      • 1970-01-01
      • 2011-05-28
      • 2018-12-04
      • 1970-01-01
      • 2021-06-12
      • 1970-01-01
      相关资源
      最近更新 更多