首页 > 解决方案 > 如何从无服务器火炮中的随机 JSON 索引中捕获属性

问题描述

在 Artillery 中,如何在从 GET 返回的 JSON 数组中捕获随机索引的属性,以便我后续的 POST 均匀分布在资源中?

https://artillery.io/docs/http-reference/#extracting-and-reusing-parts-of-a-response-request-chaining

我正在使用无服务器火炮来运行负载测试,该测试在后台使用 artillery.io 。

我的很多场景都是这样的:

      -
        get:
          url: "/resource"
          capture:
            json: "$[0].id"
            as: "resource_id"
      -
        post:
          url: "/resource/{{ resource_id }}/subresource"
          json:
            body: "Example"

获取资源列表,然后 POST 到其中一个资源。

如您所见,我正在使用capture从 JSON 响应中捕获 ID。我的问题是它总是从数组的第一个索引中获取 id。

这将意味着在我的负载测试中,我最终绝对会打击一个资源,而不是均匀地打击它们,这将是一种更有可能的情况。

我希望能够做类似的事情:

capture:
  json: "$[RANDOM].id
  as: "resource_id"

但我一直无法在 JSONPath 定义中找到任何可以让我这样做的东西。

标签: jsonjsonpathartillery

解决方案


在自定义 JS 代码中定义 setResourceId 函数并告诉 Artillery 加载您的自定义代码,将 config.processor 设置为 JS 文件路径:

处理器:“./custom-code.js”

   - get:
      url: "/resource"
      capture:
        json: "$"
        as: "resources"
  - function: "setResourceId"
  -  post:
      url: "/resource/{{ resourceId }}/subresource"
      json:
        body: "Example"

包含以下函数的 custom-code.js 文件

function setResourceId(context, next) {
    const randomIndex = Math.round(Math.random() * context.vars.resources.length);
    context.vars.resourceId = context.vars.resources[randomIndex].id;
}

推荐阅读