Django REST framework 单元测试实例解析

yipeiwu_com6年前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并安装的步骤详解

下载官网python并安装的步骤详解

怎么下载官网python并安装? Python火了起来,很多人开始学习起来了,那么Python安装包,去哪里下载呢。那当然是去官网咯。 Python官网或直接 访问 https://ww...

Python切片索引用法示例

本文实例讲述了Python切片索引用法。分享给大家供大家参考,具体如下: 在Python中,可以用用简单的方括号加一个下标的方式访问序列的每一个元素,这种方式称之为切片操作符,切片操作符...

python加载自定义词典实例

如下所示: #加载词典 def load_dict_from_file(filepath): _dict = {} try: with io.open(filepat...

Python面向对象类继承和组合实例分析

本文实例讲述了Python面向对象类继承和组合。分享给大家供大家参考,具体如下: 在python3中所有类默认继承object,凡是继承了object的类都成为新式类,以及该子类的子类P...

Python 使用requests模块发送GET和POST请求的实现代码

①GET # -*- coding:utf-8 -*- import requests def get(url, datas=None): response = reques...