The general api encapsulates the actual combat, which will bring you an in-depth understanding of PO

In ordinary interface automation testing, if the parameters of the interface, such as
If the transmission parameters such as url and headers change, or the logic and assertion of the test case change, the whole test code needs to be changed. apiobject design pattern draws lessons from the design pattern of pageobject, which can realize an elegant and powerful interface testing framework.

**Idea**

apiobject design pattern can be simply divided into six modules: API object, interface test framework, configuration module, data encapsulation, Utils and test cases.

  • Interface test framework: base_api to complete the driving of api

  • API object: inherit base_ After the API, complete the encapsulation of the interface

  • Configuration module: finish reading the configuration file

  • Data encapsulation: data encapsulation of data construction and test cases

  • Utils: encapsulation of other functions, improvement of native framework

  • Test case: call Page/API object to realize business and assert

Boring concepts may be difficult to understand. Later chapters will focus on these modules for theoretical disassembly and example demonstration.

**api mode application**

Here, in combination with the department management of enterprise wechat, the Department list interface will be obtained as an interface test case, from no encapsulation to encapsulation transformation using apiobject design pattern. Combine actual combat with theory to have a deeper understanding of apiobject design pattern.

Environmental preparation

Enterprise wechat server API: https://work.weixin.qq.com/api/doc/90000/90135/90664 . Enterprise wechat without any encapsulation and transformation can obtain Department list interface test cases

import requests  
  
class TestDemo:  
    def test_get_token(self):        r = requests.get(url="https://qyapi.weixin.qq.com/cgi-bin/gettoken",            params={"corpid": "ww93348658d7c66ef4", "corpsecret": "T0TFrXmGYel167lnkzEydsjl6bcDDeXVmkUnEYugKIw"})        return r.json()["access_token"]  
    def test_department_list(self):        r = requests.get(url="https://qyapi.weixin.qq.com/cgi-bin/department/list",            params={"access_token": self.test_get_token(), "id": 1})        assert r.json()["errcode"] == 0        return print(r.json())

thinking

  • api

    • base_api.py is a general method used to encapsulate all APIs, such as printing log and secondary encapsulation of assertion tools. It does not involve business-related operations

    • wework.py inherit base_api and implement the basic business, and then all the specific business resources are inherited from Wework, such as the acquisition of token;

    • department inherits from wework and is used to implement the specific business logic of the corresponding module, such as sending the request, what parameters are in the request, etc.

  • All test cases are stored uniformly in the testcases folder, and API objects are called to realize business and assert

  • utils folder memory is used to encapsulate other functions and improve the lack of native framework

  • Data folder data structure and data encapsulation of test cases. In addition, there are configuration modules and data encapsulation, which will be introduced in later chapters

**Actual combat cases**

utils.py, encapsulating a jsonpath method in this file.

import jsonfrom jsonpath import jsonpath  
class Utils:    @classmethod    def jsonpath(cls, json_object, expr):        return jsonpath(json_object, expr)

base_api.py, in this file, call the jsonpath method in utils.

from test_wework.utils.Utils import Utils  
class BaseApi:    json_data = None  
    def jsonpath(self, expr):        return Utils.jsonpath(self.json_data, expr)

wework.py, which inherits the class BaseApi to obtain the token. The internal design of the function will be described in detail in the chapter "general api encapsulation" later.

class WeWork(BaseApi):    corpid = "ww93348658d7c66ef4"    contact_secret = "T0TFrXmGYel167lnkzEydsjl6bcDDeXVmkUnEYugKIw"    token = dict()    token_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"  
    @classmethod    def get_token(cls, secret=contact_secret):        # Avoid repeated requests and speed up if secret not in CLS token. keys():            r = cls. get_ access_ token(secret)            cls. token[secret] = r["access_token"]        return cls. token[secret]  
    @classmethod    def get_access_token(cls, secret):        r = requests.get(cls.token_url, params={"corpid": cls.corpid, "corpsecret": secret})        return r.json()

department.py, which inherits the class WeWork, initiates a get request to get the list of the Department.

class Department(BaseApi):    list_url = "https://qyapi.weixin.qq.com/cgi-bin/department/list"  
    def list(self, id):        self.json_data = requests.get(self.list_url, params={"access_token": WeWork.get_contact_token(), "id": id}).json()        return self.json_data

test_department.py, assert whether the first name in the return value is "WestWayyt".

class TestDepartment:    department = Department()  
    def test_department_list(self):        r = self.department.list(1)        assert self.department.jsonpath(expr="$..name")[0] == "WestWayyt"

**General api encapsulation practice**

In the apiobject design pattern, a "base_api" is required as the parent class of other API steps, and the general functions are placed in this parent class for other APIs to inherit and call directly. The advantage of this is to reduce repeated code and improve the reusability of code.

The api was used in the demonstration above-
Base is mentioned when the script is modified by object design pattern_ api. However, in the above, it just encapsulates a simple method in a utils. Not fully reflected_ The actual function of API.

Next, through the definition and encapsulation of general interface protocol, we will actually experience the base_ The cleverness of API.

base_api.py, which encapsulates the request in the code. Of course, we can't see the specific advantages here:

import requests  
class BaseApi:  
    def request(self, method, url, **kwargs):        self.json_data = requests.request(method=method, url=url, **kwargs)        return self.json_data

wework.py, which inherits from the class BaseApi, can directly call the request method in the parent class (there is no need to import the requests Library) to initiate a get request:

from test_interface.test_wework.api.base_api import BaseApi  
class WeWork(BaseApi):    corpid = "ww93348658d7c66ef4"    contact_secret = "T0TFrXmGYel167lnkzEydsjl6bcDDeXVmkUnEYugKIw"    token = dict()    token_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"  
    def get_access_token(self):        r = self.request(method="get", url=self.token_url,                         params={"corpid": self.corpid, "corpsecret": self.contact_secret})        return r.json()

test_wework.py, which is inherited from the class WeWork. The main purpose is to check the above get_ access_ Whether the token (self) is successful:

from test_interface.test_wework.api.wework import WeWork  
class TestWeWork(WeWork):  
    def test_get_access_token(self):        r = self.get_access_token()        assert r["errcode"]==0

In the above case, in base_api.py encapsulates requests one more layer. In this way, as long as it is a subclass of BaseApi, it can be called directly without reference
Requests library. Thus, various requests are initiated, and the definition and encapsulation of general interface protocol are realized.

** _
Come to Hogwarts test and development society to learn more advanced technologies of software testing and test development. The knowledge points include web automated testing, app automated testing, interface automated testing, test framework, performance testing, security testing, continuous integration / continuous delivery / DevOps, test left, test right, precision testing, test platform development, test management, etc, The course technology covers bash, pytest, junit, selenium, appium, postman, requests, httprunner, jmeter, jenkins, docker, k8s, elk, sonarqube, Jacobo, JVM sandbox and other related technologies, so as to comprehensively improve the technical strength of test and development engineers

Click for more information

Added by Avi on Tue, 08 Mar 2022 11:44:24 +0200