Skip to content
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
2 changes: 2 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ jobs:
elixir: 1.17.x
- otp: 27.x
elixir: 1.18.x
- otp: 27.x
elixir: 1.19.x
env:
MIX_ENV: test
steps:
Expand Down
7 changes: 3 additions & 4 deletions lib/mimic/module.ex
Original file line number Diff line number Diff line change
Expand Up @@ -129,13 +129,12 @@ defmodule Mimic.Module do
if @elixir_version >= 1.18 do
defp generate_mimic_struct(module) do
if function_exported?(module, :__info__, 1) && module.__info__(:struct) != nil do
struct_info = module.__info__(:struct)

struct_template = Map.from_struct(module.__struct__())

struct_params =
for %{field: field} <- struct_info,
do: {field, Macro.escape(struct_template[field])}
Enum.map(module.__info__(:struct), fn %{field: field} ->
{field, Macro.escape(struct_template[field])}
end)

quote do
defstruct unquote(struct_params)
Expand Down
56 changes: 36 additions & 20 deletions test/mimic_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -1103,26 +1103,42 @@ defmodule Mimic.Test do
}
end

if @elixir_version >= 1.18 do
test "copies struct fields" do
StructNoEnforceKeys
|> stub(:bar, fn -> @stubbed end)

assert StructNoEnforceKeys.__info__(:struct) == [
%{field: :foo, default: nil},
%{field: :bar, default: nil}
]
end
else
test "copies struct fields" do
StructNoEnforceKeys
|> stub(:bar, fn -> @stubbed end)

assert StructNoEnforceKeys.__info__(:struct) == [
%{field: :foo, required: false},
%{field: :bar, required: false}
]
end
cond do
@elixir_version >= 1.19 ->
test "copies struct fields" do
StructNoEnforceKeys
|> stub(:bar, fn -> @stubbed end)

# Why pattern matching:
# Direct comparison causes the compiler to emit a warning.
# The `default` key may or may not exist in the struct info.
assert [
%{field: :foo, default: nil, required: false},
%{field: :bar, default: nil, required: false}
] = StructNoEnforceKeys.__info__(:struct)
end

@elixir_version >= 1.18 ->
test "copies struct fields" do
StructNoEnforceKeys
|> stub(:bar, fn -> @stubbed end)

assert StructNoEnforceKeys.__info__(:struct) == [
%{field: :foo, default: nil},
%{field: :bar, default: nil}
]
end

true ->
test "copies struct fields" do
StructNoEnforceKeys
|> stub(:bar, fn -> @stubbed end)

assert StructNoEnforceKeys.__info__(:struct) == [
%{field: :foo, required: false},
%{field: :bar, required: false}
]
end
end

test "protocol still works" do
Expand Down
Loading