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:

https://github.com/johantell/moxinet

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

josevalim
Hi everyone, We would like to announce that Plataformatec is working on a new MySQL driver called MyXQL. Our goal is to eventually integ...
New
josevalim
Yes, yet another parser combinator library! Most of the parser combinators in the ecosystem are either compile-time, often using AST tra...
159 19228 141
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43622 214
New
mikehostetler
I’m excited to announce Jido, a framework providing foundational primitives for building autonomous agent systems in Elixir. While develo...
New
MRdotB
I needed to reuse React components from my Chrome extension in my Phoenix/LiveView backend. I noticed that for Svelte/Vue, there are live...
New
wojtekmach
Hey everyone! Req is an HTTP client for Elixir that I’ve been working on for quite some time. There is already a lot of HTTP clients out...
New
RobertDober
Earmark is a pure-Elixir Markdown converter. It is intended to be used as a library (just call Earmark.as_html), but can also be used as...
239 12560 134
New
sbs
Only 650 LOC, wrote for fun :slight_smile: https://github.com/sunboshan/qrcode
New
anshuman23
Hello all, I have been working on my proposed project called Tensorflex as part of Google Summer of Code 2018.. Tensorflex can be used f...
New
wfgilman
I’ve cleaned up and open sourced three financial libraries I was using for my company. They are bindings for the APIs of these three comp...
New

Other popular topics Top

New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 52341 488
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
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
marick
I had some trouble figuring out how to make many-to-many associations work. Once I got it working, I wrote a blog post. Because I’m a nov...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement