首页 > 其他分享 >『接口测试干货』| Newman+Postman接口自动化测试完整过程

『接口测试干货』| Newman+Postman接口自动化测试完整过程

时间:2023-11-25 10:04:22浏览次数:36  
标签:npm 测试 -- value newman json 接口 key Postman

(『接口测试干货』| Newman+Postman接口自动化测试完整过程)

1 Newman简介

  • NewmanPostman的一个扩展库(NodeJs库);
  • Newman+Postman可完成接口自动化测试工作;
  • Postman导出的JSON格式文件可通过Newman的命令行执行;
  • 因为Postman运行后只有概要结果,没有像其他自动化测试框架那么完美漂亮的测试报告样式,所以引入了Newman
  • Newman可快速完成集合的运行,构造自动化以及持续集成工作。

2 如何安装Newman?

2.1 安装NodeJs

  • 下载地址:NodeJs
  • 下载后直接双击运行即可node-v20.10.0-x64.msi在这里插入图片描述

2.2 安装Newman

  • 直接命令行输入以下命令即可:
npm install -g newman
C:\Windows\System32>npm install -g newman
npm WARN deprecated [email protected]: this library is no longer supported
npm WARN deprecated [email protected]: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.

added 118 packages, and audited 119 packages in 15s

9 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities
npm notice
npm notice New major version of npm available! 7.19.1 -> 10.2.4
npm notice Changelog: https://github.com/npm/cli/releases/tag/v10.2.4
npm notice Run npm install -g [email protected] to update!
  • 注意安装时要以管理员身份打开,不然会报错:
C:\Users\Administrator>npm install -g newman
npm ERR! code EPERM
npm ERR! syscall open
npm ERR! path C:\Program Files\nodejs\node_cache\_cacache\tmp\9c4058f4
npm ERR! errno EPERM
npm ERR! FetchError: Invalid response body while trying to fetch https://registry.npmjs.org/newman: EPERM: operation not permitted, open 'C:\Program Files\nodejs\node_cache\_cacache\tmp\9c4058f4'
npm ERR!     at C:\Program Files\nodejs\nod_global\node_modules\npm\node_modules\minipass-fetch\lib\body.js:162:15
npm ERR!     at async [nodeFromEdge] (C:\Program Files\nodejs\nod_global\node_modules\npm\node_modules\@npmcli\arborist\lib\arborist\build-ideal-tree.js:936:19)
npm ERR!     at async [buildDepStep] (C:\Program Files\nodejs\nod_global\node_modules\npm\node_modules\@npmcli\arborist\lib\arborist\build-ideal-tree.js:882:11)
npm ERR!     at async Arborist.buildIdealTree (C:\Program Files\nodejs\nod_global\node_modules\npm\node_modules\@npmcli\arborist\lib\arborist\build-ideal-tree.js:218:7)
npm ERR!     at async Arborist.reify (C:\Program Files\nodejs\nod_global\node_modules\npm\node_modules\@npmcli\arborist\lib\arborist\reify.js:134:5)
npm ERR!     at async Install.install (C:\Program Files\nodejs\nod_
  • 验证Newman是否安装成功:
'newman' 不是内部或外部命令,也不是可运行的程序
或批处理文件。
  • 问题排查:我们已经安装了node.js了,也已经安装了newman,其他都ok了。但还是不行查看node版本也是好的; 在这里插入图片描述

2.2 解决Newman不是内部命令

  • 根据上边的提示,我们已经做好了很多工作,但是还是不行;
  • 这里需要配置node.js的一些环境变;
  • node.js的安装目录下新建两个文件夹如下node_globalnode_cache在这里插入图片描述
  • 打开系统环境变量,新增NODE_PATH变量:
NODE_PATH
D:\nodejs\node_modules

在这里插入图片描述

  • 在系统环境变量的path新增:%NODE_PATH%在这里插入图片描述
  • 打开用户环境变量,修改path中的npm路径为:D:\nodejs\node_global在这里插入图片描述 在这里插入图片描述
  • 重启电脑、重启电脑、重启电脑(重要的事情说三遍)。
  • 验证newman是否安装成功:
newman -h
newman --version

在这里插入图片描述

3 Newman使用

3.1 Newman如何运行集合?

  • postman中将脚本导出,集合-右键-三个点-【Export】: 在这里插入图片描述
  • 导出为JSON格式文件即可: 在这里插入图片描述
  • 我们导出的文件为:test.postman_collection.json
  • 直接命令行执行以下命令运行脚本:
newman run test.postman_collection.json
  • 运行结果如下:
C:\Users\Administrator\Desktop>newman run test.postman_collection.json
newman

test

→ zentao
  POST http://127.0.0.1/zentao/api.php/v1/tokens [201 Created, 1.29kB, 1997ms]
  √  状态码为201

┌─────────────────────────┬─────────────────────┬─────────────────────┐
│                         │            executed │              failed │
├─────────────────────────┼─────────────────────┼─────────────────────┤
│              iterations │                   1 │                   0 │
├─────────────────────────┼─────────────────────┼─────────────────────┤
│                requests │                   1 │                   0 │
├─────────────────────────┼─────────────────────┼─────────────────────┤
│            test-scripts │                   1 │                   0 │
├─────────────────────────┼─────────────────────┼─────────────────────┤
│      prerequest-scripts │                   0 │                   0 │
├─────────────────────────┼─────────────────────┼─────────────────────┤
│              assertions │                   1 │                   0 │
├─────────────────────────┴─────────────────────┴─────────────────────┤
│ total run duration: 2.1s                                            │
├─────────────────────────────────────────────────────────────────────┤
│ total data received: 44B (approx)                                   │
├─────────────────────────────────────────────────────────────────────┤
│ average response time: 1997ms [min: 1997ms, max: 1997ms, s.d.: 0µs] │
└─────────────────────────────────────────────────────────────────────┘

在这里插入图片描述

3.2 如何查看帮助文档?

  • 使用以下命令即可:
newman -h
或
newman --help
C:\Users\Administrator\Desktop>newman -h
Usage: newman [options] [command]

Options:
  -v, --version               output the version number
  -h, --help                  display help for command

Commands:
  run [options] <collection>  Initiate a Postman Collection run from a given URL or path

To get available options for a command:
  newman <command> -h

C:\Users\Administrator\Desktop>newman --help
Usage: newman [options] [command]

Options:
  -v, --version               output the version number
  -h, --help                  display help for command

Commands:
  run [options] <collection>  Initiate a Postman Collection run from a given URL or path

To get available options for a command:
  newman <command> -h

3.3 环境变量设置

  • 脚本文件和环境变量是两个文件;
  • 所以运行脚本的时候如果有环境变量,那么直接加-e--environment即可:
newman run 脚本文件 -e 环境变量文件

3.4 关于全局变量

  • 这个和环境变量类似,如果有全局变量,使用-g--globals即可;
newman run 脚本文件 -g 全局变量文件

3.5 数据源文件

  • Postman中可以设置迭代次数和数据源文件,而在Newman中使用的话,需要加-d--iteration-data参数指定数据源的路径:
newman run 脚本文件 -g 全局变量文件 -d 数据源文件
  • 迭代次数通过-n--iteration-count来确定。

3.6 如何导出变量

  • 直接在命令行加如下参数即可:
--export-environment
--export-globals
--export-collection

4 测试报告

  • Newman支持CLI、JSON、HTML、JUNIT等等;
  • 本文主要说下HTML格式的报告使用。

4.1 newman-reporter-html安装

  • newman-reporter-html插件安装:
npm install -g newman-reporter-html

在这里插入图片描述

4.2 newman-reporter-html使用

  • 使用方法:
命令 说明
-r,json,junit 表示指定生成HTML、JSON、XML格式形式的测试报告
--reporter-json-export xxx.json 生成JSON格式的测试报告
--reporter-junit-export xxx.xml 生成XML格式的测试报告
--reporter-html-export xxx.html 生成HTML格式的测试报告
  • 生成的测试报告默认保存到当前目录下,如果报告名称为目录名,则保存到指定目录下;
  • 比如HTML报告:
newman run test.postman_collection.json \
-r html --reporter-html-export html_report.html

在这里插入图片描述

  • 比如XML格式报告:
newman run test.postman_collection.json \
-r junit --reporter-junit-export xml_report.xml

在这里插入图片描述

  • 比如JSON格式报告:
newman run test.postman_collection.json \
-r json --reporter-json-export json_report.json
{
  "collection": {
    "_": {
      "postman_id": "a1ee2193-7e02-4c50-892f-1e4d706a1132"
    },
    "item": [
      {
        "id": "393ea4b7-bfcf-4e3e-853d-e05a263435bf",
        "name": "zentao",
        "request": {
          "description": {
            "content": "禅道系统接口测试",
            "type": "text/plain"
          },
          "url": {
            "protocol": "http",
            "path": [
              "zentao",
              "api.php",
              "v1",
              "tokens"
            ],
            "host": [
              "127",
              "0",
              "0",
              "1"
            ],
            "query": [],
            "variable": []
          },
          "method": "POST",
          "body": {
            "mode": "raw",
            "raw": "{\"account\": \"admin\", \"password\": \"ZenTao123456\"}",
            "options": {
              "raw": {
                "language": "json"
              }
            }
          }
        },
        "response": [],
        "event": [
          {
            "listen": "test",
            "script": {
              "id": "63fb0da7-27ef-4569-87c6-81697169acf5",
              "type": "text/javascript",
              "exec": [
                "pm.test(\r",
                "    \"状态码为201\",function(){\r",
                "        pm.response.to.have.status(201);\r",
                "    }\r",
                ");"
              ],
              "_lastExecutionId": "9d83ab07-5d8c-4170-bb4f-898dbd965e57"
            }
          }
        ]
      }
    ],
    "event": [],
    "variable": [],
    "info": {
      "_postman_id": "a1ee2193-7e02-4c50-892f-1e4d706a1132",
      "name": "test",
      "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
    }
  },
  "environment": {
    "id": "a4b8954c-a10e-4b54-80d0-bb003c56953e",
    "values": []
  },
  "globals": {
    "id": "a084d77b-cbf5-4498-9770-200d6e0a4168",
    "values": []
  },
  "run": {
    "stats": {
      "iterations": {
        "total": 1,
        "pending": 0,
        "failed": 0
      },
      "items": {
        "total": 1,
        "pending": 0,
        "failed": 0
      },
      "scripts": {
        "total": 1,
        "pending": 0,
        "failed": 0
      },
      "prerequests": {
        "total": 1,
        "pending": 0,
        "failed": 0
      },
      "requests": {
        "total": 1,
        "pending": 0,
        "failed": 0
      },
      "tests": {
        "total": 1,
        "pending": 0,
        "failed": 0
      },
      "assertions": {
        "total": 1,
        "pending": 0,
        "failed": 0
      },
      "testScripts": {
        "total": 1,
        "pending": 0,
        "failed": 0
      },
      "prerequestScripts": {
        "total": 0,
        "pending": 0,
        "failed": 0
      }
    },
    "timings": {
      "responseAverage": 154,
      "responseMin": 154,
      "responseMax": 154,
      "responseSd": 0,
      "dnsAverage": 0,
      "dnsMin": 0,
      "dnsMax": 0,
      "dnsSd": 0,
      "firstByteAverage": 0,
      "firstByteMin": 0,
      "firstByteMax": 0,
      "firstByteSd": 0,
      "started": 1700804595902,
      "completed": 1700804596169
    },
    "executions": [
      {
        "cursor": {
          "position": 0,
          "iteration": 0,
          "length": 1,
          "cycles": 1,
          "empty": false,
          "eof": false,
          "bof": true,
          "cr": false,
          "ref": "1d6d4e14-53d2-4ab6-8e78-87c67bad8bc9",
          "httpRequestId": "b5949fe3-d241-4020-a10c-b4adcbef9bb1"
        },
        "item": {
          "id": "393ea4b7-bfcf-4e3e-853d-e05a263435bf",
          "name": "zentao",
          "request": {
            "description": {
              "content": "禅道系统接口测试",
              "type": "text/plain"
            },
            "url": {
              "protocol": "http",
              "path": [
                "zentao",
                "api.php",
                "v1",
                "tokens"
              ],
              "host": [
                "127",
                "0",
                "0",
                "1"
              ],
              "query": [],
              "variable": []
            },
            "method": "POST",
            "body": {
              "mode": "raw",
              "raw": "{\"account\": \"admin\", \"password\": \"ZenTao123456\"}",
              "options": {
                "raw": {
                  "language": "json"
                }
              }
            }
          },
          "response": [],
          "event": [
            {
              "listen": "test",
              "script": {
                "id": "63fb0da7-27ef-4569-87c6-81697169acf5",
                "type": "text/javascript",
                "exec": [
                  "pm.test(\r",
                  "    \"状态码为201\",function(){\r",
                  "        pm.response.to.have.status(201);\r",
                  "    }\r",
                  ");"
                ],
                "_lastExecutionId": "9d83ab07-5d8c-4170-bb4f-898dbd965e57"
              }
            }
          ]
        },
        "request": {
          "description": {
            "content": "禅道系统接口测试",
            "type": "text/plain"
          },
          "url": {
            "protocol": "http",
            "path": [
              "zentao",
              "api.php",
              "v1",
              "tokens"
            ],
            "host": [
              "127",
              "0",
              "0",
              "1"
            ],
            "query": [],
            "variable": []
          },
          "header": [
            {
              "key": "Content-Type",
              "value": "application/json",
              "system": true
            },
            {
              "key": "User-Agent",
              "value": "PostmanRuntime/7.33.0",
              "system": true
            },
            {
              "key": "Accept",
              "value": "*/*",
              "system": true
            },
            {
              "key": "Cache-Control",
              "value": "no-cache",
              "system": true
            },
            {
              "key": "Postman-Token",
              "value": "4dd31771-a07b-42e8-b78a-ac244c4dca6c",
              "system": true
            },
            {
              "key": "Host",
              "value": "127.0.0.1",
              "system": true
            },
            {
              "key": "Accept-Encoding",
              "value": "gzip, deflate, br",
              "system": true
            },
            {
              "key": "Connection",
              "value": "keep-alive",
              "system": true
            },
            {
              "key": "Content-Length",
              "value": "48",
              "system": true
            }
          ],
          "method": "POST",
          "body": {
            "mode": "raw",
            "raw": "{\"account\": \"admin\", \"password\": \"ZenTao123456\"}",
            "options": {
              "raw": {
                "language": "json"
              }
            }
          }
        },
        "response": {
          "id": "2a26af66-ad21-42d2-8b7a-b89cd7339a47",
          "status": "Created",
          "code": 201,
          "header": [
            {
              "key": "Date",
              "value": "Fri, 24 Nov 2023 05:43:16 GMT"
            },
            {
              "key": "Server",
              "value": "Apache"
            },
            {
              "key": "Set-Cookie",
              "value": "zentaosid=9f0dab6ebbe1e65c99a8abb3c351d89a; path=/zentao/; HttpOnly"
            },
            {
              "key": "Set-Cookie",
              "value": "lang=zh-cn; expires=Sun, 24-Dec-2023 05:43:16 GMT; Max-Age=2592000; path=/zentao/"
            },
            {
              "key": "Set-Cookie",
              "value": "device=desktop; expires=Sun, 24-Dec-2023 05:43:16 GMT; Max-Age=2592000; path=/zentao/; HttpOnly"
            },
            {
              "key": "Set-Cookie",
              "value": "theme=default; expires=Sun, 24-Dec-2023 05:43:16 GMT; Max-Age=2592000; path=/zentao/"
            },
            {
              "key": "Expires",
              "value": "Thu, 19 Nov 1981 08:52:00 GMT"
            },
            {
              "key": "Cache-Control",
              "value": "private"
            },
            {
              "key": "Pragma",
              "value": "no-cache"
            },
            {
              "key": "X-Content-Type-Options",
              "value": "nosniff"
            },
            {
              "key": "X-XSS-Protection",
              "value": "1; mode=block"
            },
            {
              "key": "Strict-Transport-Security",
              "value": "max-age=3600; includeSubDomains"
            },
            {
              "key": "Referrer-Policy",
              "value": "no-referrer-when-downgrade"
            },
            {
              "key": "X-Permitted-Cross-Domain-Policies",
              "value": "master-only"
            },
            {
              "key": "X-Download-Options",
              "value": "noopen"
            },
            {
              "key": "Content-Security-Policy",
              "value": "form-action 'self';connect-src 'self';"
            },
            {
              "key": "X-Frame-Options",
              "value": "SAMEORIGIN"
            },
            {
              "key": "Access-Control-Allow-Origin",
              "value": "*"
            },
            {
              "key": "Access-Control-Allow-Credentials",
              "value": "true"
            },
            {
              "key": "Access-Control-Allow-Headers",
              "value": "Origin,X-Requested-With,Content-Type,Accept,Authorization,Token,Referer,User-Agent"
            },
            {
              "key": "Access-Control-Allow-Methods",
              "value": "GET,POST,PUT,DELETE,OPTIONS,PATCH"
            },
            {
              "key": "Content-Length",
              "value": "44"
            },
            {
              "key": "Keep-Alive",
              "value": "timeout=10, max=100"
            },
            {
              "key": "Connection",
              "value": "Keep-Alive"
            },
            {
              "key": "Content-Type",
              "value": "application/json"
            }
          ],
          "stream": {
            "type": "Buffer",
            "data": [
              123,
              34,
              116,
              111,
              107,
              101,
              110,
              34,
              58,
              34,
              57,
              102,
              48,
              100,
              97,
              98,
              54,
              101,
              98,
              98,
              101,
              49,
              101,
              54,
              53,
              99,
              57,
              57,
              97,
              56,
              97,
              98,
              98,
              51,
              99,
              51,
              53,
              49,
              100,
              56,
              57,
              97,
              34,
              125
            ]
          },
          "cookie": [],
          "responseTime": 154,
          "responseSize": 44
        },
        "id": "393ea4b7-bfcf-4e3e-853d-e05a263435bf",
        "assertions": [
          {
            "assertion": "状态码为201",
            "skipped": false
          }
        ]
      }
    ],
    "transfers": {
      "responseTotal": 44
    },
    "failures": [],
    "error": null
  }
}
  • 以下是生成的几个报告: 在这里插入图片描述

4.3 htmlextra安装

  • htmlextra主要实现比较高级的测试报告,需要进行安装:
npm install -g newman-reporter-htmlextra

在这里插入图片描述

4.4 htmlextra使用

  • 使用方法和newman-reporter-html基本一样;
  • 使用命令方法:
newman run test.postman_collection.json -r \
htmlextra --reporter-html-export html_report.html
  • 执行命令后会在当前目录或者指定目录生成一个newman文件夹,文件夹中保存着生成的文报告信息;
  • 测试报告样式如下: 在这里插入图片描述

5 关于postman使用

  • 这个之前的文章已经介绍了,直接去浏览即可,这里不再赘述;
  • 大概思路就是使用postman生成接口数据,导出来后使用Newman运行和生成测试报告。

标签:npm,测试,--,value,newman,json,接口,key,Postman
From: https://blog.51cto.com/NoamaNelson/8556590

相关文章

  • map 接口的遍历
    packagecom.wxledu.map_;importjava.util.*;@SuppressWarnings({"all"})publicclassMapFor{publicstaticvoidmain(String[]args){Mapmap=newHashMap();map.put("邓超","孙俪");map.put("......
  • 5分钟掌握接口自动化测试,4个知识点简单易学!
    一.什么是接口测试接口测试是一种软件测试方法,用于验证不同软件组件之间的通信接口是否按预期工作。在接口测试中,测试人员会发送请求并检查接收到的响应,以确保接口在不同场景下都能正常工作。就工具而言,常见的测试工具有Jmeter、Postman等。但这类工具往往更是做接口调试,对于做......
  • Jmeter接口测试 —— jmeter对图片验证码的处理
    ​jmeter对图片验证码的处理在web端的登录接口经常会有图片验证码的输入,而且每次登录时图片验证码都是随机的;当通过jmeter做接口登录的时候要对图片验证码进行识别出图片中的字段,然后再登录接口中使用;通过jmeter对图片验证码的识别方法1、通过ocrserver工具识别图片验证码;如下......
  • 以精确反馈促进学生编程逻辑和问题解决意识:一种基于两层测试的在线编程训练方法
    (PromotingStudents’ProgrammingLogicandProblem-SolvingAwarenessWithPrecisionFeedback:ATwo-TierTest-BasedOnlineProgrammingTrainingApproach)DOI:10.1177/07356331221087773一、摘要研究目的:培养学生的计算机编程技能已成为全球重要的教育问题。然而,学......
  • Postman 安装
    貌似从版本10.14开始,从文件导入必须登录。(登录之后每次打开必须联网,体验很差。)可以先安装旧版,导入后再更新。旧版10.13.6下载https://www.filehorse.com/download-postman/80098/download/ 安装报错versionmismatchdetectedpostman使用旧版本报错versionmismatchdetecte......
  • Ubuntu 安装 JMeter:快速搭建高效性能测试环境
    ApacheJMeter是一个开源的负载测试工具,可以用于测试静态和动态资源,确定服务器的性能和稳定性。在本文中,我们将讨论如何下载和安装 JMeter。安装Java(已安装Java的此步骤可跳过)要下载Java,请遵循以下步骤:输入命令 `sudoaptinstallopenjdk-11-jre-headless` 进行安装。输入......
  • 软件测试/人工智能|AutoGPT原理与架构介绍
    简介我们生活中已经有越来越多的人工智能融入了,手机汽车等等接入了越来越多的人工智能,人工智能就像是我们的一个助手一样。不仅能够理解我们的需求,而且还能够与我们一起学习与成长。人工智能已无缝融入我们工作、生活,并帮助我们有效完成各种目标。大模型技术的发展与应用,使以上想法......
  • 软件测试/人工智能|教你如何使用ChatGPT的API
    简介自从有了ChatGPT之后,我每天都想去调戏它一番,自从开放了ChatGPT的API,我就想着通过API来使用ChatGPT,这样的话,速度上的体验应该会更好,本文就来介绍一下如何使用ChatGPT的API。环境准备在调用API之前,我们首先需要准备好我们的环境,一是我们需要安装openAI第三方库,OpenAI提供了一个......
  • 2023.7信友队暑假集训第2次测试复盘
    信友队暑假集训第2次测试总结:本次比赛都出的以前做过的题,但本蒟蒻确只写了320(悲第一题:排行榜一道水题,秒A#include<bits/stdc++.h>usingnamespacestd;stringans[105],s[105],t[105];intvis[105];intmain(){intn;cin>>n;memset(vis,0,sizeofvis);......
  • Apache Bench(ab 压力测试工具)的安装与使用
    1.ab安装下面介绍在liunx和windows上的安装1.1、linux yum 安装yuminstallhttpd-tools或者yum-yinstallhttpd-tools测试安装是否成功:[root@vichtml]#ab-VThisisApacheBench,Version2.3<$Revision:655654$>Copyright1996AdamTwiss,Zeus......