Python+unittest+xlrd+request Build API Test Framework

Source: Internet
Author: User

Implementation features

1. You can write a use case in a table

2. Automatic execution of test cases in tables

3. Deep assertion of the response results, which can locate the different values and positions of the expected results and the test Results.

4. Form a test report in HTML format

source code can be downloaded in githube : https://github.com/wcnszbd/Mytest

Attach First:

then the code: structure Diagram

1 #!/usr/bin/env python2 #-*-coding:utf-8-*-3 #@Time: 2017-07-28 18:074 Importxlrd5 ImportRequests6 classApitool:7 8     #use case methods in the Fetch table9     defxlsee (self, xlsfile):TenSheetlist = []#used to save all the data in the table oneRqapi = Xlrd.open_workbook (xlsfile)#get File Object aSheet_name = Rqapi.sheet_names () [0]#gets the first sheet name -Sheet = Rqapi.sheet_by_name (sheet_name)#Gets the first sheet object -Nrow = Sheet.nrows#get total number of rows the          forIinchRange (1, nrow): - sheetlist.append (sheet.row_values (I)) -         returnsheetlist -  +     #Request Method -     defrequest (self, rqtype, rqurl, paramete, headers): +         ifRqtype = ="Get": aApiresult = Requests.get (url=rqurl, params=paramete, headers=headers)#Send Request at             returnApiresult -         ifRqtype = ="Post": -Apiresult = requests.post (url=rqurl, data=paramete, headers=Headers) -             returnApiresult -         Else: -             Print("Request parameter error, request type only support get+post, request address support string, parameter support Dict") in  -  to     #depth assertion of the returned JSON value +  -     defCompare_json_data (self,a, B, L = [], XPath ='.'): the         ifIsinstance (A, List) andisinstance (B, list): *              forIinchRange (len (A)): $                 Try:Panax NotoginsengSelf.compare_json_data (a[i], b[i], L, XPath +'[%s]'%Str (I)) -                 except: theL.append ('▇▇▇a key%s[%s] not found in b \ n'%(xpath, I)) +         ifIsinstance (A, Dict) andisinstance (B, dict): a              forIinchA: the                 Try: + b[i] -                 except: $L.append ('key%s/%s in ▇▇▇a not found in b \ n'%(xpath, I)) $                     Continue -                 if  not(isinstance (a.get (i), (list, dict))orisinstance (b.get (i), (list, dict)): -                     ifType (a.get (i))! =type (b.get (i)): theL.append ('absolute path of ▇▇▇ type with different parameters in [A]:%s/%s??? A is%s, and B is%s \ n'%(xpath, i, type (a.get (i)), type (b.get (i) ))) -                     elifA.get (i)! =B.get (i):WuyiL.append ('▇▇▇ Absolute path for content with only different parameters in [A]:%s/%s??? A is%s, and B is%s \ n'%(xpath, i, a.get (i), b.get (i))) the                     Continue -Self.compare_json_data (a.get (i), b.get (i), L, XPath +'/'+Str (I)) wu             return -         ifType (A)! =type (B): aboutL.append ('absolute path of ▇▇▇ type with different parameters in [A]:%s??? A is%s, and B is%s \ n'%(xpath, type (A), type (B))) $         elifA! = B andType (A) is  notlist: -L.append ('▇▇▇ Absolute path for only content with different parameters in [A]:%s??? A is%s, and B is%s \ n'%(xpath, A, B)) -         returnL -  a     defAssert (self,a,b): +C = [] the self.compare_json_data (A, B, C) -         assertLen (C) = = 0,"\ n"+"". Join (C)

1 #!/usr/bin/env python2 #-*-coding:utf-8-*-3 #@Time: 2017-07-28 18:074 ImportUnitTest5 ImportHtmltestrunner6 Import time7 ImportTool8 ImportJSON9 Ten classTest (unittest. TestCase): oneheixiongjing = 666 a     #Get test Data -  - #closure functions are used to generate use cases the  - defDemo (i): -     defcase (self): -Caseurl = i[2]+i[3] +RequestType = i[4] -Paramete = i[5] +Result = Json.loads (i[6]) aApiresult = apitest.request (requesttype, caseurl, paramete,"') atCode =Apiresult.status_code -         assertCode = = 200,'▇▇▇ Request failed! '+'  '+'code:'+str (code) +'  '+'url='+Caseurl -Pam =json.loads (apiresult.text) - Apitest. Assert (pam, Result) -  -SetAttr (case,'__doc__', str (i[1])) in     return case -  to #generate use cases based on the number of use case loops + defTestall (num): -      forIinchnum: theSetAttr (Test,'Test_'+str (int (i[0])), demo (i) ) *  $ Panax Notoginseng if __name__=="__main__": -Apitest =Tool. Apitool () theXlsfile = R"D:\myapi_test2\apicase.xls"  #file path +Sheetlist1 =Apitest.xlsee (xlsfile) a Testall (sheetlist1) theSuit =Unittest.makesuite (Test) +now = Time.strftime ("%y-%m-%d%h_%m_%s", Time.localtime (time.time ())) -filename ="d:\\myapi_test2\\report\\"+now+'result.html' #defines a report storage path that supports relative paths.  $fp = open (filename,'WB') $Runner = Htmltestrunner.htmltestrunner (stream=fp, title='Automated test reports', description='XX Platform V1.0') - Runner.run (suit) -     #Unittest.main ()

Period Thanks @ Big Bro @ Three seniors @ Rice Brother @ brother's Guide

I qq:915069792

Why choose?

Some people like to create the world, they do programmers

Some people like to save the world, they do Testers.

Python+unittest+xlrd+request Build API Test Framework

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.