Home / Blog / Mock the SellerMagnet API in Elixir Tests Without Spending Credits

Mock the SellerMagnet API in Elixir Tests Without Spending Credits

Test the Elixir client that calls the SellerMagnet API without hitting it: run a tiny local :gen_tcp HTTP server instead of the real API, point the quickstart's own SELLERMAGNET_API_BASE test seam at it, and cover every billed, free and refunded status code with mix test.

November 16, 2026
5 min read
SellerMagnet Team
Share & Bookmark
Terminal window showing a mix test run that points the SellerMagnet API client at a local gen_tcp test server while the real client code runs unchanged

Mock the SellerMagnet API in Elixir tests by running a tiny local HTTP server instead of the real API: point the quickstart's own SELLERMAGNET_API_BASE environment variable at 127.0.0.1, and let the unchanged client.ex, retry.ex and product.ex from the Elixir quickstart run against it. No credit is spent, no request leaves the test machine, and the fake server fails closed so a forgotten scripted route cannot be mistaken for a real answer.

Key Takeaways

  • client.ex calls Erlang's :httpc directly, with no handler-injection seam to mock in-process; point the existing SELLERMAGNET_API_BASE test seam at a local server instead.
  • A ~100-line :gen_tcp listener is enough: no Plug, no Cowboy, no new dependency beyond what the quickstart already uses.
  • Make the fake fail closed: a request before a test installs its scripted route should get a loud 500, not a quiet, made-up success.
  • retry.ex's sleep_fun argument is already injectable, so a 429/500/502 test records the requested wait instead of a real :timer.sleep, while the real backoff and Retry-After math still run.
  • A 429 is free and worth waiting out; a 500 is refunded and worth exactly one retry; a 502/503 is billed on every attempt, so the attempt cap matters for the bill, not just the code.

Why not just call the real API in an Elixir test suite?

Every SellerMagnet API request is billed per the table below, whether it comes from production code or mix test. A CI run that fires on every push would spend credits on every build, a slow or flaky network turns a code bug into a failed pipeline, and a 429 or a second consecutive 500 a test wants to simulate on demand cannot be forced on the live API at all. A local server makes every status code - including the ones that are rare in practice - reproducible on every run.

Scenarios worth testing, and what the fake server needs to script for each.
ScenarioChargedRetry?Client should
happy path lookup + offers + statisticsbillednodecode, up to 3 credits
404 product not foundbillednorecord it; do not retry
free gate 400 (missing marketplaceId)freenofix the request, no retry
statistics' own free 400 (marketplace not covered)freenoreport :not_covered, not an error
401 insufficient creditsfreenostop; top up credits
429 concurrency capfreeyeshonour Retry-After, then retry
500 internal errorrefundedyesretry once, then stop
502 / 503 upstreambilledyesretry up to the attempt cap

How do I fake the server, not my own client code?

client.ex's new/1 already reads SELLERMAGNET_API_BASE from the environment, falling back to the real API only when it is unset - a seam the quickstart documents for exactly this purpose. FakeServer.start/0 binds a :gen_tcp listener on a random free port and defaults every request to a 500 until a test calls install/2 with its own scripted {status, body} function, so client.ex, retry.ex and product.ex run exactly as they would in production, pointed at http://127.0.0.1:<port>/api instead of the live host.

Blueprint sequence diagram of an Elixir test pointing the SellerMagnet client at a local gen_tcp server while the real client code runs unchanged
Only the base URL changes; client.ex, retry.ex and product.ex run unmodified.

test/support/fake_server.ex - a gen_tcp test double, fails closed

defmodule FakeServer do
  @moduledoc """
  A minimal HTTP/1.1 test double over :gen_tcp (stdlib only, no Plug/Cowboy dependency): it
  fails closed until install/2 scripts a route, so a request sent before installing one gets a
  loud 500 instead of quietly looking like a real answer. Points the quickstart's own
  SELLERMAGNET_API_BASE test seam at 127.0.0.1 - lib/sellermagnet/client.ex, retry.ex and
  product.ex run completely unchanged against it.
  """

  @doc "Starts a listener on a random free port. Returns a handle for install/2, calls/1, stop/1."
  def start do
    {:ok, listen} = :gen_tcp.listen(0, [:binary, packet: :line, active: false, reuseaddr: true])
    {:ok, port} = :inet.port(listen)
    {:ok, agent} = Agent.start_link(fn -> {nil, []} end)
    acceptor = spawn(fn -> accept_loop(listen, agent) end)
    %{listen: listen, port: port, agent: agent, acceptor: acceptor}
  end

  def stop(%{listen: listen, acceptor: acceptor}) do
    Process.exit(acceptor, :kill)
    :gen_tcp.close(listen)
  end

  @doc """
  route_fun.(method, path, query, headers) -> {status, body} | {status, body, extra_headers}.
  Replaces whatever route was installed before; each test installs its own and nothing leaks
  across tests because every test starts a fresh server (see test/support/fake_server_case.ex).
  """
  def install(%{agent: agent}, route_fun), do: Agent.update(agent, fn {_old, calls} -> {route_fun, calls} end)

  @doc "Every request the server has received so far, oldest first: {method, path, query, headers}."
  def calls(%{agent: agent}), do: Agent.get(agent, fn {_route, calls} -> Enum.reverse(calls) end)

  def base_url(%{port: port}), do: "http://127.0.0.1:#{port}"

  defp accept_loop(listen, agent) do
    case :gen_tcp.accept(listen, 200) do
      {:ok, sock} ->
        spawn(fn -> handle(sock, agent) end)
        accept_loop(listen, agent)

      {:error, :timeout} ->
        accept_loop(listen, agent)

      {:error, :closed} ->
        :ok
    end
  end

  defp handle(sock, agent) do
    case recv_request_line(sock) do
      {:ok, method, target} ->
        headers = recv_headers(sock)
        {path, query} = split_target(target)
        route = Agent.get(agent, fn {r, _} -> r end)
        Agent.update(agent, fn {r, calls} -> {r, [{method, path, query, headers} | calls]} end)

        case route do
          nil ->
            respond(sock, 500, ~s({"success":false,"message":"fakeserver: install/2 first"}), [])

          fun ->
            case fun.(method, path, query, headers) do
              {status, body} -> respond(sock, status, body, [])
              {status, body, extra} -> respond(sock, status, body, extra)
            end
        end

      :error ->
        :ok
    end

    :gen_tcp.close(sock)
  end

  defp recv_request_line(sock) do
    case :gen_tcp.recv(sock, 0, 2_000) do
      {:ok, line} ->
        case line |> String.trim() |> String.split(" ") do
          [method, target, _version] -> {:ok, method, target}
          _ -> :error
        end

      {:error, _} ->
        :error
    end
  end

  defp recv_headers(sock, acc \\ []) do
    case :gen_tcp.recv(sock, 0, 2_000) do
      {:ok, line} ->
        trimmed = String.trim(line)

        if trimmed == "" do
          Enum.reverse(acc)
        else
          [name, value] = String.split(trimmed, ":", parts: 2)
          recv_headers(sock, [{String.downcase(name), String.trim(value)} | acc])
        end

      {:error, _} ->
        Enum.reverse(acc)
    end
  end

  defp split_target(target) do
    case String.split(target, "?", parts: 2) do
      [path] -> {path, %{}}
      [path, qs] -> {path, URI.decode_query(qs)}
    end
  end

  defp respond(sock, status, body, extra_headers) do
    base = [
      "HTTP/1.1 #{status} x\r\n",
      "Content-Type: application/json\r\n",
      "Content-Length: #{byte_size(body)}\r\n",
      "Connection: close\r\n"
    ]

    extra = Enum.map(extra_headers, fn {k, v} -> "#{k}: #{v}\r\n" end)
    :gen_tcp.send(sock, Enum.join(base ++ extra) <> "\r\n" <> body)
  end
end
Blueprint table of test scenarios against the SellerMagnet API's status codes, billing and the correct Elixir client reaction
Each row needs its own scripted response; a happy-path test alone misses most of this.

What does a full mix test scenario suite look like?

Each test starts its own FakeServer in setup/1 and stops it with on_exit/1, so no route or call log leaks between tests even when ExUnit runs them async: true. The 429 and 500/502 tests pass a sleep_fun that records the requested wait in an Agent instead of sleeping for real, so the whole 13-test suite below finishes in under half a second while still proving the real Retry-After value and the real attempt cap from retry.ex.

test/sellermagnet_mock_test.exs - the scenario suite, run for real below

defmodule SellerMagnetMockTest do
  use ExUnit.Case, async: true

  alias SellerMagnet.{Client, Product}

  setup do
    server = FakeServer.start()
    on_exit(fn -> FakeServer.stop(server) end)
    client = Client.new(key: "test-key", base: FakeServer.base_url(server) <> "/api")
    %{server: server, client: client}
  end

  defp ok_envelope(data), do: ~s({"success":true,"data":#{Jason.encode!(data)}})

  # --- 1. happy path: lookup, offers, statistics all 200 ------------------------------------
  test "happy path decodes lookup, offers and statistics", %{server: server, client: client} do
    FakeServer.install(server, fn _method, path, _query, _headers ->
      cond do
        String.ends_with?(path, "amazon-product-lookup") ->
          {200, ok_envelope(%{"productInfo" => %{"buyBoxInfo" => %{"price" => 444.99, "currencyCode" => "USD"}}})}

        String.ends_with?(path, "amazon-product-offers") ->
          {200, ok_envelope(%{"buyBox" => %{"sellerId" => "A2SELLER", "totalPrice" => 449.5}, "offers" => [%{}, %{}]})}

        String.ends_with?(path, "amazon-product-statistics") ->
          {200, ok_envelope(%{"buyBoxPrice" => 44499, "buyBoxFulfillment" => "FBA"})}
      end
    end)

    assert {:ok, %{price: 444.99, currency: "USD"}} = Product.lookup(client, "B0CL61F39H", "ATVPDKIKX0DER")
    assert {:ok, %{featured: %{seller_id: "A2SELLER", total_price: 449.5}, offer_count: 2}} =
             Product.offers(client, "B0CL61F39H", "ATVPDKIKX0DER")
    assert {:ok, %{minor_units: 44499, decimal: 444.99, fulfillment: "FBA"}} =
             Product.statistics(client, "B0CL61F39H", "ATVPDKIKX0DER")

    [{_, _, _, headers} | _] = FakeServer.calls(server)
    assert {"x-api-key", "test-key"} in headers
  end

  # --- 2. "N/A" price / nulls decode to nil, never 0.0 ---------------------------------------
  test "a missing price is nil, not 0.0 or a crash", %{server: server, client: client} do
    FakeServer.install(server, fn _m, _p, _q, _h ->
      {200, ok_envelope(%{"productInfo" => %{"buyBoxInfo" => %{"price" => "N/A", "currencyCode" => nil}}})}
    end)

    assert {:ok, %{price: nil, currency: nil}} = Product.lookup(client, "B0CL61F39H", "ATVPDKIKX0DER")
  end

  # --- 3. empty buyBox {} on offers means no featured offer, not a crash ---------------------
  test "empty buyBox means no featured offer", %{server: server, client: client} do
    FakeServer.install(server, fn _m, _p, _q, _h -> {200, ok_envelope(%{"buyBox" => %{}, "offers" => []})} end)

    assert {:ok, %{featured: nil, offer_count: 0}} = Product.offers(client, "B0CL61F39H", "ATVPDKIKX0DER")
  end

  # --- 4. 404 is billed once and never retried ------------------------------------------------
  test "404 is reported once, never retried", %{server: server, client: client} do
    FakeServer.install(server, fn _m, _p, _q, _h ->
      {404, ~s({"success":false,"message":"Invalid product"})}
    end)

    assert {:error, {:api, 404, "Invalid product", nil}} = Product.lookup(client, "B0NOTFOUND", "ATVPDKIKX0DER")
    assert length(FakeServer.calls(server)) == 1
  end

  # --- 5. free gate 400 (missing/unsupported param) is reported once, never retried ----------
  test "a free gate 400 is reported once, never retried", %{server: server, client: client} do
    FakeServer.install(server, fn _m, _p, _q, _h ->
      {400, ~s({"success":false,"message":"marketplaceId is required"})}
    end)

    assert {:error, {:api, 400, "marketplaceId is required", nil}} =
             Product.lookup(client, "B0CL61F39H", "ATVPDKIKX0DER")
    assert length(FakeServer.calls(server)) == 1
  end

  # --- 6. statistics' own free 400 (marketplace not covered) maps to :not_covered -------------
  test "statistics free 400 maps to :not_covered, not an error tuple", %{server: server, client: client} do
    FakeServer.install(server, fn _m, _p, _q, _h ->
      {400, ~s({"success":false,"message":"marketplace not covered"})}
    end)

    assert {:not_covered, "marketplace not covered"} = Product.statistics(client, "B0CL61F39H", "A2VIGQ35RCS4UG")
    assert length(FakeServer.calls(server)) == 1
  end

  # --- 7. 401 (no credits) is reported once, never retried -----------------------------------
  test "401 is reported once, never retried", %{server: server, client: client} do
    FakeServer.install(server, fn _m, _p, _q, _h -> {401, ~s({"success":false,"message":"insufficient credits"})} end)

    assert {:error, {:api, 401, "insufficient credits", nil}} = Product.lookup(client, "B0CL61F39H", "ATVPDKIKX0DER")
    assert length(FakeServer.calls(server)) == 1
  end

  # --- 8. 429 is free and retried, honouring Retry-After ---------------------------------------
  test "429 is retried and the real Retry-After value is passed to sleep_fun", %{server: server, client: client} do
    {:ok, agent} = Agent.start_link(fn -> 0 end)

    FakeServer.install(server, fn _m, _p, _q, _h ->
      n = Agent.get_and_update(agent, fn n -> {n, n + 1} end)

      if n == 0 do
        {429, ~s({"success":false,"message":"Max 2 concurrent requests per API key. Retry shortly."}),
         [{"Retry-After", "2"}]}
      else
        {200, ok_envelope(%{"productInfo" => %{"buyBoxInfo" => %{"price" => 10.0, "currencyCode" => "USD"}}})}
      end
    end)

    waits = Agent.start_link(fn -> [] end) |> elem(1)
    sleep_fun = fn ms -> Agent.update(waits, fn w -> [ms | w] end) end

    {:ok, data} =
      SellerMagnet.Retry.get(
        client,
        "/amazon-product-lookup",
        [asin: "B0CL61F39H", marketplaceId: "ATVPDKIKX0DER"],
        sleep_fun
      )

    assert get_in(data, ["productInfo", "buyBoxInfo", "price"]) == 10.0
    assert Agent.get(waits, & &1) == [2_000]
    assert length(FakeServer.calls(server)) == 2
  end

  # --- 9. a plain 500 is refunded and retried exactly once, a second 500 is reported ----------
  test "500 is retried once, a second consecutive 500 is reported, not retried again", %{
    server: server,
    client: client
  } do
    FakeServer.install(server, fn _m, _p, _q, _h -> {500, ~s({"success":false,"message":"internal error"})} end)
    sleep_fun = fn _ms -> :ok end

    result = SellerMagnet.Retry.get(client, "/amazon-product-lookup", [asin: "B0CL61F39H", marketplaceId: "ATVPDKIKX0DER"], sleep_fun)

    assert {:error, {:api, 500, "internal error", nil}} = result
    assert length(FakeServer.calls(server)) == 2
  end

  # --- 10. 502/503 are billed and retried every attempt up to the cap -------------------------
  test "502 is retried up to the attempt cap, billed every time", %{server: server, client: client} do
    FakeServer.install(server, fn _m, _p, _q, _h -> {502, ~s({"success":false,"message":"upstream error"})} end)
    sleep_fun = fn _ms -> :ok end

    result = SellerMagnet.Retry.get(client, "/amazon-product-lookup", [asin: "B0CL61F39H", marketplaceId: "ATVPDKIKX0DER"], sleep_fun)

    assert {:error, {:api, 502, "upstream error", nil}} = result
    assert length(FakeServer.calls(server)) == 4
  end

  # --- 11. a malformed ASIN is skipped before any call is made --------------------------------
  test "a 9-character ASIN never reaches the server" do
    refute Product.asin?("B0CL61F39")
    refute Product.asin?("B0CL61F39H\n")
  end

  # --- 12. fails closed: a request before install/2 gets a loud 500, not a quiet pass ---------
  test "fails closed before any route is installed", %{client: client} do
    sleep_fun = fn _ms -> :ok end

    result = SellerMagnet.Retry.get(client, "/amazon-product-lookup", [asin: "B0CL61F39H", marketplaceId: "ATVPDKIKX0DER"], sleep_fun)

    assert {:error, {:api, 500, "fakeserver: install/2 first", nil}} = result
  end

  # --- 13. two concurrent lookups against the same fake server do not cross-contaminate -------
  test "two concurrent requests each get their own scripted answer keyed on their own asin", %{
    server: server,
    client: client
  } do
    FakeServer.install(server, fn _m, _p, query, _h ->
      price = if query["asin"] == "B0CL61F39H", do: 1.50, else: 2.50
      {200, ok_envelope(%{"productInfo" => %{"buyBoxInfo" => %{"price" => price, "currencyCode" => "USD"}}})}
    end)

    t1 = Task.async(fn -> Product.lookup(client, "B0CL61F39H", "ATVPDKIKX0DER") end)
    t2 = Task.async(fn -> Product.lookup(client, "B0CLTBHXWQ", "APJ6JRA9NG5V4") end)

    assert {:ok, %{price: 1.50}} = Task.await(t1)
    assert {:ok, %{price: 2.50}} = Task.await(t2)
    assert length(FakeServer.calls(server)) == 2
  end
end

mix test --trace output (unmodified run)

SellerMagnetMockTest [test/sellermagnet_mock_test.exs]
  * test 502 is retried up to the attempt cap, billed every time (170.1ms) [L#141]
  * test fails closed before any route is installed (3.8ms) [L#158]
  * test 404 is reported once, never retried (4.8ms) [L#57]
  * test 500 is retried once, a second consecutive 500 is reported, not retried again (3.3ms) [L#127]
  * test a missing price is nil, not 0.0 or a crash (10.7ms) [L#41]
  * test empty buyBox means no featured offer (2.2ms) [L#50]
  * test statistics free 400 maps to :not_covered, not an error tuple (1.9ms) [L#78]
  * test two concurrent requests each get their own scripted answer keyed on their own asin (3.6ms) [L#167]
  * test 401 is reported once, never retried (1.7ms) [L#88]
  * test 429 is retried and the real Retry-After value is passed to sleep_fun (3.5ms) [L#96]
  * test a 9-character ASIN never reaches the server (0.2ms) [L#152]
  * test happy path decodes lookup, offers and statistics (5.4ms) [L#16]
  * test a free gate 400 is reported once, never retried (2.1ms) [L#67]

Finished in 0.4 seconds (0.4s async, 0.00s sync)
13 tests, 0 failures

Randomized with seed 1

Never hand-write a fake of Product.lookup/3 or Retry.get/4

A fake that reimplements Product.lookup/3 or Retry.get/4 tests the fake's own logic, not the real client. Fake one level below your code - here, the HTTP server itself - so a real bug in the decoding or retry logic still shows up as a failing test.

Does the same pattern work for other languages?

Yes - fake the one thing the real code talks to, whatever shape that takes. The Python mock-testing guide fakes requests.Session.get in-process; this guide points Elixir's own SELLERMAGNET_API_BASE test seam at a :gen_tcp server instead, because :httpc has no in-process handler to fake. The 429/Retry-After guide and the 502/503 retry guide are the production behaviour this suite checks against; keep all three in sync when the retry logic changes. Credit costs and the free trial are on the pricing page, and every endpoint's parameters are in the API documentation and code examples.

Frequently Asked Questions

Can Elixir tests call the real SellerMagnet API instead of faking it?

They can, but every call is billed the same as production traffic, so a CI run that fires on every push spends credits on every build, and a flaky network turns a code bug into a failed pipeline. Pointing SELLERMAGNET_API_BASE at a local test server keeps the real client.ex/retry.ex/product.ex under test while the live API never sees a request.

Why run a real local HTTP server instead of mocking :httpc directly?

client.ex calls :httpc.request, an Erlang stdlib function with no handler-injection seam to mock in-process (unlike Go's http.RoundTripper or Java's embedded HttpServer constructor argument). The quickstart's own SELLERMAGNET_API_BASE environment variable already exists to point the client at a different base URL, so a tiny :gen_tcp server on 127.0.0.1 answers real HTTP/1.1 requests while client.ex, retry.ex and product.ex run completely unmodified.

Why not add Plug and Cowboy as test dependencies?

They would work, but the quickstart ships with zero HTTP-server dependencies, and a 100-line :gen_tcp listener is small enough to read in one sitting and audit for exactly what it does: fail closed until a test installs a route, then answer with that route's scripted status and body. Fewer dependencies also means fewer version mismatches between the post and a reader's own mix.lock.

How do I avoid real waits for a 429 or 500 retry test?

retry.ex already takes an injectable sleep_fun argument (it defaults to &:timer.sleep/1), so tests pass a function that records the requested wait instead of actually sleeping. The real backoff math and the real Retry-After value are still exercised; only the literal clock wait is skipped, which is why this suite runs in well under a second.

Should the fake server allow a request through if a test forgets to install a route?

No. FakeServer answers every unscripted request with a 500 and the message "install/2 first", which retry.ex treats like any other refunded 500: it retries once, then reports the error. A forgotten install fails the test loudly with that message instead of quietly returning an empty success.

Bottom line: when your language's HTTP client has no in-process seam to fake, point its existing test-base-URL setting at a small local server instead of adding a mocking framework. The suite above runs in well under a second, spends zero credits, and still exercises the real retry backoff and Retry-After handling in retry.ex.

Related Articles

Continue exploring topics related to this article.

Back to Blog

Ready to Extract Amazon Data at Scale?

Start building with SellerMagnet API today. Real-time product data, competitive pricing, and review analytics at your fingertips.

150 free API credits • No credit card required • Cancel anytime