unit-testingelixirex-unitplug

Handling error for large queries and sending 413 response


I have a voice note upload function. I was writing tests and as part of it I wrote the following test for larger files where I want to have it throw a 413 Entity too large error:

test "send VN fail when too large", %{conn: conn} do
  Couchdb.Connector.Storage.storage_down(CouchdbHelperFunctions.db_props(@create_user_data.username))

  {:ok, user_data} = UserManager.create_user(@create_user_data)
  {:ok, token, _} = UserManager.authenticate(@create_user_data.username, @create_user_data.password)

  conn = put_req_header(conn, "authorization", "Bearer " <> token)
  {:ok, chatroom_data} = ChatroomManager.create_chatroom(user_data.id, "test")
  {:ok, voice_note_file} = File.read("test/4051.mp3")

  conn = put_req_header(conn, "content-type", "application/octet-stream")

  response =
    conn
    |> post chatroom_chatroom_path conn, :send_voice_note, chatroom_data.id, body: voice_note_file

  assert response.status == 413
end

The test fails with this:

 1) test send_voice_note/2 send VN fail when too large (BackendWeb.ChatroomControllerTest)
 test/backend_web/controllers/chatroom_controller_test.exs:233
 ** (Plug.Conn.InvalidQueryError) maximum query string length is 1000000, got a query with 1242763 bytes
 code: |> post chatroom_chatroom_path conn, :send_voice_note, chatroom_data.id, body: voice_note_file
 stacktrace:
   (plug) lib/plug/conn.ex:845: Plug.Conn.fetch_query_params/2
   (plug) lib/plug/parsers.ex:256: Plug.Parsers.call/2
   (backend) lib/backend_web/endpoint.ex:1: BackendWeb.Endpoint.plug_builder_call/2
   (backend) lib/backend_web/endpoint.ex:1: BackendWeb.Endpoint.call/2
   (phoenix) lib/phoenix/test/conn_test.ex:224: Phoenix.ConnTest.dispatch/5
   test/backend_web/controllers/chatroom_controller_test.exs:245: (test)

I also tried adding this to my error_view.ex in hopes of having it throw a response but it didn't work out. Any ideas if i'm adding it in the wrong place?

defimpl Plug.Exception, for: Plug.Conn.InvalidQueryError do
  def status(_exception), do: 413
end

Solution

  • Ok, so I managed to fix my issue by:

    1. Changing the assert in my test to the following:

      assert_error_sent(413, fn ->
        conn
        |> post chatroom_chatroom_path conn, :send_voice_note, chatroom_data.id, body: voice_note_file    
      end
      
    2. And implementing Plug.Exception in my error_view.ex:

      defimpl Plug.Exception, for: Plug.Conn.InvalidQueryError do
        def status(_exception), do: 413
      end