PYTHON+REQUESTS+EXCEL+UNITTEST+DDT interface automates data-driven and generates HTML reports

Source: Internet
Author: User
Tags throw exception

Objective

1. Environment Readiness:

    • python3.6
    • Requests
    • Xlrd
    • Openpyxl
    • Htmltestrunner_api

2. Currently implemented functions:

    • Encapsulating requests Request method
    • Filling out interface request parameters in Excel
    • After you finish running, regenerate an Excel report, and the results are written to excel
    • Execution with UNITTEST+DDT data-driven mode
    • Htmltestrunner generating a visual HTML report
    • For a single interface request that is not associated can be executed in batch, you need to log in to write to the session in SetupClass to keep cookies
    • Token-associated cannot be implemented
    • Logging log file is temporarily not joined

3. Currently known defects:

    • Parameter Association cannot be implemented: The result of the last request is the parameter of the next request, such as token
    • Interface request parameter name is duplicated, currently not processed, such as key1=value1&key1=value2, two keys are the same, this need to be stored in tuples, currently not judged
    • The resulting Excel style is not processed, and later slowly optimizes the style
    • Novice Python may encounter module import error problem
Project structure

Excel test Data

XLRD reading Excel data

1. First read the test data from Excel, return to the dictionary format

# coding:utf-8# Shanghai-Yo # QQ Group: 226296743import Xlrdclass Excelutil (): Def __init__ (self, Excelpath, sheetname= "Sheet1"):         Self.data = Xlrd.open_workbook (excelpath) self.table = Self.data.sheet_by_name (sheetname) # Gets the first row as the key value Self.keys = self.table.row_values (0) # Gets the total number of rows Self.rownum = self.table.nrows # Gets the overall number of columns SE Lf.colnum = Self.table.ncols def dict_data (self): if Self.rownum <= 1:print ("Total number of rows less than 1") Else                : R = [] j = 1 for I in List (range (self.rownum-1)): s = {}  # from the second row take the corresponding values value s[' rowNum '] = i+2 values = self.table.row_values (j) for X in             List (range (self.colnum)): s[self.keys[x]] = Values[x] R.append (s) j + = 1 return rif __name__ = = "__main__": filepath = "debug_api.xlsx" sheetname = "Sheet1" data = Excelutil (    filepath, SheetName)Print (Data.dict_data ()) 
Encapsulating Request Method

1. Use the data read from Excel as the request parameter, encapsulate the requests request method, pass in the request parameter, and return the result

2. In order to not pollute the test data, the report will be tested when the Excel copy should be the new Excel

3. Write the data in the new Excel with the results returned by the test

# coding:utf-8import Jsonimport requestsfrom excelddtdriver.common.readexcel Import Excelutilfrom Excelddtdriver.common.writeexcel import Copy_excel, write_excel# Shanghai-Yo # QQ Group: 226296743def send_requests (S, testdata): ' ' Package requests Request ' method = Testdata[' method '] url = testdata["url"] # the params parameter after the URL try:params = eval        (testdata["params"]) Except:params = None # request Header Headers Try:headers = eval (testdata["headers"])  Print ("Request header:%s"% headers) except:headers = None # POST request body type = testdata["type"] Test_nub = testdata[' id '] print ("******* executing case:-----%s----**********"% test_nub) print ("Request method:%s, request url:%s"% (method, U        RL)) Print ("Request params:%s"% params) # POST request body Content Try:bodydata = eval (testdata["Body"]) except: Bodydata = {} # to determine whether to transmit data or json if type = = "Data": BODY = bodydata elif Type = = "JSON": BODY = JSO N.dumps (bodydata) else:body = Bodydata    If method = = "POST": Print ("POST request body type:%s, body content:%s"% (type, body)) Verify = False res = {} # accepts return data                      Try:r = S.request (Method=method, Url=url, Params=params, Headers=headers, Data=body, verify=verify) p        Rint ("page return information:%s"% R.content.decode ("Utf-8")) res[' id '] = testdata[' id '] res[' rowNum '] = testdata[' RowNum '] res["statuscode"] = str (r.status_code) # Status code turns to str res["text"] = R.content.decode ("Utf-8") res["times "] = str (r.elapsed.total_seconds ()) # Interface Request Time goto STR if res[" statuscode "]! =" $ ": res[" error "] = res[" Te            XT "] else:res[" error "] =" "res[" msg "] =" "If testdata[" Checkpoint "] in res[" text "]:            res["Result" = "Pass" Print ("Use case test Result:%s---->%s"% (TEST_NUB, res["result"]) Else: res["result"] = "faiL "return res except Exception as msg:res[" msg "] = str (msg) return resdef wirte_result (result, fi    Lename= "Result.xlsx"): # Number of rows returning results row_nub row_nub = result[' RowNum '] # write StatusCode wt = WRITE_EXCEL (filename)            Wt.write (ROW_NUB, 8, result[' statuscode ') # Write return status code statuscode, 8th column wt.write (ROW_NUB, 9, result[' Times ')           # time consuming Wt.write (ROW_NUB, result[' error ') # Return information when status code is not 200 wt.write (ROW_NUB, + result[' result ') # test results Pass or fail Wt.write (ROW_NUB, result[' msg ') # throw exception if __name__ = = "__main__": data = E Xcelutil ("Debug_api.xlsx"). Dict_data () print (data[0]) s = requests.session () res = send_requests (s, data[0]) c Opy_excel ("Debug_api.xlsx", "Result.xlsx") Wirte_result (res, filename= "result.xlsx")
Test Case UNITTEST+DDT

1. Test cases are built using the UnitTest framework and are used in batch execution using DDT data-driven patterns

# coding:utf-8import Unittestimport ddtimport osimport requestsfrom excelddtdriver.common Import Base_apifrom Excelddtdriver.common Import readexcelfrom Excelddtdriver.common import writeexcel# Shanghai-Yo # QQ Group: 226296743# Get Demo_ Api.xlsx Path Curpath = Os.path.dirname (Os.path.realpath (__file__)) testxlsx = Os.path.join (Curpath, "demo_api.xlsx") # Copy the demo_api.xlsx file to the report under Report_path = Os.path.join (Os.path.dirname (Curpath), "Report") Reportxlsx = Os.path.join ( Report_path, "result.xlsx") TestData = Readexcel. Excelutil (TESTXLSX). Dict_data () @ddt. Ddtclass Test_api (unittest. TestCase): @classmethod def setupclass (CLS): CLS.S = Requests.session () # If you have a login, you'll be logged in here first writ Eexcel.copy_excel (Testxlsx, reportxlsx) # copy xlsx @ddt. Data (*testdata) def test_api (self, Data): # First copy Excel data to Report res = base_api.send_requests (SELF.S, data) Base_api.wirte_result (res, filename=reportxlsx) # Check Checkpoint checkpoint check = data["Checkpoint"] Print ("Checkpoint->:%s"%check) # returns the result Res_text = res[" text "] Print (" Return actual result->:%s "%res_text) # Assertion Self.asser Ttrue (check in res_text) if __name__ = = "__main__": Unittest.main ()
Generate reports

1. Use Htmltestrunner to generate HTML report, I changed the name here, changed to htmltestrunner_api.py
This file is common to selenium reports, and GitHub is available for download Https://github.com/yoyoketang/selenium_report/tree/master/selenium_report

# coding=utf-8import Unittestimport timefrom excelddtdriver.common import htmltestrunner_apiimport os# Shanghai-Yo # QQ Group: 226296743curpath = Os.path.dirname (Os.path.realpath (__file__)) Report_path = Os.path.join (Curpath, "report") if Not os.path.exists (Report_path): Os.mkdir (report_path) Case_path = Os.path.join (Curpath, "case") def add_case (Casepath =case_path, rule= "test*.py"): "Load all test Cases '" # to define Discover method Parameters Discover = Unittest.defaultTestLoader.discover (ca Sepath, Pattern=rule,) return discoverdef run_case (all_case, Reportpat H=report_path): "Executes all the use cases and writes the results to the test report ' Htmlreport = reportpath+r" \result.html "Print (" test report generated address:%s "% Htmlreport ) fp = open (Htmlreport, "WB") Runner = Htmltestrunner_api.                                               Htmltestrunner (STREAM=FP, verbosity=2, title= "test Report", description= "use Case execution") # Call Add_case functionreturn value Runner.run (all_case) fp.close () if __name__ = = "__main__": Cases = Add_case () run_case (cases) 

2. Generated Excel Report

3. Generated HTML reports

---------------------------------Python interface automation has been written-------------------------
The small partner who bought the book can download it to the source in the last article of the book.

Book Purchase address https://yuedu.baidu.com/ebook/585ab168302b3169a45177232f60ddccda38e695

PYTHON+REQUESTS+EXCEL+UNITTEST+DDT interface automates data-driven and generates HTML reports

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.