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

mor*_*gan 4 python doctest

我的函数从文件中读取,并且需要以独立于绝对路径的方式编写 doctest。编写 doctest 的最佳方法是什么?编写临时文件很昂贵,而且不能防故障。

And*_*Dog 5

您可以有一个采用路径的参数,用下划线标记以说明它仅供内部使用。然后参数应默认为非测试模式下的绝对路径。命名临时文件是解决方案,使用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)
Run Code Online (Sandbox Code Playgroud)

对于 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)
Run Code Online (Sandbox Code Playgroud)