Ir para o conteúdo

tempest_fastapi_sdk.testing.fakes

Dublês dos terceiros com que um serviço conversa.

« Web, UI e utilitários


FakePixProvider

FakePixProvider(*, provider_name: str = 'fake')

Bases: _Steerable

A PixRefundProvider that keeps charges and refunds in dicts.

Refunds follow the contract the real adapters keep: idempotent on refund_reference per charge, partial refunds summed, a refund above what is left refused with :class:~tempest_fastapi_sdk.exceptions.PixRefundExceedsBalanceException. Only a PAID charge (or a REFUNDED one, for the replay and the balance error) can be refunded; anything else raises ValueError. :meth:fail_after_next_refund reproduces the case idempotency exists for: the refund lands and the answer is lost.

Example:

>>> provider = FakePixProvider()
>>> charge = await provider.create_pix_charge(
...     PixChargeRequest(amount_cents=1990, reference="order-1"),
... )
>>> event = provider.advance(charge.provider_charge_id, PaymentStatusEnum.PAID)
>>> event.type is PixEventTypeEnum.CHARGE_PAID
True

Attributes:

Name Type Description
provider_name str

Copied into :attr:PixCharge.provider.

calls list[str]

Contract methods that ran, in order.

Start with no charges.

Parameters:

Name Type Description Default
provider_name str

The name to stamp on every charge, when a test asserts on more than one provider at a time.

'fake'

charges property

charges: Mapping[str, PixCharge]

Every charge this provider issued, keyed by provider-side id.

Returns:

Type Description
Mapping[str, PixCharge]

Mapping[str, PixCharge]: A read-only view, so a test reads state

Mapping[str, PixCharge]

without being able to corrupt it by accident.

refunds property

refunds: Mapping[str, tuple[PixRefund, ...]]

Every refund applied, keyed by the charge's provider-side id.

Returns:

Type Description
Mapping[str, tuple[PixRefund, ...]]

Mapping[str, tuple[PixRefund, ...]]: A read-only view, oldest

Mapping[str, tuple[PixRefund, ...]]

refund first. A replayed reference does not add an entry, which

Mapping[str, tuple[PixRefund, ...]]

is what a test asserts to prove a retry did not refund twice.

fail_after_next_refund

fail_after_next_refund(error: BaseException) -> None

Make the next refund apply, then raise error.

Parameters:

Name Type Description Default
error BaseException

What the caller sees instead of the answer — say TimeoutError.

required

Unlike :meth:fail_next, which fails before anything happens, this is the lost answer: the money went back, the caller does not know. A retry with the same refund_reference must answer that refund and not apply a second one. Replays do not consume it.

create_pix_charge async

create_pix_charge(request: PixChargeRequest) -> PixCharge

Issue a pending charge, or answer the one the reference already has.

Idempotent on :attr:PixChargeRequest.reference, as the contract promises and the real adapters behave: a second create with the same reference returns the charge the first one issued, in whatever state it is now, and issues nothing.

Parameters:

Name Type Description Default
request PixChargeRequest

What the service asked to charge.

required

Returns:

Name Type Description
PixCharge PixCharge

The charge, in canonical shape.

Raises:

Type Description
BaseException

Whatever :meth:fail_next queued.

get_pix_charge async

get_pix_charge(charge_id: str) -> PixCharge

Read a charge back.

Parameters:

Name Type Description Default
charge_id str

The provider-side id.

required

Returns:

Name Type Description
PixCharge PixCharge

The stored charge.

Raises:

Type Description
KeyError

When no charge carries that id.

BaseException

Whatever :meth:fail_next queued.

cancel_pix_charge async

cancel_pix_charge(charge_id: str) -> PixCharge

Withdraw a charge.

Parameters:

Name Type Description Default
charge_id str

The provider-side id.

required

Returns:

Name Type Description
PixCharge PixCharge

The charge in its cancelled shape.

Raises:

Type Description
KeyError

When no charge carries that id.

BaseException

Whatever :meth:fail_next queued.

refund_pix_charge async

refund_pix_charge(
    charge_id: str, amount_cents: int | None = None, *, refund_reference: str
) -> PixRefund

Refund a paid charge, idempotently on refund_reference.

Parameters:

Name Type Description Default
charge_id str

The provider-side id.

required
amount_cents int | None

How much to refund; None refunds what is left.

None
refund_reference str

The refund's idempotency key, scoped to the charge.

required

Returns:

Name Type Description
PixRefund PixRefund

The refund, COMPLETED — the existing one when the

PixRefund

reference was used before, with refunded_cents current.

Raises:

Type Description
KeyError

When no charge carries that id.

ValueError

When amount_cents is not positive, or the charge was never paid.

PixRefundReferenceConflictException

When the reference names a refund of another amount.

PixRefundExceedsBalanceException

When less is left than asked.

BaseException

Whatever :meth:fail_next queued (nothing is applied), or :meth:fail_after_next_refund queued (the refund is applied first).

get_refunded_cents async

get_refunded_cents(charge_id: str) -> int

Sum the refunds applied to a charge.

Parameters:

Name Type Description Default
charge_id str

The provider-side id.

required

Returns:

Name Type Description
int int

Cents refunded; 0 with no refund.

Raises:

Type Description
KeyError

When no charge carries that id.

BaseException

Whatever :meth:fail_next queued.

parse_webhook

parse_webhook(event: object) -> PixPaymentEvent

Turn this fake's delivery shape into a canonical event.

Parameters:

Name Type Description Default
event object

A mapping with charge_id and, optionally, status (a :class:PaymentStatusEnum or its value). Defaults to a paid event, because that is the delivery a checkout test is usually after.

required

Returns:

Name Type Description
PixPaymentEvent PixPaymentEvent

The canonical event.

Raises:

Type Description
TypeError

When event is not a mapping.

KeyError

When no charge carries that id.

BaseException

Whatever :meth:fail_next queued.

advance

advance(charge_id: str, status: PaymentStatusEnum) -> PixPaymentEvent

Move a charge to status and return the event that reports it.

Parameters:

Name Type Description Default
charge_id str

The provider-side id.

required
status PaymentStatusEnum

The state to move to.

required

Returns:

Name Type Description
PixPaymentEvent PixPaymentEvent

The event a real provider's webhook would have

PixPaymentEvent

delivered for that transition.

Raises:

Type Description
KeyError

When no charge carries that id.

This is the steering the real provider does not give you: reaching PAID against a sandbox means somebody scanning a QR code, and reaching CHARGED_BACK means somebody disputing a payment. Here it is one call, and it does not consume a queued :meth:fail_next — steering the fake is not a call the service made.

FakeCardProvider

FakeCardProvider(*, provider_name: str = 'fake')

Bases: _Steerable

A CardProvider that keeps charges in a dict.

A charge is approved unless :meth:decline_next queued a decline, which comes back as a :attr:PaymentStatusEnum.FAILED charge — returned, not raised, as the real adapter returns the provider's HTTP 402. A capture=False request comes back :attr:PaymentStatusEnum.AUTHORIZED.

The fake refuses the transitions a real provider refuses, with ValueError: capturing or cancelling anything but an authorization, refunding anything but a paid charge, refunding more than is left. The real adapter raises httpx.HTTPStatusError there instead; what this fake guarantees is that the branch is reachable, not the exception type.

Example:

>>> provider = FakeCardProvider()
>>> charge = await provider.create_card_charge(
...     CardChargeRequest(
...         amount_cents=10000,
...         reference="order-1",
...         card_token="tok",
...         payment_method_id="visa",
...     ),
... )
>>> refunded = await provider.refund_card_charge(
...     charge.provider_charge_id, amount_cents=3000
... )
>>> (refunded.status, refunded.refunded_cents)
(<PaymentStatusEnum.PAID: 'paid'>, 3000)

Attributes:

Name Type Description
provider_name str

Copied into :attr:CardCharge.provider.

calls list[str]

Contract methods that ran, in order.

Start with no charges and no declines queued.

Parameters:

Name Type Description Default
provider_name str

The name to stamp on every charge.

'fake'

charges property

charges: Mapping[str, CardCharge]

Every charge this provider issued, keyed by provider-side id.

Returns:

Type Description
Mapping[str, CardCharge]

Mapping[str, CardCharge]: A read-only view.

decline_next

decline_next(status_detail: str = 'rejected_by_issuer') -> None

Make the next :meth:create_card_charge come back declined.

Parameters:

Name Type Description Default
status_detail str

The reason, copied into :attr:CardCharge.status_detail. The default is the one the Mercado Pago sandbox answered for a declined test card.

'rejected_by_issuer'

Queue several to decline several creates in a row. Unlike :meth:fail_next, the create still answers: a decline is a result.

create_card_charge async

create_card_charge(request: CardChargeRequest) -> CardCharge

Approve, authorize or decline a charge.

Parameters:

Name Type Description Default
request CardChargeRequest

What the service asked to charge.

required

Returns:

Name Type Description
CardCharge CardCharge

PAID, AUTHORIZED when capture=False, or

CardCharge

FAILED when :meth:decline_next queued a decline.

Raises:

Type Description
BaseException

Whatever :meth:fail_next queued.

get_card_charge async

get_card_charge(charge_id: str) -> CardCharge

Read a charge back.

Parameters:

Name Type Description Default
charge_id str

The provider-side id.

required

Returns:

Name Type Description
CardCharge CardCharge

The stored charge.

Raises:

Type Description
KeyError

When no charge carries that id.

BaseException

Whatever :meth:fail_next queued.

capture_card_charge async

capture_card_charge(charge_id: str) -> CardCharge

Capture an authorization.

Parameters:

Name Type Description Default
charge_id str

The provider-side id.

required

Returns:

Name Type Description
CardCharge CardCharge

The charge, PAID.

Raises:

Type Description
KeyError

When no charge carries that id.

ValueError

When the charge is not AUTHORIZED.

BaseException

Whatever :meth:fail_next queued.

cancel_card_charge async

cancel_card_charge(charge_id: str) -> CardCharge

Release an authorization.

Parameters:

Name Type Description Default
charge_id str

The provider-side id.

required

Returns:

Name Type Description
CardCharge CardCharge

The charge, CANCELLED.

Raises:

Type Description
KeyError

When no charge carries that id.

ValueError

When the charge is not AUTHORIZED.

BaseException

Whatever :meth:fail_next queued.

refund_card_charge async

refund_card_charge(charge_id: str, amount_cents: int | None = None) -> CardCharge

Refund a paid charge in full or in part.

Parameters:

Name Type Description Default
charge_id str

The provider-side id.

required
amount_cents int | None

How much to refund; None refunds what is left.

None

Returns:

Name Type Description
CardCharge CardCharge

PAID with status_detail partially_refunded

CardCharge

while something is left, REFUNDED once nothing is — the

CardCharge

states the Mercado Pago sandbox reported.

Raises:

Type Description
KeyError

When no charge carries that id.

ValueError

When the charge is not PAID, or the amount is not positive or exceeds what is left.

BaseException

Whatever :meth:fail_next queued.

advance

advance(
    charge_id: str, status: PaymentStatusEnum, *, status_detail: str | None = None
) -> CardCharge

Move a charge to status, with no transition check.

Parameters:

Name Type Description Default
charge_id str

The provider-side id.

required
status PaymentStatusEnum

The state to move to — say :attr:PaymentStatusEnum.CHARGED_BACK, which no contract method reaches.

required
status_detail str | None

The reason to store.

None

Returns:

Name Type Description
CardCharge CardCharge

The updated charge.

Raises:

Type Description
KeyError

When no charge carries that id.

Steering, not a call the service made: it does not consume a queued :meth:fail_next.

FakeObjectStorageClient

FakeObjectStorageClient(*, default_bucket: str = DEFAULT_FAKE_BUCKET)

Bases: _Steerable

A :class:~tempest_fastapi_sdk.privacy.SubjectStorageClient in memory.

Same signatures and return shapes as the :class:~tempest_fastapi_sdk.storage.AsyncMinIOClient calls it stands in for: put_object answers an ETag, list_objects the keys, remove_objects the :class:~tempest_fastapi_sdk.storage.ObjectDeleteError of each key the store refused.

Example:

>>> client = FakeObjectStorageClient()
>>> storage = SubjectObjectStorage(client, prefix="users")
>>> await storage.put(42, "avatar.png", b"png")
'users/42/avatar.png'
>>> client.fail_delete("users/42/avatar.png")
>>> await storage.delete_all(42)
Traceback (most recent call last):
SubjectErasureError: 1 object(s) of subject '42' were not deleted: ...

Attributes:

Name Type Description
default_bucket str

The bucket an operation without bucket uses.

deleted list[str]

Keys actually deleted, in order.

calls list[str]

Methods that ran, in order.

Start with no objects.

Parameters:

Name Type Description Default
default_bucket str

The bucket used when a call passes none.

DEFAULT_FAKE_BUCKET

objects property

objects: Mapping[str, bytes]

Every object in the default bucket, by key.

Returns:

Type Description
Mapping[str, bytes]

Mapping[str, bytes]: A read-only view.

bucket_objects

bucket_objects(bucket: str) -> Mapping[str, bytes]

Every object in bucket, by key.

Parameters:

Name Type Description Default
bucket str

The bucket.

required

Returns:

Type Description
Mapping[str, bytes]

Mapping[str, bytes]: A read-only view, empty for an unknown

Mapping[str, bytes]

bucket.

fail_delete

fail_delete(*keys: str) -> None

Make the store refuse to delete keys.

Parameters:

Name Type Description Default
*keys str

Keys to refuse. remove_objects reports them as AccessDenied and keeps them; remove_object raises :class:PermissionError for them.

()

Steering, not a call the service made: it does not consume a queued :meth:fail_next.

put_object async

put_object(
    key: str,
    data: bytes | BinaryIO,
    *,
    bucket: str | None = None,
    content_type: str = "application/octet-stream",
    metadata: dict[str, str] | None = None,
    length: int | None = None,
) -> str

Store one object.

Parameters:

Name Type Description Default
key str

Object key.

required
data bytes | BinaryIO

The payload; a stream is read to the end.

required
bucket str | None

Target bucket.

None
content_type str

MIME type, reported back by :meth:stat_object.

'application/octet-stream'
metadata dict[str, str] | None

User metadata, reported back by :meth:stat_object.

None
length int | None

Accepted for signature parity; the fake reads the whole stream.

None

Returns:

Name Type Description
str str

An ETag — the MD5 of the payload, as S3 answers for a

str

single-part upload.

Raises:

Type Description
BaseException

Whatever :meth:fail_next queued.

presigned_get_url async

presigned_get_url(
    key: str,
    *,
    bucket: str | None = None,
    expires: timedelta = timedelta(hours=1),
    filename: str | None = None,
    media_type: str | None = None,
    as_attachment: bool | None = None,
) -> str

Build a fake download URL.

The overrides are echoed in the query as the S3 response-* parameters, so a test can assert what the real link would sign.

Parameters:

Name Type Description Default
key str

Object key.

required
bucket str | None

Source bucket.

None
expires timedelta

URL lifetime, echoed in the URL.

timedelta(hours=1)
filename str | None

Name presented to the client.

None
media_type str | None

Content-Type override.

None
as_attachment bool | None

Download or inline.

None

Returns:

Name Type Description
str str

https://fake-storage/<bucket>/<key>?expires=<seconds>,

str

plus the overrides.

Raises:

Type Description
BaseException

Whatever :meth:fail_next queued.

ValueError

When media_type is not a bare type/subtype.

presigned_post_policy async

presigned_post_policy(
    key: str,
    *,
    max_bytes: int,
    content_type: str | None = None,
    min_bytes: int = 0,
    bucket: str | None = None,
    expires: timedelta = timedelta(minutes=15),
) -> PresignedPost

Build a fake form upload.

Nothing listens on the URL, as with :meth:presigned_put_url; the fields echo the limits a real policy would sign.

Parameters:

Name Type Description Default
key str

Destination object key.

required
max_bytes int

Largest accepted file.

required
content_type str | None

The only Content-Type accepted.

None
min_bytes int

Smallest accepted file.

0
bucket str | None

Target bucket.

None
expires timedelta

Lifetime, echoed in the fields.

timedelta(minutes=15)

Returns:

Name Type Description
PresignedPost PresignedPost

https://fake-storage/<bucket> with key,

PresignedPost

Content-Type when given, and the limits as fields.

Raises:

Type Description
BaseException

Whatever :meth:fail_next queued.

ValueError

When the size range is empty or inverted.

presigned_put_url async

presigned_put_url(
    key: str, *, bucket: str | None = None, expires: timedelta = timedelta(minutes=15)
) -> str

Build a fake upload URL.

Nothing listens on it: a test that needs the object stored calls :meth:put_object with the key the URL names, standing in for the client's PUT.

Parameters:

Name Type Description Default
key str

Destination object key.

required
bucket str | None

Target bucket.

None
expires timedelta

URL lifetime, echoed in the URL.

timedelta(minutes=15)

Returns:

Name Type Description
str str

https://fake-storage/<bucket>/<key>?method=PUT&expires=<seconds>.

Raises:

Type Description
BaseException

Whatever :meth:fail_next queued.

stat_object async

stat_object(key: str, *, bucket: str | None = None) -> ObjectStat

Describe a stored object.

Parameters:

Name Type Description Default
key str

Object key.

required
bucket str | None

Source bucket.

None

Returns:

Name Type Description
ObjectStat ObjectStat

Size, MD5 ETag, the content type and metadata given

to ObjectStat

meth:put_object, and when it was stored. raw is

ObjectStat

None: there is no minio object behind the fake.

Raises:

Type Description
FileNotFoundError

When key is not stored.

BaseException

Whatever :meth:fail_next queued.

stream_object async

stream_object(
    key: str,
    *,
    bucket: str | None = None,
    chunk_size: int = FAKE_STREAM_CHUNK_SIZE,
    offset: int = 0,
    length: int | None = None,
) -> AsyncIterator[bytes]

Open a stored object, or one byte range of it, as a chunk stream.

The range is cut before streaming, the way a Range request makes the store send only that slice: a length past the end yields what exists. The slice is then cut in chunk_size pieces, so a test that asks for small chunks sees the same pagination the real clients produce — which is what :func:~tempest_fastapi_sdk.storage.object_download_response streams.

Parameters:

Name Type Description Default
key str

Object key.

required
bucket str | None

Source bucket.

None
chunk_size int

Bytes per chunk; the last one may be shorter.

FAKE_STREAM_CHUNK_SIZE
offset int

First byte to read.

0
length int | None

How many bytes to read from offset; None reads to the end.

None

Returns:

Type Description
AsyncIterator[bytes]

AsyncIterator[bytes]: Chunks of at most chunk_size bytes.

Raises:

Type Description
ValueError

When offset is negative, or length or chunk_size is not positive, as the real clients refuse them.

FileNotFoundError

When key is not stored.

BaseException

Whatever :meth:fail_next queued.

list_objects async

list_objects(
    prefix: str = "", *, bucket: str | None = None, recursive: bool = True
) -> list[str]

List the keys under prefix, sorted.

Parameters:

Name Type Description Default
prefix str

Prefix filter.

''
bucket str | None

Source bucket.

None
recursive bool

Accepted for signature parity; the fake always lists every key under the prefix.

True

Returns:

Type Description
list[str]

list[str]: The matching keys.

Raises:

Type Description
BaseException

Whatever :meth:fail_next queued.

remove_object async

remove_object(
    key: str, *, bucket: str | None = None, version_id: str | None = None
) -> None

Delete one object; a missing key is not an error, as on S3.

Parameters:

Name Type Description Default
key str

Object key.

required
bucket str | None

Target bucket.

None
version_id str | None

Accepted for signature parity.

None

Raises:

Type Description
PermissionError

When :meth:fail_delete marked key.

BaseException

Whatever :meth:fail_next queued.

remove_objects async

remove_objects(
    keys: Iterable[str], *, bucket: str | None = None
) -> list[ObjectDeleteError]

Delete many objects, reporting the refused ones.

Parameters:

Name Type Description Default
keys Iterable[str]

Object keys; duplicates collapse.

required
bucket str | None

Target bucket.

None

Returns:

Type Description
list[ObjectDeleteError]

list[ObjectDeleteError]: One AccessDenied entry per key

list[ObjectDeleteError]

meth:fail_delete marked; those keys stay stored.

Raises:

Type Description
BaseException

Whatever :meth:fail_next queued.

FakePayoutProvider

FakePayoutProvider(*, status: PayoutStatusEnum = CONFIRMED)

Bases: _Steerable

A PayoutProvider that sends nothing and remembers every transfer.

Steer the two failure branches a withdrawal has with :meth:fail_next: PayoutRejectedException (the money did not leave, the wallet gives the debit back) and any other exception, such as TimeoutError (the outcome is unknown, the debit is kept).

Example

payout = FakePayoutProvider() result = await payout.transfer_to_pix_key( ... PayoutRequest( ... amount_cents=5000, ... pix_key="driver@example.com", ... pix_key_type=PixKeyType.EMAIL, ... correlation_id="w-1", ... ), ... ) result.status is PayoutStatusEnum.CONFIRMED True

Attributes:

Name Type Description
provider_name str

Copied into :attr:PayoutResult.provider.

status PayoutStatusEnum

What every accepted transfer reports.

transfers list[PayoutRequest]

Accepted transfers, in order.

calls list[str]

Contract methods that ran, in order.

Start with no transfers.

Parameters:

Name Type Description Default
status PayoutStatusEnum

The status every accepted transfer gets.

CONFIRMED

transfer_to_pix_key async

transfer_to_pix_key(request: PayoutRequest) -> PayoutResult

Accept a transfer, unless a failure was queued.

Parameters:

Name Type Description Default
request PayoutRequest

The transfer.

required

Returns:

Name Type Description
PayoutResult PayoutResult

The accepted transfer, with :attr:status.

Raises:

Type Description
BaseException

Whatever :meth:fail_next queued. A failed call is not added to :attr:transfers.

FakeTextBackend

FakeTextBackend(*, default: str | None = None)

Bases: _Steerable

A TextBackend that answers from a queue, then from a template.

Example:

>>> backend = FakeTextBackend()
>>> backend.queue("Bom dia!")
>>> await backend.generate("Cumprimente o cliente")
'Bom dia!'

Attributes:

Name Type Description
prompts list[str]

Every prompt this backend was given, in order.

conversations list[list[dict[str, Any]]]

Every message list :meth:stream_chat received, copied, in order.

calls list[str]

Methods that ran, in order.

Start with an empty queue.

Parameters:

Name Type Description Default
default str | None

Reply to use once the queue is empty. When None, the reply echoes the prompt as "[fake] <prompt>" — deterministic, and it shows in an assertion which prompt produced it.

None

queue

queue(*replies: str) -> None

Queue replies, consumed one per call, in order.

Parameters:

Name Type Description Default
*replies str

The replies to hand out.

()

generate async

generate(prompt: str, *, config: GenerationConfig | None = None, **kwargs: Any) -> str

Answer a single prompt.

Parameters:

Name Type Description Default
prompt str

The prompt.

required
config GenerationConfig | None

Recorded, never applied — a fake has no sampler to configure.

None
**kwargs Any

Recorded and ignored, for signature parity with the real backends.

{}

Returns:

Name Type Description
str str

The next queued reply, or the default.

Raises:

Type Description
BaseException

Whatever :meth:fail_next queued.

chat async

chat(
    messages: list[dict[str, str]],
    *,
    config: GenerationConfig | None = None,
    **kwargs: Any,
) -> str

Answer a message list.

Parameters:

Name Type Description Default
messages list[dict[str, str]]

The conversation so far.

required
config GenerationConfig | None

Recorded, never applied.

None
**kwargs Any

Recorded and ignored.

{}

Returns:

Name Type Description
str str

The next queued reply, or the default derived from the last

str

message's content.

Raises:

Type Description
BaseException

Whatever :meth:fail_next queued.

stream

stream(
    prompt: str, *, config: GenerationConfig | None = None, **kwargs: Any
) -> AsyncIterator[str]

Stream a reply word by word.

Parameters:

Name Type Description Default
prompt str

The prompt.

required
config GenerationConfig | None

Recorded, never applied.

None
**kwargs Any

Recorded and ignored.

{}

Returns:

Type Description
AsyncIterator[str]

AsyncIterator[str]: The reply, one whitespace-separated chunk at

AsyncIterator[str]

a time, so a consumer's incremental rendering is exercised

AsyncIterator[str]

rather than handed the whole string at once.

stream_chat

stream_chat(
    messages: list[dict[str, Any]],
    *,
    config: GenerationConfig | None = None,
    **kwargs: Any,
) -> AsyncIterator[str]

Stream the reply to a message list word by word.

Records the conversation in :attr:conversations, so a test can assert the system turn reached the backend as its own turn.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

The conversation so far.

required
config GenerationConfig | None

Recorded, never applied.

None
**kwargs Any

Recorded and ignored.

{}

Returns:

Type Description
AsyncIterator[str]

AsyncIterator[str]: The reply, one whitespace-separated chunk at

AsyncIterator[str]

a time. The default reply derives from the last message.

FakeStructuredBackend

FakeStructuredBackend()

Bases: _Steerable

A structured-output generator that answers with instances you queue.

Same chat_structured and generate_structured signatures as :class:~tempest_fastapi_sdk.genai.ollama.OllamaGenerator, so it slots in wherever a route calls one of the two — typically through app.dependency_overrides — and it satisfies :class:~tempest_fastapi_sdk.genai.StructuredTextBackend.

There is no default reply: a schema has no neutral instance to invent, and a made-up one would let the route serialise data the test never chose. A call with nothing queued raises :class:LookupError; a queued instance of another class raises :class:TypeError. Both are raised after the call is recorded, so :attr:requests still shows what the route asked for. A failure queued with :meth:fail_next is raised before that: the call shows up in :attr:calls only, not in :attr:requests or :attr:prompts.

Example:

>>> backend = FakeStructuredBackend()
>>> backend.queue(Invoice(number="42", total_cents=1990))
>>> (await backend.chat_structured(messages, Invoice)).number
'42'

Attributes:

Name Type Description
requests list[StructuredRequest]

Every call, in order, with the arguments it carried.

prompts list[str]

The content of the last turn of each call — the document or question the route sent.

calls list[str]

Methods that ran, in order.

Start with an empty queue and nothing recorded.

queue

queue(*replies: BaseModel) -> None

Queue instances, consumed one per call, in order.

Parameters:

Name Type Description Default
*replies BaseModel

The validated instances to hand out. Each must be an instance of the schema the matching call asks for.

()

chat_structured async

chat_structured(
    messages: list[dict[str, Any]],
    schema: type[StructuredT],
    *,
    config: GenerationConfig | None = None,
    think: ThinkLevel | None = None,
    truncate: bool | None = None,
    **kwargs: Any,
) -> StructuredT

Answer a message list with the next queued instance.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

Chat turns, recorded.

required
schema type[StructuredT]

The schema the reply must be.

required
config GenerationConfig | None

Recorded, never applied.

None
think ThinkLevel | None

Recorded, never applied.

None
truncate bool | None

Recorded, never applied.

None
**kwargs Any

Recorded in :attr:StructuredRequest.options.

{}

Returns:

Name Type Description
StructuredT StructuredT

The next queued instance.

Raises:

Type Description
BaseException

Whatever :meth:fail_next queued.

LookupError

When nothing is queued.

TypeError

When the queued instance is not a schema.

generate_structured async

generate_structured(
    prompt: str,
    schema: type[StructuredT],
    *,
    system: str | None = None,
    config: GenerationConfig | None = None,
    think: ThinkLevel | None = None,
    truncate: bool | None = None,
    **kwargs: Any,
) -> StructuredT

Answer a prompt with the next queued instance.

Parameters:

Name Type Description Default
prompt str

The input text, recorded as a user turn.

required
schema type[StructuredT]

The schema the reply must be.

required
system str | None

Recorded as a system turn ahead of prompt.

None
config GenerationConfig | None

Recorded, never applied.

None
think ThinkLevel | None

Recorded, never applied.

None
truncate bool | None

Recorded, never applied.

None
**kwargs Any

Recorded in :attr:StructuredRequest.options.

{}

Returns:

Name Type Description
StructuredT StructuredT

The next queued instance.

Raises:

Type Description
BaseException

Whatever :meth:fail_next queued.

LookupError

When nothing is queued.

TypeError

When the queued instance is not a schema.

StructuredRequest dataclass

StructuredRequest(
    method: str,
    messages: list[dict[str, Any]],
    schema: type[BaseModel],
    config: GenerationConfig | None = None,
    think: ThinkLevel | None = None,
    truncate: bool | None = None,
    options: dict[str, Any] = dict(),
)

One call a :class:FakeStructuredBackend received.

Attributes:

Name Type Description
method str

"chat_structured" or "generate_structured".

messages list[dict[str, Any]]

The turns the real generator would post — for generate_structured, the optional system turn followed by the prompt as a user turn, as :class:~tempest_fastapi_sdk.genai.ollama.OllamaGenerator builds them. A copy: mutating the caller's list afterwards does not change the record.

schema type[BaseModel]

The schema the caller asked for.

config GenerationConfig | None

The config argument.

think ThinkLevel | None

The think argument.

truncate bool | None

The truncate argument.

options dict[str, Any]

Every other keyword argument.

FakeModerationBackend

FakeModerationBackend(*, flagged_score: float = 0.99)

Bases: _Steerable

A ModerationBackend that flags what you tell it to flag.

Example:

>>> moderator = FakeModerationBackend()
>>> moderator.flag("idiota", category="insult")
>>> (await moderator.check("seu idiota")).flagged
True

Attributes:

Name Type Description
checked list[str]

Every text this backend saw, in order.

calls list[str]

Methods that ran, in order.

Start flagging nothing.

Parameters:

Name Type Description Default
flagged_score float

Score reported for a flagged text. Clean text always scores 0.0.

0.99

flag

flag(substring: str, *, category: str = 'fake') -> None

Flag any text containing substring, case-insensitively.

Parameters:

Name Type Description Default
substring str

The needle to look for.

required
category str

Category name reported for the match.

'fake'

check async

check(text: str) -> ModerationResult

Moderate one text.

Parameters:

Name Type Description Default
text str

The text to check.

required

Returns:

Name Type Description
ModerationResult ModerationResult

Flagged when any registered substring is

ModerationResult

present, with every matching category listed.

Raises:

Type Description
BaseException

Whatever :meth:fail_next queued.

FakePushDispatcher

FakePushDispatcher(*, platforms: set[str] | None = None)

Bases: _Steerable

A PushDispatcher that appends to a list.

Example:

>>> from tempest_fastapi_sdk.push import PushPlatformEnum
>>> dispatcher = FakePushDispatcher(platforms={PushPlatformEnum.WEB.value})
>>> dispatcher.platforms
frozenset({'web'})

Attributes:

Name Type Description
platforms frozenset[str]

Which platform values this dispatcher claims, matching the real dispatchers' attribute.

sent list[SentPush]

Deliveries accepted, in order.

calls list[str]

Methods that ran, in order.

Start with nothing sent.

Parameters:

Name Type Description Default
platforms set[str] | None

Platform values to claim. Defaults to every platform the SDK models, so a fan-out over a mixed fleet is exercised without registering three fakes.

None

send async

send(device: PushDevice, payload: PushPayloadSchema) -> None

Record a delivery instead of performing one.

Parameters:

Name Type Description Default
device PushDevice

The target device.

required
payload PushPayloadSchema

The notification.

required

Raises:

Type Description
BaseException

Whatever :meth:fail_next queued — queue :class:~tempest_fastapi_sdk.push.PushDeviceGoneError to exercise the path that prunes a dead token.

sent_to

sent_to(token: str) -> list[SentPush]

Every delivery aimed at one device token.

Parameters:

Name Type Description Default
token str

The device token to filter by.

required

Returns:

Type Description
list[SentPush]

list[SentPush]: Matching deliveries, in order. Empty when the

list[SentPush]

token was never targeted — which is a passing assertion about

list[SentPush]

nothing being sent, not an error.

SentPush dataclass

SentPush(device: PushDevice, payload: PushPayloadSchema)

One delivery this dispatcher accepted.

Attributes:

Name Type Description
device PushDevice

Where it would have gone.

payload PushPayloadSchema

What it would have carried.

FakeEmailUtils

FakeEmailUtils(
    *, from_addr: str = "fake@example.test", template_dir: str | Path | None = None
)

Bases: EmailUtils

An EmailUtils whose messages land in :attr:outbox.

Example:

>>> mailer = FakeEmailUtils()
>>> await mailer.send("ana@example.test", "Ativação", "Seu link")
>>> mailer.outbox[0].subject
'Ativação'

Attributes:

Name Type Description
outbox list[SentEmail]

Messages accepted, in order.

Build a mailer that never opens a socket.

Parameters:

Name Type Description Default
from_addr str

Default sender stamped on messages.

'fake@example.test'
template_dir str | Path | None

Passed straight through, so :meth:render_template renders the service's real templates.

None

The host and port the parent needs are placeholders on purpose: nothing here connects, and a plausible-looking host would invite the reader to think it might.

fail_next

fail_next(error: BaseException) -> None

Make the next :meth:send raise error.

Parameters:

Name Type Description Default
error BaseException

The exception to raise. Queue several to fail several sends, in the order queued.

required

send async

send(
    to: str | Iterable[str],
    subject: str,
    body: str,
    *,
    html: str | None = None,
    cc: Iterable[str] | None = None,
    bcc: Iterable[str] | None = None,
    attachments: Iterable[Path | EmailAttachment] | None = None,
    reply_to: str | None = None,
    from_addr: str | None = None,
) -> None

Append the message to :attr:outbox instead of sending it.

Parameters:

Name Type Description Default
to str | Iterable[str]

Recipient or recipients.

required
subject str

Subject line.

required
body str

Plain-text body.

required
html str | None

HTML alternative.

None
cc Iterable[str] | None

Carbon copies.

None
bcc Iterable[str] | None

Blind carbon copies.

None
attachments Iterable[Path | EmailAttachment] | None

Files to attach, recorded as given.

None
reply_to str | None

Reply-To header.

None
from_addr str | None

Sender override for this message.

None

Raises:

Type Description
BaseException

Whatever :meth:fail_next queued.

sent_to

sent_to(address: str) -> list[SentEmail]

Every message addressed to one recipient.

Parameters:

Name Type Description Default
address str

The address to filter by, matched in to, cc and bcc.

required

Returns:

Type Description
list[SentEmail]

list[SentEmail]: Matching messages, in order.

SentEmail dataclass

SentEmail(
    to: tuple[str, ...],
    subject: str,
    body: str,
    html: str | None = None,
    cc: tuple[str, ...] = tuple(),
    bcc: tuple[str, ...] = tuple(),
    attachments: tuple[Path | EmailAttachment, ...] = tuple(),
    reply_to: str | None = None,
    from_addr: str | None = None,
)

One message the fake accepted.

Attributes:

Name Type Description
to tuple[str, ...]

Recipients, normalized to a tuple.

subject str

The subject line.

body str

The plain-text body.

html str | None

The HTML alternative, when one was given.

cc tuple[str, ...]

Carbon copies.

bcc tuple[str, ...]

Blind carbon copies.

attachments tuple[Path | EmailAttachment, ...]

Files that would have been attached, as given (a Path is not read).

reply_to str | None

Reply-To, when set.

from_addr str | None

Per-message sender override, when set.

FakeGeocodingBackend

FakeGeocodingBackend()

Bases: _Steerable

A GeocodingBackend answering from a table you fill.

Example:

>>> backend = FakeGeocodingBackend()
>>> backend.add_place("Recife", Coordinate(latitude=-8.05, longitude=-34.9))
>>> result = await backend.geocode("recife")
>>> result.coordinate.latitude
-8.05

Attributes:

Name Type Description
queries list[str]

Every query this backend saw, in order.

calls list[str]

Methods that ran, in order.

Start with an empty table, which resolves nothing.

add_place

add_place(
    query: str,
    coordinate: Coordinate,
    *,
    display_name: str | None = None,
    place_type: str | None = None,
    bounding_box: BoundingBox | None = None,
) -> None

Teach the backend one place.

Parameters:

Name Type Description Default
query str

The text that resolves to it, matched case-insensitively.

required
coordinate Coordinate

Where it is.

required
display_name str | None

Name to report back. Defaults to query.

None
place_type str | None

Nominatim-style type, when a test asserts on it.

None
bounding_box BoundingBox | None

Optional geographic extent for the place.

None

geocode async

geocode(query: str) -> GeocodeResult | None

Resolve a query to a place.

Parameters:

Name Type Description Default
query str

The text to resolve.

required

Returns:

Type Description
GeocodeResult | None

GeocodeResult | None: The registered place, or None when the

GeocodeResult | None

table has no entry — which is the same answer the real backend

GeocodeResult | None

gives for an address nobody can find, and the branch a service

GeocodeResult | None

usually forgets to handle.

Raises:

Type Description
BaseException

Whatever :meth:fail_next queued.

reverse async

reverse(coordinate: Coordinate) -> GeocodeResult | None

Resolve a coordinate back to the nearest registered place.

Parameters:

Name Type Description Default
coordinate Coordinate

Where to look.

required

Returns:

Type Description
GeocodeResult | None

GeocodeResult | None: The registered place closest to

GeocodeResult | None

coordinate, or None when the table is empty. Nearest wins

GeocodeResult | None

rather than exact-match, because a service reverse-geocodes a GPS

GeocodeResult | None

reading, and a GPS reading never lands on a stored decimal.

Raises:

Type Description
BaseException

Whatever :meth:fail_next queued.

FakeGmapsScraperClient

FakeGmapsScraperClient(
    places: Sequence[PlaceSchema] = (),
    *,
    default_keywords: Sequence[str] = (),
    zoom: int = 15,
    depth: int = 1,
    lang: str = "pt",
    max_time_seconds: int = MIN_GMAPS_MAX_TIME_SECONDS,
    poll_seconds: float = 2.0,
    wait_seconds: float = 600.0,
)

Bases: _Steerable

In-memory stand-in for GmapsScraperClient and PlacesBackend.

Delegates :meth:build_job to :meth:GmapsScraperClient.build_job so payload validation (fast_mode=True, email=False, max_time_seconds >= 180, non-empty keywords) stays identical to the real client. Registered places are filtered by great-circle distance using :func:~tempest_fastapi_sdk.geo.haversine_km.

Example

fake = FakeGmapsScraperClient(default_keywords=("padaria",)) fake.add_place( ... PlaceSchema( ... source="gmaps_scraper", ... external_id="ChIJ1", ... name="Padaria Central", ... coordinate=Coordinate(latitude=-5.0892, longitude=-42.8019), ... ) ... ) places = await fake.search_nearby( ... Coordinate(latitude=-5.0892, longitude=-42.8019), ... radius_m=800, ... ) len(places) 1

Attributes:

Name Type Description
default_keywords tuple[str, ...]

Fallback search keywords used by :meth:search_nearby when included_types is omitted.

zoom int

Default map zoom level.

depth int

Default pagination depth.

lang str

Default language code.

max_time_seconds int

Default server-side max_time budget in seconds.

poll_seconds float

Default polling interval in seconds.

wait_seconds float

Default wait deadline in seconds.

jobs list[dict[str, JsonValue]]

Every job payload produced during :meth:scrape or :meth:search_nearby, in order.

scrape_calls list[tuple[Coordinate, tuple[str, ...], int]]

Every (coordinate, keywords, radius_m) observed, in order.

calls list[str]

Methods that ran, in order.

Start with an optional initial catalog of places.

Parameters:

Name Type Description Default
places Sequence[PlaceSchema]

Initial places returned when they fall within the requested radius.

()
default_keywords Sequence[str]

Optional default keywords used by :meth:search_nearby when included_types is omitted.

()
zoom int

Default zoom level (1-21). Defaults to 15.

15
depth int

Default pagination depth (>= 1). Defaults to 1.

1
lang str

Default language code. Defaults to "pt".

'pt'
max_time_seconds int

Default server-side max_time budget in seconds (>= 180). Defaults to 180.

MIN_GMAPS_MAX_TIME_SECONDS
poll_seconds float

Default polling interval in seconds (> 0). Defaults to 2.0.

2.0
wait_seconds float

Default wait deadline in seconds (> 0). Defaults to 600.0.

600.0

Raises:

Type Description
ValueError

When any default parameter is out of range or default_keywords contains a blank string.

add_place

add_place(place: PlaceSchema) -> None

Register one place in the in-memory catalog.

Parameters:

Name Type Description Default
place PlaceSchema

Place to include in future scrape results.

required

add_csv

add_csv(text: str) -> list[PlaceSchema]

Parse a CSV snapshot via :func:parse_gmaps_csv and register its places.

Parameters:

Name Type Description Default
text str

Raw CSV content exported by gosom/google-maps-scraper.

required

Returns:

Type Description
list[PlaceSchema]

list[PlaceSchema]: The newly parsed and registered places.

build_job staticmethod

build_job(
    coordinate: Coordinate,
    *,
    keywords: Sequence[str],
    radius_m: int = 800,
    zoom: int = 15,
    depth: int = 1,
    lang: str = "pt",
    max_time_seconds: int = MIN_GMAPS_MAX_TIME_SECONDS,
) -> dict[str, JsonValue]

Build a hardened job payload using :meth:GmapsScraperClient.build_job.

Parameters:

Name Type Description Default
coordinate Coordinate

Center coordinate of the search area.

required
keywords Sequence[str]

One or more non-empty search terms.

required
radius_m int

Search radius in meters (> 0). Defaults to 800.

800
zoom int

Map zoom level between 1 and 21. Defaults to 15.

15
depth int

Pagination depth (>= 1). Defaults to 1.

1
lang str

Language code sent to Google Maps. Defaults to "pt".

'pt'
max_time_seconds int

Server-side job timeout in seconds (>= 180). Defaults to 180.

MIN_GMAPS_MAX_TIME_SECONDS

Returns:

Type Description
dict[str, JsonValue]

dict[str, JsonValue]: JSON-serializable job creation payload.

scrape async

scrape(
    coordinate: Coordinate,
    *,
    keywords: Sequence[str],
    radius_m: int = 800,
    zoom: int | None = None,
    depth: int | None = None,
    lang: str | None = None,
    max_time_seconds: int | None = None,
    poll_seconds: float | None = None,
    wait_seconds: float | None = None,
) -> list[PlaceSchema]

Record a scrape job and return registered places within radius_m.

Parameters:

Name Type Description Default
coordinate Coordinate

Center coordinate of the search area.

required
keywords Sequence[str]

One or more non-empty search queries.

required
radius_m int

Search radius in meters (> 0). Defaults to 800.

800
zoom int | None

Optional zoom override.

None
depth int | None

Optional pagination depth override.

None
lang str | None

Optional language override.

None
max_time_seconds int | None

Optional max_time override (>= 180).

None
poll_seconds float | None

Optional poll interval override (> 0).

None
wait_seconds float | None

Optional wait deadline override (> 0).

None

Returns:

Type Description
list[PlaceSchema]

list[PlaceSchema]: Registered places within radius_m meters.

Raises:

Type Description
ValueError

When any parameter violates the real client's rules.

BaseException

Whatever :meth:fail_next queued.

search_nearby async

search_nearby(
    coordinate: Coordinate,
    *,
    radius_m: int = 800,
    included_types: Sequence[str] | None = None,
) -> list[PlaceSchema]

Return registered places near coordinate, matching PlacesBackend.

Parameters:

Name Type Description Default
coordinate Coordinate

Center coordinate of the search.

required
radius_m int

Search radius in meters (> 0). Defaults to 800.

800
included_types Sequence[str] | None

Optional search keywords for this call; falls back to :attr:default_keywords when None.

None

Returns:

Type Description
list[PlaceSchema]

list[PlaceSchema]: Registered places within radius_m meters.

Raises:

Type Description
ValueError

When neither included_types nor :attr:default_keywords provides a keyword, or when radius_m <= 0.

BaseException

Whatever :meth:fail_next queued.

FakePlacesBackend

FakePlacesBackend(places: Sequence[PlaceSchema] = ())

Bases: _Steerable

A PlacesBackend answering from an in-memory catalog of places.

Filters nearby queries using :func:~tempest_fastapi_sdk.geo.haversine_km and bounding-box queries using :meth:BoundingBox.contains, so tests can exercise spatial filtering and tag lookups without hitting Overpass or any external places API.

Example:

>>> backend = FakePlacesBackend()
>>> backend.add_place(
...     PlaceSchema(
...         source="overpass",
...         external_id="node/1",
...         name="Padaria Central",
...         coordinate=Coordinate(latitude=-23.5505, longitude=-46.6333),
...     )
... )
>>> places = await backend.search_nearby(
...     Coordinate(latitude=-23.5505, longitude=-46.6333),
...     radius_m=500,
... )
>>> len(places)
1

Attributes:

Name Type Description
nearby_queries list[tuple[Coordinate, int]]

Every (coordinate, radius_m) passed to :meth:search_nearby, in order.

bbox_queries list[BoundingBox]

Every bounding box passed to :meth:search_bbox, in order.

tag_queries list[str]

Every osm_id passed to :meth:fetch_tags, in order.

calls list[str]

Methods that ran, in order.

Start with an optional initial catalog of places.

Parameters:

Name Type Description Default
places Sequence[PlaceSchema]

Initial places returned by spatial queries when they fall within the requested radius or box.

()

add_place

add_place(place: PlaceSchema) -> None

Register one place in the in-memory catalog.

Parameters:

Name Type Description Default
place PlaceSchema

Place to include in future nearby and bbox searches.

required

add_tags

add_tags(osm_id: str, tags: Mapping[str, str]) -> None

Register raw OSM tags for a given osm_id.

Parameters:

Name Type Description Default
osm_id str

Canonical OSM identifier (e.g. "node/123").

required
tags Mapping[str, str]

Tag mapping returned by :meth:fetch_tags.

required

search_nearby async

search_nearby(coordinate: Coordinate, *, radius_m: int = 800) -> list[PlaceSchema]

Return registered places within radius_m meters of coordinate.

Parameters:

Name Type Description Default
coordinate Coordinate

Center point of the search.

required
radius_m int

Search radius in meters. Must be strictly positive.

800

Returns:

Type Description
list[PlaceSchema]

list[PlaceSchema]: Places whose great-circle distance to

list[PlaceSchema]

coordinate is at most radius_m meters.

Raises:

Type Description
ValueError

When radius_m <= 0.

BaseException

Whatever :meth:fail_next queued.

search_bbox async

search_bbox(bbox: BoundingBox, *, timeout_s: int = 180) -> list[PlaceSchema]

Return registered places falling inside bbox.

Parameters:

Name Type Description Default
bbox BoundingBox

Axis-aligned geographic bounding box.

required
timeout_s int

Timeout parameter matching :meth:~tempest_fastapi_sdk.geo.OverpassPlacesBackend.search_bbox.

180

Returns:

Type Description
list[PlaceSchema]

list[PlaceSchema]: Places contained within bbox.

Raises:

Type Description
ValueError

When timeout_s <= 0 or bbox has inverted bounds.

BaseException

Whatever :meth:fail_next queued.

fetch_tags async

fetch_tags(osm_id: str, *, timeout_s: int = 30) -> dict[str, str]

Return registered OSM tags for osm_id, or an empty dict.

Parameters:

Name Type Description Default
osm_id str

Canonical OSM identifier (e.g. "node/123").

required
timeout_s int

Timeout parameter matching :meth:~tempest_fastapi_sdk.geo.OverpassPlacesBackend.fetch_tags.

30

Returns:

Type Description
dict[str, str]

dict[str, str]: Copy of the registered tag mapping, or {} when

dict[str, str]

none was registered.

Raises:

Type Description
ValueError

When timeout_s <= 0.

BaseException

Whatever :meth:fail_next queued.

FakeRoutingBackend

FakeRoutingBackend(*, source: str = 'fake')

Bases: _Steerable

A RoutingBackend that estimates offline.

Example:

>>> backend = FakeRoutingBackend()
>>> estimate = await backend.route(
...     Coordinate(latitude=-8.05, longitude=-34.9),
...     Coordinate(latitude=-8.06, longitude=-34.91),
... )
>>> estimate.source
'fake'

Attributes:

Name Type Description
routes list[tuple[Coordinate, Coordinate]]

Every pair asked for.

calls list[str]

Methods that ran, in order.

Start with no canned answers.

Parameters:

Name Type Description Default
source str

Value stamped on :attr:TravelEstimate.source, so an assertion can tell a faked estimate from an OSRM one.

'fake'

add_route

add_route(
    origin: Coordinate, destination: Coordinate, estimate: TravelEstimate
) -> None

Pin one pair to an exact estimate.

Parameters:

Name Type Description Default
origin Coordinate

Where the trip starts.

required
destination Coordinate

Where it ends.

required
estimate TravelEstimate

What to return for that pair, verbatim — for the test that needs a specific duration rather than a plausible one.

required

route async

route(
    origin: Coordinate, destination: Coordinate, *, mode: TravelModeEnum = CAR
) -> TravelEstimate

Estimate a trip.

Parameters:

Name Type Description Default
origin Coordinate

Where the trip starts.

required
destination Coordinate

Where it ends.

required
mode TravelModeEnum

How it travels.

CAR

Returns:

Name Type Description
TravelEstimate TravelEstimate

The pinned estimate for this pair when there is

TravelEstimate

one; otherwise the SDK's own offline estimate, restamped with

TravelEstimate

attr:source.

Raises:

Type Description
BaseException

Whatever :meth:fail_next queued.

route_through async

route_through(
    points: Sequence[Coordinate],
    *,
    mode: TravelModeEnum = CAR,
    with_geometry: bool = False,
) -> RouteThroughResult

Estimate a route through several points, one :meth:route per leg.

Each leg goes through :meth:route, so a pair pinned with :meth:add_route is honoured inside a longer route too, and every leg lands in :attr:routes.

Parameters:

Name Type Description Default
points Sequence[Coordinate]

The ordered points. At least two.

required
mode TravelModeEnum

How it travels.

CAR
with_geometry bool

Whether to fill the geometry with the points themselves (straight lines).

False

Returns:

Name Type Description
RouteThroughResult RouteThroughResult

The legs and their sums, stamped with

RouteThroughResult

attr:source.

Raises:

Type Description
ValueError

If fewer than two points are given.

BaseException

Whatever :meth:fail_next queued.

matrix async

matrix(
    sources: list[Coordinate],
    destinations: list[Coordinate] | None = None,
    *,
    mode: TravelModeEnum = CAR,
) -> DistanceMatrix

Estimate every (source, destination) pair through :meth:route.

Parameters:

Name Type Description Default
sources list[Coordinate]

The origin coordinates (rows).

required
destinations list[Coordinate] | None

The destination coordinates (columns); None means sources.

None
mode TravelModeEnum

How it travels.

CAR

Returns:

Name Type Description
DistanceMatrix DistanceMatrix

One cell per pair, source_label stamped with

DistanceMatrix

attr:source.

Raises:

Type Description
ValueError

If sources is empty.

BaseException

Whatever :meth:fail_next queued.

FakeWebSearchBackend

FakeWebSearchBackend()

Bases: _Steerable

A WebSearchBackend answering from a table you fill.

Example:

>>> backend = FakeWebSearchBackend()
>>> backend.add_results(
...     "pix",
...     [SearchResult(
...         title="Pix",
...         url="https://example.test/pix",
...         snippet="Pagamento instantâneo",
...         content="Pix é o pagamento instantâneo brasileiro.",
...     )],
... )
>>> results = await backend.search("Pix", max_results=5)
>>> results[0].title
'Pix'

Attributes:

Name Type Description
queries list[str]

Every query this backend saw, in order.

calls list[str]

Methods that ran, in order.

Start with an empty table, which returns no results.

add_results

add_results(query: str, results: list[SearchResult]) -> None

Register the results one query returns.

Parameters:

Name Type Description Default
query str

The query, matched case-insensitively.

required
results list[SearchResult]

What to return for it, in order.

required

search async

search(query: str, *, max_results: int) -> list[SearchResult]

Search.

Parameters:

Name Type Description Default
query str

What to search for.

required
max_results int

Ceiling on how many come back. Honoured, so a consumer that assumes the backend respects it is exercised the same way the real one exercises it.

required

Returns:

Type Description
list[SearchResult]

list[SearchResult]: The registered results, truncated to

list[SearchResult]

max_results. Empty when the query was never registered —

list[SearchResult]

an empty result set is a valid search, not an error.

Raises:

Type Description
BaseException

Whatever :meth:fail_next queued.

FakeLinkedInClient

FakeLinkedInClient()

Bases: _Steerable

In-memory stand-in for LinkedInClient.

Example

fake = FakeLinkedInClient() image_urn = await fake.upload_image( ... "urn🇱🇮person:abc123", ... b"\xff\xd8\xff", ... ) result = await fake.publish_post( ... "urn🇱🇮person:abc123", ... "Hello LinkedIn!", ... media_urn=image_urn, ... ) len(fake.published_posts) 1

Attributes:

Name Type Description
calls list[str]

Names of methods that ran, in order.

published_posts list[PublishedLinkedInPost]

Posts published, in order.

uploaded_images list[UploadedLinkedInImage]

Images uploaded, in order.

deleted_posts list[str]

Post URNs passed to delete_post, in order.

Start with empty records and zero counters.

aclose async

aclose() -> None

No-op close matching :meth:LinkedInClient.aclose.

publish_post async

publish_post(
    author_urn: str,
    commentary: str,
    *,
    visibility: LinkedInVisibilityEnum = PUBLIC,
    distribution: LinkedInFeedDistributionEnum = MAIN_FEED,
    lifecycle_state: LinkedInLifecycleStateEnum = PUBLISHED,
    article: LinkedInArticleContentSchema | None = None,
    media_urn: str | None = None,
    alt_text: str | None = None,
) -> LinkedInPostResultSchema

Record a post instead of calling LinkedIn.

Validates inputs through :class:LinkedInPostCreateSchema so invalid URNs or mutually exclusive content fail the same way as the real client.

Parameters:

Name Type Description Default
author_urn str

Author URN (urn:li:person:... or urn:li:organization:...).

required
commentary str

Post text body.

required
visibility LinkedInVisibilityEnum

Audience visibility.

PUBLIC
distribution LinkedInFeedDistributionEnum

Feed distribution.

MAIN_FEED
lifecycle_state LinkedInLifecycleStateEnum

Lifecycle state.

PUBLISHED
article LinkedInArticleContentSchema | None

Optional article card.

None
media_urn str | None

Optional image URN.

None
alt_text str | None

Optional alt text for media_urn.

None

Returns:

Name Type Description
LinkedInPostResultSchema LinkedInPostResultSchema

Synthetic post result with

LinkedInPostResultSchema

urn:li:share:fake-<n>.

Raises:

Type Description
ValueError

When inputs fail :class:LinkedInPostCreateSchema.

BaseException

Whatever :meth:fail_next queued.

upload_image async

upload_image(owner_urn: str, data: bytes, *, content_type: str = 'image/jpeg') -> str

Record an image upload and return a synthetic urn:li:image:... URN.

Parameters:

Name Type Description Default
owner_urn str

Owner URN (urn:li:person:... or urn:li:organization:...).

required
data bytes

Raw binary image bytes.

required
content_type str

MIME type for the upload.

'image/jpeg'

Returns:

Name Type Description
str str

Synthetic urn:li:image:fake-<n> URN.

Raises:

Type Description
ValueError

When owner_urn is malformed, data is empty, or content_type is blank.

BaseException

Whatever :meth:fail_next queued.

delete_post async

delete_post(post_urn: str) -> None

Record a post deletion.

Parameters:

Name Type Description Default
post_urn str

Post URN to delete.

required

Raises:

Type Description
ValueError

When post_urn is malformed.

BaseException

Whatever :meth:fail_next queued.

PublishedLinkedInPost dataclass

PublishedLinkedInPost(post_urn: str, payload: LinkedInPostCreateSchema)

One post recorded by :class:FakeLinkedInClient.

Attributes:

Name Type Description
post_urn str

Synthetic post URN assigned by the fake.

payload LinkedInPostCreateSchema

Validated input parameters.

UploadedLinkedInImage dataclass

UploadedLinkedInImage(image_urn: str, owner_urn: str, data: bytes, content_type: str)

One image upload recorded by :class:FakeLinkedInClient.

Attributes:

Name Type Description
image_urn str

Synthetic urn:li:image:... URN assigned by the fake.

owner_urn str

Validated owner URN passed to upload_image.

data bytes

Raw binary image bytes uploaded.

content_type str

MIME type sent for the binary upload.

FakeMercadoPagoOrdersAPI

FakeMercadoPagoOrdersAPI(
    *,
    webhook_secret: str = FAKE_WEBHOOK_SECRET,
    clock: Callable[[], datetime] | None = None,
)

Mercado Pago's /v1/orders with state, as an httpx handler.

Wire it under the real adapter and nothing else changes::

api = FakeMercadoPagoOrdersAPI()
provider = MercadoPagoPixProvider(api.http_client())

Routes answered (anything else is 404):

  • POST /v1/orders — Pix (payment_method.id == "pix") or card. Idempotent on X-Idempotency-Key: the same key with the same body replays the first answer, with another body answers 409 idempotency_key_already_used.
  • GET /v1/orders/{id} — 404 for an id it never created.
  • POST /v1/orders/{id}/cancel — an action_required order.
  • POST /v1/orders/{id}/capture — a waiting_capture card order.
  • POST /v1/orders/{id}/refund — a processed order, in full (no body) or in part (transactions[0].amount), until nothing is left.

The provider-side moves are methods: :meth:pay, :meth:expire, :meth:fail, plus :meth:cancel, :meth:capture and :meth:refund for driving those without the adapter. Each returns the signed :class:MercadoPagoDelivery announcing the new state.

Attributes:

Name Type Description
webhook_secret str

The secret deliveries are signed with.

calls list[tuple[str, str]]

(method, path) of every request answered, in order.

Start with no orders.

Parameters:

Name Type Description Default
webhook_secret str

Signs every delivery the transitions return. Defaults to :data:FAKE_WEBHOOK_SECRET.

FAKE_WEBHOOK_SECRET
clock Callable[[], datetime] | None

Source of created_date and date_of_expiration. Defaults to the current UTC time.

None

order_ids property

order_ids: list[str]

Every order id created, oldest first.

Returns:

Type Description
list[str]

list[str]: The ids.

order

order(order_id: str) -> dict[str, Any]

Read an order as GET /v1/orders/{id} would answer it.

Parameters:

Name Type Description Default
order_id str

The order id.

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: A copy; changing it changes nothing here.

Raises:

Type Description
KeyError

If no such order was created.

find_order_id

find_order_id(reference: str) -> str

Resolve an order id or an external_reference to an order id.

A service shows its own reference (the external_reference it sent on create, usually a correlation_id) in its screens and logs; the ORD… id only appears in the provider's answer. This accepts either.

Parameters:

Name Type Description Default
reference str

An order id, or the external_reference of an order.

required

Returns:

Name Type Description
str str

reference itself when it is an order id; otherwise the id

str

of the most recent order created with that

str

external_reference — a service that charges the same

str

reference again after an expiry means the new order.

Raises:

Type Description
KeyError

If no order has that id or that external_reference.

decline_next_card

decline_next_card(status_detail: str = 'rejected_by_issuer') -> None

Make the next card create answer 402 with a failed order.

Parameters:

Name Type Description Default
status_detail str

The payment's status_detail. rejected_by_issuer is what the sandbox answered for the OTHE holder.

'rejected_by_issuer'

lose_next_answer

lose_next_answer() -> None

Apply the next POST, then raise httpx.ReadTimeout.

The failure a retry under the same idempotency key has to survive. Works on the in-process transport; through make_fake_orders_app the exception becomes a 500 instead.

transport

transport() -> MockTransport

Wrap this handler in an httpx transport.

Returns:

Type Description
MockTransport

httpx.MockTransport: Pass it as transport= to an

MockTransport

HTTPClient or an httpx.AsyncClient.

http_client

http_client(
    *, base_url: str = DEFAULT_BASE_URL, retry_policy: RetryPolicy | None = None
) -> HTTPClient

Build the HTTPClient the Mercado Pago adapters take.

Parameters:

Name Type Description Default
base_url str

Any host; requests never leave the process.

DEFAULT_BASE_URL
retry_policy RetryPolicy | None

Forwarded to the client. RetryPolicy(max_attempts=1) surfaces a :meth:lose_next_answer to the caller instead of retrying it.

None

Returns:

Name Type Description
HTTPClient HTTPClient

The client, over :meth:transport.

delivery

delivery(
    order_id: str,
    *,
    action: str | None = None,
    request_id: str | None = None,
    ts: int | None = None,
) -> MercadoPagoDelivery

Build the signed delivery about an order's current state.

Parameters:

Name Type Description Default
order_id str

The order id.

required
action str | None

The body's action; :func:order_action when None.

None
request_id str | None

The x-request-id; a UUID4 when None.

None
ts int | None

The signature's timestamp in seconds; now when None.

None

Returns:

Name Type Description
MercadoPagoDelivery MercadoPagoDelivery

Signed with :attr:webhook_secret.

Raises:

Type Description
KeyError

If no such order was created.

pay

pay(order_id: str) -> MercadoPagoDelivery

Mark a pending Pix order paid, as the payer's bank would.

The order becomes processed / accredited, its payment gains paid_amount and an e2e_id, and the QR fields go — the shape of a paid order read from the sandbox (pix_get_paid.json).

Parameters:

Name Type Description Default
order_id str

A Pix order in action_required / waiting_transfer.

required

Returns:

Name Type Description
MercadoPagoDelivery MercadoPagoDelivery

order.processed (not observed live; see

MercadoPagoDelivery

func:order_action).

Raises:

Type Description
KeyError

If no such order was created.

ValueError

If the order is not a pending Pix order.

expire

expire(order_id: str) -> MercadoPagoDelivery

Let a pending Pix order run out, as its deadline would.

canceled / expired with the payment expired / expired — read from the sandbox after a PT60S order's deadline (pix_get_expired.json). The adapter reads it as :attr:PaymentStatusEnum.EXPIRED.

Parameters:

Name Type Description Default
order_id str

A Pix order in action_required.

required

Returns:

Name Type Description
MercadoPagoDelivery MercadoPagoDelivery

order.canceled — the one action observed

MercadoPagoDelivery

live, on a canceled order whose status_detail the evidence

MercadoPagoDelivery

does not record.

Raises:

Type Description
KeyError

If no such order was created.

ValueError

If the order is not a pending Pix order.

fail

fail(order_id: str, status_detail: str = 'rejected_by_issuer') -> MercadoPagoDelivery

Fail a pending order, as a declined payment would.

Parameters:

Name Type Description Default
order_id str

An order in action_required.

required
status_detail str

The payment's status_detail.

'rejected_by_issuer'

Returns:

Name Type Description
MercadoPagoDelivery MercadoPagoDelivery

order.failed (not observed live).

Raises:

Type Description
KeyError

If no such order was created.

ValueError

If the order is not pending.

cancel

cancel(order_id: str) -> MercadoPagoDelivery

Cancel a pending order, as POST /v1/orders/{id}/cancel does.

Parameters:

Name Type Description Default
order_id str

An order in action_required.

required

Returns:

Name Type Description
MercadoPagoDelivery MercadoPagoDelivery

order.canceled, the action name observed

MercadoPagoDelivery

live (on an order whose cause — cancel or expiry — the evidence

MercadoPagoDelivery

does not record).

Raises:

Type Description
KeyError

If no such order was created.

ValueError

If the order is not pending.

capture

capture(order_id: str) -> MercadoPagoDelivery

Capture a card authorization, as POST …/capture does.

Parameters:

Name Type Description Default
order_id str

A card order in waiting_capture.

required

Returns:

Name Type Description
MercadoPagoDelivery MercadoPagoDelivery

order.processed (not observed live).

Raises:

Type Description
KeyError

If no such order was created.

ValueError

If the order is not waiting on capture.

refund

refund(order_id: str, amount_cents: int | None = None) -> MercadoPagoDelivery

Refund a processed order, as POST …/refund does.

Parameters:

Name Type Description Default
order_id str

A processed order.

required
amount_cents int | None

Cents to refund; None refunds what is left.

None

Returns:

Name Type Description
MercadoPagoDelivery MercadoPagoDelivery

order.refunded after the last cent,

MercadoPagoDelivery

order.processed after a partial refund (neither observed

MercadoPagoDelivery

live).

Raises:

Type Description
KeyError

If no such order was created.

ValueError

If the order is not processed or the amount is not positive or exceeds what is left.

apply

apply(
    order_id: str, transition: str, amount_cents: int | None = None
) -> MercadoPagoDelivery

Apply a transition by name — what the control route calls.

Parameters:

Name Type Description Default
order_id str

The order id.

required
transition str

pay, expire, fail, cancel, capture or refund.

required
amount_cents int | None

For refund only.

None

Returns:

Name Type Description
MercadoPagoDelivery MercadoPagoDelivery

The delivery about the new state.

Raises:

Type Description
KeyError

If no such order was created.

ValueError

For an unknown transition, or one that does not apply.

MercadoPagoDelivery dataclass

MercadoPagoDelivery(
    query: dict[str, str],
    headers: dict[str, str],
    payload: dict[str, Any],
    body: bytes,
    data_id: str,
    request_id: str,
    timestamp: str,
)

One signed notification, ready to send to a webhook route.

Attributes:

Name Type Description
query dict[str, str]

The query string — data.id, type and, when the order has one, data.external_reference.

headers dict[str, str]

x-signature, x-request-id and content-type.

payload dict[str, Any]

The decoded body.

body bytes

The body exactly as it goes on the wire.

data_id str

The order id the signature covers.

request_id str

The x-request-id the signature covers.

timestamp str

The ts the signature covers, in seconds.

url

url(endpoint: str) -> str

Join the route's URL and this delivery's query string.

Parameters:

Name Type Description Default
endpoint str

The webhook route, absolute or relative.

required

Returns:

Name Type Description
str str

endpoint?data.id=…&type=order….

send async

send(client: AsyncClient, endpoint: str) -> Response

Post this delivery with an async client.

Parameters:

Name Type Description Default
client AsyncClient

Any async client — one over httpx.ASGITransport(app=app) reaches a FastAPI app in-process.

required
endpoint str

The webhook route.

required

Returns:

Type Description
Response

httpx.Response: What the route answered.

send_sync

send_sync(client: Client, endpoint: str) -> Response

Post this delivery with a sync client.

Parameters:

Name Type Description Default
client Client

Any sync client, fastapi.testclient.TestClient included.

required
endpoint str

The webhook route.

required

Returns:

Type Description
Response

httpx.Response: What the route answered.

build_mercado_pago_delivery

build_mercado_pago_delivery(
    order: Mapping[str, Any],
    *,
    secret: str,
    action: str | None = None,
    request_id: str | None = None,
    ts: int | None = None,
    live_mode: bool = False,
    application_id: str = FAKE_APPLICATION_ID,
    user_id: str = FAKE_USER_ID,
) -> MercadoPagoDelivery

Build the notification Mercado Pago sends about an order.

The shape is the production delivery of 2026-11-13 (vendor/mercadopago-evidence.md section 11). The signature is :func:sign_manifest over the order id as delivered, the request id and the timestamp — the same call the SDK's verifier makes, which lowercases the id into the manifest.

Parameters:

Name Type Description Default
order Mapping[str, Any]

The order, at least {"id": "ORD…"}. Its external_reference goes into the query and a summary of it into data, as observed.

required
secret str

The webhook secret the receiving service verifies with.

required
action str | None

The body's action. None takes :func:order_action of the order — read its docstring for which names were observed.

None
request_id str | None

The x-request-id. None draws a UUID4.

None
ts int | None

The signature's timestamp, in seconds since the epoch. None takes the current time; pass an old one to test the verifier's tolerance window.

None
live_mode bool

The body's live_mode. True on the observed production delivery; False by default because this delivery is not one.

False
application_id str

The body's application_id.

FAKE_APPLICATION_ID
user_id str

The body's user_id.

FAKE_USER_ID

Returns:

Name Type Description
MercadoPagoDelivery MercadoPagoDelivery

The delivery.

Raises:

Type Description
ValueError

If the order carries no id, or secret is empty — the SDK's verifier rejects every delivery under an empty secret, so building one would only produce a 401 that looks like a signing bug.

order_action

order_action(order: Mapping[str, Any]) -> str

Name the action a delivery about this order carries.

order.<status> — the rule the one observed live action fits: a canceled order arrived as order.canceled (production, 2026-11-13).

Provenance of each name this produces, so a test that branches on the action knows what it rests on:

  • order.canceled — observed on a live delivery.
  • order.processed, order.refunded, order.action_required, order.failed — not observed, and not in the vendored document either, whose WebhookNotification.action lists only order.created and order.updated. They are this simulator's extrapolation of the observed rule.

Pass action= to :func:build_mercado_pago_delivery to send order.created / order.updated (in the vendored document, not observed) or anything else. The SDK's delivery dependency does not branch on the action: it re-reads the order and decides on its status.

Parameters:

Name Type Description Default
order Mapping[str, Any]

The order the delivery is about.

required

Returns:

Name Type Description
str str

order.<status>, or order.updated when the order carries

str

no status.

FAKE_WEBHOOK_SECRET module-attribute

FAKE_WEBHOOK_SECRET: Final[str] = 'tempest-fake-mercado-pago-webhook-secret'

Secret :class:FakeMercadoPagoOrdersAPI signs its deliveries with by default.

A fixed, public value: it only ever authenticates the simulator to a service under test. Configure the service with the same value, or pass your own to the constructor.

make_fake_orders_app

make_fake_orders_app(api: FakeMercadoPagoOrdersAPI) -> FastAPI

Serve a simulator over HTTP, for a service running on its own.

tempest mercado-pago fake-api runs it under uvicorn. Every /v1/orders route answers as the in-process handler does, and :data:FAKE_CONTROL_PREFIX adds:

  • GET /_fake/orders — every order id.
  • GET /_fake/orders/{reference} — one order, by id or by external_reference (:meth:FakeMercadoPagoOrdersAPI.find_order_id); 404 when none matches.
  • POST /_fake/orders/{reference}/{transition} — resolve the order the same way, apply :meth:FakeMercadoPagoOrdersAPI.apply (?amount_cents= for a partial refund) and answer {"order": <order>, "action": <action>}. The delivery itself is not sent: the server does not know the service's secret, so tempest mercado-pago simulate-webhook (or the simulation routes of make_mercado_pago_router(simulation_url=...)) signs and sends it.

Parameters:

Name Type Description Default
api FakeMercadoPagoOrdersAPI

The simulator whose state the app serves; keep a reference to drive it from the same process.

required

Returns:

Name Type Description
FastAPI FastAPI

The app.

FakeApifyClient

FakeApifyClient()

Bases: _Steerable

In-memory stand-in for ApifyClient.

Supports both FIFO queued responses (global or per-actor), reusable per-actor responses, and configurable failures (global via :meth:fail_next or per-actor via :meth:set_actor_error).

Example

fake = FakeApifyClient() fake.set_actor_items( ... "apify~instagram-profile-scraper", ... [{"username": "padaria", "followersCount": 1200, "postsCount": 40}], ... ) items = await fake.run_actor_sync_items( ... "apify~instagram-profile-scraper", ... {"usernames": ["padaria"]}, ... )

Attributes:

Name Type Description
calls list[str]

Method names called, in order.

recorded_calls list[ApifyActorCall]

Detailed call log with normalized actor_id, run_input and timeout.

Initialize an empty fake client with no seeded responses or errors.

enqueue_items

enqueue_items(
    items: Sequence[Mapping[str, JsonValue]], *, actor_id: str | None = None
) -> None

Queue one dataset response for the next matching call.

Parameters:

Name Type Description Default
items Sequence[Mapping[str, JsonValue]]

Dataset items to return.

required
actor_id str | None

Optional actor ID to scope this queued response to. None appends to the fallback FIFO queue.

None

Raises:

Type Description
ValueError

When actor_id is provided and invalid.

set_actor_items

set_actor_items(actor_id: str, items: Sequence[Mapping[str, JsonValue]]) -> None

Set a reusable dataset response for actor_id.

Used whenever no per-actor queued response is pending for that actor.

Parameters:

Name Type Description Default
actor_id str

Apify actor ID, owner~actor or owner/actor.

required
items Sequence[Mapping[str, JsonValue]]

Dataset items returned on every call to actor_id.

required

Raises:

Type Description
ValueError

When actor_id is invalid.

set_actor_error

set_actor_error(actor_id: str, error: BaseException | None) -> None

Configure (or clear) a persistent error raised for actor_id.

Parameters:

Name Type Description Default
actor_id str

Apify actor ID, owner~actor or owner/actor.

required
error BaseException | None

Exception to raise for every call to actor_id, or None to clear the configured error.

required

Raises:

Type Description
ValueError

When actor_id is invalid.

aclose async

aclose() -> None

Mark the fake client as closed.

run_actor_sync_items async

run_actor_sync_items(
    actor_id: str, run_input: Mapping[str, JsonValue], *, timeout: float | None = None
) -> list[dict[str, JsonValue]]

Return queued or seeded dataset items for actor_id.

Parameters:

Name Type Description Default
actor_id str

Apify actor ID, owner~actor or owner/actor.

required
run_input Mapping[str, JsonValue]

JSON input payload for the actor.

required
timeout float | None

Optional per-call timeout override in seconds.

None

Returns:

Type Description
list[dict[str, JsonValue]]

list[dict[str, JsonValue]]: Fresh copy of the configured items, or

list[dict[str, JsonValue]]

[] when nothing was configured.

Raises:

Type Description
ValueError

When actor_id is invalid or timeout is not positive.

BaseException

Whatever was queued via :meth:fail_next or set via :meth:set_actor_error.

ApifyActorCall dataclass

ApifyActorCall(actor_id: str, run_input: dict[str, JsonValue], timeout: float | None)

Recorded invocation of :meth:FakeApifyClient.run_actor_sync_items.

Attributes:

Name Type Description
actor_id str

Normalized Apify actor identifier.

run_input dict[str, JsonValue]

Copy of the JSON input dictionary.

timeout float | None

Timeout override passed to the call.

FakeZapClient

FakeZapClient(
    *,
    status: AcceptedResponseStatus | None = QUEUED,
    persistent: bool = True,
    media: Mapping[str, bytes] | None = None,
    id_prefix: str = "out-",
)

Bases: _Steerable, ZapClient

In-memory stand-in for :class:ZapClient covering ZapInbox seams.

Subclasses :class:ZapClient without opening an HTTPClient so it fits anywhere a service expects ZapClient (including :class:ZapInbox and FastAPI dependency_overrides).

Attributes:

Name Type Description
status AcceptedResponseStatus | None

Status returned on accepted sends in persistent mode. Setting status=None or persistent=False simulates a gateway running without persistence (id=None, status=None, deduped=False).

persistent bool

Whether sends generate sequential outbox ids and deduplicate by idempotency_key.

id_prefix str

Prefix for generated outbox ids (default "out-").

media dict[str, bytes]

Map from WhatsApp message_id to raw media bytes returned by :meth:get_message_media.

sent list[ZapSentText]

Accepted (non-deduplicated) text sends, in order.

calls list[str]

Method names invoked on this fake, in order.

Build a fake zap-api client with no network transport.

Parameters:

Name Type Description Default
status AcceptedResponseStatus | None

Status returned by :meth:send_text. Defaults to :attr:AcceptedResponseStatus.QUEUED. Pass :attr:AcceptedResponseStatus.FAILED to simulate an already failed outbox row, or None for non-persistent mode.

QUEUED
persistent bool

When True (default) and status is not None, assigns sequential ids and deduplicates repeated idempotency_key calls. When False, answers id=None, status=None, deduped=False on every send.

True
media Mapping[str, bytes] | None

Initial mapping of message_id to raw media bytes for :meth:get_message_media.

None
id_prefix str

Prefix for generated outbox ids (for example "out-1", "out-2").

'out-'

set_media

set_media(message_id: str, data: bytes) -> None

Seed or replace media bytes returned by :meth:get_message_media.

Parameters:

Name Type Description Default
message_id str

The WhatsApp message id.

required
data bytes

Raw media bytes to serve for message_id.

required

sent_to

sent_to(to: str) -> list[ZapSentText]

Return every accepted text sent to one recipient.

Parameters:

Name Type Description Default
to str

Recipient phone digits (chat_key).

required

Returns:

Type Description
list[ZapSentText]

list[ZapSentText]: Matching sent records, in send order.

send_text async

send_text(
    *, body: SendTextRequest | None = None, idempotency_key: str | None = None
) -> AcceptedResponse

Record a text send and return an :class:AcceptedResponse.

In persistent mode (persistent=True and status is not None), repeating a previously seen idempotency_key returns the original id and status with deduped=True and does not append to :attr:sent. In non-persistent mode, every send returns id=None, status=None, deduped=False.

Parameters:

Name Type Description Default
body SendTextRequest | None

The text request payload.

None
idempotency_key str | None

Optional idempotency key used to deduplicate retries.

None

Returns:

Name Type Description
AcceptedResponse AcceptedResponse

The simulated 202 response.

Raises:

Type Description
ValueError

When body is None.

BaseException

Whatever :meth:fail_next queued.

get_message_media async

get_message_media(message_id: str) -> bytes

Return seeded media bytes for message_id or raise 404.

Parameters:

Name Type Description Default
message_id str

The WhatsApp message id (messageId in the inbound webhook).

required

Returns:

Name Type Description
bytes bytes

The raw bytes stored under message_id in :attr:media.

Raises:

Type Description
ValueError

If message_id is empty, . or .., matching :meth:ZapClient.get_message_media.

HTTPStatusError

A 404 error when message_id is not in :attr:media.

BaseException

Whatever :meth:fail_next queued.

ZapSentText dataclass

ZapSentText(
    body: SendTextRequest,
    to: str,
    text: str,
    reply_to: str | None = None,
    idempotency_key: str | None = None,
    outbound_id: str | None = None,
    status: AcceptedResponseStatus | None = None,
)

One text message accepted by :class:FakeZapClient.

Deduplicated retries with an already-seen idempotency_key do not append a second record here, mirroring the real gateway's outbox behavior.

Attributes:

Name Type Description
body SendTextRequest

The request model passed to :meth:FakeZapClient.send_text.

to str

Recipient phone digits, copied from body.to.

text str

Message body, copied from body.text.

reply_to str | None

Quoted WhatsApp message id, copied from body.reply_to.

idempotency_key str | None

The idempotency key passed to send_text, when given.

outbound_id str | None

The id returned in :class:AcceptedResponse, or None in non-persistent mode.

status AcceptedResponseStatus | None

The status returned in :class:AcceptedResponse, or None in non-persistent mode.

sign_zap_webhook

sign_zap_webhook(body: bytes, secret: str | bytes) -> str

Compute the x-zap-signature header value for a raw webhook body.

Uses HMAC-SHA256 hex prefixed with :data:ZAP_WEBHOOK_SIGNATURE_PREFIX ("sha256="), matching the gateway's signPayload and accepted by :func:~tempest_fastapi_sdk.integrations.messaging.zap.webhook_verifier and :func:~tempest_fastapi_sdk.integrations.messaging.zap.make_zap_webhook_dependency.

Parameters:

Name Type Description Default
body bytes

Exact raw request bytes to sign.

required
secret str | bytes

Shared webhook secret. Strings are encoded as UTF-8.

required

Returns:

Name Type Description
str str

Signature string in the form "sha256=<hex>".

Raises:

Type Description
ValueError

When secret is empty or whitespace only.

make_zap_inbound

make_zap_inbound(
    *,
    message_id: str = "msg-1",
    from_: str = _DEFAULT_JID,
    chat_key: str | None = _DEFAULT_PHONE,
    push_name: str | None = "Fulano",
    text: str | None = "Hello!",
    media_type: ZapInboundMediaTypeEnum | None = None,
    media_url: str | None = None,
    timestamp: datetime | None = None,
    event: ZapWebhookEventEnum = MESSAGE_RECEIVED,
) -> ZapInboundMessage

Build a valid :class:ZapInboundMessage with sensible defaults.

All fields are explicit typed keyword arguments so callers override only what a test cares about and get full static type checking. Serialize with model_dump_json(by_alias=True).encode("utf-8") to produce the wire payload for :func:sign_zap_webhook.

Parameters:

Name Type Description Default
message_id str

WhatsApp messageId.

'msg-1'
from_ str

Raw sender JID (from on the wire).

_DEFAULT_JID
chat_key str | None

Resolved recipient phone digits, or None for groups, broadcasts, channels or unmapped LIDs.

_DEFAULT_PHONE
push_name str | None

Sender display name.

'Fulano'
text str | None

Text message body or media caption.

'Hello!'
media_type ZapInboundMediaTypeEnum | None

Media category, or None for plain text.

None
media_url str | None

Gateway media path/URL, or None when absent or lost.

None
timestamp datetime | None

Message timestamp. Defaults to a fixed UTC timestamp for deterministic tests.

None
event ZapWebhookEventEnum

Webhook event name. Defaults to :attr:ZapWebhookEventEnum.MESSAGE_RECEIVED.

MESSAGE_RECEIVED

Returns:

Name Type Description
ZapInboundMessage ZapInboundMessage

Validated inbound message schema.

make_zap_status

make_zap_status(
    *,
    id: str = "out-1",
    status: AcceptedResponseStatus = DELIVERED,
    consumer: str = "test-consumer",
    to: str = _DEFAULT_PHONE,
    kind: ZapOutboundKindEnum | str = TEXT,
    wa_message_id: str | None = None,
    error: str | None = None,
    timestamp: datetime | None = None,
    event: ZapWebhookEventEnum | None = None,
) -> ZapStatusCallback

Build a valid :class:ZapStatusCallback with sensible defaults.

When event is omitted, derives message.<status> from status (for sent, delivered, read and failed). Serialize with model_dump_json(by_alias=True).encode("utf-8") to produce the wire payload for :func:sign_zap_webhook.

Parameters:

Name Type Description Default
id str

Outbox row id returned by the send's 202.

'out-1'
status AcceptedResponseStatus

Reported delivery status. Defaults to :attr:AcceptedResponseStatus.DELIVERED.

DELIVERED
consumer str

Consumer name registered on the gateway.

'test-consumer'
to str

Recipient phone digits.

_DEFAULT_PHONE
kind ZapOutboundKindEnum | str

Outbound message kind. Defaults to :attr:ZapOutboundKindEnum.TEXT.

TEXT
wa_message_id str | None

WhatsApp message id, when known.

None
error str | None

Failure reason, typically set when status is :attr:AcceptedResponseStatus.FAILED.

None
timestamp datetime | None

Callback timestamp. Defaults to a fixed UTC timestamp for deterministic tests.

None
event ZapWebhookEventEnum | None

Explicit webhook event override. Derived from status when None.

None

Returns:

Name Type Description
ZapStatusCallback ZapStatusCallback

Validated status callback schema.

Raises:

Type Description
ValueError

When event is None and status is not a callback status (queued or sending).