如何使这个Python filterwarnings语句工作?

2024-09-30 19:35:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在将一个大型Django项目升级到该框架的最新版本。为了帮助识别即将被否决的内容,我开始使用Python的-W参数运行单元测试:

python -Wa manage.py test classes.tests.test_file.TestFileClassIT.test_copy_all_files

当我以这种方式运行一个测试时,我会遇到很多这样的错误:

/srv/https/example.com/repo/classes/tests/test_file.py:30: ResourceWarning: unclosed file <_io.TextIOWrapper name='/var/www/example.com/photos/file.txt' mode='w' encoding='UTF-8'>

我希望Python忽略所有这种类型的警告,因为我没有时间在数百个触发它的测试中修复它。为此,我发现warnings包提供了此功能,因此我将其添加到一个测试模块中,以了解其工作原理:

# test_file.py
import unittest

import warnings
warnings.filterwarnings("ignore", message="ResourceWarning: unclosed file*")

class TestFileClassIT(unittest.TestCase):
    def test_copy_all_files(self):
        ...
        open("file1.txt", "w").close
        ...

但是,我仍然在测试的输出中看到ResourceWarning。我已经阅读了文档,这似乎是如何使用警告模块。我也尝试过我的警告没有包括星号和警告字符串的结尾,但这也不起作用。在我的代码中包含此警告以使其正常工作的正确方法是什么?你知道吗


Tags: pytestcom警告exampletestsfilesall
1条回答
网友
1楼 · 发布于 2024-09-30 19:35:31

在这个特定的错误中,在类的测试函数test_copy_all_filesTestFileClassIT

    warnings.simplefilter('ignore', ResourceWarning)

对于所有错误,您是否尝试过在警告列表中插入一个简单的条目而不是filterwarnings?你知道吗

    warnings.simplefilter('ignore')

根据PEP-0565关于warnings system

    if not sys.warnoptions:
        warnings.simplefilter("ignore")

相关问题 更多 >