postman的常见断言

【接口测试】Postman常见五类断言方法 一看就懂:Postman常见五类断言方法 阅读详情

介绍断言之前,我们先测试1个接口

案例接口地址:https://www.v2ex.com/api/nodes/show.json?name=python

  • Method: GET

  • Authentication: None

做测试的同学,我相信每个人都知道断言,就是结果和预期对比,如果一致,则用例通过,如果不一致,断言失败,用例失败。那么上面这个接口我们如何用postman来进行断言呢?也很简单,用到postman tests 这个模块。

 那么上面的接口我们如何断言呢?很简单,从响应内容做断言。比如我们可以断言 id=90,url = "http://www.v2ex.com/go/python",状态码等于200

我们在tests输入框填写:

pm.test("Status code is 200", function () {

    pm.response.to.have.status(200);

});   //断言状态码是200

var jsonData = JSON.parse(responseBody);

tests["Check respose id value"] = jsonData.id === 90; //断言id是90

tests["Check respose url value"] = jsonData.url === "http://www.v2ex.com/go/python"; //断言url

操作步骤:1、填写断言 2、点击send

 查看断言结果:

当然上面断言是比较简单的断言,如果返回的数据如下所示,我们应该如何断言呢?

  1. {

  2. "status": 1,

  3. "message": "success",

  4. "data": [

  5. {

  6. "id": 1,

  7. "title": "乡愁",

  8. "author": "余光中",

  9. "content": "小时候,乡愁是一枚小小的邮票,我在这头,母亲在那头。长大后,乡愁是一张窄窄的船票,我在这头,新娘在那头"

  10. },

  11. {

  12. "id": 5,

  13. "title": "乡愁",

  14. "author": "余光中",

  15. "content": "小时候,乡愁是一枚小小的邮票,我在这头,母亲在那头。长大后,乡愁是一张窄窄的船票,我在这头,新娘在那头"

  16. }

  17. ]

  18. }

跟上面断言不同的是,data里面可能有多个json格式的数据,如果我们想断言data里面第一个json应该如何断言呢?其实也非常简单,我们在tests输入框填写:

  1. var jsonData = JSON.parse(responseBody);

  2. tests["Check respose status value"] = jsonData.status === 1;

  3. pm.test("判断data里面第一个json数据的id为1", function () {

  4. var jsonData = pm.response.json();

  5. pm.expect(jsonData.data[0].id).to.eql(1);});

postman常见断言方法介绍:

Setting an environment variable  (设置一个环境变量)

1

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 (获取环境变量)

1

pm.environment.get("variable_key")

Getting an environment variable (whose value is a stringified object)  获取一个环境变量(其值是一个字符串化的对象)

// 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 (清除一个环境变量)

1

pm.environment.unset("variable_key");

Set a global variable (设置一个全局变量)

1

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

Get a global variable (获取一个全局变量)

1

pm.globals.get("variable_key");

Clear a global variable (清除全局变量)

1

pm.globals.unset("variable_key");

Get a variable (获取一个变量)

该函数在全局变量和活动环境中搜索变量。

1

pm.variables.get("variable_key");

Check if response body contains a string (检查响应主体是否包含字符串)

1

2

3

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 (检查响应主体是否等于一个字符串)

1

2

3

pm.test("Body is correct", function () {

    pm.response.to.have.body("response_body_string");

});

Check for a JSON value (检查JSON值)

1

2

3

4

pm.test("Your test name", function () {

    var jsonData = pm.response.json();

    pm.expect(jsonData.value).to.eql(100);

});

Content-Type is present (内容类型存在)

1

2

3

pm.test("Content-Type is present", function () {

    pm.response.to.have.header("Content-Type");

});

Response time is less than 200ms (响应时间小于200ms)

1

2

3

pm.test("Response time is less than 200ms", function () {

    pm.expect(pm.response.responseTime).to.be.below(200);

});

Status code is 200 (状态码是200)

1

2

3

pm.test("Status code is 200", function () {

    pm.response.to.have.status(200);

});

Code name contains a string (代码名称包含一个字符串)

1

2

3

pm.test("Status code name has string", function () {

    pm.response.to.have.status("Created");

});

Successful POST request status code (成功的POST请求状态码)

1

2

3

pm.test("Successful POST request", function () {

    pm.expect(pm.response.code).to.be.oneOf([201,202]);

});

Use TinyValidator for JSON data (对于JSON数据使用TinyValidator)

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;

});

Decode base64 encoded data (解码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

pm.test('Contents are valid', function() {

  pm.expect(CryptoJS.enc.Utf8.stringify(intermediate)).to.be.true; // a check for non-emptiness

});

Send an asynchronous request (发送异步请求)

该功能既可以作为预先请求,也可以作为测试脚本使用。

pm.sendRequest("https://postman-echo.com/get", function (err, response) {

    console.log(response.json());

});

Convert XML body to a JSON object (将XML正文转换为JSON对象)

1

var jsonObject = xml2Json(responseBody);

最后感谢每一个认真阅读我文章的人!作为一位过来人也是希望大家少走一些弯路,如果你不想再体验一次学习时找不到资料,坚持几天便放弃的感受的话,在这里我给大家分享一些软件测试的学习资源,这些资料,对于【软件测试】的朋友来说应该是最全面最完整的备战仓库,希望能给你前进的路上带来帮助。如果你用得到的话可以直接拿走:

软件测试资料领取:[内部资源] 想拿年薪40W+的软件测试人员,这份资料必须领取~

软件测试面试刷题工具领取:软件测试面试刷题【800道面试题+答案免费刷】

这些资料,对于【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴上万个测试工程师们走过最艰难的路程,希望也能帮助到你! 

postman接口测试常见的断言添加方式 以上海7天的气预报接口为例,添加断言发送请求,查看返回的结果 请求地址:https://tianqiapi.com/free/week?appid=79373561&appsecret=ldMDlIM2&city={{cityname}} 请求方式:GET 发送请求,返回的主体内容: { "cityid": "101020100", "city": "上海", "update_time": "2021-10-13 17:06:50", "data": [ { "date" 阅读详情

相关推荐

自适应动态规划硕士博士论文学习

强化学习关注随机过程中的序贯决策问题,而自适应动态规划关注动态系统的控制问题。吸引域:系统渐近稳定的区域。

DarlingLSA的博客 1439

Postman设置断言

1、什么是断言?一般一个完整的接口测试,包括:请求->获取响应正文->断言,请求和获取响应正文很常见。断言一般是对请求的响应结果做操作,判断预期结果与实际结果是否一致。2、postman中在哪里设置断言?(1)设置断言的操作栏位置(2)自动生成断言代码(3)断言的流程①在postman的tests页签中截取要对比的响应信息;②利用断言语句tests[]或chai.js形式把实际响应信息与期望结果对比;③执行请求进行结果查看;

Free355的博客 3013

数字图像处理第九章笔记

目录一、腐蚀与膨胀1、腐蚀2、膨胀3、对偶性4、开操作与闭操作二、一些基本的形态学算法1、边界提取2、孔洞填充3、连通分量提取4、凸壳5、细化6、粗化7、骨架8、形态学重建三、灰度级形态学1、腐蚀和膨胀2、开运算和闭运算3、灰度级形态学算法 一、腐蚀与膨胀 1、腐蚀 腐蚀可以去除图像的某些部分。 2、膨胀 膨胀可以连接裂缝。 3、对偶性 膨胀和腐蚀彼此关于集合求补运算和反射运算是对偶的 4、开操作与闭操作 开操作:B对A先腐蚀,再进行膨胀 可以平滑物体轮廓,断开较窄的狭颈并消除较细的突出物。 闭操作

方悔读书迟 1381

Postman的七种断言方法+超时设置!

postman在发送请求后,需要对返回的结果做判断,验证是否符合预期,如状态码、响应头、响应正文等信息进行断言操作,在设置时会给定一个预期结果,在发送请求后会得到一个实际如果,如果两者结果一致,则认为是成功的(PASS),否则则是失败的(Fail),这种操作就叫做断言。断言主要是在Test操作框内进行设置,使用JavaScript语言编写,断言的结果在下方响应内容的TestResult。

myh919的博客 5875

Python | 处理CMIP6 NC数据,以tas为例

各位同学,一般在文章最后一章我们可能会做不同气候情景下变量的未来时空变化特征,类似上图。从cmip6下载的nc数据常需要转换格式、裁剪到研究区和重采样等,本期代码可以解决这类问题。

qq_48539301的博客 1389

PSINS工具箱学习(四)捷联惯导更新算法

原始 Markdown文档、Visio流程图、XMind思维导图见:https://github.com/LiZhengXiao99/Navigation-Learning。

实践出真理,接毕设/课设项目开发指导 611

Postman—添加断言和正则表达式(2)

前言 postman断言是JavaScript语言编写的,在postman客户端指定区域编写即可。 断言会在请求返回之后,运行,并根据断言的pass\fail情况体现在最终测试结果中。 一、断言步骤 1、打开保存的postman完成的访问百度经验的一个简单的Get请求。点击Send,查看响应信息。 这里就设置,检查响应信息里面包含:“百度新闻——全球最大的中文新闻平台”这几个字、 同时设置响应httpCode为200,断言响应成功。 2、点击Url下方的Tests,这里设置断言。 点进来后这里是空的,你如果

weixin_44503360的博客 1387

华为od 面试八股文_C语言_02_含答案

华为od 面试八股文_C语言_02_含答案

MISAYAONE的博客 2253

接口测试|Postman设置断言

Postman设置断言

Tester_muller的博客 1873

KVM — 与 QEMU 和 Libvirt 的关系

目录目录 前言 KVM QEMU KVM 与 QEMU qemu-kvm Libvirt Libvirt 在 OpenStack 中的应用前言如果是刚开始接触虚拟机技术的话, 对上述的概念肯定会有所混淆, 傻傻的分不清. 尤其在看虚拟化技术文档时导致理解能力下降, 所以在开始学习虚拟化技术之前对这些概念有一个整体的认识和清晰的理解, 就显得很有必要了.KVMKVM(Kernel-basedVirtu

烟云的计算 5744

《SOC架构-ARM架构-文档导读》-目录

小白请看“Armv8/Armv9架构从入门到精通”专栏。以翻译为主的,深度深度深度深度/深入深入深入 学习ARM架构的文章。

baron-周贺贺-代码改变世界ctw 2093

【Postman接口测试】Postman的常见断言

在使用Postman进行接口测试时,断言是验证接口响应是否符合预期的关键手段。通过设置各种断言,我们能够确保接口按照设计要求返回正确的数据、状态码、响应头信息以及在规定的时间内完成响应。下面将详细介绍Postman中常见的断言,包括状态码断言、响应正文断言、响应头断言和响应时间断言,并结合具体案例进行说明。

weixin_61631131的博客 1696

【QT开发教程】QMatrix4x4类详解及实战应用:Qt中的4x4矩阵变换

在计算机图形学和三维图形应用中,矩阵变换是一个核心概念。Qt框架提供了QMatrix4x4类,用于处理4x4矩阵变换,帮助开发者在三维空间中进行复杂的几何计算。本文将深入探讨QMatrix4x4的功能及其在Qt应用中的实际应用。

科技改变人类,技术成就未来 735

Postman的常见断言

介绍断言之前,我们先测试1个接口: 接口地址:https://www.v2ex.com/api/nodes/show.json?name=python Method: GET Authentication: None 做测试的同学,我相信每个人都知道断言,就是结果和预期对比,如果一致,则用例通过,如果不一致,断言失败,用例失败。那么上面这个接口我们如何用postman来进行...

weixin_42639325的博客 474

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

Postman中常见的断言方法

Postman 提供了丰富的断言方法,用于验证 API 响应的正确性。这些断言通常编写在 “Tests” 标签中,使用 JavaScript 语法。

m0_46193169的博客 227

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

postman常见断言方法

转自:postman的常见断言 ** postman常见断言方法介绍: ** 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("a

跌 3524

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

postman测试base64_postman的常见断言

介绍断言之前,我们先测试1个接口案例接口地址:https://www.v2ex.com/api/nodes/show.json?name=pythonMethod: GETAuthentication: None做测试的同学,我相信每个人都知道断言,就是结果和预期对比,如果一致,则用例通过,如果不一致,断言失败,用例失败。那么上面这个接口我们如何用postman来进行断言呢?也很简单,...

weixin_36024106的博客 581

postman之常见断言

postman常见断言用法

sinat_33987631的博客 1191
上一篇: 2025最新面试跳槽,软件测试面试题的整理与解析
下一篇: 软件测试里的可访问性测试方法
程序员可可
博客等级 码龄2年 3536粉丝 428原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值