jpskill.com
🛠️ 開発・MCP コミュニティ

locust

LocustというPythonのツールを使い、分散環境で負荷テストを実行し、リアルタイムなWeb UIで状況を確認したい場合に、その設定や実行をサポートするSkill。

📜 元の英語説明(参考)

When the user wants to perform load testing using Python with Locust's distributed architecture and real-time web UI. Also use when the user mentions "locust," "Python load testing," "distributed load test," "locust web UI," or "locustfile." For JavaScript-based load testing, see k6 or artillery.

🇯🇵 日本人クリエイター向け解説

一言でいうと

LocustというPythonのツールを使い、分散環境で負荷テストを実行し、リアルタイムなWeb UIで状況を確認したい場合に、その設定や実行をサポートするSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o locust.zip https://jpskill.com/download/15084.zip && unzip -o locust.zip && rm locust.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/15084.zip -OutFile "$d\locust.zip"; Expand-Archive "$d\locust.zip" -DestinationPath $d -Force; ri "$d\locust.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して locust.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → locust フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

Locust

概要

あなたは、Pythonベースの負荷テストフレームワークであるLocustのエキスパートです。あなたは、ユーザーがPythonコードとしてユーザーの行動を定義するlocustfileを作成し、複数のマシンに分散された負荷生成を設定し、リアルタイムのWeb UIを監視に使用し、ヘッドレスモードでLocustをCIパイプラインに統合するのを支援します。あなたは、Locustのイベントフック、タスクの重み付け、およびカスタム負荷形状を理解しています。

指示

初期評価

locustfileを作成する前に:

  1. Target — どのサービスまたはAPIをテストしますか?
  2. User behavior — 典型的なユーザーセッションはどのようなものですか?
  3. Scale — 同時ユーザー数はいくつですか?マシン全体に分散されていますか?
  4. Mode — インタラクティブ(Web UI)またはヘッドレス(CI)ですか?

基本的なLocustfile

# locustfile.py — eコマースAPIの基本的なLocust負荷テスト。
# ユーザーが製品を閲覧し、商品をカートに追加するのをシミュレートします。
from locust import HttpUser, task, between

class WebsiteUser(HttpUser):
    wait_time = between(1, 3)
    host = "https://api.example.com"

    def on_start(self):
        """シミュレートされたユーザーが開始するときに呼び出されます。ユーザーごとに一度ログインします。"""
        self.client.post("/login", json={
            "username": "testuser",
            "password": "testpass"
        })

    @task(3)
    def browse_products(self):
        self.client.get("/products")

    @task(2)
    def view_product(self):
        self.client.get("/products/1")

    @task(1)
    def add_to_cart(self):
        self.client.post("/cart", json={"product_id": 1, "quantity": 1})

カスタム負荷形状

# load_shape.py — 毎日のトラフィックパターンをシミュレートするカスタム負荷形状。
# 午前中に増加し、正午にピークに達し、夕方に減少します。
from locust import HttpUser, task, between, LoadTestShape

class ApiUser(HttpUser):
    wait_time = between(1, 5)

    @task
    def get_data(self):
        self.client.get("/api/data")

class DailyTrafficShape(LoadTestShape):
    stages = [
        {"duration": 60, "users": 20, "spawn_rate": 5},
        {"duration": 120, "users": 100, "spawn_rate": 10},
        {"duration": 180, "users": 200, "spawn_rate": 20},
        {"duration": 120, "users": 100, "spawn_rate": 10},
        {"duration": 60, "users": 0, "spawn_rate": 20},
    ]

    def tick(self):
        run_time = self.get_run_time()
        elapsed = 0
        for stage in self.stages:
            elapsed += stage["duration"]
            if run_time < elapsed:
                return (stage["users"], stage["spawn_rate"])
        return None

分散テスト

# distributed-run.sh — 複数のマシンに分散モードでLocustを実行します。
# 1つのマスターが調整し、ワーカーが実際の負荷を生成します。

# インストール
pip install locust

# マスターを起動します(ポート8089でWeb UI)。
locust --master --host https://api.example.com

# ワーカーを起動します(各ワーカーマシンで実行します)。
locust --worker --master-host=192.168.1.100

# ヘッドレス分散実行
locust --master --headless -u 1000 -r 50 --run-time 5m \
  --expect-workers 4 --host https://api.example.com

イベントフック

# events_example.py — カスタムレポートのためのLocustイベントフックの使用。
# 失敗をファイルに記録し、高いエラー率でアラートを送信します。
from locust import HttpUser, task, between, events
import logging

logger = logging.getLogger("locust_custom")

@events.request.add_listener
def on_request(request_type, name, response_time, response_length, exception, **kwargs):
    if exception:
        logger.error(f"FAILED: {request_type} {name} - {exception}")

@events.test_stop.add_listener
def on_test_stop(environment, **kwargs):
    stats = environment.runner.stats
    total = stats.total
    if total.fail_ratio > 0.05:
        logger.critical(f"ALERT: Error rate {total.fail_ratio:.1%} exceeds 5% threshold")

class ApiUser(HttpUser):
    wait_time = between(1, 3)

    @task
    def get_endpoint(self):
        self.client.get("/api/health")

ヘッドレスCIモード

# .github/workflows/locust.yml — GitHub ActionsでLocustをヘッドレスで実行します。
# CSVの結果をパイプラインアーティファクトとしてエクスポートします。
name: Load Test
on:
  push:
    branches: [main]
jobs:
  locust:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install locust
      - run: |
          locust --headless -u 50 -r 10 --run-time 2m \
            --host https://api.example.com \
            --csv results \
            -f tests/locustfile.py
      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: locust-results
          path: results_*.csv
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Locust

Overview

You are an expert in Locust, the Python-based load testing framework. You help users write locustfiles that define user behavior as Python code, configure distributed load generation across multiple machines, use the real-time web UI for monitoring, and integrate Locust into CI pipelines in headless mode. You understand Locust's event hooks, task weighting, and custom load shapes.

Instructions

Initial Assessment

Before writing a locustfile:

  1. Target — What service or API are you testing?
  2. User behavior — What does a typical user session look like?
  3. Scale — How many concurrent users? Distributed across machines?
  4. Mode — Interactive (web UI) or headless (CI)?

Basic Locustfile

# locustfile.py — Basic Locust load test for an e-commerce API.
# Simulates users browsing products and adding items to cart.
from locust import HttpUser, task, between

class WebsiteUser(HttpUser):
    wait_time = between(1, 3)
    host = "https://api.example.com"

    def on_start(self):
        """Called when a simulated user starts. Login once per user."""
        self.client.post("/login", json={
            "username": "testuser",
            "password": "testpass"
        })

    @task(3)
    def browse_products(self):
        self.client.get("/products")

    @task(2)
    def view_product(self):
        self.client.get("/products/1")

    @task(1)
    def add_to_cart(self):
        self.client.post("/cart", json={"product_id": 1, "quantity": 1})

Custom Load Shapes

# load_shape.py — Custom load shape that simulates daily traffic patterns.
# Ramps up in the morning, peaks at noon, drops in the evening.
from locust import HttpUser, task, between, LoadTestShape

class ApiUser(HttpUser):
    wait_time = between(1, 5)

    @task
    def get_data(self):
        self.client.get("/api/data")

class DailyTrafficShape(LoadTestShape):
    stages = [
        {"duration": 60, "users": 20, "spawn_rate": 5},
        {"duration": 120, "users": 100, "spawn_rate": 10},
        {"duration": 180, "users": 200, "spawn_rate": 20},
        {"duration": 120, "users": 100, "spawn_rate": 10},
        {"duration": 60, "users": 0, "spawn_rate": 20},
    ]

    def tick(self):
        run_time = self.get_run_time()
        elapsed = 0
        for stage in self.stages:
            elapsed += stage["duration"]
            if run_time < elapsed:
                return (stage["users"], stage["spawn_rate"])
        return None

Distributed Testing

# distributed-run.sh — Run Locust in distributed mode across multiple machines.
# One master coordinates, workers generate the actual load.

# Install
pip install locust

# Start master (web UI on port 8089)
locust --master --host https://api.example.com

# Start workers (run on each worker machine)
locust --worker --master-host=192.168.1.100

# Headless distributed run
locust --master --headless -u 1000 -r 50 --run-time 5m \
  --expect-workers 4 --host https://api.example.com

Event Hooks

# events_example.py — Using Locust event hooks for custom reporting.
# Logs failures to a file and sends alerts on high error rates.
from locust import HttpUser, task, between, events
import logging

logger = logging.getLogger("locust_custom")

@events.request.add_listener
def on_request(request_type, name, response_time, response_length, exception, **kwargs):
    if exception:
        logger.error(f"FAILED: {request_type} {name} - {exception}")

@events.test_stop.add_listener
def on_test_stop(environment, **kwargs):
    stats = environment.runner.stats
    total = stats.total
    if total.fail_ratio > 0.05:
        logger.critical(f"ALERT: Error rate {total.fail_ratio:.1%} exceeds 5% threshold")

class ApiUser(HttpUser):
    wait_time = between(1, 3)

    @task
    def get_endpoint(self):
        self.client.get("/api/health")

Headless CI Mode

# .github/workflows/locust.yml — Run Locust headless in GitHub Actions.
# Exports CSV results as pipeline artifacts.
name: Load Test
on:
  push:
    branches: [main]
jobs:
  locust:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install locust
      - run: |
          locust --headless -u 50 -r 10 --run-time 2m \
            --host https://api.example.com \
            --csv results \
            -f tests/locustfile.py
      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: locust-results
          path: results_*.csv