Simple implementation of interface automation testing practical tutorial based on python+unittest

1 Introduction

This article starts with a simple interface test by getting the basic interface test code from Postman, adjusting and optimizing the interface call step by step, and adding basic result judgments, and explains the Unittest framework call that comes with Python. I hope that you can have an understanding of interface automation testing through this article. A general understanding.

Why do we need to do interface automation testing?

In the current context of frequent iterations of Internet products, the time for regression testing is getting less and less, and it is difficult to complete regression of all functions in every iteration. However, interface automated testing has attracted more and more attention due to its simple implementation, low maintenance cost, and easy improvement of coverage.

Why write the framework yourself?

After using Postman debugging, you can directly obtain the basic code of the interface test. Using requests + unittest together can easily implement the encapsulation of automated interface testing, and the API of requests is very user-friendly and very simple. However, after encapsulation (especially for companies within the company) specific interface), which can further improve scripting efficiency.

2. An existing simple interface example

Next use requests + unittest to test a query interface

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
}

 

3. Test ideas

1. Get the original Postman script

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

3. Basic transformation of the original script**

4. Use unittest in the python standard library to write test cases**

Original script implementation
Not optimized

This code is just a simple call, and it returns too many results, and a lot of the returned information is temporarily useless. The sample code is as follows

import requests
 
url = "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)

 

Optimized first version

Adjust the code structure, output the result as Json, obtain the response.status_code that needs to be verified, and obtain the results['total'] that need to be used for result verification.

#!/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 unittest
import json
import traceback
import requests
 
 
url = "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"
    }
 
#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)
Optimized version 3

1. This version has major changes. It introduces the config file, separately encapsulates the result verification module, introduces the unittest module, realizes automatic interface calling, and adds a log processing module;
2. Encapsulate different Post request results and call different interfaces 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 unittest
import json
import traceback
import requests
import time
import result_statistics
import config as cf
from com_logger import  match_Logger
 
 
class MyTestSuite(unittest.TestCase):
    """docstring for MyTestSuite"""
    #@classmethod
    def sedUp(self):
        print "start..."
    #图片匹配统计
    def test_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)
            #预期结果与实际结果校验,调用result_statistics模块
            result_statistics.test_result(results,196)
        else:
            print "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']
        '''
 
    #文字匹配数据统计
    def test_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)
            #预期结果与实际结果校验,调用result_statistics模块
            result_statistics.test_result(results,190)
        else:
            print "http error info:%s" %response.status_code
 
        #print(response.text)
 
    def tearDown(self): 
        pass
 
if __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.889s
 
OK
success case: 1
fail case: 1

Suggestions for subsequent improvements

1. It is also recommended to use HTMLTestRunner for the unittest output report (I currently encapsulate the result statistics)

2. Continue to encapsulate, parameterize and modularize the interface

3. The unittest unit testing framework implements parameterized calls to third-party module references (nose-parameterized)

4. A series of functions such as continuous integration running environment, scheduled tasks, triggered running, and email sending can all be implemented on Jenkins.

 Thank you to everyone who reads my article carefully. There is always a courtesy. Although it is not a very valuable thing, if you can use it, you can take it directly:

 

These materials should be the most comprehensive and complete preparation warehouse for [software testing] friends, and this warehouse also accompanies Thousands of test engineers have gone through the most difficult journey, and I hope it can help you!Friends in need can click on the small card below to receive it 

 

Guess you like

Origin blog.csdn.net/kk_lzvvkpj/article/details/134863068