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

2024-05-29 05:23:59 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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


编辑:基于以下公认答案的解决方案:

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中包含所有doctest。在


Tags: 文件函数代码namehelloworldreturndef
2条回答

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

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

您可以使用所需的doctest在模块末尾添加一个测试函数,以避免污染非测试代码的docstring:

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

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

您可以将doctest附加到文件末尾的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
"""

相关问题 更多 >

    热门问题