Postman’s pre- and post-scripts fully support JavaScript writing. JavaScript has many built-in objects and methods that can help us complete various tasks, such as generating random numbers and testing response data.
Generate random numbers
Use the Math.random()
method to generate a random decimal between 0 and 1, for example:
Math.random() // Number between 0.0-1.0, decimal 0.465413246541
Generate a random number within a specified range:
Math.random()*10 // Number between 0.0-10.0, decimal 9.465413246541
Generate an integer, you can use the Math.floor()
, Math.ceil()
or Math.round()
method to get the decimal all:
Math.floor(Math.random()*10) // Discard the decimal part directly 0,1,2,3,4,5,6,7,8,9 Math.floor(9.232323123313213)=9 // Discard the decimal part 9 directly Math.ceil(Math.random()*10) //Add 1 method, add 1 to the integer part, 1,2,3,4,5,6,7,8,9,10 Math.ceil(9.232323233231121)=10 //Add 1 method, add 1 to the integer part, 10 Math.round(Math.random()*10) // Rounding method, nearest integer 0,1,2,3,4,5,6,7,8,9,10 Math.round(9.232323233231121)=9 // Rounding method, nearest integer 9
Scenario 1: Randomly generate a username
Generate a username in the format kira001,kira002,jkira003.
var num=""; // Loop to generate 3 digits for(var i=0;i<3;i + + ){ num + =Math.floor(Math.random()*10); } // Splice username var username = "kira" + num; // print username console.log(username) // kira456
Scenario 2: Randomly generate a phone number
Generate a phone number with the first three digits being 135,138,156,181,199.
//Define the first three digits list var list=["135","138","156","181","199"]; //Get a random subscript var index= Math.floor(Math.random()*list.length) // Get the first three digits var pre_phone3=list[index]; // Define the last eight digits as an empty string var back_phone8=""; // Loop to generate the last eight digits for(var i=0;i<8;i + + ){ back_phone8 + =Math.floor(Math.random()*10); } // Splice phone numbers var phonenum = pre_phone3 + back_phone8; // print phone number console.log(phonenum) // 15612345678 // Set as a temporary variable, request direct {<!-- -->{phonenum}} call pm.variables.set('phonenum',phonenum);
Request data or response data processing
When testing the interface, we need to perform some logical processing and assertions on the request data or response data to ensure the correctness and integrity of the data.
Method 1: pm object
The pm
object is a global object that provides some properties and methods to access request and response information.
console.log(pm.response.code) // Extract status code 200 console.log(pm.response.reason()) // Extract response information OK console.log(pm.response.headers) // Extract response headers console.log(pm.response.responseTime) // Extract response time console.log(pm.response.text()) // Extract the response body. No matter what format the body is in, you can use this function to extract it. console.log(pm.response.json()) // Extract the response data in json format and convert it into a json object (i.e. python dictionary)
Method 2: responseCode, responseTime and other objects
Objects such as responseCode
and responseTime
are global objects that can also be used to access request and response information.
var code=responseCode.code; // Get the status code 200 in the response var codename=responseCode.name; // Extract response information OK var time=responseTime; //Extract response time var headers=postman.getResponseHeader('Content-Type'); // Extract Content-Type in the response header var cookies=postman.getResponseCookie('name').value; // Get the value in the response cookie, fill in the name value of the cookie in parentheses var body=getResponseBody; // Get the response body (it is a string, if it is in json format, it is a json string) var jsonData= JSON.parse(body) // Convert json string to json object (dictionary)
Assertion response information
pm.test()
is a global function used to define a test case and accepts a callback function as a parameter.
Assertion status code
Status code refers to a representation of the server’s processing result of the request, such as: 200 means success, 404 means not found, 500 means server error, etc.
Method 1: pm.response.to.have.status()
pm.response.to.have.status()
is used to determine the status code of the response.
pm.test("Status code is 200", function () { pm.response.to.have.status(200); });
Method 2: pm.expect()
pm.expect()
is a global function that creates an expected value and accepts an actual value as a parameter. `pm.expect() also provides some chain methods that can be used to make various assertions.
var code=pm.response.code; pm.test("Simple example of chain assertion",function(){ pm.expect(code).to.equal(200); pm.expect({a: 1}).to.deep.equal({a: 1}); pm.expect({a: {b: ['x', 'y']}}).to.have.nested.property('a.b[1]'); pm.expect({'.a': {'[b]': 'x'}}).to.nested.include({'\.a.\[b\]': 'x'} ); pm.expect({a: 1}).to.have.own.property('a'); pm.expect({a: 1, b: 2}).to.not.have.any.keys('c', 'd'); pm.expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); pm.expect([]).to.be.an('array').that.is.empty; });
pm.expect()
has many chain methods, specific reference link: https://www.chaijs.com/api/bdd/
Method 3: if statement and tests object
tests
is a global object used to store test results and accepts a Boolean value as a parameter.
var code =pm.response.code; if(code==200){ tests['The status codes are consistent! ']=true; }else{ tests['status code inconsistent']=false; }
Method 4: tests object and comparison operator
A comparison operator is an operator that compares two values for size or equality and returns a Boolean value.
tests['Status code test']=pm.response.code===200;
Assertion response body
The response body refers to the data returned by the server to the client, which can be text, pictures, audio, video, etc.
Method 1: pm.expect()
Full match or partial match
pm.test("Full match or partial match", function () { var body =pm.response.text(); pm.expect(body).to.equal('{"status":2,"msg":"Request successful"}');//Full match pm.expect(body).to.include('Request successful'); // Partial match });
The specific content of the response is not fixed, but its format and structure are fixed, so it can be structured or key-value matched.
pm.test("Response structure matching", function () { var jsonData = pm.response.json(); // structure matching pm.expect(jsonData).to.eql({ "errcode": 0, "data": { "user_id": 1 } }); //Key value matching pm.expect(jsonData.status).to.equal(2); pm.expect(jsonData.msg).to.equal("Request successful"); });
Method 2: pm.response.to.have.jsonBody()
pm.test("Body is json", function () { //Check whether the response body is in json format. pm.response.to.have.jsonBody(); //Check whether a certain key or value exists in the response body. pm.response.to.have.jsonBody('status'); // Check whether the key exists pm.response.to.have.jsonBody(2);//Check whether the value exists });
Method 3: pm.response.to.have.jsonSchema()
Check whether the response body conforms to a json schema (schema)
, contains two required attributes errcode (number) and errmsg (string).
pm.test("Body matches schema", function () { var schema = { "type": "object", // object "properties": { "errcode": { "type": "number" // Number type }, "errmsg": { "type": "string" // String type } }, "required": ["errcode", "errmsg"] // required }; pm.response.to.have.jsonSchema(schema); });
Analysis of assertion ideas in common special scenarios
-
Scenario 1: The number of response body
json
formats is relatively large and cannot fully match the entirejson
format. How to assert?-
Only check some key keys or values in the response body
-
-
Scenario 2: The returned data in
json
format changes. How to assert?-
In this case, use the
json
pattern to check the structure and constraints of the response body, rather than the specific content.
-
-
Scenario 3: What if the returned Body data in
json
format changes dynamically?-
First check whether it is in
json
format -
You can only check whether the expected keys exist in
body
, mainly checking which core keys -
You can check whether the returned
json
structure is correct
-
Finally:The complete software testing video tutorial below has been compiled and uploaded. Friends who need it can get it by themselves[Guaranteed 100% Free]
Software Testing Interview Document
We must study to find a high-paying job. The following interview questions are the latest interview materials from first-tier Internet companies such as Alibaba, Tencent, Byte, etc., and some Byte bosses have given authoritative answers. After finishing this set I believe everyone can find a satisfactory job based on the interview information.