This article was first published on:Walker AI

In software testing, writing interface automation use cases for projects has become the tester’s permanent testing job. Using Python as an example, this article is based on the three use-case data reading methods used by the author: XLRD, PANDAS, and YAML.

1. Python third-party library XLRD

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

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

Once Python has installed third-party libraries, start reading interface use cases. The method is not encapsulated for demonstration purposes.

XLRD code demo

Here is an example code:

import unittest
import xlrd

Open the interface use case excel file
excel_data = xlrd.open_workbook('register.xlsx')
# Read the sheet page in excel file where the use case is stored
sheet = excel_data.sheet_by_name('register')
print(sheet.nrows)
print(sheet.row_values(1))
Append all read use cases to the data list
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
Copy the code

After executing the py file, print and read the list of data, and successfully read and read the example data of excel file:

But the above method will put the entire Excel file use cases into a list, data access is not very convenient. Now we split the data and read the data in combination with DDT data-driven mode:

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_)

# introduced decorator @ddt; @data to import data; Split data @unpack
@ddt
class register(unittest.TestCase) :
    @data(*data_)
    @unpack
    def test_register(self, title, data, check) :
        print(data)


if __name__ == '__main__':
    unittest.main()
Copy the code

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

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

XLRD applies to projects that have little interface data and interface fields are not frequently adjusted. If you have a large number of interfaces in your project, the Excel file that holds the use cases will grow as you write the interface use cases. The legibility and maintainability of test cases will become difficult problems in the later testing work and affect the testing efficiency.

2. The Python third-party library is pandas

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

Start by creating an Excel file to store the test data:

Pandas code

Example code:

Read the use case from the Excel file with the name parameter as sheet name
def read_excel_data(inputdir,name) :
     dataframe = pandas.DataFrame(columns=['Interface name'.'cases'.'Requested address'.'Request body'.'assertion that'.'agreement'.'Request mode'])	The pass parameter is the column name in the Excel file
     try:
         datafile = pandas.read_excel(inputdir,sheet_name=name)
         dataframe = dataframe.append(datafile, ignore_index=True, sort=True)
     except:
         print("Warning: Excel file opening exception, please try again!")
     To_list = dataframe.to_dict(orient='records')	When the parameter ='records', the converted form is a list
     return To_list
Copy the code

from common.data 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 '	The path to the excel file is specified according to the actual project structure
getdata(path)
Copy the code

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

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

Reading test cases in Excel files by XLRD is the mainstream data reading method in interface testing. However, it can be found from the above case that if the data in the Excel file is increasing, the maintenance cost of the later test is relatively high, and the format of the table is not easy to read because of the large amount of data. This is one of the drawbacks of this approach.

3. Python third-party library YAMl

Yaml is a serialization language for writing configuration files in the form of lists, dictionaries, and nested output. Hierarchies 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
Copy the code

Common YAML formats:

Colon and space (” : “) : dictionary format

The following data is read as dict
name: A
age: 1
spouse:
    name: B
    age: 2
slave:
 - name: C  # - represents a list
   age: 3
 - name1: D
   age1: 4
Copy the code

Yaml code demo

Read dict data from a YAML file as follows:

import os
import yaml

class LoadTestData:
    # Set path to obtain yamL file data
    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) :
    Param API_name: API file location :param API_name: API file name: return: file data ""
    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 success')
Copy the code

Note that yaml.load, when invoked, may prompt an exception due to an older version of YAML. Solution: Specify loader = yaml.FullLoader to resolve the exception.

As you can see from the actual use of YAML above, YAML is much more readable than the data stored in Excel tables, and Python itself supports creating new YAML files for better interaction with scripting languages. You can also create different YAML files for different test modules to realize test data isolation between functional modules.

conclusion

In the test, the test data can be quickly integrated and assembled, whether stored in Excel tables or yamL files. However, when the excel table stores too much data, it has some problems such as reduced readability and long script execution time. Yaml has the advantages of simplicity, high interaction with Python, and the ability to isolate test data from functional templates. But you also need to have some knowledge of the YAML writing specification to use it properly.

This article is just a simple sharing from a Python test data reading perspective. If there is any inappropriate place, we welcome you to correct.


PS: more dry technology, pay attention to the public, | xingzhe_ai 】, and walker to discuss together!