測試
Django 內建以 Python 標準函式庫 unittest 為基礎的測試框架,並額外提供操作資料庫、模擬 HTTP 請求的工具,不需要另外安裝套件就能替 Models、Views 寫測試。及早補上關鍵功能的測試,能在修改程式碼時立刻發現哪裡壞掉,而不是等到使用者回報才發現。
官方文件:Testing in Django,對應官方教學的 Part 5:Testing。
測試檔案放在哪裡
startapp 建立 App 時,會自動產生一個 tests.py(或 tests/ 目錄),測試程式碼通常就寫在這裡:
用 TestCase 測試 Model
繼承 django.test.TestCase,每個測試方法都以 test_ 開頭。TestCase 會在每個測試方法執行前後,自動把資料庫包在一個交易(transaction)裡,測試之間不會互相污染資料:
# tests.py
from django.test import TestCase
from .models import Post
class PostModelTests(TestCase):
def test_str_returns_title(self):
post = Post.objects.create(title="Hello", content="World")
self.assertEqual(str(post), "Hello")
用 Client 測試 View
self.client 是 Django 測試框架提供的模擬瀏覽器,可以發送 GET/POST 請求,檢查回應的狀態碼、內容、使用的 Template 等,不需要真的啟動伺服器:
from django.test import TestCase
from django.urls import reverse
class PostListViewTests(TestCase):
def test_list_view_status_code(self):
response = self.client.get(reverse("post-list"))
self.assertEqual(response.status_code, 200)
def test_list_view_uses_correct_template(self):
response = self.client.get(reverse("post-list"))
self.assertTemplateUsed(response, "myapp/post_list.html")
常用的斷言方法(assertion):
| 方法 | 用途 |
|---|---|
assertEqual(a, b) |
檢查兩個值相等 |
assertTrue(x) / assertFalse(x) |
檢查條件成立/不成立 |
assertContains(response, text) |
檢查回應內容含有某段文字 |
assertTemplateUsed(response, name) |
檢查是否使用了指定的 Template |
assertRedirects(response, url) |
檢查回應是否導向指定網址 |
執行測試
只想跑某個 App 或某個測試類別,可以指定路徑:
執行測試時,Django 會自動建立一個獨立的測試資料庫,測試結束後銷毀,因此不用擔心測試資料弄髒正式或開發用的資料庫。
下一步
功能與測試都完成後,就可以準備 靜態檔案與上線,把網站部署到正式環境。