【译】Postman脚本4-示例


test 脚本将会在发送请求并且从服务器中收到响应后运行。

让我们看一些使用 Postman 进行测试的例子,其中大多数都可以在 Postman 中的模版找到,你可以根据需求运行任意数量的测试。

环境

设置环境变量

pm.environment.set("variable_key", "variable_value");

将嵌套对象设置为环境变量

var array = [1, 2, 3, 4];
pm.environment.set("array", JSON.stringify(array, null, 2));

var obj = { a: [1, 2, 3, 4], b: { c: 'val' } };
pm.environment.set("obj", JSON.stringify(obj));

获取环境变量

var value = pm.environment.get("variable_key");

如果值是一个字符串格式的JSON:

// 如果数据来源未知,应该将这些语句放入 try-catch 中

var array = JSON.parse(pm.environment.get("array"));
var obj = JSON.parse(pm.environment.get("obj"));

清除环境变量

pm.environment.unset("variable_key");

集合

设置集合变量

pm.collectionVariables.set(variableName:String, variableValue:String);

获取集合变量

pm.collectionVariables.get(variableName:String);

清除集合变量

pm.collectionVariables.unset(variableName:String);

全局

设置全局变量

pm.globals.set("variable_key", "variable_value");

获取全局变量

pm.globals.get("variable_key");

清除全局变量

pm.globals.unset("variable_key");

变量

此函数在全局变量和当前环境中搜索变量

var value = pm.variables.get("variable_key");

response 处理

检查 response body 是否包含特定字符串

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

检查 response body 是否与特定字符串相等

pm.test("Body is correct", function () {
    pm.response.to.have.body("response_body_string");
});

检查JSON值

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

存在Content-Type

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

响应时间小于200毫秒

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

状态码为200

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

状态码名称中包含特定字符串

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

POST请求成功状态码

pm.test("Successful POST request", function () {
    pm.expect(pm.response.code).to.be.oneOf([201,202]);
});

验证 response 结构

使用 tv4 进行 JSON schema 验证

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;
});

使用 avj 进行 JSON schema 验证

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;
});

编码 / 解码

对 base64 数据进行解码

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

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

将 XML body 转换成 JSON 对象

var jsonObject = xml2Json(responseBody);

发送异步请求

此功能同时适用于 pre-request 脚本和 test 脚本

pm.sendRequest("https://postman-echo.com/get", function (err, response) {
    console.log(response.json());
});

样本数据文件

JSON 文件由键值对组成

下载JSON文件

对于 CSV 文件,第一行需要包含变量名

下载CSV文件

断言库示例

以下是 Postman 测试脚本中使用的一些最常见的断言测试列表。

请注意,此列表并不详尽,有关完整的参考,请查看以下文档 ChaiJS expect BDD library

断言目标中是否存在子字符串

pm.test("Check if pattern is in target string",function () {
    pm.expect('foobar').to.have.string('bar');
});

严格比较

const TEN = 10;
pm.test('Check if number is equal to 10', function () {
    pm.expect(TEN).to.equal(10);
});

非严格比较

pm.test("Our JSON is loosely equal to the provided JSON", function () {
 pm.expect(data1).to.deep.equal(data2);
});

注解:

  1. .deep 会导致调用链中的 .equal .include .members .keys 和 .property 断言使用相等而不是严格相等(===)。
  2. 虽然 .eql 也是宽松比较,但是 .deep.equal 会导致调用链之后的其它声明也是宽松比较,而 .eql 不会。

断言返回数据中的值

pm.test("Check response value", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.value).to.eql(100);
});

断言当前环境

pm.test("Check if environment is production", function () {
    pm.expect(pm.environment.get('env')).to.equal('production');
});

断言目标类型与特定字符串类型相等

pm.test("Check if target is string", function () {
   pm.expect('Postman').to.be.a('string');
});
pm.test("Check if target is an object", function () {
    pm.expect({a: 1}).to.be.an('object');
});
pm.test("Check if target is undefined", function () {
     pm.expect(undefined).to.be.an('undefined');
});

注解:

  1. 在对目标进行断言之前,最好使用 .a 检查一下目标的类型。
  2. 类型不区分大小写。

断言目标是否为空

pm.test("Check if array is empty", function () {
    expect([]).to.be.empty;
});
pm.test("Check if string is empty", function () {
    pm.expect('').to.be.empty;
});

可以将其与 .a 组合用来检查目标是否为空但是却拥有类型,例如数组或对象。

例如:

pm.test("Check if array is empty", function () {
    pm.expect([]).to.be.an('array').that.is.empty;
});

断言目标包含已经传递的 keys

pm.test("Check if object contains all provided keys", function () {
    pm.expect({a: 1, b: 2}).to.have.all.keys('a', 'b');
});
pm.test("Checking if object contains any ONE of the keys", function () {
    pm.expect({a: 1, b: 2}).to.have.any.keys('a', 'b');
});
pm.test("Check if object contains any NONE of the provided keys", function () {
    pm.expect({a: 1, b: 2}).to.not.have.any.keys('c', 'd');
});

断言目标包含描述属性

pm.test("Check if object contains the property", function () {
    pm.expect({a: 1}).to.have.property('a');
});

注解:

  1. 目标可以是对象,集合,数组和字典。
  2. 如果 .keys 不带 .all 或 .any 运行,表达式默认为 .all。
  3. 由于 .keys 根据目标的类型执行不同的操作,建议在使用 .keys 之前使用 .a 对目标进行类型检查。
pm.test("Check if object contains all the keys", function () {
    pm.expect({a: 1, b: 2}).to.be.an('object').that.has.all.keys('a', 'b');
});

断言目标长度

pm.test("Check the length of the target", function () {
    pm.expect('foo').to.have.lengthOf(3);
});
pm.test("Check the size of the target", function () {
    pm.expect([1, 2, 3]).to.have.lengthOf(2);
});

断言目标数组与特定数组有相同元素

pm.test("Check if the target has same members as the array set", function () {
    pm.expect([1, 2, 3]).to.have.members([2, 1, 3]);
});

注解:

  1. 默认情况下,.members 进行严格比较。
  2. 元素的顺序可以不一样。

断言目标包含提供的项

pm.test("Check if the target array includes the number provided", function () {
    pm.expect([1, 2, 3]).to.include(2);
});
pm.test("Check if the target object includes the properties provided", function () {
    pm.expect({a: 1, b: 2, c: 3}).to.include({a: 1, b: 2});
});

注解:建议首先声明目标的类型,因为 .include 可以对各种类型进行操作,所以建议在使用 .include 时同时使用 .a 。

例如:

pm.test("Check if the target is an array that includes the number specified", function () {
    pm.expect([1, 2, 3]).to.be.an('array').that.includes(2);
});

老版编写 Postman 测试的方法(不建议使用)

注解:本节涉及了在老版本 Postman 中编写测试的语法。如果你现在正准备编写测试,请使用上述语法。

老版本 Postman 编写测试依赖对特殊的测试对象设置值。你可以为对象中的一个元素设置一个描述key,然后判断它是 true 还是 false。例如:tests["Body contains user_id"] = responsebody.has("user_id");将检查 response body 中是否包含 user_id

你可以根据测试内容的需求来添加 keys。你可以在 tests 选项下的 response 视图区域查看测试结果。选项标题显示通过了多少测试,并且会列出你在 tests 变量中设置的 keys,如果值为 true,则测试通过。

设置环境变量(不建议使用)

postman.setEnvironmentVariable("key", "value");

将嵌套对象设置为环境变量(不建议使用)

var array = [1, 2, 3, 4];
postman.setEnvironmentVariable("array", JSON.stringify(array, null, 2));

var obj = { a: [1, 2, 3, 4], b: { c: 'val' } };
postman.setEnvironmentVariable("obj", JSON.stringify(obj));

获取环境变量(不建议使用)

postman.getEnvironmentVariable("key");

获取环境变量(值为字符串对象)(不建议使用)

// These statements should be wrapped in a try-catch block if the data is coming from an unknown source.

var array = JSON.parse(postman.getEnvironmentVariable("array"));
var obj = JSON.parse(postman.getEnvironmentVariable("obj"));

删除环境变量(不建议使用)

postman.clearEnvironmentVariable("key");

设置全局变量(不建议使用)

postman.setGlobalVariable("key", "value");

获取全局变量(不建议使用)

postman.getGlobalVariable("key");

删除全局变量(不建议使用)

postman.clearGlobalVariable("key");

检查 response body 中是否包含字符串(不建议使用)

tests["Body matches string"] = responseBody.has("string_you_want_to_search");

将 XML body 转换为 JSON 对象(不建议使用)

var jsonObject = xml2Json(responseBody);

检查 response body是否与字符串相等(不建议使用)

tests["Body is correct"] = responseBody === "response_body_string";

检查 JSON 值(不建议使用)

var data = JSON.parse(responseBody);
tests["Your test name"] = data.value === 100;

Content-Type 已存在(不区分大小写)(不建议使用)

tests["Content-Type is present"] = postman.getResponseHeader("Content-Type");
tests["Content-Type is present"] = postman.getResponseHeader("Content-Type");
//Note: the getResponseHeader() method returns the header value, if it exists.

Content-Type 已存在(区分大小写)(不建议使用)

tests["Content-Type is present"] = responseHeaders.hasOwnProperty("Content-Type");

响应时间小于200毫秒(不建议使用)

tests["Response time is less than 200ms"] = responseTime < 200;

响应时间在特定区间内(包含最小值,不包含最大值)(不建议使用)

tests["Response time is acceptable"] = _.inRange(responseTime, 100, 1001);
// _ is the inbuilt Lodash v3.10.1 object, documented at https://lodash.com/docs/3.10.1

状态码为200(不建议使用)

tests["Status code is 200"] = responseCode.code === 200;

状态码包含字符串(不建议使用)

tests["Status code name has string"] = responseCode.name.has("Created");

POST请求成功状态码(不建议使用)

tests["Successful POST request"] = responseCode.code === 201 || responseCode.code === 202;

为 JSON 数据使用 TinyValidator(不建议使用)

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

tests["Valid Data1"] = tv4.validate(data1, schema);
tests["Valid Data2"] = tv4.validate(data2, schema);
console.log("Validation failed: ", tv4.error);

对 base64 编码数据进行解码(不建议使用)

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
tests["Contents are valid"] = CryptoJS.enc.Utf8.stringify(intermediate); // a check for non-emptiness

文章作者: ASCII13
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 ASCII13 !
  目录