Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"type": "feature",
"description": "Added instrument and instrument_async to record a test against a live service and play it back offline."
}
124 changes: 123 additions & 1 deletion packages/smithy-test/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,126 @@ generated protocol tests that treats `NaN == NaN`, and `xml_equal`, a semantic X
equality check. It also provides `verify_models` and `ConformanceError` for
generated conformance tests, `check_rules_case` for endpoint rule tests, and
`mock` with `HTTPMockController`, `HTTPMockExpectation`, `HTTPMockError` and
`HTTPMockMismatchError` for answering a sync client's requests without sending them.
`HTTPMockMismatchError` for answering a sync client's requests without sending them,
and `instrument` for recording a live-service test and playing it back offline.

## Recording and playing back live-service tests

`instrument` (`instrument_async` for async clients) lets one test run against the
live service once, then run offline from what the service answered. Write the test as
you would a live integration test. Record it to get honest server responses, and
every later run replays them as a functional test with the same assertions.

```py
from aws_sdk_s3.client import S3Client
from aws_sdk_s3.config import S3Config
from smithy_test import instrument


def test_list_buckets() -> None:
client = S3Client(S3Config.resolve(region="us-west-2"))

with client, instrument(client):
buckets = client.list_buckets().buckets or []

assert all(bucket.name for bucket in buckets)
```

An async client is instrumented the same way, with `await` and `async with`:

```py
async with client, await instrument_async(client):
...
```

### Where recordings go

Without a path, the recording is `recordings/<test function>/<client>.py` next to the
file of the function that calls `instrument`. The example above uses
`recordings/test_list_buckets/s3.py`. The client name is the class name without
`Async` and `Client`, in snake case, so a sync and an async client of the same service
share a recording.

Pass `path=`, as in `instrument(client, path=...)`, when `instrument` is called from a helper
instead of the test, which would name the recording after the helper, when a test
instruments two clients of the same service, or when the call has no source file.
Then the inference raises a `ValueError`.

### Modes

The mode comes from the `mode` keyword argument (`"record"` or `"playback"`), then from the
`SMITHY_PYTHON_TEST_MODE` environment variable, and defaults to `playback`.

- `playback` answers each operation from the recording, so the test runs offline.
The call fails if the recording is missing, and on exit if a recorded call was
never made.
- `record` sends requests to the live service with the client's own credentials and
writes the responses to the recording path when the block exits. A block that
raises writes nothing.

```sh
SMITHY_PYTHON_TEST_MODE=record pytest tests/functional/test_buckets.py
```

Use the `with` form. A recording is written when the block exits, so a call without
`with` plays back but doesn't record.

### What a recording is

A recording is a Python module that calls `controller.expect_operation(...)` once per
operation, with the responses in the order the client received them:

```py
def install(controller: HTTPMockController) -> None:
(
controller.expect_operation("ListBuckets")
.times(1)
.respond_with(
status_code=200,
headers={"Content-Type": "application/xml"},
body=cleandoc(
r"""
<ListAllMyBucketsResult>
...
</ListAllMyBucketsResult>
"""
),
)
)
```

- Responses are matched by operation name and never by request, so control flow in the
test can't hand an operation the response of another one. Requests aren't recorded.
- The same operation called more than once gets its responses in order. A call beyond
the recorded ones raises, naming the operation.
- One recording serves a sync and an async client alike. If a test runs for both,
point both at the same path and record either one.
- XML and JSON bodies are written indented. Other bodies, including data streams, are
written as bytes literals. A data stream is read in full and handed back to the
client as a new stream, so the live test sees what the service sent.
- Event streams can't be recorded. Instrumenting a call that returns one raises
`HTTPRecordError`.

You can edit a recording by hand, and
`controller.expect_operation(...)` works in a test with no recording at all.

### What is scrubbed

Recordings are meant to be committed, so responses are scrubbed as they're recorded.
Scrubbing is best effort. Review a recording before you commit it.

- Replaced with stand-ins of the same length: request and host IDs, account IDs (with
approved fictitious example IDs), access key IDs, UUIDs, IP addresses, email
addresses, and the role and session names of assumed-role ARNs.
- Refused: the credentials' secret access key or session token appearing anywhere in
a response, in plain, URL-encoded, JSON-escaped, XML-escaped or base64 form. The
recording isn't written, and the error is kept even if the test catches it.
- Refused: the access key ID or the account ID in a form that can't be replaced.
- Left alone: payloads covered by a checksum or digest header, which can't change
without failing validation.

The recorder reads the access key ID, secret, session token and account ID, when the
credentials carry one, from the client's own credentials identity. Pass
`redact=["<value>"]` for anything else that must not appear, such as an account ID the
credentials don't carry. Pass `scrubbers=[...]`, functions from text to text, to scrub
more.
6 changes: 6 additions & 0 deletions packages/smithy-test/src/smithy_test/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
from .http_mock import HTTPMockExpectation as HTTPMockExpectation
from .http_mock import HTTPMockMismatchError as HTTPMockMismatchError
from .http_mock import mock as mock
from .http_record import HTTPRecorder as HTTPRecorder
from .http_record import HTTPRecordError as HTTPRecordError
from .http_record import instrument as instrument

__version__ = "0.5.0"
__all__ = (
Expand All @@ -18,8 +21,11 @@
"HTTPMockError",
"HTTPMockExpectation",
"HTTPMockMismatchError",
"HTTPRecordError",
"HTTPRecorder",
"check_rules_case",
"deep_equal",
"instrument",
"mock",
"verify_models",
"xml_equal",
Expand Down
7 changes: 7 additions & 0 deletions packages/smithy-test/src/smithy_test/_private/errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
from smithy_core.exceptions import SmithyError


class HTTPRecordError(SmithyError):
"""Raised when a call can't be recorded."""
52 changes: 41 additions & 11 deletions packages/smithy-test/src/smithy_test/_private/http_mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import inspect
import re
from collections.abc import Callable, Iterable, Iterator, Mapping
from contextvars import ContextVar
from copy import deepcopy
from typing import Any, Protocol, cast
from urllib.parse import parse_qsl
Expand All @@ -14,6 +15,23 @@

MOCK_CREDENTIAL = "HTTP_MOCK"

CURRENT_OPERATION: ContextVar[str | None] = ContextVar(
"smithy_test_current_operation", default=None
)
"""The operation whose call is in flight, set by the invoke wrapper of a mocked or
recording client so that transports can tell operations apart."""


_MISSING = object()

_CLIENT_ATTRIBUTES = ("_setup_done", "_config", "_transport")
_CLIENT_HOOKS = {
"_post_setup": ("config",),
"_build_call": ("input", "operation", "config", "retry_strategy"),
"_invoke": ("input", "operation", "default_plugins", "plugins"),
}
_CREDENTIAL_FIELDS = ("aws_access_key_id", "aws_secret_access_key", "aws_session_token")


class MockTransport(Protocol):
"""A mock transport, holding the config transports it replaced."""
Expand All @@ -27,13 +45,17 @@ class NoResponse(SmithyError):

def take_over(
client: ClientBase[Any],
transport: MockTransport,
transport: Any,
wrap_invoke: Callable[[Callable[..., Any]], Callable[..., Any]],
install: Callable[[Any, Any], None] | None = None,
) -> None:
"""Route the client's calls to the transport and replace its credentials.
"""Route the client's calls to the transport.

:param install: Puts the transport into a config. Defaults to replacing the
config's transport and credentials, as a mock does.
:raises TypeError: If the client's internals aren't the ones this relies on.
"""
_scrub = install or _scrub_config
_check_client(client)
# Typed as Any so instance attributes can shadow the client's methods.
target: Any = client
Expand Down Expand Up @@ -86,15 +108,23 @@ def mismatches(
return failures, cause


_MISSING = object()
def track_operation(invoke: Callable[..., Any]) -> Callable[..., Any]:
"""Wrap ``_invoke`` so transports can tell which operation is being called."""

_CLIENT_ATTRIBUTES = ("_setup_done", "_config", "_transport")
_CLIENT_HOOKS = {
"_post_setup": ("config",),
"_build_call": ("input", "operation", "config", "retry_strategy"),
"_invoke": ("input", "operation", "default_plugins", "plugins"),
}
_CREDENTIAL_FIELDS = ("aws_access_key_id", "aws_secret_access_key", "aws_session_token")
def _invoke(*args: Any, **kwargs: Any) -> Any:
token = CURRENT_OPERATION.set(operation_name(invoke, args, kwargs))
try:
return invoke(*args, **kwargs)
finally:
CURRENT_OPERATION.reset(token)

return _invoke


def operation_name(invoke: Callable[..., Any], args: Any, kwargs: Any) -> str:
"""Find the name of the operation among the arguments of an ``_invoke`` call."""
operation = inspect.signature(invoke).bind(*args, **kwargs).arguments["operation"]
return operation.schema.id.name


def _check_client(client: ClientBase[Any]) -> None:
Expand Down Expand Up @@ -127,7 +157,7 @@ def _check_config(config: Any) -> None:
)


def _scrub(config: Any, transport: MockTransport) -> None:
def _scrub_config(config: Any, transport: MockTransport) -> None:
_check_config(config)
source_of = getattr(config, "source_of", None)
# A default transport belongs to the config, so the mock closes it in its place.
Expand Down
Loading
Loading