Sample
req 0.7.2: Stub HTTP responses for Elixir code that uses Req, with no network, no fake server process and no mocking library
Verified sample for hex req 0.7.2: Stub HTTP responses for Elixir code that uses Req, with no network, no fake server process and no mocking library. The…
sha256:1a5be8dc134928a8238887f9504e70f60f67fb5fa956fd3fc577d86784ecfa1d
This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured.
How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people.
MIT-0
Execution evidence
The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.
- Evidence basis
- Signed contract pass
- Verification receipts
- 1
- Signing keys that built it
- 1
Declared environment
elixir 1 linux x64 elixir 1 elixir mix
Verification-run environments
| Environment | Contract | Stages | Run |
|---|---|---|---|
| elixir 1 · linux alpine/x64 · docker ed25519:a2ec939a4c60e243 | PASS | compile:PASS · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · hex@1 |
2026-08-14 |
Case
HOW- Goal
- Stub HTTP responses for Elixir code that uses Req, with no network, no fake server process and no mocking library
- Packages
- Symbols
-
- Req.Test.stub
- Req.Test.expect
- Req.Test.verify!
- Req.Test.json
- Req.Test.transport_error
- Req.Plug
- Req.Steps.decode_body
- Req.Steps.retry
- Req.Steps.handle_http_errors
- Req.request!
- Req.TransportError
- Plug.Conn.send_resp
- Environment
- elixir 1
- Created
- 2026-08-14T20:15:02Z
Contract
- assert the response content-type is what decodes the body, so a stub built with Req.Test.json hands the caller a map and no .json() accessor is called anywhere, and that headers are a map of lists where a missing header reads as nil
- assert the same JSON bytes sent with Plug.Conn.send_resp and no content-type stay a binary, so a clean HTTP 200 stops matching the caller's %{"celsius" => _} clause
- assert that with no content-type the request URL path decides instead: /data.json is decoded while /data and /data.txt are not, because decode_body falls back to application/octet-stream and resolves that through MIME.from_path
- assert an HTTP 500 is {:ok, response} and raises from neither Req.request/1 nor Req.request!/1, that the error body is decoded like any other body, and that http_errors: :raise reports the body still undecoded because handle_http_errors runs ahead of decode_body
- assert retry is on by default: one 500 on GET calls the stub four times (the initial request plus max_retries 3), the same 500 on POST calls it once because :safe_transient covers GET and HEAD only, and retry: :transient opts POST in
- assert Req.Test.transport_error produces {:error, %Req.TransportError{}} rather than a response, which a queue of canned responses cannot express, and that Req.get! raises it
- assert expectations are consumed in order ahead of a stub whatever the registration order, and that once drained Req.Test falls through to the stub instead of failing
- assert an exhausted expectation with no stub raises "no mock or stub for X" while a name never registered raises the different "cannot find mock/stub X in process #PID<...>"
- assert an unmet expectation fails nothing until Req.Test.verify! is called, and that verify! then names how many more uses were expected
- assert JSON decoding is switched off by decode_body: false, decoders: false or raw: true, that :decoders replaces the default [:json, :json_api] rather than extending it, and that a codec under :decoders is the 0.7.0 replacement for the deprecated :decode_json
- assert Req.Test implements the Plug behaviour and the stub name is literally that plug's options, so a bare function plug stubs HTTP with no registry at all
Files
- csx.json
- lib/csx_req/weather.ex
- mix.exs
- mix.lock
- test/contract_test.exs
- test/test_helper.exs
Source
{"buildCommand":["mix","deps.compile","--no-deps-check"],"case":{"caseId":"case:sha256:9c5c162cfef516bde95542fc5e44a501e30a7954c5e57ba5501fdf8985a88f42","constraints":{"runtime":"elixir"},"contract":["assert the response content-type is what decodes the body, so a stub built with Req.Test.json hands the caller a map and no .json() accessor is called anywhere, and that headers are a map of lists where a missing header reads as nil","assert the same JSON bytes sent with Plug.Conn.send_resp and no content-type stay a binary, so a clean HTTP 200 stops matching the caller's %{\"celsius\" =\u003e _} clause","assert that with no content-type the request URL path decides instead: /data.json is decoded while /data and /data.txt are not, because decode_body falls back to application/octet-stream and resolves that through MIME.from_path","assert an HTTP 500 is {:ok, response} and raises from neither Req.request/1 nor Req.request!/1, that the error body is decoded like any other body, and that http_errors: :raise reports the body still undecoded because handle_http_errors runs ahead of decode_body","assert retry is on by default: one 500 on GET calls the stub four times (the initial request plus max_retries 3), the same 500 on POST calls it once because :safe_transient covers GET and HEAD only, and retry: :transient opts POST in","assert Req.Test.transport_error produces {:error, %Req.TransportError{}} rather than a response, which a queue of canned responses cannot express, and that Req.get! raises it","assert expectations are consumed in order ahead of a stub whatever the registration order, and that once drained Req.Test falls through to the stub instead of failing","assert an exhausted expectation with no stub raises \"no mock or stub for X\" while a name never registered raises the different \"cannot find mock/stub X in process #PID\u003c...\u003e\"","assert an unmet expectation fails nothing until Req.Test.verify! is called, and that verify! then names how many more uses were expected","assert JSON decoding is switched off by decode_body: false, decoders: false or raw: true, that :decoders replaces the default [:json, :json_api] rather than extending it, and that a codec under :decoders is the 0.7.0 replacement for the deprecated :decode_json","assert Req.Test implements the Plug behaviour and the stub name is literally that plug's options, so a bare function plug stubs HTTP with no registry at all"],"goal":"Stub HTTP responses for Elixir code that uses Req, with no network, no fake server process and no mocking library","kind":"HOW","packages":["pkg:hex/req@0.7.2","pkg:hex/plug@1.20.3","pkg:hex/jason@1.4.5"],"schemaVersion":1,"symbols":["Req.Test.stub","Req.Test.expect","Req.Test.verify!","Req.Test.json","Req.Test.transport_error","Req.Plug","Req.Steps.decode_body","Req.Steps.retry","Req.Steps.handle_http_errors","Req.request!","Req.TransportError","Plug.Conn.send_resp"]},"contractCommand":["mix","test","--no-deps-check"],"environment":{"arch":"x64","ecosystem":"hex","executionContext":"elixir","language":"elixir","os":"linux","packageManager":"mix","runtime":"elixir","runtimeVersion":"1","schemaVersion":1},"license":"MIT-0","packages":["pkg:hex/req@0.7.2","pkg:hex/plug@1.20.3","pkg:hex/jason@1.4.5"],"schemaVersion":1,"symbols":["Req.Test.stub","Req.Test.expect","Req.Test.verify!","Req.Test.json","Req.Test.transport_error","Req.Plug","Req.Steps.decode_body","Req.Steps.retry","Req.Steps.handle_http_errors","Req.request!","Req.TransportError","Plug.Conn.send_resp"],"verifierAdapter":"hex@1"}
defmodule CsxReq.Weather do
@moduledoc """
Production code that calls an HTTP JSON API, written so a test can replace
the network without editing this file.
The only test seam is the `:req_options` application env: empty in
production (or carrying the API key), and in tests carrying
`plug: {Req.Test, CsxReq.Weather}`. That tuple is a plug: `Req.Test` itself
implements the Plug behaviour, and the second element is the *name* a stub
is registered under. `Req.Test.call/2` looks the name up in an ownership
registry keyed by the calling process — the same model Mox uses — which is
why several `async: true` tests can register different stubs under the same
name at once.
Look at what `get_rating/1` matches on: `body: %{"celsius" => celsius}`, an
already-decoded map. Nothing here calls a `.json()` accessor, and that is
the difference from httpx's MockTransport or Guzzle's MockHandler. Req's
`decode_body` response step decodes the body from the *response*
content-type, so `Req.Test.json/2` in the stub is what makes this clause
match. Send the same bytes without a content-type, or set
`decode_body: false`, and `body` is a binary, this clause does not match,
and `get_rating/1` returns `:error` for what is still a clean HTTP 200.
"""
@doc """
Classifies the current temperature, or `:error` if the call did not produce
a 200 with a decoded JSON object.
"""
def get_rating(location) do
case get_temperature(location) do
{:ok, %{status: 200, body: %{"celsius" => celsius}}} ->
cond do
celsius < 18.0 -> {:ok, :too_cold}
celsius < 30.0 -> {:ok, :nice}
true -> {:ok, :too_hot}
end
_ ->
:error
end
end
@doc """
Returns `{:ok, %Req.Response{}}` or `{:error, exception}`.
An HTTP 500 is `{:ok, response}`: `Req.request/1` only returns `:error` for
things that stopped the exchange happening at all, such as a transport
error. `:http_errors` is the option that changes that, and its default is
`:return`.
"""
def get_temperature(location, overrides \\ []) do
[base_url: "https://weather.example.com", params: [location: location]]
|> Keyword.merge(Application.get_env(:csx_req, :req_options, []))
|> Keyword.merge(overrides)
|> Req.request()
end
end
defmodule CsxReq.MixProject do
use Mix.Project
def project do
[
app: :csx_req,
version: "0.1.0",
elixir: "~> 1.15",
deps: deps()
]
end
def application, do: [extra_applications: []]
defp deps do
# Req.Test ships inside req itself, so stubbing HTTP needs no extra test
# library and no fake server process. What it does need is plug, and plug
# is where people get caught: req declares it `optional: true`, and both
# Req.Plug and every Req.Test helper are wrapped in
# `if Code.ensure_loaded?(Plug)` evaluated at req's compile time. Leave
# plug out of your deps and nothing fails to compile — you get a runtime
# `raise "missing plug dependency"` from inside the stub instead. So plug
# is listed here explicitly even though no line of this project calls it
# directly except Plug.Conn.send_resp in the stubs.
#
# jason arrives as a hard dependency of req and is req's built-in JSON
# codec. It is named here too because req 0.7.0 deprecated
# `decode_json: opts` in favour of `decoders: [json: &Jason.decode(&1,
# opts)]`, which puts Jason in your own source and therefore in your own
# deps.
[{:req, "0.7.2"}, {:plug, "1.20.3"}, {:jason, "1.4.5"}]
end
end
%{
"finch": {:hex, :finch, "0.23.0", "e3f9287ac25a8832f848b144c2b57346aac65b205e2e0629a52adfe6507fd837", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:mint, "~> 1.8", [hex: :mint, repo: "hexpm", optional: false]}, {:nimble_options, "~> 0.4 or ~> 1.0", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:nimble_pool, "~> 1.1", [hex: :nimble_pool, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "80e58d3f936f57e3fdf404f83a3642897ae6d9fb642934e46da4d8fe761b99d5"},
"hpax": {:hex, :hpax, "1.0.4", "777de5d433b0fbdc7c418159c8055910faa8047ffdb3d6b31098d2a46cd7685c", [:mix], [], "hexpm", "afc7cb142ebcc2d01ce7816190b98ce5dd49e799111b24249f3443d730f377ca"},
"jason": {:hex, :jason, "1.4.5", "2e3a008590b0b8d7388c20293e9dcc9cf3e5d642fd2a114e4cbbb52e595d940a", [:mix], [{:decimal, "~> 1.0 or ~> 2.0 or ~> 3.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "b0c823996102bcd0239b3c2444eb00409b72f6a140c1950bc8b457d836b30684"},
"mime": {:hex, :mime, "2.0.7", "b8d739037be7cd402aee1ba0306edfdef982687ee7e9859bee6198c1e7e2f128", [:mix], [], "hexpm", "6171188e399ee16023ffc5b76ce445eb6d9672e2e241d2df6050f3c771e80ccd"},
"mint": {:hex, :mint, "1.9.3", "3337184d69179695c7a9f1714d92c11e629d36c8c037a21cf490131d3d150554", [:mix], [{:castore, "~> 0.1.0 or ~> 1.0", [hex: :castore, repo: "hexpm", optional: true]}, {:hpax, "~> 0.1.1 or ~> 0.2.0 or ~> 1.0", [hex: :hpax, repo: "hexpm", optional: false]}], "hexpm", "5f7c9342480c069dbbc4eeac3490303c9e01870ff01a7f1d29b6107054fc1e74"},
"nimble_options": {:hex, :nimble_options, "1.1.1", "e3a492d54d85fc3fd7c5baf411d9d2852922f66e69476317787a7b2bb000a61b", [:mix], [], "hexpm", "821b2470ca9442c4b6984882fe9bb0389371b8ddec4d45a9504f00a66f650b44"},
"nimble_pool": {:hex, :nimble_pool, "1.1.0", "bf9c29fbdcba3564a8b800d1eeb5a3c58f36e1e11d7b7fb2e084a643f645f06b", [:mix], [], "hexpm", "af2e4e6b34197db81f7aad230c1118eac993acc0dae6bc83bac0126d4ae0813a"},
"plug": {:hex, :plug, "1.20.3", "56c480c633ec2ce10140e236e15233bf576e1d323887d7c96711bd02ab5160db", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_crypto, "~> 1.1.1 or ~> 1.2 or ~> 2.0", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.3 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "be266aee1b8536ef6409d58cf39a3121319f0ec47cfa1b24024485aa0e76ad76"},
"plug_crypto": {:hex, :plug_crypto, "2.2.0", "144014737daaf485407f5ed77daeaad74d651b216a28c87543f8cc7043f8efc8", [:mix], [], "hexpm", "83a95744ab1c75876542b6fab135fcc176280e0f301a111c1f757fddcec95d2c"},
"req": {:hex, :req, "0.7.2", "364eae2e5f5c984f2dac6d71c07f8c8c89ce0bc49c4d746dacb7a306823020de", [:mix], [{:brotli, "~> 0.3.1", [hex: :brotli, repo: "hexpm", optional: true]}, {:finch, "~> 0.21", [hex: :finch, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:mime, "~> 2.0.6 or ~> 2.1", [hex: :mime, repo: "hexpm", optional: false]}, {:nimble_csv, "~> 1.0", [hex: :nimble_csv, repo: "hexpm", optional: true]}, {:plug, "~> 1.0", [hex: :plug, repo: "hexpm", optional: true]}], "hexpm", "c9cdfa276b05d8db2a27fda5d233e6858b764d47189d76cbb186e130a871ae0b"},
"telemetry": {:hex, :telemetry, "1.4.2", "a0cb522801dffb1c49fe6e30561badffc7b6d0e180db1300df759faa22062855", [:rebar3], [], "hexpm", "928f6495066506077862c0d1646609eed891a4326bee3126ba54b60af61febb1"},
}
defmodule CsxReqTest do
# async: true is safe on purpose. Req.Test keeps stubs in an ownership
# registry keyed by the calling process (vendored nimble_ownership, the
# same model as Mox) and the registry starts in :private mode, so two
# concurrent tests can register different plugs under the same name. That
# is the one thing a mutable module-level response queue cannot do.
use ExUnit.Case, async: true
alias CsxReq.Weather
@url "https://api.example.com/items"
# Counts the :hit messages the stubs below send to this process. Req runs
# the plug synchronously in the caller, so retries land in this mailbox.
defp hits(acc \\ 0) do
receive do
:hit -> hits(acc + 1)
after
0 -> acc
end
end
defp body(name, opts \\ []) do
Req.get!([plug: {Req.Test, name}, url: @url, retry: false] ++ opts).body
end
## 1. Decoding is driven by the response content-type
test "a stub returns a body and the content-type decodes it, with no accessor call" do
Req.Test.stub(Weather, fn conn -> Req.Test.json(conn, %{"celsius" => 25.0}) end)
{:ok, resp} = Weather.get_temperature("Krakow")
assert resp.status == 200
# Req.Test.json/2 sets the content-type as a side effect; that header, not
# the helper's name, is the whole mechanism. Headers are a map of lists in
# Req 0.5+, not a keyword list, and a missing header reads as nil rather
# than []. The cache-control entry is Plug.Conn's default, present on
# every stubbed response.
assert resp.headers == %{
"cache-control" => ["max-age=0, private, must-revalidate"],
"content-type" => ["application/json; charset=utf-8"]
}
assert Req.Response.get_header(resp, "content-type") == ["application/json; charset=utf-8"]
assert Req.Response.get_header(resp, "x-missing") == []
assert resp.headers["x-missing"] == nil
# The body is already a map. There is no resp.json() step, which is what
# makes production code able to pattern match straight on the body.
assert resp.body == %{"celsius" => 25.0}
assert Weather.get_rating("Krakow") == {:ok, :nice}
end
test "the same bytes without a content-type stay a binary and break the caller's match" do
raw = Jason.encode!(%{"celsius" => 25.0})
Req.Test.stub(Weather, fn conn -> Plug.Conn.send_resp(conn, 200, raw) end)
{:ok, resp} = Weather.get_temperature("Krakow")
assert resp.status == 200
assert Req.Response.get_header(resp, "content-type") == []
assert resp.body == raw
# A perfectly good 200 that the caller cannot read: decode_body never ran,
# so the %{"celsius" => _} clause does not match. Stub with
# Req.Test.json/2, or Plug.Conn.put_resp_content_type/2, not send_resp/3
# alone.
assert Weather.get_rating("Krakow") == :error
end
test "with no content-type the URL path decides, so a .json path decodes anyway" do
raw = Jason.encode!(%{"celsius" => 25.0})
plug = fn conn -> Plug.Conn.send_resp(conn, 200, raw) end
# Req.Steps.decode_body falls back to "application/octet-stream" when the
# response has no content-type, and octet-stream is resolved through
# MIME.from_path(request.url.path). Identical stub, identical bytes, and
# the body type is decided by the request URL. This is the reason a stub
# that "works" against one endpoint suddenly returns a string on another.
assert Req.get!(plug: plug, url: "https://api.example.com/data.json").body ==
%{"celsius" => 25.0}
assert Req.get!(plug: plug, url: "https://api.example.com/data").body == raw
assert Req.get!(plug: plug, url: "https://api.example.com/data.txt").body == raw
end
## 2. A 500 is a value; retry is the step that reacts to it
test "an HTTP 500 does not raise, not even from the bang functions" do
Req.Test.stub(Weather, fn conn ->
conn |> Plug.Conn.put_status(500) |> Req.Test.json(%{"error" => "boom"})
end)
# Req.request/1 returns :error only when the exchange did not happen.
# A 500 happened, so it is {:ok, response}.
{:ok, resp} = Weather.get_temperature("Krakow", retry: false)
assert resp.status == 500
# Error bodies go through the same decoder as success bodies.
assert resp.body == %{"error" => "boom"}
# Req.request!/1 raises the exception from {:error, exception}. There is
# no exception here, so it returns the 500 response.
assert %Req.Response{status: 500} =
Req.request!(plug: {Req.Test, Weather}, url: @url, retry: false)
# Raising on 4xx/5xx is opt-in. Note which body the message carries: the
# undecoded binary, because the response steps run
# retry -> handle_http_errors -> ... -> decode_body, so the raise happens
# before the decoder. The exception you read in CI and the body the same
# request would have returned are not the same value.
error =
assert_raise(RuntimeError, fn ->
Weather.get_temperature("Krakow", retry: false, http_errors: :raise)
end)
assert Exception.message(error) ==
"The requested URL returned error: 500\n" <>
~s|Response body: "{\\"error\\":\\"boom\\"}"|
end
test "retry fires on a 500 for GET but not for POST" do
Req.Test.stub(RetryStub, fn conn ->
send(self(), :hit)
Plug.Conn.send_resp(conn, 500, "boom")
end)
opts = [plug: {Req.Test, RetryStub}, url: @url, retry_delay: 0, retry_log_level: false]
# :retry defaults to :safe_transient: 408/429/500/502/503/504 and a few
# transport errors, on GET and HEAD only. :max_retries defaults to 3, so a
# single failing GET calls the stub four times. A stub is reusable, so
# nothing here signals that three extra requests happened — count them.
assert Req.get!(opts).status == 500
assert hits() == 4
# The same 500 on POST is returned immediately: retrying a non-idempotent
# method is not safe, so :safe_transient excludes it.
assert Req.post!(opts).status == 500
assert hits() == 1
# :transient is the opt-in for every method.
assert Req.post!(opts ++ [retry: :transient]).status == 500
assert hits() == 4
end
test "a stub can fail below HTTP, which a queue of responses cannot express" do
Req.Test.stub(BrokenStub, &Req.Test.transport_error(&1, :timeout))
opts = [plug: {Req.Test, BrokenStub}, url: @url]
assert Req.get(opts ++ [retry: false]) == {:error, %Req.TransportError{reason: :timeout}}
assert_raise Req.TransportError, fn -> Req.get!(opts ++ [retry: false]) end
# :timeout is in the transient set, so this is also what retry reacts to.
assert {:error, %Req.TransportError{}} =
Req.get(opts ++ [retry_delay: 0, retry_log_level: false])
assert hits() == 0
end
## 3. expect versus stub
test "expectations are consumed in order and then fall through to the stub" do
Req.Test.stub(OrderStub, fn conn -> Plug.Conn.send_resp(conn, 200, "stub") end)
Req.Test.expect(OrderStub, 2, fn conn -> Plug.Conn.send_resp(conn, 200, "expected") end)
# expect/3 wins while it has uses left, regardless of registration order.
assert body(OrderStub) == "expected"
assert body(OrderStub) == "expected"
# Once drained, Req.Test falls back to the stub instead of failing. So a
# stub registered alongside expectations turns "used too many times" from
# an error into silence — that combination is only worth it when the extra
# calls genuinely do not matter.
assert body(OrderStub) == "stub"
assert Req.Test.verify!(OrderStub) == :ok
end
test "an exhausted expectation raises, and an unregistered name raises differently" do
Req.Test.expect(OnceStub, fn conn -> Plug.Conn.send_resp(conn, 200, "once") end)
assert body(OnceStub) == "once"
# expect/3 without a stub is the strict form. expect/2 defaults to one
# use, so the second request blows up at the call site rather than at
# verification time.
assert_raise RuntimeError, "no mock or stub for #{inspect(OnceStub)}", fn ->
body(OnceStub)
end
# Different failure, different message: this one means the name was never
# registered from a process this one can see. If you hit it in a spawned
# task, the fix is Req.Test.allow/3, not another stub.
assert_raise RuntimeError, ~r/^cannot find mock\/stub .* in process #PID/, fn ->
body(UnregisteredStub)
end
end
test "an unmet expectation is silent until something verifies it" do
Req.Test.expect(UnmetStub, 2, fn conn -> Plug.Conn.send_resp(conn, 200, "ok") end)
assert body(UnmetStub) == "ok"
# Nothing has failed at this point, and nothing will: Req.Test does not
# fail a test on its own. Asking is either verify!/0,1 here or
# `setup {Req.Test, :verify_on_exit!}`, which is the version that also
# covers tests that forget to ask.
assert_raise RuntimeError, ~r/expected .* to be still used 1 more times/, fn ->
Req.Test.verify!(UnmetStub)
end
# verify!/1 is scoped to one name; verify!/0 checks every name this
# process owns, which matters once a test registers more than one.
assert Req.Test.verify!(OtherStub) == :ok
end
## 4. Turning the decoding off
test "decoding can be switched off, and :decoders replaces the default list" do
raw = ~s({"celsius":25.0})
Req.Test.stub(DecodeStub, fn conn -> Req.Test.json(conn, %{"celsius" => 25.0}) end)
assert body(DecodeStub) == %{"celsius" => 25.0}
# Three separate switches, all landing on the undecoded binary. :raw also
# turns off decompression; :decoders false turns off every format;
# :decode_body false is the narrow one.
assert body(DecodeStub, decode_body: false) == raw
assert body(DecodeStub, decoders: false) == raw
assert body(DecodeStub, raw: true) == raw
# :decoders replaces the default [:json, :json_api] rather than adding to
# it, so asking for one more format silently loses JSON.
assert body(DecodeStub, decoders: [:gz]) == raw
assert body(DecodeStub, decoders: [:gz, :json]) == %{"celsius" => 25.0}
# req 0.7.0 deprecated `decode_json: opts` in favour of a codec under
# :decoders. This is the replacement spelling for atom keys.
assert body(DecodeStub, decoders: [json: &Jason.decode(&1, keys: :atoms)]) ==
%{celsius: 25.0}
end
## Wiring
test "Req.Test is a plug and the stub name is its options" do
# plug: {Req.Test, name} is the ordinary {module, options} plug form, so
# Req.Plug calls Req.Test.call(conn, Req.Test.init(name)). The name is not
# a config key Req looks up: it is literally the plug's options.
assert Req.Test.__info__(:attributes)[:behaviour] == [Plug]
assert Req.Test.init(SomeName) == SomeName
# A bare function plug needs no registry at all. What Req.Test adds on top
# is the name indirection and the process ownership, not the stubbing.
plug = fn conn -> Req.Test.json(conn, %{"ok" => true}) end
assert Req.get!(plug: plug, url: @url).body == %{"ok" => true}
end
end
# This is what would live in config/test.exs in a real app: the production
# module reads its Req options out of the application env, and the test
# environment is the only place that points them at a stub.
#
# retry_delay/retry_log_level are test-only. Req's retry step sleeps with
# exponential backoff and jitter (roughly 0.949s, 1.97s, 3.87s) and logs a
# warning before each attempt, so a suite that exercises retries without
# these two options is both slow and noisy.
Application.put_env(:csx_req, :req_options,
plug: {Req.Test, CsxReq.Weather},
retry_delay: 0,
retry_log_level: false
)
ExUnit.start()