Django REST framework 單元測試實例解析
這篇文章主要介紹了Django REST framework 單元測試實例解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
環(huán)境
Win10
Python3.7
Django2.2
項目
參照官網(wǎng) 快速開始 寫了一個 demo
測試
參照官網(wǎng) 測試
和 Django 的測試差不多
創(chuàng)建 tutorial/tests/tests.py
import json
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
class LittleTestCase(TestCase):
def setUp(self):
self.click = APIClient()
def test_users_post(self):
# /users/ POST
data = {
"username": "tom",
"email": "tom@example.com"
}
response = self.client.post("/users/", data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
# /users/:id GET 地址
response_content = json.loads(response.content)
user_url = response_content["url"]
# /users/:id GET 檢查新增用戶是否符合預期
response = self.client.get(user_url)
response_content = json.loads(response.content)
self.assertEqual(response.status_code, 200)
self.assertEqual("tom", response_content["username"])
self.assertEqual("tom@example.com", response_content["email"])
執(zhí)行測試
python manage.py test <測試文件所在目錄>
python manage.py test tests/
測試結果
執(zhí)行一個測試成功
測試前創(chuàng)建測試數(shù)據(jù)庫,測試完畢刪除數(shù)據(jù)庫
Creating test database for alias 'default'... System check identified no issues (0 silenced). . ---------------------------------------------------------------------- Ran 1 test in 0.022s OK Destroying test database for alias 'default'...
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
使用Python實現(xiàn)Mysql數(shù)據(jù)庫相關操作詳解
這篇文章主要介紹了使用Python實現(xiàn)Mysql數(shù)據(jù)庫相關操作詳解,pymysql是Python中操作數(shù)據(jù)庫的第三方模塊,通過這個模塊的相關方法,我們可以連接并且去操作mysql數(shù)據(jù)庫,需要的朋友可以參考下2023-08-08
Python3正則表達式之:(?(id/name)yes-pattern|no-pattern)條件性匹配
(?(id/name)yes-pattern|no-pattern)的作用是對于給出的id或者name,先嘗試去匹配 yes-pattern部分的內(nèi)容,如果id或name條件不滿足,則去匹配no-pattern部分的內(nèi)容2021-10-10
Python用61行代碼實現(xiàn)圖片像素化的示例代碼
這篇文章主要介紹了Python用61行代碼實現(xiàn)圖片像素化的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2018-12-12

