Testing#
TestSqsBroker runs the broker in process, with no AWS service behind it. It takes either broker
class and needs neither backend's network.
@pytest.mark.asyncio()
async def test_bill_publishes_a_shipment() -> None:
async with TestSqsBroker(broker) as br:
await br.publish({"id": 1}, SnsTopic("orders"))
bill.mock.assert_called_once_with({"id": 1})
ship.mock.assert_called_once_with({"order_id": 1})
The service under test:
from faststream import FastStream
from faststream_sqs_sns import CapoSqsBroker, SnsTopic, SqsQueue
broker = CapoSqsBroker(region="eu-central-1")
app = FastStream(broker)
shipments = broker.publisher("shipments")
@broker.subscriber(SqsQueue("orders-billing", declare=True), topic=SnsTopic("orders"))
@shipments
async def bill(order: dict[str, int]) -> dict[str, int]:
return {"order_id": order["id"]}
@broker.subscriber("shipments")
async def ship(shipment: dict[str, int]) -> None: ...
@broker.subscriber("orders")
async def handle(order: dict[str, int]) -> None: ...
A publish reaches the handlers directly. handler.mock records the decoded body of each call,
and the handler's reply reaches the subscribers of its queue.
Routing#
The test broker routes the way SQS and SNS do:
- A queue publish reaches one subscriber of that queue.
- When several subscribers read one queue, they take the messages in turn.
- A topic publish fans out to every queue whose subscriber names the topic with
topic=. - A subscriber read by
get_one()or iteration keeps what is published until it is read. - A batch subscriber gets the messages the way one receive would bring them.
- Ack, nack and reject are recorded on the message. Nothing is redelivered and the receive count
is 1. A
delayis recorded and the message is delivered at once.
Validation#
A publish the service would reject raises SqsServiceError with the service's error code. The
test broker checks the sizes of a message and a batch, attribute names, values and count,
group and deduplication ids, queue and topic names, the FIFO rules and the delay range. The body
and attribute encoding is the one the real producer uses, so base64 bodies run in the test.
@pytest.mark.asyncio()
async def test_a_rejected_publish_raises() -> None:
async with TestSqsBroker(broker) as br:
with pytest.raises(SqsServiceError) as error:
await br.publish({"id": 1}, "orders", delay=1000)
assert error.value.code == "InvalidParameterValue"
Destinations nobody declared#
The test broker does not check topology the service did not declare. A publish to a queue or a topic that no subscriber or publisher of the app names succeeds, and so does a read of a queue nobody created.
@pytest.mark.asyncio()
async def test_a_destination_nobody_declared_is_accepted() -> None:
async with TestSqsBroker(broker) as br:
await br.publish({"id": 1}, "nobody-reads-this")
await br.publish({"id": 1}, SnsTopic("nobody-subscribed"))
A test that must prove a queue exists, or that a policy lets SNS write to it, runs against LocalStack.