HTTP Interface Automation Test framework implementation

Source: Internet
Author: User
Tags python script


I. Description of TEST requirements

A series of HTTP interface functional tests on the service backend.

Input: Constructs different parameter input values according to the interface description

Output: XML file

Eg:http://www.***.com/shoes_product/test/nike_list.jsp?listid=1

Second, the realization method

1. Use Python script to drive test

2, the Use of Excel table management test data, including use case management, test data entry, test results display and so on, this needs to encapsulate an Excel class.

3, call the HTTP interface using the Python encapsulated API can be

4, the test needs the HTTP assembly character to turn processing can

5, set 2 checkpoints, the return value field in the XML file (obtained by parsing XML); XML file correctness (file comparison)

6, the first implementation of the test in a semi-automatic way, that is, manually check the output of the XML file is correct, once the correct storage of the XML file, for subsequent regression testing the expected results, if the error is found manually corrected to the expected file. (Note that not every test is a manual check of the file, only the first test is checked)

Third, Excel table style

Iv. Implementation Code

1. Test framework Code

View Plaincopy to Clipboardprint? 
 #**************************************************************** # testframe.py # author:anndy # version:1.1.1 # Description: Automated test Platform #**************************************************************** import Os,sys, Urllib, HTTPL IB, Profile, DateTime, time from xml2dict import xml2dict import win32com.client from win32com.client import DISPATC H import xml.etree.ElementTree as et #import mysqldb #Excel表格中测试结果底色 ok_color=0xffffff ng_color=0xff #NT_COLO R=0xffff nt_color=0xc0c0c0 #Excel表格中测试结果汇总显示位置 testtime=[1, [] testresult=[2,] #Excel模版设置 #self. Titleind Ex=3 #Excel中测试用例标题行索引 #self. Casebegin =4 #Excel中测试用例开始行索引 #self. Argbegin =3 #Excel中参数开始列索引 #self. Argcount =8 #Excel中 Number of supported parameters Class Create_excel:def __init__ (self, sFile, dtitleindex=3, dcasebegin=4, Dargbegin=3, dargcount=8): self.x LAPP = Win32com.client.Dispatch (' ET. Application ') #MS: Excel wps:et try:self.book = Self.xlApp.Workbooks.OpeN (sFile) except:print_error_info () print "Open file failed" exit () Self.file=sfile Self.titleindex=dtitleindex SELF.C Asebegin=dcasebegin self.argbegin=dargbegin Self.argcount=dargcount self.allresult=[] Self.retCol=self.argbegin+s Elf.argcount self.xmlcol=self.retcol+1 self.resultcol=self.xmlcol+1 def close (self): #self. Book.close (SaveChanges =0) Self.book.Save () Self.book.Close () #self. xlApp.Quit () del Self.xlapp def read_data (self, isheet, IRow, Icol ): Try:sht = Self.book.Worksheets (isheet) svalue=str (sht. Cells (IRow, Icol). Value) Except:self.close () print (' Read data failed ') exit () #去除 '. 0 ' if svalue[-2:]== '. 0 ': svalue = svalue[0:-2] ret  
 Urn svalue def write_data (self, isheet, IRow, Icol, SData, color=ok_color): Try:sht = Self.book.Worksheets (Isheet) Sht. Cells (IRow, Icol). Value = Sdata.decode ("Utf-8") sht. Cells (IRow, Icol). Interior.color=color Self.book.Save () except:self.close () print (' Write data failed ') exit () #获取用例个数 deF Get_ncase (Self, isheet): Try:return self.get_nrows (Isheet)-self.casebegin+1 except:self.close () print (' Get CAs E number failed ') exit () def get_nrows (self, isheet): Try:sht = Self.book.Worksheets (isheet) return sht.  UsedRange.Rows.Count except:self.close () print (' Get nrows failed ') exit ()
 def get_ncols (self, isheet): Try:sht = Self.book.Worksheets (isheet) return sht. UsedRange.Columns.Count except:self.close () print (' Get Ncols failed ') exit () def del_testrecord (self, suiteid): Try : #为提升性能特别从For循环提取出来 nrows=self.get_nrows (Suiteid) +1 ncols=self.get_ncols (Suiteid) +1 BEGINCOL=SELF.ARGBEGIN+SELF.A Rgcount #提升性能 sht = self.book.Worksheets (Suiteid) for row in range (Self.casebegin, nrows): for col in range (Begi Ncol, Ncols): Str=self.read_data (Suiteid, Row, col) #清除实际结果 [] startpos = Str.find (' [') if Startpos>0:str = S Tr[0:startpos].strip () Self.write_data (Suiteid, Row, col, str, ok_color) Else: #提升性能 sht. Cells (Row, col). Interior.Color = Ok_color #清除TestResul列中的测试结果, set to NT Self.write_data (Suiteid, Row, self.argbegin+self.argcount+1, ', Ok_color) Self.write_data (Suiteid, Row, Self.resultcol, ' NT ', Nt_color) except:self.close () print (' Purge data failed ') Exi T () #执行调用 def httpinvoke (ipport, URL): conn = Httplib. HttpconNection (Ipport) conn.request ("GET", url) RSPs = conn.getresponse () data = Rsps.read () conn.close () return data #获取用例基本信息 [Interface,argcount,[argnamelist]] def get_caseinfo (Data, Suiteid): caseinfolist=[] Sinterface=data.read_ Data (Suiteid, 1, 2) argcount=int (Data.read_data (Suiteid, 2, 2)) #获取参数名存入ArgNameList argnamelist=[] for I in range (0, Argcount): Argnamelist.append (Data.read_data (Suiteid, Data.titleindex, Data.argbegin+i)) Caseinfolist.append ( Sinterface) caseinfolist.append (argcount) caseinfolist.append (argnamelist) return caseinfolist #获取输入 def GET_INP UT (Data, Suiteid, Caseid, caseinfolist): Sarge= "#参数组合 for J in range (0, caseinfolist[1]): If Data.read_data (Suit EID, Data.casebegin+caseid, data.argbegin+j)! = "None": sarge=sarge+caseinfolist[2][j]+ ' = ' +data.read_data (SuiteID, Data.casebegin+caseid, Data.argbegin+j) + ' & ' #去掉结尾的 & characters if sarge[-1:]== ' & ': SArge = sarge[0:-1] sinput= Caseinfolist[0]+sarge #组合全部参数 REturn SInput 1. #结果判断 2.def Assert_result (Sreal, Sexpect): 3.sreal=str (sreal) 4.sexpect=str (sexpect) 5.if Sreal==sexpect:6.retu
 RN ' OK ' 7.else:8.return ' NG '
 #将测试结果写入文件 def write_result (Data, Suiteid, Caseid, Resultcol, *result): If Len (result) >1:ret= ' OK ' for I in RA Nge (0, Len (result)): If result[i]== ' ng ': ret= ' ng ' break if ret== ' ng ': Data.write_data (Suiteid, Data.casebegin+ca SeId, Resultcol,ret, Ng_color) else:Data.write_data (Suiteid, Data.casebegin+caseid, Resultcol,ret, Ok_color) data.a Llresult.append (ret) else:if result[0]== ' NG ': Data.write_data (Suiteid, Data.casebegin+caseid, Resultcol,result[0],  Ng_color) elif result[0]== ' OK ': Data.write_data (Suiteid, Data.casebegin+caseid, resultcol,result[0], OK_COLOR) Else: 

 #NT Data.write_data (Suiteid, Data.casebegin+caseid, resultcol,result[0], Nt_color) Data.allresult.append (result[0]) #将当前结果立即打印 print ' case ' +str (caseid+1) + ': ', data.allresult[-1] #打印测试结果 def statisticresult (excelobj): Allresult List=excelobj.allresult count=[0, 0, 0] for I in range (0, Len (allresultlist)): #print ' case ' +str (i+1) + ': ', Allresult List[i] Count=countflag(Allresultlist[i],count[0], count[1], count[2]) print ' statistic result as follow: ' print ' OK: ', count[0] print ' NG: ', count[1] print ' NT: ', count[2] #解析XmlString返回Dict def get_xmlstring_dict (xml_string): xml = Xml2dict () retur n xml.fromstring (xml_string) #解析XmlFile返回Dict def get_xmlfile_dict (xml_file): xml = Xml2dict () return Xml.parse (x Ml_file) #去除历史数据expect [Real] def delcomment (Excelobj, Suiteid, IRow, Icol, str): startpos = Str.find (' [') if star Tpos>0:str = Str[0:startpos].strip () excelobj.write_data (Suiteid, IRow, Icol, str, ok_color) return str #检查每个 Item (unstructured) def check_item (Excelobj, Suiteid, caseid,real_dict, Checklist, Begincol): ret= ' OK ' for Checkid in range ( 0, Len (checklist)): real=real_dict[checklist[checkid]][' value '] expect=excelobj.read_data (Suiteid, Excelobj.casebegin+caseid, Begincol+checkid) #如果检查不一致测将实际结果写入expect字段, format: expect[real] #将return NG result=assert_res Ult (real, expect) if result== ' NG ': writestr=expect+ ' [' +real+ '] ' Excelobj.write_data (Suiteid, Excelobj.casebegin+caseid, Begincol+checkid, Writestr, NG_  COLOR) ret= ' NG ' return ret #检查结构体类型 def check_struct_item (Excelobj, Suiteid, Caseid,real_struct_dict, Structlist, Structbegin, Structcount): ret= ' OK ' if structcount>1: #传入的是List for Structid in range (0, structcount): STRUCTD Ict=real_struct_dict[structid] Temp=check_item (excelobj, Suiteid, Caseid,structdict, Structlist, structbegin+ Structid*len (structlist)) if temp== ' ng ': ret= ' ng ' else: #传入的是Dict temp=check_item (Excelobj, Suiteid, Caseid,real_ 
 Struct_dict, Structlist, structbegin) if temp== ' ng ': ret= ' ng ' return ret #获取异常函数及行号 def print_error_info (): 
 "" "Return the frame object for the caller ' s stack frame." " Try:raise Exception except:f = Sys.exc_info () [2].tb_frame.f_back print (F.f_code.co_name, F.f_lineno) #测试结果计数 def countflag (Flag,ok, Ng, nt): calculation = {' OK ': lambda:[ok+1, Ng, nt], ' ng ': laMbda:[ok, Ng+1, NT], ' NT ': Lambda:[ok, Ng, Nt+1]} return Calculation[flag] () 

2. Project Test Code

View Plaincopy to Clipboardprint? #-*-Coding:utf-8-*-#**************************************************************** # xxx_server_case.py # Aut Hor:anndy # version:1.0 # Description: Content Services system test code #************************************************************** * * FROM testframe Import * from common_lib import * httpstring= ' http://xxx.com/xxx_product/test/' expectxmldir=o S.GETCWD () + '/testdir/expect/' realxmldir=os.getcwd () + '/testdir/real/' def run (interface_name, Suiteid): print ' "' +i nterface_name+ ' ' + ' Test begin,please waiting ... ' global expectxmldir, Realxmldir #根据接口名分别创建预期结果目录和实际结果目录 expectd Ir=expectxmldir+interface_name realdir=realxmldir+interface_name if os.path.exists (expectdir) = = 0:os.makedirs (expe Ctdir) if os.path.exists (realdir) = = 0:os.makedirs (realdir) Excelobj.del_testrecord (Suiteid) #清除历史测试数据 Casecount =excelobj.get_ncase (Suiteid) #获取case个数 caseinfolist=get_caseinfo (Excelobj, Suiteid) #获取Case基本信息 #遍历执行case
 For Caseid in range (0, casecount): #检查是否执行该Case if Excelobj.read_data (Suiteid,excelobj.casebegin+caseid, 2) = = ' N ': Write_result (Excelobj, Suiteid, Caseid, Excelobj.resultcol, ' NT ') continue #当前Case结束, proceed to the next case #获取测试数据 Sinput=htt 
 Pstring+get_input (Excelobj, Suiteid, Caseid, caseinfolist) Xmlstring=httpinvoke (Com_ipport, sInput) #执行调用 #获取返回码并比较 Result_code=et.fromstring (xmlstring). Find ("Result_code"). Text Ret1=check_result (excelobj, Suiteid, Caseid,result_ 

 Code, EXCELOBJ.RETCOL) #保存预期结果文件 expectpath=expectdir+ '/' +str (caseid+1) + '. Xml ' #saveXmlfile (Expectpath, xmlstring) #保存实际结果文件 realpath=realdir+ '/' +str (caseid+1) + '. Xml ' Savexmlfile (Realpath, xmlstring) #比较预期结果和实际结果 ret2= Check_ XMLFile (Excelobj, Suiteid, Caseid,expectpath, Realpath) #写测试结果 Write_result (Excelobj, Suiteid, Caseid, Excelobj.resul Tcol, Ret1, Ret2) print ' "' +interface_name+ '" ' + ' Test end! '

3. Test entrance

View Plaincopy to Clipboardprint?
 #-*-Coding:utf-8-*- 
 #**************************************************************** 
 # main.py 
 # Author:anndy 
 # version:1.0  
 # Description: Test assembly, use case execution entry 
#********************************************** From 

 testframe import * from 
 xxx_server_case import * 
 import xxx_server_case 

 # Product System interface Test 
 #设置测试环境 
 xxx_server_case.excelobj=create_excel (OS.GETCWD () + ' \testdir\xxx_testcase.xls ') 
 xxx_server_case.com_ipport=xxx.com ' 

 #Add testsuite begin 
 Run ("Xxx_book_list", 4) 
 #Add Other Suite from here 
 #Add Testsuite end 

 Statisticresult (xxx_server_case.excelobj) 
 Xxx_server_ Case.excelobj.close ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.