Search code examples
pythondoctestdocstring

Python: Why does this doc test fail?


This code that's in the doctest works when run by itself, but in this doctest it fails in 10 places. I can't figure out why it does though. The following is the entire module:

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()

Solution

  • doctest requires that you use ... for continuation lines:

    >>> @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)