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()
答案 0 :(得分: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)
答案 1 :(得分:1)
尝试完全从python提示符粘贴代码。这意味着它将包含一些...
以及>>>
。否则,doctest解析器将不知道何时存在多行表达式。
预览:格雷格说的话。
答案 2 :(得分: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()