Testing#
TestPubSubBroker runs the broker in process, with no Pub/Sub service behind it.
@pytest.mark.asyncio()
async def test_bill_publishes_a_shipment() -> None:
async with TestPubSubBroker(broker) as br:
await br.publish({"id": 1}, "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_gcp_pubsub import PubSub, PubSubBroker, PubSubTopic
broker = PubSubBroker(project_id="faststream-test")
app = FastStream(broker)
shipments = broker.publisher(PubSubTopic("shipments", declare=True))
@broker.subscriber(PubSub("orders-billing", declare=True), topic="orders")
@shipments
async def bill(order: dict[str, int]) -> dict[str, int]:
return {"order_id": order["id"]}
@broker.subscriber(PubSub("shipments-courier", declare=True), topic="shipments")
async def ship(shipment: 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 topic.
Routing#
The test broker routes the way the service does:
- A topic delivers to every subscription attached to it.
- The consumers of one subscription share its messages, in turn.
- A subscription read by
get_one()or iteration keeps what is published until it is read. - Ack, nack and reject settle the message once: each message reaches its handler one time.
A declaration always succeeds, and a publish reaches whichever subscriptions the service declares for its topic.
Validation#
A publish the service would reject raises the service's InvalidArgument: attribute names and
sizes, the ordering key size, message and request size, and the resource id format.
@pytest.mark.asyncio()
async def test_a_rejected_publish_raises() -> None:
async with TestPubSubBroker(broker) as br:
with pytest.raises(InvalidArgument):
await br.publish({"id": 1}, "orders", ordering_key="k" * 2000)
Against the emulator#
with_real=True runs the same test against a real service, such as the
emulator. Declare the resources the service uses with
declare=True, as the example service does.
@pytest.mark.gcp()
@pytest.mark.asyncio()
async def test_bill_with_the_emulator() -> None:
async with TestPubSubBroker(broker, with_real=True) as br:
await br.publish({"id": 1}, "orders")
await bill.wait_call(10)
bill.mock.assert_called_once_with({"id": 1})
Mark such tests gcp and run them with just test-gcp while the emulator is up.