2017-02-18 23 views
2

有時我正在編寫小型實用程序函數並將它們打包爲python包。
有多小? 30 - 60行蟒蛇。
而我的問題是你認爲在實際代碼中編寫測試不好嗎?濫用?在實際代碼中寫入python單元測試

我可以看到在代碼本身內使用示例的好處,而不會在文件之間跳轉(再次來自真正的小項目)。 例子:

#!/usr/bin/env python 
# Actual code 
def increment(number, by=1): 
    return number += by 

# Tests 
def test_increment_positive(): 
    assert increment(1) == 2 

def test_increment_negative(): 
    assert increment(-5) == -4 

def test_increment_zero(): 
    assert increment(0) == 1 

從我用的監測框架黎曼採取黎曼你寫你的測試文件連同你的代碼link

回答

3

你可以寫doctests你的文檔中,以指示如何的總體思路你功能可用於:

def increment(number, by=1): 
    """ Increments the given number by some other number 
    >>> increment(3) 
    4 
    >>> increment(5,3) 
    8 
    """ 
    return number += by 

從文檔:

  • 通過驗證所有交互式示例仍按記錄工作來檢查模塊的文檔是否是最新的。
  • 通過驗證來自測試文件或測試對象的交互式示例如預期工作來執行迴歸測試。
  • 要編寫一個包的教程文檔,用輸入輸出示例自由地說明。根據 例子或說明文是否強調,這有 味「識字測試」或「可執行文件」