Skip to content

k6スクリプトサンプル

Grafana k6上で実行するスクリプトのサンプル集です。

cf. https://grafana.com/docs/k6/latest/using-k6/

レスポンスを検証

import http from "k6/http";
import { sleep, check } from "k6";

export const options = {
  vus: 1,
  duration: "10s",
  thresholds: {
    http_req_duration: ["avg < 100"], // 平均処理時間[ms]を検証
  },
};

export default function () {
  const res = http.get("http://host.docker.internal:8080/api/v1/me?name=nob");

  // HTTPステータス検証
  check(res, { "status is 200": (res) => res.status === 200 });

  // レスポンスモデル検証
  check(res, {
    "response name is correct": (res) => res.json().name === "nob",
    "response age is correct": (res) => res.json().age === 13,
  });

  sleep(1);
}

指定の回数だけAPIを打鍵

import http from "k6/http";
import { sleep, check } from "k6";

export const options = {
  scenarios: {
    contacts: {
      executor: "shared-iterations", // 各ユーザが均等にリクエストをすることを担保する場合はper-vu-iterationsを使う
      vus: 10,
      iterations: 200, // 10ユーザで合計200回APIを実行
      maxDuration: "3m", // 3分経過したら強制終了
    },
  },
};

export default function () {
  http.get("http://host.docker.internal:8080/api/v1/me?name=nob");
}

仮想ユーザごとに異なるリクエストを送信

import http from "k6/http";
import { sleep, check } from "k6";

export const options = {
  vus: 2,
  duration: "5s",
};

export default function () {
  // virtual userのIDととそれに紐づく業務アプリ上のユーザ情報のマップ
  const usersMap = new Map([
    [1, { name: "nob1", age: 13 }],
    [2, { name: "nob2", age: 706 }],
  ]);

  const res = http.get(
    "http://host.docker.internal:8080/api/v1/me" +
      "?name=" +
      usersMap.get(__VU).name,
  );

  check(res, { "status is 200": (res) => res.status === 200 });
  check(res, {
    "response name is correct": (res) =>
      res.json().name === usersMap.get(__VU).name,
    "response age is correct": (res) =>
      res.json().age === usersMap.get(__VU).age,
  });

  sleep(1);
}