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实现名片管理系统源代码,供大家参考,具体内容如下 import os def print_menu(): print("*"*50) print(...

如何利用Boost.Python实现Python C/C++混合编程详解

前言 学习中如果碰到问题,参考官网例子: D:\boost_1_61_0\libs\python\test 参考:Boost.Python 中英文文档。 利用Boost.Python...

Python中is与==判断的区别

在 Python 中,比较两个对象(变量)是否相等,可以用 “is” 和 “==” 操作,但它俩有什么区别?什么时候用 “is”,什么时候用 “==” ?在面试时,发现不少候选人很难把这...

pandas DataFrame 警告(SettingWithCopyWarning)的解决

刚接触python不久,编程也是三脚猫,所以对常用的这几个工具还没有一个好的使用习惯,毕竟程序语言是头顺毛驴。所以最近在工作中使用的时候在使用pandas的DataFrame时遇到了以下...

详解python播放音频的三种方法

第一种 使用pygame模块 pygame.mixer.init() pygame.mixer.music.load(self.wav_file) pygame.mix...