Django 环境搭建及Restful 接口测试实践

Django 环境搭建及Restful 接口测试实践_第1张图片

作者:桃子

本文分为两部分,一是搭建django接口开发环境,二是接口测试,接口测试分别介绍了使用postman工具测试、Request+Unittest测试和Drango自带测试模块

一 django接口开发

 Django 安装

实践:输入 django-admin.py 运行成功

 drango rest  framework 安装

 项目创建

d 盘创建新项目

命令:django-admin startproject django_restful

django_restful 项目中创建 api 应用

命令:python manage.py startapp api


进入 D:\django_restful\django_restful 目录下,打开 setting.py 文件创建 api 和 rest_framework

Django 环境搭建及Restful 接口测试实践_第2张图片

配置 rest_framewor 权限

在 setting.py 文件末尾添加权限代码:

REST_FRAMEWORK = {

    'DEFAULT_PERMISSION_CLASSES': [

        'rest_framework.permissions.IsAuthenticated',

    ]

}

 数据库迁移

cmd下输入命令: python manage.py migrate

提示如下图迁移成功

Django 环境搭建及Restful 接口测试实践_第3张图片

 创建超级管理员

cmd下输入命令: python manage.py createsuperuser

依次输入账号、邮箱、密码,如下图


Django 环境搭建及Restful 接口测试实践_第4张图片

 启动server

启动django ,登录创建的用户python manage.py runserver


Django 环境搭建及Restful 接口测试实践_第5张图片

浏览器输入地址:http://127.0.0.1:8000/


Django 环境搭建及Restful 接口测试实践_第6张图片

 登录超级管理员账户

浏览器输入地址:http://127.0.0.1:8000/admin

输入账号、密码后登录


Django 环境搭建及Restful 接口测试实践_第7张图片

 数据序列化


Django 环境搭建及Restful 接口测试实践_第8张图片

在API文件夹下新建serializers.py文件,定义API返回形式,返回哪些字段,返回怎样的格式等


Django 环境搭建及Restful 接口测试实践_第9张图片

代码:

# from django.contrib.auth.models import User,Group

from  rest_framework import serializers

from api.models import User,Group

class UserSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:

        model=User

        fields=('url','username','email','groups')

class GroupSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:

        model=Group

        fields=('url','name')

 创建视图

Django rest framework 使用ViewSets定义视图的展现形式,如何向用户展示数据,展示什么数据等

在 Api下vies.py文件编写如下代码

from django.shortcuts import render

# from django.contrib.auth.models import User,Group

from rest_framework import viewsets

from api.serializers import UserSerializer,GroupSerializer

from api.models import User,Group

# Create your views here.

class UserViewSet(viewsets.ModelViewSet):

    """

        retrieve:

            Return a user instance.


        list:

            Return all users,odered by most recent joined.


        create:

            Create a new user.


        delete:

            Remove a existing user


        partial_update:

            Update one or more fields on a existing user.


        update:

            Update a user.



    """

    queryset = User.objects.all()

    serializer_class = UserSerializer

class GroupViewSet(viewsets.ModelViewSet):

    """

            retrieve:

                Return a group instance.

            list:

                Return all groups, ordered by most recently joined.

            create:

                Create a new group.

            delete:

                Remove an existing group.

            partial_update:

                Update one or more fields on an existing group.

            update:

                Update a group.

        """

    queryset = Group.objects.all()

    serializer_class = GroupSerializer

 URL路由配置

打开django_restful/urls.py文件,填写下面的代码配置路由

"""django_restful URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:

    https://docs.djangoproject.com/en/2.0/topics/http/urls/

Examples:

Function views

    1. Add an import:  from my_app import views

    2. Add a URL to urlpatterns:  path('', views.home, name='home')

Class-based views

    1. Add an import:  from other_app.views import Home

    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')

Including another URLconf

    1. Import the include() function: from django.urls import include, path

    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))

"""

from django.contrib import admin

from django.urls import path

from django.conf.urls import include

from rest_framework import routers

from api import views

#from rest_framework.schemas import get_schema_view

#from rest_framework_swagger.renderers import SwaggerUIRenderer,OpenAPIRenderer

#schema_view=get_schema_view(title='API',renderer_classes=[OpenAPIRenderer,SwaggerUIRenderer])

router=routers.DefaultRouter()

router.register(r'users',views.UserViewSet)

router.register(r'groups',views.GroupViewSet)

urlpatterns = [

    path('admin/', admin.site.urls),

    path('',include(router.urls)),

    path('api-auth/',include('rest_framework.urls',namespace='rest_framework')),

    path('docs/',schema_view,name='docs')

]

cmd下重新启动服务:python manage.py runserver

# from django.contrib.auth.models import User,Group

from  rest_framework import serializers

from api.models import User,Group

class UserSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:

        model=User

        fields=('url','username','email','groups')

class GroupSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:

        model=Group

        fields=('url','name')

 打开API主页


Django 环境搭建及Restful 接口测试实践_第10张图片

 Swagger 接口文档生成

Swagger是一个框架,是一个restful风格的web服务,每次接口有变动,接口文档也会自动更新

django接入swagger

cmd 安装swagger :pip install django-rest-swagger


Django 环境搭建及Restful 接口测试实践_第11张图片

打开 setting.py 文件,添加django-rest-swagger应用

打开views.py 填写如下代码:

from django.shortcuts import render

from django.contrib.auth.models import User,Group

from rest_framework import viewsets

from api.serializers import UserSerializer,GroupSerializer

#from api.models import User,Group

# Create your views here.

class UserViewSet(viewsets.ModelViewSet):

    """

        retrieve:

            Return a user instance.


        list:

            Return all users,odered by most recent joined.


        create:

            Create a new user.

        delete:

            Remove a existing user

        partial_update:

            Update one or more fields on a existing user.

        update:

            Update a user.



    """

    queryset = User.objects.all()

    serializer_class = UserSerializer

class GroupViewSet(viewsets.ModelViewSet):

    """

            retrieve:

                Return a group instance.

            list:

                Return all groups, ordered by most recently joined.

            create:

                Create a new group.

            delete:

                Remove an existing group.

            partial_update:

                Update one or more fields on an existing group.

            update:

                Update a group.

        """

    queryset = Group.objects.all()

    serializer_class = GroupSerializer

打开url.py 添加如下代码

"""django_restful URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:

    https://docs.djangoproject.com/en/2.0/topics/http/urls/

Examples:

Function views

    1. Add an import:  from my_app import views

    2. Add a URL to urlpatterns:  path('', views.home, name='home')

Class-based views

    1. Add an import:  from other_app.views import Home

    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')

Including another URLconf

    1. Import the include() function: from django.urls import include, path

    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))

"""

from django.contrib import admin

from django.urls import path

from django.conf.urls import include

from rest_framework import routers

from api import views

from rest_framework.schemas import get_schema_view

from rest_framework_swagger.renderers import SwaggerUIRenderer,OpenAPIRenderer

schema_view=get_schema_view(title='API',renderer_classes=[OpenAPIRenderer,SwaggerUIRenderer])

router=routers.DefaultRouter()

router.register(r'users',views.UserViewSet)

router.register(r'groups',views.GroupViewSet)

urlpatterns = [

    path('admin/', admin.site.urls),

    path('',include(router.urls)),

    path('api-auth/',include('rest_framework.urls',namespace='rest_framework')),

    path('docs/',schema_view,name='docs')

]

启动服务,浏览器打开网址http://127.0.0.1:8000/docs/

界面如下:


Django 环境搭建及Restful 接口测试实践_第12张图片

三 Restful 接口测试

可以使用工具测试如postman或者jmeter,也可以通过request+unittest脚本测试

测试场景:

正常测试:数据的增删改查

异常测试:未授权,参数异常等

postman测试

1. user接口

 查询功能

get方法

url输入http://127.0.0.1:8000/users

授权:authorization选择basic auth,输入账户、密码

点击send


Django 环境搭建及Restful 接口测试实践_第13张图片

send结果:

Django 环境搭建及Restful 接口测试实践_第14张图片

 创建用户

POST方法

url输入/http://127.0.0.1:8000/users

授权:authorization选择basic auth,输入账户、密码

body下输入username 33333

点击send


Django 环境搭建及Restful 接口测试实践_第15张图片

 修改用户

修改ueser id为2的用户名改为lbz

PATCH 方法

url输入/http://127.0.0.1:8000/users/2/

授权:authorization选择basic auth,输入账户、密码

body下输入username lbz

点击send


Django 环境搭建及Restful 接口测试实践_第16张图片

 删除测试

删除ueser id为3的用户

PATCH 方法

url输入/http://127.0.0.1:8000/users/3/

授权:authorization选择basic auth,输入账户、密码

点击send


 未授权测试

输入路径如http://127.0.0.1:8000/users/

不授权,点击send,提示如下


Django 环境搭建及Restful 接口测试实践_第17张图片

脚本测试

Request+Unittest测试

在API目录下新建test_unittest.py,输入下面代码,实现增删改查功能

#-*-coding:GBK -*-

import requests

import unittest

class UserTest(unittest.TestCase):

    def setUp(self):

        self.base_url='http://127.0.0.1:8000/users'

        self.auth=('51zxw','51zxw20182018')

#查询功能

    def test_get_user(self):

        r=requests.get(self.base_url+'/1/',auth=self.auth)

        result=r.json()

        self.assertEqual(result['username'],'51zxw')

        self.assertEqual(result['email'],'[email protected]')


#添加功能

    def test_add_user(self):

        form_data={'username':'add1','email':'[email protected]','groups':'http://127.0.0.1:8000/groups/2/'}

        r=requests.post(self.base_url+'/',data=form_data,auth=self.auth)

        result=r.json()

        self.assertEqual(result['username'],'add1')


#修改功能

    def test_update_user(self):

        form_data={'email':'[email protected]'}

        r=requests.patch(self.base_url+'/2/',data=form_data,auth=self.auth)

        result=r.json()


        self.assertEqual(result['email'],'[email protected]') 

#删除功能

    def test_delete_user(self):

        r=requests.delete(self.base_url+'/3/',auth=self.auth)

        self.assertEqual(r.status_code,404) 

#无授权

    def test_no_auth(self):

        r=requests.get(self.base_url)

        result=r.json()

        self.assertEqual(result['detail'],'Authentication credentials were not provided.')

if __name__=='_main_':

    unittest.main()

Drango自带测试模块

打开API目录下新建tests文件输入下面代码,实现增删改查功能

#-*-coding:GBK -*-

from django.test import TestCase

import requests

class UserTest(TestCase):

    def setUp(self):

        self.base_url='http://127.0.0.1:8000/users'

        self.auth=('51zxw','51zxw20182018')

#查询功能

    def test_get_user(self):

        r=requests.get(self.base_url+'/1/',auth=self.auth)

        result=r.json()

        self.assertEqual(result['username'],'51zxw')

        self.assertEqual(result['email'],'[email protected]')

#添加功能

    def test_add_user(self):

        form_data={'username':'add1','email':'[email protected]','groups':'http://127.0.0.1:8000/groups/2/'}

        r=requests.post(self.base_url+'/',data=form_data,auth=self.auth)

        result=r.json()

        self.assertEqual(result['username'],'add1')

#修改功能

    def test_update_user(self):

        form_data={'email':'[email protected]'}

        r=requests.patch(self.base_url+'/2/',data=form_data,auth=self.auth)

        result=r.json()

        self.assertEqual(result['email'],'[email protected]') 

#删除功能

    def test_delete_user(self):

        r=requests.delete(self.base_url+'/3/',auth=self.auth)

        self.assertEqual(r.status_code,404) 

#无授权

    def test_no_auth(self):


        r=requests.get(self.base_url)

        result=r.json()

        self.assertEqual(result['detail'],'Authentication credentials were not provided.')

运行:

cmd下:python manage.py test

查看结果:

Django 环境搭建及Restful 接口测试实践_第18张图片

浏览器输入路径查看:http://127.0.0.1:8000/users/

Django 环境搭建及Restful 接口测试实践_第19张图片

你可能感兴趣的:(Django 环境搭建及Restful 接口测试实践)