A fake of an HTTP service that handles intercepted requests.
See Loopback.HTTPFake.Router for a more convenient way to write fakes.
use Loopback.HTTPFake makes a module a GenServer with one more callback,
handle_request/2, which handles the intercepted requests. The :match option
generates the matches?/1 function, which matches the request's URL against a string,
a regex, or a list of them. For more complex matching, for example on the method or
headers, define matches?/1 manually. The fake also gets a whereis!/0 function
that returns the PID of the fake.
For example, a fake with a helper that simulates an outage:
defmodule ExampleApiFake do
use Loopback.HTTPFake, match: "example.com"
# A helper for tests.
def trigger_downtime do
GenServer.call(whereis!(), :downtime)
end
@impl true
def init(_opts) do
{:ok, %{up?: true}}
end
@impl true
def handle_request(_request, state) do
status = if state.up?, do: 200, else: 503
{:reply, Loopback.HTTPResponse.json(status, %{}), state}
end
@impl true
def handle_call(:downtime, _from, state) do
{:reply, :ok, %{state | up?: false}}
end
endOptions
:match- a string, a regex, or a list of them. It generates amatches?/1that returnstruefor the requests whose URL contains any of the strings or matches any of the regexes. Without this option, implementingmatches?/1is required.
Other options customize the generated child_spec/1, like with use GenServer.
Summary
Callbacks
Handles a request within the fake's process.
Decides whether the fake handles the request.
Types
@type reply() :: %Loopback.HTTPResponse{body: term(), headers: term(), status: term()} | %Loopback.HTTPError{reason: term()} | :passthrough
A fake's reply to a request:
- a
Loopback.HTTPResponse- the response, with any status, so both success and error responses like 404 or 500. - a
Loopback.HTTPError- a transport error, likeLoopback.HTTPError.timeout(). :passthrough- the request should be sent to the real service.
@type request() :: %Loopback.HTTPRequest{ body: term(), headers: term(), method: term(), url: term() }
An intercepted request.
Callbacks
@callback handle_request(request(), state :: term()) :: {:reply, reply(), new_state} | {:reply, reply(), new_state, timeout() | :hibernate | {:continue, term()}} | {:stop, reason :: term(), reply(), new_state} when new_state: term()
Handles a request within the fake's process.
Like GenServer.handle_call/3, it returns {:reply, reply, new_state} or another of
its results that includes a reply. The reply is a response, a transport error or
:passthrough, see reply/0. If it raises, the fake crashes and the process making
the request exits, so errors that the fake simulates on purpose should be replies.
Decides whether the fake handles the request.
It's generated if the :match option is provided. It's called in the process making the
request, so it can't use the fake's state.