当前位置:   article > 正文

关于PostMan中Tests脚本的使用_postman tests脚本

postman tests脚本

不得不说PostMan真的是一个强大的接口测试工具,深得人心。

小编也在闲暇之余整理了一些有关于PostMan中的Tests脚本的示例,希望能帮助到热爱学习热爱工作的各位。

  1. 状态码验证:
    1. pm.test("Status code is 200", function () {
    2. pm.response.to.have.status(200);
    3. });
  2. 响应时间验证:
    1. pm.test("Response time is less than 500ms", function () {
    2. pm.expect(pm.response.responseTime).to.be.below(500);
    3. });
  3. JSON 响应体验证:
    1. pm.test("Response body has a valid key", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData).to.have.property('keyName');
    4. });
  4. 字符串匹配验证:
    1. pm.test("Response body contains expected text", function () {
    2. pm.expect(pm.response.text()).to.include("expectedText");
    3. });
  5. 数组长度验证
    1. pm.test("Response body has an array with at least 3 elements", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData.arrayProperty).to.have.lengthOf.at.least(3);
    4. });
  6. 数据类型验证:
    1. pm.test("Response body property has the correct data type", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData.propertyName).to.be.a('number');
    4. });
  7. 头部信息验证
    1. pm.test("Content-Type header is present", function () {
    2. pm.response.to.have.header("Content-Type");
    3. });
  8. 环境变量验证:
    1. pm.test("Environment variable has expected value", function () {
    2. pm.expect(pm.environment.get("variableName")).to.equal("expectedValue");
    3. });
  9. 响应体 JSON Schema 验证:
    1. pm.test("Response body follows JSON schema", function () {
    2. var jsonData = pm.response.json();
    3. var schema = {
    4. "type": "object",
    5. "properties": {
    6. "name": { "type": "string" },
    7. "age": { "type": "number" }
    8. },
    9. "required": ["name", "age"]
    10. };
    11. pm.expect(tv4.validate(jsonData, schema)).to.be.true;
    12. });
    13. //此示例使用 tv4 库进行 JSON Schema 验证。
  10. 多个条件的组合验证:
    1. pm.test("Multiple conditions combined", function () {
    2. var jsonData = pm.response.json();
    3. // Check multiple conditions
    4. pm.expect(jsonData.property1).to.equal("expectedValue1");
    5. pm.expect(jsonData.property2).to.be.an('array').that.includes('expectedValue2');
    6. pm.expect(jsonData.property3).to.have.lengthOf.at.most(5);
    7. });
  11. 日期格式验证:
    1. pm.test("Date format is valid", function () {
    2. var jsonData = pm.response.json();
    3. var dateFormat = /\d{4}-\d{2}-\d{2}/; // Example: YYYY-MM-DD
    4. pm.expect(jsonData.dateProperty).to.match(dateFormat);
    5. });
  12. 断言异常情况:有时,你可能需要验证 API 返回的错误状态。
    1. pm.test("Check for an error response", function () {
    2. pm.expect(pm.response.json().status).to.equal("error");
    3. });
  13. 验证数组元素
    1. pm.test("All items in the array meet a certain condition", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData.items).to.satisfy(function (items) {
    4. return items.every(function (item) {
    5. return item.property > 0;
    6. });
    7. });
    8. });
  14. 验证响应头信息:
    1. pm.test("Check for a specific header value", function () {
    2. pm.expect(pm.response.headers.get("Content-Type")).to.equal("application/json");
    3. });
  15. 环境变量和全局变量的更新:可以根据 API 响应更新环境变量或全局变量,以便后续请求使用更新后的值
    1. pm.test("Update environment variable based on response", function () {
    2. var jsonData = pm.response.json();
    3. pm.environment.set("variableName", jsonData.propertyToUpdate);
    4. });
  16. 文件上传后的验证:如果你的 API 支持文件上传,可以验证上传操作是否成功
    1. pm.test("Check if file upload was successful", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData.status).to.equal("success");
    4. pm.expect(jsonData.uploadedFiles.length).to.be.above(0);
    5. });
  17. 验证重定向:如果 API 返回了重定向响应,你可以验证重定向的状态码和目标地址。
    1. pm.test("Check for a redirect", function () {
    2. pm.expect(pm.response.code).to.be.oneOf([301, 302]);
    3. pm.expect(pm.response.headers.get("Location")).to.equal("https://newlocation.com");
    4. });
  18. 使用正则表达式进行文本匹配:使用正则表达式来验证响应体中的文本是否符合特定的模式。
    1. pm.test("Check for a specific pattern in the response body", function () {
    2. pm.expect(pm.response.text()).to.match(/PatternToMatch/);
    3. });
  19. 数据存在性验证:确保特定的键存在于响应体中。
    1. pm.test("Check if specific data exists in the response", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData).to.include.keys("expectedKey");
    4. });
  20. 比较两个响应体
    1. pm.test("Compare two response bodies", function () {
    2. var jsonData1 = pm.response.json();
    3. var jsonData2 = pm.iterationData.get("expectedResponse");
    4. pm.expect(jsonData1).to.eql(jsonData2);
    5. });
  21. 验证响应时间是否在一定范围内:确保 API 的响应时间在预期的范围内。
    1. pm.test("Response time is within an acceptable range", function () {
    2. pm.expect(pm.response.responseTime).to.be.within(100, 1000); // 100ms to 1000ms
    3. });
  22. 验证响应头信息是否包含特定值:检查响应头信息中是否包含特定值。
    1. pm.test("Check for a specific value in the response header", function () {
    2. pm.expect(pm.response.headers.get("Content-Type")).to.include("application/json");
    3. });
  23. 验证响应体中数组元素的属性:遍历数组中的每个元素并验证其属性。
    1. pm.test("Check properties of each item in the array", function () {
    2. var jsonData = pm.response.json();
    3. jsonData.forEach(function (item) {
    4. pm.expect(item).to.have.property("propertyName");
    5. });
    6. });
  24. 验证响应体中对象的值是否满足条件:确保对象的属性值满足特定条件。
    1. pm.test("Check if object properties meet certain conditions", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData.propertyName).to.satisfy(function (value) {
    4. return value > 0 && value < 100;
    5. });
    6. });
  25. 使用外部库进行验证:如果需要进行更复杂的验证,你可以引入外部库并使用它来验证响应。
    1. pm.test("Use external library for advanced validation", function () {
    2. var jsonData = pm.response.json();
    3. var isValid = externalLibrary.validate(jsonData);
    4. pm.expect(isValid).to.be.true;
    5. });
  26. 测试脚本中的日志记录:在测试脚本中使用 console.log 记录信息,有助于调试和定位问题。
    1. pm.test("Logging information for debugging", function () {
    2. var jsonData = pm.response.json();
    3. console.log("Response data:", jsonData);
    4. pm.expect(jsonData).to.have.property("expectedKey");
    5. });
  27. 验证响应头信息中是否包含特定的 Cookie:
    1. pm.test("Check for a specific cookie in the response headers", function () {
    2. pm.expect(pm.response.headers.has("Set-Cookie")).to.be.true;
    3. });
  28. 使用 Chai 库进行更丰富的断言:如果你想使用更丰富的断言功能,可以结合 Chai 库 使用。首先,在 Postman 的 "Pre-request Script" 或 "Tests" 中添加以下代码:
    1. // 引入 Chai 库
    2. var chai = require('chai');
    3. // 使用 Chai 断言库的 BDD 风格
    4. var expect = chai.expect;

            然后,你可以在测试脚本中使用 Chai 提供的更多断言功能:使用 Chai 能够提供更多的断言选项和更清晰的测试语法。

    1. pm.test("Use Chai for advanced assertions", function () {
    2. var jsonData = pm.response.json();
    3. // 使用 Chai 断言
    4. expect(jsonData).to.have.property("propertyName").that.is.a("string");
    5. expect(jsonData.arrayProperty).to.be.an("array").that.includes("expectedValue");
    6. });
  29. 在循环中执行测试:在循环中执行测试,适用于需要对数组中的每个元素进行相同验证的情况。
    1. pm.test("Loop through array elements for validation", function () {
    2. var jsonData = pm.response.json();
    3. // 假设 responseData 是一个数组
    4. jsonData.forEach(function (item) {
    5. pm.test("Check individual item", function () {
    6. pm.expect(item).to.have.property("property").that.is.a("string");
    7. // 添加更多的断言...
    8. });
    9. });
    10. });
  30. 验证响应体是否符合 OpenAPI 规范:如果你有 OpenAPI 规范,可以使用相应的库验证响应是否符合规范。
    1. pm.test("Validate response against OpenAPI specification", function () {
    2. var jsonData = pm.response.json();
    3. var openAPISpec = { /* Your OpenAPI specification here */ };
    4. var isValid = openAPISpecValidator.validate(jsonData, openAPISpec);
    5. pm.expect(isValid).to.be.true;
    6. });
  31. 验证特定条件下的重定向:在某些情况下验证 API 返回的重定向。
    1. pm.test("Check for redirect under specific conditions", function () {
    2. // 在特定条件下,期望 302 状态码和正确的 Location 头
    3. pm.expect(pm.response.code).to.equal(302);
    4. pm.expect(pm.response.headers.get("Location")).to.equal("https://redirectedlocation.com");
    5. });
  32. 使用环境变量动态构建请求:
    1. pm.test("Dynamically build request using environment variables", function () {
    2. var apiKey = pm.environment.get("api_key");
    3. var requestUrl = `https://api.example.com/data?apiKey=${apiKey}`;
    4. // 发送请求
    5. pm.sendRequest({
    6. url: requestUrl,
    7. method: 'GET',
    8. // 其他请求选项...
    9. }, function (err, response) {
    10. // 处理响应...
    11. });
    12. });
  33. 验证响应体是否符合 JSON Schema:使用 Postman 的内置 JSON Schema 验证功能,确保响应体符合预期的 JSON Schema。
    1. pm.test("Validate response against JSON Schema", function () {
    2. var jsonData = pm.response.json();
    3. var schema = {
    4. type: "object",
    5. properties: {
    6. key1: { type: "string" },
    7. key2: { type: "number" },
    8. key3: { type: "array" }
    9. },
    10. required: ["key1", "key2"]
    11. };
    12. pm.expect(jsonData).to.have.jsonSchema(schema);
    13. });
  34. 验证日期的格式和范围:
    1. pm.test("Validate date format and range", function () {
    2. var jsonData = pm.response.json();
    3. var dateFormat = /^\d{4}-\d{2}-\d{2}$/; // YYYY-MM-DD
    4. pm.expect(jsonData.date).to.match(dateFormat);
    5. pm.expect(new Date(jsonData.date)).to.be.within(new Date("2022-01-01"), new Date("2023-01-01"));
    6. });
  35. 验证 JSON 响应体中的嵌套属性:用于验证 JSON 响应体中的嵌套属性。
    1. pm.test("Check nested properties in JSON response", function () {
    2. var jsonData = pm.response.json();
    3. // 验证嵌套属性
    4. pm.expect(jsonData).to.have.nested.property("parentProperty.childProperty").that.is.a("string");
    5. });
  36. 使用 Newman 运行 Postman 集合并生成报告:在 Postman 的 "Tests" 中使用 Newman 运行集合,并将结果保存为报告。
    1. pm.test("Run collection using Newman", function () {
    2. pm.expect(pm.info.iteration).to.equal(1); // 只在第一次迭代运行
    3. // 构建 Newman 命令
    4. var newmanCommand = `newman run ${__ENV.PATH_TO_COLLECTION} --reporters cli,json --reporter-json-export ${__ENV.PATH_TO_REPORT}`;
    5. // 执行命令
    6. var commandOutput = exec(newmanCommand);
    7. // 打印 Newman 输出
    8. console.log(commandOutput);
    9. // 检查 Newman 是否成功运行
    10. pm.expect(commandOutput).to.include("run completed");
    11. });
  37. 验证响应头信息中是否包含特定的值:检查响应头信息中是否包含特定的值,例如压缩编码方式。
    1. pm.test("Check for a specific value in the response header", function () {
    2. pm.expect(pm.response.headers.get("Content-Encoding")).to.equal("gzip");
    3. });
  38. 使用环境变量设置请求头信息:在测试脚本中使用环境变量设置请求头信息,适用于需要动态设置请求头的情况。
    1. pm.test("Set request headers using environment variables", function () {
    2. var apiKey = pm.environment.get("api_key");
    3. pm.request.headers.upsert({ key: 'Authorization', value: `Bearer ${apiKey}` });
    4. });
  39. 验证响应体中的时间戳是否有效:
    1. pm.test("Check if timestamp in the response is valid", function () {
    2. var jsonData = pm.response.json();
    3. var timestamp = jsonData.timestamp;
    4. // 验证 timestamp 是否为有效的 Unix 时间戳
    5. pm.expect(timestamp).to.be.above(0);
    6. });
  40. 使用 pm.response.to.be.* 进行更多的断言:Postman 提供了一组 pm.response.to.be.* 的断言,用于更方便的验证响应。
    1. pm.test("Additional assertions using pm.response.to.be", function () {
    2. pm.response.to.be.ok; // 确保响应为真值
    3. pm.response.to.be.withBody; // 确保响应体存在
    4. pm.response.to.be.json; // 确保响应体为 JSON
    5. pm.response.to.be.header("Content-Type", "application/json"); // 确保 Content-Type 为 application/json
    6. });
  41. 验证响应体中的日期格式:使用正则表达式验证响应体中的日期格式。
    1. pm.test("Check if date in the response follows a specific format", function () {
    2. var jsonData = pm.response.json();
    3. var dateRegex = /^\d{4}-\d{2}-\d{2}$/; // 日期格式为 YYYY-MM-DD
    4. pm.expect(jsonData.date).to.match(dateRegex);
    5. });
  42. 验证数组中元素的唯一性:确保数组中的元素是唯一的。
    1. pm.test("Check if array elements are unique", function () {
    2. var jsonData = pm.response.json();
    3. var uniqueElements = new Set(jsonData.arrayProperty);
    4. pm.expect(uniqueElements.size).to.equal(jsonData.arrayProperty.length);
    5. });
  43. 验证响应体中某个属性的值在一定范围内:验证响应体中某个属性的值是否在指定范围内。
    1. pm.test("Check if property value is within a specific range", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData.propertyValue).to.be.within(1, 100);
    4. });
  44. 在预期的响应时间内重试请求:在测试脚本中使用 pm.sendRequest 来重试请求,直到满足预期的响应时间条件。
    1. // 在 "Tests" 脚本中使用 pm.sendRequest 重试请求,直到响应时间在指定范围内
    2. pm.test("Retry request until response time is within expected range", function () {
    3. var maxRetryCount = 5;
    4. var expectedResponseTime = 200; // 期望的响应时间
    5. pm.sendRequest(function () {
    6. return {
    7. url: pm.request.url,
    8. method: pm.request.method,
    9. header: pm.request.headers,
    10. body: pm.request.body
    11. };
    12. }, function (err, response) {
    13. pm.expect(response.responseTime).to.be.below(expectedResponseTime);
    14. if (response.responseTime > expectedResponseTime && pm.iteration < maxRetryCount) {
    15. // 重试请求
    16. return true;
    17. }
    18. });
    19. });
  45. 验证响应体中的属性值是否满足某个条件:
    1. pm.test("Check if property value meets a specific condition", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData.propertyValue).to.satisfy(function (value) {
    4. return value > 0 && value % 2 === 0; // 满足大于0且为偶数的条件
    5. });
    6. });
  46. 验证响应体中的属性是否存在:确保响应体中包含指定的属性。
    1. pm.test("Check if a property exists in the response", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData).to.have.property("propertyName");
    4. });
  47. 验证响应体中的属性是否为布尔值:确保响应体中的属性是布尔类型。
    1. pm.test("Check if a property is a boolean in the response", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData.booleanProperty).to.be.a("boolean");
    4. });
  48. 验证响应体中的属性是否为字符串并且不为空:确保响应体中的属性是非空字符串。
    1. pm.test("Check if a property is a non-empty string in the response", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData.stringProperty).to.be.a("string").and.to.not.be.empty;
    4. });
  49. 验证响应体中的属性是否为数组并且长度大于零:确保响应体中的属性是数组且长度大于零。
    1. pm.test("Check if a property is an array with length greater than zero", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData.arrayProperty).to.be.an("array").and.to.have.length.above(0);
    4. });
  50. 验证响应体中的属性是否为对象并且包含指定键:确保响应体中的属性是对象并且包含指定的键。
    1. pm.test("Check if a property is an object with a specific key", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData.objectProperty).to.be.an("object").and.to.have.property("specificKey");
    4. });
  51. 验证响应体中的属性是否为数字并且大于某个值:
    1. pm.test("Check if a property is a number greater than a specific value", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData.numberProperty).to.be.a("number").and.to.be.greaterThan(10);
    4. });
  52. 验证响应体中的属性是否满足自定义函数定义的条件:自定义函数用于验证响应体中的属性是否满足特定条件。
    1. // 自定义函数,用于验证属性是否为正偶数
    2. function isPositiveEvenNumber(value) {
    3. return typeof value === "number" && value > 0 && value % 2 === 0;
    4. }
    5. pm.test("Check if a property meets custom condition", function () {
    6. var jsonData = pm.response.json();
    7. pm.expect(jsonData.customProperty).to.satisfy(isPositiveEvenNumber);
    8. });
  53. 验证响应体中的属性是否为特定枚举值之一:确保响应体中的属性是特定枚举值之一。
    1. pm.test("Check if a property has one of the specified enum values", function () {
    2. var jsonData = pm.response.json();
    3. var enumValues = ["value1", "value2", "value3"];
    4. pm.expect(jsonData.enumProperty).to.be.oneOf(enumValues);
    5. });
  54. 验证响应体中的属性是否为特定字符串的前缀或后缀:确保响应体中的属性是特定字符串的前缀或后缀。
    1. pm.test("Check if a property has a specific prefix or suffix", function () {
    2. var jsonData = pm.response.json();
    3. var prefix = "prefix_";
    4. var suffix = "_suffix";
    5. pm.expect(jsonData.stringProperty).to.startWith(prefix).and.to.endWith(suffix);
    6. });
  55. 验证响应体中的属性是否为特定正则表达式的匹配:确保响应体中的属性匹配指定的正则表达式。
    1. pm.test("Check if a property matches a specific regex pattern", function () {
    2. var jsonData = pm.response.json();
    3. var regexPattern = /^[\d]{3}-[\d]{2}-[\d]{4}$/; // 日期格式为 XXX-XX-XXXX
    4. pm.expect(jsonData.dateProperty).to.match(regexPattern);
    5. });
  56. 验证响应体中的属性是否包含某个子字符串:
    1. pm.test("Check if a property contains a specific substring", function () {
    2. var jsonData = pm.response.json();
    3. var substring = "expectedSubstring";
    4. pm.expect(jsonData.stringProperty).to.include(substring);
    5. });
  57. 验证响应体中数组元素的属性是否满足条件:确保数组中的每个元素的属性满足特定条件。
    1. pm.test("Check if array elements meet specific conditions", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData.arrayProperty).to.satisfy(function (array) {
    4. return array.every(function (item) {
    5. return item.property > 0;
    6. });
    7. });
    8. });
  58. 验证响应体中属性的值是否与其他属性的值相关联:确保响应体中的属性值之间存在关联关系。
    1. pm.test("Check if properties are correlated in the response", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData.property1 + jsonData.property2).to.equal(jsonData.property3);
    4. });
  59. 在多次迭代中共享变量并进行验证:在多次迭代中共享变量,并在后续迭代中进行验证。
    1. pm.test("Share variables across iterations and perform validation", function () {
    2. var jsonData = pm.response.json();
    3. // 将值保存到环境变量中以便在后续迭代中使用
    4. pm.environment.set("sharedVariable", jsonData.property);
    5. // 在后续迭代中验证共享变量的值
    6. if (pm.info.iteration > 1) {
    7. pm.expect(pm.environment.get("sharedVariable")).to.equal("expectedValue");
    8. }
    9. });
  60. 在请求之间共享变量并进行验证:在请求之间共享变量,并在后续请求中进行验证。
    1. pm.test("Share variables across requests and perform validation", function () {
    2. var jsonData = pm.response.json();
    3. // 将值保存到环境变量中以便在后续请求中使用
    4. pm.environment.set("sharedVariable", jsonData.property);
    5. // 发送后续请求,使用共享变量
    6. pm.sendRequest({
    7. url: 'https://api.example.com/nextRequest',
    8. method: 'GET',
    9. header: {
    10. 'Authorization': `Bearer ${pm.environment.get("sharedVariable")}`
    11. }
    12. // 其他请求选项...
    13. }, function (err, response) {
    14. // 处理响应...
    15. });
    16. });
  61. 使用 pm.expect 的自定义消息进行更清晰的断言:
    1. pm.test("Use custom message for clearer assertion", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData.property, "Property should be equal to expected value").to.equal("expectedValue");
    4. });
  62. 使用 pm.expect 的 to.be 链式语法进行更复杂的断言:
    1. pm.test("Complex assertions using chained syntax", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData)
    4. .to.have.property("property1")
    5. .that.is.an("array")
    6. .and.to.have.lengthOf.at.least(1)
    7. .and.to.include("expectedValue");
    8. });
  63. 在数组中查找满足条件的元素:
    1. pm.test("Find element in array that meets a condition", function () {
    2. var jsonData = pm.response.json();
    3. var matchingElement = jsonData.arrayProperty.find(function (item) {
    4. return item.property === "expectedValue";
    5. });
    6. pm.expect(matchingElement).to.exist;
    7. });
  64. 使用 pm.iterationData 进行数据驱动测试:使用 pm.iterationData 进行数据驱动测试,通过外部数据文件或数据集合进行迭代测试。
    1. pm.test("Data-driven testing using pm.iterationData", function () {
    2. var testData = pm.iterationData.get("testData");
    3. var jsonData = pm.response.json();
    4. pm.expect(jsonData.property).to.equal(testData.expectedValue);
    5. });
  65. 验证响应体中的属性是否为特定类型的对象:确保响应体中的属性是特定类型的对象,并包含指定的键。
    1. pm.test("Check if a property is of a specific object type", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData.objectProperty).to.be.an("object").that.has.all.keys("key1", "key2");
    4. });
  66. 验证响应体中的属性是否为特定类型的数组:
    1. pm.test("Check if a property is of a specific array type", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData.arrayProperty).to.be.an("array").that.includes("expectedValue");
    4. });
  67. 验证响应体中的属性是否为 null 或 undefined:确保响应体中的属性为 null 或 undefined。
    1. pm.test("Check if a property is null or undefined", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData.nullOrUndefinedProperty).to.be.oneOf([null, undefined]);
    4. });
  68. 在请求中使用动态生成的 UUID:在 "Pre-request Script" 中使用 uuid 库生成 UUID,并将其设置为环境变量,然后在请求中使用。
    1. // 在 "Pre-request Script" 中生成 UUID 并设置为环境变量
    2. var uuid = require('uuid');
    3. pm.environment.set('dynamicUUID', uuid.v4());
  69. 在测试脚本中使用动态生成的时间戳:在测试脚本中生成动态的时间戳进行验证
    1. pm.test("Use dynamic timestamp in the test script", function () {
    2. var dynamicTimestamp = Math.floor(Date.now() / 1000);
    3. pm.expect(dynamicTimestamp).to.be.above(0);
    4. });
  70. 验证响应体中的属性是否包含某个键,并且该键的值满足条件:
    1. pm.test("Check if property contains a key with a value meeting a condition", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData.propertyObject).to.have.property("dynamicKey").that.satisfies(function (value) {
    4. return value > 0;
    5. });
    6. });
  71. 验证响应体中的属性值是否是指定属性的子集:
    1. pm.test("Check if property values are subsets of another property", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData.propertySubset).to.have.all.keys("key1", "key2").and.to.include.all.values("value1", "value2");
    4. });
  72. 在测试脚本中使用环境变量进行条件性验证:在测试脚本中使用环境变量进行条件性验证,根据环境变量的值决定是否执行特定的断言。
    1. pm.test("Conditional validation using environment variable", function () {
    2. var jsonData = pm.response.json();
    3. var shouldValidate = pm.environment.get("shouldValidate");
    4. if (shouldValidate === "true") {
    5. pm.expect(jsonData.property).to.equal("expectedValue");
    6. } else {
    7. console.log("Validation skipped based on environment variable.");
    8. }
    9. });
  73. 验证响应体中的属性值是否近似等于某个数值:确保响应体中的属性值近似等于指定的数值,可以设置一个允许的误差范围。
    1. pm.test("Check if property value is approximately equal to a specific number", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData.propertyValue).to.be.closeTo(10.5, 0.1); // 允许的误差为0.1
    4. });
  74. 验证响应体中的属性值是否满足正则表达式的条件:使用正则表达式验证响应体中的属性值是否满足特定的条件。
    1. pm.test("Check if property value matches a regular expression", function () {
    2. var jsonData = pm.response.json();
    3. var regexPattern = /^[A-Za-z]+$/; // 只包含字母的字符串
    4. pm.expect(jsonData.propertyValue).to.match(regexPattern);
    5. });
  75. 验证响应体中的属性值是否在指定的数组范围内:
    1. pm.test("Check if property value is within a specified array range", function () {
    2. var jsonData = pm.response.json();
    3. var validValues = ["value1", "value2", "value3"];
    4. pm.expect(jsonData.propertyValue).to.be.oneOf(validValues);
    5. });
  76. 验证响应体中的属性值是否为真值(例如,非空字符串、非零数字等):
    1. pm.test("Check if property value is a truthy value", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData.propertyValue).to.be.truthy;
    4. });
  77. 在测试脚本中使用 pm.response.to.have.property 进行断言:
    1. pm.test("Assertion using pm.response.to.have.property", function () {
    2. pm.response.to.have.property("propertyName").that.is.a("string").and.to.equal("expectedValue");
    3. });
  78. 在测试脚本中使用 pm.expect 和自定义函数进行高级验证:例如验证属性是否为两个数字之和。
    1. // 自定义函数,用于验证属性是否为两个数字之和
    2. function isSumOfTwoNumbers(value, number1, number2) {
    3. return value === number1 + number2;
    4. }
    5. pm.test("Advanced validation using custom function", function () {
    6. var jsonData = pm.response.json();
    7. pm.expect(jsonData.propertyValue).to.satisfy(isSumOfTwoNumbers, 5, 7);
    8. });
  79. 在测试脚本中使用 pm.iteration 和环境变量进行动态验证:根据迭代次数动态获取期望值
    1. pm.test("Dynamic validation using pm.iteration and environment variable", function () {
    2. var jsonData = pm.response.json();
    3. var expectedValue = pm.environment.get("expectedValue_" + pm.iteration);
    4. pm.expect(jsonData.propertyValue).to.equal(expectedValue);
    5. });
  80. 在测试脚本中使用pm.expect 和 lodash 库进行深度比较:
    1. // 在 "Pre-request Script" 中安装 lodash 库
    2. // npm install lodash
    3. var _ = require('lodash');
    4. pm.test("Deep comparison using pm.expect and lodash", function () {
    5. var expectedData = {
    6. key1: "value1",
    7. key2: {
    8. key3: "value3"
    9. }
    10. };
    11. var jsonData = pm.response.json();
    12. pm.expect(jsonData).to.deep.equal(expectedData);
    13. });
  81. 在测试脚本中使用 pm.expect 进行 JSON Schema 验证:
    1. // 在 "Pre-request Script" 中安装 Ajv 库
    2. // npm install ajv
    3. var Ajv = require('ajv');
    4. var ajv = new Ajv();
    5. pm.test("JSON Schema validation using pm.expect", function () {
    6. var jsonData = pm.response.json();
    7. var schema = {
    8. type: 'object',
    9. properties: {
    10. property1: { type: 'string' },
    11. property2: { type: 'number' }
    12. },
    13. required: ['property1', 'property2'],
    14. additionalProperties: false
    15. };
    16. var validate = ajv.compile(schema);
    17. var isValid = validate(jsonData);
    18. pm.expect(isValid, "Response doesn't match the expected JSON Schema").to.be.true;
    19. });
  82. 在测试脚本中使用 pm.expect 进行 XML 验证:
    1. // 在 "Pre-request Script" 中安装 xml2js 库
    2. // npm install xml2js
    3. var parseString = require('xml2js').parseString;
    4. pm.test("XML validation using pm.expect", function () {
    5. var xmlData = pm.response.text();
    6. var expectedXml = '<root><element>value</element></root>';
    7. parseString(xmlData, function (err, result) {
    8. var expectedResult;
    9. parseString(expectedXml, function (err, result) {
    10. expectedResult = result;
    11. });
    12. pm.expect(result).to.deep.equal(expectedResult);
    13. });
    14. });
  83. 在测试脚本中使用 pm.test 进行响应时间的验证:确保响应时间在指定的范围内。
    1. pm.test("Check if response time is within expected range", function () {
    2. pm.expect(pm.response.responseTime).to.be.below(1000); // 期望响应时间在1秒以内
    3. });
  84. 在测试脚本中使用 pm.environment 进行环境变量的动态验证:
    1. pm.test("Dynamic validation using environment variable", function () {
    2. var jsonData = pm.response.json();
    3. var expectedValue = pm.environment.get("expectedValue");
    4. pm.expect(jsonData.property).to.equal(expectedValue);
    5. });
  85. 在测试脚本中使用 pm.expect 进行 OAuth 2.0 验证:确保响应包含必要的 OAuth 2.0 令牌信息。
    1. pm.test("OAuth 2.0 validation using pm.expect", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData.access_token).to.exist;
    4. pm.expect(jsonData.token_type).to.equal("Bearer");
    5. pm.expect(jsonData.expires_in).to.be.above(0);
    6. });
  86. 在测试脚本中使用 pm.expect 验证跨站请求伪造(CSRF)保护:确保实施了跨站请求伪造保护。
    1. pm.test("CSRF protection validation using pm.expect", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData.csrfToken).to.exist;
    4. });
  87. 在测试脚本中使用 pm.expect 进行 HTTP 响应码验证:确保响应码是 200。
    1. pm.test("Check if HTTP response code is 200 OK", function () {
    2. pm.response.to.have.status(200);
    3. });
  88. 在测试脚本中使用 pm.expect 验证响应体长度:
    1. pm.test("Check if response body length is within expected range", function () {
    2. pm.expect(pm.response.text().length).to.be.within(10, 1000);
    3. });
  89. 在测试脚本中使用 pm.expect 进行 HTML 响应内容验证:确保响应中包含预期的 HTML 元素。
    1. pm.test("Check if HTML response contains expected element", function () {
    2. var htmlResponse = pm.response.text();
    3. pm.expect(htmlResponse).to.include('<title>Expected Title</title>');
    4. });
  90. 在测试脚本中使用 pm.expect 验证重定向:检查重定向的目标地址。
    1. pm.test("Check if response is a redirect", function () {
    2. pm.expect(pm.response.to.have.status(302));
    3. pm.expect(pm.response.to.have.header("Location", "https://new-location.com"));
    4. });
  91. 在测试脚本中使用 pm.expect 验证响应体的 JSONPath 表达式:
    1. pm.test("Check if response JSON contains expected value using JSONPath", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData).to.have.jsonPath("$.data[0].name", "Expected Name");
    4. });
  92. 在测试脚本中使用 pm.expect 进行 HMAC 签名验证:
    1. // 在 "Pre-request Script" 中安装 crypto-js 库
    2. // npm install crypto-js
    3. var CryptoJS = require("crypto-js");
    4. pm.test("HMAC signature validation using pm.expect", function () {
    5. var jsonData = pm.response.json();
    6. var secretKey = "yourSecretKey";
    7. var expectedSignature = CryptoJS.HmacSHA256(JSON.stringify(jsonData), secretKey).toString();
    8. pm.expect(jsonData.signature).to.equal(expectedSignature);
    9. });
  93. 在测试脚本中使用 pm.expect 验证响应体中的属性是否是特定日期格式:
    1. pm.test("Check if date property follows a specific format", function () {
    2. var jsonData = pm.response.json();
    3. var dateRegex = /^\d{4}-\d{2}-\d{2}$/; // 日期格式为 YYYY-MM-DD
    4. pm.expect(jsonData.dateProperty).to.match(dateRegex);
    5. });
  94. 在测试脚本中使用 pm.expect 进行 GraphQL 响应验证:
    1. pm.test("GraphQL response validation using pm.expect", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData).to.have.property("data");
    4. pm.expect(jsonData.data).to.have.property("user");
    5. pm.expect(jsonData.data.user).to.have.property("name").that.is.a("string").and.to.equal("ExpectedName");
    6. });
  95. 在测试脚本中使用 pm.expect 验证响应体中的属性是否包含特定元素:
    1. pm.test("Check if property contains specific elements", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData.arrayProperty).to.include.members(["value1", "value2"]);
    4. });
  96. 在测试脚本中使用 pm.expect 验证响应头中是否包含特定键值对:
    1. pm.test("Check if response headers contain specific key-value pairs", function () {
    2. pm.expect(pm.response.headers.get("Content-Type")).to.equal("application/json");
    3. pm.expect(pm.response.headers.get("Cache-Control")).to.include("max-age=3600");
    4. });
  97. 在测试脚本中使用 pm.expect 验证响应体中的属性值是否为布尔类型:
    1. pm.test("Check if property value is a boolean", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData.booleanProperty).to.be.a("boolean");
    4. });
  98. 在测试脚本中使用 pm.expect 验证响应体中的属性值是否在指定的数字范围内:
    1. pm.test("Check if property value is within a specified number range", function () {
    2. var jsonData = pm.response.json();
    3. pm.expect(jsonData.numberProperty).to.be.within(1, 100);
    4. });

    关于postman的tests脚本,我整理的暂时就只有这么多,后续学到了新的test脚本的话我也会进行更新,如果大家有关于postman tests的其他脚本,欢迎大家补充分享。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/832274
推荐阅读
相关标签
  

闽ICP备14008679号