General API package combat (interface test framework combat)

image                                                                       

In the APIObject design pattern, a base_api parent class is needed  as other API steps, and general functions are placed in this parent class for other APIs to directly inherit and call. The advantage of this is that it reduces repetitive code and improves code reusability.

Common API package combat

Mentioned in the previous chapter when demonstrating the use of API-Object design pattern to transform the script  base_api. However, in the previous chapter, it only encapsulated  utils a simple method in one. Does not fully reflect  base_api the actual effect.

Next, we will actually experience base_api the ingenuity through the definition and encapsulation of the common interface protocol  .

  • base_api.py

In the code, a layer of encapsulation is performed on the request. Of course, there is no specific advantage 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

Inherited from the class  BaseApi, you can directly call the request method in the parent class  (without importing 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

The WeWorkmain purpose of inheriting from the class  is to check get_access_token(self) whether the above  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

Above, in the above case, requests are encapsulated in base_api.py with one more layer, so that as long as they belong to  BaseApi a subclass of this class, they can directly call the requests library without reference. In this way, various requests are initiated and the definition and encapsulation of common interface protocols are realized.

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/112828101