【发布时间】:2021-07-28 20:17:21
【问题描述】:
我的 Python doctests 打开一些它永远不会关闭的文件。这不会引起任何问题;当对象被销毁时它们会自动关闭,并且添加逻辑以确保它们被明确关闭会不必要地使我的文档复杂化。
但是,当 doctest 在 unittest 内部运行时,它们开始发出 ResourceWarning()s,给我的输出添加无用的噪音。
例如,给定leak.py:
def hello(f):
"""
>>> a = open("test-file","w")
>>> hello(a)
>>> open("test-file").read()
'hello'
"""
f.write("hello")
f.flush()
def load_tests(loader, tests, ignore):
import doctest
tests.addTests(doctest.DocTestSuite())
return tests
使用 Python 3.6.9 在 doctest 和 unittest 下运行它会生成:
$ python3 --version
Python 3.6.9
$ python3 -m doctest leak.py -v
[...]
3 passed and 0 failed.
Test passed.
$ python3 -m unittest leak
/tmp/fileleak/leak.py:1: ResourceWarning: unclosed file <_io.TextIOWrapper name='test-file' mode='r' encoding='UTF-8'>
def hello(f):
/usr/lib/python3.6/doctest.py:2175: ResourceWarning: unclosed file <_io.TextIOWrapper name='test-file' mode='w' encoding='UTF-8'>
test.globs.clear()
.
----------------------------------------------------------------------
Ran 1 test in 0.003s
OK
有几种方法可以在 doctest 中清理它,但它们都会增加复杂性,从而分散文档的注意力。这包括对a.close() 的显式调用,使用with open("test-file") as a:(它还将测试的输出推送到with 块下方,或者使用`warnings.simplefilter("ignore") 彻底丢弃警告。
如何让 doctest 在 unittest 下运行以抑制 ResourceWarning()s 像 doctest 一样?
【问题讨论】:
标签: python python-unittest suppress-warnings doctest