Simple implementation of interface Automation testing (based on python+unittest)

Source: Internet
Author: User

Simple implementation of interface Automation testing (based on Python+unittest) introduction

In this paper, the basic interface test from the postman to get the simple interface test start, step-by-step optimization interface calls, and add basic results to judge, explain the Python's own unittest framework call, I hope you can through this article on the interface Automation test have a general understanding.

Why do the introduction of interface Automation testing?

In the context of frequent iterations of Internet products, regression testing is less time-intensive and it is difficult to complete regression of all functions in each iteration. However, the interface Automation test is more and more important because of its simple implementation, low maintenance cost, easy to improve coverage and so on.

Why write your own framework?

Using postman debugging through the direct can get interface test Basic code, combined with Requets + unittest easy to Implement Interface Automation test encapsulation, and requests API is very user-friendly, very simple, However, the efficiency of scripting can be further improved by encapsulation (especially for specific interfaces within the company).

An example of an existing simple interface

Use requests + UnitTest to test a query interface below

The interface information is as follows

Request Information:

Method:post

Url:api/match/image/getjson

Request:

{"category": "image","offset": "0","limit": "30","sourceId": "0","metaTitle": "","metaId": "0","classify": "unclassify","startTime": "","endTime": "","createStart": "","createEnd": "","sourceType": "","isTracking": "true","metaGroup": "","companyId": "0","lastDays": "1","author": ""}

Response Example:

{"timestamp" : xxx,"errorMsg" : "","data" : {"config" : xxx}

Postman test methods See:

Test ideas

1. Get Postman Original script

2. Use the requests library to simulate sending HTTP requests * *

3. Basic transformation of the original script * *

4. Write the test case** using the Python standard library unittest

Original script implementation not optimized

The code is simply a one-time call, and there are too many results returned, and a lot of the return information is temporarily useless, as shown in the example code

Import Requestsurl ="Http://cpright.xinhua-news.cn/api/match/image/getjson" querystring = {"Category":"Image","Offset":"0","Limit":"30","SourceID":"0","Metatitle":"","Metaid":"0","Classify":"Unclassify","StartTime":"","EndTime":"","Createstart":" ","Createend": "","sourcetype": "","istracking":"true","Metagroup": ""," CompanyID ":" 0 ","lastdays ":" 1 "," author ":""}headers = { ' Cache-control ': " No-cache ", ' Postman-token ': " e97a99b0-424b-b2a5-7602-22cd50223c15 "}response = Requests.request (" POST ", url, headers=headers, params=querystring) print (response.text)       
Optimize the first edition

Adjust code structure, output JSON, get Response.status_code to validate, and results[' total ' required to get results checksum

#!/usr/bin/env python#coding: Utf-8"' UnitTest merchant backgroud interface@author:zhang_jin@version:1.0@see:http://www.python-requests.org/en/master/'Import UnitTestImport JSONImport TracebackImport Requestsurl ="Http://cpright.xinhua-news.cn/api/match/image/getjson" querystring = {"Category":"Image","Offset":"0","Limit":"30","SourceID":"0","Metatitle":"","Metaid":"0","Classify":"Unclassify","StartTime":"","EndTime":"","Createstart":"","Createend":"","SourceType":"","Istracking":"True","Metagroup":"","CompanyID":"0", "lastdays":  "1",  "author":  ' Cache-control ': " No-cache " , " E97A99B0-424B-B2A5-7602-22CD50223C15 "}< Span class= "hljs-comment" > #Post接口调用response = Requests.request ( "POST", url, headers= Headers, params=querystring)  #对返回结果进行转义成json串results = Json.loads (response.text)  #获取http请求的status_code print  "Http Code: ", Response.status_code #获取结果中的total的值 print Results[ ' total '] #print (response.text)     
Optimize second Edition

The interface calls exception handling, increases try,except processing, returns a result of 200 for return Response.status_code, and is not 200 data exception information.

#!/usr/bin/env python#coding: Utf-8"' UnitTest merchant backgroud interface@author:zhang_jin@version:1.0@see:http://www.python-requests.org/en/master/'Import JSONImport TracebackImport Requestsurl ="Http://cpright.xinhua-news.cn/api/match/image/getjson" querystring = {"Category":"Image","Offset":"0","Limit":"30","SourceID":"0","Metatitle":"","Metaid":"0","Classify":"Unclassify","StartTime":"","EndTime":"","Createstart":"","Createend":"","SourceType":"","Istracking":"True","Metagroup":"","CompanyID":"0","Lastdays":"1","Author":""}headers = {' Cache-control ':"No-cache",' Postman-token ':"E97a99b0-424b-b2a5-7602-22cd50223c15"}Try#Post接口调用 response = Requests.request ( "POST", url, headers=headers, params=querystring)  #对http返回值进行判断, basic check for 200 if Response.status_code = 200:results = Json.loads (response.text) if results[ Total '] = = 191: print  "Success" else: print  "Fail" print results[ "total" else:  #对于http返回非200的code, output the corresponding code raise Exception ( "HTTP error info:%s"%response.status_code) except: Traceback.print_exc ()             
Optimize the third edition

1. This version changes large, the introduction of config file, separate package results check module, introduce UnitTest module, realize automatic interface call, and add log processing module;
2. The different POST request results are encapsulated, the different interfaces are called separately;
3. Statistics and final output of test case results

#!/usr/bin/env python#coding: Utf-8"' UnitTest interface@author:zhang_jin@version:1.0@see:http://www.python-requests.org/en/master/'Import UnitTestImport JSONImport TracebackImport requestsImport timeImport Result_statisticsImport ConfigAs CFFrom Com_loggerImport Match_loggerClassMytestsuite(UnitTest. TestCase):"" "DocString for Mytestsuite" ""# @classmethodDefSedup(self):Print"Start ..."#图片匹配统计Deftest_image_match_001(self): url = cf. URL1 querystring = {"Category":"Image","Offset":"0","Limit":"30","SourceID":"0","Metatitle":"","Metaid":"0","Classify":"Unclassify","StartTime":"","EndTime":"","Createstart":"","Createend":"","SourceType":"","Istracking":"True","Metagroup":"","CompanyID":"0","Lastdays":"1","Author":""} headers = {' Cache-control ':"No-cache",' Postman-token ':"545a2e40-b120-2096-960c-54875be347be"} response = Requests.request ("POST", url, headers=headers, params=querystring)if Response.status_code = =200:response.encoding = response.apparent_encoding results = json.loads (response.text)#预期结果与实际结果校验, call the Result_statistics module Result_statistics.test_result (results,196)ElsePrint"HTTP Error info:%s"%response.status_code#match_Logger. Info ("Start image_query22222")#self. Assertequal (results[' total '), 888"' Try:self.assertEqual (results[' total '], 888) except:match_Logger.error (TRACEBACK.FORMAT_EXC ()) #print results[' Total '] "#文字匹配数据统计Deftest_text_match_001(self): Text_url = cf. URL2 querystring = {"Category":"Text","Offset":"0","Limit":"30","SourceID":"0","Metatitle":"","Metaid":"0","StartTime":"2017-04-14","EndTime":"2017-04-15","Createstart":"","Createend":"","SourceType":"","Istracking":"True","Metagroup":"","CompanyID":"0","Lastdays":"0","Author":"","Content":""} headers = {' Cache-control ':"No-cache",' Postman-token ':"EF3C29D8-1C88-062A-76D9-F2FBEBF2536C"} response = Requests.request ("POST", Text_url, Headers=headers, params=querystring)if Response.status_code = =200:response.encoding = response.apparent_encoding results = json.loads (response.text)#预期结果与实际结果校验, call the Result_statistics module Result_statistics.test_result (results,190)ElsePrint"HTTP Error info:%s"%response.status_code#print (Response.text)def teardown passif __name__ =  ' __main__ ':  #image_match_Logger = Alogger (' Image_match ', log_level= ' INFO ')  #构造测试集合 suite=unittest. TestSuite () suite.addtest (Mytestsuite ( "test_image_match_001")) Suite.addtest ( Mytestsuite ( "test_text_match_001"))  #执行测试 runner = UnitTest. Texttestrunner () Runner.run (suite) print  "Success Case:", Result_statistics.num_success print  "Fail case:", Result_ Statistics.num_fail  #unittest. Main ()       
Final output log information
Zj-Mac:unittest lazybone$ python image_test_3.py 测试结果:通过.测试结果:不通过 错误信息: 期望返回值:190 实际返回值:4522.----------------------------------------------------------------------Ran 2 tests in 0.889sOKsuccess case: 1fail case: 1
Recommendations for follow-up improvements

The 1.unittest output report can also be recommended using Htmltestrunner (I am currently encapsulating the results statistics)

2. Continued encapsulation of the interface, parameterization, modularity

3.unittest Unit Test framework for parameterized invocation of third-party module references (nose-parameterized)

4. Continuous integration of the operating environment, scheduled tasks, trigger operation, mail delivery and a range of functions can be implemented on Jenkins.

Simple implementation of interface Automation testing (based on python+unittest)

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.