Python 如何为从文件读取的函数编写doctest?

Python 如何为从文件读取的函数编写doctest?,python,doctest,Python,Doctest,我的函数从文件中读取数据,而doctest需要以独立于绝对路径的方式编写。写博士考试最好的方法是什么?编写临时文件的成本很高,而且不能防故障。您的doctest可以使用moduleStringIO从字符串中提供文件对象。您可以有一个参数,该参数采用路径,并用下划线标记,以说明它仅供内部使用。然后,参数应默认为非测试模式下的绝对路径。命名临时文件是解决方案,使用with语句应该是无故障的 #!/usr/bin/env python3 import doctest import json impor

我的函数从文件中读取数据,而doctest需要以独立于绝对路径的方式编写。写博士考试最好的方法是什么?编写临时文件的成本很高,而且不能防故障。

您的doctest可以使用module
StringIO
从字符串中提供文件对象。

您可以有一个参数,该参数采用路径,并用下划线标记,以说明它仅供内部使用。然后,参数应默认为非测试模式下的绝对路径。命名临时文件是解决方案,使用
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)
对于Python 2.x,doctest将有所不同:

#!/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)

这太棒了。我能够像导入tempfile一样执行导入tempfile的
import-tempfile
——在带有tempfile的
上方有一行单独的代码。在doctest本身中命名为…
行,其工作原理是导入doctest不会打印任何内容。我相信,如果您没有在其他地方使用tempfile模块,它可以在doctest中访问,但不能在代码中访问。