Skip to content
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

Copy structs when they exist #67

Merged
merged 1 commit into from
Jun 21, 2024
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
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
Loading