Interface Automation Framework: Process Encapsulation and Test Case Design Based on Encrypted Interface

For interface testing, it is not enough to master the usage of Requests or other powerful libraries. It is also necessary to have the ability to customize an interface automation testing framework according to the company's business processes and needs. So, next, we mainly introduce how the interface test case analysis and general process encapsulation are completed.

Interface test case analysis

First of all, before doing use case analysis, you can track down all the causes of failures in the company over the past year, locate the cause of the problem, or get quality pain points through investigations with CTO, product manager, R&D, operation and maintenance, and testing, and you can also analyze business architecture and process calls , and the monitoring system understands the usage data of the business, so as to obtain the quality requirements .

After getting the quality requirements, through docking with product managers, project managers, R&D directors, etc., to learn about the business scope to be tested, business scenario use cases, and business interface analysis, so as to determine the company's test plan . Combining the test plan with the quality requirements for analysis, you can start the design of business use cases, and the analysis of interface test cases is also included.

quality requirements sample
Test pain points The company's interface has been unstable and affects the use of users
quality feedback There have been several major failures in the past six months
Regression Testing Every upgrade will affect the old function
testing strategy Currently the company does not have a reliable testing system
refactoring test The transformation of microservices requires a good test system guarantee

Interface testing encapsulation idea

The idea of ​​interface encapsulation is mainly divided into three major dimensions: configuration, interface encapsulation, and business process . in:

  • Configuration is mainly used to obtain initial configuration and dependencies based on configuration files;
  • Interface encapsulation follows the APIObject design pattern to abstract and encapsulate interface calls;
  • The business process is responsible for data initialization and business use case design, including process definitions formed by multiple APIs, and does not include any interface implementation details and assertions.

The following will be combined with actual combat cases for a detailed introduction.

Design of Test Cases Based on Encrypted Interface

Due to information security reasons, many interfaces encrypt requests and responses during transmission. It is obviously not feasible to directly assert this part of the data. It is also necessary to perform additional decryption processing on this part of the interface before asserting the decrypted interface.

Environmental preparation

Before actual combat, you need to prepare an interface for encrypting the response. After initiating a get request to it, an encrypted response message is obtained.

First prepare a demo in JSON format:

{"topics":
{
"orange":"movie",
"shool":"testing-studio",
"president":"seveniruby"
}
}

Encrypt it with base64 to get an encrypted file demo64.txt

base64 demo.json >demo64.txt

Use the Python command to start a service in the directory where "demo64.txt" is located

python -m http.server 10000

It looks like this after startup:

Use the curl command to make a get request to this service:

curl http://127.0.0.1:10000/demo64.txt

If the request is successful, it means that the environment has been prepared successfully

Combat practice

Call base64 and directly decrypt the returned request to get the decrypted response. Convert the decrypted response to JSON format. At this time, you can make an assertion on the returned value without reporting an error.

import base64
import json
import requests
class TestEncode:
    url = "http://127.0.0.1:10000/demo64.txt"
    def test_encode(self):
        r = requests.get(self.url)
        encode = json.loads(base64.b64decode(r.content))
        assert encode["topics"]["president"] == "seveniruby"

This way of writing is obviously not elegant enough. If the protocol of the interface under test changes, the Requests library cannot support the changed protocol, and another third library needs to be called to send the request information, and the underlying source code still needs to be modified. In this case, you can add a layer of encapsulation to construct a more general sending method.

First of all, it is necessary to save all request information through a dictionary structure, including the sending protocol, decoding method, request method, etc., and this dictionary structure also provides an important foundation for the subsequent data-driven transformation .

 req_data={
            "schema": "http",
            "method": "get",
            "url": "http://127.0.0.1:10000/demo64.txt",
            "headers": None
        }

By adding judgment conditions in the structure of the request information schema, different request protocols can be selected. For example, if  schema it is "http", choose to call the encapsulated requests library.

class ApiRequest:
    #构造send方法,通过
    def send(self, data: dict):
        if "http" == data["schema"] :
            res = requests.request(data["method"],data["url"],header=data["headers"])
            return json.loads(base64.decode(res.content))
        elif "dubbo" ==  data["schema"]:
            pass
        elif "websocket" == data["schema"]:
            pass
        else:
            pass        

Call ApiRequestthe send method in the class to send the request and make an assertion

class TestEncode:
   def test_api(self):
        req_data={
            "schema": "http",
            "encoding": "base64",
            "method": "get",
            "url": "http://127.0.0.1:10000/demo64.txt",
            "headers": None
        }
        re = ApiRequest()
        data = re.send(req_data)
        assert data["topics"]["president"] == "seveniruby"

If faced with different algorithms, the underlying source code needs to be modified, so the algorithm needs to be encapsulated. Use whichever algorithm you need. The idea of ​​encapsulation is the same as above. First, add a field in the dictionary structure  encoding to judge the different encryption conditions selected.

 req_data={
            "schema": "http",
            "method": "get",
            "url": "http://127.0.0.1:10000/demo64.txt",
            "headers": None,
            "encoding": "base64"
        }

encodingIt is still possible to select different decryption methods by adding judgment conditions in the structure of the request information  .

class ApiRequest:
    def send(self, data: dict):
        if "http" == data["schema"] :
            res = requests.request(data["method"],data["url"],headers=data["headers"])
            return json.loads(base64.b64decode(res.content))
            #通过请求信息的结构体中的`encoding`,去选择不同的解密方式。
            if data["encoding"] == "base64":
                return json.loads(base64.b64decode(res.content))
            elif data["encoding"] == "private":
                return json.loads(requests.post("url", data=res.content).content)
            else:
                return json.loads(res.content)

Summarize

First of all, it is necessary to clarify what kind of processing method can be used in the face of an encrypted response result:

  1. If you know which general encryption algorithm is used, you can solve it yourself.
  2. If you don't know the corresponding encryption algorithm, you can ask R&D to provide the lib for encryption and decryption.
  3. If it is neither a general encryption algorithm, nor can R&D provide encryption and decryption libs, the encryption party can provide remote analysis services, so that the algorithm remains confidential.

This article mainly talks about how to deal with such a decryption algorithm in the case of understanding the use of encryption algorithms. However, the idea of ​​encapsulation is the same. No matter what kind of situation you are facing, you can specify the content of the data through the formatted data, and encapsulate the encryption, decryption or selected protocol through a layer of logical encapsulation.

Finally: In order to give back to the die-hard fans, I have compiled a complete software testing video learning tutorial for you. If you need it, you can get it for free【保证100%免费】

Software Testing Interview Documentation

We must study to find a high-paying job. The following interview questions are the latest interview materials from first-tier Internet companies such as Ali, Tencent, and Byte, and some Byte bosses have given authoritative answers. Finish this set The interview materials believe that everyone can find a satisfactory job.

Guess you like

Origin blog.csdn.net/jiangjunsss/article/details/131595915