如何使用pytest断言没有警告出现

zez*_*llo 8 python warnings unit-testing pytest python-3.x

我要确保在一个断言中根本不提出任何警告

pytest文档找不到有关警告的任何明确答案。

我已经尝试过,认为可能None意味着“没有”:

def test_AttrStr_parse_warnings():
    """Check _AttrStr.parse() raises proper warnings in proper cases."""
    with pytest.warns(None):
        _AttrStr('').parse()
Run Code Online (Sandbox Code Playgroud)

但是此断言也总是正确的,例如,即使实际发出警告,测试也不会失败:

def test_AttrStr_parse_warnings():
    """Check _AttrStr.parse() raises proper warnings in proper cases."""
    with pytest.warns(None):
        _AttrStr('').parse()
        warnings.warn('any message')
Run Code Online (Sandbox Code Playgroud)

zez*_*llo 11

可以“记录”任何可能引发的警告,并使用它添加另一个断言,以确保引发的警告数量为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
Run Code Online (Sandbox Code Playgroud)

为了确保它有效:添加warnings.warn('any message')第二个断言使测试失败。

  • 甚至更漂亮:`assert not record.list`。 (4认同)
  • 或更短:“断言不记录”(请参阅​​[使用示例](https://docs.pytest.org/en/5.2.2/warnings.html#custom-failure-messages)) (4认同)