Testing your code¶
contree_client.testing ships in-memory test doubles for user
test suites. ContreeClient and ContreeAsyncClient implement the
same interface as every real backend but perform no I/O: each API
method is mocked by name, results are returned exactly as given, and
every call is recorded for assertions. mock() itself is a plain
synchronous call on both flavours.
Because all adapters are interchangeable (see
Transport adapters), any code annotated against the
base classes from contree_client.types accepts the test double
unchanged.
Mocking operations¶
mock(operation, result) prepares the next return value of an API
method; calling anything unmocked raises NotMockedError:
from contree_client.models import WhoAmIResponse
from contree_client.testing import ContreeClient
client = ContreeClient()
client.mock(
"whoami",
WhoAmIResponse(
token_uuid="a1b2c3d4-e5f6-7890-abcd-ef1234567890",
token_expiration=None,
permissions={"spawn": True},
operations_stat={},
),
)
assert client.whoami().permissions["spawn"] is True
from contree_client.models import WhoAmIResponse
from contree_client.testing import ContreeAsyncClient
client = ContreeAsyncClient()
client.mock(
"whoami",
WhoAmIResponse(
token_uuid="a1b2c3d4-e5f6-7890-abcd-ef1234567890",
token_expiration=None,
permissions={"spawn": True},
operations_stat={},
),
)
assert (await client.whoami()).permissions["spawn"] is True
Sequential results¶
Repeated mock() calls for the same operation queue results; the last
one is sticky. This models polling loops naturally:
client.mock("get_operation_status", running) # first call
client.mock("get_operation_status", success) # every call after that
assert not client.get_operation_status(UUID).status.is_terminal()
assert client.get_operation_status(UUID).status.is_terminal()
client.mock("get_operation_status", running) # first call
client.mock("get_operation_status", success) # every call after that
assert not (await client.get_operation_status(UUID)).status.is_terminal()
assert (await client.get_operation_status(UUID)).status.is_terminal()
Errors¶
error= raises instead of returning — API errors are ordinary
exception instances:
from contree_client.exceptions import NotFoundError
client.mock("get_operation_status", error=NotFoundError(404, "no such"))
from contree_client.exceptions import NotFoundError
client.mock("get_operation_status", error=NotFoundError(404, "no such"))
Streaming operations¶
Iterator-returning operations (iter_operation_events,
inspect_image_archive, …) take an iterable of items and yield them
one by one; a queued error is raised after the items, which models
a stream broken mid-flight:
client.mock(
"iter_operation_events",
[stdout_event, exit_event],
error=ConnectionError("broken"),
)
client.mock(
"iter_operation_events",
[stdout_event, exit_event],
error=ConnectionError("broken"),
)
Asserting on calls¶
Every invocation is recorded as a Call with positional and keyword
arguments:
client.spawn_instance("uname -a", "tag:ubuntu:latest", shell=True)
(call,) = client.calls_for("spawn_instance")
assert call.args == ("uname -a", "tag:ubuntu:latest")
assert call.kwargs == {"shell": True}
await client.spawn_instance("uname -a", "tag:ubuntu:latest", shell=True)
(call,) = client.calls_for("spawn_instance")
assert call.args == ("uname -a", "tag:ubuntu:latest")
assert call.kwargs == {"shell": True}
Asserting on construction¶
The double accepts the same constructor kwargs as every real backend
(base_url, project, timeout, retry, identity, …) and
records them in constructed_with — convenient for testing code that
builds clients itself (factories, from_profile wiring):
client = build_my_client(testing.ContreeClient) # code under test
assert client.constructed_with["project"] == "my-project"
assert client.constructed_with["identity"] == "my-cli/1.2.3"
client = build_my_client(testing.ContreeAsyncClient) # code under test
assert client.constructed_with["project"] == "my-project"
assert client.constructed_with["identity"] == "my-cli/1.2.3"
Reference¶
In-memory test doubles for user test suites.
ContreeClient and ContreeAsyncClient here implement the same
interface as every real backend, but perform no I/O: each API method
must be mocked first with MockMixin.mock(), and calling anything
unmocked raises NotMockedError. Results are returned exactly
as given, calls are recorded for assertions:
from contree_client.models import WhoAmIResponse
from contree_client.testing import ContreeClient
client = ContreeClient()
client.mock("whoami", WhoAmIResponse(permissions={"spawn": True}))
assert client.whoami().permissions["spawn"] is True
assert client.calls_for("whoami")
Repeated mock() calls for the same operation queue sequential
results; the last one is sticky (convenient for polling loops):
client.mock("get_operation_status", running)
client.mock("get_operation_status", success)
Iterator-returning operations (iter_operation_events,
inspect_image_archive, …) take an iterable of items and yield
them one by one; a queued error is raised after the items, which
models a stream broken mid-flight.
- exception contree_client.testing.NotMockedError[source]¶
Bases:
AssertionErrorAn API method was called without a prepared mock.
- class contree_client.testing.Call(operation, args, kwargs)[source]¶
Bases:
objectOne recorded API method invocation.
- class contree_client.testing.Outcome(result: 'Any', error: 'BaseException | None')[source]¶
Bases:
object- Parameters:
result (Any)
error (BaseException | None)
- error: BaseException | None¶
- contree_client.testing.unmocked(spec)[source]¶
- Parameters:
spec (RequestSpec)
- Return type:
- class contree_client.testing.MockMixin[source]¶
Bases:
objectMock bookkeeping shared by the sync and async test clients.
- mock(operation, result=None, *, error=None)[source]¶
Prepare the next outcome of operation.
resultis returned as-is (an iterable of items for iterator operations);erroris raised instead (after the items for iterator operations).- Parameters:
operation (str)
result (Any)
error (BaseException | None)
- Return type:
None
- mocked_response(spec)[source]¶
Resolve internal helper requests through operation mocks.
- Parameters:
spec (RequestSpec)
- Return type:
- class contree_client.testing.ContreeClient(token='test-token', *, base_url='https://api.tokenfactory.nebius.com/sandboxes', project=None, timeout=None, retry=None, identity=None, ssl_context=None)[source]¶
Bases:
MockMixin,ContreeSyncClientSynchronous test double; see the module docstring.
- Parameters:
token (str)
base_url (str)
project (str | None)
timeout (float | None)
retry (RetryPolicy | None)
identity (str | None)
ssl_context (ssl.SSLContext | None)
- request(spec)[source]¶
Execute the request and return the buffered response.
- Parameters:
spec (RequestSpec)
- Return type:
- stream(spec, auto_decompress=True)[source]¶
Execute the request and yield response body chunks.
With
auto_decompress=Falsethe body is yielded exactly as served (e.g. the gzip the server always applies is kept).- Parameters:
spec (RequestSpec)
auto_decompress (bool)
- Return type:
- class contree_client.testing.ContreeAsyncClient(token='test-token', *, base_url='https://api.tokenfactory.nebius.com/sandboxes', project=None, timeout=None, retry=None, identity=None, ssl_context=None)[source]¶
Bases:
MockMixin,ContreeAsyncClientAsynchronous test double; see the module docstring.
- Parameters:
token (str)
base_url (str)
project (str | None)
timeout (float | None)
retry (RetryPolicy | None)
identity (str | None)
ssl_context (ssl.SSLContext | None)
- async request(spec)[source]¶
Execute the request and return the buffered response.
- Parameters:
spec (RequestSpec)
- Return type:
- stream(spec, auto_decompress=True)[source]¶
Execute the request and yield response body chunks.
With
auto_decompress=Falsethe body is yielded exactly as served (e.g. the gzip the server always applies is kept).- Parameters:
spec (RequestSpec)
auto_decompress (bool)
- Return type:
AsyncGenerator[bytes, None]