Force Hackney request timeout in test

717 views Asked by At

I'm looking for a way to be able to reproduce a Hackney HTTP POST request timeout in one of my controller tests. I'm also using ExVCR, but that doesn't seem to allow you to force a request timeout either.

I've tried setting the Hackney timeout to 1 when I make the request, and it times out, but I don't want to actually make the request in my test.

I'd be open to using a mock/stub, but want to make sure I can still use ExVCR in the unit tests that are actually making requests to the service I'm integrating with. All the mock libraries and patterns I've seen stub out the entire module for the entire test environment which is not what I want.

Here's a sample of the request I'm making:

:hackney.post(url, [timeout: 1], body, get_auth())

and I would like this to return {:error, :timeout} which is what Hackney returns in a real timeout scenario.

1

There are 1 answers

0
Guillaume Milan On

If I understood correctly the question, you want :hackney to timeout during test

  • If you don't want to make the query, it's better to make a macro that execute different codes between test and production.

  • If you want to create a server that can force timeout: You can create a router that take some time to answer with a Plug.Router module.

For example with the following code:

defmodule MyRouter do 
   use Plug.Router 
   plug(:match)
   plug(:dispatch)

   post _ do 
     :timer.sleep(2000)
    send_resp(conn, 200, "ok")
   end
end

Be sure to start the router with the command Plug.Adapters.Cowboy.child_spec(:http, MyRouter, [], [port: 4000])

You can query the server at the address 127.0.0.1:4000/ with your :hackney command.

Hope I understood the question correctly