只是简单记录一下测试代码怎么写
环境
Win10
Python3.7
Django2.2
项目
参照官网 快速开始 写了一个 demo
测试
参照官网 测试
和 Django 的测试差不多
创建 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"])
执行测试
python manage.py test <测试文件所在目录>
python manage.py test tests/
测试结果,执行一个测试成功
测试前创建测试数据库,测试完毕删除数据库
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'...
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Django REST framework 单元测试 - Python技术站