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

时间:2013-05-30 08:50:35

标签: python doctest

我的函数从文件读取,并且doctest需要以独立于绝对路径的方式编写。什么是最好的博士学位方法?编写临时文件很昂贵而且不会出现故障。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

您可以使用带有下划线的路径的参数来声明它仅供内部使用。然后,该参数应默认为非测试模式下的绝对路径。命名临时文件是解决方案,使用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)