Pytest 支持使用 warns() 测试警告消息。例如,
auth.py:
import warnings
def warn_for_plain_text_security():
warnings.warn("Notice: Credentials in the .rc file is deprecated")
warn_for_plain_text_security()
test_auth.py:
import unittest
import warnings
import pytest
from auth import warn_for_plain_text_security
class AuthProviderTest(unittest.TestCase):
def test_insecure_creds(self):
with pytest.warns(UserWarning, match='Notice:') as w:
warn_for_plain_text_security()
但是,警告(实际上只是成功的单元测试)随后会显示在摘要报告中。
我希望能够测试 Python 警告,但只能在摘要中看到 real 警告。有办法做到这一点吗?
===================================================================================== test session starts ======================================================================================
platform darwin -- Python 3.10.8, pytest-8.0.1, pluggy-1.4.0
rootdir: /private/tmp
collected 1 item
test_auth.py . [100%]
================== warnings summary ==================
auth.py:5
/private/tmp/auth.py:5: UserWarning: Notice: Credentials in the .rc file is deprecated
warnings.warn("Notice: Credentials in the .rc file is deprecated")
-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
============ 1 passed, 1 warning in 0.02s ============
有一个 WarningsRecorder 实例,但不清楚是否可以在测试用例期间对其进行操作。
我发现了问题所在,原来的 test_insecure_creds() 在单元测试中被调用了两次,但警告只报告一个警告文本,因为重复项被抑制了。
当我添加“with pytest.warns”时,捕获了其中一个警告,但另一个警告仍未处理。
有关警告的文档可能对此更清楚,但它应该按预期工作。