三步驟使用 nose 開始測試1. 安裝或更新 nose# easy_install -U nose沒用過 easy_install ? 你該開始試著用了!2. 撰寫測試用例 (test case)打開一個新的 python 檔案, 我們統一在這個新檔案裡寫測試用例將要測試的模組匯入:
file something.py 的內容:class Hello:def __init__(self):self.template = "hello world"def render(self):return self.template這篇文章不講怎麼寫 python 程式, 這部份請自理:Pnose 測試工具試別測試用例的條件是判斷找到的這個類別或方法的名稱是不是以"test" 或 "Test"開頭. 如果是的話就當成是測試用例.所以要弄一個剛剛範例程式用的測試用例, 我們只要寫下:
file testsomething.py 的內容:def test_Hello():abc = Hello()assert "hello" in abc.render()assert "bonjour" not in abc.render()assert 是 nose 用來判斷測試結果的語法. 主要有這兩種:
assert 片段 in "結果"
assert 片段 not in "結果"對照上面範例, 可以得知上面兩者的意思就是:
測試結果"hello"字串應該在 abc.render() 回應的結果裡
測試結果"bonjour"字串應該不會在 abc.render() 回應的結果裡如果上面任一種情況不符合 assert 敘述, 這個測試用例就會回報失敗.3. 開始測試切換到檔案在的檔案目錄下, 輸入# nosetests結果應該類似這個樣子:
D:\path\pyfile>nosetests......----------------------------------------------------------------------Ran 1 tests in 0.020sOK那麼如果我們改動了 something.py 中 self.template 變數的內容, 在內容裡加上了 "bonjour" 字樣, 會發生什麼事情呢?有測試工具的好處就是我們只要單純地再次運行 nosetests 命令就好了, 不用花腦力去判斷或思考:) 我們查看訊息時會看到類似以下的訊息:
2, in runTestself.testFunc()File "D:\path\pyfile\testsomething.py", line 90, in test_Helloassert "bonjour" not in abc.render()AssertionError-----------------Ran 1 tests in 0.030sFAILED (failures=1, errors=1)上面的報告提醒我們有一件錯誤: "bonjour"字串原本不應該出現在 abc.render() 回應結果中的, 但結果中竟然出現了!所以如果我們的測試用例寫的好, 就可以肯定我們剛剛改動 something.py 時出了些問題. 測試這件事確實有效!還有一種更直覺的方式: 使用 doctestnosetests --with-doctestdoctest 是什麼? 怎麼使用 doctest 呢? 下次再開講囉====== 楔子 ==自從聽說了敏捷方法 (Agile programming)後, 一直很想試試這種"測試先行"的開發方式.但是在 python 上前後試過 unitest, doctest, 都不夠"簡單到會想常常拿來用"的程度,今天拿了一份原型寫得差不多的程式, 試著寫些測試用例 (test case) 後用 nose 測試工具來測試看看, 想不到 nose 還蠻容易使用的.我知道這個工具已經快半年了, 到今天才有時間, 勇氣真的下去嘗試.讓我白白錯過這樣好用的工具這麼久, 應該怪在 nose 太少文件可以參考的頭上吧?與其怪人, 不如我自己來寫個"三步驟使用 nose 開始測試"的簡易文件好了. |