2012-03-19 36 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 
"""