Created
February 12, 2025 19:31
-
-
Save Nezteb/e4599e1494d61b6ae9a50bb1c8fb0e2e to your computer and use it in GitHub Desktop.
Elixir ExUnit helper for asserting that two maps (or structs) have equal values at the specified paths.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule TestHelpers do | |
import ExUnit.Assertions, only: [assert: 2, flunk: 1] | |
@spec assert_nested_paths_equal(map(), map(), [atom()]) :: :ok | |
def assert_nested_paths_equal(map1, map2, paths) do | |
Enum.each(paths, fn path -> | |
with {:ok, value1} <- get_nested_field(map1, path), | |
{:ok, value2} <- get_nested_field(map2, path) do | |
assert value1 == value2, | |
"Path #{inspect(path)} differs: #{inspect(value1)} != #{inspect(value2)}" | |
else | |
{:error, key} -> | |
flunk("Path missing key: #{inspect(path)} (key: #{inspect(key)})") | |
end | |
end) | |
end | |
defp get_nested_field(struct, path) when is_list(path) do | |
Enum.reduce_while(path, {:ok, struct}, fn key, {:ok, acc} -> | |
case Map.fetch(acc, key) do | |
{:ok, value} -> {:cont, {:ok, value}} | |
:error -> {:halt, {:error, key}} | |
end | |
end) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment