如何为一个从文件中读取数据的函数编写doctest?

4

我的函数需要从文件中读取数据,我需要编写一个doctest,但是需要使其与绝对路径无关。最好的编写doctest的方法是什么?编写临时文件既费时又不可靠。

2个回答

6

您可以设置一个参数,用下划线标记路径,以表明它仅供内部使用。在非测试模式下,该参数应默认为绝对路径。命名临时文件是解决方案,并且使用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)

1
太好了。 我能够像这样在doctest本身中使用import tempfile作为>>> import tempfile - 单独的一行,位于with tempfile.Named...代码行之上。 这样导入doctest不会打印任何东西。 我认为,如果您未在其他地方使用tempfile模块,则以此方式可以在doctest中访问它,而无需在代码中使用它。 - Sean Breckenridge

1

您的doctest可以使用模块StringIO,从字符串提供文件对象。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接