Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deduplicate data passed to FormPayload #137

Merged
merged 1 commit into from
Oct 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions lib/phoenix_test/form_payload.ex
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,20 @@ defmodule PhoenixTest.FormPayload do

def new(form_data) when is_list(form_data) do
form_data
|> deduplicate_preserving_order()
|> Enum.map_join("&", fn {key, value} ->
"#{URI.encode_www_form(key)}=#{if(value, do: URI.encode_www_form(value))}"
end)
|> Plug.Conn.Query.decode()
end

defp deduplicate_preserving_order(form_data) do
form_data
|> Enum.reverse()
|> Enum.uniq()
|> Enum.reverse()
end

def add_form_data(payload, form_data) when is_map(payload) and is_list(form_data) do
Enum.reduce(form_data, payload, fn {name, value}, acc ->
with_placeholder = Plug.Conn.Query.decode("#{URI.encode_www_form(name)}=placeholder")
Expand Down
24 changes: 24 additions & 0 deletions test/phoenix_test/form_payload_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ defmodule PhoenixTest.FormPayloadTest do
use ExUnit.Case, async: true

alias PhoenixTest.Form
alias PhoenixTest.FormData
alias PhoenixTest.FormPayload

describe "new" do
Expand Down Expand Up @@ -107,6 +108,29 @@ defmodule PhoenixTest.FormPayloadTest do
assert %{"hidden" => ["some_value"]} = FormPayload.new(form.form_data)
end

test "deduplicates data with same name with [] and same value" do
form_data =
"email[]"
|> FormData.to_form_data("value")
|> FormData.add_data(FormData.to_form_data("email[]", "value"))

payload = FormPayload.new(form_data)

assert payload == %{"email" => ["value"]}
end

test "preserves order of operations when deduplicating data" do
form_data =
"email"
|> FormData.to_form_data("value")
|> FormData.add_data(FormData.to_form_data("email", "other_value"))
|> FormData.add_data(FormData.to_form_data("email", "value"))

payload = FormPayload.new(form_data)

assert payload == %{"email" => "value"}
end

test "ignores hidden value for checkbox when checked" do
html = """
<form id="form">
Expand Down
Loading