postman test examples

原文链接:https://learning.getpostman.com/docs/postman/scripts/test-examples/


Test scripts are run after a request is sent and a response has been received from the server.

Let’s look at some examples of Postman tests. Most of these are available as snippets inside Postman. You can run as many tests as you want for a request.

Environments

Setting an environment variable

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

Setting a nested object as an environment variable

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

Getting an environment variable

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

If the value is a stringified JSON:

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

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

Clear an environment variable

pm.environment.unset("variable_key");

Collection

Setting an collection variable

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

Get a collection variable

pm.collectionVariables.get(variableName:String);

Clear a collection variable

pm.collectionVariables.unset(variableName:String);

Globals

Set a global variable

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

Get a global variable

pm.globals.get("variable_key");

Clear a global variable

pm.globals.unset("variable_key");

Variables

This function searches for the variable across globals and the active environment.

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

Response handling

Check if response body contains a string

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

Check if response body is equal to a string

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

Check for a JSON value

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

Content-Type header is present

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

Response time is less than 200ms

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

Status code is 200

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

Code name contains a string

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

Successful POST request status code

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

Validate response structure

JSON schema validation with tv4

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

JSON schema validation with ajv

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

Encode/decode

Decode base64 data

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

Convert XML body to a JSON object

var jsonObject = xml2Json(responseBody);

Send an asynchronous request

This function is available as both a pre-request and test script.

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

Sample data files

JSON files are composed of key/value pairs.

Download JSON file

For CSV files, the top row needs to contain variable names.

Download CSV file


Assertion library examples

Following is a list of some of the most common assertion tests used in the Postman test scripts.

Note that this list is not exhaustive. For the complete reference, see the documentation at: ChaiJS expect BDD library

Assert if substring exists in target

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

Strict Comparison

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

Loose comparison

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

Note:

  1. .deep causes all .equal, .include, .members, .keys, and .property assertions that follow in the chain to use deep equality(loose equality) instead of strict (===) equality.
  2. While the .eql also compares loosely, .deep.equal causes deep equality comparisons to also be used for any other assertions that follow in the chain while .eql does not.

Assert the value of response

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

Assert the current environment

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

Assert the type of the target is equal to the given string type

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

Note:

  1. It’s often best to use .a to check a target’s type before making more assertions on the same target.
  2. Types are case insensitive.

Assert if the target is empty

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

This can be combined with .a to check if the target is empty but has a type, say for example an array or an object.

Example:

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

Assert that the target contains the keys passed

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

Assert that the target contains said property

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

Note:

  1. Target can be an object, set, array or map.
  2. If .keys is run without .all or .any, the expression defaults to .all.
  3. As .keys does different things based on the target’s type, it’s recommended to check the target’s type before using .keys using .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');
    });

Assert the length of target

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

Assert that the target array has the same members as the given array set

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

Note:

  1. By default, .members makes strict comparison.
  2. The order of members is irrelevant.

Assert that the target contains the provided item

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

Note:
It is advised to first assert the type of target, as .include operates on various types. Hence it is advised
to chain .a when using .include.

Example:

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

Older style of writing Postman tests (deprecated)

Note: This section refers to deprecated script syntax used in older versions of Postman. If you are writing scripts now, please use the syntax mentioned above.

The older style of writing Postman tests relies on setting values for the special tests object. You can set a descriptive key for an element in the object and then say if it's true or false. For example, tests["Body contains user_id"] = responsebody.has("user_id"); will check whether the response body contains the user_id string.

You can add as many keys as needed, depending on how many things you want to test for. You can view your test results in the response viewer under the Tests tab. The tab header shows how many tests passed, and the keys that you set in the tests variable are listed here. If the value evaluates to true, the test passed.

Setting an environment variable (deprecated)

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

Setting a nested object as an environment variable (deprecated)

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

Getting an environment variable (deprecated)

postman.getEnvironmentVariable("key");

Getting an environment variable (whose value is a stringified object) (deprecated)

// 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"));

Clear an environment variable (deprecated)

postman.clearEnvironmentVariable("key");

Set a global variable (deprecated)

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

Get a global variable (deprecated)

postman.getGlobalVariable("key");

Clear a global variable (deprecated)

postman.clearGlobalVariable("key");

Check if response body contains a string (deprecated)

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

Convert XML body to a JSON object (deprecated)

var jsonObject = xml2Json(responseBody);

Check if response body is equal to a string (deprecated)

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

Check for a JSON value (deprecated)

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

Content-Type is present (Case-insensitive checking) (deprecated)

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

Content-Type is present (Case-sensitive) (deprecated)

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

Response time is less than 200ms (deprecated)

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

Response time is within a specific range (lower bound inclusive, upper bound exclusive) (deprecated)

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

Status code is 200 (deprecated)

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

Code name contains a string (deprecated)

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

Successful POST request status code (deprecated)

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

Use TinyValidator for JSON data (deprecated)

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

Decode base64 encoded data (deprecated)

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
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,179评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,229评论 2 380
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,032评论 0 336
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,533评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,531评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,539评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,916评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,574评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,813评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,568评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,654评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,354评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,937评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,918评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,152评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,852评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,378评论 2 342

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,353评论 0 23
  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom阅读 2,689评论 0 3
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,279评论 0 10
  • 课程介绍部分 一.课程回顾 二.补充: nfs服务常见问题: 三.全网备份项目部署说明 四.全网备份需求完成阶段 ...
    流云若雨阅读 303评论 1 0
  • 看悟空传各种求不得的哭,求不得,爱别离,呵呵,哪一个我不曾尝试过。这天这地这生生世世的纠缠不休的爱恨情仇,摆脱不了...
    平衡非平衡阅读 122评论 0 0