【发布时间】:2018-04-14 03:42:57
【问题描述】:
我正在测试一个程序转换工具。它导致其中一个 CPython 测试失败,但我终生无法弄清楚原因。
这是来自 CPython 测试套件的 test_sax.py 中的一项测试的缩小版本,https://github.com/python/cpython/blob/master/Lib/test/test_sax.py#L143。这个 sn-p 写入一个 XML 文件,然后以错误的编码将其读回。这会导致xml.sax.parse 失败并引发异常。当它这样做时,它打开的文件应该被泄露。垃圾收集器检测到此泄漏。以下测试检查此行为:
def test_parse_bytes(self):
make_xml_file(self.data, 'iso-8859-1', None)
with support.check_warnings(('unclosed file', ResourceWarning)) :
with self.assertRaises(SAXException):
self.check_parse(TESTFN)
gc.collect()
我的程序转换工具将这个 sn-p 更改为如下内容:
def test_parse_bytes(self):
make_xml_file(self.data, 'iso-8859-1', None)
with support.check_warnings(('unclosed file', ResourceWarning)) :
t = self.assertRaises(SAXException)
with t:
self.check_parse(TESTFN)
gc.collect()
根据我对 Python 的了解,这些 sn-ps 也应该是完全相同的。当我进入调试器时,我不知道他们在做什么不同。然而,不知何故,后者 sn-p 导致文件不被泄露,从而导致测试失败。为什么?
【问题讨论】:
标签: python-3.x cpython