Django REST framework 单元测试实例解析

yipeiwu_com7年前Python基础

这篇文章主要介绍了Django REST framework 单元测试实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

环境

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'...

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python 列表中[ ]中冒号‘:’的作用

中括号[ ]:用于定义列表或引用列表、数组、字符串及元组中元素位置 list1 = ['physics', 'chemistry', 1997, 2000] list2 = [1,...

浅谈Series和DataFrame中的sort_index方法

Series 的 sort_index(ascending=True) 方法可以对 index 进行排序操作,ascending 参数用于控制升序或降序,默认为升序。 若要按值对 Ser...

python中的一些类型转换函数小结

函数               &...

解决pycharm无法识别本地site-packages的问题

解决pycharm无法识别本地site-packages的问题

之前一直用python自带的IDLE写python程序,后来发现有一些限制啥的,于是下载了pycharm作为IDE去处理python 新建项目以后本以为能直接跑以前的代码,发现有些库无法...

Django之使用celery和NGINX生成静态页面实现性能优化

Django之使用celery和NGINX生成静态页面实现性能优化

性能优化原理: 当我们要给client浏览器返回一个页面时,我们需要去数据库查询数据并将数据和基本页面模板渲染形成页面返回给客户端,但如果每一个用户访问时都去查询一次首页的的数据时,当日...