Fl4m3Ph03n1x

Fl4m3Ph03n1x

Background

I have a Phoenix application, freshly created. This app has an endpoint that makes a request to an external service, and I would like to exercise/test the entire stack vertically.

To achieve this I have opted to try bypass to mock responses from the external service.

What I tried

To achieve this I have come up with the following code:

defmodule MyApp.ApplicationTest do
  @moduledoc false

  use ExUnit.Case, async: false

  alias HTTPoison

  @external_service_port 5112

  setup do
    bypass = Bypass.open(port: @external_service_port)

    {:ok, bypass: bypass}
  end

  test "client can handle an error response", %{bypass: bypass} do
    Bypass.expect_once(bypass, "GET", "api/users/validate", fn conn ->
      Plug.Conn.resp(conn, 429, ~s<{"errors": [{"code": 88, "message": "Rate limit exceeded"}]}>)
    end)

    MyApp.Application.start(nil, nil) |> IO.inspect(label: "APPLICATION STARTUP")

    HTTPoison.get("http://localhost:4000/api/users/validate") |> IO.inspect(label: "REQUEST")
  end
end

Problem

Unfortunately, when I run the test this is the output I get:

❯ mix test test/my_app/application_test.exs 
APPLICATION STARTUP: {:error, {:already_started, #PID<0.404.0>}}
REQUEST: {:error, %HTTPoison.Error{reason: :econnrefused, id: nil}}

My understanding is that the application is already started, but somehow I cannot reach it and I don’t know why.

Questions

  1. Is this the correct way to exercise the entire stack using ByPass with Phoenix?
  2. Is there a better way of testing this?
  3. Why can’t I access my application?

Showing Posts 1 to 10

fuelen

fuelen

You don’t need to start MyApp.Application manually. mix does this for you. Check mix.exs file, probably it has something like this:

def application do
  [
    mod: {MyApp.Application, []},
    # ...
  ]
end

Bypass started a server using port 5112, but you’re making requests to 4000

Fl4m3Ph03n1x

Fl4m3Ph03n1x OP

I am confused then. My objective is to use bypass to simulate the response from the external service (which uses port 5112). Port 4000 is the default port for when I use mix phx.server.

Does this mean that both my application (usually at port 4000) and the external service I am trying to simulate, are both in port 5112?

If so, how do I make bypass distinguish between them?

mudasobwa

mudasobwa

Creator of Cure

bypass obviously cannot mock external ports, it injects a plug into your server pipeline, that’s it.

Fl4m3Ph03n1x

Fl4m3Ph03n1x OP

So, this means I cannot use bypass to mock responses from an external service while also using HTTTPoison to directly call my application, correct?

The best I could do is to directly call the validate function in MyApp.ValidateController and then use bypass to mock the response from the external service said controller would eventually call, right?

mudasobwa

mudasobwa

Creator of Cure

I am not sure I see any advantage of using bypass over mox here.

I would do the following: mock HTTPoison.Base behaviour with mox. Make an HTTP client configurable, and point the configuration to your Mox module for HTTPoison in test env, and to HTTPoison otherwise. Do return whatever you want from the mocks.

nivanson

nivanson

I’ve been using test_server for this purpose. It’s not perfect but it is pretty good.

See GitHub - danschultzer/test_server: No fuzz ExUnit test server to mock third party services · GitHub

Fl4m3Ph03n1x

Fl4m3Ph03n1x OP

Isn’t this the same as bypass?
Meaning, if I use testserver I will not be able to call my app’s endpoints while simulating the third party, correct?

ananthakumaran

ananthakumaran

Bypass starts an HTTP server, it doesn’t mock anything. I think OP’s issue is about using HTTPoison to hit his own service. This should be done via plug test module.

LostKobrakai

LostKobrakai

One can also test ones own endpoint with an http client, but that requires actually binding the endpoint to a port, which is not the default. Adding server: true for the endpoint in config/test.exs would enable that. I’d only do that for integration tests though, as indeed plug level tests are usually fine and have the better DX especially around thing going wrong.

nivanson

nivanson

I don’t understand what you are asking. Why would you not be able to call your own application server?

You would be running your own server for your application. If your endpoint is running you should be able to hit it as usual. Test server does not change that. It is an entirely different server running on a different port. Your test can hit either your server or the test server.

Where Next? Top

Trending in Questions Top

Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
Onor.io
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
Trolleger
What approach to take when sending live updates to “random” users Hi! I have a question, I have a little chat app, and when I create a DM...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
matt-savvy
Anyone here using Honeybadger? My Honeybadger account is being overwhelmed with noise from some bots. Seeing a lot of Bandit.HTTPError...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews