{
  "version": 13,
  "name": "code-loops",
  "description": "Code blocks and loops: a retry until 200, a request inside a for loop, http() and a variable shared between steps.",
  "tags": [
    "code"
  ],
  "globals": [
    {
      "name": "$baseUrl",
      "value": "https://dummyjson.com"
    },
    {
      "name": "$maxPrice",
      "value": "500"
    },
    {
      "name": "$picked",
      "value": "[]"
    }
  ],
  "globalFunctions": "// Assertion helpers, built on check(label, pass, details).\n// Each records a pass / fail line in the log and the report.\n// A failed one fails its step when the step is done;\n// the code keeps running. Change them or add your own.\n// r defaults to the last response.\n\nfunction assertTrue(value, label = \"is true\") {\n  return check(label, Boolean(value), { actual: value, expected: true });\n}\n\nfunction assertEqual(actual, expected, label = \"equals \" + JSON.stringify(expected)) {\n  return check(label, isEqual(actual, expected), { actual, expected });\n}\n\nfunction assertNotEqual(actual, unexpected, label = \"does not equal \" + JSON.stringify(unexpected)) {\n  return check(label, !isEqual(actual, unexpected), { actual, expected: \"not \" + JSON.stringify(unexpected) });\n}\n\n// text contains a part, or a list contains an item\nfunction assertContains(haystack, needle, label = \"contains \" + JSON.stringify(needle)) {\n  const pass = Array.isArray(haystack) ? haystack.some((x) => isEqual(x, needle)) : String(haystack).includes(needle);\n  return check(label, pass, { actual: haystack, expected: needle });\n}\n\nfunction assertMatch(text, regex, label = \"matches \" + regex) {\n  return check(label, new RegExp(regex).test(String(text)), { actual: text, expected: String(regex) });\n}\n\nfunction assertLessThan(actual, limit, label = \"< \" + limit) {\n  return check(label, Number(actual) < Number(limit), { actual, expected: \"< \" + limit });\n}\n\nfunction assertGreaterThan(actual, limit, label = \"> \" + limit) {\n  return check(label, Number(actual) > Number(limit), { actual, expected: \"> \" + limit });\n}\n\n// expected: 200, \"2xx\", or a list such as [200, 201]\nfunction assertStatus(expected, r = response) {\n  const list = [].concat(expected).map(String);\n  const status = String(r && r.status);\n  const pass = list.some((e) => e === status || (/^[1-5]xx$/i.test(e) && e[0] === status[0]));\n  return check(\"status is \" + list.join(\" or \"), pass, { actual: r && r.status, expected });\n}\n\nfunction assertTimeBelow(ms, r = response) {\n  return check(\"time < \" + ms + \" ms\", Boolean(r) && r.timeMs < ms, { actual: r && r.timeMs, expected: \"< \" + ms });\n}\n\n// without expected, the header only has to exist\nfunction assertHeader(name, expected, r = response) {\n  const value = r ? r.headers[String(name).toLowerCase()] : undefined;\n  if (expected === undefined) return check(\"header \" + name + \" exists\", value !== undefined, { actual: value });\n  return check(\"header \" + name + \" equals \" + expected, String(value) === String(expected), { actual: value, expected });\n}\n\n// e.g. assertJsonPath(\"$.items[0].id\", 42); without expected, the value only has to exist\nfunction assertJsonPath(path, expected, r = response) {\n  const value = jsonPath(path, r);\n  if (expected === undefined) return check(path + \" exists\", value !== undefined, { actual: value });\n  return check(path + \" equals \" + JSON.stringify(expected), isEqual(value, expected), { actual: value, expected });\n}\n\n// schema: a JSON Schema object\nfunction assertSchema(schema, r = response) {\n  const result = validateSchema(r, schema);\n  return check(\"matches the JSON Schema\", result.valid, { error: result.errors || undefined });\n}\n",
  "libraries": [],
  "activeEnvironment": "",
  "auth": {
    "type": "none"
  },
  "settings": {},
  "data": {
    "file": ""
  },
  "cookies": [],
  "steps": [
    {
      "id": "health",
      "type": "request",
      "name": "Health check (retries until 200)",
      "conditional": "true",
      "method": "GET",
      "url": "$baseUrl/test",
      "params": [],
      "headers": [],
      "bodyMode": "raw",
      "body": "",
      "multipart": [],
      "bodyFile": {
        "path": "",
        "contentType": ""
      },
      "followRedirects": true,
      "httpVersion": "inherit",
      "auth": {
        "type": "inherit"
      },
      "extract": [],
      "checks": [
        {
          "enabled": true,
          "target": "json",
          "path": "$.status",
          "op": "equals",
          "value": "ok"
        }
      ],
      "loop": {
        "enabled": true,
        "count": 3,
        "untilStatus": 200,
        "intervalMs": 500
      },
      "saveResponse": {
        "enabled": false,
        "path": "",
        "onlyOk": true
      }
    },
    {
      "id": "list",
      "type": "request",
      "name": "List phones",
      "conditional": "true",
      "method": "GET",
      "url": "$baseUrl/products/category/smartphones",
      "params": [
        {
          "name": "limit",
          "value": "10"
        },
        {
          "name": "select",
          "value": "title,price"
        }
      ],
      "headers": [],
      "bodyMode": "raw",
      "body": "",
      "multipart": [],
      "bodyFile": {
        "path": "",
        "contentType": ""
      },
      "followRedirects": true,
      "httpVersion": "inherit",
      "auth": {
        "type": "inherit"
      },
      "extract": [],
      "checks": [
        {
          "enabled": true,
          "target": "status",
          "path": "",
          "op": "equals",
          "value": "200"
        }
      ],
      "loop": {
        "enabled": false,
        "count": 5,
        "untilStatus": 200,
        "intervalMs": 1000
      },
      "saveResponse": {
        "enabled": false,
        "path": "",
        "onlyOk": true
      }
    },
    {
      "id": "pick",
      "type": "code",
      "name": "Pick the affordable ones",
      "conditional": "true",
      "code": "// response is the previous request's response.\nconst phones = JSON.parse(response.body).products;\n\n// A $variable assigned without let / const is shared with later steps.\n$picked = phones.filter((p) => p.price <= $maxPrice).map((p) => p.id);\nlog(`${$picked.length} of ${phones.length} phones cost at most ${$maxPrice}`);",
      "requests": []
    },
    {
      "id": "details",
      "type": "code",
      "name": "Check each one (request in a loop)",
      "conditional": "true",
      "code": "// The request box below is a request stored in this step: click it to edit.\nconst inStock = [];\nfor ($id of $picked) {\n  const r = await request(\"rq_details\");\n  if (r.checks.passed) inStock.push(JSON.parse(r.body).title);\n}\nlog(\"In stock: \" + inStock.join(\", \"));",
      "requests": [
        {
          "id": "rq_details",
          "name": "Product details",
          "conditional": "true",
          "method": "GET",
          "url": "$baseUrl/products/$id",
          "params": [
            {
              "name": "select",
              "value": "title,price,stock"
            }
          ],
          "headers": [],
          "bodyMode": "raw",
          "body": "",
          "multipart": [],
          "bodyFile": {
            "path": "",
            "contentType": ""
          },
          "followRedirects": true,
          "httpVersion": "inherit",
          "auth": {
            "type": "inherit"
          },
          "extract": [],
          "checks": [
            {
              "enabled": true,
              "target": "status",
              "path": "",
              "op": "equals",
              "value": "200"
            },
            {
              "enabled": true,
              "target": "json",
              "path": "$.stock",
              "op": "gt",
              "value": "0"
            }
          ],
          "loop": {
            "enabled": false,
            "count": 5,
            "untilStatus": 200,
            "intervalMs": 1000
          },
          "saveResponse": {
            "enabled": false,
            "path": "",
            "onlyOk": true
          }
        }
      ]
    }
  ]
}
