Skip to content

Test outbound requests

Use a fake when you want to run your own controller, command or service and control what the external API returns. Orionis prepares and validates the request as usual, then routes it to a fixture in the current async context. Configure the catalog profile before starting Reactor, even when all responses will be simulated.

Save this in tests/test_catalog.py. From the project root run python -B reactor test with the project environment active. This test checks that creating a product sends the correct JSON to /products and that the application can read the ID from a 201 Created response.

import json
from orionis.support.facades import Http
from orionis.test import TestCase
class TestCatalog(TestCase):
async def test_create_product(self) -> None:
catalog = Http.client("catalog").acceptJson()
url = "https://catalog.example.com/products"
product = {"sku": "NB-42", "name": "Notebook", "stock": 8}
fixtures = {("POST", url): Http.response({"data": {"id": 42}}, status=201)}
async with Http.fake(fixtures) as fake:
result = await catalog.post("/products", json=product)
self.assertEqual(result.status(), 201)
self.assertEqual(result.throw().json("data.id"), 42)
fake.assertSentCount(1)
fake.assertSent(
lambda req: req.method == "POST"
and req.url == url
and req.client == "catalog"
and json.loads(req.body) == product
)

Http.response(...) prepares the fixture and async with Http.fake(fixtures) activates it. await catalog.post(...) returns a ClientResponse that you read as you would in production. The block intercepts sends from a client built before entering it, including sends made through an IHttpManager injected by the same application.

Use a tuple (method, absolute_url) as the key. The fake uppercases the method and looks up the final URL exactly, including the encoded query and the order of repeated parameters. A relative path, a different port or an extra parameter will miss. Fixture keys do not accept wildcards or request callbacks. Headers and bodies can be verified with an assertion.

fake.assertSent(predicate) calls a synchronous predicate with a prepared request and succeeds if at least one recorded attempt matches. The record exposes method, url, client, ordered headers, serialized body (bytes or None), timeouts and max_response_bytes. For headers compare names case-insensitively, for example any(k.lower() == "accept" and v == "application/json" for k, v in req.headers). Use dummy credentials in tests because the prepared fields include the final headers. fake.assertSentCount(n) checks the exact number of attempts; use both assertions when only one send should occur.

A missing fixture raises HttpFakeException inside the block and records the attempted request. A destination rejected before transport does not reach the fake. This test would also catch an unintended outbound attempt.

from orionis.http.client.exceptions import HttpDestinationException
from orionis.support.facades import Http
from orionis.test import TestCase
class TestDestination(TestCase):
async def test_requires_allowed_origin(self) -> None:
async with Http.fake({}) as fake:
with self.assertRaises(HttpDestinationException):
await Http.get("https://unlisted.example.com/products")
fake.assertSentCount(0)

Return the representation your application expects

Section titled “Return the representation your application expects”
Fixture valueHow the application sees it
Http.response({"id": 42}, status=201)UTF-8 JSON, status 201 and default Content-Type: application/json. Lists, finite JSON numbers, booleans and None are JSON too.
Http.response("ready", headers={"Content-Type": "text/plain"})UTF-8 text that you can read with text(). Strings are encoded verbatim. For a JSON string literal, supply its serialized bytes, e.g. b'"ready"'.
Http.response(b"\xff", headers={"Content-Type": "application/octet-stream"})Exactly those bytes for body(). Use raw bytes for invalid JSON, binary data or non-UTF-8 text.
Http.response(status=204)Successful empty response. Status defaults to 200; the accepted fixture status range is 100–599.
Http.response(headers=[("X-Tag", "a"), ("X-Tag", "b")])Two distinct headers in order; headerValues("x-tag") returns both.
Http.response({"error": "busy"}, status=503)A normal 503 response. Your application decides whether to branch on the status or call throw().
HttpTimeoutException("read") as the outcomeThe await raises that exception. Any instance of HttpClientException can be an outcome.

The usual body reader also processes fixture data. For example, Http.response(b"ab", headers={"Content-Length": "4"}) on GET produces HttpTransportException with category protocol. A body above the configured size limit still fails. A simulation exercises application behavior; real DNS, TLS negotiation, socket reuse and network timing require a controlled endpoint.

Return a sequence and exercise failure paths

Section titled “Return a sequence and exercise failure paths”

A single outcome is reusable for that key. A list or tuple provides one outcome per attempt in order. Exhausting it raises HttpFakeException. Here three explicit calls simulate a timeout, a recovery and an unexpected extra send. Configure a response status when the remote server replies; configure an exception when the caller should receive no response.

from orionis.http.client.exceptions import HttpFakeException, HttpTimeoutException
from orionis.support.facades import Http
from orionis.test import TestCase
class TestAvailability(TestCase):
async def test_two_separate_calls(self) -> None:
key = ("GET", "https://catalog.example.com/products/42")
catalog = Http.client("catalog")
outcomes = [HttpTimeoutException("read"), Http.response({"id": 42})]
async with Http.fake({key: outcomes}) as fake:
with self.assertRaises(HttpTimeoutException) as first:
await catalog.get("/products/42")
self.assertEqual(first.exception.phase, "read")
result = await catalog.get("/products/42")
self.assertEqual(result.json("id"), 42)
with self.assertRaises(HttpFakeException):
await catalog.get("/products/42")
fake.assertSentCount(3)

Each fake has its own fixtures and recorded attempts. Entering another scope temporarily replaces the outer scope for that task. When the inner scope exits, the same builder uses the outer fixtures again.

from orionis.support.facades import Http
async def check_isolated_prices() -> None:
key = ("GET", "https://catalog.example.com/products/42")
catalog = Http.client("catalog")
async with Http.fake({key: Http.response({"price": 8})}) as outer:
async with Http.fake({key: Http.response({"price": 10})}) as inner:
assert (await catalog.get("/products/42")).json("price") == 10
inner.assertSentCount(1)
assert (await catalog.get("/products/42")).json("price") == 8
outer.assertSentCount(1)

Child tasks inherit the current fake. Concurrent tasks can open separate fakes to keep their histories independent. Await tasks that should use a fake before exiting its block: a child that inherited an expired fake receives HttpClosedException. Assertions can inspect the recorded attempts after exit. Responses and errors · Concurrency and lifecycle