Proficient in api interface testing, interface classification, interface architecture, http, webservice, dubbo interface protocol, interface process, interface tools, cookie, session, token interface authentication principles and actual combat

One, [What is interface testing? Why do interface testing]

Interface testing and interface automation testing have always been confusing concepts for many people. So it is very important to understand the concept of 2.
Interface: A piece of program code with logic processing functions, which can be used by other methods, services or applications.
For the party that calls the interface, the interface can be regarded as a black box. It only needs to be responsible for passing in parameters according to the agreement, and then receives the returned data, without knowing the logic in the black box.

1. The role of the interface

  • 1. System-to-system calls. For example, UnionPay will provide a payment interface to be called by the application responsible for the three-party payment. When the user initiates a payment request, the application will pass the relevant necessary parameter values ​​to the UnionPay server through the payment interface. After the UnionPay server completes the processing, it will call the callback of the application. Interface, returns the payment processing result.
  • 2. The front-end application calls the back-end service. For example, the application program calls the interface of the server, and the server calls the interface of DAO [data access object data access object]. From the perspective of a certain system, the application itself mainly includes two parts: one is interaction, and the other is data display. The application program obtains the corresponding data from the database through the interface of the data access object, and the server-side interface processes the data accordingly and finally returns it to the application program, and the application program displays it.
  • 3. Calls between services. For example, a registered user will first call the service of querying user information to check whether it has been registered. If it returns registered, the interface responsible for the registered user will return the result to the previous page.
  • Interface testing is a test for testing the interface between system components, and is mainly used to detect the interaction points between external systems and internal subsystems. The focus of the test is to check the data interaction, transfer and control management process, and the mutual logical dependencies between the systems.

2. Why do interface tests

  • 1. It is difficult to ensure high coverage only by front-end testing. The interface test can simulate various types of input parameters, including some input parameters that cannot be simulated at the front end. It can also design relatively complete input parameter values ​​according to the definition of the interface document, and ensure the quality at the interface layer. Most of the problems are the interaction and data display problems of the application itself.
  • 2. Compared with interactive interface testing and functional testing, interface testing is easier to automate, more stable in execution, and lower in maintenance costs.
  • 3. Interface automation is suitable for regression testing, etc., which can reduce the labor cost of manual regression testing.
  • 4. The front-end and back-end systems are separated. From the perspective of security, only relying on the front-end cannot meet the security requirements. It is relatively easy to bypass the front-end, so the back-end needs to also perform input verification, which can only be verified by interface testing.

3. What types of interfaces are there?

Interfaces are generally divided into two types: 1. Internal interfaces of the program 2. External interfaces of the system

The external interface of the system: For example, if you want to obtain resources or information from other websites or servers, others will definitely not share the database with you. They can only provide you with a method they have written to obtain data, and you quote it. The interface can use the method he wrote, so as to achieve the purpose of data sharing.

The interface inside the program: the interaction between methods, between modules and modules, the interface thrown inside the program, such as the bbs system, there are login modules, posting modules, etc., then you must log in first if you want to post, then this The two modules have to interact, and it will throw an interface for the internal system to call.

2. [Classification of Interface Tests]

Classification of interfaces:

1. webservice interface

2. http api interface

The webService interface is transmitted through http through the soap protocol. Both the request message and the return message are in xml format. We only use the passing tool to perform the call test when testing.

webService uses protocols such as soup, rmi, and rpc

The http api interface uses the http protocol to distinguish calls through paths. Request messages are in the form of key-value, and the returned messages are generally json strings. There are methods such as get and post, which are also the most commonly used two request method.

JSON is a universal data type that all languages ​​recognize. (The essence of json is a string. It has nothing to do with other languages. It can only be converted into data types in other languages ​​after a little processing. For example, it can be converted into a dictionary in Python, and the form of key-value can be converted into native in JavaScript. Object, can be converted into a class object in java, etc.)

The difference between http and webservice interface:

Httpservice gets what you want through post and get.
Webservice uses the soap protocol to get what you want. Compared with httpservice, it can handle more complex data types.

The http protocol transmits strings, while webservice is packaged into more complex objects.

 Three, [understand http, webservice, Dubbo interface protocol]
 


1. Interface

API: Application Programming Interface, application programming interface

1) Interface classification

Hardware interface: with connection function and adaptation. The connection method between two hardware devices (for example, the mouse and the computer are connected through the USB interface)

Software interface: the channel for data interaction between software programs (the user interface is the software interface)

2) Software interface classification

Program internal interface: it is the interface between the client and the server, used to realize the data transfer between the client and the server

External interface: such as logging in through a third party, third-party payment, and returning to the current system by calling the external interface

3) Common interface protocols

webService interface: use the soup protocol to transmit through http, the request message and the return message are both in xml format, and the commonly used testing tool is soupUI

http protocol interface: currently the most widely used, using the HTTP protocol to transmit data, common request methods include get, post, etc., commonly used testing tools include postman, jmeter

Dubbo, websocket, ws://..., ftp:// and other protocols.

4) Interface test

The essence is to send a request to the server based on a certain protocol, and then the server returns a response, and then analyzes the response data to determine whether it is consistent with our expected return, so as to verify whether the function is correct.

Two, HTTP protocol interpretation

1) http protocol: hypertext transfer protocol

2) https: Simply put, it is the secure version of http, adding the SSL layer under http (the secure transmission protocol for the main user web of SSL)

3) The default port number of http is: 80, the default port can be omitted in the url

 The default port number of https is: 443, the default port can be omitted in the url

4) HTTP request process

Client: PC-side application browser APP applet

HTTP communication: request information sent by the client to the server

       The response information returned by the server to the client

Client: front end -----> active request. The client that can initiate the corresponding request.

Server: backend -----> passive acceptance.

 

  

  Extension URL:

5) HTTP request information

请求行: 请求方法/请求网址/协议版本
请求头部:header
host
connection
upgrade-insecure-requests
user-agent:用户代理,通过客户端代理
referer
accept-encoding
cookie
备注:域名和IP地址之间是映射关系,域名是为了好记
Request data:

 

6) HTTP response information

Status line: status code 
Message header: 
  content-type: returned data format 
    test/html 
    application/json 
    application/xml 

response body:

7) HTTP response status code

状态码           含义                 客户端client                                 服务器端server 
1xx      | Informational 信息     啥都不用做,知道就好                          信息收到了,后续会处理                               
2xx      | Successful 成功        啥都不用做,知道就好                          请求已正确处理                                               
3xx      | Redirection 重定向     重新请求返回的新地址                          client需要的内容,由于一些原因,比如地址已发生变化了,然后返回该内容的新地址 
4xx      | 客户端的错误            确保用正确的参数和信息正确,重新请求             请求已正确处理                               
5xx      | 服务器端的错误           都无需操作,服务器端改了bug后,重新发送请求      服务器端的代码的bug导致了出错

8) HTTP request method

The difference between get and post:

a) Different application scenarios

  get get resources

  Post submits data, creates new data/modifies existing data

 

b) Parameter storage 

  The parameters of the get request can be displayed on the browser URL, and the query string is passed through ?param=value [that is, the query string method]

  post can use query string, but usually not, usually put it in the body request body

c) Security

Neither get nor post is more secure. You can see the data in the packet capture. It is said on the Internet that the post is more secure because the data is placed in the body and cannot be seen by the naked eye. But it is not safe, and the get request It is directly visible to the naked eye in the URL

Note: Encryption has nothing to do with the request method, everything can be encrypted

[WebService protocol]

Both http and webservice are application layer protocols based on the TCP/IP protocol

Webservice is based on the http-based soap protocol to transmit data webservice=soap=http+xml, the webservice protocol is composed of http+xml, where wsdl is used in xml, and wsdl is a format in the description language xml.

Socket is a transmission protocol based on TCP/IP, which is the encapsulation of TCP/IP protocol

Both socket and TCP are based on the TCP/IP transport layer protocol

Note: Restful is an interface specification, not an interface protocol. The http protocol is also used in the restful interface specification.

 Because most of them now use the http protocol instead of the webservice protocol, so there is no actual operation, just reproduced to understand the theory.

1. Creation of WSDL WebService:

1. Create [Web Service Project]:

image.png

WebServices Framework should choose JAX-WS:

image.png

2. Write a simple test case:

package com.webservice;

public class WebService{

public String printData(String printerName){
    String strRet = "Welcome to use WebService, " + printerName;
    
    System.out.println("Print from WebService:" + strRet);
    
    return strRet;
}   

3. Publish Web Service:
Click New Web Service on the toolbar:

image.png

Strategy chooses the second one (Create web service from Java class):

 

image.png

Check [Generate WSDL in project]:

 

image.png

After clicking [Finish], the system will generate two files under WEB-INF/wsdl:

 

image.png
 
WebServiceService.wsdl:这个文件是用来描述Web Service内容的
<?xml version="1.0" encoding="UTF-8"?>
 
<definitions xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://webservice.com/" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="WebServiceService" targetNamespace="http://webservice.com/">
<types>
<xsd:schema>
<xsd:import namespace="http://webservice.com/" schemaLocation="WebServiceService_schema1.xsd"/>
</xsd:schema>
</types>
<message name="printData">
<part element="tns:printData" name="parameters"/>
</message>
<message name="printDataResponse">
<part element="tns:printDataResponse" name="parameters"/>
</message>
<portType name="WebServiceDelegate">
<operation name="printData">
<input message="tns:printData"/>
<output message="tns:printDataResponse"/>
</operation>
</portType>
<binding name="WebServicePortBinding" type="tns:WebServiceDelegate">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="printData">
<soap:operation soapAction=""/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
</binding>
<service name="WebServiceService">
<port binding="tns:WebServicePortBinding" name="WebServicePort">
<soap:address location="http://localhost:8080/WebService/WebServicePort"/>
</port>
</service>
</definitions>
 
WebServiceService_schema1.xsd:用来说明Web Service的命令及其参数
比如:sample里面的WebService是【printData】,有一个String类型的参数【arg0】,返回值一个String类型的值。
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://webservice.com/" targetNamespace="http://webservice.com/" version="1.0">
 
<xs:element name="printData" type="tns:printData"/>
 
<xs:element name="printDataResponse" type="tns:printDataResponse"/>
 
<xs:complexType name="printData">
<xs:sequence>
<xs:element minOccurs="0" name="arg0" type="xs:string"/>
</xs:sequence>
</xs:complexType>
 
<xs:complexType name="printDataResponse">
<xs:sequence>
<xs:element minOccurs="0" name="return" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:schema>

 Just deploy the WebService project to Tomcat.
(The deployment method is omitted)

2. Calling WSDL WebService:
Method 1: Create a Web Service Client to call:
1. Create a [Java Project]:

image.png

2. Click New Web Service Client on the toolbar:

image.png

 

image.png

3. Select [WSDL URL]:

image.png

4. After clicking [Next] to complete the creation, the relevant files will be automatically generated under src/com/webservice. (Except for WebServiceTest.java, this is the calling file created by myself)

image.png

5. Create【WebServiceTest.java】

 

image.png

The code is as follows:
package com.webservice;

public class WebServiceTest{

public static void main(String[] args){
    WebServiceService wssPrintData = new WebServiceService();
    WebServiceDelegate wsdPrintData = wssPrintData.getWebServicePort();
    
    System.out.println(wsdPrintData.printData("sun"));
}   

}

6.【WebServiceTest.java】Right click→Run As→Java Application
Output result:
Welcome to use WebService, sun

Method 2: Call with HttpClient:

package com.httpclientforwsdl;
 
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
 
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
 
public class WebServiceHttpClientTest{
   
   
public synchronized static String accessService(String wsdl,String ns,String method,Map<String,String> params,String result)throws Exception{  
    //拼接参数  
    String param = getParam(params);  
    String soapResponseData = "";  
    //拼接SOAP  
    StringBuffer soapRequestData = new StringBuffer("");  
    soapRequestData.append("<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");  
    soapRequestData.append("<soap:Body>");  
    soapRequestData.append("<ns1:"+method+" xmlns:ns1=\""+ns+"\">");  
    soapRequestData.append(param);  
    soapRequestData.append("</ns1:"+method+">");  
    soapRequestData.append("</soap:Body>" + "</soap:Envelope>");  
    PostMethod postMethod = new PostMethod(wsdl);  
    // 然后把Soap请求数据添加到PostMethod中  
    byte[] b=null;  
    InputStream is=null;  
    try {  
        b = soapRequestData.toString().getBytes("utf-8");   
        is = new ByteArrayInputStream(b, 0, b.length);  
        RequestEntity re = new InputStreamRequestEntity(is, b.length,"text/xml; charset=UTF-8");  
        postMethod.setRequestEntity(re);  
        HttpClient httpClient = new HttpClient();  
        int status = httpClient.executeMethod(postMethod);  
        System.out.println("status:"+status);  
        if(status==200){  
            soapResponseData = getMesage(postMethod.getResponseBodyAsString(),result);  
        }  
    } catch (Exception e) {  
        e.printStackTrace();  
    } finally{  
        if(is!=null){  
            is.close();  
        }  
    }  
    return soapResponseData;  
}  
  
public static String getParam(Map<String,String> params){  
    String param = "";  
    if(params!=null){  
        Iterator<String> it  = params.keySet().iterator();  
        while(it.hasNext()){  
            String str = it.next();  
            param+="<"+str+">";  
            param+=params.get(str);  
            param+="</"+str+">";  
        }  
    }  
    return param;  
}  
  
public static String getMesage(String soapAttachment,String result){  
    System.out.println("message:"+soapAttachment);  
    if(result==null){  
        return null;  
    }  
    if(soapAttachment!=null && soapAttachment.length()>0){  
        int begin = soapAttachment.indexOf(result);  
        begin = soapAttachment.indexOf(">", begin);  
        int end = soapAttachment.indexOf("</"+result+">");  
        String str = soapAttachment.substring(begin+1, end);  
        str = str.replaceAll("<", "<");  
        str = str.replaceAll(">", ">");  
        return str;  
    }else{  
        return "";  
    }  
}  
  
/** 
 * @param args 
 */  
public static void main(String[] args) {   
    try {  
        Map<String,String> param = new HashMap<String,String>();  
        param.put("arg0", "sun");
        String wsdl="http://localhost:8080/WebService/WebServicePort?wsdl";  
        String ns = "http://webservice.com/";  
        String method="printData";  
        String response =accessService(wsdl,ns,method,param,"return");  
        System.out.println("main:"+response);  
          
    } catch (Exception e) {  
        e.printStackTrace();  
    }  
}  

Show results:

status:200
七月 15, 2016 3:43:27 下午 org.apache.commons.httpclient.HttpMethodBase getResponseBody
警告: Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.
message:<?xml version="1.0" ?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><ns2:printDataResponse xmlns:ns2="http://webservice.com/"><return>Welcome to use WebService, sun</return></ns2:printDataResponse></S:Body></S:Envelope>
main:Welcome to use WebService, sun

[Dubbo interface test method]

1. Directly connect to telnet and then use the dubbo protocol to call the method

(1) You can see it in the configuration file of the project

dubbo.protocol.port=10022

It shows that the port exposed by dubbo is 10022, and you can directly access this port with telnet.

telnet lcoalhost 10022 and you can see

Indicates that the connection is successful.

  1. View services with ls

  1. Check the methods under the service ls -l

  1. Then use invoke to test the interface. Note here that the pom needs to add the fastjson dependency, otherwise it will report Invalid json argument, cause: com/alibaba/fastjson/JSON dubbo

2. Idea plugin dubbo Invoke

In the idea plug-in supermarket, I found that dubbo invoke integrates invoke.

  1. Download and install the plugin DubboInvoke

  1. Add annotations to methods exposed externally

/**
 *
 * @param name 姓名
 *             example=haha
 * @return
 */
String sayHello(String name);

 

  1. Call, click where this interface appears

Choose to use the plug-in, here note that serverAddress is the service ip port of dubbo.

 

Then click invoke to see the generation test results.

Four, [Http protocol details]

Detailed explanation of Http protocol

think:

The user opens a browser, enters a URL, and sends data to the server. How should the data be sent?

If each website has its own rules, the entire Internet will be messed up, and user access will not be very convenient. Each website must develop its own client software, resulting in greater operating costs.

Therefore, there must be a unified rule for everyone to have a basis for sending data or receiving data, so the HTTP protocol comes from this.

1. Introduction to HTTP protocol

1. Introduction to HTTP protocol

The HTTP protocol is the abbreviation of Hyper Text Transfer Protocol (Hypertext Transfer Protocol), which is a transmission protocol for transmitting hypertext between a World Wide Web (WWW: World Wide Web) server and a local browser.

HTTP is an object-oriented protocol belonging to the application layer. It is suitable for distributed hypermedia information systems due to its simple and fast method. It was proposed in 1990, and after several years of use and development, it has been continuously improved and expanded. The HTTP protocol works on a client-server architecture. As an HTTP client, the browser sends all requests to the HTTP server, that is, the WEB server, through the URL. The web server sends response information to the client according to the received request.

image-20200924172049937

Using the HTTP protocol, whenever a new request is sent, a corresponding new response will be generated. The protocol itself does not retain information about all previous request or response messages. This is to process a large number of transactions faster and ensure the scalability of the protocol, and the HTTP protocol is deliberately designed to be so simple. However, with the continuous development of the Web, there are more and more difficult business processes due to statelessness. For example, if a user logs in to a shopping website, even after he jumps to other pages of the site, he needs to be able to continue to log in. For this example, in order to be able to grasp who sent the request, the website needs to save the user's state. Although HTTP/1.1 is a stateless protocol, in order to achieve the desired state-keeping function, Cookie technology is introduced. With cookies and then using the HTTP protocol to communicate, the state can be managed. We will explain the details about cookies later.

2. What is the HTTP protocol

  • Hypertext Transfer Protocol, which specifies the format of data interaction between the browser and the server
  • Use the browser as an HTTP client to send all requests to the HTTP server, that is, the WEB server, through the URL.
  • If the server does not follow this protocol, then you need to develop a client yourself to allow users to download the web application and access it through the web application. Otherwise, the user cannot access your web application through the browser.

Two, the four major characteristics of the HTTP protocol

1. Application layer protocol based on TCP/IP protocol

2. Based on the request-response model

The HTTP protocol stipulates that: the request is sent from the client, and finally the server responds to the client request and returns

That is to say, the user accesses data and establishes communication from the client first, and the server will not send data and respond to the client until it receives the request.

image-20200924172118199

3. No state saving: do not save user information state

HTTP is a stateless protocol that does not save state . The HTTP protocol itself does not save the communication state between the request and the response . That is to say, at the HTTP level, the protocol does not .

Summary: I have seen you thousands of times, and I always treat you like first love.

image-20200924172149501

Using the HTTP protocol, whenever a new request is sent, a corresponding new response will be generated. The protocol itself does not retain information about all previous request or response messages.

effect:

  • In order to process a large number of transactions faster and ensure the scalability of the protocol , the HTTP protocol is deliberately designed to be so simple.

question:

  • With the continuous development of the Web, business processing has become more difficult due to statelessness
  • For example, if a user logs in to a shopping website, even after he jumps to other pages of the site, he needs to be able to continue to log in. For this example, in order to be able to grasp who sent the request, the website needs to save the user's state. how to achieve

solve:

  • Although HTTP/1.1 is a stateless protocol, in order to achieve the desired state-keeping function, Cookie technology is introduced .
  • With cookies and then using the HTTP protocol to communicate, the state can be managed.

 

4. No (short) connection

The meaning of connectionless is to limit each connection to only process one request. After the server finishes processing the client's request and receives the client's response, it disconnects . That is: the server responds once the client requests a request, and there is no relationship after that.

Effect: This method can save transmission time.

solution:

  • Later, websocket can be used to achieve long connection, which allows the two parties to establish a connection and not disconnect by default (this is what QQ and WeChat chat use)

3. HTTP request protocol and response protocol

Since the HTTP protocol specifies the communication format between the client and the server, the http protocol includes the request protocol that the browser needs to follow to send data to the server and the request protocol that the server needs to follow when sending data to the browser.

How does the HTTP protocol specify the message format?

First of all, let's hand a socket server

Simple socket server:

import socket
 
server = socket.socket()  # 默认就是基于网络的TCP协议
server.bind(("127.0.0.1", 8888))
server.listen(5)
while True:
    conn, addr = server.accept()
    data = conn.recv(1024)
    print(data)  # 将请求数据的打印出来
    conn.send(b"ok")
    conn.close()

 Then run the socket server to see, enter in the browser URL: 127.0.0.1:8888, the socket server will receive the following data:

b'GET / HTTP/1.1\r\n              ## 请求首行
Host: 127.0.0.1:8080\r\n          ## 请求头 (下面都是,一大堆的K:V键值对)
Connection: keep-alive\r\n
Cache-Control: max-age=0\r\n
Upgrade-Insecure-Requests: 1\r\n
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3823.400 QQBrowser/10.7.4307.400\r\n
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\n
Accept-Encoding: gzip, deflate, br\r\n
Accept-Language: zh-CN,zh;q=0.9\r\n
Cookie: csrftoken=WCzjKvmjOSdJbYKs0uIfPtiFfLl04FENb6p9CjypP7ZObcUpydaQPLZN0qPOVqwj\r\n
\r\n'     ## 换行
b''       ## 请求体
 

 

  • The messages used for HTTP protocol interaction are referred to as HTTP messages . The HTTP message of the requesting end (client) is used as a request message, and the HTTP message of the responding end (server) is used as a response message.
  • The HTTP message itself is a word text composed of multiple lines of data

image-20200924172222493

Then let's visit CSDN again to check the corresponding data received by the browser: Right-click on the web page to check ---->Network---->Click the URL of the current web page---->Headers----- >View Response Headers

image-20210315192622788

1. Request protocol

1.1 Request format

image-20200924172250257

 

 

The request format of the HTTP GET method

  • Format specification:
// 请求首行 : 请求方法, 协议版本...
// 请求头 : 一大堆的 k:v 键值对
// 空行 \r\n : 用来标识作用
// 请求体 : 并不是所有的请求方法都有, 只要用来携带敏感性数据(get没有,post有)

 

img

  • Request method:

    1. "get" request: request data from the server (example: enter the URL to get the corresponding content)
    2. "post" request: submit data to the server (for example: log in, enter username and password, submit to the server for verification)
  • The difference between get and post
    1. 都可以携带额外的参数 : 
        // GET 提交的数据会放在URL之后,以"?"分割URL和传输数据,参数之间以"&"相连
        // POST方法是把提交的数据放在HTTP包的请求体(Body)中.
    2. 提交的数据大小限制 : 
        // 浏览器对URL长度有限制, 所以GET提交的数据大小有限制
        // POST方法没有数据大小限制
    3. 数据的安全性 : 
        // GET方式提交数据, 会带来安全问题, 比如一个登录页面, 通过GET方式提交数据时, 用户名和密码将出现在URL上
        // 如果页面可以被缓存或者其他人可以访问这台机器, 就可以从历史记录获得该用户的账号和密码
     

2. HTTP response

After the server receives the HTTP request from the client, according to the action requirements in the HTTP request, the server takes specific actions and responds to the client with the result, which is called an HTTP response.

2.1 Request format

 

image-20200924172428894

format description

// 响应首行 : 响应状态码, 协议版本....
// 响应头 : 一大堆 k:v 键值对
// 空行 \r\n : 用来标识作用
// 响应体 : 响应正文, 展示给用户的数据

img

  • The HTTP response consists of three parts: status line, response header, and response body;
  • Status line: including protocol version Version, status code Status Code, response phrase;
  • Response header (server header): including the software to build the server, the time to send the response, the format of the response data and other information, including the HTTP status code (HTTP Status Code);
  • Response body: It is the specific data of the response.

Response status code description:

The HTTP status code consists of three decimal numbers. The first decimal number defines the type of the status code, and the last two numbers have a classification function. Different status codes represent different meanings.

image-20200924172516228

// 用简单的数字来表示一串中文意思(状态或者描述性信息)
1XX : 1开头的,服务端已经接受到你的数据正在处理,你可以继续提交
2XX : 200 OK>>> : 请求成功
3XX : 重定向(当你在访问一个需要登陆之后才能看的页面你会发现会自动跳转到登陆页面)
4XX : 403当前请求不符合条件(没有权限), 404请求资源不存在
5XX : 服务器内部错误,无法完成请求

 ps : In addition to the response codes mentioned above, the company will also customize its own status codes

4. URL Uniform Resource Locator

The uniform resource locator is a concise representation of the location and access method of resources that can be obtained from the Internet, and is the address of standard resources on the Internet. Every file on the Internet has a unique URL, which contains information indicating where the file is located and what the browser should do with it

Format:

Protocol: //IP:port(80)/path?name=lqz&age=18

? The previous one is the request path, ? After that is the request data part

form: scheme:[//[user:password@]host[:port]][/]path[?query-string][#anchor]

 Note: Boxes are optional

  •  scheme : protocol (eg: http, https, ftp)
  • user : password@user's login name and password
  • host : IP address or domain name of the server
  • port : The port of the server (if it is the default port of the protocol, http 80 or https 443)
  • path : the path to access the resource
  • query-string: parameter, which usually uses key-value pairs to formulate the data sent to the http server
  • anchor : anchor (jump to the specified anchor position of the web page)

Write an interface test plan

The goals of the interface test plan and the functional test plan are the same, both are to determine the requirements, determine the test environment and test methods, prepare for the design of test columns, and initially formulate the interface test progress plan. Generally speaking, the interface test plan includes an overview, test resources, test functions and key points, test strategies, test risks, and test standards.

Write and review interface test cases

Similar to the functional test, before starting the interface test, it is necessary to write and review the interface test cases according to the project-related documents such as ball requirements documents and interface documents. The interface idea is shown in the figure:

Execute interface tests

According to the written interface test cases, implement the interface test with the help of testing tools (such as Postman, JMeter, SoapUI), and report the found problems.

Key points of continuous integration of interface automation

During project testing, interfaces will be added, decreased, or changed, and test cases will be updated accordingly. Therefore, tools (such as GitHub, etc.) are needed to maintain test cases for continuous integration, and monitor the operation of project interfaces in real time through automated testing. For interface testing, continuous integration is the core content, and only by means of automation can low-cost and high-yield be achieved. The continuous integration of interface automation testing mainly includes the following contents:
(1) In terms of process: In the regression phase, the coverage of interface exception scenarios is strengthened, and gradually extended to the system testing and smoke testing phases, and finally achieves full process automation.
(2) Result display: richer result display, trend analysis, quality statistics and analysis, etc.
(3) Problem location: Error information and logs are more accurate, making it easier to reproduce and locate problems.
(4) Result verification: Strengthen automatic verification capabilities, such as database information verification.
(5) Code coverage: Constantly try to drop from the current black box to the white box to improve the code coverage.
(6) Performance requirements: improve the performance testing system, and monitor whether the interface performance indicators are normal through automated means.

 -----------------------

Interface testing process and use case design

Interface testing is a very important part of the entire project testing process. The object of the test is the interface, so you can intervene in the test very early, fully verify the code logic, and find program problems earlier, which is more efficient than UI testing. And it is easier to verify extreme and unusual cases.

Interface testing process:

Similar to the functional testing process, a complete interface testing process is as follows:

  1. Analyze interface documents and requirements documents
  2. Write an interface test plan
  3. Write interface test cases
  4. Interface Test Execution
  5. Output interface test report.

The general interface use case design is based on the interface documents and product requirements documents provided by the development. First, get acquainted with the interface documents.

interface documentation

An example of how an interface document describes a specific interface information is as follows:

interface documentation

It mainly includes the following parts:

  • Interface Description
  • request method
  • Request URL
  • request parameters
  • return data
  • return instance

 

Interface Use Case Design Principles

The principle of the interface test is to simulate the process that the client sends a request message to the server, the server processes the corresponding message after receiving the request message and returns a response to the client, and the client receives the response.

The method used in interface testing is actually consistent with black-box testing, and interface testing can even be understood as functional testing without an interface. It’s just that there are more test points for interface testing. In addition to various functional points that need to be verified on the interface, it also includes interface security and interface performance.

The design of general test cases should range from the verification of single interface parameters to the verification of the entire business function point, and some security and abnormal situations can also be verified.

The basic principles of interface use case design points are as follows:

 

Interface test case design principles 

 

How to determine the coverage of use cases?

How to quickly evaluate your test case coverage: 1) Whether the parameter verification is complete (including various boundaries and business rules) 2) Whether the business requirement point coverage is complete (single interface business function, dependent on interface business function) 3) Interface exception scenario coverage Is it complete (abnormal data,)

 

A general interface use case should include the following parts:

Use case number, module name, interface name, use case title, request method, request URL, request parameters (including request header and request body), expected results, actual results, etc.

Not all of them are required. According to the increase or decrease of actual usage, an actual use case template is as follows:

Interface test case

------------

1. Interface use case template

When it comes to test cases, we know that the two most important elements are: test steps and expected results. In fact, the same is true for interface testing. In the steps of interface testing, the most important thing is to realize the sending of preset requests to the interface, and the results should focus on the response information and subsequent processing. Therefore, the interface test case layout can consider the following two forms. It should be noted that in actual work scenarios, we may also test the concatenation and mixing scenarios between interfaces.

2. Test report template

The interface test report is often combined with the interface performance test report. If you want to report separately, you can consider the following:

 

Briefly describe some background information related to the test project, such as the introduction of the system under test, the project launch plan, etc. The definition and design of the system interface are introduced. For example, how many interfaces does the system have? Which protocol to use? What delivery methods are involved? What is the request format? What return criteria to use? Table description available. The description of the purpose, scope and objectives of this interface test should be consistent with the corresponding content in the "Interface Test Implementation Plan" of this interface test.

The purpose of the test is to ensure that the system interface functions and logic processing have been verified, conform to the definition and requirements of the "Interface Definition Manual", and meet the needs of the system. The test objects are mainly divided into single-scenario interface function test and mixed-scenario interface function test. From this point, you can consider posting the x-mind diagram from "Project Interface Test Cases".

Among them, the scope of test indicators is mainly divided into the received request and returned message of the tested interface, the returned status of the tested interface, the corresponding business logic processing of the tested interface, the processing involving data precipitation, and the serial interaction of multiple interfaces in complex scenarios. Then the test tool will use Postman, and Postman is an interface test plug-in of Google. It is easy to use, supports use case management, supports get, post, file upload, response verification, variable management, environment parameter management and other functions, and can be run in batches. And support use case export and import.

test resources

Test records can be divided into single-scenario interface tests and test result data. Then combine the problems found in the test to analyze the overall test results and make a judgment. These problems include interface business function error defects, interface exception handling defects, interface processing data precipitation defects and interface security defects.

The mixed scene interface test includes the test result data and the test result data of this mixed scene interface test.

 

After analyzing the overall test results and making judgments based on the problems found in the test, the general conclusion of the performance test can be drawn. Generally, the comparison between the test result and the test target is used as the test conclusion.

------

1 project address

    https://gitee.com/HUJIAFANGFUJIDDD/vue_api_server.git

2 deployment

  #cd /usr/local

#git clone https://gitee.com/HUJIAFANGFUJIDDD/vue_api_server.git (If git is not installed, first yum install git -y)

3 Install npm and node environment
 

wget https://npm.taobao.org/mirrors/node/v14.15.3/node-v14.15.3-linux-x64.tar.xz
 
xz -d node-v14.15.3-linux-x64.tar.xz
 
tar -xvf node-v14.15.3-linux-x64.tar
 
cd node-v14.15.3-linux-x64
 
# 建立软连接,变为全局
 
ln -s /usr/local/nodejs/node-v14.15.3-linux-x64/bin/npm /usr/local/bin/
 
ln -s /usr/local/nodejs/node-v14.15.3-linux-x64/bin/node /usr/local/bin/
 
vim /etc/profile
 
# 以下两个路径为加入nodejs路径
 
export NODE_HOME=/usr/local/nodejs/node-v14.15.3-linux-x64
 
export PATH=$NODE_HOME/bin:$PATH
 
# 配置生效
 
source /etc/profile
 
# 成功
 
node -v

4 Enter the vue_api_server project directory, and then execute npm install to install the dependency package.

5 Install Mysql, if you already have it, you can ignore this step

6 Enter the db directory and import mydb.sql into the Mysql database

  mysql>CREATE DATABASE `api_db_mysql` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

 mysql>use api_db_mysql;

  mysql>source /usr/local/vue_api_server/db/mydb.sql

7 Enter the config directory under the vue_api_server directory and open the file default.json

    The modification is as follows:
 

{
        "config_name" : "develop",

        "jwt_config" : {
                "secretKey":"itcast",

                "expiresIn":86400

        },

        "upload_config":{
                "baseURL":"http://192.168.234.133:8888",

                "upload_ueditor":"uploads/ueditor",

                "simple_upload_redirect":"http://192.168.234.133/reload"

        },

        "db_config" : {
                "protocol" : "mysql",

                "host" : "127.0.0.1",

                "database" : "api_db_mysql",

                "user" : "root",

                "password" : "Xsy@210721",

                "port" : 3306

        }

}

8 In the vue_api_server directory, execute the command

#node app.js

Returning these logs indicates that the deployment is successful:

9 Using VUE_API_Server

After completing the previous service environment deployment, the service port 8888 is monitored by default, the interface reference address is http://192.168.234.133:8888/api/private/v1/, and the data return format uses JSON uniformly.

Login interface:

Get the roles interface (note that Type=Bearer Token is added in Authorization, and the Token value is the token value returned by the login interface above)

 

Notice:

For business interfaces such as creating a user and querying a user, a token needs to be obtained from the login authorization API, and the token token must be provided in the request header using the Authorization field

There are many interfaces in the project, executing node app.js will print out all interfaces

[Detailed explanation of interface testing tools]

Interface Test Tool

  The interface test tool is shown in the figure:

1.Fiddler

First of all, this is an HTTP protocol debugging proxy tool. To put it bluntly, it is a tool for capturing http packets. Both web testing and mobile testing can use this tool. Since it is an http protocol, this tool can also support interface testing. In a later article, I will specifically introduce the tool fiddler.

2. PostMan
Postman is a very popular API debugging tool. In fact, developers use more. Because testers will have more choices for interface testing, such as Jmeter, soapUI, etc. However, for debugging the interface during the development process, Postman is indeed simple and convenient enough, and powerful. This is a google tool

A plug-in developed by the engineer, which can be installed on the chrome browser. Supports different interface test requests, can manage test suites and automate running, the weakness is that the automatic assertion function is not powerful. Continuous integration testing with jenkins and code management libraries is not possible. However, it is definitely a good half-manual, half-automatic test

Testing tools, I usually write automated interface test cases, and I will open postman for auxiliary testing and debugging. This tool will also be introduced later in the article.

 This is a packet capture tool on a computer that supports capture of various packets, including TCP, UDP, and HTTP. If you do the underlying network data test, you generally need to use it. As an interface test, this software is a bit unfriendly. Because refreshing data is too fast, it is difficult to locate the interface corresponding to each operation. So, we won't go into too much

Introducing this tool.

4. SoupUI    
SoapUI is an open source testing tool that checks, invokes, and implements Web Service function/load/compliance testing through soap/http. The tool can be used as a separate test software, and can also be integrated into Eclipse, maven2.X, Netbeans and intellij using plug-ins.

SoapUI is a free and open source cross-platform functional testing solution. With an easy-to-use graphical interface and enterprise-level features, SoapUI lets you easily and quickly create and execute automated functional, regression, compliance and load tests. In a test environment, SoapUI provides complete test coverage and supports all

There are standard protocols and technologies.

SoapUI is developed based on Java, supports multiple platforms, and is very easy to install.

This is an open source free and enterprise version of the paid software. It is used a lot in foreign interface tests. This tool can support interface automation testing and interface performance testing, and can also support continuous integration testing with jenkins. You can just learn about it. You can download a community free version and try a demo.

5. Java code for interface testing
The code is omnipotent, and the note-taking tool is also developed from the code. Why use code for interface automation testing? Because the functions of some tools are limited, many companies need some specific functions, but the tools do not support them, so they have to use codes for development. Generally use Java for automated testing, mainly using httpclient.jar

This package, then use unit testing tools such as junit or testng to develop test cases, and then create a job on jenkins for continuous integration testing.

6. Python code for interface testing
      is the same as Java, using a very good and powerful third-party library requests in Python can easily create interface automation use cases. The unit test framework under python generally uses unittest. To generate a test report, generally choose HTMLTestRunner.py. Similarly, continuous integration testing can be done with jenkins.

7. LoadRunner
       should not think that LR can only do performance testing, loadrunner can also do interface automation and interface stress testing. It's just that many of us don't know how to use LR functions to develop interface test cases.

8. JMeter
      JMeter, like loadrunner, is famous for performance testing, and JMeter is generally used for interface performance testing. For example, java+Jmeter+ant+jenkins does interface performance monitoring test.

      The above introduces so many tools, which basically cover interface function testing, interface automation testing, and interface performance testing.
 

5. [In-depth understanding of cookie, session, token authentication principles and actual combat]-------

A cookie is a small piece of text stored on the client, which can be used to identify the user's identity, and it will be carried and sent to the server when the browser makes another request to the same server next time.

advantage:

  • Cookies allow the server to identify user sessions at a relatively low cost.
  • The cookie will only be sent to the domain name that sets the cookie, which ensures the relative security of the cookie.
  • Since cookies do not follow the strict same-origin policy, a subdomain can be set to obtain the cookie of the parent domain. This feature is very conducive to the implementation of single sign-on.
  • You can set the cookie expiration time to ensure that the cookie is used within the validity period.

 shortcoming:

  • The cookie size is only 4k, so it cannot hold large amounts of content.
  • The cookie is saved on the client, so it is not safe enough. If someone hijacks the cookie, the server cannot distinguish whether it is the user himself or the hacker who is using the session state.
  • If there is no setting on the server side that prohibits js from reading cookies, js can create, modify and delete cookies under this domain name, so in order to prevent xss attacks, you need to set the cookie to HttpOnly.
  • If the browser is set to disable cookies, the server cannot track user sessions based on cookies

 Pseudocode :

    @GetMapping("put")
    public void test2(HttpServletRequest request, HttpServletResponse response){
        // Cookie 为键值对数据格式
        Cookie cookie_username = new Cookie("cookie_username", "admin");
        // 即:过期时间,单位是:秒(s)
        cookie_username.setMaxAge(30 * 24 * 60 * 60);
        // 表示当前项目下都携带这个cookie
        cookie_username.setPath(request.getContextPath());
        // 使用 HttpServletResponse 对象向客户端发送 Cookie
        response.addCookie(cookie_username);
    }
 
    @GetMapping("del")
    public void test4(HttpServletRequest request, HttpServletResponse response){
        // 根据 key 将 value 置空
        Cookie cookie_username = new Cookie("cookie_username", "");
        // 设置持久时间为0
        cookie_username.setMaxAge(0);
        // 设置共享路径
        cookie_username.setPath(request.getContextPath());
        // 向客户端发送 Cookie
        response.addCookie(cookie_username);
    }

After executing the put request, you can see on the client:

After executing the del request, it cannot be seen on the client side:

session
session is another mechanism that is stored on the server and used to identify user sessions, based on cookies. After the user initiates a request, the server will create a session for the request and can set related attributes, and then the server will put the sessionid in the cookie and return it to the browser. The browser will always request this cookie in the future, and the server can get the corresponding session through the sessionid and know which user's session it is.

Schematic:

advantage:

  • Save user information on the server, better security

  • Even if the user disables cookies, the sessionid can still be passed by splicing after the url

  • The expiration time can be set, and there is a renewal mechanism to make the session last longer

  • Using session can make it easier to pass parameters between pages

shortcoming:

  • It will increase the storage burden of the server. If the session is placed in the memory, it will also be a challenge to the memory in the case of a large number of users.

  • If it is a distributed server, session information cannot be synchronized well

Pseudocode :

 

    @GetMapping("put")
    public void test4( HttpSession session){
        session.setAttribute("session_username","admin");
    }
 
    @GetMapping("del")
    public void test5(HttpSession session){
        session.removeAttribute("session_username");
    }
 
    @GetMapping("get")
    public void test6( HttpSession session){
        System.out.println(session.getAttribute("session_username"));
    }
 
//    常用方法
//    public Object getAttribute(String name)
//    返回session对象中与指定名称绑定的对象,如果不存在则返回null
//
//    public Enumeration getAttributeNames()
//    返回session对象中所有的对象名称
//
//    public long getCreationTime()
//    返回session对象被创建的时间, 以毫秒为单位,从1970年1月1号凌晨开始算起
//
//    public String getId()
//    返回session对象的ID
//
//    public long getLastAccessedTime()
//    返回客户端最后访问的时间,以毫秒为单位,从1970年1月1号凌晨开始算起
//
//    public int getMaxInactiveInterval()
//    返回最大时间间隔,以秒为单位,servlet 容器将会在这段时间内保持会话打开
//
//    public void invalidate()
//    将session无效化,解绑任何与该session绑定的对象
//
//    public boolean isNew()
//    返回是否为一个新的客户端,或者客户端是否拒绝加入session
//
//    public void removeAttribute(String name)
//    移除session中指定名称的对象
//
//    public void setAttribute(String name, Object value)
//    使用指定的名称和值来产生一个对象并绑定到session中
//
//    public void setMaxInactiveInterval(int interval)
//    用来指定时间,以秒为单位,servlet容器将会在这段时间内保持会话有

After the put request is executed, it cannot be seen on the client 

Execute the get request, which can be seen on the server side

Execute the del request and then execute the get request, which cannot be seen on the server

For distributed session issues, see Distributed session sharing issues 

token

Token is an authentication method, which is vividly called "token" after being translated by many people. It has higher scalability and higher security, and is very suitable for use in web applications and mobile development applications.

There are many kinds of tokens, such as the commonly used jwt, whose full name is Json Web Token, which is a lightweight authorization and identity authentication specification in JSON style, which can realize stateless and distributed web application authorization.

the difference:

  • Ordinary token: the server verifies the token information sent by the client and needs to query the data

  • jwt token: the jwt token itself stores user information, which can be directly parsed from the jwt token

Finally, I would like to thank everyone who has read my article carefully. Reciprocity is always necessary. Although it is not a very valuable thing, you can take it away if you need it:

These materials should be the most comprehensive and complete preparation warehouse for [ software testing ] friends. This warehouse has also accompanied tens of thousands of test engineers through the most difficult journey, and I hope it can help you! Partners can click the small card below to receive

Guess you like

Origin blog.csdn.net/kk_lzvvkpj/article/details/132474246