Python enables simple HTTP interface automation

Source: Internet
Author: User
Tags python script

Today to share a simple Python script, using Python for the HTTP interface of automated testing, the script is simple, the logic is: Read the Excel written test cases, and then based on the content of the use case in Excel call, Determine whether the return value in the expected result is consistent with the value in the return message, and if not, submit the bug to the bug management system based on the use case title, and the bug management system used here is bugfree. The final statistical test results: How many use cases are executed in total, how many use cases are passed, how many use cases are failed, the message header is added to the current time, and the test results are sent to the specified mailbox.

Implementation steps:

1, read Excel, save the contents of the test case, here you need to define a read Excel function Readexcel ();

2, according to the request URL and parameters in Excel stitching request message, call the interface, and save the return message, here need to define a request to convert the data into a dictionary function param_to_dic ();

3, read the return message, and the expected result contrast, inconsistent to write a bug in the Bugfree database, and write the request message, return message and test results to the test case in Excel, here need to define a comparison of the expected results and return the result of the function contrastres (), A function writebug () that submits a bug to Bugfree, a function copy_excel () that writes the test result to Excel, and a function interfacetest () that defines an interface request.

4, Statistical test results, send test mail. You need to define a send_email () function.

HTTP interface is the most commonly used two kinds of request, post and get two methods, this blog share is the simplest common URL request. Example: http://192.168.21.129/bugfree/index.php/info/edit?type=bug&action=opened&product_id=1

There are several modules that need to be used: Requests, XLRD (read Excel), xlutils (write Excel), Pymysql (Connection database), Yagmail (send mail) The five modules are third-party modules and need to be installed separately.

First write the use case in Excel, need to have the field project, use case ID, interface name, use case description, request method, request URL, request data (multiple parameter words with & semicolon separated), expected results, request message, return message, tester, test results

The test cases are as follows:

The overall code is as follows:

Import Xlrd,requests,time,pymysql,yagmail fromxlutils Import copydef readexcel (file_path):Try: Book=Xlrd.open_workbook (file_path) except Exception asE:print ('path is not present or Excel is incorrect', E)Else: Sheet= Book.sheet_by_index (0) Rows=sheet.nrows Count_check= Rows-1case_list= []         forIinchrange (rows):ifI! =0: Case_list.append (Sheet.row_values (i)) Interfacetest (Count_check,case_list,file_path) def InterfaceT EST (count_check,case_list,file_path): Result_flags=[] #存测试结果, pass or fail Request_urls=[] #存请求报文的list response=[] #存返回报文的list count_pass=0Count_fail=0     for  Case inchcase_list:Try: Product= Case[0] # project, when the bug can be raised according to the project case_id= Case[1] # Use case ID, use interface_name when mentioning bug= Case[2] # Interface name, also to mention the bug when using Case_detail= Case[3] # Use case Description method= Case[4] # Request Way URL= Case[5] # request URL param= Case[6] # into the ginseng Res_check= Case[7] # expected result Tester= Case[Ten] # testers except Exception asE:print ('The test case is not formatted correctly! %s'%e)ifparam = ="': New_url=URL request_urls.append (new_url)Else: New_url= URL +'?'+param request_urls.append (new_url)ifMethod.upper () = ='GET': Results= requests.Get(URL,params=param_to_dic (param)). JSON () Results_str= requests.Get(URL,params=param_to_dic (param)). Text Response.append (results) Res=contrastres (results, Res_check)Else: Results=requests.post (URL, param_to_dic (param)). JSON () Results_str=requests.post (URL, param_to_dic (param)). Text Response.append (results) Res=contrastres (results, Res_check)if 'Pass' inchRes:result_flags.append ('Pass') Count_pass+=1        Else: Result_flags.append ('fail') Count_fail+=1Writebug (case_id, Interface_name, New_url, Results_str, Res_check) copy_excel (File_path, Result_flags, Request_urls, Response,count_check,count_pass,count_fail) def param_to_dic (param): Data_list= Param.split ('&') Data= {}     forIinchData_list:k, v= I.split ('=') Data[k]=vreturndatadef contrastres (Results, Res_check): Check_code= Res_check.split ('=')[1]    if int(check_code) = = results['Error_code']:        return 'Pass'    Else: # Print ('error, return parameter inconsistent with expected result'+Res_check)return 'fail'def copy_excel (File_path, Res_flags, Request_urls, Response,count_check,count_pass,count_fail): Book=Xlrd.open_workbook (file_path) New_book=copy.copy (book) sheet= New_book.get_sheet (0) I=1     forRequest_url, Response, flaginchZip (request_urls, Response, Res_flags): Sheet.write (i,8, u'%s'%request_url) Sheet.write (i,9, u'%s'%response) Sheet.write (i, One, u'%s'%flag) I+=1New_book.save ('%s_ test results. xls'% Time.strftime ('%y%m%d%h%m%s')) Atta='%s_ test results. xls'% Time.strftime ('%y%m%d%h%m%s') Send_mail (Count_check, Count_fail, Count_pass, Atta)
def writebug (bug_id, interface_name, request, Response, Res_check):
now = Time.strftime ("%y-%m-%d%h:%m:%s") # takes the current time as the time to raise the bug
Bug_title = bug_id + ' _ ' + interface_name + ' _ Result and expected error ' # Bug title with the bug number plus interface name and then add _ result and expected mismatch, you can freely define what kind of bug title
Step = ' [Request message]<br/> ' + ' + request + ' <br/> ' + ' [expected result]<br/> ' + Res_check + ' <br/> ' + ' <br/> ' + ' [Response message]<br/> ' + ' <br/> ' + response # The recurrence step is request message + expected result + return message
sql = INSERT into ' bf_bug_info ' (' created_at ', ' created_by ', ' updated_at ', ' updated_by ', ' bug_status ', ' assign_to ', ' ') Le ', ' mail_to ', ' repeat_step ', ' lock_version ', ' resolved_at ', ' resolved_by ', ' closed_at ', ' closed_by ', ' related_bug ', ' Related_case ', ' related_result ', ' \
"' productmodule_id ', ' modified_by ', ' solution ', ' duplicate_id ', ' product_id ', ' \
"' Reopen_count ', ' priority ', ' severity ') VALUES ('%s ', ' 1 ', '%s ', ' 1 ', ' Active ', ' 1 ', '%s ', ' System administrator ', '%s ', ' 1 ', NULL, NUL L, NULL, NULL, ', ', ', ', null, ' \
"' 1 ', NULL, NULL, ' 1 ', ' 0 ', ' 1 ', ' 1 ');"% (now, now, Bug_title, step) # SQL, this project ID, creator, severity, assigned to WHO, all in SQL Write dead, when used can be based on the item and interfaces to determine the severity of the bug and who to submit it to
Coon = Pymysql.connect (user= ' root ', passwd= ' 123456 ', db= ' Bugfree ', port=3306, host= ' 192.168.21.129 ', charset= ' UTF8 ') # Connect to MySQL using the Connect method of the Pymysql module, incoming account, password, database, port, IP, and character set
cursor = Coon.cursor () # Build cursor
Cursor.execute (SQL) # Execute SQL
Coon.commit () # Submit
Cursor.close () # Close cursor
Coon.close () # Close connection
def send_mail (Count_check,count_fail,count_pass,atta):
now = Time.strftime ("%y-%m-%d%h:%m:%s")
Username = ' [email protected] '
passwd = ' xxxxxxxxxx '
rece = ' [email protected] '
title = ' Python Interface Automation test Report ' +now
CC = ' [email protected]a.com '
Content = ' Big guy Hello: This test runs the%s use case, failed%s bar, success%s bar, test case detailed execution results please see annex '% (Count_check, Count_fail, Count_pass)
Mail_host = ' smtp.qq.com '
Mail = Yagmail. SMTP (user = Username,password = Passwd,host = Mail_host,smtp_ssl = True)
Mail.send (to = RECE,CC = Cc,subject = title,contents = Content,attachments = Atta)
# print (' Send success! ‘)

viewing test messages

To view the submission of a bug in Bugfree:

Python enables simple HTTP interface automation

Related Article

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.