Assertions with Enum.any?

I am trying to unit test a function that returns a very long list (by necessity), every element of which should satisfy a certain condition. I am presently testing it like this…

assert Enum.all?(some_func(...), fn x ->

…which works, but I have to look through the list manually to see which element failed the test. How could I get better reporting that gives me this information?

How about using Enum.filter/2 where you keep all the elements that does not satisfy the condition?
The list should be smaller and it’d be easier to inspect.

1 Like

You can build your own version of Enum.all? based on Enum.reduce_while. all? is meant to only return a boolean value.

1 Like

Maybe in this way:

|> Enum.with_index()
|> Enum.each(fn {element, index} ->
  assert check(element), "#{index} fails: #{inspect(element)}"


assert some_func(...)
       |> Enum.with_index()
       |> Enum.reject(fn {element, _index} ->
       end) == []

@Marcus gave you an excellent suggestion IMO. This will give you a context – the index of the element and the element itself – after an assertion fails.

1 Like

Excellent, thanks! (I went with the second option because in this case I only need to see the first thing that failed.)