把python doctest放在代码文件的末尾?

时间:2012-03-19 12:03:50

标签: python unit-testing doctest docstring

我可以将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()

实际上很简单,创建一个虚函数作为包含一个docstring中所有doctests的最后一个函数。

2 个答案:

答案 0 :(得分:2)

您可以将doctests附加到文件末尾的docstring中,如下所示:

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

# ... some other code here

# Add docstrings for doctest:
myfunc.__doc__ += """
>>> myfunc()
>>> repr(myfunc())
None
"""

答案 1 :(得分:1)

doctest用于测试文档中的示例是否与实现同步。

如果有很多测试;作为代码编写的单元测试可能比基于doctest的测试更容易维护。

您可以使用所需的doctests在模块末尾添加测试函数,以避免污染非测试代码的文档字符串:

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

if __name__=="__main__": 
    test()  # if the module is called as a script then run tests
相关问题