我想确保在一个断言中根本没有警告。
在 pytest documentation about warnings 中找不到任何明确的答案. (无效链接,3.2.* 文档不再可用)。
我已经试过了,我想 None
可能意味着“没有”:
def test_AttrStr_parse_warnings():
"""Check _AttrStr.parse() raises proper warnings in proper cases."""
with pytest.warns(None):
_AttrStr('').parse()
但是这个断言也总是正确的,例如,测试不会失败,即使实际上引发了警告:
def test_AttrStr_parse_warnings():
"""Check _AttrStr.parse() raises proper warnings in proper cases."""
with pytest.warns(None):
_AttrStr('').parse()
warnings.warn('any message')
最佳答案
对于 pytest >= 7.0
The doc现在明确提到这种情况应该以这种方式解决(没有 pytest):
with warnings.catch_warnings():
warnings.simplefilter("error")
...
尽管这可能无法完全解决某些情况(动态检查:参见 this post)。
下面为 pytest < 7.0 建议的解决方案现在引发了 DeprecationWarning。感谢@Warren-Weckesser 在评论中指出这一点!
pytest < 7.0 的可能解决方案
然而它并没有计划像这样使用,它可以“记录”任何可能引发的警告,并使用它来添加另一个断言以确保引发的警告数量为0
:
def test_AttrStr_parse_warnings():
"""Check parse() raises proper warnings in proper cases."""
with pytest.warns(None) as record:
_AttrStr('').parse()
assert len(record) == 0
为确保它有效:在第二个断言中添加 warnings.warn('any message')
让测试失败。
关于python - 如何使用 pytest 断言不引发警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45671803/