Django筆記三十六之單元測試匯總介紹

Django 的單元測試使用了 Python 的標準庫:unittest。

在我們創(chuàng)建的每一個 application 下面都有一個 tests.py 文件,我們通過繼承 django.test.TestCase 編寫我們的單元測試。

本篇筆記會包括單元測試的編寫方式,單元測試操作流程,如何復用數(shù)據(jù)庫結構,如何測試接口,如何指定 sqlite 作為我們的單元測試數(shù)據(jù)庫等

以下是本篇筆記目錄:

  1. 單元測試示例、使用和介紹
  2. 單元測試流程介紹
  3. 單元測試的執(zhí)行命令
  4. 復用測試數(shù)據(jù)庫結構
  5. 判斷函數(shù)
  6. 接口的測試
  7. 標記測試
  8. 單元測試配置
  9. 使用 SQLite 作為測試數(shù)據(jù)庫

1、單元測試示例、使用和介紹

首先我們編寫 blog/tests.py 文件,創(chuàng)建一個簡單的單元測試:

from django.test import TestCase
from blog.models import Blog


class BlogCreateTestCase(TestCase):
    def setUp(self):
        Blog.objects.create(name="Python", tag_line="this is a tag line")

    def test_get_blog(self):
        blog = Blog.objects.get(name="Python")
        self.assertEqual(blog.name, "Python")

以上是一個很簡單的單元測試示例,接下來我們執(zhí)行這個單元測試:

python3 manage.py test blog.tests.BlogCreateTestCase.test_get_blog

執(zhí)行之后可以看到控制臺會輸出一些信息,如果沒有報錯,說明我們的這個單元測試成功執(zhí)行。

在 BlogCreateTestCase 中,這個單元測試繼承了 django.test.TestCase,我們在 setUp() 函數(shù)中執(zhí)行一些操作,這個操作會在執(zhí)行某個測試,比如 test_get_blog() 前先執(zhí)行。

我們執(zhí)行的是 test_get_blog() 函數(shù),這里的邏輯是先獲取一個 blog 示例,然后通過 assertEqual() 函數(shù)判斷兩個輸入的值是否相等,如果相等,則單元測試通過,否則會報失敗的錯誤。

2、單元測試流程介紹

首先我們看一下 settings.py 中的數(shù)據(jù)庫定義:

# hunter/settings.py

DATABASES = {
    'default': {
        'ENGINE': "django.db.backends.mysql",
        'NAME': "func_db",
        "USER": "root",
        "PASSWORD": "123456",
        "HOST": "192.168.1.9",
        "PORT": 3306,
    },
}

當我們執(zhí)行下面這個命令之后:

python3 manage.py test blog.tests.BlogCreateTestCase.test_get_blog

系統(tǒng)會去 default 這個數(shù)據(jù)庫的連接地址,創(chuàng)建一個新的數(shù)據(jù)庫,數(shù)據(jù)庫名稱為當前數(shù)據(jù)庫的名稱加上 test_ 前綴。

比如我們連接的正式數(shù)據(jù)庫名稱為 func_db,那么測試數(shù)據(jù)庫名為 test_func_db。

創(chuàng)建該數(shù)據(jù)庫之后,系統(tǒng)會將當前系統(tǒng)所有的 migration 都執(zhí)行一遍到測試數(shù)據(jù)庫,然后依據(jù)我們單元測試的邏輯,比如 setUp() 中對數(shù)據(jù)的初始化,以及 test_get_blog() 中對數(shù)據(jù)的獲取和比較操作執(zhí)行一遍邏輯。

這個流程結束之后,系統(tǒng)會自動刪除剛剛創(chuàng)建的測試數(shù)據(jù)庫,至此,一個單元測試執(zhí)行的流程就結束了。

3、單元測試的執(zhí)行命令

執(zhí)行單個單元測試

上面我們執(zhí)行的單元測試的命令精確到了類中的函數(shù),我們也可以直接執(zhí)行某個單元測試,比如我們的 BlogCreateTestCase 內容如下:

class BlogCreateTestCase(TestCase):
    def setUp(self):
        Blog.objects.create(name="Python", tag_line="this is a tag line")

    def test_get_blog(self):
        print("test_get_blog")
    
    def test_get_blog_2(self):
        print("test_get_blog_2")

我們直接執(zhí)行命令到這個單元測試:

python3 manage.py test blog.tests.BlogCreateTestCase

那么系統(tǒng)就會執(zhí)行 BlogCreateTestCase 下 test_get_blog 和 test_get_blog_2 這兩個函數(shù)。

執(zhí)行單元測試文件

再往上一層,我們可以執(zhí)行某個單元測試的文件,比如該 tests.py 內容如下:

# blog/tests.py

class BlogCreateTestCase(TestCase):
    def setUp(self):
        Blog.objects.create(name="Python", tag_line="this is a tag line")

    def test_get_blog(self):
        print("test_get_blog")
        
class BlogCreateTestCase2(TestCase):
    
    def test_get_blog_2(self):
        print("test_get_blog_2")

當我們執(zhí)行:

python3 manage.py test blog.tests

系統(tǒng)就會將 tests.py 中 BlogCreateTestCase 和 BlogCreateTestCase2 這兩個單元測試都執(zhí)行一遍。

執(zhí)行系統(tǒng)所有單元測試

如果我們想要統(tǒng)一執(zhí)行系統(tǒng)全部單元測試,可以直接如下操作:

python3 manage.py test

單元測試查找邏輯

當我們執(zhí)行上面那條命令的時候,系統(tǒng)是如何查找處測試文件的呢?

系統(tǒng)會搜索目錄下所有 test 開頭的文件夾或者文件,如果是文件夾,則繼續(xù)尋找文件夾下 test 開頭的文件,對于每個 test 開頭的文件,找到繼承了 django.test.TestCase 的類,然后執(zhí)行每個開頭名為 test 的類函數(shù)。

接下來我們舉幾個示例,假設我們在 blog 的目錄下有這樣的結構:

blog/
    test_123/
        no_test.py
        test_ok.py
        tests.py
    tests/
        tests.py
        test_123.py
    no_test/
        test_123.py
    test.py
    test_123.py
    no_test.py

在上面這個目錄結構下,系統(tǒng)會去搜索 test_123tests 文件夾下 test 開頭的文件,以及 blog 下的 test.pytest_123.py,尋找其中繼承了 django.test.TestCase 的類作為單元測試然后執(zhí)行。

在這里,比如 test_123/no_test.py 這個文件就不會被判定為測試文件,因為它名稱不是 test 開頭的。

而在 test 開頭的測試文件中,如果一個類繼承了 django.test.TestCase,但是它的類函數(shù)并不是以 test 開頭的,這樣的函數(shù)也不會被執(zhí)行,比如:

class BlogCreateTestCase(TestCase):
    def setUp(self):
        Blog.objects.create(name="如何Python", tag_line="this is a tag line")

    def test_ok(self):
        print("12344444............")
        self.assertEqual(1, 1)

    def no_test(self):
        print("no test")

比如上面這個單元測試,test_ok 這個類函數(shù)就會被作為單元測試的一部分,而 no_test 則不會被執(zhí)行。

如果測試文件較多,為了統(tǒng)一管理,我們可以都放在 application 下的 tests 文件夾下,比如:

blog/
    tests/
        test_1.py
        test_2.py
        test_3.py

4、復用測試數(shù)據(jù)庫結構

當我們寫完一個功能,然后編寫這個功能的單元測試,緊接著去測這個單元測試,系統(tǒng)就會去創(chuàng)建一個數(shù)據(jù)庫,然后執(zhí)行所有的 migration,然后執(zhí)行單元測試邏輯,執(zhí)行結束之后會刪掉該測試數(shù)據(jù)庫。

在我們的項目中,如果維護到了后期,擁有的 migration 較多,每次執(zhí)行單元測試都要刪掉然后重建數(shù)據(jù)庫,在時間上是一個很大的消耗,那么我們如何在執(zhí)行完一個單元測試之后保存當前的測試數(shù)據(jù)庫用于下一次執(zhí)行呢。

那就是使用 --keepdb 參數(shù)。

按照前面的邏輯,我們的測試數(shù)據(jù)庫會在 DATABASES 中定義的數(shù)據(jù)庫地址新建一個數(shù)據(jù)庫,我們可以使用 --keepdb 執(zhí)行這樣的操作:

python3 manage.py test --keepdb blog.tests.BlogCreateTestCase

加上 --keepdb 參數(shù)之后,執(zhí)行單元測試結束之后,我們可以通過 workbench 或者 navicat 等工具去該數(shù)據(jù)庫地址查看,會多出一個名為 test_fund_db 的數(shù)據(jù)庫,那就是我們執(zhí)行單元測試之后沒有刪除的測試數(shù)據(jù)庫。

當我們下次再執(zhí)行這個或者其他單元測試的時候,可以發(fā)現(xiàn)執(zhí)行的時間就變得很快了,而且在控制臺會輸出這樣一條信息:

Using existing test database for alias 'default'...

意思就是使用已經(jīng)存在的測試數(shù)據(jù)庫。

而不加 --keepdb 的時候,輸出的是:

Creating test database for alias 'default'...

表示的是正在創(chuàng)建新的測試數(shù)據(jù)庫。

注意: 雖然單元測試結束之后數(shù)據(jù)庫的結構還會保留,但是在單元測試中我們創(chuàng)建的數(shù)據(jù)還是會被刪除。這個僅限于在單元測試中創(chuàng)建的數(shù)據(jù),通過 migration 初始化的數(shù)據(jù)還是存在數(shù)據(jù)庫中。

5、判斷函數(shù)

在介紹測試接口前,我們先介紹一下幾個判定函數(shù)。

self.assertEqual

這個函數(shù)接收三個參數(shù),前兩個參數(shù)用于比較是否相等,第三個參數(shù)為 msg,用于在前兩個參數(shù)不相等時報出的錯誤信息,但是可不傳,默認為 None。

比如我們這樣操作:

self.assertEqual(Blog.objects.count(), 20, msg="blog count error")

self.assertEqual(Blog.objects.count(), 20)

如果前兩個參數(shù)不相等則單元測試會不通過。

self.assertTrue

這個函數(shù)接收兩個參數(shù),前一個參數(shù)是一個表達式,后一個參數(shù)是 msg,也是用于前一個參數(shù)不為 True 的時候報出的錯誤信息,可不傳,默認為 None。

我們可以這樣操作:

self.assertTrue(Blog.objects.filter(name="Python").exists(), "Pyrhon blog not exists")

self.assertTrue(Blog.objects.filter(name="Python").exists())

同樣,如果表達式參數(shù)不為 True,則單元測試不會通過。

self.assertIn

接收三個參數(shù),如果第二個參數(shù)不包含第一個參數(shù),則會報錯,比如:

self.assertIn(6, [1,2,3], "not in list")

self.assertIn("a", "def", "not in string")

self.assertIsNone

接口兩個參數(shù),表示如果傳入的參數(shù)為 None 則通過單元測試:

a = None
self.assertIsNone(a)

對于 assertEqual、 assertTrue、assertIn、assertIsNone 還有對應的相反意義的函數(shù)

  • assertNotEqual 表示判定兩者不相等
  • assertFalse 表示判定表達式為 False
  • assertNotIn 表示判定后者不包含前者
  • assertIsNotNone 表示判定不為 None

這里還有一些判定大于、小于、大于等于、小于等于的函數(shù),這里就不做多介紹了 assertGreater、assertLess、assertGreaterEqual、assertLessEqual

self.fail(msg="failed testcase")

如果我們希望在某些判斷條件下直接讓單元測試不通過,可以直接使用 self.fail() 函數(shù),比如:

a = 1
b = 2
if a < b:
    self.fail(msg="a < b")

6、接口的測試

在上面我們的單元測試中,我們使用的只是簡單的對于 model 的創(chuàng)建查詢和驗證,但是一般來說,除了測試系統(tǒng)的工具類函數(shù),我們常用到的測試用途是測試和驗證接口的邏輯。

在介紹如何對接口進行測試前,一下 model_mommy 庫。

model_mommy 庫

這是個可以模擬 model 數(shù)據(jù)的庫,它有什么用處呢,比如我們想創(chuàng)建幾條 model 的數(shù)據(jù),但是不關心一些必填字段的值,或者只想指定某幾個字段特定的值,或者想批量創(chuàng)建某個 model 的數(shù)據(jù)。

首先我們引入這個庫:

pip3 install model_mommy

使用 model_mommy 來創(chuàng)建模擬數(shù)據(jù):

from model_mommy import mommy

blog_1 = mommy.make(Blog, name="Python")

這樣我們就創(chuàng)建了一條數(shù)據(jù),這個時候如果我們打印出 blog_1 的內容,可以發(fā)現(xiàn) Blog 的有默認值的字段都被默認值填充,無默認值的都會被無意義數(shù)據(jù)填充

print(blog_1.__dict__)

#  'id': 4, 'name': 'Python', 'tag_line': 'sIDENcYqKVwESvEUAwZGIVtGdWHhKyNNoDzoaZCdDuqQuIKCkwazqwfcNEEtzfcoZeEnVVDiVLzAhhOuYsxiuKUOVFifUimnCLbMNHMpYLYxHCVSVfiggeBQhmRPFuIUwiKDUSDZztzQzFlKfcSxdnewsekQBzlCuMZLVPyOrfTXYWgPIkBhytzBkcMbpvCvidSETxZRjWeeEBPLELHpHYOmKgKHdNxrmjjLlewGWKTLQNFPFWOGndzncghTEcuFnEfRQvGgXcsPTfaGAHDDqPGyNeerTmOHDTUmnWmzHIXF', 'char_count': 0, 'is_published': 0, 'pub_datetime': None}

或者我們想批量創(chuàng)建二十條 Blog 的數(shù)據(jù),我們可以通過 _quantity 參數(shù)這樣操作:

mommy.make(Blog, _quantity=20)

Client() 調用接口

調用接口用到的函數(shù)是 Client()

假設我們想要調用登錄接口,我們可以如下操作:

from django.test import Client

url = "/users/login"
c = Client()
response = c.post(url, data={"username": "admin", "password": "123456"}, content_type="application/json")

self.assertEqual(response.json().get("code"), 0)

使用單元測試而不是使用 postman 調用有一個好處就是我們不用把后端服務啟動起來,所以這里的 url 相應的也不用加上 ip 地址或者域名。

調用接口還有另一種方式,就是在繼承了 django.test.TestCase 的單元測試中直接使用 self.client,它與實例化 Client() 后的直接作用效果是一樣的,都可以用來調用接口。

那為什么要使用 self.client 呢,是為了自動保存登錄接口的 session。

比如對于 /users/user/info 這個需要登錄后才能訪問到的用戶信息接口,我們就可以使用 self.client 在 setUp() 初始化數(shù)據(jù)的時候先進行登錄操作,接著就可以以已登錄狀態(tài)訪問用戶信息接口了。

class UserInfoTestCase(TestCase):
    def setUp(self):
        username = "admin"
        password = make_password("123456")
        User.objects.create(username=username, password=password)

        url = "/users/login"
        response = self.client.post(url, data={"username": "admin", "password": "123456"}, content_type="application/json")
        resp_data = response.json()
        print("login...")
        self.assertEqual(resp_data.get("code"), 0)
    
    def test_user_info(self):
        url = "/users/user/info"
        response = self.client.post(url)
        print(response.json())

如果系統(tǒng)大部分接口都需要以登錄狀態(tài)才能訪問,我們甚至可以將登錄操作寫入一個基礎類,其他的單元測試都繼承這個類,這樣就不需要重復編寫登錄的接口了:

class BaseTestCase(TestCase):
    def setUp(self):
        username = "admin"
        password = make_password("123456")
        User.objects.create(username=username, password=password)

        url = "/users/login"
        response = self.client.post(url, data={"username": "admin", "password": "123456"}, content_type="application/json")
        resp_data = response.json()
        print("login...")
        self.assertEqual(resp_data.get("code"), 0)



class UserInfoTestCase(BaseTestCase):
    def test_user_info(self):
        url = "/users/user/info"
        response = self.client.post(url)
        print(response.json())


class TestCase2(BaseTestCase):
    def test_case(self):
        url = "/xx/xxx"
        response = self.client.post(url)
        print(response.json())

7、標記測試

一般來說,我們的單元測試是都要全部通過才能上線進入生產(chǎn)環(huán)境的,但是某些情況下,我們對系統(tǒng)只進行了少部分的修改,或者說只需要測試某些特定的重要功能就可以上線,這種情況下可以給我們的測試用例打上 tag,這樣在測試的時候就可以挑選特定的單元測試,通過即可上線。

這個 tag 可以打到一個單元測試上,也可以打到某個單元測試的函數(shù)上,比如我們有三個標記,fast,slow,core,以下是幾個單元測試:

from django.test import tag

class SingleTestCase(TestCase):
    @tag("fast", "core")
    def test_1(self):
        print("fast, core from SingleTestCase.test_1")

    @tag("slow")
    def test_2(self):
        print("slow from SingleTestCase.test_2")


@tag("core")
class CoreTestCase(TestCase):
    def test_1(self):
        print("core from CoreTestCase")

然后我們可以通過 --tag 指定標記的單元測試:

python3 manage.py test --keepdb --tag=core

python3 manage.py test --keepdb --tag=core --tag=slow

8、單元測試配置

編碼配置

在前面我們的數(shù)據(jù)庫鏈接中,并沒有指定數(shù)據(jù)庫的編碼,而我們創(chuàng)建生產(chǎn)數(shù)據(jù)庫的時候使用的 charset 是 utf-8,而測試數(shù)據(jù)庫在創(chuàng)建的時候沒有指定編碼的話,默認使用的是 latin1 編碼。

這樣會造成一個問題,就是我們的單元測試在往數(shù)據(jù)庫寫入數(shù)據(jù)的時候就會因為不支持中文而導致報錯。

比如在不設置編碼的時候我們使用下面的單元測試就會報錯:

from django.test import TestCase
from blog.models import Blog


class BlogCreateTestCase(TestCase):
    def setUp(self):
        Blog.objects.create(name="測試數(shù)據(jù)", tag_line="this is a tag line")

    def test_get_blog(self):
        blog = Blog.objects.get(name="測試數(shù)據(jù)")
        self.assertEqual(blog.name, "測試數(shù)據(jù)")

所以如果要指定創(chuàng)建的測試數(shù)據(jù)庫的編碼,我們需要加上一個配置:

DATABASES = {
    'default': {
        ...
        "TEST": {
            "CHARSET": "utf8",
        },
    }
}

測試數(shù)據(jù)庫名稱

默認情況下,測試數(shù)據(jù)庫的名稱是 'test_' + DATABASES['default']['name'],如果我們想指定測試數(shù)據(jù)庫名稱,可以額外加一個 NAME 字段:

DATABASES = {
    'default': {
        ...
        "TEST": {
            "CHARSET": "utf8",
            "NAME": "test_default_db",
        },
    }
}

9、使用 SQLite 作為測試數(shù)據(jù)庫

目前我們的測試數(shù)據(jù)庫是在 default 數(shù)據(jù)庫的地址新建一個數(shù)據(jù)庫,如果我們想要運行單元測試的時候直接在本地使用 SQLite 作為我們的測試數(shù)據(jù)庫,可以在 settings.py 中定義 DATABASES 的后面加上下面的定義:

import sys

if "test" in sys.argv:
    DATABASES = {
        "default": {
            "ENGINE": "django.db.backends.sqlite3",
            "NAME": os.path.join(BASE_DIR, "db.sqlite3"),
            "TEST": {
                "NAME": os.path.join(BASE_DIR, "test_db.sqlite3"),
            }
        }
    }

其中,sys.argv 是一個列表,列表元素是我們執(zhí)行命令的各個參數(shù)。

所以當我們執(zhí)行單元測試命令的時候,會包含 test,所以數(shù)據(jù)庫的鏈接內容就會走我們這個邏輯。

在這部分,我們使用 ENGINE 來確定了后端數(shù)據(jù)庫的類型為 SQLite,然后通過 DATABASES["default"]["test"]["NAME"] 來指定我們的測試數(shù)據(jù)庫地址。

當我們執(zhí)行單元測試的命令時,在系統(tǒng)根目錄下就會多出一個 test_db.sqlite3 的數(shù)據(jù)庫。

原文鏈接:Django筆記三十六之單元測試匯總介紹

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容