2012-03-19 57 views
2

我可以把python doctests放在每个函数的主体中,我有时候喜欢小函数库,因为它们和函数在同一个文件中。把python doctest放在代码文件的末尾?

或者我可以把它们放在一个单独的文件中,并执行单独的文件,这是很好的情况下,我不想在函数之间进行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() 

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

+0

'测试()'可能比'doctest_container一个更好的名字() ',你可以在'test()'里面移动doctest.testmod()。我已经相应地更新了答案。 – jfs 2012-03-20 00:50:31

回答

1

doctest是测试你的文档中的例子是与实现同步。

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

你可以在与所需文档测试模块的末尾添加测试功能,以避免污染的非测试代码的文档字符串:

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

if __name__=="__main__": 
    test() # if the module is called as a script then run tests 
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 
"""