diff --git a/lib/plug/adapters/test/conn.ex b/lib/plug/adapters/test/conn.ex index 6633ca40..54e6930a 100644 --- a/lib/plug/adapters/test/conn.ex +++ b/lib/plug/adapters/test/conn.ex @@ -90,8 +90,10 @@ defmodule Plug.Adapters.Test.Conn do def chunk(%{method: "HEAD"} = state, _body), do: {:ok, "", state} - def chunk(%{chunks: chunks} = state, body) do - body = chunks <> IO.iodata_to_binary(body) + def chunk(%{owner: owner, ref: ref, chunks: chunks} = state, chunk) do + chunk = IO.iodata_to_binary(chunk) + send(owner, {ref, :chunk, chunk}) + body = chunks <> chunk {:ok, body, %{state | chunks: body}} end diff --git a/lib/plug/test.ex b/lib/plug/test.ex index 3a1a774a..64e3c1b7 100644 --- a/lib/plug/test.ex +++ b/lib/plug/test.ex @@ -99,13 +99,39 @@ defmodule Plug.Test do end end + @doc """ + Returns the sent body chunks. + + This function depends on gathering the messages sent by the test adapter when + response body chunks are sent. Calling this function will clear the chunk + messages from the inbox for the process. To assert on multiple informs, the + result of the function should be stored in a variable. + + ## Examples + + conn = conn(:get, "/") + assert Plug.Test.sent_chunks(conn) == ["foo", "bar"] + """ + def sent_chunks(%Plug.Conn{adapter: {Plug.Adapters.Test.Conn, %{ref: ref}}}) do + Enum.reverse(receive_chunks(ref, [])) + end + + defp receive_chunks(ref, chunks) do + receive do + {^ref, :chunk, chunk} -> + receive_chunks(ref, [chunk | chunks]) + after + 0 -> chunks + end + end + @doc """ Returns the informational requests that have been sent. This function depends on gathering the messages sent by the test adapter when informational messages, such as an early hint, are sent. Calling this function will clear the informational request messages from the inbox for the - process. To assert on multiple informs, the result of the function should be + process. To assert on multiple informs, the result of the function should be stored in a variable. ## Examples diff --git a/test/plug/adapters/test/conn_test.exs b/test/plug/adapters/test/conn_test.exs index 7bd31d3a..11ed650a 100644 --- a/test/plug/adapters/test/conn_test.exs +++ b/test/plug/adapters/test/conn_test.exs @@ -114,6 +114,24 @@ defmodule Plug.Adapters.Test.ConnTest do assert child_conn.host == "www.elixir-lang.org" end + test "sent chunks" do + conn = conn(:get, "/") + conn = Plug.Conn.send_chunked(conn, 200) + {:ok, conn} = Plug.Conn.chunk(conn, "foo") + {:ok, conn} = Plug.Conn.chunk(conn, "bar") + + assert conn.resp_body == "foobar" + assert Plug.Test.sent_chunks(conn) == ["foo", "bar"] + end + + test "sent chunks on send_resp" do + conn = conn(:get, "/") + conn = Plug.Conn.send_resp(conn, 200, "foobar") + + assert conn.resp_body == "foobar" + assert Plug.Test.sent_chunks(conn) == [] + end + test "inform adds to the informational responses to the list" do conn = conn(:get, "/")