使用 Newman 在命令行上运行集合

Newman 是 Postman 的命令行 Collection Runner。它使您能够直接从命令行运行和测试 Postman 集合。它在构建时考虑了可扩展性,因此您可以轻松地将其与您的持续集成服务器和构建系统集成。

Newman 与 Postman 保持功能对等,并允许您以在 Postman 的集合运行器中执行集合的方式运行集合。

Newman 驻留在NPM 注册表GitHub 上

纽曼 gif

入门

Newman 基于 Node.js 构建。要运行 Newman,请确保您已安装 Node.js。

您可以在 Linux、Windows 和 macOS 上下载并安装Node.js。

安装 Node.js 后,只需一个命令即可使用 Newman。在您的系统上全局从 npm 安装 Newman,这样您就可以从任何地方运行它。

$ npm install -g newman

运行 Newman 最简单的方法是使用集合运行它。您可以从文件系统运行任何集合文件。

您可以导出集合以作为文件共享。

$ newman run mycollection.json

您还可以通过共享将集合作为 URL 传递。

您的集合可能使用环境变量。要提供一组随附的环境变量,请从 Postman 导出模板并使用-e标志运行它们。

$ newman run https://www.postman.com/collections/cb208e7e64056f5294e5 -e dev_environment.json

选项

Newman 提供了一组丰富的选项来自定义运行。-h您可以通过使用标志运行它来检索选项列表。

$ newman run -h

效用

选项 细节
-h,--help 输出使用信息
-v,--version 输出版本号

基本设置

选项 细节
--folder [folderName] 指定要从集合运行的单个文件夹。
-e,--environment [file|URL] 将 Postman 环境指定为 JSON [文件]
-d,--iteration-data [file] 指定要使用 json 或 csv 的数据文件
-g,--globals [file] 将 Postman 全局文件指定为 JSON [文件]
-n,--iteration-count [number] 定义要运行的迭代次数

请求选项

选项 细节
--delay-request [number] 指定请求之间的延迟(以毫秒为单位) [数字]
--timeout-request [number] 为请求指定请求超时(以毫秒为单位)

杂项。

选项 细节
--bail 当测试用例失败时停止运行器
--silent 关闭终端输出
--color off 关闭彩色输出 (auto|on|off) (默认: "auto")
-k,--insecure 关闭严格的 ssl
-x,--suppress-exit-code 即使在失败后继续运行测试,但退出code=0
--ignore-redirects 关闭3XX响应的自动跟踪
--verbose 显示收集运行的详细信息和发送的每个请求

使用该-n选项设置运行集合的迭代次数。

$ newman run mycollection.json -n 10  # runs the collection 10 times

要提供一组不同的数据,例如每次迭代的变量,您可以使用-d指定 JSON 或 CSV 文件。

例如,如下所示的数据文件运行2次迭代,每次迭代使用一组变量。

[{
    "url": "http://127.0.0.1:5000",
    "user_id": "1",
    "id": "1",
    "token_id": "123123",
},
{
    "url": "http://postman-echo.com",
    "user_id": "2",
    "id": "2",
    "token_id": "899899",
}]
$ newman run mycollection.json -d data.json

以下是上述变量集的 CSV 文件示例:

url, user_id, id, token_id
http://127.0.0.1:5000, 1, 1, 123123123
http://postman-echo.com, 2, 2, 899899

默认情况下,如果一切运行良好(例如没有任何异常),Newman 会以状态码 0 退出。

持续集成工具响应这些退出代码并相应地通过或失败构建。

您可以使用-x--suppress-exit-code覆盖当前运行的默认退出代码。

您可以使用该--bail标志告诉 Newman 在状态码为 1 的测试用例错误上停止,然后可以由 CI 工具或构建系统拾取。

$ newman run PostmanCollection.json -e environment.json --bail

测试失败的示例集合

→ Status Code Test
  GET https://postman-echo.com/status/404 [404 Not Found, 534B, 1551ms]
  1\. response code is 200

┌─────────────────────────┬──────────┬──────────┐
│                         │ executed │   failed │
├─────────────────────────┼──────────┼──────────┤
│              iterations │        10 │
├─────────────────────────┼──────────┼──────────┤
│                requests │        10 │
├─────────────────────────┼──────────┼──────────┤
│            test-scripts │        10 │
├─────────────────────────┼──────────┼──────────┤
│      prerequest-scripts │        00 │
├─────────────────────────┼──────────┼──────────┤
│              assertions │        11 │
├─────────────────────────┴──────────┴──────────┤
│ total run duration: 1917ms                    │
├───────────────────────────────────────────────┤
│ total data received: 14B (approx)             │
├───────────────────────────────────────────────┤
│ average response time: 1411ms                 │
└───────────────────────────────────────────────┘

  #  failure        detail

 1\.  AssertionFai…  response code is 200
                    at assertion:1 in test-script
                    inside "Status Code Test" of "Example Collection with
                    Failing Tests"

所有测试和请求的结果都可以导出到文件中。使用 JSON 报告器和文件名将输出保存到文件中。

$ newman run mycollection.json --reporters cli,json --reporter-json-export outputfile.json

注意: Newman 允许您使用 Postman 支持的所有库和对象来运行测试和预请求脚本。

在 CI/CD 中使用 Newman

默认情况下,如果一切都按预期运行且无异常,Newman 会以状态码 0 退出。您可以配置您的持续集成工具以响应 Newman 的退出代码并相应地通过或失败构建。--bail如果Newman 遇到状态代码为 1 的测试用例错误,您还可以使用该标志让 Newman 停止运行,然后您的 CI 工具或构建系统可以获取该错误。

文件上传

纽曼还支持文件上传。要使其正常工作,请将文件上传到集合中指定的相对位置。例如,查看此集合:

{
    "variables": [],
    "info": {
        "name": "file-upload",
        "_postman_id": "9dbfcf22-fdf4-f328-e440-95dbd8e4cfbb",
        "description": "A set of `POST` requests to upload files as form data fields",
        "schema": "https://schema.getpostman.com/json/collection/v2.0.0/collection.json"
    },
    "item": [
        {
            "name": "Form data upload",
            "event": [
                {
                    "listen": "test",
                    "script": {
                        "type": "text/javascript",
                        "exec": [
                            "var response = JSON.parse(responseBody).files[\"sample-file.txt\"];",
                            "",
                            "tests[\"Status code is 200\"] = responseCode.code === 200;",
                            "tests[\"File was uploaded correctly\"] = /^data:application\\/octet-stream;base64/.test(response);",
                            ""
                        ]
                    }
                }
            ],
            "request": {
                "url": "https://postman-echo.com/post",
                "method": "POST",
                "header": [],
                "body": {
                    "mode": "formdata",
                    "formdata": [
                        {
                            "key": "file",
                            "type": "file",
                            "enabled": true,
                            "src": "sample-file.txt"
                        }
                    ]
                },
                "description": "Uploads a file as a form data field to `https://postman-echo.com/post` via a `POST` request."
            },
            "response": []
        }
    ]
}

该文件sample-file.txt必须作为集合存在于当前工作目录中。像往常一样运行这个集合。

$ newman run file-upload.postman_collection.json

图书馆

纽曼是从头开始建造的图书馆。它可以以各种方式扩展和使用。您可以在 Node.js 代码中按如下方式使用它:

var newman = require('newman'); // require Newman in your project

// call newman.run to pass `options` object and wait for callback
newman.run({
    collection: require('./sample-collection.json'),
    reporters: 'cli'
}, function (err) {
    if (err) { throw err; }
    console.log('collection run complete!');
});

自定义记者

当人们想要生成满足特定用例的收集运行报告时,自定义报告器会派上用场。例如,当请求(或其测试)失败时注销响应正文,等等。

构建自定义记者

自定义报告器是一个名称为 form 的 Node 模块newman-reporter-<name>。要创建自定义报告器:

  1. 导航到您选择的目录,然后使用npm init.

  2. 添加一个index.js文件,该文件导出以下形式的函数:

function (emitter, reporterOptions, collectionRunOptions) {
  // emitter is is an event emitter that triggers the following events: https://github.com/postmanlabs/newman#newmanrunevents
  // reporterOptions is an object of the reporter specific options. See usage examples below for more details.
  // collectionRunOptions is an object of all the collection run options:
  // https://github.com/postmanlabs/newman#newmanrunoptions-object--callback-function--run-eventemitter
};
  1. 使用 发布您的记者npm publish,或在本地使用您的记者。有关详细信息,请参阅使用说明。

范围内的记者包名称@myorg/newman-reporter-<name>也受支持。

使用自定义记者

为了使用自定义报告器,必须先安装它。例如,要使用 Newman TeamCity 报告器,请安装报告器包:

npm install newman-reporter-teamcity

请注意,包的名称为 形式newman-reporter-<name>,其中<name>是报告者的实际名称。如果 Newman 是全局安装的,则安装应该是全局的,否则是本地的。npm install ...使用全局安装的-g标志运行。

要使用本地(未发布)报告器,请npm install <path/to/local-reporter-directory>改为运行命令。

通过 CLI 或以编程方式使用已安装的报告器。此处,newman-reporter在选项中指定报告者名称时不需要前缀。

范围内的报告程序包必须使用范围前缀指定。例如,如果您的包名称是@myorg/newman-reporter-name,则必须使用 指定报告者@myorg/name

命令行:

newman run /path/to/collection.json -r myreporter --reporter-myreporter-<option-name> <option-value> # The option is optional

以编程方式:

var newman = require('newman');

newman.run({
   collection: '/path/to/collection.json',
   reporters: 'myreporter',
   reporter: {
     myreporter: {
       'option-name': 'option-value' // this is optional
     }
   }
}, function (err, summary) {
  if (err) { throw err; }
  console.info('collection run complete!');
});

在上述两种情况下,报告选项都是可选的。

有关完整的文档,请参阅Newman README

有关收集运行的更多信息,请参阅: