3

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

3 回答 3

7

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)
于 2010-01-09T23:43:50.077 回答
1

尝试完全从 python 提示符粘贴代码。这意味着它将包含一些...以及>>>. 否则 doctest 解析器将不知道何时存在多行表达式。

预览:格雷格所说的。

于 2010-01-09T23:44:46.930 回答
0

这是我更正后的模块(现在可以使用):

class requiresparams(object):
    """

    Used as a decorator with an iterable passed in, this will look for each item
    in the iterable given as a key in the params argument of the function being
    decorated. It was built for a series of PayPal methods that require
    different params, and AOP was the best way to handle it while staying DRY.


    >>> @requiresparams(['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()
于 2010-01-10T00:00:40.260 回答