很早就知道TDD 的開發模式了,不過總是養不成先寫測試的習慣,這次強制自己 把自己新項目中的測試部分加上,藉此機會也學習了 pytest.
參考教程http://www.testclass.net/pytest/
這個網站上有很多 關於 test 的介紹也推薦給大家隨時查閱。
下面介紹一下我使用的情況。
我使用的IDE 是VS Code, python3.6
按照 pytest
pip install pytest
測試的目錄結構和src 目錄同級 然後編寫測試代碼。
我的項目的代碼結構如下
├── config #相關配置文件
├── logs #log文件夾
├── src
│ ├── algorithm #具體業務邏輯代碼
│ │ ├── algorithm_result.py
│ │ ├── health_info.py
│ │ ├── load_info.py
│ │ └── parcel_info.py
│ ├── dao #關於數據庫訪問鏈接的代碼
│ │ ├── database_connection.py
│ │ ├── database_dao.py
│ │ ├── database_service.py
│ │ ├── table_model.py
│ │ └── type.py
│ ├── logsetting # log 的配置
│ │ └── log_setting.py
│ ├── route.py # 主程序
│ ├── static # 前端代碼
│ └── util
│ └── sendmail # 發郵件相關的代碼
└── test # 測試代碼
├── algorithm
│ ├── test_algorithm_result.py
│ ├── test_health_info.py
│ ├── test_load_info.py
│ └── test_parcel_info.py
└── test_route.py
目前就針對 algorithm方面寫了pytest.
下面的代碼是用來判斷我代碼中get_load_info() 這個函數是否正確返回的。
import sys
import datetime
import pytest
sys.path.append("../src")
import algorithm.health_info as hi
class TestHealthInfo(object):
def test_get_health_info(self):
dt = datetime.datetime.now().strftime("%Y-%m-%d")
res= hi.get_health_info(dt)
assert res['health']!= None
#爲了測試多個用例,這裏測試5次分別將3,4,6,7,8 這些參數代入進行測試
@pytest.mark.parametrize("campid", [3, 4, 6, 7, 8])
def test_get_algrithm_status_dic(self, campid):
dt = datetime.datetime.now().strftime("%Y-%m-%d")
res = hi.get_algrithm_status_dic(dt, campid)
print(res)
assert res['NORMAL'] != None
assert type(res) == dict
@pytest.mark.parametrize("campid", [3, 4, 6, 7, 8])
def test_get_confirm_status_dic(self, campid):
dt = datetime.datetime.now().strftime("%Y-%m-%d")
res = hi.get_confirm_status_dic(dt, campid)
print(res)
assert res['wave'] != None
這裏@pytest.mark.parametrize("campid", [3, 4, 6, 7, 8]) 這一行給定了這個測試的參數,在運行的時候這個測試會執行5次,分別傳入3,4,6,7,8 的參數進行測試,這個是我覺得比較方便的地方
用了斷言判斷相應的字段是否爲空,判斷返回值類型是否是 dict .
然後剩下的就是 在命令行裏 輸入pytest了。
還有另外一種方式就是這個VS code 裏 會出現如下標誌
點一下這個 Run Test 就能針對性的進行測試,或者按照Code Runner 這個拓展插件,選中 測試代碼右擊 run code 也可以。
這裏由於有5個參數因此在這Run test後面有(Multiple)的標識, 當我們點擊這個標識的時候,也可以去選擇運行指定一個參數進行測試。還是比較人性化的。如下圖。
這個pytest 還是比較方便的。學會這個技能之後就能使用TDD的開發模式啦