Skip to content

Commit

Permalink
copy structs when they exist
Browse files Browse the repository at this point in the history
  • Loading branch information
harrisi authored and edgurgel committed Jun 21, 2024
1 parent ca14511 commit 572e837
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
11 changes: 10 additions & 1 deletion lib/mimic/module.ex
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,20 @@ defmodule Mimic.Module do
mimic_info = module_mimic_info()
mimic_behaviours = generate_mimic_behaviours(module)
mimic_functions = generate_mimic_functions(module)
quoted = [mimic_info | [mimic_behaviours ++ mimic_functions]]
mimic_struct = generate_mimic_struct(module)
quoted = [mimic_info, mimic_struct | mimic_behaviours ++ mimic_functions]
Module.create(module, quoted, Macro.Env.location(__ENV__))
module
end

defp generate_mimic_struct(module) do
if module.__info__(:struct) != nil do
quote do
defstruct unquote(for %{field: field} <- module.__info__(:struct), do: field)
end
end
end

defp module_mimic_info do
quote do: def(__mimic_info__, do: :ok)
end
Expand Down
15 changes: 15 additions & 0 deletions test/mimic_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -945,4 +945,19 @@ defmodule Mimic.Test do
assert_receive {:add, 1, 2}
end
end

describe "structs" do
test "copies struct fields" do
struct_fields =
Structs.__info__(:struct)
|> Enum.map(&Map.get(&1, :field))

Mimic.copy(Structs)

Structs
|> stub(:foo, fn -> :stubbed end)

assert Structs.__info__(:struct) |> Enum.map(&Map.get(&1, :field)) == struct_fields
end
end
end
6 changes: 6 additions & 0 deletions test/support/test_modules.ex
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,9 @@ defmodule NoStubs do
@moduledoc false
def add(x, y), do: x + y
end

defmodule Structs do
@moduledoc false
defstruct [:foo, :bar]
def foo, do: nil
end

0 comments on commit 572e837

Please sign in to comment.