2019-07-19|閱讀時間 ‧ 約 8 分鐘

[Python] 用 Pytest 來做 Unit Test

什麼是Pytest?
Pytest是一款強大的Python測試工具,支援平行化測試,使用上簡單方便,適合用在各種不同類型的軟體架構,也適用於RD、QA或獨立測試小組,也適合正要導入TDD的公司。
被選為最受歡迎的Testing Framework。(不多說了自己看吧 XD)

來寫測試吧!
  • 先用pip安裝pytest:
pip install pytest
  • 測試專案 - Folder Structure []
pytest-demo
   │  README.md
   │
   ├─libs
   │      module.py
   │      __init__.py
   │
   └─tests
          test_module.py
  • libs\module.py
  • tests\test_module.py
1. 在 module.py 定義一個名為 Module 的 class,再將class import 至 test_module.py
2. 接著,宣告兩個測試function,命名方式為test_開頭
3. 將pytest-demo這個路徑加入PYTHONPATH。 [] []
我們將驗證 Module.get_true() 的回傳值為True,而 Module.get_false() 回傳值為 False
在pytest-demo路徑下執行測試:
pytest-demo> pytest
==================== test session starts ====================
platform win32 -- Python 3.6.2, pytest-5.0.1, py-1.8.0, pluggy-0.12.0
rootdir: ..\pytest-demo
collected 2 items
tests\test_module.py ..     [100%]
==================== 2 passed in 0.03 seconds ====================
測試成功的執行了! 但...我想看更詳細的訊息怎麼辦? 使用 pytest -v 或是 pytest --verbose 會得到以下結果~~~~
\pytest-demo> pytest -v
==================== test session starts ==================== platform win32 -- Python 3.6.2, pytest-5.0.1, py-1.8.0, pluggy-0.12.0 -- ..\programs\python\python36-32\python.exe
cachedir: .pytest_cache
rootdir: ..\pytest-demo
collected 2 items
tests/test_module.py::test_get_true_func PASSED [ 50%] tests/test_module.py::test_get_false_func PASSED [100%]
==================== 2 passed in 0.03 seconds ====================
太神啦! 簡單快速地完成了!  但我們更改一下 get_true() 的回傳值為 False 來產生測試失敗的狀況:
\pytest-demo> pytest -v
==================== test session starts ====================
platform win32 -- Python 3.6.2, pytest-5.0.1, py-1.8.0, pluggy-0.12.0 -- ..\programs\python\python36-32\python.exe
cachedir: .pytest_cache
rootdir: ..\pytest-demo
collected 2 items
tests/test_module.py::test_get_true_func FAILED [ 50%] tests/test_module.py::test_get_false_func PASSED [100%]
==================== FAILURES ==================== ____________________________________________________________ test_get_true_func _____________________________________________________________
def test_get_true_func():
>       assert Module.get_true() is True
E       assert False is True
E        +  where False = <function Module.get_true at 0x036A0930>()
E        +    where <function Module.get_true at 0x036A0930> = Module.get_true
tests\test_module.py:5: AssertionError
==================== 1 failed, 1 passed in 0.07 seconds ====================
在 Windows PowerShell Console 下會有顏色可以很簡單的區分 PASS or FAIL

參考資料:

分享至
成為作者繼續創作的動力吧!
從 Google News 追蹤更多 vocus 的最新精選內容從 Google News 追蹤更多 vocus 的最新精選內容

Wis Chang的沙龍 的其他內容

發表回應

成為會員 後即可發表留言
© 2024 vocus All rights reserved.