에이전트 파이프라인의 통합 테스트
격리된 테스트 환경에서 실제 서비스를 대상으로 종단 간 테스트를 실행합니다.
에이전트 파이프라인의 통합 테스트은(는) CoddyKit의 무료 AI Agents 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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 fixture 패턴을 사용하십시오. 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 tokensCI에서 통합 검사 실행하기
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')통합 검사 모범 사례 요약
신뢰할 수 있는 에이전트 통합 검사를 위한 핵심 규칙은 다음과 같습니다.
- 항상 별도의 검사 데이터베이스를 사용하고 운영 데이터베이스는 절대 사용하지 마십시오
yieldfixture를 사용하여 모든 검사 후 검사 데이터를 정리하십시오- 할당량이 제한된 전용 검사 API 키를 사용하십시오
- pytest 마커를 사용하여 빠른 단위 검사와 느린 통합 검사를 분리하십시오
- 푸시할 때마다 단위 검사를 실행하고 통합 검사는 일정에 따라 실행하십시오
- 폐기 가능한 깨끗한 데이터베이스 환경에는 Docker를 사용하십시오
이해도 확인: 통합 검사
에이전트 처리 흐름의 통합 검사에 대해 제대로 이해했는지 확인해 보십시오.
복습: 에이전트 처리 흐름의 통합 검사
이제 완전하고 신뢰할 수 있는 통합 검사 모음을 구축하는 데 필요한 지식을 갖추었습니다.
@pytest.mark.integration을 사용하여 느린 검사와 빠른 단위 검사를 분리하십시오- 전용 데이터베이스와 정리 fixture를 사용하여 검사 데이터를 격리하십시오
- 깨끗한 환경을 위해 Docker 또는 격리된 서비스를 사용하십시오
- 환경 변수를 통해 검사 전용 API 키를 구성하십시오
- 모든 커밋에서 단위 검사를 실행하고 CI에서는 매일 밤 통합 검사를 실행하십시오
pytest-cov로 검사 범위를 측정하여 검사되지 않은 경로를 찾으십시오
잘 구성된 검사 피라미드는 에이전트가 발전하는 동안에도 신뢰성을 유지하게 해 줍니다.
자주 묻는 질문
“에이전트 파이프라인의 통합 테스트” 강의는 무료인가요?
네 — “에이전트 파이프라인의 통합 테스트” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Agents 강의 전체를 잠금 해제할 수 있습니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.
“에이전트 파이프라인의 통합 테스트”에서 뭘 배우나요?
격리된 테스트 환경에서 실제 서비스를 대상으로 종단 간 테스트를 실행합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Agents을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
AI Agents을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 AI Agents은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“에이전트 파이프라인의 통합 테스트” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 AI Agents 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 AI Agents 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 에이전트 테스트가 다른 이유
- 테스트에서 LLM 호출 모의 처리
- 단정문 기반 에이전트 테스트
- 에이전트 파이프라인의 통합 테스트