Skip to content

Commit

Permalink
Fix regression where wrong type would raise an
Browse files Browse the repository at this point in the history
unexpected error
  • Loading branch information
mathieuprog committed Sep 29, 2022
1 parent 59f8a2c commit 946d513
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 6 deletions.
8 changes: 2 additions & 6 deletions lib/polymorphic_embed.ex
Original file line number Diff line number Diff line change
Expand Up @@ -380,14 +380,10 @@ defmodule PolymorphicEmbed do
end

defp get_metadata_for_type(type, types_metadata) do
type = maybe_to_existing_atom(type)
Enum.find(types_metadata, &(type == &1.type))
type = to_string(type)
Enum.find(types_metadata, &(type == to_string(&1.type)))
end

defp maybe_to_existing_atom(value) when is_atom(value), do: value

defp maybe_to_existing_atom(value), do: String.to_existing_atom(value)

defp get_field_options(schema, field) do
try do
schema.__schema__(:type, field)
Expand Down
47 changes: 47 additions & 0 deletions test/polymorphic_embed_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -522,6 +522,53 @@ defmodule PolymorphicEmbedTest do
assert email_module == reminder.channel.__struct__
end

test "wrong type as string adds error in changeset" do
generator = :polymorphic
reminder_module = get_module(Reminder, generator)

attrs = %{
date: ~U[2020-05-28 02:57:19Z],
text: "This is an Email reminder",
channel: %{
my_type_field: "unknown type"
}
}

insert_result =
struct(reminder_module)
|> reminder_module.changeset(attrs)
|> Repo.insert()

assert {:error, %Ecto.Changeset{errors: [channel: {"is invalid", []}]}} = insert_result
end

test "wrong type as string raises" do
generator = :polymorphic
reminder_module = get_module(Reminder, generator)

sms_reminder_attrs = %{
date: ~U[2020-05-28 02:57:19Z],
text: "This is an SMS reminder",
channel: %{
my_type_field: "sms",
number: "02/807.05.53",
country_code: 1,
result: %{success: true},
attempts: [],
provider: %{
__type__: "unknown type",
api_key: "foo"
}
}
}

assert_raise RuntimeError, ~r"could not infer polymorphic embed from data", fn ->
struct(reminder_module)
|> reminder_module.changeset(sms_reminder_attrs)
|> Repo.insert()
end
end

test "pass non-changeset as first argument to cast_polymorphic_embed/3 should fail" do
generator = :polymorphic

Expand Down

0 comments on commit 946d513

Please sign in to comment.