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: AssertionError

An API method was called without a prepared mock.

class contree_client.testing.Call(operation, args, kwargs)[source]

Bases: object

One recorded API method invocation.

Parameters:
operation: str
args: tuple[Any, ...]
kwargs: dict[str, Any]
class contree_client.testing.Outcome(result: 'Any', error: 'BaseException | None')[source]

Bases: object

Parameters:
result: Any
error: BaseException | None
contree_client.testing.unmocked(spec)[source]
Parameters:

spec (RequestSpec)

Return type:

NotMockedError

class contree_client.testing.MockMixin[source]

Bases: object

Mock bookkeeping shared by the sync and async test clients.

mocks: dict[str, deque[Outcome]]
calls: list[Call]
mock(operation, result=None, *, error=None)[source]

Prepare the next outcome of operation.

result is returned as-is (an iterable of items for iterator operations); error is raised instead (after the items for iterator operations).

Parameters:
Return type:

None

calls_for(operation)[source]

Recorded calls of a single operation, in order.

Parameters:

operation (str)

Return type:

list[Call]

api_method(operation)[source]
Parameters:

operation (str)

Return type:

Any

take(operation)[source]
Parameters:

operation (str)

Return type:

Outcome

record(operation, args, kwargs)[source]
Parameters:
Return type:

Outcome

build_wrapper(operation, method)[source]
Parameters:
  • operation (str)

  • method (Any)

Return type:

Any

mocked_response(spec)[source]

Resolve internal helper requests through operation mocks.

Parameters:

spec (RequestSpec)

Return type:

ResponseData

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, ContreeSyncClient

Synchronous test double; see the module docstring.

Parameters:
log: Logger = <Logger contree_client.testing (ERROR)>
request(spec)[source]

Execute the request and return the buffered response.

Parameters:

spec (RequestSpec)

Return type:

ResponseData

stream(spec, auto_decompress=True)[source]

Execute the request and yield response body chunks.

With auto_decompress=False the body is yielded exactly as served (e.g. the gzip the server always applies is kept).

Parameters:
Return type:

Iterator[bytes]

close()[source]

Release the underlying transport resources.

Return type:

None

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, ContreeAsyncClient

Asynchronous test double; see the module docstring.

Parameters:
log: Logger = <Logger contree_client.testing (ERROR)>
async request(spec)[source]

Execute the request and return the buffered response.

Parameters:

spec (RequestSpec)

Return type:

ResponseData

stream(spec, auto_decompress=True)[source]

Execute the request and yield response body chunks.

With auto_decompress=False the body is yielded exactly as served (e.g. the gzip the server always applies is kept).

Parameters:
Return type:

AsyncGenerator[bytes, None]

async close()[source]

Release the underlying transport resources.

Return type:

None