python-testing

작성자: microsoft

코드베이스 전반에 걸쳐 최소 85%의 테스트 커버리지를 목표로 하며, 핵심 패키지와 중요 경로에 중점을 둡니다. 테스트는 빠르고 신뢰할 수 있으며 유지보수가 용이해야 합니다. 새 코드를 추가할 때는 코드베이스의 관련 부분이 테스트로 커버되는지 확인하고 필요에 따라 새 테스트를 추가합니다. 기존 코드를 수정할 때는 변경 사항을 커버하도록 테스트를 업데이트하거나 추가합니다. PR의 경우 각 커밋은 단위 테스트만으로 테스트되며(-m "not integration" 사용), 전체 스위트는 다음을 포함하여 실행됩니다...

npx skills add https://github.com/microsoft/agent-framework --skill python-testing

Python Testing

CI enforces at least 85% line coverage for every package classified Beta or Production/Stable. Alpha packages are report-only, and the DevUI and experimental Lab packages are excluded from aggregate coverage enforcement. Tests should be fast, reliable, and maintainable. When adding new code, check that the relevant sections of the codebase are covered by tests, and add new tests as needed. When modifying existing code, update or add tests to cover the changes. We run tests in two stages, for a PR each commit is tested with unit tests only (using -m "not integration"), and the full suite including integration tests is run when merging.

When an API is marked as deprecated, migrate ordinary tests to its replacement in the same change. Retain only focused tests that validate the deprecated behavior and warning; integration tests, samples, and unrelated unit tests should use the supported API.

Running Tests

# Run tests for all packages in parallel
uv run poe test

# Run tests for a specific workspace package
uv run poe test -P core

# Run all selected tests in a single pytest invocation
uv run poe test -A

# With coverage
uv run poe test -A -C
uv run poe test -P core -C

# Run only unit tests (exclude integration tests)
uv run poe test -A -m "not integration"

# Run only integration tests
uv run poe test -A -m integration

Direct package execution still works when you need it:

uv run --directory packages/core poe test

Test Configuration

  • Async mode: asyncio_mode = "auto" is enabled — do NOT use @pytest.mark.asyncio, but do mark tests with async def and use await for async calls
  • Timeout: Default 60 seconds per test
  • Import mode: importlib for cross-package isolation
  • Parallelization: Large packages (core, ag-ui, orchestrations, anthropic) use pytest-xdist (-n auto --dist worksteal) in their poe test task. The aggregate uv run poe test -A sweep also uses xdist across the selected packages.

Test Directory Structure

Test directories must NOT contain __init__.py files.

Non-core packages must place tests in a uniquely-named subdirectory:

packages/anthropic/
├── tests/
│   └── anthropic/       # Unique subdirectory matching package name
│       ├── conftest.py
│       └── test_client.py

Core package can use tests/ directly with topic subdirectories:

packages/core/
├── tests/
│   ├── conftest.py
│   ├── core/
│   │   └── test_agents.py
│   └── openai/
│       └── test_client.py

Fixture Guidelines

  • Use conftest.py for shared fixtures within a test directory
  • Before adding new fixtures, check if existing ones can be reused or extended
  • Use descriptive names: mapper, test_request, mock_client

File Naming

  • Files starting with test_ are test files — do not use this prefix for helpers
  • Prefer extending an existing test file that already covers the same component or behavior; create a new file only for a distinct surface without an appropriate existing file
  • Use conftest.py for shared utilities

Integration Tests

Integration tests require external services (OpenAI, Azure, etc.) and are controlled by three markers:

  1. @pytest.mark.flaky — marks the test as potentially flaky since it depends on external services
  2. @pytest.mark.integration — used for test selection, so integration tests can be included/excluded with -m integration / -m "not integration"
  3. @skip_if_..._integration_tests_disabled decorator — skips the test when the required API keys or service endpoints are missing

Adding New Integration Tests

All three markers must be applied to every new integration test:

@pytest.mark.flaky
@pytest.mark.integration
@skip_if_openai_integration_tests_disabled
async def test_openai_chat_completion() -> None:
    ...

For test files where all tests are integration tests (e.g., Azure Functions, Durable Task), use the module-level pytestmark list:

pytestmark = [
    pytest.mark.flaky,
    pytest.mark.integration,
    pytest.mark.sample("01_single_agent"),
    pytest.mark.usefixtures("function_app_for_test"),
]

CI Workflow

The merge CI workflow (python-merge-tests.yml) splits integration tests into parallel jobs by provider with change-based detection:

  • Unit tests — always run all non-integration tests
  • OpenAI integration — runs when packages/core/agent_framework/openai/ or core infrastructure changes
  • Azure OpenAI integration — runs when packages/core/agent_framework/azure/ or core changes
  • Misc integration — Anthropic, Ollama, MCP tests; runs when their packages or core change
  • Functions integration — Azure Functions + Durable Task; runs when their packages or core change
  • Foundry integration — runs when packages/foundry/ or core changes

Core infrastructure changes (e.g., _agents.py, _types.py) trigger all integration test jobs. Scheduled and manual runs always execute all jobs.

Keeping CI Workflows in Sync

Two workflow files define the same set of parallel test jobs:

  • python-merge-tests.yml — runs on PRs, merge queue, schedule, and manual dispatch. Uses path-based change detection to skip unaffected integration jobs.
  • python-integration-tests.yml — called from the manual integration test orchestrator (integration-tests-manual.yml). Always runs all jobs (no path filtering).

These workflows must be kept in sync. When you add, remove, or modify a test job, update both files. The job structure, pytest commands, and xdist flags should match between them. The only difference is that python-merge-tests.yml has path filters and conditional job execution, while python-integration-tests.yml does not.

Updating the CI When Adding Integration Tests for a New Provider

When adding integration tests for a new provider package, you must update both python-merge-tests.yml and python-integration-tests.yml:

  1. Add a path filter for the new provider in the paths-filter job in python-merge-tests.yml so the CI knows which file changes should trigger those tests.
  2. Add the test job to both workflow files — either add them to the existing python-tests-misc-integration job, or create a dedicated job if the provider:
    • Has a large number of integration tests
    • Requires special infrastructure setup (emulators, Docker containers, etc.)
    • Has long-running tests that would slow down the misc job

The python-tests-misc-integration job is intended for small integration test suites that don't need dedicated infrastructure. When a provider's integration tests grow large or gain special requirements, split them out into their own job (like python-tests-functions was split out for Azure Functions + Durable Task).

Best Practices

  • Run only related tests, not the entire suite
  • Review existing tests to understand coding style before creating new ones
  • Use print statements for debugging, then remove them when done
  • Resolve all errors and warnings before committing

microsoft의 다른 스킬

oss-growth
microsoft
OSS 성장 해커 페르소나
agent-framework-azure-ai-py
microsoft
Microsoft Agent Framework Python SDK(agent-framework-azure-ai)를 사용하여 Azure AI Foundry 에이전트를 구축합니다. AzureAIAgentsProvider로 지속적 에이전트를 만들 때, 호스팅 도구(코드 인터프리터, 파일 검색, 웹 검색)를 사용할 때, MCP 서버를 통합할 때, 대화 스레드를 관리할 때, 또는 스트리밍 응답을 구현할 때 사용합니다. 함수 도구, 구조화된 출력, 다중 도구 에이전트를 다룹니다.
development
airunway-aks-setup
microsoft
AKS에서 AI Runway 설정 — 빈 클러스터에서 실행 중인 모델까지. 클러스터 검증, 컨트롤러 설치, GPU 평가, 공급자 설정, 첫 배포를 다룹니다. 시기: "AI Runway 설정", "AKS 클러스터 온보딩", "AI Runway 설치", "airunway 설정", "AKS에 모델 배포", "AKS에서 GPU 추론", "AKS에서 KAITO 설정", "AKS에서 LLM 실행", "AKS에서 vLLM", "AKS에서 모델 서빙 설정", "AI Runway 컨트롤러".
devops
appinsights-instrumentation
microsoft
Azure Application Insights로 웹앱을 계측하기 위한 지침입니다. 원격 분석 패턴, SDK 설정, 구성 참조를 제공합니다. WHEN: 앱 계측 방법, App Insights SDK, 원격 분석 패턴, App Insights란 무엇인가, Application Insights 지침, 계측 예시, APM 모범 사례.
devops
applicationinsights-web-ts
microsoft
브라우저/웹 앱을 Application Insights JavaScript SDK(@microsoft/applicationinsights-web)로 계측합니다. Real User Monitoring(RUM) — 페이지 뷰, 클릭, AJAX/fetch 종속성, 예외, 사용자 지정 이벤트, 백엔드 OpenTelemetry 트레이스와 상관관계가 있는 브라우저 측 GenAI 에이전트 트레이스에 사용합니다. SDK Loader Script 및 npm 설정, 프레임워크 확장(React, React Native, Angular), Click Analytics, 텔레메트리 이니셜라이저, 브라우저에서 생성된 에이전트/도구/모델 스팬에 대한 OTel GenAI 의미론적 규칙을 다룹니다.
devops
azure-ai-anomalydetector-java
microsoft
Azure AI Anomaly Detector SDK for Java로 이상 탐지 애플리케이션을 구축하세요. 단변량/다변량 이상 탐지, 시계열 분석 또는 AI 기반 모니터링을 구현할 때 사용하세요.
development
azure-ai-language-conversations-py
microsoft
azure-ai-language-conversations Python SDK를 사용하여 대화형 언어 이해(CLU)를 구현합니다. ConversationAnalysisClient로 대화 의도와 엔터티를 분석하거나, NLP 기능을 구축하거나, 애플리케이션에 언어 이해를 통합할 때 사용합니다.
development
azure-ai-ml-py
microsoft
Azure Machine Learning SDK v2 for Python. ML 작업 영역, 작업, 모델, 데이터 세트, 컴퓨팅 및 파이프라인에 사용합니다. 트리거: "azure-ai-ml", "MLClient", "workspace", "model registry", "training jobs", "datasets".
development