Skip to content

Commit 3ef2fb5

Browse files
Add unit tests for outer-document-only pk rename
Pure unit tests on `Mongo.Ecto.Conversions.from_ecto_pk/2` and `inject_params/3` covering the recursion fix: - top-level `:id` is renamed to `:_id` - a nested map's `:id` is left alone even when the parent pk is `:id` - the same holds inside a list of nested maps - `pk: nil` is a no-op Verified by reverting `conversions.ex` to the pre-patch version: 3 of the 5 tests fail (nested `:id` ends up as `:_id`). With the patch they all pass.
1 parent 5d53d6f commit 3ef2fb5

1 file changed

Lines changed: 72 additions & 0 deletions

File tree

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
defmodule Mongo.Ecto.ConversionsTest do
2+
use ExUnit.Case, async: true
3+
4+
alias Mongo.Ecto.Conversions
5+
6+
describe "from_ecto_pk/2" do
7+
test "renames the primary key to :_id at the top level" do
8+
assert {:ok, encoded} = Conversions.from_ecto_pk(%{id: "abc", title: "t"}, :id)
9+
10+
assert Map.new(encoded) == %{_id: "abc", title: "t"}
11+
end
12+
13+
test "does not rename :id inside a nested map when the parent pk is :id" do
14+
input = %{
15+
id: "abc",
16+
title: "outer",
17+
jurisdiction: %{id: "MD", title: "Maryland"}
18+
}
19+
20+
assert {:ok, encoded} = Conversions.from_ecto_pk(input, :id)
21+
22+
encoded_map = Map.new(encoded)
23+
assert encoded_map[:_id] == "abc"
24+
refute Map.has_key?(encoded_map, :id)
25+
26+
# The nested :id field must be passed through unchanged — it belongs to
27+
# the embedded sub-document, not the parent schema.
28+
assert Map.new(encoded_map[:jurisdiction]) == %{id: "MD", title: "Maryland"}
29+
end
30+
31+
test "does not rename :id inside a list of nested maps" do
32+
input = %{id: "abc", items: [%{id: "one"}, %{id: "two"}]}
33+
34+
assert {:ok, encoded} = Conversions.from_ecto_pk(input, :id)
35+
36+
encoded_map = Map.new(encoded)
37+
assert encoded_map[:_id] == "abc"
38+
39+
assert Enum.map(encoded_map[:items], &Map.new/1) == [
40+
%{id: "one"},
41+
%{id: "two"}
42+
]
43+
end
44+
45+
test "leaves nested maps alone when the pk is nil" do
46+
input = %{id: "abc", jurisdiction: %{id: "MD"}}
47+
48+
assert {:ok, encoded} = Conversions.from_ecto_pk(input, nil)
49+
50+
encoded_map = Map.new(encoded)
51+
assert encoded_map[:id] == "abc"
52+
assert Map.new(encoded_map[:jurisdiction]) == %{id: "MD"}
53+
end
54+
end
55+
56+
describe "inject_params/3" do
57+
test "renames the primary key to :_id only at the top level" do
58+
input = %{
59+
id: "abc",
60+
jurisdiction: %{id: "MD", title: "Maryland"}
61+
}
62+
63+
assert {:ok, encoded} = Conversions.inject_params(input, {}, :id)
64+
65+
encoded_map = Map.new(encoded)
66+
assert encoded_map[:_id] == "abc"
67+
refute Map.has_key?(encoded_map, :id)
68+
69+
assert Map.new(encoded_map[:jurisdiction]) == %{id: "MD", title: "Maryland"}
70+
end
71+
end
72+
end

0 commit comments

Comments
 (0)