Interface test framework combat: data-driven test data (5)

Data-driven is the change of data to drive the execution of automated tests and ultimately cause changes in test results. Simply put, it is a parameterized application. Test cases with a small amount of data can use parameterization of the code to achieve data-driven. In the case of large amounts of data, it is recommended to use a structured file (such as YAML, JSON, etc.) to store the data, and then read it in the test case Take these data.

Parametric realization of data drive

This article still uses  @pytest.mark.parametrize decorators for parameterization and parameterization to achieve data-driven.

Through parameterization, determine that the parentid of the department with id 2 and 3 is 1:

import pytest

class TestDepartment:
    department = Department()

    @pytest.mark.parametrize("id", [2, 3])
    def test_department_list(self, id):
        r = self.department.list(id)
        assert self.department.jsonpath(expr="$..parentid")[0] == 1

The above code first uses a  @pytest.mark.parametrize decorator to pass two sets of data. The test results show that two test cases are executed instead of one test case. That is, pytest will automatically generate two corresponding test cases and execute them to generate two test results.

YAML files realize data-driven combat

When the amount of test data is large, you can consider storing the data in a structured file. The data in the format required by the code is read from the file and passed to the test case for execution.

This actual combat is demonstrated in YAML. YAML is structured by using dynamic fields. It is data-centric and is more suitable for data-driven than Excel, csv, JSON, XML, etc.

Store the two sets of data parameterized above into a YAML file and create a  data/department_list.yml file with the following code:

- 2
- 3

The above code defines a YAML data file format  department_list.yml , file defines a list, the list there are two data, the last generated data format is: [1,2] . Transform the parameterized data in the test case to department_list.yml read from the  file, the code is as follows:

class TestDepartment:
    department = Department()

    @pytest.mark.parametrize("id", \
    yaml.safe_load(open("../data/department_list.yml")))
    def test_department_list(self, id):
        r = self.department.list(id)
        assert self.department.jsonpath(expr="$..parentid")[0] == 1

The above code only needs to use the  yaml.safe_load() method, read  department_list.yml the data in the file, and pass it into the use case  test_department_list() method to complete the verification of the input and result.

For more advanced content of the interface testing framework, we will share in the follow-up article. Pay attention to the " Programmer Two Black " official account to get more test and development dry goods content.

Guess you like

Origin blog.csdn.net/m0_52650621/article/details/112832106