johantell

johantell

Moxinet - mox-like mocks, but for the HTTP layer

Ever struggled with mocking external HTTP services in Elixir tests? Found yourself writing brittle mocks that don’t catch real-world encoding issues? I just released v0.5.0 of moxinet, a library that solves these problems by mocking at the HTTP layer instead of the Elixir code level.

What is moxinet
Think of it as “mox for HTTP” - it lets you mock external services by running an actual server, giving you the confidence that your HTTP layer works correctly,

This comes with some benefits:

  • A unified way of testing HTTP interactions among multiple libraries/clients
  • Ability to test/verify what is actually received on an external server (I’ve more than once experienced that the step where a passed data structure is encoded to JSON often happens so deep inside HTTP clients, that errors/bugs in those steps are hard to identify during testing)
  • More control to test unusual behaviours like timeouts/capped connections
  • Code that runs in tests no longer differs from code in production.
  • Minimal setup

Why I built moxinet
I built Moxinet after experiencing production issues where the mock worked perfectly, but the actual HTTP request failed due to header or encoding issues. In that specific case, the data to be sent was encoded to JSON via a @derive declaration within the HTTP client.

I had used the strategy of spinning up test servers to interact with during testing in other languages, but failed to find a similar alternative in the Elixir ecosystem.

How it works
Moxinet spins up its own plug-based server, which you’ll route your requests to in the test environment. In your tests, you define expectations that specify how the server will respond; you can even make assertions about the payload/headers. The server expects an x-moxinet-ref header that helps identify which test-pid it originated from (automatically added by the adapter when using req)

A normal setup looks like this:

# config/test.exs

config :req, default_options: [adapter: Moxinet.ReqTestAdapter]

config :my_app, GithubAPI,
  endpoint: http://localhost:4040/github
# test/support/moxinet_mocks.ex
defmodule GithubMock do
  use Moxinet.Mock
end

defmodule MyApp.MockServer do
  use Moxinet.Server

  forward("/github", to: GithubMock)
end
# test/test_helper.exs
{:ok, _} = Moxinet.start(port: 4040, router: MyApp.MockServer)
alias Moxinet.Response

describe "create_pr/1" do
  test "creates a PR and returns its id" do
    GithubMock.expect(:post, "/pull-requests/123", fn _payload ->
      %Response{status: 202, body: %{id: "pull-request-id"}, headers: [{"X-Rate-Limit", 10}]}
    end)

    assert {:ok,
      %{
       status: 202,
       body: %{"id" => "pull-request-id"},
       headers: [
         {"X-Rate-Limit", 10},
         {"Content-Type", "application/json"}
       ]
      }
    } = GithubAPI.create_pr(title: "My PR")
  end
end

Hex: moxinet | Hex
Github:

I’d love to hear about your use cases!

Most Liked

johantell

johantell

I don’t know all details about bypass, but from what I can tell, bypass and moxinet share the same main strategy, where an actual server is opened on a local port.

The main differences (from what I can tell from looking through the bypass source) are that bypass opens up one server per test, whereas moxinet opens up one local server and routes traffic to different mocks instead. By opening up one port/server per test (with Bypass.open), bypass doesn’t have to know which pid made the actual call, which moxinet must solve through a header. A downside is that you’d have to inject the port into every call, whereas in Moxinet, you only have to define it when changing the base URL for your client.

With that I do think (even if it’s a biased view) that even if bypass is more mature (and currently has more controls to allow/deny requests to the test server) moxinet could have the upper hand in ease of use and added security that the external API is called due to the base endpoint being changed (where in bypass I’m unsure how you’d manage calls that deep in a call tree without dependency injection)

Note that I have limited knowledge of bypass so I might be wrong in my some assumptions

aifrak

aifrak

Thanks for the explanation.

Where Next?

Popular in Announcing Top

jsm
Once is an Ecto type for locally unique 64-bits IDs generated by multiple Elixir nodes. Locally unique IDs make it easier to keep things ...
New
BartOtten
This powerful library works together with Phoenix Router to provide the ultimate routing solution. It simplifies route manipulation, givi...
New
Gigitsu
Hi everyone! I’d like to share a small library I’ve recently extracted from a project I’m working on: ginject. ginject provides a minim...
New
pcharbon
This is a new extension for the Ash framework that lets you use the Commanded library in a more declarative manner and removes most of th...
New
fuelen
Hi all! Confispex is a tool which allows defining specs for runtime configuration, cast values according to specified types and inspect ...
New
mikehostetler
LLM DB - LLM Model Metadata Package This package was extracted out of the ReqLLM project. LLM DB is a model metadata catalog with fast, ...
New
hauleth
It is library created by me and @abc3. It is simple client for DuckDB, but with small twist when compared with other libraries out there ...
New
corka149
A JSON patch is a way to define a sequence of manipulating operations on a JavaScript object. The IETF published the RFC 6902 - found he...
New
fhunleth
Elixir Circuits is a set of libraries for interacting with hardware. We previously announced Circuits.UART, and now we’re ready to announ...
New
waseigo
I saw this LinkedIn post: *Can your programming language do this? This is a macro in Clojure called `dotrace`. When you surround a pie...
New

Other popular topics Top

lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> someth...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
magnetic
Hey :wave:t3: Elixir community, I’ve been learning Elixir, and working on some side projects. My editor of choice is VSCode, and althoug...
New

We're in Beta

About us Mission Statement