Snake's Home

python接口测试

当时做的一个项目,开始是用postman,手工改参数来测试接口请求。
后面改进了一下,把请求和参数,以及期望结果写在了一个Excel里面,然后生成PDF报告。

APItest.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
#encoding:utf-8  

import ConfigParser
import os
import xlrd
import re
import httplib
import urllib
from urlparse import urlparse
import json
import time
import unittest
import pdf

currentdir=os.path.split(os.path.realpath(__file__))[0]
class test_class():
def getexcel(self):
casefile=currentdir + '/case.xls'
if ((os.path.exists(casefile))==False):
print "当前路径下没有case.xls,请检查!"
data=xlrd.open_workbook(casefile)
table = data.sheet_by_name('login')
nrows = table.nrows #行数
ncols = table.ncols #列数
#colnames = table.row_values(1) #某一行数据
for rownum in range(1,nrows):
for col in range (3, ncols):
value=table.cell(rownum,col).value
if (col==3):
method=value
if (col==4):
url=value
return table,nrows,ncols

def getexceldetail(self,table,row,ncols):
#rownum = table.row_values(row) #某一行数据

for col in range (0, ncols):
value=table.cell(row,col).value
if (col==0):
caseid=value
print caseid
if (col==3):
method=value
print method
if (col==4):
url=value
return method,url,caseid

def httpget(self,url):
httpClient = None
conn = urlparse(url)
url=url.encode('utf-8')
try:
httpClient = httplib.HTTPConnection(conn.netloc, timeout=10)
httpClient.request('GET', url)

# response是HTTPResponse对象
response = httpClient.getresponse()
print response
d0=response.read()
d0=d0.decode('unicode_escape')
except Exception, e:
print e
finally:
if httpClient:
httpClient.close()
return response.status,d0

def httppost(self,url):
httpClient = None
conn = urlparse(url)
url=url.encode('utf-8')
try:
header = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}

httpClient = httplib.HTTPConnection(conn.netloc, timeout=30)
httpClient.request("POST", url)
response1 = httpClient.getresponse()
d1=response1.read()
d1=d1.decode('unicode_escape')
except Exception, e:
print e
finally:
if httpClient:
httpClient.close()
return response1.status,d1

def compare(self,status,actualljson):
if (status==200):
print "request pass"
if ( actualljson['response'] =='100'):
print "pass"
result="pass"
else:
print "fail"
result="fail"
else:
print "request fail"
result="fail"
return result

def transferlist2dict(self,data):
#index=data.find(":")
text=data.replace('=',':')
strList=text.split(',')
strDict={}
for strItem in strList:
strCh=strItem.split(':')
strDict[strCh[0]]=strCh[1]
return strDict

def testapi(self):
table,number,ncolor=self.getexcel()
pcount=0
fcount=0
failidlist=[]
for n in range(1,number):
Start=time.time()
method,url,caseid=self.getexceldetail(table,n,ncolor)
print Start
if (method=="GET"):
status,readvalue=self.httpget(url)
#readvalue=json.loads(readvalue)
#self.compare(status,readvalue)
if (method=="POST"):
status,readvalue=self.httppost(url)
readvalue=json.loads(readvalue)
result=self.compare(status,readvalue)
if (result=="pass"):
pcount=pcount+1
else:
fcount=fcount+1
print caseid
failidlist.append(caseid)
End=time.time()
diff= End-Start
print "The time is " +str(diff)
return pcount,fcount,failidlist

now1 = time.strftime('%m-%d-%H_%M_%S', time.localtime(time.time()))
t=test_class()
pcount,fcount,failidlist=t.testapi()
datas=[(0,fcount),(0,pcount)]
now2 = time.strftime('%m-%d-%H_%M_%S', time.localtime(time.time()))
ytype=[now1,now2]
des="API test result"
des1="Pass:%s,Fail:%s,Failed ID: %s"%(pcount,fcount,failidlist)
print des1
f=pdf.pdfreport()
f.createpdf(datas,ytype,des,des1)

pdy.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from reportlab.graphics.shapes import Drawing  
from reportlab.graphics.charts.barcharts import VerticalBarChart
from urllib import urlopen
from reportlab.graphics.shapes import *
from reportlab.graphics.charts.lineplots import LinePlot
from reportlab.graphics.charts.textlabels import Label
from reportlab.graphics import renderPDF
class pdfreport():
def createpdf(self,datas,ytype,des,des1):
drawing = Drawing(400, 200)
#data = [(13, 5, 20),(14, 6, 21)]
data=datas
bc = VerticalBarChart()
bc.x = 50
bc.y = 50
bc.height = 125
bc.width = 300
bc.data = data
bc.strokeColor = colors.black
bc.valueAxis.valueMin = 0
bc.valueAxis.valueMax = 50
bc.valueAxis.valueStep = 10
bc.categoryAxis.labels.boxAnchor ='ne'
bc.categoryAxis.labels.dx = 8
bc.categoryAxis.labels.dy = -2
bc.categoryAxis.labels.angle = 30
#bc.categoryAxis.categoryNames = ['Jan-99','Feb-99','Mar-99']
bc.categoryAxis.categoryNames =ytype
drawing.add(bc)

#drawing.add(String(250,150,"ss", fontSize=14,fillColor=colors.red))
drawing.add(String(250,150,des, fontSize=14,fillColor=colors.black))
drawing.add(String(50,140,des1, fontSize=14,fillColor=colors.red))
renderPDF.drawToFile(drawing,'APIReport.pdf','API')
#renderPDF.drawToFile(drawing,'APIReport.pdf','API')

本文发表在: Testerhome