Java interface automation framework series 07: design idea of Web interface automation test framework

1.Java web interface automation framework

Framework Name: Java+Maven+httpClients+TestNg+Allure

(only Java is explained this time, not git and jenkins. If git and jenkins are included, please refer to the general chapter of Java automation framework)

Frame diagram:

Framework idea:

 

2. Analysis interface

CASB interface reference:

https://10.1.1.104/uim/doc.html

https://10.1.1.104/sem/doc.html

https://10.1.1.104/kms/doc.html

2.1.Post methods (such as querying roles)

Here, you need to collect and understand more interfaces, which can be called through Chrome tools or MeterSphere.

Obtain multiple interfaces for comparison. For example, execute all interfaces with user permissions, and get input parameters and return parameters for analysis.

The following examples:

Query role and login are both POST interfaces.

1. Login
 Interface address: / uim/v1/login
 Request method: POST
 Request example:
{
    "username": "",
    "password": "",
    "ukeySn": "",
    "serverRandom": "",
    "ukeySign": ""
}
Return result:
{
    "code": 0,
    "data": {
        "accessToken": "",
        "expiresDate": "",
        "expiresIn": 0,
        "refreshExpiresDate": "",
        "refreshExpiresIn": 0,
        "refreshToken": "",
        "scope": "",
        "tokenType": ""
    },
    "msg": "success"
}
​
2. Query role:
Interface address: / uim/v1/role/list
 Request method: POST
 Request example:
{
    "page": 1,
    "limit": 10,
    "sidx": "",
    "order": ""
}
Response example:
{
    "code": 0,
    "data": {
        "currPage": 0,
        "list": [
            {
                "createTime": "",
                "permissionIdList": [],
                "permissionList": [
                    {
                        "childPermissionList": [
                            {
                                "childPermissionList": [
                                    {}
                                ],
                                "createTime": "",
                                "parentId": "",
                                "parentPermission": {},
                                "permissionId": "",
                                "resourceDescribe": "",
                                "resourceIcon": "",
                                "resourceName": "",
                                "resourceOrder": 0,
                                "resourceRouter": "",
                                "resourceType": 0,
                                "resourceUrls": ""
                            }
                        ],
                        "createTime": "",
                        "parentId": "",
                        "parentPermission": {},
                        "permissionId": "",
                        "resourceDescribe": "",
                        "resourceIcon": "",
                        "resourceName": "",
                        "resourceOrder": 0,
                        "resourceRouter": "",
                        "resourceType": 0,
                        "resourceUrls": ""
                    }
                ],
                "roleDescribe": "",
                "roleId": "",
                "roleName": ""
            }
        ],
        "pageSize": 0,
        "totalCount": 0,
        "totalPage": 0
    },
    "msg": "success"
}

2.2.Get method (for example, delete role)

Request address: / uim/v1/role/delete
Request method: GET
Request parameter: id =
Response example:
{
    "code": 0,
    "data": {},
"msg": "success"
}

All interfaces have request header information, input parameters, interface request and output parameters

1. Input parameters: POST interface, all of which are in JSON format

GET interfaces are parameter input parameters

2. Send and process requests

3. Output parameters: all CASB interfaces are in JSON format

3. Select tool / language

Tools used here: refer to 0 CASB2. 0 interface automation training plan Basic Java knowledge for framework tool classes in the md document.

3.1. Language selection

The Java language is selected here because of encryption and decryption. The plug-in needs to encrypt the database insert data and decrypt the query data through the Java language + plug-in jar package.

Pure web interface automation actually costs less to learn with python or meterSphere.

The Python language supports testng and allure, and reports are more friendly.

3.2. Tool selection for interface

3.2. 1. Send request (HttpClient)

The framework uses CloseableHttpClient.

Tool class: HttpsClientUtils

Here is the HttpClient tool class I wrote, such as the Get and Post methods
    /**
* send HttpGet request without request header and request parameters
* @ param url request address
     * @return doGet(url,null,null)
     */
    public  HttpClientResult doGet(String url) throws Exception {
    }
    
    /**
* send HttpGet request with request header and request parameters
* @ param url request address
     * @param headers ,params
     */
    public  HttpClientResult doGet(String url,Map<String, String> headers,Map<String,String> params) throws Exception{}

    /**
* send POST request without request parameters
* @ param url request address
     * @return doPost(url,headers,null)
     */

    public  HttpClientResult doPost(String url,Map<String, String> headers) throws Exception {
    }
    /**
* send POST request with request parameters
* @ param url request address
* @ param headers request header
* @ param jsonStr request json
     */

    public  HttpClientResult doPost(String url, Map<String, String> headers,String jsonStr) throws Exception {}

3.2. 2. Input parameters of interface

3.2. 2.1. If the input parameter is written directly in the code, there is no need to 2

3.2. 2.2. Obtain the input parameters of the interface through Excel and transfer them

So here you need to learn the tool to read Excel. This framework introduces Ali's easyexcel

Tool class: ExcelUtil

How to write to Excel:
    /**
* write excel
* @ param fileName write the file name of excel
     * @param sheetName
* @ param dataList data
     */
public static void writeExcel(String fileName, String sheetName, List<ApiDataBean> dataList) {}

How to read excel:
    /**
* Read excel and put it into caseDataBean
* @ param fileName read the file name of excel
     * @return datalist
     */
public static List<ApiDataBean> readExcel(String fileName, String sheetName){}

3.2. 2.3. The variable used by the input parameter requires a public parameter to replace the variable

Tool class: ParamUtil

Call: String reqUrl = host + url;
       Map<String, String> headers=getHeader(token);
       String reqData=paramUtil.getCommonParam(data.getParam());
/ / send request
        HttpsClientUtils httpUtil = new HttpsClientUtils();
        HttpClientResult httpResult = httpUtil.doPost(reqUrl, headers,reqData);
      
   /**
* take public parameters and replace them to process ${}
* @ param param @description parameter
     * @return param
     */
    public String getCommonParam(String param) {}

3.2. 3. Output parameter analysis of interface

3.2. 3.1. The interface is simple to parse back parameters. You can directly use Java's JsonPath

reference resources: GitHub - json-path/JsonPath: Java JsonPath implementation

3,2.3. 2. Complex interface back parameter resolution

It needs to be written by yourself (there are four methods for Json parsing, and I choose the gson used here)

Call, for example:
    String roleId = JsonUtil.getTargetValue(resultContent, roleName, "roleName", "roleId");    

    /**
     * Parse the json tree structure of the first layer, only JsonObject, and obtain the value of a key in the json of the first layer
     * @param jsonString json character string
     * @param dataKey key
     */
    public static String gsonParserString(String jsonString,String dataKey){}
    
        /**
     * Parse the layer-2 json tree structure, only JsonObject, and obtain the value of a key in the layer-2 json
     * @param jsonString  json character string
     * @param dataKey key
     */
    public static String gsonParserString_2(String jsonString,String dataKey){}
    
        /**
     * Parse the three-tier tree structure with a JsonArray(list) to obtain the value of the specified key of the first json in the list in the third tier json
     * @param jsonString json character string
     * @param dataKey (Get the list in data (String type)
     */
    public static String gsonParserString_3l(String jsonString,String dataKey){}
    
        /**
     * Parse the four layer tree structure with two jsonarrays to obtain all the values of the specified key in the layer 4 json list
     * @param jsonString json character string
     * @param dataKey (Get the list in data (String type)
     */
    //For (jsonelement element: jsonarray) traverses the data
    public static List<String> gsonParserString_4l(String jsonString, String list1,String list2,String dataKey){}
    
        /**
     * Parse the three-tier tree structure with a JsonArray(list), and find the value of key2 in the same json that matches the value of key1 in the third tier json
     * @param jsonString json character string
     * @param targetKey (Get the list in data (String type)
     */
    public static String getTargetValue(String jsonString,String sourceName,String sourceKey,String targetKey){}  

For the other three Json treatments, please refer to: Detailed explanation of the four JSON parsing methods in JAVA - I understand the truth Zz - blog Garden

3.3. Single interface debugging tool class

3.3.1.POST interface

For example: login

 String loginUrl = "https://10.1.1.104/uim/v1/login";
    String jsonStr = "{\"username\":\"YWRtaW4=\",\"password\":\"bGlhblNoaTIwMjA=\"}";
    //Request header
    Map<String, String> headers=new HashMap<>();
    headers.put("Content-Type","application/json;charset=UTF-8");
    //Send request
    HttpsClientUtils httpUtils = new HttpsClientUtils();
    HttpClientResult result=httpUtils.doPost(loginUrl,headers, jsonStr);

All codes:

package com.ciphergateway.server;

import com.ciphergateway.bean.HttpClientResult;
import com.ciphergateway.utils.Base64Util;
import com.ciphergateway.utils.HttpsClientUtils;
import com.ciphergateway.utils.JsonUtil;
import com.ciphergateway.utils.PropertiesUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

//import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;


public class Login {
    private static final Logger log= LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);


    /**
     * Get the token of login
     */
    public String getToken() throws Exception{
        //Get profile
        String filename="config.properties";
        PropertiesUtil pro=new PropertiesUtil(filename);
        String host=pro.readProperty("HOST");
        String username=pro.readProperty("USER_NAME");
        String password=pro.readProperty("USER_SECRET");
        Base64Util base64=new Base64Util();
        String user_base64 = base64.getBase64(username);
        String password_base64 = base64.getBase64(password);

        //Test HTTPS
        HttpsClientUtils httpUtils = new HttpsClientUtils();
        String loginUrl = host+"/uim/v1/login";
        String jsonStr = "{\"username\":\"" + user_base64 + "\",\"password\":\"" + password_base64 + "\"}";
        //System.out.println(jsonStr);
        //Request header
        Map<String, String> headers=new HashMap<>();
        headers.put("Content-Type","application/json;charset=UTF-8");

        HttpClientResult httpResult= null;
        try {
            httpResult = httpUtils.doPost(loginUrl, headers,jsonStr);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e);
        }
        //System.out.println(httpResult.getCode());
        //System.out.println(httpResult.getContent());
        int code=httpResult.getCode();
        String resultContent=httpResult.getContent();
        log.info(code+" "+resultContent);

        String token =JsonUtil.gsonParserString_2(resultContent,"accessToken");

        return token;
    }


/*    public static void main(String[] args) throws Exception {
        Login lo=new Login();
        String token=lo.getToken();
        System.out.println(token);

    }*/
}

3.3.2.GET method (delete role)

String reqUrl ="https://10.1.1.104/uim/v1/role/delete";
     Map<String, String> map_delete = new HashMap<>();
     map_delete.put("id", "1234567890212222");
     Map<String, String> headers=new HashMap<>();
     headers.put("Content-Type","application/json;charset=UTF-8");
     headers.put("Authorization",token);
     //Send request
     HttpsClientUtils httpUtils = new HttpsClientUtils();
     HttpClientResult httpResult = httpUtils.doGet(reqUrl, headers, map_delete);

3.4. Assertions (TestNg unit test framework)

You need to use the TestNg unit test framework for batch testing, asserting and initializing data and cleaning data. three

Batch test: testng.xml
 Initialization data:@BeforeTest
 Test:@Test
 Clean up data:@AfterTest
 Assertion: Assert
 For example:
1,TestNg Default assertion:
Assert.assertEquals(code, expectData, data.getDesc());
2,Assertions added for exception scenarios:
Assertion.verifyEquals(code, expectData, data.getDesc());

3.5. Results and report presentation

3.5.1Excel test results

remarks: dataList_w yes List<ApiDataBean>parameter
        //Call excel method to write data
        String excelFile_result="src/data/testcase/apiData_result.xlsx";
        private String sheet1="User permission interface use case";
        ExcelUtil.writeExcel(excelFile_result,sheet1,dataList_w);

3.5.2.Allure Report

Refer to configuration and use of Web interface automation Allure report

https://blog.csdn.net/fen_fen/article/details/122020651

4. Summary

4.1. Tools / frameworks used by the web interface framework

Serial numberTool or frame nameedition
1Mavenapache-maven-3.8.1
2httpClienthttpClient 4.5.3
3TestNGTestng 6.11
4Allure test reportAllure 2.13.2
5GitStone smelting git

4.2. Advantages of framework

1. Data driven method is adopted to solve the test of a large number of functional repeatability interfaces

2. Code layering

3. For the returned JSON string, the combination of JSONPath and Gson is used to accurately determine the content of JSON.

4. You can generate more intuitive reports.

5. In the later stage, it can continue to integrate with Jenkins, generate test reports based on the execution results, and send emails to inform relevant personnel.

Keywords: Java Front-end

Added by andym01480 on Mon, 20 Dec 2021 04:57:18 +0200