The leader saw it and gave you a raise! Python +ddt+excel is a new trick, the interface automation test is easy to get done, and the test report is amazing!

Table of contents

How to use python +ddt+excel to realize interface automation testing

1. Preparation

1. Install python environment

2. Install related libraries

2. Design and test

1. Write excel file

2. Encapsulate excel operation

3. Encapsulate requests request

3. Execute the test

1. Write test cases

2. Generate test report

Fourth, view the results


"  Interface automation testing refers to the process of verifying whether the interface meets the design specifications and functional requirements by simulating the user sending a request by writing code or using tools. "

How to use python +ddt+excel to realize interface automation testing

Interface automation testing can improve test efficiency and quality, save test cost and time, and ensure test coverage and maintainability.

Let Brother Yong guide you how to use python +ddt+excel to realize interface automation testing, please see the following content:

1. Preparation

1. Install python environment

Python is a concise, elegant, and easy-to-learn programming language. It has rich third-party libraries and community support, and is very suitable for automated testing of interfaces. Install python version 3.0 or above), and configure environment variables to use python commands on the command line.

2. Install related libraries

In order to perform interface automation testing, we need to install the following libraries:

  • requests: Used to send HTTP requests, supporting various methods, parameters, headers, authentication, etc.

  • xlrd: used to read the data in the excel file, supports xls and xlsx format.

  • openpyxl: used to write data in excel files, supports xlsx format.

  • ddt: Used to implement data-driven testing, which can read multiple sets of data from excel files and generate multiple test cases.

  • unittest: Used to write and execute test cases, support assertions, pre-post conditions, test suites, etc.

  • HTMLTestRunner_api: Used to generate test reports in HTML format, supporting charts, logs, screenshots, etc.

We can use the pip command to install these libraries, for example:

pip install requests

2. Design and test

1. Write excel file

We need to fill in the relevant information of the interface in the excel file, including:

  • interface name

  • request address

  • request method

  • request parameters

  • expected outcome

For example:

We can save this excel file as test_data.xlsx and put it in the test_datas directory of the project.

2. Encapsulate excel operation

In order to read and write data in excel files conveniently, we need to encapsulate some excel operation functions, for example:

  • open form

  • get header

  • get all data

  • data input

We can define these functions in a class, save it as excel_handler.py, and put it in the Lib directory of the project. The specific code is as follows:

from openpyxl import load_workbook
from openpyxl.worksheet.worksheet import Worksheet
 
class ExcelHandler():
    '''操作Excel'''
    def __init__(self, file):
        '''初始化函数'''
        self.file = file
    
    def open_sheet(self, sheet_name) -> Worksheet:
        '''打开表单'''
        wb = load_workbook(self.file)
        sheet = wb[sheet_name]
        return sheet
    
    def read_rows(self,sheet_name):
        '''读取除表头外所有数据(除第一行外的所有数据)'''
        sheet = self.open_sheet(sheet_name)
        rows = list(sheet.rows)[1:]
        data = []
        for row in rows:
            row_data = []
            for cell in row:
                row_data.append(cell.value)
            data.append(row_data)
        return data
     def read_key_value(self,sheet_name):
        '''获取所有数据,将表头与内容结合整....'''                ...
        return data

3. Encapsulate requests request

In order to send HTTP requests conveniently, we need to encapsulate some requests request functions, for example:

  • Initialize session

  • send request

  • close session

We can define these functions in a class, save it as requests_handler.py, and put it in the Lib directory of the project. The specific code is as follows:

import requests
 
class HTTPHandler:
    # 初始化
    def __init__(self):
        self.session = requests.Session()
    
    # 定义一个方法,接收访问http请求的方式
    def visit(self, url, method, params=None, data=None, json=None, **kwargs):
        res = self.session.request(method, url, params=params, data=data, json=json, **kwargs)
        try:
            return res.json()
        except ValueError:
            print('return not json')
    
    # 关闭session会话
    def close_session(self):
        self.session.close()

3. Execute the test

1. Write test cases

We need to use unittest and ddt to write and execute test cases, the specific steps are as follows:

  • Import related libraries and modules

  • Define a test class that inherits unittest.TestCase

  • Define a class method to initialize the session and read the data in the excel file

  • Use the @ddt.data decorator to pass in the data in the excel file

  • Define a test method to send a request and assert whether the response is as expected

We can save these codes as test_api.py and put them in the test_cases directory of the project. The specific code is as follows:

from Lib.excel_handler import ExcelHandler
from Lib.requests_handler import HTTPHandler
import requests
import ddt
import unittest
 
data = ExcelHandler('test_datas/test_data.xlsx').read_key_value('Sheet1')
 
@ddt.ddt
class TestAPI(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.s = HTTPHandler()
    
    @ddt.data(*data)
    def test_api(self,params):
        print('params:%s' % params)
        case_name = params.get('接口名称')
        url = params.get('请求地址')
        args = eval(params.get('请求参数')) if isinstance(params.get('请求参数'), str) else params.get('请求参数')
        method = params.get('请求方法')
        expct_res1 = params.get('预期结果')
        
        # 发起请求,获取返回数据
        result = self.s.visit(url, method, params=args)
 
        # 分析返回数据
        response_data = result['name']
 
        
        # 断言响应结果是否符合预期
        self.assertEqual(expct_res1, response_data)
 
    @classmethod
    def tearDownClass(cls):
       cls.s.close_session()

2. Generate test report

We need to use HTMLTestRunner_api to generate test reports in HTML format, the specific steps are as follows:

  • Import related libraries and modules

  • Define a test suite and add test cases

  • Define a test report file name and path

  • Define a test runner, passing in the file object and related parameters of the test report

  • Use the test runner to run the test suite

We can save these codes as run.py and put them in the root directory of the project. The specific code is as follows:

import unittest
from HTMLTestRunner_api import HTMLTestRunner
from test_cases.test_api import TestAPI
 
# 定义一个测试套件
suite = unittest.TestSuite()
# 添加测试用例
suite.addTest(unittest.makeSuite(TestAPI))
 
# 定义一个测试报告的文件名和路径
report_file = 'reports/test_report.html'
 
# 定义一个测试运行器,传入测试报告的文件对象和相关参数
with open(report_file, 'wb') as f:
    runner = HTMLTestRunner(f, title='接口自动化测试报告', description='用例执行情况')
    # 使用测试运行器来运行测试套件
    runner.run(suite)

Fourth, view the results

After running the run.py file, we can see the generated test_report.html file in the reports directory, open it, and we can see the following:
 

We can see that there are 11 test cases, 6 passed and 5 failed. We can also see the details of each test case, including case name, request address, request parameters, expected results, actual results, etc. We can also see some graphs, logs, screenshots, etc.

In this way, we have completed the process of implementing interface automation testing with python +ddt+excel.


Finally, I would like to thank everyone who has read my article carefully. Looking at the fans’ growth and attention all the way, there is always a need for reciprocity. Although it is not a very valuable thing, you can take it away if you need it:

These materials should be the most comprehensive and complete preparation warehouse for [software testing] friends. This warehouse has also accompanied tens of thousands of test engineers through the most difficult journey. I hope it can help you too!

In my QQ technology exchange group (technical exchange and resource sharing, no advertising)

 

Guess you like

Origin blog.csdn.net/weixin_67553250/article/details/131580344