Testing Elixir - MapSet.new vs. Enum.sort in unit test example

Title: Testing Elixir - MapSet.new vs. Enum.sort (p. 80 PDF)

The example on this page shows an assertion with the code:

code: assert Enum.sort(actual_fields_with_types) ==
       Enum.sort(@expected_fields_with_types)

But the previous code example (p.77) uses MapSet.New instead of Enum.sort:

code: assert MapSet.new(actual_fields_with_types) ==
       MapSet.new(@expected_fields_with_types)

Not sure which is better, TBH. :smiley:

Also while I’m here – p83, there’s a typo, attibribute should be attribute. :smiley:

…Paul

2 Likes

Not sure if I submitted this right, LMK. :smiley:

2 Likes

Depends on what you want to test, as the behaviour of these is different in case of actual_fields_with_types = [1,2,1] and @expected_fields_with_types == [2, 1]

2 Likes

Yeah, I was thinking that myself, but either way, the text is inconsistent. Not sure if the intent was to switch back to Enum.sort and it didn’t get backported, or the intention was go forward with MapSet.new (which is actually described in the text as the method used) and wasn’t copied all the way through.

2 Likes

Thanks @dotdotdotpaul! This is funny because I was using Enum.sort and Andrea was pushing for MapSet.new. I let him switch up the code sample (I wrote the majority of that chapter) and it looks like that led to some inconsistency. We will get fix it so that it used one or the other, but I will try to address the trade-offs here so you can decide which you prefer.

MapSet.new is fast and consistent, but, as @hauleth pointed out, it doesn’t allow duplicate entries. So… it honestly just depends on what you need. The thing that I tend to find myself doing is writing a single test assertion helper, called something like assert_unordered_lists_are_equal(lists, opts \\ []) and let the opts include :allow_dupes. Then, you have a clearly stated function and the implementation isn’t as important. In fact, depending on the options, you can do it in a different way. That only issue there, then would be slight inconsistency in the test output.

We don’t write a ton of helper functions in the samples, largely because the more complex or spread the code, the harder it is to fit on the page.

Again, thanks for catching the inconsistency. We’ll get that resolved, but ultimately, both solutions are just fine unless you need duplicates in your list.

2 Likes

Cool beans, glad I could help. :smiley:

2 Likes