Moment For Technology

Introduction to common use-case reading methods for Python interface automation

Posted on April 5, 2023, 6:25 p.m. by Erin Hammond
Category: python Tag: python interface test
This article was first published at:Walker AI

In software testing, writing interface automation use cases for projects has become a tester's regular testing task. Using Python as an example, this article is based on the three methods I have used to read data from use cases: XLRD, Pandas, and YAML. Here is a brief introduction of their use methods and analysis.

1. Python third-party library XLRD

The XLRD module, which can be used to read Excel documents, is one of the most common use case reads, used as follows. To take the demonstration convention of registering an interface as an example, first create a new Excel document with the parameters of the custom interface use case:

(The following data are randomly generated and do not involve any system)

Now that Python has installed the third-party libraries, start reading the interface use cases. For the sake of demonstration, the method is not encapsulated.

XLRD code demonstration

Here is the example code:

Import unittest import XLRD # Excel_data = xlrd.open_workbook('register.xlsx') # Read the sheet in the Excel file where the use case is stored Sheet = Excel_Data. sheet_by_name('register') Print (sheet.nrows) Print (sheet.row_values(1)) Sheet = Excel_Data. sheet_by_name('register') Print (sheet.nrows) Print (sheet.row_values(1) data = [] for i in range(1, sheet.nrows): data.append(sheet.row_values(i)) print(data) class register(unittest.TestCase): def test_register_check(self): pass

After executing the PY file, print and read the data list, and successfully read and extract the use case data from the Excel file:

However, the above method will store the entire use case of the Excel file in a single list, which is not convenient for data access. Now we split the data, combined with the DDT data-driven way to read the data:

import unittest import xlrd from ddt import ddt,data,unpack excel_data = xlrd.open_workbook('register.xlsx') sheet = excel_data.sheet_by_name('register') # print(sheet.nrows) # print(sheet.row_values(1)) data_ = [] for i in range(1, Sheet.nrows): data_.append(sheet.row_values(I)) print(data_) # @ddt; Import data @data; @[email protected] class register(unittest.testcase): @data(*data_) @unpack def test_register(self, title, data, check): print(data) if __name__ == '__main__': unittest.main()

Through the data and unpack methods in DDT, each piece of data in the Excel file is a separate list, which is easier to provide to the interface test case:

The XLRD module is used very frequently in interface automation and is very simple to call methods. After reading the Excel test case, you can also use the decorator DDT to split the data, making the data even simpler.

XLRD is suitable for projects where the project interface data is small and the interface fields are not often adjusted. If the number of interfaces in the project is very large, the content of the Excel file containing the use cases will be constantly expanded when the interface use cases are written. The readability and maintainability of test cases will become difficult problems in the later testing work and affect the testing efficiency.

2. The third library for Python is Pandas

Pandas is a Python data analysis package that helps users work with large data sets. Using the DataFrame method in Pandas, you can retrieve test data from an Excel spreadsheet. Pandas, like XRLD, can read Excel files.

First create an Excel file to hold the test data:

Pandas Code Demo

Example code:

Def read_excel_data(inputDir,name): Data Aframe (Columns =[' Interface Name ',' Use Case ',' Request Address ',' Request Body ',' Assertion ',' Protocol ',' Request Mode ']) datafile = pandas.read_excel(inputdir,sheet_name=name) dataframe = dataframe.append(datafile, ignore_index=True, Sort =True) except: print("Warning: Excel file is not open, please try again!" To_dict = dataframe.to_dict(Orient ='records') # return To_list when parameter ='records

from import read_excel_data import pytest def getdata(path): GetData = read_excel_data(path, 'edit xx') print(getData) path = r'.. \common\ Interface Use Case Document.xlsx '# Path to the Excel file, specifying getData (Path) by actual project structure

Call the wrapped method and successfully read all the use case data in the Excel file:

This method is similar to XLRD in that it also obtains the required interface use cases by reading the data in a two-dimensional table.

XLRD and other methods to read test cases in Excel file is a more mainstream way to read data in interface testing. However, it can be found from the above case that if the Excel file contains more and more data, the maintenance cost of the later test will be relatively high. At the same time, the table format in large data is not convenient to read. This is also a drawback to such an approach.

3. Python third-party library YAML

YAML is a serialization language for writing configuration files. The output of the file format can be lists, dictionaries, or nested. Hierarchical relationships are separated by Spaces, but TAB indentation is not supported.

Dashes and Spaces (" - ") : List format

# The following data will be read as a list -testapi-url-get

Common YAML formats:

Colons and Spaces (" : ") : Dictionary format

Dict: A age: 1 spouse: name: B age: 2 slave: -name: C # - denoted as list age: 3-name1: D age1:4

YAML code demonstration

Read the dict data from the YAML file as follows:

Def load_data(self, file_name) def load_data(self, file_name) yaml_path = os.path.join(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'test_file'), file_name) yaml_data = yaml.load(open(yaml_path), Loader=yaml.FullLoader) # print(yaml_data) return yaml_data def get_yaml_data(api_file, api_name): "" Get the data for API_NAME in YAML :param API_FILE: API file location :param API_NAME: API file name: return: Data = loadTestData (). Load_data (api_file)[api_name] print(data) return data if __name__ == '__main__': file_name = 'api_data.yaml' api_name = 'test' # LoadTestData().load_data(file_name) get_yaml_data(file_name,api_name ) Print (' read successfully ')

Note that YAML. LOAD may prompt an exception when called because of a higher version of YAML. Solution: Specify Loader = YAML.FullLoader to resolve the exception.

As you can see from the above example, YAML is much more readable than Excel tables, and Python supports the creation of new YAML files, making it more interactive with scripting languages. For different test modules, different YAML files can also be created to achieve test data isolation between functional modules.


In the test, whether the data is stored in Excel form or YAML file, the test data can be quickly integrated and assembled. However, when the Excel spreadsheet stores too much data, the readability will decrease and the script execution time will be longer. YAML has the advantages of simplicity, high interaction with Python, and isolation of test data from functional templates. However, some understanding of YAML's writing specification is also required to use it correctly.

This article is just a brief sharing based on the Python test data reading perspective. If there is any inappropriateness, you are welcome to correct.

About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.