python自动化测试三部曲之request+django实现接口测试

国庆期间准备写三篇博客,介绍和总结下接口测试,由于国庆期间带娃,没有按照计划完成,今天才完成第二篇,惭愧惭愧。

这里我第一篇博客的地址:https://www.cnblogs.com/bainianminguo/p/11616526.html,主要是介绍unittest框架,有兴趣的同学们可以移步去查阅

这里废话少说,进入正题

我的思路是这样的

1、先用django实现登陆、增加、删除、查看4个接口

2、在excel定义好测试案例、然后读取excel中的案例,然后把案例用unittest框架组装和封装

3、启动django,执行测试案例

一、先跑通unittest到django的流程

1、先创建一个Django的项目

2、创建路由,这里我们使用二级路由

a、先复制工程目录下的urls.py文件到app目录下

b、修改工程目录下的urls.py文件,定义一级路由

c、修改app目录下的urls.py文件,设置二级路由,这里切记务必要删除默认的admin这条路由

d、定义这条路由指向的视图的函数

e、启动django,这里我们使用9090端口启动,因为我们的Jenkins端口用的是8080

E:\python\unittestForDjango>python manage.py runserver 9090

f、这里的是启动成功的样式,我圈住的告警可以忽略,因为这里Django的admin需要的,我们这里不会用到django的admin

g、打开浏览器访问django,我们的一个简单的Django项目已经跑通

3、在视图函数中定义一个方法,这个方法分别处理GET请求和POST请求

a、定义视图函数

这里通过这个参数告诉浏览器,我们返回的是JSON数据

return HttpResponse(result, content_type="application/json;charset=utf-8")
def test_login(request):
    method = request.method.upper()
    if method == "GET":
        result = {}
        name = request.GET.get("username",None)
        pwd = request.GET.get("pwd",None)
        result["name"] = name
        result["pwd"] = pwd
        result = json.dumps(result)
        # return HttpResponse(result)
        return HttpResponse(result, content_type="application/json;charset=utf-8")

    else:
        result = {}
        name = request.POST.get("username",None)
        pwd = request.POST.get("pwd",None)
        result["name"] = name
        result["pwd"] = pwd
        result = json.dumps(result)
        return HttpResponse(result,content_type="application/json;charset=utf-8")

b、使用request模块发起POST和GET请求

#Auther Bob
#--*--conding:utf-8 --*--
import requests
import json

class TestCase(object):
    def __init__(self,username,pwd,url):
        self.username = username
        self.pwd = pwd
        self.url = url

    def get(self):
        # 发送get请求
        url = self.url + "?username=" + str(self.username) + "&" + "pwd=" + str(self.pwd)
        res = requests.get(url=url)
        print(res.text,type(res.text))

    def post(self):
        # 发送post请求
        data = {
            "username" : self.username,
            "pwd" : self.pwd
        }
        res = requests.post(url=self.url,data=data)
        print(res.text)

if __name__ == ‘__main__‘:
    url = "http://127.0.0.1:9090/web/login/"
    username = "zhangsan"
    pwd = "123"

    t = TestCase(username,pwd,url)

    t.get()
    t.post()

c、这里我们引入unittest框架,测试案例可以这么写

import unittest
from test3 import test_request
class TestDjango(unittest.TestCase):

    def setUp(self):
        print("unittest框架的前置条件")

    def tearDown(self):
        print("unittest框架的后置条件")

    def test_01(self):
        url = "http://127.0.0.1:9090/web/login/"
        username = "zhangsan"
        pwd = "123"
        t = test_request.TestCase(url=url,username=username,pwd=pwd)
    def test_02(self):
        url = "http://127.0.0.1:9090/web/login/"
        username = "zhangsan"
        pwd = "123"
        t = test_request.TestCase(url=url,username=username,pwd=pwd)
        t.post()

if __name__ == ‘__main__‘:
    unittest.main(verbosity=2)

d、这里有重复代码,我们可以利用unittest框架中的classmethod来解决,因为实例化一个测试类可以放在前置条件中

import unittest
from test3 import test_request
class TestDjango(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        url = "http://127.0.0.1:9090/web/login/"
        username = "zhangsan"
        pwd = "123"
        # 这里的t虽然是类变量,但是python的中的实例是可以用引用类变量的
        cls.t = test_request.TestCase(url=url,username=username,pwd=pwd)

    def setUp(self):
        print("unittest框架的前置条件")

    def tearDown(self):
        print("unittest框架的后置条件")

    def test_01(self):
        self.t.get()
    def test_02(self):
        self.t.post()

if __name__ == ‘__main__‘:
    unittest.main(verbosity=2)

e、在testcase中加入断言

import unittest
from test3 import test_request
class TestDjango(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        url = "http://127.0.0.1:9090/web/login/"
        username = "zhangsan"
        pwd = "123"
        # 这里的t虽然是类变量,但是python的中的实例是可以用引用类变量的
        cls.t = test_request.TestCase(url=url,username=username,pwd=pwd)

    def setUp(self):
        print("unittest框架的前置条件")

    def tearDown(self):
        print("unittest框架的后置条件")

    def test_01(self):
        res = self.t.get()
        self.assertEqual(200,res.status_code)
    def test_02(self):
        res = self.t.post()
        self.assertEqual(200, res.status_code)

if __name__ == ‘__main__‘:
    unittest.main(verbosity=2)

f、引入testsuite

import unittest
from unittest import TestLoader

from test3 import test_unittest

if __name__ == ‘__main__‘:
    suite = unittest.TestSuite()
    loader = TestLoader()
    test_cases1 = unittest.TestLoader().loadTestsFromModule(test_unittest)
    # 参数是一个模块,会把这个模块里的所有case加载进来
    suite.addTests(test_cases1)
    runner = unittest.TextTestRunner(verbosity=2)
    runner.run(suite)

二、在django中设计接口

这里我们写一个简单的例子,设计一个用户表,设计4个接口

接口1:登陆

接口2:增加用户,需要用户登陆

接口3:删除用户,需要用户登陆

接口4:查询用户,不需要用户登陆

1、先看登陆接口

a、登录接口对应的url

下面是一级路由

url(r‘^web/‘, include(‘unittesstApp1.urls‘))

下面是二级路由

url(r‘^login/‘, views.test_login),

b、登录接口的视图函数

def test_login(request):
    method = request.method.upper()
    if method == "GET":
        returndict = {"code": 200, "error": None}
        username = request.GET.get("username",None)
        password = request.GET.get("password",None)
        if username == "admin" and password == "admin123.":
            request.session["username"] = username
            request.session["password"] = password
            result = json.dumps(returndict)
        else:
            returndict["code"] = 201
            returndict["error"] = "用户名或者密码错误"
            result = json.dumps(returndict)
        return HttpResponse(result,content_type="application/json;charset=utf-8")

这里我们用到了session来代替cookies

2、增加用户接口

a、增加用户对应的url

一级路由同登陆接口,下面是二级路由

url(r‘^add/‘, views.test_add),

b、增加用户接口对应的视图函数,这里我们做了各种异常处理,且判断了用户是否登陆,也就是通过是否携带cookies来判断

def test_add(request):
    method = request.method.upper()
    if method == "POST":
        returndict = {"code": 200, "error": None}
        username = request.session.get("username",None)
        password = request.session.get("password",None)

        if username == "admin" and password == "admin123.":
            newusername = request.POST.get("username",None)
            age = request.POST.get("age",None)
            sex = request.POST.get("sex",None)
            pwd = request.POST.get("pwd",None)
            userinfo = [newusername,age,sex,pwd]
            print(userinfo)
            if not "None" in userinfo and all(userinfo):
                if models.userInfo.objects.filter(username = userinfo[0]).exists():
                    returndict["error"] = "{username} is exists,please add a new username".format(username = username)
                    returndict["code"] = 201
                    result = json.dumps(returndict)
                    return HttpResponse(result, content_type="application/json;charset=utf-8")
                else:
                    models.userInfo.objects.create(
                        username = newusername,
                        age = age,
                        sex = sex,
                        pwd = pwd
                    )
                    if models.userInfo.objects.filter(username=userinfo[0]).exists():
                        result = json.dumps(returndict)
                        return HttpResponse(result, content_type="application/json;charset=utf-8")
                    else:
                        returndict["error"] = "{username} is error,please retry add".format(username=username)
                        returndict["code"] = 201
                        result = json.dumps(returndict)
                        return HttpResponse(result, content_type="application/json;charset=utf-8")
            else:
                returndict["error"] = "must input username,age,sex,pwd"
                returndict["code"] = 201
                result = json.dumps(returndict)
                return HttpResponse(result, content_type="application/json;charset=utf-8")
        else:
            returndict = {"code": 201, "error": "用户名或者密码错误"}
            result = json.dumps(returndict)
            return HttpResponse(result, content_type="application/json;charset=utf-8")

3、删除接口

a、删除用户对应的url

一级路由同登陆接口,这里只看二级路由

  url(r‘^del/‘, views.del_user),

b、删除接口对应的视图函数,这里我做了各种异常处理,也做了用户是否登陆的检测,也是通过检测cookies来实现

def del_user(request):
    method = request.method.upper()
    if method == "POST":
        returndict = {"code": 200, "error": None}
        username = request.session.get("username",None)
        password = request.session.get("password",None)
        if username == "admin" and password == "admin123.":
            delusername = request.POST.get("username",None)
            print(delusername)
            if delusername != None:
                if models.userInfo.objects.filter(username=delusername).exists():
                    delid = models.userInfo.objects.get(username=delusername).id
                    print(delid)
                    try:
                        models.userInfo.objects.get(id=delid).delete()
                    except Exception as e:
                        returndict = {"code": 201, "error": e}
                        result = json.dumps(returndict)
                        return HttpResponse(result, content_type="application/json;charset=utf-8")
                    else:
                        result = json.dumps(returndict)
                        return HttpResponse(result, content_type="application/json;charset=utf-8")
                else:
                    returndict = {"code": 201, "error": "{username} is not exists".format(username = delusername)}
                    result = json.dumps(returndict)
                    return HttpResponse(result, content_type="application/json;charset=utf-8")
            else:
                returndict = {"code": 201, "error": "you must input a username"}
                result = json.dumps(returndict)
                return HttpResponse(result, content_type="application/json;charset=utf-8")

        else:
            returndict = {"code": 201, "error": "username or password is error"}
            result = json.dumps(returndict)
            return HttpResponse(result, content_type="application/json;charset=utf-8")

4、查看接口

a、查看接口对应的url

一级路由同登陆接口url,下面是二级路由

url(r‘^scan/‘, views.get_user),

b、查看接口对应的url,这里我们不检测用户是否登陆,直接把查到的数据返回给客户,如果查询报错,才返回错误的信息

def get_user(request):
    method = request.method.upper()
    returndict = {"code": 200, "userinfo": None}
    if method == "GET":
        try:
            alluser = models.userInfo.objects.all().values_list("username")
            alluserlist = []
            for i in alluser:
                alluserlist.append(i)

            returndict["userinfo"] = alluserlist

        except Exception as e:
            returndict["code"] = "201"
            returndict["error"] = e
        finally:
            result = json.dumps(returndict)
            return HttpResponse(result, content_type="application/json;charset=utf-8")

5、设计删除数据库中所有的接口,用来做后置条件

def del_alluser(request):
    method = request.method.upper()
    if method == "POST":
        returndict = {"code": 200, "error": None}
        username = request.session.get("username", None)
        password = request.session.get("password", None)
        if username == "admin" and password == "admin123.":
            if models.userInfo.objects.all().count() > 0:
                models.userInfo.objects.all().delete()
            result = json.dumps(returndict)
            return HttpResponse(result, content_type="application/json;charset=utf-8")

三、案例准备

1、在excel中写好接口测试案例

2、定义常量,也就是每列对应的值

class TestConfig(object):
    def __init__(self):
        self.name = 0
        self.url = 1
        self.method = 2
        self.cookies = 3
        self.data = 4
        self.res = 5
        self.exec = 6

    def getname(self):
        return self.name

    def geturl(self):
        return self.url

    def getmethod(self):
        return self.method

    def getcookies(self):
        return self.cookies

    def getdata(self):
        return self.data

    def getres(self):
        return self.res

    def getexec(self):
        return self.exec

3、定义读取excel的类,因为我要从excel中读取案例

import xlrd
import os

class testexcel(object):
    casepath = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "case", "testcase.xlsx")

    def __init__(self):
        self.casepath = testexcel.casepath
        self.execlobj = xlrd.open_workbook(self.casepath)
        self.sheetobj = self.execlobj.sheet_by_index(0)

    def get_excel_data(self,row,col):
        max_row = self.get_excel_max_row()
        max_col = self.get_excel_max_col()
        if row > max_row -1 or col > max_col - 1:
            return False
        else:
            data = self.sheetobj.cell_value(row,col)
            return data

    def get_excel_max_row(self):
        r_num = self.sheetobj.nrows
        return r_num

    def get_excel_max_col(self):
        c_num = self.sheetobj.ncols
        return c_num

4、定义我们的接口函数

import requests
import json

class TestLogin(object):
    def __init__(self,username,pwd,url):
        self.username = username
        self.pwd = pwd
        self.url = url

    def get(self):
        # 发送get请求
        url = self.url + "?username=" + str(self.username) + "&" + "password=" + str(self.pwd)
        res = requests.get(url=url,
                           headers={
                      "user-agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"
                  })
        # print(json.loads(res.text))
        return res

    def post(self):
        # 发送post请求
        data = {
            "username" : self.username,
            "pwd" : self.pwd
        }
        res = requests.post(url=self.url,
                            data=data,
                            headers={
                                "user-agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"
                            },
                            )
        # print(res.text)
        return res

class TestAdd(object):
    def __init__(self,username,age,sex,pwd,cookies,url):
        self.username = username
        self.age = age
        self.sex = sex
        self.pwd = pwd
        self.url = url
        self.cookies = cookies
    def post(self):
        # 发送post请求
        data = {
            "username" : self.username,
            "pwd" : self.pwd,
            "age" : self.age,
            "sex" : self.sex
        }
        res = requests.post(url=self.url,
                            data=data,
                            headers={
                                "user-agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"
                            },
                            cookies=self.cookies,
                            )
        # print(res.text)
        return res

class Testdel(object):
    def __init__(self, username,cookies,url):
        self.username = username
        self.cookies = cookies
        self.url = url

    def post(self):
        # 发送post请求
        data = {
            "username": self.username,
        }
        res = requests.post(url=self.url,
                            data=data,
                            headers={
                                "user-agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"
                            },
                            cookies=self.cookies,
                            )
        # print(res.text)
        return res

class Testscan(object):
    def __init__(self,url):
        self.url = url
    def get(self):
        res = requests.get(url=self.url,
                            headers={
                                "user-agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"
                            },
                            cookies=None,
                            )
        return res

5、定义测试案例

import unittest
from test3 import test_request
import json
from util import test_json
from util import test_excel
from case import testconfig
import requests

class TestDjango(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.alldata = test_json.testjson()

    @classmethod
    def tearDownClass(cls):
        url = "http://127.0.0.1:9090/web/login/" + "?username=" + "admin" + "&" + "password=" + "admin123."
        res = requests.get(url=url,
                           headers={
                      "user-agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"
                  })
        url = "http://127.0.0.1:9090/web/delall/"
        requests.post(url=url,
                      headers={
                          "user-agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"
                      },
                      cookies = res.cookies
                      )

    def get_cookies(self):
        url = "http://127.0.0.1:9090/web/login/" + "?username=" + "admin" + "&" + "password=" + "admin123."
        res = requests.get(url=url,
                           headers={
                      "user-agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"
                  })
        # print(json.loads(res.text))
        return res.cookies

    @unittest.skip(‘noexec‘)
    def test_login_ok(self):
        row = 1
        configobj = testconfig.TestConfig()
        excelobj = test_excel.testexcel()
        execstatus = excelobj.get_excel_data(row,configobj.getexec())
        if execstatus == "YES":
            cookiesstatus = excelobj.get_excel_data(row, configobj.getcookies())
            if cookiesstatus == "YES":
                cookies = self.get_cookies()
            else:
                cookies = None
            data = excelobj.get_excel_data(row, configobj.getdata())
            data = json.loads(data)
            url = excelobj.get_excel_data(row, configobj.geturl())
            res = excelobj.get_excel_data(row, configobj.getres())
            method = excelobj.get_excel_data(row, configobj.getmethod())
            if method == "GET":
                testobj = test_request.TestLogin(data["username"],data["pwd"],url)
                resobj = testobj.get()
                self.assertEqual(int(res),json.loads(resobj.text)["code"])

    @unittest.skip(‘noexec‘)
    def test_login_pwd_error(self):
        row = 2
        configobj = testconfig.TestConfig()
        excelobj = test_excel.testexcel()
        execstatus = excelobj.get_excel_data(row,configobj.getexec())
        if execstatus == "YES":
            cookiesstatus = excelobj.get_excel_data(row, configobj.getcookies())
            if cookiesstatus == "YES":
                cookies = self.get_cookies()
            else:
                cookies = None
            data = excelobj.get_excel_data(row, configobj.getdata())
            data = json.loads(data)
            url = excelobj.get_excel_data(row, configobj.geturl())
            res = excelobj.get_excel_data(row, configobj.getres())
            method = excelobj.get_excel_data(row, configobj.getmethod())
            if method == "GET":
                testobj = test_request.TestLogin(data["username"],data["pwd"],url)
                resobj = testobj.get()
                self.assertEqual(int(res),json.loads(resobj.text)["code"])

    @unittest.skip(‘noexec‘)
    def test_login_user_error(self):
        row = 3
        configobj = testconfig.TestConfig()
        excelobj = test_excel.testexcel()
        execstatus = excelobj.get_excel_data(row,configobj.getexec())
        if execstatus == "YES":
            cookiesstatus = excelobj.get_excel_data(row, configobj.getcookies())
            if cookiesstatus == "YES":
                cookies = self.get_cookies()
            else:
                cookies = None
            data = excelobj.get_excel_data(row, configobj.getdata())
            data = json.loads(data)
            url = excelobj.get_excel_data(row, configobj.geturl())
            res = excelobj.get_excel_data(row, configobj.getres())
            method = excelobj.get_excel_data(row, configobj.getmethod())
            if method == "GET":
                testobj = test_request.TestLogin(data["username"],data["pwd"],url)
                resobj = testobj.get()
                self.assertEqual(int(res),json.loads(resobj.text)["code"])

    @unittest.skip(‘noexec‘)
    def test_user_pwd_error(self):
        row = 4
        configobj = testconfig.TestConfig()
        excelobj = test_excel.testexcel()
        execstatus = excelobj.get_excel_data(row,configobj.getexec())
        if execstatus == "YES":
            cookiesstatus = excelobj.get_excel_data(row, configobj.getcookies())
            if cookiesstatus == "YES":
                cookies = self.get_cookies()
            else:
                cookies = None
            data = excelobj.get_excel_data(row, configobj.getdata())
            data = json.loads(data)
            url = excelobj.get_excel_data(row, configobj.geturl())
            res = excelobj.get_excel_data(row, configobj.getres())
            method = excelobj.get_excel_data(row, configobj.getmethod())
            if method == "GET":
                testobj = test_request.TestLogin(data["username"],data["pwd"],url)
                resobj = testobj.get()
                self.assertEqual(int(res),json.loads(resobj.text)["code"])

    @unittest.skip(‘noexec‘)
    def test_insert_ok(self):
        row = 5
        configobj = testconfig.TestConfig()
        excelobj = test_excel.testexcel()
        execstatus = excelobj.get_excel_data(row, configobj.getexec())
        if execstatus == "YES":
            cookiesstatus = excelobj.get_excel_data(row, configobj.getcookies())
            if cookiesstatus == "YES":
                cookies = self.get_cookies()
            else:
                cookies = None
            data = excelobj.get_excel_data(row, configobj.getdata())
            data = json.loads(data)
            url = excelobj.get_excel_data(row, configobj.geturl())
            res = excelobj.get_excel_data(row, configobj.getres())
            method = excelobj.get_excel_data(row, configobj.getmethod())
            if method == "POST":
                testobj = test_request.TestAdd(data["username"], data["age"],data["sex"], data["pwd"],cookies,url)
                resobj = testobj.post()
                print(json.loads(resobj.text))
                self.assertEqual(int(res), json.loads(resobj.text)["code"])

    @unittest.skip(‘noexec‘)
    def test_insert_nologin(self):
        row = 6
        configobj = testconfig.TestConfig()
        excelobj = test_excel.testexcel()
        execstatus = excelobj.get_excel_data(row, configobj.getexec())
        if execstatus == "YES":
            cookiesstatus = excelobj.get_excel_data(row, configobj.getcookies())
            if cookiesstatus == "YES":
                cookies = self.get_cookies()
            else:
                cookies = None
            data = excelobj.get_excel_data(row, configobj.getdata())
            data = json.loads(data)
            url = excelobj.get_excel_data(row, configobj.geturl())
            res = excelobj.get_excel_data(row, configobj.getres())
            method = excelobj.get_excel_data(row, configobj.getmethod())
            if method == "POST":
                testobj = test_request.TestAdd(data["username"], data["age"],data["sex"], data["pwd"],cookies,url)
                resobj = testobj.post()
                print(json.loads(resobj.text))
                self.assertEqual(int(res), json.loads(resobj.text)["code"])

    @unittest.skip("noexec")
    def test_insert_user_error(self):
        row = 7
        configobj = testconfig.TestConfig()
        excelobj = test_excel.testexcel()
        execstatus = excelobj.get_excel_data(row, configobj.getexec())
        if execstatus == "YES":
            cookiesstatus = excelobj.get_excel_data(row, configobj.getcookies())
            if cookiesstatus == "YES":
                cookies = self.get_cookies()
            else:
                cookies = None
            data = excelobj.get_excel_data(row, configobj.getdata())
            data = json.loads(data)
            url = excelobj.get_excel_data(row, configobj.geturl())
            res = excelobj.get_excel_data(row, configobj.getres())
            method = excelobj.get_excel_data(row, configobj.getmethod())
            if method == "POST":
                testobj = test_request.TestAdd(data.get("username",None), data.get("age",None), data.get("sex",None), data.get("pwd",None), cookies, url)
                resobj = testobj.post()
                print(json.loads(resobj.text))
                self.assertEqual(int(res), json.loads(resobj.text)["code"])

    @unittest.skip(‘no exec‘)
    def test_insert_pwd_error(self):
        row = 8
        configobj = testconfig.TestConfig()
        excelobj = test_excel.testexcel()
        execstatus = excelobj.get_excel_data(row, configobj.getexec())
        if execstatus == "YES":
            cookiesstatus = excelobj.get_excel_data(row, configobj.getcookies())
            if cookiesstatus == "YES":
                cookies = self.get_cookies()
            else:
                cookies = None
            data = excelobj.get_excel_data(row, configobj.getdata())
            data = json.loads(data)
            url = excelobj.get_excel_data(row, configobj.geturl())
            res = excelobj.get_excel_data(row, configobj.getres())
            method = excelobj.get_excel_data(row, configobj.getmethod())
            if method == "POST":
                testobj = test_request.TestAdd(data.get("username",None), data.get("age",None), data.get("sex",None), data.get("pwd",None), cookies, url)
                resobj = testobj.post()
                print(json.loads(resobj.text))
                self.assertEqual(int(res), json.loads(resobj.text)["code"])

    @unittest.skip("no exec")
    def test_insert_sex_error(self):
        row = 9
        configobj = testconfig.TestConfig()
        excelobj = test_excel.testexcel()
        execstatus = excelobj.get_excel_data(row, configobj.getexec())
        if execstatus == "YES":
            cookiesstatus = excelobj.get_excel_data(row, configobj.getcookies())
            if cookiesstatus == "YES":
                cookies = self.get_cookies()
            else:
                cookies = None
            data = excelobj.get_excel_data(row, configobj.getdata())
            print(data)
            data = json.loads(data)
            print(data)
            url = excelobj.get_excel_data(row, configobj.geturl())
            res = excelobj.get_excel_data(row, configobj.getres())
            method = excelobj.get_excel_data(row, configobj.getmethod())
            if method == "POST":
                testobj = test_request.TestAdd(data.get("username",None), data.get("age",None), data.get("sex",None), data.get("pwd",None), cookies, url)
                resobj = testobj.post()
                print(json.loads(resobj.text))
                self.assertEqual(int(res), json.loads(resobj.text)["code"])

    @unittest.skip(‘no exec‘)
    def test_insert_age_error(self):
        row = 10
        configobj = testconfig.TestConfig()
        excelobj = test_excel.testexcel()
        execstatus = excelobj.get_excel_data(row, configobj.getexec())
        if execstatus == "YES":
            cookiesstatus = excelobj.get_excel_data(row, configobj.getcookies())
            if cookiesstatus == "YES":
                cookies = self.get_cookies()
            else:
                cookies = None
            data = excelobj.get_excel_data(row, configobj.getdata())
            print(data)
            data = json.loads(data)
            print(data)
            url = excelobj.get_excel_data(row, configobj.geturl())
            res = excelobj.get_excel_data(row, configobj.getres())
            method = excelobj.get_excel_data(row, configobj.getmethod())
            if method == "POST":
                testobj = test_request.TestAdd(data.get("username",None), data.get("age",None), data.get("sex",None), data.get("pwd",None), cookies, url)
                resobj = testobj.post()
                print(resobj.text)
                print(json.loads(resobj.text))
                self.assertEqual(int(res), json.loads(resobj.text)["code"])

    @unittest.skip(‘no exec‘)
    def test_insert_user_exist(self):
        row = 11
        configobj = testconfig.TestConfig()
        excelobj = test_excel.testexcel()
        execstatus = excelobj.get_excel_data(row, configobj.getexec())
        if execstatus == "YES":
            cookiesstatus = excelobj.get_excel_data(row, configobj.getcookies())
            if cookiesstatus == "YES":
                cookies = self.get_cookies()
            else:
                cookies = None
            data = excelobj.get_excel_data(row, configobj.getdata())
            print(data)
            data = json.loads(data)
            print(data)
            url = excelobj.get_excel_data(row, configobj.geturl())
            res = excelobj.get_excel_data(row, configobj.getres())
            method = excelobj.get_excel_data(row, configobj.getmethod())
            if method == "POST":
                testobj = test_request.TestAdd(data.get("username", None), data.get("age", None), data.get("sex", None),
                                               data.get("pwd", None), cookies, url)
                resobj = testobj.post()
                print(resobj.text)
                print(json.loads(resobj.text))
                self.assertEqual(int(res), json.loads(resobj.text)["code"])

    def test_get_user(self):
        row = 12
        configobj = testconfig.TestConfig()
        excelobj = test_excel.testexcel()
        execstatus = excelobj.get_excel_data(row, configobj.getexec())
        if execstatus == "YES":
            cookiesstatus = excelobj.get_excel_data(row, configobj.getcookies())
            if cookiesstatus == "YES":
                cookies = self.get_cookies()
            else:
                cookies = None

            url = excelobj.get_excel_data(row, configobj.geturl())
            res = excelobj.get_excel_data(row, configobj.getres())
            method = excelobj.get_excel_data(row, configobj.getmethod())
            if method == "POST":
                testobj = test_request.Testscan(url)
                resobj = testobj.get()
                # print(resobj.text
                print(json.loads(resobj.text))
                self.assertEqual(int(res), json.loads(resobj.text)["code"])

    @unittest.skip(‘no exec‘)
    def test_del_user(self):
        row = 13
        configobj = testconfig.TestConfig()
        excelobj = test_excel.testexcel()
        execstatus = excelobj.get_excel_data(row, configobj.getexec())
        if execstatus == "YES":
            cookiesstatus = excelobj.get_excel_data(row, configobj.getcookies())
            if cookiesstatus == "YES":
                cookies = self.get_cookies()
            else:
                cookies = None
            data = excelobj.get_excel_data(row, configobj.getdata())
            print(data)
            data = json.loads(data)
            print(data)
            url = excelobj.get_excel_data(row, configobj.geturl())
            res = excelobj.get_excel_data(row, configobj.getres())
            method = excelobj.get_excel_data(row, configobj.getmethod())
            if method == "POST":
                testobj = test_request.Testdel(data.get("username", None),cookies, url)
                resobj = testobj.post()
                print(resobj.text)
                print(json.loads(resobj.text))
                self.assertEqual(int(res), json.loads(resobj.text)["code"])

    def test_del_noexistuser(self):
        row = 14
        configobj = testconfig.TestConfig()
        excelobj = test_excel.testexcel()
        execstatus = excelobj.get_excel_data(row, configobj.getexec())
        if execstatus == "YES":
            cookiesstatus = excelobj.get_excel_data(row, configobj.getcookies())
            if cookiesstatus == "YES":
                cookies = self.get_cookies()
            else:
                cookies = None
            data = excelobj.get_excel_data(row, configobj.getdata())
            print(data)
            data = json.loads(data)
            print(data)
            url = excelobj.get_excel_data(row, configobj.geturl())
            res = excelobj.get_excel_data(row, configobj.getres())
            method = excelobj.get_excel_data(row, configobj.getmethod())
            if method == "POST":
                testobj = test_request.Testdel(data.get("username", None),cookies, url)
                resobj = testobj.post()
                print(resobj.text)
                print(json.loads(resobj.text))
                self.assertEqual(int(res), json.loads(resobj.text)["code"])

6、引入unittest的suit,组织案例

import unittest
from unittest import TestLoader

from test3 import test_unittest

if __name__ == ‘__main__‘:
    suite = unittest.TestSuite()
    loader = TestLoader()
    test_cases1 = unittest.TestLoader().loadTestsFromModule(test_unittest)
    # 参数是一个模块,会把这个模块里的所有case加载进来
    suite.addTests(test_cases1)
    runner = unittest.TextTestRunner(verbosity=2)
    runner.run(suite)

四、执行案例

1、启动django

E:\python\unittestForDjango>python manage.py runserver 9090
Performing system checks...

System check identified no issues (0 silenced).
October 19, 2019 - 22:46:42
Django version 1.11.7, using settings ‘unittestForDjango.settings‘
Starting development server at http://127.0.0.1:9090/
Quit the server with CTRL-BREAK

2、执行测试套件

test_del_noexistuser (test3.test_unittest.TestDjango) ... {"username":"test1"}
{‘username‘: ‘test1‘}
ok
test_del_user (test3.test_unittest.TestDjango) ... skipped ‘no exec‘
test_get_user (test3.test_unittest.TestDjango) ... {"code": 201, "error": "test1 is not exists"}
{‘code‘: 201, ‘error‘: ‘test1 is not exists‘}
{‘code‘: 200, ‘userinfo‘: []}
ok
test_insert_age_error (test3.test_unittest.TestDjango) ... skipped ‘no exec‘
test_insert_nologin (test3.test_unittest.TestDjango) ... skipped ‘noexec‘
test_insert_ok (test3.test_unittest.TestDjango) ... skipped ‘noexec‘
test_insert_pwd_error (test3.test_unittest.TestDjango) ... skipped ‘no exec‘
test_insert_sex_error (test3.test_unittest.TestDjango) ... skipped ‘no exec‘
test_insert_user_error (test3.test_unittest.TestDjango) ... skipped ‘noexec‘
test_insert_user_exist (test3.test_unittest.TestDjango) ... skipped ‘no exec‘
test_login_ok (test3.test_unittest.TestDjango) ... skipped ‘noexec‘
test_login_pwd_error (test3.test_unittest.TestDjango) ... skipped ‘noexec‘
test_login_user_error (test3.test_unittest.TestDjango) ... skipped ‘noexec‘
test_user_pwd_error (test3.test_unittest.TestDjango) ... skipped ‘noexec‘

----------------------------------------------------------------------
Ran 14 tests in 1.466s

OK (skipped=12)

原文地址:https://www.cnblogs.com/bainianminguo/p/11706244.html

时间: 2024-10-13 12:07:01

python自动化测试三部曲之request+django实现接口测试的相关文章

python自动化测试三部曲之untitest框架

终于等到十一,有时间写博客了,准备利用十一这几天的假期把这个系列的博客写完 该系列文章本人准备写三篇博客 第一篇:介绍python自动化测试框架unittest 第二篇:介绍django框架+request库实现接口测试 第三篇:介绍利用Jenkins实现持续集成 今天进入第一篇,unittest框架介绍 一.unittest简述 unittest是python语言的单元测试框架,在python的官方文档中,对unittest单元测试框架进行了详细的介绍,感兴趣的读者可以到https://www

Python菜鸟之路:Django 路由补充FBV和CBV

在Python菜鸟之路:Django 路由.模板.Model(ORM)一节中,已经介绍了几种路由的写法及对应关系,那种写法可以称之为FBV: function base view . 今天补充另外一种路由关系的写法:CBV,即:class base view , 也可以看做为面向资源编程的另外一种叫法,类似tornado中的路由写法. 1. 建立路由关系urls.py from app01 import views urlpatterns = [ url(r'^home/', views.Hom

python学习笔记十五 django基础

Python的WEB框架有Django.Tornado.Flask 等多种,Django相较与其他WEB框架其优势为:大而全,框架本身集成了ORM.模型绑定.模板引擎.缓存.Session等诸多功能. 1.创建django程序 通过命令行 django-admin startproject mysite 创建project 一个工程可以包含多个app,app共用一个project的配置文件 cd mysite python manage.py startapp app01 创建app01 pyt

python自动化测试(2)-自动化基本技术原理

python自动化测试(2) 自动化基本技术原理 1   概述 在之前的文章里面提到过:做自动化的首要本领就是要会 透过现象看本质 ,落实到实际的IT工作中就是 透过界面看数据. 掌握上面的这样的本领可不是容易的事情,必须要有扎实的计算机理论基础,才能看到深层次的本质东西. 2   应用软件逻辑结构 数据库应用系统 可能是最典型的网络应用程序了,关于它的软件架构如下: 一般在逻辑上分为4层: 用户界面层 UI 为终端用户提供交互的人机界面 业务逻辑层 BLL 将数据库抽象出来的对象进行拼接成具体

python自动化测试

python自动化测试 欢迎光临 python自动化测试 小站! 小站基于IT行业,重点关注python,软件自动化测试,测试等. 联系方式 飞信 372818219 相关的群:python开发自动化测试群113938272和开发测试群6089740. 小站运行于新浪云平台SAE,基于python的知名流程管理工具Trac.暂时主要使用其博客功能. 未来拟基于Trac迁移和创建一些开源项目,增加使用wiki,任务单,时间线等功能. 目前的开源项目项目:python中文翻译和实例:??http:/

Python的Web应用框架--Django

一:简介 python的web框架有很多,个人查了一下,有Django.Pylons. Tornado.Bottle和Flask等,其中使用人数最多的是Django,而我学习Django也是因为openstack中使用的是django框架. Django是一个开放源代码的Web应用框架,由Python写成,采用了MVC的软件设计模式,即模型M,视图V和控制器C. 二:安装 由于Django2.0以后便不再支持python2.x,所以在安装时一定要注意. 2.1.Python3.x+Django2

Python全栈开发之Django基础

[TOC] No.1 MVC&MTV MVC M全拼为Model,主要封装对数据库层的访问,对数据库中的数据进行增.删.改.查操作 V全拼为View,用于封装结果,生成页面展示的html内容 C全拼为Controller,用于接收请求,处理业务逻辑,与Model和View交互,返回结果 MTV M全拼为Model,与MVC中的M功能相同,负责和数据库交互,进行数据处理 V全拼为View,与MVC中的C功能相同,接收请求,进行业务处理,返回应答 T全拼为Template,与MVC中的V功能相同,负

?《Python自动化测试修炼宝典》线上课程已经成功入驻网易云课堂......

<Python自动化测试修炼宝典>线上课程已经成功入驻网易云课堂...... IT测试老兵利用工作之余,亲自录制的<Python自动化测试修炼宝典>线上课程已经成功入驻网易云课堂,想要提高测试技术的小伙伴可以线上购买课程进行学习. 课程背景 测试人员进阶实战课程.本套课程以作者多年测试实战经验为背景,结合大量测试案例深入浅出讲解目前主流web端.app端自动化测试框架以及使用Python如何从0到1实现接口测试框架的搭建. 课程特色 系统教学+实战案例+开放源码.涵盖Python3

【Python之路Day17】django

Python的WEB框架有Django.Tornado.Flask 等多种,Django相较与其他WEB框架其优势为:大而全,框架本身集成了ORM.模型绑定.模板引擎.缓存.Session等诸多功能. 安装环境: 通过“cmd”打开一个新的命令提示符窗口,直接输入:“django-admin.py”,如果提示:“'django- admin.py' 不是内部或外部命令,也不是可运行的程序或批处理文件,那么说明你还没有django环境,请先下载安装,之后配好环境变量.相关参考:http://blo