atomkirk

atomkirk

Assert a list of patterns ignoring order

Do you think theres a way to write a function that matches a list of patterns with a list of values ignoring order? We use UXID and insert_all in our code a lot (which means all the inserted_at values are the same), which means theres not many options for guaranteeing sort order of results for doing assert […, …] = Repo.all(Model) which means tests are flakey. I just want to test “Records with these shapes were inserted into the db” and I don’t care about order.

@josevalim per https://twitter.com/josevalim/status/1493725996276760582

Most Liked

josevalim

josevalim

Creator of Elixir

Here is a macro (with tests) that matches all elements in the collection matches exactly one pattern in the list:

defmodule ListAssertions do
  defmacro assert_unordered(patterns, expression) when is_list(patterns) do
    clauses =
      patterns
      |> Enum.with_index()
      |> Enum.flat_map(fn {pattern, index} ->
        quote do
          unquote(pattern) -> unquote(index)
        end
      end)

    clauses =
      clauses ++
        quote do
          _ -> :not_found
        end

    quote do
      ListAssertions.__assert_unordered__(
        unquote(Macro.escape(patterns)),
        unquote(expression),
        fn x -> case x, do: unquote(clauses) end
      )
    end
  end

  def __assert_unordered__(patterns, enum, fun) do
    result =
      Enum.reduce(enum, %{}, fn item, acc ->
        case fun.(item) do
          :not_found ->
            raise ArgumentError,
                  "#{inspect(item)} does not match any pattern: #{Macro.to_string(patterns)}"

          index when is_map_key(acc, index) ->
            raise ArgumentError,
                  "both #{inspect(item)} and #{inspect(acc[index])} match pattern: " <>
                    Macro.to_string(Enum.fetch!(patterns, index))

          index when is_integer(index) ->
            Map.put(acc, index, item)
        end
      end)

    if map_size(result) == length(patterns) do
      :ok
    else
      raise ArgumentError,
            "expected enumerable to have #{length(patterns)} entries, got: #{map_size(result)}"
    end
  end
end

ExUnit.start()

defmodule ListAssertionsTest do
  use ExUnit.Case, async: true

  import ListAssertions

  test "all match" do
    assert_unordered([:foo, :bar, :baz], [:foo, :baz, :bar])
    assert_unordered([{:ok, _}, {:error, _}], [{:error, :bad}, {:ok, :good}])
  end

  test "duplicates" do
    assert_unordered([{:ok, _}, {:error, _}], [{:error, :bad}, {:ok, :good}, {:ok, :bad}])
  end

  test "too few" do
    assert_unordered([{:ok, _}, {:error, _}], [{:error, :bad}])
  end

  test "unknown" do
    assert_unordered([{:ok, _}, {:error, _}], [:what])
  end
end

Better error messages that integrate nicely with ExUnit are left as an exercise to the reader. :slight_smile:

23
Post #8
LostKobrakai

LostKobrakai

It might sound dump, but if your data has no fixed order, then do not use assertions, which require order. Enum.find can do that for example. Testing for the length of lists can also make sure you‘re not missing records or have additional ones.

Sebb

Sebb

You could find some inspiration here:

just make it take a list of maps to match agains your values.

atomkirk

atomkirk

Works like a frickin’ charm. This seems generally useful. Do you want me to improve messages (like you said) and offer PR to add to ExUnit.Assertions?

josevalim

josevalim

Creator of Elixir

At the moment I don’t think it is ExUnit.Assertions material but I will keep an eye open for more use cases!

Where Next?

Popular in Questions Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
New
logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
sacepums
Hey guys. I'm new to elixir and im really stocked about it. But I ran into a bit of problem - I need to convert a date sting, for examp...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
Exadra37
Sometimes I want to check if the input into a function is not a blank string. My first approach: defmodule Example do def do_stuff(s...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New

Other popular topics Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1140 51847 244
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

We're in Beta

About us Mission Statement