编程语言
首页 > 编程语言> > Python:为什么这个doc测试失败了?

Python:为什么这个doc测试失败了?

作者:互联网

doctest中的这段代码在单独运行时起作用,但在这个doctest中,它在10个地方失败了.我无法弄清楚它为什么会这样.以下是整个模块:

class requireparams(object):
    """
    >>> @requireparams(['name', 'pass', 'code'])
    >>> def complex_function(params):
    >>>     print(params['name'])
    >>>     print(params['pass'])
    >>>     print(params['code'])
    >>> 
    >>> params = {
    >>>     'name': 'John Doe',
    >>>     'pass': 'OpenSesame',
    >>>     #'code': '1134',
    >>> }
    >>> 
    >>> complex_function(params)
    Traceback (most recent call last):
        ...
    ValueError: Missing from "params" argument: code
    """
    def __init__(self, required):
        self.required = set(required)

    def __call__(self, params):
        def wrapper(params):
            missing = self.required.difference(params)
            if missing:
                raise ValueError('Missing from "params" argument: %s' % ', '.join(sorted(missing)))
        return wrapper

if __name__ == "__main__":
    import doctest
    doctest.testmod()

解决方法:

doctest要求您使用…作为延续行:

>>> @requireparams(['name', 'pass', 'code'])
... def complex_function(params):
...     print(params['name'])
...     print(params['pass'])
...     print(params['code'])
...
>>> params = {
...     'name': 'John Doe',
...     'pass': 'OpenSesame',
...     #'code': '1134',
... }
...
>>> complex_function(params)

标签:python,docstring,doctest
来源: https://codeday.me/bug/20190726/1547036.html