0Pricing
AI Agents · レッスン

エージェントパイプラインの統合テスト

分離されたテスト環境で、実際のサービスを対象にエンドツーエンドテストを実行します。

「エージェントパイプラインの統合テスト」はCoddyKit上の無料AI Agentsレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはAI Agents学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 AI Agentsコースには全4レッスンが含まれています。

エージェントの統合テストとは

単体テストは、個々のコンポーネントを分離して検証します。統合テストは、複数のコンポーネントが実際の環境またはそれに近い環境で正しく連携することを検証します。

エージェントの場合は、LLM呼び出し、ツール実行、データ保存を含むパイプライン全体を、実際のサービスまたはサンドボックス化されたサービスに対して実行することを意味します。

エンドツーエンドテストの構成

エンドツーエンドのエージェントテストでは、実際のクエリをパイプライン全体に通し、最終結果を検証します。これらのテストはサンドボックス化された環境で実行し、本番データベースや実際のユーザーデータに対しては決して実行しないでください。

import pytest

# Mark as integration test — skipped in fast unit test runs
@pytest.mark.integration
def test_research_agent_full_pipeline():
    from myagent import ResearchAgent

    agent = ResearchAgent(
        openai_api_key='YOUR_TEST_KEY',
        search_api_key='YOUR_TEST_KEY'
    )

    result = agent.run('What is the population of Tokyo?')

    # Structural assertions — not exact string matching
    assert isinstance(result, dict)
    assert result['status'] == 'completed'
    assert 'tokyo' in result['answer'].lower() or 'japan' in result['answer'].lower()
    assert len(result['sources']) >= 1

テストデータの分離

統合テストによって共有データを汚染してはいけません。専用のテストデータベース、分離された名前空間、またはテスト後に削除する一時データを使用します。本番テーブルには決してテストデータを書き込まないでください。

import os
import pytest

# Use a separate test database URL
@pytest.fixture(scope='session')
def test_db():
    test_db_url = os.environ.get(
        'TEST_DATABASE_URL',
        'postgresql://localhost/myagent_test'  # separate test DB
    )
    # Set up test schema
    from myagent.database import create_tables
    create_tables(test_db_url)
    yield test_db_url
    # Tear down after all tests in the session
    from myagent.database import drop_tables
    drop_tables(test_db_url)

各テスト後のクリーンアップ

各統合テストでは、作成したデータをすべてクリーンアップする必要があります。pytestのyieldフィクスチャパターンを使用し、yieldの前にセットアップを行い、後にクリーンアップを行います。これにより、テストが互いに独立し、任意の順序で実行できるようになります。

import pytest

@pytest.fixture
def clean_agent_memory(test_db):
    # No setup needed — DB starts empty
    yield
    # Cleanup: delete any records created during this test
    from myagent.database import clear_conversation_history
    clear_conversation_history(test_db)

@pytest.mark.integration
def test_agent_stores_conversation(clean_agent_memory, test_db):
    from myagent import Agent
    agent = Agent(db_url=test_db)

    agent.run('Remember that my name is Alex')
    history = agent.get_history()

    assert len(history) > 0
    assert any('Alex' in str(msg) for msg in history)
    # clean_agent_memory fixture deletes these after the test

サンドボックス化されたサービス:テスト用APIキー

統合テストには、権限とクォータを制限した専用のテスト用APIキーを使用します。CIで本番用キーを使用してはいけません。テスト用キーはコードに保存せず、CIの環境変数として保存します。

import os
import pytest

# Skip integration tests if test keys are not configured
def requires_integration_keys():
    return pytest.mark.skipif(
        not os.environ.get('OPENAI_TEST_KEY'),
        reason='Integration test keys not configured'
    )

@requires_integration_keys()
@pytest.mark.integration
def test_live_weather_tool():
    from myagent.tools import get_weather
    result = get_weather(city='London', unit='celsius')

    assert result['success'] is True
    assert 'temperature' in result
    assert isinstance(result['temperature'], (int, float))

サンドボックス化されたデータベースにDockerを使う

実際のデータベースが必要な統合テストでは、テストセッション用のDockerコンテナを起動します。これにより、毎回クリーンで分離されたデータベースが保証され、開発用データベースとの競合を避けられます。

# conftest.py — docker-based test database
import subprocess
import pytest

@pytest.fixture(scope='session')
def docker_postgres():
    container_id = subprocess.check_output([
        'docker', 'run', '-d',
        '-e', 'POSTGRES_PASSWORD=test',
        '-e', 'POSTGRES_DB=agent_test',
        '-p', '5434:5432',  # use non-standard port to avoid conflicts
        'postgres:15'
    ]).decode().strip()

    import time
    time.sleep(2)  # wait for Postgres to start

    yield 'postgresql://postgres:test@localhost:5434/agent_test'

    subprocess.run(['docker', 'stop', container_id])
    subprocess.run(['docker', 'rm', container_id])

環境別のテスト設定

統合テストでは、ローカル、CI、ステージングの各環境に応じて異なる設定が必要です。環境変数と設定ヘルパーを使って、適切な設定を自動的に選択します。

import os

def get_test_config() -> dict:
    env = os.environ.get('TEST_ENV', 'local')

    configs = {
        'local': {
            'db_url': 'postgresql://localhost/agent_test',
            'openai_key': os.environ.get('OPENAI_TEST_KEY', ''),
            'use_real_llm': False  # use mocks locally
        },
        'ci': {
            'db_url': os.environ.get('CI_DATABASE_URL', ''),
            'openai_key': os.environ.get('CI_OPENAI_KEY', ''),
            'use_real_llm': True  # use real LLM in CI integration tests
        },
        'staging': {
            'db_url': os.environ.get('STAGING_DATABASE_URL', ''),
            'openai_key': os.environ.get('STAGING_OPENAI_KEY', ''),
            'use_real_llm': True
        }
    }
    return configs[env]

config = get_test_config()

print(f"TEST_ENV not set -> using '{os.environ.get('TEST_ENV', 'local')}' config")
print(f"DB URL       : {config['db_url']}")
print(f"Use real LLM : {config['use_real_llm']}")

テスト選択のためのpytestマーカー

カスタムpytestマーカーを使ってテストを分類し、関連するサブセットだけを実行します。pytest.iniでマーカーを設定し、コマンドラインで-mを使って選択します。

# pytest.ini
# [pytest]
# markers =
#     unit: Fast unit tests with mocked dependencies
#     integration: Slower tests with real or sandboxed services
#     expensive: Tests that make real LLM calls and cost money

# Run only unit tests (fast CI check):
# pytest -m unit

# Run only integration tests:
# pytest -m integration

# Run everything except expensive tests:
# pytest -m 'not expensive'

# In test files:
import pytest

@pytest.mark.unit
def test_tool_format():
    pass  # fast, no external calls

@pytest.mark.integration
@pytest.mark.expensive
def test_with_real_llm():
    pass  # slow, costs tokens

CIで統合テストを実行する

CIパイプライン(GitHub Actions、GitLab CI)を設定し、プッシュごとに単体テストを実行し、統合テストはスケジュールまたはリリース前に実行します。これにより、速度とカバレッジのバランスを取れます。

# .github/workflows/test.yml (abbreviated)
# name: Tests
# on:
#   push:
#     branches: [main, develop]
#   schedule:
#     - cron: '0 2 * * *'  # nightly integration tests
#
# jobs:
#   unit-tests:
#     runs-on: ubuntu-latest
#     steps:
#       - uses: actions/checkout@v3
#       - run: pip install -r requirements.txt
#       - run: pytest -m unit --tb=short
#
#   integration-tests:
#     if: github.event_name == 'schedule'
#     env:
#       CI_OPENAI_KEY: ${{ secrets.CI_OPENAI_KEY }}
#       CI_DATABASE_URL: ${{ secrets.CI_DATABASE_URL }}
#     steps:
#       - run: pytest -m integration --tb=long

print('Unit tests on every push, integration tests nightly')

エージェントのテストカバレッジを測定する

pytest-covを使って、エージェントのコードのどの行がテストでカバーされているかを測定します。LLM呼び出しをモックする場合でも、ツール関数とエージェントのオーケストレーションロジックは高いカバレッジを目指します。

# Install: pip install pytest-cov

# Run tests with coverage report:
# pytest --cov=myagent --cov-report=html -m unit

# This generates an HTML report showing which lines are untested
# Uncovered lines in the agent loop are high-risk areas

# Example coverage config in pyproject.toml:
# [tool.coverage.run]
# omit = ["tests/*", "scripts/*"]
#
# [tool.coverage.report]
# fail_under = 80  # fail if coverage drops below 80%

print('Coverage reports highlight untested code paths in your agent')

統合テストのベストプラクティスまとめ

信頼性の高いエージェント統合テストの基本ルール:

  • 必ず独立したテストデータベースを使用し、本番環境は決して使用しない
  • yieldフィクスチャを使って、すべてのテストの後にテストデータをクリーンアップする
  • クォータを制限した専用のテスト用APIキーを使用する
  • pytestマーカーを使って、高速な単体テストと低速な統合テストを分ける
  • プッシュごとに単体テストを実行し、統合テストはスケジュールに従って実行する
  • 使い捨て可能でクリーンなデータベース環境にはDockerを使用する

理解度チェック:統合テスト

エージェントのパイプラインに対する統合テストについて、理解度を確認しましょう。

復習:エージェントパイプラインの統合テスト

これで、完全で信頼性の高い統合テストスイートを構築するための知識が身に付きました。

  • @pytest.mark.integrationを使って、低速なテストと高速な単体テストを分けます
  • 専用データベースとクリーンアップフィクスチャを使って、テストデータを分離します
  • クリーンな環境にはDockerまたはサンドボックス化されたサービスを使用します
  • 環境変数を使って、テスト専用のAPIキーを設定します
  • コミットごとに単体テストを実行し、CIでは統合テストを毎晩実行します
  • pytest-covでカバレッジを測定し、未テストのパスを見つけます

整理されたテストピラミッドにより、エージェントが進化しても信頼性を維持できます。

よくある質問

「エージェントパイプラインの統合テスト」レッスンは無料ですか?

はい。「エージェントパイプラインの統合テスト」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、AI Agentsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 AI Agentsコースには全4レッスンが含まれています。

「エージェントパイプラインの統合テスト」で何を学びますか?

分離されたテスト環境で、実際のサービスを対象にエンドツーエンドテストを実行します。 ブラウザで直接実行するハンズオンコードでAI Agentsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

AI Agentsを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのAI Agentsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。

「エージェントパイプラインの統合テスト」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このAI Agentsレッスンでコードを書いて実行できますか?

はい。すべてのAI Agentsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. エージェントのテストが異なる理由
  2. テストにおけるLLM呼び出しのモック
  3. アサーションベースのエージェントテスト
  4. エージェントパイプラインの統合テスト
← AI Agentsに戻る