如何使此Python filterwarnings语句起作用?

时间:2019-07-01 16:45:24

标签: 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忽略所有这种类型的警告,因为我没有时间去研究和解决触发它的数百种测试。为此,我发现警告包提供了此功能,因此我将其添加到一个测试模块中以了解其工作原理:

# 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。我已经阅读了文档,这似乎是如何使用警告模块。我也尝试过警告,但不包括星号和警告字符串的末尾,但这也不起作用。在我的代码中包含此警告以使其正常工作的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

针对该特定错误,在您的课程test_copy_all_files中的测试功能内 {em> TestFileClassIT

    warnings.simplefilter('ignore', ResourceWarning)

关于所有错误,您是否尝试过将简单条目插入警告列表而不是filterwarnings

    warnings.simplefilter('ignore')

根据warnings system上的PEP-0565

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