![](/img/trans.png)
[英]Record where files are opened to debug “ResourceWarning: unclosed file”
[英]Make pytest fail on ResourceWarning (unclosed files)
我的一些测试需要确保打开的文件已关闭。 让我们用最简单的例子:
# test_example.py
import pytest
@pytest.mark.filterwarnings('error::ResourceWarning')
def test_resourcewarning():
open('/dev/null')
当我运行pytest
时,警告被抛出,甚至在测试 output 中打印出来,但测试仍然通过:
$ pytest
============================ test session starts =============================
platform darwin -- Python 3.10.2, pytest-7.1.1, pluggy-1.0.0
rootdir: /path/to/project
collected 1 item
test_example.py . [100%]
============================== warnings summary ==============================
test_example.py::test_resourcewarning
/path/to/python/site-packages/_pytest/unraisableexception.py:78: PytestUnrai
sableExceptionWarning: Exception ignored in: <_io.FileIO [closed]>
Traceback (most recent call last):
File "/path/to/project/test_example.py", line 5, in test_resourcewarning
open('/dev/null')
ResourceWarning: unclosed file <_io.TextIOWrapper name='/dev/null' mode='r'
encoding='UTF-8'>
warnings.warn(pytest.PytestUnraisableExceptionWarning(msg))
-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
======================== 1 passed, 1 warning in 0.01s ========================
删除@pytest.mark.filterwarnings
或将警告类型更改为不相关的内容(如DeprecationWarning
)会导致测试通过而根本不会打印任何警告,因此很明显这是在捕获警告 - 但它似乎随后被 pytest 捕获。Pytest然后抛出pytest.PytestUnraisableExceptionWarning
,这不会失败,因为我没有为此进行过滤。 如果我对pytest.PytestUnraisableExceptionWarning
进行过滤,测试也会通过,因为它不是在寻找原始的ResourceWarning
。
我能想到的唯一解决方案是对两者进行过滤:
@pytest.mark.filterwarnings('error::ResourceWarning')
@pytest.mark.filterwarnings('error::pytest.PytestUnraisableExceptionWarning')
但在这一点上它对我来说没有任何意义,即使在通过文档和谷歌搜索结果进行拖网之后我不明白如果 pytest 只是要吞下它们并让我捕获它自己的警告过滤应该如何工作实际注册测试失败的警告,因此唯一合乎逻辑的结论是我不知道我在做什么(或者这是一个错误)。
我错过了什么?
我最近了解到默认情况下会忽略ResourceWarning
。 在jaraco/skeleton (我从中派生我的项目)中,我添加了此提交以默认启用警告,实质上是将以下内容添加到 pytest.ini:
[pytest]
filterwarnings =
default::ResourceWarning
使用error
而不是 default 在整个项目中default
启用错误。
尝试这个:
#test_example.py
import pytest
@pytest.mark.filterwarnings("error")
def test_resourcewarning():
open('/dev/null')
这使我的测试失败:
取自 pytest 文档( https://docs.pytest.org/en/stable/stable/how-to/capturefilter-warnings-warnings.html )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.