postman preliminary and common scripts

Posted by 121212 on Wed, 09 Mar 2022 14:14:11 +0100

The design of docking interface parameters is simple and easy.

A brief introduction to Postman

  • Chrome post is a powerful API for debugging web requests.
  • Postman can send any type of http request and support GET/PUT/POST/DELETE. Any number of headers can be attached to the request header.
  • Postman supports different authentication mechanisms (basic, digest, OAuth).
  • Postman is very simple and easy to use. You can send a request by filling in the URL, header, body, etc.
  • No Chinese support.
  • Postman uses the interface in chrome.
  • Postman is based on js language.

Official address

  1. Official website address: https://www.getpostman.com/
  2. Official document address: https://www.getpostman.com/docs/
  3. Official address of problem feedback: https://go.pstmn.io/app-issues
  4. Official git address: https://github.com/postmanlabs
  5. Official case study: http://blog.getpostman.com/case-studies/
  6. Official blog: http://blog.getpostman.com/
  7. Official download address: https://www.getpostman.com/apps/

The versions are:

  1. chrome plug-in version
  2. mac version
  3. linux Version (32 / 64)
  4. windows client version (32 / 64)

newman:

      https://www.npmjs.com/package/newman

  1. The package used to run the postman script.
  2. Based on nodejs.
  3. Designed for postman.
  4. Powerful function, can generate html and other reports, and can do continuous integration.

1, postman download and installation

1. Download

  • (1) First: Baidu online disk download address:

Link: https://pan.baidu.com/s/1hlKY_X8rFdUj2hq3X2K2SQ

Extraction code: w465

  • Second: download from the official website:

Click me to open the official website of postman to download

2. Installation

  • windows version, download and install all the way.

  • After installation, open it and register an account to use it.

To register an account, you need a personal email. You need to take a user name and set a password

2, Familiar with postman interface

1. Collection bar

 

2. Request bar

 

3. New column

 

4. Useful little buttons

 

3, Detailed function introduction

1. Global settings

(1) Global settings entry

  • Entrance 1:

 

  • Entrance 2:

 

(2) Global settings -- Genaral

Global settings - Genaral: you can set font size, SSL certificate authentication, etc

 

(3) Global settings -- Theme

You can set two themes: default white and dark

 

(4) Global settings -- View version

 

2. Assemble

(1) New collection

 

(2) Edit fields when creating a new set

You can edit the name, description, authentication, pre script, post script and variable of the collection.

Generally, you can only edit the name, description and.

 

(3) What operations can a collection do?

Rename, edit, add interface request, add folder, copy, export, delete

 

3. Interface request

(1) url of the interface request

 

(2) Send interface request

 

(3) Save interface request

There are two types: save and save as

 

(4) Input parameter of get request

The input parameters of the get request should be written in Params:

 

(5) Input parameters of post request

  • The input parameters of the post request should be placed in the body

 

  • post input parameter types supported by postman

 

  • Differences between commonly used urlencoded and form data types:

<table>
<tr style="font-weight: bolder">
<td>Post requests have different parameter transfer methods</td>
<td>Characteristics</td>
</tr>
<tr>
<td>application/x-www-form-urlencoded</td>
<td>If not specified, the default method is key1 = value1 & key2 = Value2</td>
</tr>
<tr>
<td>multipart/form-data</td>
<td>It is generally used for form file upload</td>
</tr>
</table>

(6) Pre script

  • The pre script is placed in the pre request script:

 

(7) Post script

  • Put the post script in Tests:

 

(8) Response data

  • Pretty view:

 

  • Raw view:

 

  • Preview view:

 

(9) Run set

  • A. Operation entrance:

 

  • B. Understanding of operation collection interface:

 

  • C. After running a collection, you will see the running results:

 

  • D. Click the orange button "Run Summary" in the figure below to view the summary results:

  • E. Summary result display:

4, Assertion of common scripts in postman

1. Status code and description

==(1) The status code is 200==

pm.test("Status code is 200", function () {
    pm.response.to.have.status(200); # 200 is of type int
});

(2) Status code name (OK, Not Found...)

pm.test("Status code name has string", function () {
    pm.response.to.have.status("Created"); # Created: string type
});

(3) The actual status code is among the expected status codes

pm.test("The status code is 200 or 201", function () {
    pm.expect(pm.response.code).to.be.oneOf([201,202]);
});

2. String assertion in response

**(1) Check whether the response body * * is equal to the string****

pm.test("Response data = Some string", function () {
    pm.response.to.have.body("response_body_string");
});

==**(2) Check whether the response body * * contains a string****==

pm.test("Body matches string", function () {
    pm.expect(pm.response.text()).to.include("string_you_want_to_search");
});

3. Check JSON value (※ extremely important ※)

==(1) Check whether the value of a field in the response data is equal to xxx==

pm.test("Your test name", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.student.count).to.eql(100);
});

==(2) Judge whether a field is included under a field in the response (in js language)==

hasOwnProperty

pm.test("Checking response choose_subject Whether the field contains name field",function(){
    var jsonData = pm.response.json();
    pm.expect(jsonData.choose_subject.hasOwnProperty("name")).to.eql(true);
});
jsonData.choose_subject.containsKey.every(item => "name" in item); //(don't look at this)

The following is the one with js loop added (it can be ignored):

pm.test("Checking response choose_subject Whether the field contains name field",function(){
    var jsonData = pm.response.json();
    for (i=0; i<jsonData.choose_subject.length; i++ ){ 
        oneJson = jsonData.choose_subject[i];
        pm.expect(oneJson.hasOwnProperty("name")).to.eql(true);
        console.log(bool);      
    }    
});
// jsonData.choose_subject.containsKey.every(item => "name" in item);

==(3) Judge whether the value of a field under a field in the response contains a string (in js language)==

to.include

pm.test("The response contains buy_status Field below subject_name The field value includes string Chinese, mathematics and English", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.buy_status[0].subject_name).to.include('language');
});

==(4) Judge that the value of a field in the response is not empty (not 0, "", [], {}, etc.)==

pm.test("response content The value of the field cannot be empty", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.content ? true:false).to.eql(true);
});

4. A key in the header exists

pm.test("Content-Type is present", function () {
    pm.response.to.have.header("Content-Type");
});

5. Determine the field data type in the response

I'll sort out several types of:

number, string, object, array, boolean, undefind (empty)

pm.test("term_type It's an integer", function () {
    pm.expect(typeof(jsonData.return_list[0].term_type) === "number").to.eql(true);
});

pm.test("id Is a string", function () {
    pm.expect(typeof(jsonData.return_list[0].id) === "string").to.eql(true);
});

pm.test("success  Is a Boolean value", function () {
    pm.expect(typeof(jsonData.success) === "boolean").to.eql(true);
});
pm.test("return_list yes array array", function () {
    pm.expect(jsonData.return_list instanceof Array).to.eql(true);
});
pm.test("name Field not defined(Or it doesn't exist)", function () {
    var jsonData = pm.response.json();
    pm.expect(typeof(jsonData.name) === "undefined").to.eql(true);
});

Expand js language (for loop):

var jsonData = pm.response.json();
for (i=0; i<jsonData.choose_subject.length; i++ ){ 
    oneJson = jsonData.choose_subject[i];
    console.log(oneJson );       
}

6. Response time

  • Response time less than 200 ms
pm.test("Response time is less than 200ms", function () {
    pm.expect(pm.response.responseTime).to.be.below(200);
});
  • Response time greater than 10 ms
pm.test("Response time less than 200 ms", function () {
    pm.expect(pm.response.responseTime).to.be.above(10);
});

7. json advanced

(1) Get JSON data using TinyValidator

var schema = {
     "items": {
     "type": "boolean"
     }
};
var data1 = [true, false];
var data2 = [true, 123];

pm.test('Schema is valid', function() {
  pm.expect(tv4.validate(data1, schema)).to.be.true;
  pm.expect(tv4.validate(data2, schema)).to.be.true;
});

(2) JSON schema validator

var Ajv = require('ajv'),
    ajv = new Ajv({logger: console}),
    schema = {
        "properties": {
            "alpha": {
                "type": "boolean"
            }
        }
    };

pm.test('Schema is valid', function() {
    pm.expect(ajv.validate(schema, {alpha: true})).to.be.true;
    pm.expect(ajv.validate(schema, {alpha: 123})).to.be.false;
});

(3) Convert XML body to JSON object

var jsonObject = xml2Json(responseBody);

8. Decoding base64 encoded data

var intermediate,
    base64Content, // assume this has a base64 encoded value
    rawContent = base64Content.slice('data:application/octet-stream;base64,'.length);

intermediate = CryptoJS.enc.Base64.parse(base64content); // CryptoJS is an inbuilt object, documented here: https://www.npmjs.com/package/crypto-js
pm.test('Contents are valid', function() {
  pm.expect(CryptoJS.enc.Utf8.stringify(intermediate)).to.be.true; // a check for non-emptiness
});

5, postman advanced script

1. Send request (pm.sendRequest)

(1) Send get request

//const is the definition constant
const url = 'http://115.28.108.130:5000/api/user/getToken/?appid=136425';
// Send get request
pm.sendRequest(url, function (err, res) { //The first two exceptions must be named, but the second one must be named err
  console.log(err ? err : res.text());  // The console prints the request text. res.text(),res.json()
});

(2) Send form post request

//Construct a login request
const loginRequest = {
    url: 'http://115.28.108.130:5000/api/user/login/',
    method: "POST",
    body: {
        mode: 'urlencoded',  // The mode is the form url encoding mode
        urlencoded: 'name=Zhang San&password=123456'
    }
};

// Send request
pm.sendRequest(loginRequest, function (err, res) {
    console.log(err ? err : res.text());
});

(3) Send JSON format request

// Construct a registration request
const regRequest = {
  url: 'http://115.28.108.130:5000/api/user/reg/',
  method: 'POST',
  header: 'Content-Type: application/json',  //Note that the type used by the content should be declared in the Header
  body: {
    mode: 'raw',  // Use raw format
    raw: JSON.stringify({ name: 'Small', password: '123456' }) //To convert a JSON object to text, send
  }
};

// Send request
pm.sendRequest(regRequest, function (err, res) {
  console.log(err ? err : res.json());  // The response is in JSON format. You can use res.json() to get the JSON object
});

(4) Send XML format request

Sending XML format is similar to sending JSON format, as long as you specify the content format and send the corresponding content

//Construction request
const demoRequest = {
  url: 'http://httpbin.org/post',
  method: 'POST',
  header: 'Content-Type: application/xml',  // Request header specifies the content format
  body: {
    mode: 'raw',
    raw: '<xml>hello</xml>'  // Send xml as text
  }
};

//Send request
pm.sendRequest(demoRequest, function (err, res) {
  console.log(err ? err : res.json());
});

2. Change interface request order

Usefulness: sometimes we don't want collections to execute interfaces in strict order. At this time, you can change the order of interface requests.

give an example:

If there are three interfaces A, B and C under your collection, the return field of interface A has A content_type,

When content_ When type = 1, we expect to execute B interface and then C interface to end;

When content_ When type = 2, we expect the direct execution of C interface to end;

(1) General mode

  • postman.setNextRequest('name of interface request ');
//Change interface execution order
postman.setNextRequest("Send with script post request");

(2) Branching mode

var jsonData = pm.response.json()

if(jsonData.args.a == 'a'){
    postman.setNextRequest("D");
}
else{
    postman.setNextRequest("B");
}

(3) Polling mode

Scenario: when the response data of this interface is "{} \ n", execute this interface again until the response data changes

if(pm.response.text() == "{}\n"){
    postman.setNextRequest("Name of its own interface");
}

3. Print the request url, input parameter and response information in the script

(1) Print all information of the request (including url, input parameters, headers, etc.)

console.log(request);

(2) url of the print request

console.log(request.url);

The url of the get request is parameterized;

The url of the post request has no parameters

(3) Print all input parameters of get request

For example, the url of the get request is:

https://pMobile/recite_word/tlist.vpage?clazz_level={{tuobi_qiaoSuan_grade}}&sid={{student_id}}

console.log(request.url.split('?')[1]);

(4) Print all input parameters of the get request and one input parameter

For example, the url of the get request is:

https://pMobile/recite_word/tlist.vpage?clazz_level={{tuobi_qiaoSuan_grade}}&sid={{student_id}}

I want to print the value of sid input parameter:

  • The first method:
console.log(request.url.split('?')[1].split('&')[1].split('=')[1]);
  • The second method:

In the above method, when the input parameter sequence changes, the wrong value will be taken. In order to get the correct value, it is optimized as follows:

var keys = request.url.split('?')[1].split('&');//Get all the parameters and form an array

for(index in keys){
    key = keys[index].split('=')[0]; //Get the key of parameter pair
    value = keys[index].split('=')[1]; //Get value of parameter pair
    if(key === 'sid'){ //When the key of the parameter pair = the sid I want
        let sid = value; Customize a variable called sid,The value is equal to the value of the above parameter pair value
        console.log(sid);
    }
}

(5) Get all input parameters of post parameter

console.log(request.data);

(6) Get the parameter "mobile" in the input parameter of the post parameter

console.log(request.data.mobile);

(7) Get the headers of the request

console.log(request.headers);

4. Print response information in script

(1) Get all response information

console.log(pm.response);

(2) Get the headers of the response

console.log(pm.response.headers.members[0]['key']);
console.log(pm.response.headers.members[2]['value']);

(3) Acquisition and response code

console.log(pm.response.code);
console.log(pm.response.status);

5. Calculate array length

function count(o){
    var t = typeof o;
    if(t == 'string'){ //Calculates the length of the string
        return o.length;
    }else if(t == 'object'){//Calculate the length of the array
        var n = 0;
        for(var i in o){
            n++;
        }
        return n;
    }
    return false;
}

var lesson = jsonData.lessons[0];
console.log(count(lesson));//Call the count method

6, Get a returned HTML file for verification

var html, titleText;
// load the response body as HTML using cheerio
// and using cheerio's jQuery like .find API, get the H1 tag
html = cheerio(responseBody);
titleText = html.find('h1').text();
// add a test that ensures that there is some H1 content
tests["page must have h1 heading"] = Boolean(titleText);

 

Topics: PostMan