Python uses requests+excel for interface automation testing

In today's Internet era, interface automation testing has increasingly become an important part of software testing. Python is an easy-to-learn, efficient, and extensible language, making it a natural choice for developers. The two commonly used Python standard libraries, requests and xlwt, can help us easily develop interface automation tests and complete the test work faster and better.

The following are the benefits that these two libraries can bring in interface automation testing:

1. requests can conveniently simulate sending HTTP requests, implement interface testing, and support GET, POST, PUT, DELETE and other request methods. Using requests, we can easily implement the processing of interface requests and return results.

import requestsresponse = requests.get('http://example.com')

2. requests provides support for complex processing of HTTP headers and specific authentication schemes, including Basic, Digest, OAuth, etc. This means that we can easily implement authorization authentication of the interface. ​​​​​​​​

import requestsresponse = requests.get('http://example.com', auth=('user', 'pass'))

3. requests support the processing of Cookie and Session, which can be used to ensure the user's identity authentication or the continuity of subsequent requests. This is useful for tests that require multiple calls to the interface.

4. The xlwt library supports outputting or recording the test results in Excel format. Interface automation testing sometimes needs to output test reports, and xlwt can easily output the test results as an Excel table. ​​​​​​​​

import xlwtbook = xlwt.Workbook(encoding='utf-8')sheet = book.add_sheet('Sheet1')sheet.write(0, 0, '接口名称')sheet.write(0, 1, '测试结果')sheet.write(1, 0, 'test API')sheet.write(1, 1, 'Pass')book.save('result.xls')

5. The xlwt library provides formatted output for the test results. Users can customize the table style and the format, font, color, border, etc. of the table content, so that users can quickly understand the interface test results and make effective responses to them.

To sum up, requests and xlwt are two basic libraries of Python, they can easily complete interface automation testing, and greatly improve the efficiency and accuracy of testing. Therefore, if you have not used them for interface automation testing, you might as well try the following interface automation testing framework DEMO

full code

import requestsimport xlwtimport xlrdimport unittestclass BaseTestCase(unittest.TestCase):    url = ""  # 接口请求的 URL    method = "GET"  # 接口请求的方法    data = {}  # 接口请求的数据    headers = {}  # 接口请求的头部    expected_code = 200  # 预期的 HTTP 状态码    expected_result = {}  # 预期的响应结果    def setUp(self):        """每个测试方法执行前调用"""        pass    def tearDown(self):        """每个测试方法执行后调用"""        pass    def run_case(self, case):        """动态创建的测试方法,执行测试用例"""        self.url = case['url']        self.method = case['method']        self.data = case['data']        self.headers = case.get('headers', {})        self.expected_code = case.get('expected_code', 200)        self.expected_result = case.get('expected_result', {})        self.test_api()    def test_api(self):        """测试用例实现"""        response = requests.request(self.method, url=self.url, headers=self.headers, data=self.data)        self.assertEqual(response.status_code, self.expected_code)  # 断言响应的 HTTP 状态码是否与预期一致        self.assertDictEqual(response.json(), self.expected_result)  # 断言响应的结果是否与预期一致def read_excel(file_path, sheet_name):    workbook = xlrd.open_workbook(file_path)  # 打开 Excel 文件    sheet = workbook.sheet_by_name(sheet_name)  # 获取 Excel 工作表    rows = sheet.nrows  # 获取行数    cases = []    for i in range(1, rows):  # 从第 2 行开始读取测试用例        case = {}        case['url'] = sheet.cell_value(i, 0)  # 读取接口请求的 URL        case['method'] = sheet.cell_value(i, 1)  # 读取接口请求的方法        case['data'] = sheet.cell_value(i, 2)  # 读取接口请求的数据        case['headers'] = sheet.cell_value(i, 3)  # 读取接口请求的头部        case['expected_code'] = int(sheet.cell_value(i, 4))  # 读取预期的 HTTP 状态码        case['expected_result'] = eval(sheet.cell_value(i, 5))  # 读取预期的响应结果        case['name'] = sheet.cell_value(i, 6)  # 读取用例名称        cases.append(case)    return casesdef write_excel(file_path, sheet_name, cases):    workbook = xlwt.Workbook()    sheet = workbook.add_sheet(sheet_name)    sheet.write(0, 0, '用例编号')    sheet.write(0, 1, '用例名称')    sheet.write(0, 2, '测试结果')    for i, case in enumerate(cases):        sheet.write(i+1, 0, i+1)        sheet.write(i+1, 1, case.get('name', '') or case['url'])        sheet.write(i+1, 2, '通过' if case.get('result') else '失败')    workbook.save(file_path)if __name__ == '__main__':    cases = read_excel('cases.xlsx', 'Sheet1')  # 读取测试用例    suite = unittest.TestSuite()  # 创建测试套件    for case in cases:        case_name = case.get('name', '') or case['url']        setattr(BaseTestCase, 'test_{}'.format(case_name), lambda self, case=case: self.run_case(case))        # 动态创建测试方法,并将测试用例绑定到测试方法上    unittest.TextTestRunner().run(suite)  # 执行测试套件    write_excel('report.xls', 'Sheet1', cases)  # 写入测试结果报告

Let's introduce the above code in detail ⬆️

1. Install required libraries and dependencies

pip install requestspip install xlwt

2. Write the interface automation test base class and test case implementation

import requestsimport xlwtimport unittestclass BaseTestCase(unittest.TestCase):    url = ""  # 接口请求的 URL    method = "GET"  # 接口请求的方法    data = {}  # 接口请求的数据    headers = {}  # 接口请求的头部    expected_code = 200  # 预期的 HTTP 状态码    expected_result = {}  # 预期的响应结果    def setUp(self):        """每个测试方法执行前调用"""        pass  # 可以进行一些初始化工作    def tearDown(self):        """每个测试方法执行后调用"""        pass  # 可以进行一些清理工作    def test_api(self):        """测试用例实现"""        response = requests.request(self.method, url=self.url, headers=self.headers, data=self.data)        self.assertEqual(response.status_code, self.expected_code)  # 断言响应的 HTTP 状态码是否与预期一致        self.assertDictEqual(response.json(), self.expected_result)  # 断言响应的结果是否与预期一致

3. Write Excel file reading and parsing functions

import xlrddef read_excel(file_path, sheet_name):    workbook = xlrd.open_workbook(file_path)  # 打开 Excel 文件    sheet = workbook.sheet_by_name(sheet_name)  # 获取 Excel 工作表    rows = sheet.nrows  # 获取行数    cases = []    for i in range(1, rows):  # 从第 2 行开始读取测试用例        case = {}        case['url'] = sheet.cell_value(i, 0)  # 读取接口请求的 URL        case['method'] = sheet.cell_value(i, 1)  # 读取接口请求的方法        case['data'] = sheet.cell_value(i, 2)  # 读取接口请求的数据        case['headers'] = sheet.cell_value(i, 3)  # 读取接口请求的头部        case['expected_code'] = int(sheet.cell_value(i, 4))  # 读取预期的 HTTP 状态码        case['expected_result'] = eval(sheet.cell_value(i, 5))  # 读取预期的响应结果        cases.append(case)    return cases

4. Write Excel result report writing function

def write_excel(file_path, sheet_name, cases):    workbook = xlwt.Workbook()    sheet = workbook.add_sheet(sheet_name)    sheet.write(0, 0, '用例编号')    sheet.write(0, 1, '用例名称')    sheet.write(0, 2, '测试结果')    for i, case in enumerate(cases):        sheet.write(i+1, 0, i+1)        sheet.write(i+1, 1, case.get('name', ''))        sheet.write(i+1, 2, '通过' if case.get('result') else '失败')    workbook.save(file_path)

5. Write the main function

if __name__ == '__main__':    cases = read_excel('cases.xlsx', 'Sheet1')  # 读取测试用例    suite = unittest.TestSuite()  # 创建测试套件    for case in cases:        case_name = case.get('name', '') or case['url']        setattr(BaseTestCase, 'test_{}'.format(case_name), lambda self, case=case: self.run_case(case))        # 动态创建测试方法,并将测试用例绑定到测试方法上    unittest.TextTestRunner().run(suite)  # 执行测试套件    write_excel('report.xls', 'Sheet1', cases)  # 写入测试结果报告

This is a simple Python interface automation test project, which can manage test cases through Excel files, supports multiple HTTP request methods and data formats, and is suitable for various interface automation test scenarios.


If the article is helpful to you, remember to like, bookmark, and add attention. I will share some dry goods from time to time...

END Supporting Learning Resources Sharing

Finally:  In order to give back to the die-hard fans, I have compiled a complete software testing video learning tutorial for you. If you need it, you can get it for free 【保证100%免费】

Software Testing Interview Documentation

We must study to find a high-paying job. The following interview questions are the latest interview materials from first-tier Internet companies such as Ali, Tencent, and Byte, and some Byte bosses have given authoritative answers. Finish this set The interview materials believe that everyone can find a satisfactory job.

insert image description here

How to obtain the full set of information:

Guess you like

Origin blog.csdn.net/IT_LanTian/article/details/131230223