johantell

johantell

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!

Showing Posts 1 to 3

aifrak

aifrak

Thanks for making this library.

Can you explain the differences between moxinet and bypass?

Both seems to mock HTTP requests with a custom plug, but it is like the main difference is that moxinet uses an actual HTTP server, whereas bypass uses a mock HTTP server.

johantell

johantell OP

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.

— All posts loaded —

Where Next? Top

Trending in Announcing Top

bluzky
You may know https://ui.shadcn.com/, a UI component library for React. I really love it’s design style and components. I’ve built some co...
387 15136 120
New
woylie
Flop is an Elixir library that applies filtering, ordering and pagination parameters to your Ecto queries. offset-based pagination with...
New
restlessronin
The repo is at GitHub - cyberchitta/openai_ex: Community maintained Elixir library for OpenAI API · GitHub. Docs are at OpenaiEx User Gu...
152 11030 135
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
shahryarjb
The Chelekom project is a library of Phoenix and LiveView components generated via Mix tasks to fit developer needs seamlessly. One of i...
New
woylie
Phoenix components for pagination, sortable tables and filter forms with Flop and (optionally) Ecto. pagination cursor pagination sorta...
New
kip
Please say hi to a new lib, Astro that aims to deliver easy-to-consume astronomy calculations of practical use. For now it only calculat...
New

Other Trending Topics Top

akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
alexslade
Fly’s CEO posted this recently - Turn And Face The Strange · The Fly Blog It says that Fly is going all-in on sprites, which is a worry ...
New
bartblast
Hey folks, I just published a post about Hologram’s funding and where the project goes next - the short version: Curiosum as Main Spons...
New
Herve37
We’re evaluating API mocking tools for OpenAPI-based projects and would love to hear what other teams are using. We’re particularly inte...
New
mudasobwa
I am seeing a lot of aplications of Argumentum ad Vericundiam in software discussions. They do link some piece of writing and point us to...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews