1.【知道】認識單元測試
單元測試:測類、方法、函數,測試最小單位由於django的特殊性,通過接口測單元,代碼邏輯都放在類視圖中單元測試好處消滅低級錯誤快速定位bug(有些分支走不到,通過單元測試提前測出問題)提高代碼質量(測試後順便優化代碼)2.【掌握】編寫和運行django的單元測試
django環境資料庫編碼資料庫用戶權限(需要建臨時資料庫、刪臨時資料庫)每個應用,自帶tests.py類,繼承django.test.TestCase前置、後置方法test開頭的測試用例集成在django的項目文件裡,更多是開發人員寫django自動的測試運行進入manage.py目錄命令python manage.py test 指定目錄下的某個文件3. TestCase類
3.1【知道】前後置方法運行特點
django.test.TestCase類主要由
前、後置處理方法
和
test開頭的方法
組成
test開頭的方法 是編寫了測試邏輯的用例setUp方法 (名字固定)在每一個測試方法執行之前被調用tearDown方法(名字固定) 在每一個測試方法執行之前被調用setUpClass類方法(名字固定)在整個類運行前執行只執行一次tearDownClass類方法(名字固定)在調用整個類測試方法後執行一次from django.test import TestCaseclass MyTest(TestCase): @classmethod def setUpClass(cls): print('setUpClass') @classmethod def tearDownClass(cls): print('tearDownClass') def setUp(self) -> None: print('setUp') def tearDown(self) -> None: print('tearDown') def test_xxx(self): print('測試用例1') def test_yyy(self): print('測試用例2')# python manage.py test meiduo_mall.apps.users.test_code
3.2【掌握】setUpClass 和 tearDownClass應用場景
寫測試代碼:放在test開頭的方法# 定義 setUpClass: 用戶登錄# 定義 tearDownClass: 用戶退出# 定義測試方法:獲取用戶信息、獲取用戶瀏覽器記錄、獲取用戶地址列表from django.test import TestCaseimport requestsclass MyTest(TestCase): s = None # 類屬性 @classmethod def setUpClass(cls): print('setUpClass') user_info = { "username": "mike123", "password": "chuanzhi12345", "remembered": True } # 1. 創建requests.Session()對象 # cls.s類屬性的s對象 cls.s = requests.Session() # 登陸 # json以json格式發送請求 r = cls.s.post('http://127.0.0.1:8000/login/', json=user_info) print('登陸結果=', r.json()) @classmethod def tearDownClass(cls): print('tearDownClass') r = cls.s.delete('http://127.0.0.1:8000/logout/') print('登出結果=', r.json()) def test_1_info(self): r = self.s.get('http://127.0.0.1:8000/info/') print('用戶結果=', r.json()) def test_2_browse_histories(self): r = self.s.get('http://127.0.0.1:8000/browse_histories/') print('瀏覽記錄結果=', r.json()) def test_2_browse_addresses(self): r = self.s.get('http://127.0.0.1:8000/addresses/') print('地址結果=', r.json())