tempest_fastapi_sdk.testing.fakes¶
Dublês dos terceiros com que um serviço conversa.
FakePixProvider
¶
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: |
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'
|
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
¶
Make the next refund apply, then raise error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error
|
BaseException
|
What the caller sees instead of the
answer — say |
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: |
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: |
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: |
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
|
refund_reference
|
str
|
The refund's idempotency key, scoped to the charge. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
PixRefund |
PixRefund
|
The refund, |
PixRefund
|
reference was used before, with |
Raises:
| Type | Description |
|---|---|
KeyError
|
When no charge carries that id. |
ValueError
|
When |
PixRefundReferenceConflictException
|
When the reference names a refund of another amount. |
PixRefundExceedsBalanceException
|
When less is left than asked. |
BaseException
|
Whatever :meth: |
get_refunded_cents
async
¶
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; |
Raises:
| Type | Description |
|---|---|
KeyError
|
When no charge carries that id. |
BaseException
|
Whatever :meth: |
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 |
required |
Returns:
| Name | Type | Description |
|---|---|---|
PixPaymentEvent |
PixPaymentEvent
|
The canonical event. |
Raises:
| Type | Description |
|---|---|
TypeError
|
When |
KeyError
|
When no charge carries that id. |
BaseException
|
Whatever :meth: |
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
¶
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: |
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
¶
Make the next :meth:create_card_charge come back declined.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
status_detail
|
str
|
The reason, copied into
:attr: |
'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
|
|
CardCharge
|
|
Raises:
| Type | Description |
|---|---|
BaseException
|
Whatever :meth: |
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: |
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, |
Raises:
| Type | Description |
|---|---|
KeyError
|
When no charge carries that id. |
ValueError
|
When the charge is not |
BaseException
|
Whatever :meth: |
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, |
Raises:
| Type | Description |
|---|---|
KeyError
|
When no charge carries that id. |
ValueError
|
When the charge is not |
BaseException
|
Whatever :meth: |
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
|
Returns:
| Name | Type | Description |
|---|---|---|
CardCharge |
CardCharge
|
|
CardCharge
|
while something is left, |
|
CardCharge
|
states the Mercado Pago sandbox reported. |
Raises:
| Type | Description |
|---|---|
KeyError
|
When no charge carries that id. |
ValueError
|
When the charge is not |
BaseException
|
Whatever :meth: |
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: |
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
¶
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 |
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
¶
Every object in the default bucket, by key.
Returns:
| Type | Description |
|---|---|
Mapping[str, bytes]
|
Mapping[str, bytes]: A read-only view. |
bucket_objects
¶
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
¶
Make the store refuse to delete keys.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*keys
|
str
|
Keys to refuse. |
()
|
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: |
'application/octet-stream'
|
metadata
|
dict[str, str] | None
|
User metadata, reported back
by :meth: |
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: |
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
|
|
None
|
as_attachment
|
bool | None
|
Download or |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
|
str
|
plus the overrides. |
Raises:
| Type | Description |
|---|---|
BaseException
|
Whatever :meth: |
ValueError
|
When |
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 |
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
|
|
PresignedPost
|
|
Raises:
| Type | Description |
|---|---|
BaseException
|
Whatever :meth: |
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
|
|
Raises:
| Type | Description |
|---|---|
BaseException
|
Whatever :meth: |
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: |
ObjectStat
|
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
When |
BaseException
|
Whatever :meth: |
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 |
None
|
Returns:
| Type | Description |
|---|---|
AsyncIterator[bytes]
|
AsyncIterator[bytes]: Chunks of at most |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
FileNotFoundError
|
When |
BaseException
|
Whatever :meth: |
list_objects
async
¶
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: |
remove_object
async
¶
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: |
BaseException
|
Whatever :meth: |
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 |
list[ObjectDeleteError]
|
meth: |
Raises:
| Type | Description |
|---|---|
BaseException
|
Whatever :meth: |
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: |
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: |
Raises:
| Type | Description |
|---|---|
BaseException
|
Whatever :meth: |
FakeTextBackend
¶
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: |
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
|
queue
¶
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: |
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: |
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
¶
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 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: |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
StructuredT |
StructuredT
|
The next queued instance. |
Raises:
| Type | Description |
|---|---|
BaseException
|
Whatever :meth: |
LookupError
|
When nothing is queued. |
TypeError
|
When the queued instance is not a |
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 |
required |
schema
|
type[StructuredT]
|
The schema the reply must be. |
required |
system
|
str | None
|
Recorded as a |
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: |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
StructuredT |
StructuredT
|
The next queued instance. |
Raises:
| Type | Description |
|---|---|
BaseException
|
Whatever :meth: |
LookupError
|
When nothing is queued. |
TypeError
|
When the queued instance is not a |
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
|
|
messages |
list[dict[str, Any]]
|
The turns the real generator would
post — for |
schema |
type[BaseModel]
|
The schema the caller asked for. |
config |
GenerationConfig | None
|
The |
think |
ThinkLevel | None
|
The |
truncate |
bool | None
|
The |
options |
dict[str, Any]
|
Every other keyword argument. |
FakeModerationBackend
¶
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.99
|
flag
¶
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: |
FakePushDispatcher
¶
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: |
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
¶
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: |
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
¶
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: |
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 |
reply_to |
str | None
|
Reply-To, when set. |
from_addr |
str | None
|
Per-message sender override, when set. |
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
|
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 |
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: |
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
|
|
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: |
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: |
zoom |
int
|
Default map zoom level. |
depth |
int
|
Default pagination depth. |
lang |
str
|
Default language code. |
max_time_seconds |
int
|
Default server-side |
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_calls |
list[tuple[Coordinate, tuple[str, ...], int]]
|
Every
|
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: |
()
|
zoom
|
int
|
Default zoom level (1-21). Defaults to |
15
|
depth
|
int
|
Default pagination depth (>= 1). Defaults to |
1
|
lang
|
str
|
Default language code. Defaults to |
'pt'
|
max_time_seconds
|
int
|
Default server-side |
MIN_GMAPS_MAX_TIME_SECONDS
|
poll_seconds
|
float
|
Default polling interval in seconds (> 0).
Defaults to |
2.0
|
wait_seconds
|
float
|
Default wait deadline in seconds (> 0).
Defaults to |
600.0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When any default parameter is out of range or
|
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
|
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 ( |
800
|
zoom
|
int
|
Map zoom level between |
15
|
depth
|
int
|
Pagination depth ( |
1
|
lang
|
str
|
Language code sent to Google Maps. Defaults to
|
'pt'
|
max_time_seconds
|
int
|
Server-side job timeout in seconds
( |
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 ( |
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 |
None
|
poll_seconds
|
float | None
|
Optional poll interval override
( |
None
|
wait_seconds
|
float | None
|
Optional wait deadline override
( |
None
|
Returns:
| Type | Description |
|---|---|
list[PlaceSchema]
|
list[PlaceSchema]: Registered places within |
Raises:
| Type | Description |
|---|---|
ValueError
|
When any parameter violates the real client's rules. |
BaseException
|
Whatever :meth: |
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 ( |
800
|
included_types
|
Sequence[str] | None
|
Optional search keywords for
this call; falls back to :attr: |
None
|
Returns:
| Type | Description |
|---|---|
list[PlaceSchema]
|
list[PlaceSchema]: Registered places within |
Raises:
| Type | Description |
|---|---|
ValueError
|
When neither |
BaseException
|
Whatever :meth: |
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 |
bbox_queries |
list[BoundingBox]
|
Every bounding box passed to
:meth: |
tag_queries |
list[str]
|
Every |
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
¶
Register raw OSM tags for a given osm_id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
osm_id
|
str
|
Canonical OSM identifier (e.g. |
required |
tags
|
Mapping[str, str]
|
Tag mapping returned by
:meth: |
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]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
BaseException
|
Whatever :meth: |
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: |
180
|
Returns:
| Type | Description |
|---|---|
list[PlaceSchema]
|
list[PlaceSchema]: Places contained within |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
BaseException
|
Whatever :meth: |
fetch_tags
async
¶
Return registered OSM tags for osm_id, or an empty dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
osm_id
|
str
|
Canonical OSM identifier (e.g. |
required |
timeout_s
|
int
|
Timeout parameter matching
:meth: |
30
|
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
dict[str, str]: Copy of the registered tag mapping, or |
dict[str, str]
|
none was registered. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
BaseException
|
Whatever :meth: |
FakeRoutingBackend
¶
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: |
'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: |
Raises:
| Type | Description |
|---|---|
BaseException
|
Whatever :meth: |
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: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If fewer than two points are given. |
BaseException
|
Whatever :meth: |
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
|
mode
|
TravelModeEnum
|
How it travels. |
CAR
|
Returns:
| Name | Type | Description |
|---|---|---|
DistanceMatrix |
DistanceMatrix
|
One cell per pair, |
DistanceMatrix
|
attr: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
BaseException
|
Whatever :meth: |
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]
|
|
list[SearchResult]
|
an empty result set is a valid search, not an error. |
Raises:
| Type | Description |
|---|---|
BaseException
|
Whatever :meth: |
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 |
Start with empty records and zero counters.
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 ( |
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 |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
LinkedInPostResultSchema |
LinkedInPostResultSchema
|
Synthetic post result with |
LinkedInPostResultSchema
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When inputs fail :class: |
BaseException
|
Whatever :meth: |
upload_image
async
¶
Record an image upload and return a synthetic urn:li:image:... URN.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
owner_urn
|
str
|
Owner URN ( |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
BaseException
|
Whatever :meth: |
delete_post
async
¶
Record a post deletion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
post_urn
|
str
|
Post URN to delete. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
BaseException
|
Whatever :meth: |
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
¶
One image upload recorded by :class:FakeLinkedInClient.
Attributes:
| Name | Type | Description |
|---|---|---|
image_urn |
str
|
Synthetic |
owner_urn |
str
|
Validated owner URN passed to |
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 onX-Idempotency-Key: the same key with the same body replays the first answer, with another body answers409 idempotency_key_already_used.GET /v1/orders/{id}—404for an id it never created.POST /v1/orders/{id}/cancel— anaction_requiredorder.POST /v1/orders/{id}/capture— awaiting_capturecard order.POST /v1/orders/{id}/refund— aprocessedorder, 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]]
|
|
Start with no orders.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
webhook_secret
|
str
|
Signs every delivery the transitions
return. Defaults to :data: |
FAKE_WEBHOOK_SECRET
|
clock
|
Callable[[], datetime] | None
|
Source of |
None
|
order_ids
property
¶
Every order id created, oldest first.
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: The ids. |
order
¶
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
¶
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 |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
|
str
|
of the most recent order created with that |
|
str
|
|
|
str
|
reference again after an expiry means the new order. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If no order has that id or that |
decline_next_card
¶
Make the next card create answer 402 with a failed order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
status_detail
|
str
|
The payment's |
'rejected_by_issuer'
|
lose_next_answer
¶
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
¶
Wrap this handler in an httpx transport.
Returns:
| Type | Description |
|---|---|
MockTransport
|
httpx.MockTransport: Pass it as |
MockTransport
|
|
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.
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
HTTPClient |
HTTPClient
|
The client, over :meth: |
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 |
None
|
request_id
|
str | None
|
The |
None
|
ts
|
int | None
|
The signature's timestamp in seconds; now when
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
MercadoPagoDelivery |
MercadoPagoDelivery
|
Signed with :attr: |
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 |
required |
Returns:
| Name | Type | Description |
|---|---|---|
MercadoPagoDelivery |
MercadoPagoDelivery
|
|
MercadoPagoDelivery
|
func: |
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 |
required |
Returns:
| Name | Type | Description |
|---|---|---|
MercadoPagoDelivery |
MercadoPagoDelivery
|
|
MercadoPagoDelivery
|
live, on a canceled order whose |
|
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 |
required |
status_detail
|
str
|
The payment's |
'rejected_by_issuer'
|
Returns:
| Name | Type | Description |
|---|---|---|
MercadoPagoDelivery |
MercadoPagoDelivery
|
|
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 |
required |
Returns:
| Name | Type | Description |
|---|---|---|
MercadoPagoDelivery |
MercadoPagoDelivery
|
|
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 |
required |
Returns:
| Name | Type | Description |
|---|---|---|
MercadoPagoDelivery |
MercadoPagoDelivery
|
|
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 |
required |
amount_cents
|
int | None
|
Cents to refund; |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
MercadoPagoDelivery |
MercadoPagoDelivery
|
|
MercadoPagoDelivery
|
|
|
MercadoPagoDelivery
|
live). |
Raises:
| Type | Description |
|---|---|
KeyError
|
If no such order was created. |
ValueError
|
If the order is not |
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
|
|
required |
amount_cents
|
int | None
|
For |
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 — |
headers |
dict[str, str]
|
|
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 |
timestamp |
str
|
The |
url
¶
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
|
|
send
async
¶
Post this delivery with an async client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
AsyncClient
|
Any async client — one over
|
required |
endpoint
|
str
|
The webhook route. |
required |
Returns:
| Type | Description |
|---|---|
Response
|
httpx.Response: What the route answered. |
send_sync
¶
Post this delivery with a sync client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
Client
|
Any sync client, |
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 |
required |
secret
|
str
|
The webhook secret the receiving service verifies with. |
required |
action
|
str | None
|
The body's |
None
|
request_id
|
str | None
|
The |
None
|
ts
|
int | None
|
The signature's timestamp, in seconds since the
epoch. |
None
|
live_mode
|
bool
|
The body's |
False
|
application_id
|
str
|
The body's |
FAKE_APPLICATION_ID
|
user_id
|
str
|
The body's |
FAKE_USER_ID
|
Returns:
| Name | Type | Description |
|---|---|---|
MercadoPagoDelivery |
MercadoPagoDelivery
|
The delivery. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the order carries no id, or |
order_action
¶
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, whoseWebhookNotification.actionlists onlyorder.createdandorder.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
|
|
str
|
no status. |
FAKE_WEBHOOK_SECRET
module-attribute
¶
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 byexternal_reference(:meth:FakeMercadoPagoOrdersAPI.find_order_id);404when 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, sotempest mercado-pago simulate-webhook(or the simulation routes ofmake_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
¶
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 |
Initialize an empty fake client with no seeded responses or errors.
enqueue_items
¶
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
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
set_actor_items
¶
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, |
required |
items
|
Sequence[Mapping[str, JsonValue]]
|
Dataset items returned
on every call to |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
set_actor_error
¶
Configure (or clear) a persistent error raised for actor_id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
actor_id
|
str
|
Apify actor ID, |
required |
error
|
BaseException | None
|
Exception to raise for every call to
|
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
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, |
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]]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
BaseException
|
Whatever was queued via :meth: |
ApifyActorCall
dataclass
¶
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 |
persistent |
bool
|
Whether sends generate sequential outbox ids and
deduplicate by |
id_prefix |
str
|
Prefix for generated outbox ids (default |
media |
dict[str, bytes]
|
Map from WhatsApp |
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: |
QUEUED
|
persistent
|
bool
|
When |
True
|
media
|
Mapping[str, bytes] | None
|
Initial mapping of
|
None
|
id_prefix
|
str
|
Prefix for generated outbox ids (for example
|
'out-'
|
set_media
¶
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 |
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 ( |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
BaseException
|
Whatever :meth: |
get_message_media
async
¶
Return seeded media bytes for message_id or raise 404.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message_id
|
str
|
The WhatsApp message id ( |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bytes |
bytes
|
The raw bytes stored under |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
HTTPStatusError
|
A |
BaseException
|
Whatever :meth: |
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: |
to |
str
|
Recipient phone digits, copied from |
text |
str
|
Message body, copied from |
reply_to |
str | None
|
Quoted WhatsApp message id, copied from
|
idempotency_key |
str | None
|
The idempotency key passed to
|
outbound_id |
str | None
|
The |
status |
AcceptedResponseStatus | None
|
The |
sign_zap_webhook
¶
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
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 |
'msg-1'
|
from_
|
str
|
Raw sender JID ( |
_DEFAULT_JID
|
chat_key
|
str | None
|
Resolved recipient phone digits, or |
_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
|
media_url
|
str | None
|
Gateway media path/URL, or |
None
|
timestamp
|
datetime | None
|
Message timestamp. Defaults to a fixed UTC timestamp for deterministic tests. |
None
|
event
|
ZapWebhookEventEnum
|
Webhook event name. Defaults to
:attr: |
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 |
'out-1'
|
status
|
AcceptedResponseStatus
|
Reported delivery status. Defaults to
:attr: |
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: |
TEXT
|
wa_message_id
|
str | None
|
WhatsApp message id, when known. |
None
|
error
|
str | None
|
Failure reason, typically set when |
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 |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
ZapStatusCallback |
ZapStatusCallback
|
Validated status callback schema. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |