赞
踩
不得不说PostMan真的是一个强大的接口测试工具,深得人心。
小编也在闲暇之余整理了一些有关于PostMan中的Tests脚本的示例,希望能帮助到热爱学习热爱工作的各位。
- pm.test("Status code is 200", function () {
- pm.response.to.have.status(200);
- });
- pm.test("Response time is less than 500ms", function () {
- pm.expect(pm.response.responseTime).to.be.below(500);
- });
- pm.test("Response body has a valid key", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData).to.have.property('keyName');
- });
- pm.test("Response body contains expected text", function () {
- pm.expect(pm.response.text()).to.include("expectedText");
- });
- pm.test("Response body has an array with at least 3 elements", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.arrayProperty).to.have.lengthOf.at.least(3);
- });
- pm.test("Response body property has the correct data type", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.propertyName).to.be.a('number');
- });
- pm.test("Content-Type header is present", function () {
- pm.response.to.have.header("Content-Type");
- });
- pm.test("Environment variable has expected value", function () {
- pm.expect(pm.environment.get("variableName")).to.equal("expectedValue");
- });
- pm.test("Response body follows JSON schema", function () {
- var jsonData = pm.response.json();
- var schema = {
- "type": "object",
- "properties": {
- "name": { "type": "string" },
- "age": { "type": "number" }
- },
- "required": ["name", "age"]
- };
- pm.expect(tv4.validate(jsonData, schema)).to.be.true;
- });
- //此示例使用 tv4 库进行 JSON Schema 验证。
- pm.test("Multiple conditions combined", function () {
- var jsonData = pm.response.json();
-
- // Check multiple conditions
- pm.expect(jsonData.property1).to.equal("expectedValue1");
- pm.expect(jsonData.property2).to.be.an('array').that.includes('expectedValue2');
- pm.expect(jsonData.property3).to.have.lengthOf.at.most(5);
- });
- pm.test("Date format is valid", function () {
- var jsonData = pm.response.json();
- var dateFormat = /\d{4}-\d{2}-\d{2}/; // Example: YYYY-MM-DD
- pm.expect(jsonData.dateProperty).to.match(dateFormat);
- });
- pm.test("Check for an error response", function () {
- pm.expect(pm.response.json().status).to.equal("error");
- });
- pm.test("All items in the array meet a certain condition", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.items).to.satisfy(function (items) {
- return items.every(function (item) {
- return item.property > 0;
- });
- });
- });
- pm.test("Check for a specific header value", function () {
- pm.expect(pm.response.headers.get("Content-Type")).to.equal("application/json");
- });
- pm.test("Update environment variable based on response", function () {
- var jsonData = pm.response.json();
- pm.environment.set("variableName", jsonData.propertyToUpdate);
- });
- pm.test("Check if file upload was successful", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.status).to.equal("success");
- pm.expect(jsonData.uploadedFiles.length).to.be.above(0);
- });
- pm.test("Check for a redirect", function () {
- pm.expect(pm.response.code).to.be.oneOf([301, 302]);
- pm.expect(pm.response.headers.get("Location")).to.equal("https://newlocation.com");
- });
- pm.test("Check for a specific pattern in the response body", function () {
- pm.expect(pm.response.text()).to.match(/PatternToMatch/);
- });
- pm.test("Check if specific data exists in the response", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData).to.include.keys("expectedKey");
- });
- pm.test("Compare two response bodies", function () {
- var jsonData1 = pm.response.json();
- var jsonData2 = pm.iterationData.get("expectedResponse");
- pm.expect(jsonData1).to.eql(jsonData2);
- });
- pm.test("Response time is within an acceptable range", function () {
- pm.expect(pm.response.responseTime).to.be.within(100, 1000); // 100ms to 1000ms
- });
- pm.test("Check for a specific value in the response header", function () {
- pm.expect(pm.response.headers.get("Content-Type")).to.include("application/json");
- });
- pm.test("Check properties of each item in the array", function () {
- var jsonData = pm.response.json();
- jsonData.forEach(function (item) {
- pm.expect(item).to.have.property("propertyName");
- });
- });
- pm.test("Check if object properties meet certain conditions", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.propertyName).to.satisfy(function (value) {
- return value > 0 && value < 100;
- });
- });
- pm.test("Use external library for advanced validation", function () {
- var jsonData = pm.response.json();
- var isValid = externalLibrary.validate(jsonData);
- pm.expect(isValid).to.be.true;
- });
- pm.test("Logging information for debugging", function () {
- var jsonData = pm.response.json();
- console.log("Response data:", jsonData);
- pm.expect(jsonData).to.have.property("expectedKey");
- });
- pm.test("Check for a specific cookie in the response headers", function () {
- pm.expect(pm.response.headers.has("Set-Cookie")).to.be.true;
- });
- // 引入 Chai 库
- var chai = require('chai');
-
- // 使用 Chai 断言库的 BDD 风格
- var expect = chai.expect;
然后,你可以在测试脚本中使用 Chai 提供的更多断言功能:使用 Chai 能够提供更多的断言选项和更清晰的测试语法。
- pm.test("Use Chai for advanced assertions", function () {
- var jsonData = pm.response.json();
-
- // 使用 Chai 断言
- expect(jsonData).to.have.property("propertyName").that.is.a("string");
- expect(jsonData.arrayProperty).to.be.an("array").that.includes("expectedValue");
- });
- pm.test("Loop through array elements for validation", function () {
- var jsonData = pm.response.json();
-
- // 假设 responseData 是一个数组
- jsonData.forEach(function (item) {
- pm.test("Check individual item", function () {
- pm.expect(item).to.have.property("property").that.is.a("string");
- // 添加更多的断言...
- });
- });
- });
- pm.test("Validate response against OpenAPI specification", function () {
- var jsonData = pm.response.json();
- var openAPISpec = { /* Your OpenAPI specification here */ };
- var isValid = openAPISpecValidator.validate(jsonData, openAPISpec);
- pm.expect(isValid).to.be.true;
- });
- pm.test("Check for redirect under specific conditions", function () {
- // 在特定条件下,期望 302 状态码和正确的 Location 头
- pm.expect(pm.response.code).to.equal(302);
- pm.expect(pm.response.headers.get("Location")).to.equal("https://redirectedlocation.com");
- });
- pm.test("Dynamically build request using environment variables", function () {
- var apiKey = pm.environment.get("api_key");
- var requestUrl = `https://api.example.com/data?apiKey=${apiKey}`;
-
- // 发送请求
- pm.sendRequest({
- url: requestUrl,
- method: 'GET',
- // 其他请求选项...
- }, function (err, response) {
- // 处理响应...
- });
- });
- pm.test("Validate response against JSON Schema", function () {
- var jsonData = pm.response.json();
- var schema = {
- type: "object",
- properties: {
- key1: { type: "string" },
- key2: { type: "number" },
- key3: { type: "array" }
- },
- required: ["key1", "key2"]
- };
- pm.expect(jsonData).to.have.jsonSchema(schema);
- });
- pm.test("Validate date format and range", function () {
- var jsonData = pm.response.json();
- var dateFormat = /^\d{4}-\d{2}-\d{2}$/; // YYYY-MM-DD
- pm.expect(jsonData.date).to.match(dateFormat);
- pm.expect(new Date(jsonData.date)).to.be.within(new Date("2022-01-01"), new Date("2023-01-01"));
- });
- pm.test("Check nested properties in JSON response", function () {
- var jsonData = pm.response.json();
-
- // 验证嵌套属性
- pm.expect(jsonData).to.have.nested.property("parentProperty.childProperty").that.is.a("string");
- });
- pm.test("Run collection using Newman", function () {
- pm.expect(pm.info.iteration).to.equal(1); // 只在第一次迭代运行
-
- // 构建 Newman 命令
- var newmanCommand = `newman run ${__ENV.PATH_TO_COLLECTION} --reporters cli,json --reporter-json-export ${__ENV.PATH_TO_REPORT}`;
-
- // 执行命令
- var commandOutput = exec(newmanCommand);
-
- // 打印 Newman 输出
- console.log(commandOutput);
-
- // 检查 Newman 是否成功运行
- pm.expect(commandOutput).to.include("run completed");
- });
- pm.test("Check for a specific value in the response header", function () {
- pm.expect(pm.response.headers.get("Content-Encoding")).to.equal("gzip");
- });
- pm.test("Set request headers using environment variables", function () {
- var apiKey = pm.environment.get("api_key");
- pm.request.headers.upsert({ key: 'Authorization', value: `Bearer ${apiKey}` });
- });
- pm.test("Check if timestamp in the response is valid", function () {
- var jsonData = pm.response.json();
- var timestamp = jsonData.timestamp;
-
- // 验证 timestamp 是否为有效的 Unix 时间戳
- pm.expect(timestamp).to.be.above(0);
- });
- pm.test("Additional assertions using pm.response.to.be", function () {
- pm.response.to.be.ok; // 确保响应为真值
- pm.response.to.be.withBody; // 确保响应体存在
- pm.response.to.be.json; // 确保响应体为 JSON
- pm.response.to.be.header("Content-Type", "application/json"); // 确保 Content-Type 为 application/json
- });
- pm.test("Check if date in the response follows a specific format", function () {
- var jsonData = pm.response.json();
- var dateRegex = /^\d{4}-\d{2}-\d{2}$/; // 日期格式为 YYYY-MM-DD
- pm.expect(jsonData.date).to.match(dateRegex);
- });
- pm.test("Check if array elements are unique", function () {
- var jsonData = pm.response.json();
- var uniqueElements = new Set(jsonData.arrayProperty);
- pm.expect(uniqueElements.size).to.equal(jsonData.arrayProperty.length);
- });
- pm.test("Check if property value is within a specific range", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.propertyValue).to.be.within(1, 100);
- });
- // 在 "Tests" 脚本中使用 pm.sendRequest 重试请求,直到响应时间在指定范围内
- pm.test("Retry request until response time is within expected range", function () {
- var maxRetryCount = 5;
- var expectedResponseTime = 200; // 期望的响应时间
-
- pm.sendRequest(function () {
- return {
- url: pm.request.url,
- method: pm.request.method,
- header: pm.request.headers,
- body: pm.request.body
- };
- }, function (err, response) {
- pm.expect(response.responseTime).to.be.below(expectedResponseTime);
-
- if (response.responseTime > expectedResponseTime && pm.iteration < maxRetryCount) {
- // 重试请求
- return true;
- }
- });
- });

- pm.test("Check if property value meets a specific condition", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.propertyValue).to.satisfy(function (value) {
- return value > 0 && value % 2 === 0; // 满足大于0且为偶数的条件
- });
- });
- pm.test("Check if a property exists in the response", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData).to.have.property("propertyName");
- });
- pm.test("Check if a property is a boolean in the response", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.booleanProperty).to.be.a("boolean");
- });
- pm.test("Check if a property is a non-empty string in the response", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.stringProperty).to.be.a("string").and.to.not.be.empty;
- });
- pm.test("Check if a property is an array with length greater than zero", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.arrayProperty).to.be.an("array").and.to.have.length.above(0);
- });
- pm.test("Check if a property is an object with a specific key", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.objectProperty).to.be.an("object").and.to.have.property("specificKey");
- });
- pm.test("Check if a property is a number greater than a specific value", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.numberProperty).to.be.a("number").and.to.be.greaterThan(10);
- });
- // 自定义函数,用于验证属性是否为正偶数
- function isPositiveEvenNumber(value) {
- return typeof value === "number" && value > 0 && value % 2 === 0;
- }
-
- pm.test("Check if a property meets custom condition", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.customProperty).to.satisfy(isPositiveEvenNumber);
- });
- pm.test("Check if a property has one of the specified enum values", function () {
- var jsonData = pm.response.json();
- var enumValues = ["value1", "value2", "value3"];
- pm.expect(jsonData.enumProperty).to.be.oneOf(enumValues);
- });
- pm.test("Check if a property has a specific prefix or suffix", function () {
- var jsonData = pm.response.json();
- var prefix = "prefix_";
- var suffix = "_suffix";
- pm.expect(jsonData.stringProperty).to.startWith(prefix).and.to.endWith(suffix);
- });
- pm.test("Check if a property matches a specific regex pattern", function () {
- var jsonData = pm.response.json();
- var regexPattern = /^[\d]{3}-[\d]{2}-[\d]{4}$/; // 日期格式为 XXX-XX-XXXX
- pm.expect(jsonData.dateProperty).to.match(regexPattern);
- });
- pm.test("Check if a property contains a specific substring", function () {
- var jsonData = pm.response.json();
- var substring = "expectedSubstring";
- pm.expect(jsonData.stringProperty).to.include(substring);
- });
- pm.test("Check if array elements meet specific conditions", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.arrayProperty).to.satisfy(function (array) {
- return array.every(function (item) {
- return item.property > 0;
- });
- });
- });
- pm.test("Check if properties are correlated in the response", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.property1 + jsonData.property2).to.equal(jsonData.property3);
- });
- pm.test("Share variables across iterations and perform validation", function () {
- var jsonData = pm.response.json();
-
- // 将值保存到环境变量中以便在后续迭代中使用
- pm.environment.set("sharedVariable", jsonData.property);
-
- // 在后续迭代中验证共享变量的值
- if (pm.info.iteration > 1) {
- pm.expect(pm.environment.get("sharedVariable")).to.equal("expectedValue");
- }
- });
- pm.test("Share variables across requests and perform validation", function () {
- var jsonData = pm.response.json();
-
- // 将值保存到环境变量中以便在后续请求中使用
- pm.environment.set("sharedVariable", jsonData.property);
-
- // 发送后续请求,使用共享变量
- pm.sendRequest({
- url: 'https://api.example.com/nextRequest',
- method: 'GET',
- header: {
- 'Authorization': `Bearer ${pm.environment.get("sharedVariable")}`
- }
- // 其他请求选项...
- }, function (err, response) {
- // 处理响应...
- });
- });

- pm.test("Use custom message for clearer assertion", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.property, "Property should be equal to expected value").to.equal("expectedValue");
- });
- pm.test("Complex assertions using chained syntax", function () {
- var jsonData = pm.response.json();
-
- pm.expect(jsonData)
- .to.have.property("property1")
- .that.is.an("array")
- .and.to.have.lengthOf.at.least(1)
- .and.to.include("expectedValue");
- });
- pm.test("Find element in array that meets a condition", function () {
- var jsonData = pm.response.json();
-
- var matchingElement = jsonData.arrayProperty.find(function (item) {
- return item.property === "expectedValue";
- });
-
- pm.expect(matchingElement).to.exist;
- });
- pm.test("Data-driven testing using pm.iterationData", function () {
- var testData = pm.iterationData.get("testData");
- var jsonData = pm.response.json();
-
- pm.expect(jsonData.property).to.equal(testData.expectedValue);
- });
- pm.test("Check if a property is of a specific object type", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.objectProperty).to.be.an("object").that.has.all.keys("key1", "key2");
- });
- pm.test("Check if a property is of a specific array type", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.arrayProperty).to.be.an("array").that.includes("expectedValue");
- });
- pm.test("Check if a property is null or undefined", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.nullOrUndefinedProperty).to.be.oneOf([null, undefined]);
- });
- // 在 "Pre-request Script" 中生成 UUID 并设置为环境变量
- var uuid = require('uuid');
- pm.environment.set('dynamicUUID', uuid.v4());
- pm.test("Use dynamic timestamp in the test script", function () {
- var dynamicTimestamp = Math.floor(Date.now() / 1000);
- pm.expect(dynamicTimestamp).to.be.above(0);
- });
- pm.test("Check if property contains a key with a value meeting a condition", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.propertyObject).to.have.property("dynamicKey").that.satisfies(function (value) {
- return value > 0;
- });
- });
- pm.test("Check if property values are subsets of another property", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.propertySubset).to.have.all.keys("key1", "key2").and.to.include.all.values("value1", "value2");
- });
- pm.test("Conditional validation using environment variable", function () {
- var jsonData = pm.response.json();
- var shouldValidate = pm.environment.get("shouldValidate");
-
- if (shouldValidate === "true") {
- pm.expect(jsonData.property).to.equal("expectedValue");
- } else {
- console.log("Validation skipped based on environment variable.");
- }
- });
- pm.test("Check if property value is approximately equal to a specific number", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.propertyValue).to.be.closeTo(10.5, 0.1); // 允许的误差为0.1
- });
- pm.test("Check if property value matches a regular expression", function () {
- var jsonData = pm.response.json();
- var regexPattern = /^[A-Za-z]+$/; // 只包含字母的字符串
- pm.expect(jsonData.propertyValue).to.match(regexPattern);
- });
- pm.test("Check if property value is within a specified array range", function () {
- var jsonData = pm.response.json();
- var validValues = ["value1", "value2", "value3"];
- pm.expect(jsonData.propertyValue).to.be.oneOf(validValues);
- });
- pm.test("Check if property value is a truthy value", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.propertyValue).to.be.truthy;
- });
- pm.test("Assertion using pm.response.to.have.property", function () {
- pm.response.to.have.property("propertyName").that.is.a("string").and.to.equal("expectedValue");
- });
- // 自定义函数,用于验证属性是否为两个数字之和
- function isSumOfTwoNumbers(value, number1, number2) {
- return value === number1 + number2;
- }
-
- pm.test("Advanced validation using custom function", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.propertyValue).to.satisfy(isSumOfTwoNumbers, 5, 7);
- });
- pm.test("Dynamic validation using pm.iteration and environment variable", function () {
- var jsonData = pm.response.json();
- var expectedValue = pm.environment.get("expectedValue_" + pm.iteration);
-
- pm.expect(jsonData.propertyValue).to.equal(expectedValue);
- });
- // 在 "Pre-request Script" 中安装 lodash 库
- // npm install lodash
-
- var _ = require('lodash');
-
- pm.test("Deep comparison using pm.expect and lodash", function () {
- var expectedData = {
- key1: "value1",
- key2: {
- key3: "value3"
- }
- };
-
- var jsonData = pm.response.json();
- pm.expect(jsonData).to.deep.equal(expectedData);
- });

- // 在 "Pre-request Script" 中安装 Ajv 库
- // npm install ajv
-
- var Ajv = require('ajv');
- var ajv = new Ajv();
-
- pm.test("JSON Schema validation using pm.expect", function () {
- var jsonData = pm.response.json();
- var schema = {
- type: 'object',
- properties: {
- property1: { type: 'string' },
- property2: { type: 'number' }
- },
- required: ['property1', 'property2'],
- additionalProperties: false
- };
-
- var validate = ajv.compile(schema);
- var isValid = validate(jsonData);
-
- pm.expect(isValid, "Response doesn't match the expected JSON Schema").to.be.true;
- });

- // 在 "Pre-request Script" 中安装 xml2js 库
- // npm install xml2js
-
- var parseString = require('xml2js').parseString;
-
- pm.test("XML validation using pm.expect", function () {
- var xmlData = pm.response.text();
- var expectedXml = '<root><element>value</element></root>';
-
- parseString(xmlData, function (err, result) {
- var expectedResult;
- parseString(expectedXml, function (err, result) {
- expectedResult = result;
- });
-
- pm.expect(result).to.deep.equal(expectedResult);
- });
- });

- pm.test("Check if response time is within expected range", function () {
- pm.expect(pm.response.responseTime).to.be.below(1000); // 期望响应时间在1秒以内
- });
- pm.test("Dynamic validation using environment variable", function () {
- var jsonData = pm.response.json();
- var expectedValue = pm.environment.get("expectedValue");
-
- pm.expect(jsonData.property).to.equal(expectedValue);
- });
- pm.test("OAuth 2.0 validation using pm.expect", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.access_token).to.exist;
- pm.expect(jsonData.token_type).to.equal("Bearer");
- pm.expect(jsonData.expires_in).to.be.above(0);
- });
- pm.test("CSRF protection validation using pm.expect", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.csrfToken).to.exist;
- });
- pm.test("Check if HTTP response code is 200 OK", function () {
- pm.response.to.have.status(200);
- });
- pm.test("Check if response body length is within expected range", function () {
- pm.expect(pm.response.text().length).to.be.within(10, 1000);
- });
- pm.test("Check if HTML response contains expected element", function () {
- var htmlResponse = pm.response.text();
- pm.expect(htmlResponse).to.include('<title>Expected Title</title>');
- });
- pm.test("Check if response is a redirect", function () {
- pm.expect(pm.response.to.have.status(302));
- pm.expect(pm.response.to.have.header("Location", "https://new-location.com"));
- });
- pm.test("Check if response JSON contains expected value using JSONPath", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData).to.have.jsonPath("$.data[0].name", "Expected Name");
- });
- // 在 "Pre-request Script" 中安装 crypto-js 库
- // npm install crypto-js
-
- var CryptoJS = require("crypto-js");
-
- pm.test("HMAC signature validation using pm.expect", function () {
- var jsonData = pm.response.json();
- var secretKey = "yourSecretKey";
- var expectedSignature = CryptoJS.HmacSHA256(JSON.stringify(jsonData), secretKey).toString();
-
- pm.expect(jsonData.signature).to.equal(expectedSignature);
- });
- pm.test("Check if date property follows a specific format", function () {
- var jsonData = pm.response.json();
- var dateRegex = /^\d{4}-\d{2}-\d{2}$/; // 日期格式为 YYYY-MM-DD
- pm.expect(jsonData.dateProperty).to.match(dateRegex);
- });
- pm.test("GraphQL response validation using pm.expect", function () {
- var jsonData = pm.response.json();
-
- pm.expect(jsonData).to.have.property("data");
- pm.expect(jsonData.data).to.have.property("user");
- pm.expect(jsonData.data.user).to.have.property("name").that.is.a("string").and.to.equal("ExpectedName");
- });
- pm.test("Check if property contains specific elements", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.arrayProperty).to.include.members(["value1", "value2"]);
- });
- pm.test("Check if response headers contain specific key-value pairs", function () {
- pm.expect(pm.response.headers.get("Content-Type")).to.equal("application/json");
- pm.expect(pm.response.headers.get("Cache-Control")).to.include("max-age=3600");
- });
- pm.test("Check if property value is a boolean", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.booleanProperty).to.be.a("boolean");
- });
- pm.test("Check if property value is within a specified number range", function () {
- var jsonData = pm.response.json();
- pm.expect(jsonData.numberProperty).to.be.within(1, 100);
- });
关于postman的tests脚本,我整理的暂时就只有这么多,后续学到了新的test脚本的话我也会进行更新,如果大家有关于postman tests的其他脚本,欢迎大家补充分享。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。