2010-01-09 78 views
3

這個代碼在doctest中可以自行運行,但是在這個doctest中它失敗了10個地方。我無法弄清楚它爲什麼會這樣做。以下是整個模塊:Python:爲什麼此文檔測試失敗?

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

回答

7

文檔測試,您需要使用...的續行:

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

嘗試從巨蟒提示準確粘貼代碼。這意味着它將包含一些...以及>>>。否則,doctest分析器將不知道何時存在多行表達式。

預覽:Greg說了些什麼。

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