2

I'm trying to use Plug.Test to test error handling implemented with Plug.ErrorHandler -- with assert conn.status == 406 and alike.

I have the defp handle_errors (containing a single send_resp statement) and it seems to be called, however, my tests fail with the same exception still (as if handle_errors has no effect).

A reference to a sample advanced Plug (not Phoenix) app will also be appreciated.

Costa Shapiro
  • 524
  • 1
  • 3
  • 8

2 Answers2

0

Try something like this (not tested):

defmodule NotAcceptableError do
  defexception plug_status: 406, message: "not_acceptable"
end

defmodule Router do
  use Plug.Router
  use Plug.ErrorHandler

  plug :match
  plug :dispatch

  get "/hello" do
    raise NotAcceptableError
    send_resp(conn, 200, "world")
  end

  def handle_errors(conn, %{kind: _kind, reason: reason, stack: _stack}) do
    send_resp(conn, conn.status, reason.message)
  end
end

test "error" do
  conn = conn(:get, "/hello")

  assert_raise Plug.Conn.WrapperError, "** (NotAcceptableError not_acceptable)", fn ->
    Router.call(conn, [])
  end

  assert_received {:plug_conn, :sent}
  assert {406, _headers, "not_acceptable"} = sent_resp(conn)
end
Cameron
  • 4,181
  • 9
  • 36
  • 40
  • That's exactly what I tried before posting this question, but it's not a solution. – Costa Shapiro May 25 '20 at 12:39
  • Try overriding the `handle_errors/2`, and use the given `reason`. That passes the test for me (see edited above). – Cameron May 29 '20 at 15:11
  • Thanks for your reply, but matching against a formatted string is not a solution for me. I was expecting to be able to match the actual error type or something. – Costa Shapiro Jun 01 '20 at 16:24
0

Use assert_error_sent/2 to assert that you raised an error and it was wrapped and sent with a particular status. Match against its {status, headers, body} return value to assert the rest of the HTTP response met your expectations.

response = assert_error_sent 404, fn ->
  get(build_conn(), "/users/not-found")
end
assert {404, [_h | _t], "Page not found"} = response
Garth Kidd
  • 7,264
  • 5
  • 35
  • 36