【问题标题】:Put python doctest at the end of the code file?将python doctest放在代码文件的末尾?
【发布时间】:2012-03-19 12:03:50
【问题描述】:

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

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

【问题讨论】:

  • test() 可能是比doctest_container() 更好的名称,您可以将 doctest.testmod() 移到test() 中。我已经相应地更新了答案。

标签: python unit-testing doctest docstring


【解决方案1】:

您可以像这样将文档测试附加到文件末尾的文档字符串中:

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

# ... some other code here

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

【讨论】:

    【解决方案2】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-05
      • 2019-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-12
      • 2023-01-11
      • 2019-11-06
      相关资源
      最近更新 更多