Pytest 检查错误返回的消息

Pytest checking messages returned by errors

关于 pytest、str() 和 python 错误类型之间交互的一些问题破坏了完整的错误测试,我们想要确认由错误 return 编辑的确切文本。

示例如下:

def erroring_func(name, required_item_list):
   # skip boring bit. Just throw an error.
   raise KeyError(f'{name} is missing required item(s): {required_item_list')

def test_erroring_func()
    with pytest.raises(KeyError) as err:
        name = 'This dataframe'
        required_item_list = ['a column']
        _ = erroring_func(name, required_item_list)
    assert str(err.value) == f"{name} is missing required item(s): {required_item_list}"

这看起来很合理,但会 return 错误:

assert '"This dataframe is missing required item(s): [\'lat\']"' == "This dataframe is missing required item(s): ['lat']

不知何故,str(err.value) 在输出中创建了单个反斜杠,这些反斜杠在 f 字符串 (actually impossible) 中重新创建或在创建后插入字符串中非常困难。

一个不完整的补丁(缺少详细错误的主要值)是为了测试返回的错误中是否存在固定的子字符串。

def test_erroring_func()
    with pytest.raises(KeyError) as err:
        name = 'This dataframe'
        required_item_list = ['a column']
        _ = erroring_func(name, required_item_list)
    assert "is missing required item(s):" in str(err.value)

你完全可以通过匹配KeyError如何改变文本来解决。这可以用带有单引号然后双引号的 f-string f'"your text {here}"'

assert str(err.value) == f'"{name} is missing required item(s): {required_item_list}"'

(感谢 Anthony Sotile)