Python:为什么这个文档测试失败?
这段代码在单独运行的时候是可以正常工作的,但在这个测试中却在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()
3 个回答
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()
1
试着直接从 Python 提示符中复制粘贴代码。这意味着代码里会包含一些 ...
和 >>>
。否则,doctest 解析器就不知道什么时候是多行表达式了。
在预览中:Greg 说的没错。
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)