今天要介紹的Newman是Postman的一個CLI (Command-line interface)工具,讓使用者可以透過下指令的方式來執行Collection裡的請求,像是可以搭配昨天的Postman API,就可以用指令直接操作Collection、Environment等資源。
下面直接透過今天挑戰的內容來體驗Newman的功能吧,在開始前需要先將Day 13: Newman fork 回自己的工作區。
回到自己工作區後,打開資料夾Newman,搭配右方的說明文件先準備好前置工作,步驟如下:
planets
GET https://swapi.dev/api/planets
// 確認API傳回的內容有叫做 Tatooine 的行星
pm.test("Check Tatooine", function () {
    var results = pm.response.json().results;
    let pass = false;
    for(var p in results) {
        if (results[p].name === "Tatooine") {
            pass = true;
            break;
        }
    }
    pm.expect(pass).to.eql(true);
});
species
GET https://swapi.dev/api/species
pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});
// 確保回傳的物種有說`Ewokese`的
pm.test("Check Ewokese", function () {
    var results = pm.response.json().results;
    let pass = false;
    for(var p in results) {
        if (results[p].language === "Ewokese") {
            pass = true;
            break;
        }
    }
    pm.expect(pass).to.eql(true);
});
// 找 average_height 大於 100 並計數,寫回 Collection variable
pm.test("Count", function () {
    var results = pm.response.json().results;
    var count = 0;
    for(var p in results) {
        if (results[p].average_height > 100) {
            count++
        }
    }
    console.log(count)
    pm.collectionVariables.set("talls", count)
});
Persist 變數: 由於上個步驟 collectionVariables 只會修改 CURRENT VALUE,需要到Collection調整變數,用Persist將當前的值同步到INITIAL VALUE,這樣才會使共享此集合的人都能採用到該值 
到這邊就可以進行Submit來通過今天挑戰了,不過上述這些操作只是一些前置作業,畢竟今天的主題是Newman,所以接下來讓我們進行第二階段的操作
Export Collection: 點選今日Collection的選單,找到Export將關於此集合的所有設定打包成一個json檔案,並保存到自己電腦上,打開看的內容會像這樣
{
    "info": {
        "_postman_id": "11111111-2222-3333-4444-71a293bd6d1a",
        "name": "Day 13: Newman",
        "description": "## Instructions for Day 13: Newman...",
        "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
        "_exporter_id": "3172240"
    },
    ...
}
Newman: 需要透過npm來安裝,沒有npm的朋友需要先安裝nodejs,然後打開terminal來安裝Newman
npm install -g newman
newman確認是否安裝成功,順便看使用方法,其實就是直接給定 url 或是檔案路徑
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
newman來執行剛剛打包的json檔案
newman run "Day 13- Newman.postman_collection.json"
Submit資料夾一起執行 
--folder 參數,並指定今天Collection的第一個資料夾Newman,這次就不應該有錯誤了
newman run "Day 13- Newman.postman_collection.json" --folder Newman
 
今天整個流程就是透過下指令的方式去執行一整個集合下的請求,非常適合用在整合CI/CD上,當然還有其他除了執行打包檔案的方式,例如下面這種,可以透過URL,也能夠指定環境變數
newman run https://www.postman.com/collections/xxxx -e environment.json
或是將執行結果另外保存成報表檔案
newman run mycollection.json --reporters cli,json --reporter-json-export outputfile.json
其他相關資料可以參考:
那麼今天就到這邊,我們明天見~