Skip to content

Add warning when implicitly casting maps/keywords to struct encode-time #413

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

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
13 changes: 12 additions & 1 deletion lib/protobuf/encoder.ex
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,18 @@ defmodule Protobuf.Encoder do
message:
"struct #{inspect(other_mod)} can't be encoded as #{inspect(mod)}: #{inspect(struct)}"

_ ->
enumerable ->
IO.warn("""
Implicit casting from #{inspect(enumerable)} to #{inspect(mod)} struct.
This automatic coercion is deprecated in Protobuf 0.15 and will raise an error in future versions.

Instead of:
%Parent{child: %{name: ""}}

Build child structs explicitly:
%Parent{child: %Child{name: ""}}
""")

do_encode_to_iodata(struct(mod, msg))
end
end
Expand Down
14 changes: 13 additions & 1 deletion test/protobuf/encoder_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,10 @@ defmodule Protobuf.EncoderTest do
end

test "encodes map with oneof" do
msg = %Google.Protobuf.Struct{fields: %{"valid" => %{kind: {:bool_value, true}}}}
msg = %Google.Protobuf.Struct{
fields: %{"valid" => %Google.Protobuf.Value{kind: {:bool_value, true}}}
}

bin = Google.Protobuf.Struct.encode(msg)

assert Google.Protobuf.Struct.decode(bin) ==
Expand Down Expand Up @@ -309,6 +312,15 @@ defmodule Protobuf.EncoderTest do
end
end

test "gives a warning for implicitly cast structs" do
warning =
ExUnit.CaptureIO.capture_io(:stderr, fn ->
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This makes this test not really async-friendly anymore. Can we turn it to async: false and leave a comment up there explaining why (and maybe a TODO to turn it back async when we remove this warning)?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great point, added!

assert <<50, 2, 8, 1>> = Encoder.encode(%TestMsg.Foo{e: %{a: 1}})
end)

assert warning =~ "Implicit casting from %{a: 1} to TestMsg.Foo.Bar"
end

test "encodes with transformer module" do
msg = %TestMsg.ContainsTransformModule{field: 0}
assert Encoder.encode(msg) == <<10, 0>>
Expand Down
Loading