9

is there any way to doctest locally defined functions? As an example I would want

def foo():
  """ >>> foo()
  testfoo"""

  def foo2():
    """ >>> 1/0 """ 
    print 'testfoo'

  foo2()

to NOT pass the test. But still I would not want to make foo2 global for the entire module...

4

2 回答 2

4

谢谢。我已经担心没有办法绕过文档字符串之外的代码。我仍然认为可能有一个技巧可以导入函数的局部变量,从而访问嵌套函数。无论如何,使用亚历克斯方法的解决方案将读取

def foo(debug=False):
  """
     >>> foo()
     testfoo
     >>> foo(debug=True)
     """

  def foo2():
    """
       >>> 1/0"""
    print 'testfoo'


  if debug :
    import doctest
    for f in [foo2]: doctest.run_docstring_examples(f,locals())

  foo2()

现在唯一的问题是如何自动化这种方法,所以有类似的东西

for f in locals().values(): doctest.run_docstring_examples(f,locals())

但没有导入和内置的函数和变量。

于 2010-03-12T10:37:37.237 回答
1

你只是有一个空格问题 - 如果你修复它,例如如下:

def foo():
  """
    >>> foo()
    testfoo"""

  def foo2():
    """ >>> 1/0 """ 
    print 'testfoo'

  foo2()

if __name__ == '__main__':
  import doctest
  doctest.testmod()

测试通过就好了。

于 2010-03-08T18:36:18.697 回答