我的函数需要从文件中读取数据,我需要编写一个doctest,但是需要使其与绝对路径无关。最好的编写doctest的方法是什么?编写临时文件既费时又不可靠。
您可以设置一个参数,用下划线标记路径,以表明它仅供内部使用。在非测试模式下,该参数应默认为绝对路径。命名临时文件是解决方案,并且使用with
语句应该是无故障的。
#!/usr/bin/env python3
import doctest
import json
import tempfile
def read_config(_file_path='/etc/myservice.conf'):
"""
>>> with tempfile.NamedTemporaryFile() as tmpfile:
... tmpfile.write(b'{"myconfig": "myvalue"}') and True
... tmpfile.flush()
... read_config(_file_path=tmpfile.name)
True
{'myconfig': 'myvalue'}
"""
with open(_file_path, 'r') as f:
return json.load(f)
# Self-test
if doctest.testmod()[0]:
exit(1)
#!/usr/bin/env python2
import doctest
import json
import tempfile
def read_config(_file_path='/etc/myservice.conf'):
"""
>>> with tempfile.NamedTemporaryFile() as tmpfile:
... tmpfile.write(b'{"myconfig": "myvalue"}') and True
... tmpfile.flush()
... read_config(_file_path=tmpfile.name)
{u'myconfig': u'myvalue'}
"""
with open(_file_path, 'r') as f:
return json.load(f)
# Self-test
if doctest.testmod()[0]:
exit(1)
您的doctest可以使用模块StringIO
,从字符串提供文件对象。
import tempfile
作为>>> import tempfile
- 单独的一行,位于with tempfile.Named...
代码行之上。 这样导入doctest不会打印任何东西。 我认为,如果您未在其他地方使用tempfile模块,则以此方式可以在doctest中访问它,而无需在代码中使用它。 - Sean Breckenridge