Postman pre-request scripts, test scripts (pre-request scripts, tests common work summary)

Postman pre-request script (commonly used summary of pre-request scripts work)

Postman pre-request script

Official website: https://learning.postman.com/docs/writing-scripts/pre-request-scripts/

insert image description here

You can use pre-request scripts in Postman to execute JavaScript before a request runs. By including code in the Pre-request Script tab for a request, collection, or folder, you can carry out pre-processing such as setting variable values, parameters, headers, and body data. You can also use pre-request scripts for debugging code, for example by logging output to the console.

In Postman, you can use pre-request scripts to execute JavaScript before the request runs . By adding code in the "Pre-request Script" tab of a request, collection, or folder, you can perform preprocessing such as setting variable values, parameters, headers, and body data. You can also use pre-request scripts to debug your code, such as logging output to the console.

Postman test script

Official website: https://learning.postman.com/docs/writing-scripts/test-scripts/

Tests confirm that your API is working as expected, that integrations between services are functioning reliably, and that any changes haven’t broken existing functionality. You can write test scripts for your Postman API requests in JavaScript. You can also use test code to aid the debugging process when something goes wrong with your API project. For example, you might write a test to validate your API’s error handling by sending a request with incomplete data or wrong parameters.

Testing confirms that your APIs work as expected, that integrations between services are reliable, and that any changes do not break existing functionality. You can use JavaScript to script tests of Postman API requests. You can also use test code to help the debugging process when something goes wrong with your API project. For example, you can write a test to verify the error-handling functionality of your API by sending a request with incomplete data or wrong parameters.

What is the difference between pre-request script and test script

A pre-request script is a script that is executed before a request is sent, and it is used to modify the request, add parameters, set environment variables, add headers, etc. Pre-request scripts can be applied to individual requests, entire collections, or entire folders to automate some tasks before sending the request.

Test scripts are scripts that are executed after a response is received, and they are used to assert, parse, and process the response. Test scripts can access the header, body, status code, and other properties of the response, and can write logic using JavaScript to customize test results.

The main difference between pre-request scripts and test scripts is the timing of their execution. Pre-request scripts are executed before the request is sent, while test scripts are executed after the response is received.

Common work summary

The login interface returns the Set-Cookie header

Requirement:
The login interface returns the Set-Cookie header, which needs to be extracted in the pre-request script and set as the cookie for subsequent requests.

Implementation idea 1: Send a login request in JS, extract it in the pre-request script, and set it as a cookie for subsequent requests

pm.sendRequest({
    
    
    url: 'https://your-api.com/login',
    method: 'POST',
    header: {
    
    
        'Content-Type': 'application/json'
    },
    body: {
    
    
        mode: 'raw',
        raw: JSON.stringify({
    
    
            email: '[email protected]',
            password: 'password123'
        })
    }
}, function (err, res) {
    
    
    // 处理登录响应,解析出Set-Cookie标头
    if (err || res.code !== 200) {
    
    
        console.error('登录失败', err || res);
        return;
    }

    const setCookieHeader = res.headers.get('set-cookie');
    const sessionId = /sessionid=([^;]+)/.exec(setCookieHeader)[1];

    // 在环境变量中设置Session ID
    pm.environment.set('sessionId', sessionId);
});

// 设置Cookie标头以使用Session ID进行身份验证
const sessionId = pm.environment.get('sessionId');
pm.request.headers.add({
    
    
    key: 'Cookie',
    value: `sessionid=${
      
      sessionId}`
});

Implementation idea 2: Set Cookie in the POST request return in Postman, you can use Postman's test script.
In Postman, you can add JavaScript test scripts by selecting the request to test, and navigating to the "Tests" tab in the request editor. These test scripts are automatically executed when the request returns a response. So you can write code in your test script to parse the response and set the cookie.

// 处理响应
if (pm.response.code === 200) {
    
    
    const responseBody = pm.response.json();
    if (responseBody.code !== 0) {
    
    
        console.warn('API响应出现错误:', responseBody);
        pm.test("API响应出现错误", function () {
    
    
            pm.expect(responseBody.code).to.eql(0);
        });
    } else {
    
    

            // 解析Set-Cookie标头
            const setCookieHeaders = pm.response.headers.all().filter(header => header.key === 'Set-Cookie').map(header => header.value);
            if (setCookieHeaders.length > 0) {
    
    
                // 遍历所有Set-Cookie标头
                for (let i = 0; i < setCookieHeaders.length; i++) {
    
    
                    const setCookieHeader = setCookieHeaders[i];
                    const sessionIdMatch = /sessionid=([^;]+)/.exec(setCookieHeader);

                    if (sessionIdMatch !== null) {
    
    
                        const sessionId = sessionIdMatch[1];

                        // 在环境变量中设置Session ID
                        pm.environment.set('sessionId', sessionId);
                        break;
                    }
                }
            } else {
    
    
                console.warn('没有找到Set-Cookie标头');
            }

    }
} else {
    
    
    console.error(`请求失败: ${
      
      pm.response.code} ${
      
      pm.response.statusText}`);
    pm.test(`请求失败: ${
      
      pm.response.code} ${
      
      pm.response.statusText}`, function () {
    
    
        pm.expect(pm.response.code).to.eql(200);
    });
}
  • Add a message to the Test Results panel to indicate test results using the pm.test method

So far, we already have the variable sessionId in our Postman environment variable. We need to set the setting header in the pre-request script of other requests (we can put it in the entire collection collection, and all requests under the collection will execute this pre-request script, so that all requests have the required headers).

If you execute the same request multiple times, and the sessionId header is added in the pre-request script, then each execution will add a new sessionId header, resulting in duplicate headers.

To avoid this, you can remove the existing sessionId header before adding the new one, before adding the sessionId header. You can use the following JavaScript code to do it:

// 删除已存在的 sessionId 标头
pm.request.headers.remove('sessionId');
pm.request.headers.add({
    
    key: 'sessionId', value: pm.environment.get('sessionId')});

Guess you like

Origin blog.csdn.net/inthat/article/details/130419147