2

我可以将 python doctests 放在每个函数的主体中,我有时喜欢小型库,因为它们与函数在同一个文件中。

或者我可以将它们全部放在一个单独的文件中并执行单独的文件,这很好,以防我不希望函数之间的 doctest。有时我发现如果文档字符串很小,代码更容易处理。

还有一种方法可以将 python doctests 保存在同一个文件中,但将它们放在文件末尾?


编辑:一个解决方案,基于以下接受的答案:

def hello_world():
  return u'Hello World'


def hello(name):
  return u'Hello %s' % name


def doctest_container():
  """
  >>> hello_world()
  u'Hello World'

  >>> hello(u'Guido')
  u'Hello Guido'
  """
  pass


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

实际上很简单,创建一个虚拟函数作为最后一个函数,该函数在一个文档字符串中包含所有文档测试。

4

2 回答 2

2

您可以将文档测试附加到文件末尾的文档字符串中,如下所示:

def myfunc():
    """This is a docstring without a doctest
    """
    pass

# ... some other code here

# Add docstrings for doctest:
myfunc.__doc__ += """
>>> myfunc()
>>> repr(myfunc())
None
"""
于 2012-03-19T12:37:24.213 回答
1

doctest is to test that examples in your documentation are in sync with the implementation.

if there are many tests; unit tests written as code might be easier to maintain than doctest-based tests.

You could add a test function at the end of the module with desired doctests to avoid polluting docstrings of non-test code:

def test():
    """
    ..
    """
    import doctest
    doctest.testmod()

if __name__=="__main__": 
    test()  # if the module is called as a script then run tests
于 2012-03-19T14:08:13.427 回答