Proposal: assert_in_delta option to allow difference <= delta

21 views
Skip to first unread message

Devon Estes

unread,
Jan 8, 2018, 8:30:08 AM1/8/18
to elixir-lang-core
Howdy,

So I'm writing a bunch of tests today that involve checking the output of a function against some known good values and asserting that they're similar enough. These are all lists, and the code I'm using for that is this:

  defp assert_similar(list_1, list_2) do
    [list_1, list_2]
    |> Enum.zip()
    |> Enum.each(fn {left, right} ->
      assert_in_delta(left, right, right * 0.015)
    end)
  end

However, some of those values are zeros, which gives me the failure below:

     Expected the difference between 0 and 0 (0) to be less than 0.0

We discussed the issues with a negative value and assert_in_delta here: https://github.com/elixir-lang/elixir/issues/6439, but what about 0? Since absolute values can't be negative, this seems like something we should make impossible or fix somehow.

I think we could fix this if we allow the difference to be less than or equal to the delta instead of strictly less than the delta. I'm no statistician so that might be madness in that world, but it would solve this issue, and I don't think it would be unexpected by users.

Whether the user wants to accept equality as well could also be passed as an optional configuration to the macro, but considering that isn't really done anywhere else I'm not sure that's the way to go here.

The only way I found so far to work around this is below:

  defp assert_similar(list_1, list_2) do
    [list_1, list_2]
    |> Enum.zip()
    |> Enum.each(fn {left, right} ->
      if left != 0 and right != 0 do
        assert_in_delta(left, right, right * 0.015)
      else
        assert left == right
      end
    end)
  end

José Valim

unread,
Jan 8, 2018, 8:44:51 AM1/8/18
to elixir-l...@googlegroups.com
Please do send a PR.



José Valim
Founder and 
Director of R&D

--
You received this message because you are subscribed to the Google Groups "elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-core+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-lang-core/a8753e77-3993-4127-83b0-73e5bf683d1a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages