python自動(dòng)化測(cè)試三部曲之request+django實(shí)現(xiàn)接口測(cè)試
國(guó)慶期間準(zhǔn)備寫(xiě)三篇博客,介紹和總結(jié)下接口測(cè)試,由于國(guó)慶期間帶娃,沒(méi)有按照計(jì)劃完成,今天才完成第二篇,慚愧慚愧。
這里我第一篇博客的地址:http://www.dbjr.com.cn/article/197004.htm,主要是介紹unittest框架,有興趣的同學(xué)們可以移步去查閱
這里廢話少說(shuō),進(jìn)入正題
我的思路是這樣的
1、先用django實(shí)現(xiàn)登陸、增加、刪除、查看4個(gè)接口
2、在excel定義好測(cè)試案例、然后讀取excel中的案例,然后把案例用unittest框架組裝和封裝
3、啟動(dòng)django,執(zhí)行測(cè)試案例
一、先跑通unittest到django的流程
1、先創(chuàng)建一個(gè)Django的項(xiàng)目

2、創(chuàng)建路由,這里我們使用二級(jí)路由
a、先復(fù)制工程目錄下的urls.py文件到app目錄下

b、修改工程目錄下的urls.py文件,定義一級(jí)路由

c、修改app目錄下的urls.py文件,設(shè)置二級(jí)路由,這里切記務(wù)必要?jiǎng)h除默認(rèn)的admin這條路由

d、定義這條路由指向的視圖的函數(shù)

e、啟動(dòng)django,這里我們使用9090端口啟動(dòng),因?yàn)槲覀兊腏enkins端口用的是8080
E:\python\unittestForDjango>python manage.py runserver 9090
f、這里的是啟動(dòng)成功的樣式,我圈住的告警可以忽略,因?yàn)檫@里Django的admin需要的,我們這里不會(huì)用到django的admin

g、打開(kāi)瀏覽器訪問(wèn)django,我們的一個(gè)簡(jiǎn)單的Django項(xiàng)目已經(jīng)跑通

3、在視圖函數(shù)中定義一個(gè)方法,這個(gè)方法分別處理GET請(qǐng)求和POST請(qǐng)求
a、定義視圖函數(shù)
這里通過(guò)這個(gè)參數(shù)告訴瀏覽器,我們返回的是JSON數(shù)據(jù)
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模塊發(fā)起POST和GET請(qǐng)求
#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):
# 發(fā)送get請(qǐng)求
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):
# 發(fā)送post請(qǐng)求
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框架,測(cè)試案例可以這么寫(xiě)
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、這里有重復(fù)代碼,我們可以利用unittest框架中的classmethod來(lái)解決,因?yàn)閷?shí)例化一個(gè)測(cè)試類可以放在前置條件中
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的中的實(shí)例是可以用引用類變量的
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的中的實(shí)例是可以用引用類變量的
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) # 參數(shù)是一個(gè)模塊,會(huì)把這個(gè)模塊里的所有case加載進(jìn)來(lái) suite.addTests(test_cases1) runner = unittest.TextTestRunner(verbosity=2) runner.run(suite)
二、在django中設(shè)計(jì)接口
這里我們寫(xiě)一個(gè)簡(jiǎn)單的例子,設(shè)計(jì)一個(gè)用戶表,設(shè)計(jì)4個(gè)接口
接口1:登陸
接口2:增加用戶,需要用戶登陸
接口3:刪除用戶,需要用戶登陸
接口4:查詢用戶,不需要用戶登陸
1、先看登陸接口
a、登錄接口對(duì)應(yīng)的url
下面是一級(jí)路由
url(r'^web/', include('unittesstApp1.urls'))
下面是二級(jí)路由
url(r'^login/', views.test_login),
b、登錄接口的視圖函數(shù)
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"] = "用戶名或者密碼錯(cuò)誤"
result = json.dumps(returndict)
return HttpResponse(result,content_type="application/json;charset=utf-8")
這里我們用到了session來(lái)代替cookies
2、增加用戶接口
a、增加用戶對(duì)應(yīng)的url
一級(jí)路由同登陸接口,下面是二級(jí)路由
url(r'^add/', views.test_add),
b、增加用戶接口對(duì)應(yīng)的視圖函數(shù),這里我們做了各種異常處理,且判斷了用戶是否登陸,也就是通過(guò)是否攜帶cookies來(lái)判斷
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": "用戶名或者密碼錯(cuò)誤"}
result = json.dumps(returndict)
return HttpResponse(result, content_type="application/json;charset=utf-8")
3、刪除接口
a、刪除用戶對(duì)應(yīng)的url
一級(jí)路由同登陸接口,這里只看二級(jí)路由
url(r'^del/', views.del_user),
b、刪除接口對(duì)應(yīng)的視圖函數(shù),這里我做了各種異常處理,也做了用戶是否登陸的檢測(cè),也是通過(guò)檢測(cè)cookies來(lái)實(shí)現(xiàn)
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、查看接口對(duì)應(yīng)的url
一級(jí)路由同登陸接口url,下面是二級(jí)路由
url(r'^scan/', views.get_user),
b、查看接口對(duì)應(yīng)的url,這里我們不檢測(cè)用戶是否登陸,直接把查到的數(shù)據(jù)返回給客戶,如果查詢報(bào)錯(cuò),才返回錯(cuò)誤的信息
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、設(shè)計(jì)刪除數(shù)據(jù)庫(kù)中所有的接口,用來(lái)做后置條件
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")
三、案例準(zhǔn)備
1、在excel中寫(xiě)好接口測(cè)試案例

2、定義常量,也就是每列對(duì)應(yīng)的值
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的類,因?yàn)槲乙獜膃xcel中讀取案例
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、定義我們的接口函數(shù)
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):
# 發(fā)送get請(qǐng)求
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):
# 發(fā)送post請(qǐng)求
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):
# 發(fā)送post請(qǐng)求
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):
# 發(fā)送post請(qǐng)求
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、定義測(cè)試案例
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) # 參數(shù)是一個(gè)模塊,會(huì)把這個(gè)模塊里的所有case加載進(jìn)來(lái) suite.addTests(test_cases1) runner = unittest.TextTestRunner(verbosity=2) runner.run(suite)
四、執(zhí)行案例
1、啟動(dòng)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、執(zhí)行測(cè)試套件
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)
到此這篇關(guān)于python自動(dòng)化測(cè)試三部曲之request+django實(shí)現(xiàn)接口測(cè)試的文章就介紹到這了,更多相關(guān)request django 接口測(cè)試內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
pytorch+sklearn實(shí)現(xiàn)數(shù)據(jù)加載的流程
這篇文章主要介紹了pytorch+sklearn實(shí)現(xiàn)數(shù)據(jù)加載,之前在訓(xùn)練網(wǎng)絡(luò)的時(shí)候加載數(shù)據(jù)都是稀里糊涂的放進(jìn)去的,也沒(méi)有理清楚里面的流程,今天整理一下,加深理解,也方便以后查閱,需要的朋友可以參考下2022-11-11
基于python批量處理dat文件及科學(xué)計(jì)算方法詳解
今天小編就為大家分享一篇基于python批量處理dat文件及科學(xué)計(jì)算方法詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-05-05
python for循環(huán)內(nèi)輸出和外輸出方式
這篇文章主要介紹了python for循環(huán)內(nèi)輸出和外輸出方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-03-03
python字典中items()函數(shù)用法實(shí)例
Python字典items()函數(shù)作用以列表返回可遍歷的(鍵, 值)元組數(shù)組,下面這篇文章主要給大家介紹了關(guān)于python字典中items()函數(shù)用法的相關(guān)資料,需要的朋友可以參考下2022-11-11
python3+opencv3識(shí)別圖片中的物體并截取的方法
今天小編就為大家分享一篇python3+opencv3識(shí)別圖片中的物體并截取的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-12-12
Python上下文管理器類和上下文管理器裝飾器contextmanager用法實(shí)例分析
這篇文章主要介紹了Python上下文管理器類和上下文管理器裝飾器contextmanager用法,結(jié)合實(shí)例形式分析了上下文管理器類定義、使用、sqlalchemy實(shí)現(xiàn)數(shù)據(jù)庫(kù)的自動(dòng)提交和回滾相關(guān)操作技巧,需要的朋友可以參考下2019-11-11
使用Python實(shí)現(xiàn)微信拍一拍功能的思路代碼
這篇文章主要介紹了使用Python實(shí)現(xiàn)微信“拍一拍”的思路代碼,,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07

