Fl4m3Ph03n1x
How to test a Phoenix application with Bypass?
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
- Is this the correct way to exercise the entire stack using ByPass with Phoenix?
- Is there a better way of testing this?
- Why can’t I access my application?
Trending in Questions
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
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
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated!
To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead.
Sta...
New
Hello !
We want new/edit form pages to POST/PUT to their own URL rather than the resources REST defaults (post /things, put /things/:id)...
New
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app?
Looking for hints regarding:
Addi...
New
Hi all, I wanted to ask how the community is dealing with post-release steps.
Today we have Ecto migrations, which make sure that the db...
New
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
New
Other Trending Topics
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
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve.
They are GUI (Emerge) and State management (S...
New
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
@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
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #elixirconf-us
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #performance
- #security










First 10 of 12 Posts!
fuelen
You don’t need to start
MyApp.Applicationmanually.mixdoes this for you. Checkmix.exsfile, probably it has something like this:Bypassstarted a server using port5112, but you’re making requests to4000Fl4m3Ph03n1x
I am confused then. My objective is to use
bypassto simulate the response from the external service (which uses port 5112). Port4000is the default port for when I usemix 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 port5112?If so, how do I make bypass distinguish between them?
mudasobwa
bypassobviously cannot mock external ports, it injects a plug into your server pipeline, that’s it.Fl4m3Ph03n1x
So, this means I cannot use
bypassto mock responses from an external service while also usingHTTTPoisonto directly call my application, correct?The best I could do is to directly call the
validatefunction inMyApp.ValidateControllerand then usebypassto mock the response from the external service said controller would eventually call, right?mudasobwa
I am not sure I see any advantage of using
bypassovermoxhere.I would do the following: mock
HTTPoison.Basebehaviour withmox. Make an HTTP client configurable, and point the configuration to yourMoxmodule forHTTPoisonin test env, and toHTTPoisonotherwise. Do return whatever you want from the mocks.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
Isn’t this the same as
bypass?Meaning, if I use
testserverI will not be able to call my app’s endpoints while simulating the third party, correct?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
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: truefor the endpoint inconfig/test.exswould 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
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.
Last Post!
Fl4m3Ph03n1x
It has come to my attention that perhaps the best way to achieve my goal is to test the controller directly and use something like Mox or Hammox to simulate the external service.
This is due to the fact that my original plan, of doing an integration test using
bypassto simulate a response from a 3rd party service together with anHTTPoisoncall to my actual application are not compatible, sincebypasswill intersect calls to my application, preventing the 3rd party service of being called.With this in mind I have now changed the direction of my search:
And will leave this as concluded.