Introducing a new way to review your PRs.

Read the announcement

aio-libs / aiobotocore

asyncio support for botocore library using aiohttp

View on GitHub

18 documents · Updated Nov 20, 2026

docs / stubbing-and-test-support

Stubbing and test support

The stubbing and test support layer gives asynchronous client tests controlled service results without depending on AWS. It covers modeled operation results, raw HTTP exchanges, local service endpoints, in-memory response streams, credentials, and transport sessions. Together these tools let tests check client behavior, transport behavior, and service workflows with repeatable inputs.

See Testing and compatibility tooling for the wider test and compatibility model.

Test support model

The test suite chooses the smallest test double that can prove a behavior. Operation stubs check client contracts. HTTP stubs check request and response handling. Local servers check behavior that needs a real network path or a service-like state model. In-memory response bodies check stream behavior across the supported HTTP backends. Credential tests use small async clients, mocked providers, temporary files, and modeled service responses to isolate credential-chain decisions.

Asynchronous operation stubbing

home/…/stub.py provides AioStubber, an async-aware form of the botocore stubber. It places planned results in a queue and returns them through the same async response shape used by a client call. This keeps tests focused on client behavior while avoiding a live service.

Each planned success is tied to a client method and a service response. The stubber resolves the method to the service operation and validates the response against the service model. Tests can also define expected call parameters, so a wrong request fails at the client boundary instead of producing a misleading result.

The error path follows the same model. A planned client error carries a service code, message, HTTP status, and optional metadata. When a service defines extra error fields, the stubber validates the modeled fields before placing the error in the queue.

Credential tests use the same modeled response pattern for role and SSO flows. They queue responses for each chained assume-role call, check that requests carry MFA or SSO parameters, and verify that the resulting credentials include fields such as account ID. The StubbedSession helper keeps one stubber per cached service client and exposes activation and pending-response checks for session-level scenarios.

References: aiobotocore/stub.py• L1-108 tests/test_stubber.py• L9-77 tests/…/helpers.py• L8-52 tests/…/test_credentials.py• L342-398 tests/…/test_credentials.py• L1458-1516

HTTP exchange stubbing

tests/…/__init__.py provides BaseHTTPStubber and two scope variants for tests that must observe the wire boundary. The stubber listens at the client or session event layer, records outgoing requests, and returns queued asynchronous responses in order.

The response plan can set the URL, status, headers, and body. It can also contain an exception to model a failed send. Strict mode rejects a request when the response plan is empty. This makes missing or wrongly ordered responses visible rather than silently passing a test.

ClientHTTPStubber applies to one client. SessionHTTPStubber applies to the session event emitter and can cover clients created from that session. Both use AioAWSResponse, so response content is read asynchronously like content from the normal transport path.

References: tests/…/__init__.py• L120-193 aiobotocore/awsrequest.py• L5-40 tests/…/test_useragent.py• L26-125

Local service servers

The local server helpers provide a real endpoint when a test needs network scheduling, streaming, redirects, callbacks, or a service state model. They keep the client on its normal request path while replacing the external service with a process-local target.

tests/mock_server.py defines AIOServer, a small async HTTP server with immediate success and redirect routes plus a delayed streaming route. The delayed route lets transport tests observe read timeouts and shutdown behavior. The server runs in its own thread and event loop, publishes a bound ephemeral port only after it is ready, and stops when its async context ends. Startup failures and a thread that exits before binding are reported during context entry, while context exit joins the server thread.

The moto_server fixture starts a local Moto AWS service. Client fixtures point at it for mocked service workflows and use fixed test credentials. Tests that need callbacks can direct a service action back to AIOServer, which prevents the callback from reaching the public internet.

Stateful service tests use the same local-service pattern to model resource life cycles. The DynamoDB scenarios create tables, poll with a waiter until the table exists, read and write items, and verify deletion. One scenario creates the table in a concurrent task so the waiter path is tested against a resource that becomes available during polling.

References: tests/mock_server.py• L12-114 tests/test_mock_server.py• L6-52 tests/test_config.py• L122-177 tests/test_sns.py• L71-87 tests/test_dynamodb.py• L38-50 tests/test_dynamodb.py• L102-131

Shared test controls

tests/conftest.py supplies the common controls that keep async tests isolated and comparable. It removes ambient AWS configuration for normal tests, selects the HTTP backend, creates service clients against local endpoints, and provides shared checks for response status and eventual service state.

The fixtures also manage test resources such as buckets, tables, streams, topics, queues, and objects. Creation helpers return handles that tests use in their scenario. Teardown removes the resources so one test does not change the starting state of another.

HTTP tests receive an http_session_cls fixture that follows the selected backend or a test-specific configuration. The related current_http_backend fixture gives tests a stable backend name. This lets one behavior run against aiohttp and HTTPX while keeping backend-specific assertions at the transport boundary.

Some tests must patch event-listener targets before a client is created. The patch_attributes fixture applies those patches early and returns the resulting mocks. This preserves the reference that the client observes when it registers its event listeners.

References: tests/conftest.py• L53-77 tests/conftest.py• L98-161 tests/conftest.py• L190-217 tests/conftest.py• L244-313 tests/conftest.py• L446-604 tests/conftest.py• L642-785

Asynchronous response bodies

aiobotocore/response.py defines the async response-body contract used by client results. tests/test_response.py supplies in-memory body sources for the aiohttp and HTTPX paths, so tests can check the same read, iteration, line, close, and context-manager behavior without a service.

These tests model both valid and broken responses. They cover short bodies, partial reads, small transport chunks, timeouts, and connection failures. The checks ensure that both backends preserve content-length validation and expose shared client-level errors instead of leaking backend-specific stream errors. S3 integration tests then exercise these bodies through real client results and close them with the correct async or sync form for the active backend.

References: aiobotocore/response.py• L36-129 aiobotocore/response.py• L131-295 tests/test_response.py• L49-251 tests/test_response.py• L279-437 tests/test_response.py• L448-571 tests/test_basic_s3.py• L208-232 tests/test_basic_s3.py• L287-318

Transport session contracts

tests/test_httpsession.py checks the contract between the async client session and its selected HTTP backend without using a live endpoint. Backend-specific transport spies expose the request settings that reach aiohttp or HTTPX, so one behavior can be checked across the supported session paths.

The tests cover request-scoped read timeout overrides, fallback to client configuration, and updates made by request-created event handlers. They also protect session lifecycle rules: blocking SSL setup stays off the event loop, cached setup is not repeated, redirects remain available to botocore rather than being followed by the transport, and close remains safe when called more than once or while a user exception is active.

Client lifetime is part of the contract. Tests verify that an operation after the async client context has exited raises an HTTP client error rather than silently creating a new session. The HTTPX case also confirms that its underlying session is closed after the client context.

References: tests/test_httpsession.py• L15-62 tests/test_httpsession.py• L64-117 tests/test_httpsession.py• L124-206 tests/test_httpsession.py• L208-241

Credential response controls

Credential tests model external credential sources without making their real calls. Small async client doubles return queued assume-role or web-identity results. Mock providers control which source returns credentials. Temporary config files and patched environment maps let the resolver be tested with isolated profiles and source order.

The SSO fixtures combine a real async client with a botocore Stubber, a fake token loader, a fixed clock, and an in-memory cache. This makes cache hits, expired entries, required configuration, account IDs, and service errors deterministic. Process credentials use mocked subprocesses for normal async execution and a patched synchronous subprocess path when the event loop cannot start subprocesses.

Refresh tests use async mock refreshers and fixed time values. They model successful refresh, empty or missing refresh data, expired credentials, and cleanup after refresh failure. The test support therefore checks both the response data and the timing rules that decide when a response is used again.

References: tests/…/test_credentials.py• L87-109 tests/…/test_credentials.py• L1084-1123 tests/…/test_credentials.py• L1237-1283 tests/…/test_credentials.py• L1588-1751 tests/…/test_credentials.py• L1753-1895 tests/…/test_credentials.py• L1984-2089

Response and request flows

The test doubles feed different points in the client path. The following view shows how a test selects a boundary and how the planned result reaches the assertion.

flowchart LR
    T[Test scenario] --> B{Required boundary}
    B -->|Service result| S[AioStubber or StubbedSession]
    B -->|HTTP request or response| H[HTTP stubber]
    B -->|Network or service workflow| L[Local server or Moto]
    B -->|Credential source| CRED[Async client or provider mock]
    S --> C[Async client operation]
    H --> C
    L --> C
    CRED --> C
    C --> A[Test assertion]

Queued response flow

An operation-stubbed test declares the expected sequence before it calls the client. The client consumes one queued item for each matching operation, receives an async response or service error, and then exposes the result to the test.

The queue is ordered. A test that uses pagination, waiting, retries, or chained credential calls must provide enough responses for every client operation that the scenario can issue. Parameter checks and service-model validation make the queue a contract for both the request and the result.

References: aiobotocore/stub.py• L6-25 aiobotocore/stub.py• L78-108 tests/test_stubber.py• L22-37 tests/…/test_credentials.py• L342-369

HTTP interception flow

An HTTP-stubbed test attaches a response provider to the event boundary before the client sends a request. The provider records the request and removes the next planned response, which lets the test inspect headers or request data after the client finishes.

This flow is useful for behavior that is not visible in a modeled service result. User-agent features, raw bodies, status codes, and transport exceptions can be checked without starting a service implementation.

References: tests/…/__init__.py• L141-180 tests/…/__init__.py• L183-193 tests/…/test_useragent.py• L38-80

Local endpoint flow

An endpoint test gives the client a real URL and keeps the normal async HTTP path active. The endpoint can return a simple response, redirect to a success route, delay a stream, receive a service callback, or emulate AWS state through Moto.

The server context controls readiness and cleanup. Entry waits for a bound port and reports startup failures, including a server thread that exits before it publishes an endpoint. Exit signals the server and joins its thread, which prevents a failed or slow test from leaving a live server behind.

References: tests/mock_server.py• L29-81 tests/mock_server.py• L83-114 tests/test_mock_server.py• L15-52

Credential source flow

A credential-source test replaces the external source at the narrowest useful point. The resolver can receive mocked providers. A provider can receive a fake async client or subprocess. A service-backed provider can use an operation stubber while the rest of the session and credential conversion remain active.

The flow makes source selection, request parameters, cache use, refresh timing, and error conversion observable without relying on local AWS configuration or network access.

References: tests/…/test_credentials.py• L531-579 tests/…/test_credentials.py• L612-761 tests/…/test_credentials.py• L815-841 tests/…/test_credentials.py• L1777-1851

Test double selection

The following choices keep each test close to the behavior it needs to prove.

Test needPreferred supportResult under test
Check a client operation and its modeled resultAioStubber or StubbedSessionService response or ClientError without network I/O
Check request headers, raw bodies, status codes, or send errorsClientHTTPStubber or SessionHTTPStubberThe event and HTTP boundary
Check response reads, iteration, content length, or stream errorsIn-memory async response bodiesThe shared response-body contract across HTTP backends
Check credential source selection or conversionMock providers, async client doubles, or StubbedSessionCredential-chain behavior and returned credential fields
Check credential cache, expiry, or service errorsFixed clock, in-memory cache, and operation stubberDeterministic refresh and error behavior
Check process credential fallbackMocked async subprocess and patched sync subprocessAsync process path and worker-thread fallback
Check transport session setup, request timeouts, redirects, or close behaviorBackend-specific transport spies or AIOServerThe async HTTP session contract
Check timeout, streaming, redirect, callback, or endpoint behaviorAIOServerA controlled real network exchange
Check a multi-step service workflowmoto_server and service fixturesLocal service state and client integration

This separation also supports backend coverage. Tests that depend on an HTTP session are parametrized for the enabled aiohttp and HTTPX paths, while aiohttp cases are not run under Trio. The same scenario can therefore check both supported async transport combinations without changing its service setup.

References: tests/conftest.py• L190-217 tests/conftest.py• L718-785 tests/mock_server.py• L21-58 tests/test_httpsession.py• L64-241 tests/…/test_credentials.py• L1753-1851

Change checklist

When these files or sections are changed, remember to consider these:

  • When AioStubber or StubbedSession changes its queued response shape, check the async response adapter, cached-client behavior, activation path, and pending-response checks.
  • When operation response or error validation changes, check the service model fields used by credential fetchers and the expected-parameter contract.
  • When HTTP stubber event registration changes, check both client-scoped and session-scoped interception and the cleanup path.
  • When AIOServer routes or readiness behavior changes, check timeout, redirect, startup-failure, and callback tests that depend on its endpoint URL.
  • When stateful service workflow or waiter scenarios change, check resource cleanup and the timing between resource creation and waiter polling.
  • When shared client fixtures change endpoint, credential, or backend selection, check the distinction between mocked local tests and localonly tests.
  • When HTTP backend parametrization changes, check that aiohttp is not paired with Trio and that HTTPX remains optional where intended.
  • When response-body behavior changes, check read, iteration, content-length, close, and async context behavior for both aiohttp and HTTPX sources.
  • When backend stream errors change, check that timeout and connection failures still map to the shared client errors.
  • When S3 streaming tests change, check both backend-specific close paths and the client-facing stream context.
  • When credential fixtures change fixed time, cache keys, token loaders, or temporary config, check cache-hit, expiry, required-config, and refresh-failure scenarios together.
  • When credential process execution changes, check both the async subprocess path and the synchronous fallback for unsupported event loops.
  • When request timeout or HTTP session lifecycle behavior changes, check both aiohttp and HTTPX transport contracts, post-context client calls, redirect handling, and async context exit behavior.
  • When botocore or aiohttp versions change, update the compatibility guards only after confirming whether the change adds supported versions or replaces an incompatible base version.

Important failure modes

TriggerConsequenceGuard
A queued response does not match the called operation or its expected parametersThe test fails at the client boundary instead of validating the intended scenarioKeep operation order and expected parameters aligned with every client call
A strict HTTP stubber has no queued responseThe request raises HTTPStubberExceptionQueue one response for each intercepted request, including retries and helper calls
A modeled error field does not match the service error shapeStub setup fails before the client scenario runsUse fields allowed by the service model for the selected error code
A response body ends before its declared content lengthThe client raises an incomplete-read error during the terminal readSet the modeled length to the wire body or assert the failure deliberately
A backend stream raises a timeout or connection error without common mappingTests see backend-specific errors and client behavior differs by HTTP backendExercise both response-body paths and preserve the shared timeout and streaming error types
AIOServer cannot bind, exits before publishing its endpoint, or fails during startupTest setup fails rather than sending requests to an unknown targetEnter it through its async context and use the published endpoint_url
A delayed response outlasts the configured read timeoutThe client raises its async read-timeout errorUse the delayed route only with an intentional timeout assertion
A local resource is not removed after a service workflowLater tests can see stale state or resource namesUse the resource fixtures and let their teardown run
A waiter polls before a concurrently created resource is ready, or its attempt budget is too smallThe workflow fails with a waiter error even though the service becomes ready laterSet the polling delay and maximum attempts for the expected service transition
A client operation runs after its async client context has exitedThe HTTP client session is unavailable and the call failsKeep client operations inside the client context
A request-specific timeout is not copied into the backend requestThe transport uses the wrong read timeout and the test can miss request-level behaviorCheck request-created context updates against both supported backend paths
SSL setup performs blocking file work on the event loopThe loop can stall during first-session setupKeep file-backed SSL setup in the backend's worker-thread path and test cached reuse
The transport follows an S3 redirect before botocore can re-sign itThe redirected request can lose its authorization header and failReturn the redirect response to botocore and assert that the transport does not follow it
An HTTPX-backed client is used after its context exitsThe operation raises an HTTP client error instead of silently reconnectingKeep operations inside the client context and verify the underlying session is closed
Session close is not safe when called more than once or during a user exceptionCleanup raises an assertion or hides the real test failureKeep close idempotent and preserve the original user exception
A cached credential entry is expired or a required profile field is absentThe provider makes an unexpected service call or raises a configuration errorSet cache and profile state explicitly and assert both cache-hit and reload paths
A credential refresh returns empty data or fails during cleanupCredential retrieval raises a client-facing retrieval errorUse the async refresher fixture to cover empty results and protected-refresh cleanup
A dependency change produces an unapproved source digest or parser setThe compatibility suite fails before dependent tests can give a false resultReview the private patch against the new dependency and record the supported version deliberately

Key files

FileWhy to read it
aiobotocore/stub.pyDefines the async service-result and service-error stubbing boundary.
tests/…/helpers.pyDefines cached stubbed sessions and session-level stub activation checks.
aiobotocore/awsrequest.pyShows the async response shape returned to client code.
aiobotocore/response.pyDefines the shared async response-body behavior across HTTP backends.
tests/…/__init__.pyDefines raw HTTP interception, request capture, response queues, and client/session scope.
tests/mock_server.pyDefines the local HTTP server and Moto service fixture patterns.
tests/conftest.pyDefines environment isolation, backend selection, client setup, resource lifecycle, and shared assertions.
tests/test_response.pyDemonstrates deterministic response-body checks for normal reads, streaming, content length, closure, and transport errors.
tests/test_basic_s3.pyDemonstrates client-level stream use and backend-specific response cleanup in service workflows.
tests/test_httpsession.pyDemonstrates backend-neutral transport session checks for timeouts, SSL setup, redirect handling, client lifetime, and cleanup.
tests/…/test_credentials.pyDemonstrates credential-source doubles, modeled role and SSO responses, cache and refresh control, and subprocess fallback.
tests/test_patches.pyDefines compatibility guards for the private dependency patches and protocol parser set.
tests/test_stubber.pyDemonstrates modeled success and error setup for an async client.
tests/test_mock_server.pyDemonstrates local server readiness, startup failure reporting, and cleanup.
tests/…/test_useragent.pyDemonstrates request capture and per-request HTTP stubbing.