1, Preliminary preparations
1.apis.xlsx data table of tested interface
According to the interface document given by the development, we save the relevant data of the interface in APIs Xlsxl table, easy to read.
2.case01.xlsx test case
Write corresponding interface test cases case01 according to interface documents and requirements documents Xlsx, take a login interface as an example.
2, Code implementation
The code structure is as follows:
1.utlis.py reading excel table
Use xlrd module to read the contents of excel table, save the use case as a list and return.
# -*- coding: utf-8 -*- import xlrd class Excel(object): def __init__(self, file_name): # Read excel self.wb = xlrd.open_workbook(file_name) self.sh = self.wb.sheet_names() self.list_data = [] def read(self): for sheet_name in self.sh: sheet = self.wb.sheet_by_name(sheet_name) rosw = sheet.nrows for i in range(0, rosw): rowvalues = sheet.row_values(i) self.list_data.append(rowvalues) return self.list_data
2.data.py-data_to_dict processing table data
The data read from excel is processed into dictionary format.
def data_to_dict(data): """ Change use case table data to dict format :param data: :return: """ head = [] list_dict_data = [] for d in data[0]: d = case_header.get(d, d) head.append(d) for b in data[1:]: dict_data = {} for i in range(len(head)): if isinstance(b[i], str): dict_data[head[i]] = b[i].strip() else: dict_data[head[i]] = b[i] list_dict_data.append(dict_data) return list_dict_data
After processing, a use case is a separate dictionary, and all use cases are in a list. The processed data are as follows:
3.data.py-suite_cases generate test suite
Data_ to_ The data returned by dict is further processed and turned into the final test suite.
def suite_cases(data): """ dict The data processing of format is in the format of test suite :param data: :return: """ api_file = file_path.parent / 'api/apis.xlsx' excel_apis = Excel(api_file) apis = api_to_json(excel_apis.read()[1:]) testsuite = [] testcase = {} for d in data: # Format request data and assertion data for key in ('data', 'assert', 'headers'): if d[key].strip(): _ = d[key].split(',') test_data = dict() for i in _: i = i.split('=') test_data[i[0]] = i[1] d[key] = test_data if d['module'].strip(): if testcase: testsuite.append(testcase) testcase = {} testcase['module'] = d['module'] testcase['steps'] = [] no = str(d['step']).strip() if no: step = {'no': str(int(d['step']))} for key in ('id', 'title', 'condition', 'api', 'headers', 'data', 'assert'): if key == 'api': step[key] = {'type': apis[d.get(key, '')]['type'], 'url': apis['baseurl']['url'] + apis[d.get(key, '')]['url']} else: step[key] = d.get(key, '') testcase['steps'].append(step) if testcase: testsuite.append(testcase) return testsuite
Merge APIs For the data in xlsx, the data returned after processing is a list. Each element in the list represents a test case. Each element is a dictionary, which contains all the information of the test case. The processed data are as follows:
3.conftest.py send request module
Execute the test cases in the test suite and return the response data.
# -*- coding: UTF-8 -*- import pytest import requests import json @pytest.fixture() def post_request(request): data = request.param['data'] header = request.param['headers'] url = request.param['api']['url'] no = request.param['no'] response = requests.request('POST', url=url, headers=header, data=json.dumps(data)) return response, no
4.test_login.py execute login test case
Extract and execute the test cases of the login module.
# -*- coding: UTF-8 -*- import pathlib import pytest from common.data import data_to_dict, suite_cases from common.utlis import Excel file_path = pathlib.Path(__file__).parent excel_case = Excel(file_path / 'testcase/testcase.xlsx').read() test_suit = suite_cases(data_to_dict(excel_case)) for _ in test_suit: if _['module'] == 'Sign in': test_data = _['steps'] test_data = test_suit[0]['steps'] class TestLogin(object): @pytest.mark.parametrize('post_request', test_data, indirect=True) def test_login(self, post_request): response = post_request[0].json() no = int(post_request[1]) assert response['msg'] == test_data[no - 1]['assert']['msg']
5. Run test cases
Because in pytest INI file has been configured, so you can directly enter pytest on the command line to start executing the test case.
pytest.ini file configuration is as follows:
[pytest] # print and generate a saved Report addopts = -s --html=report/report.html # Match execution file python_files = test_*.py # Match execution class python_classes = Test* # Matching execution method python_functions = test_*
The results of the command line are as follows:
The test report is as follows:
The pytest HTML plug-in is used here, and allure also supports pytest. If you want a more beautiful test report interface, you can use the allure plug-in.
3, Summary
Automated tests run in this way are put on Jenkins for continuous integration. Using pytest xdist, you can also execute test cases in multiple processes, which makes the execution of tests more efficient and saves time and cost.