bjornbytes/lust

Assertions comparing tables print less-than-useful information

Closed this issue · 2 comments

Coming from Elixir I've been spoiled by assertions on lists/maps printing color-coded deep comparisons on failure:

Screenshot 2024-05-08 at 12 52 45

I tried doing something similar with lust and realised I was getting something like this

Screenshot 2024-05-08 at 12 55 08

This is my only gripe with the library so far - it's been trivial to integrate into a Love2D project and get started with, even for a Lua beginner - thank you so much for that.

My fast and dirty solution has been to add this chunk to my vendored copy of lust.lua:

local outer_tostring = tostring

local function tostring(v)
  if type(v) == 'table' then
    local ret = '{'
    local first = true
    for key, value in pairs(v) do
      if not first then
        ret = ret .. ', '
      end
      ret = ret .. tostring(key) .. ' = ' .. tostring(value)
      first = false
    end

    return ret .. '}'
  else
    return outer_tostring(v)
  end
end

...which gives me assertion errors like this instead:

Screenshot 2024-05-08 at 13 01 15

It works well enough for me for now, but I know it could use some improvements:

  • It applies to all places where lust uses tostring, whereas it should probably be used only for representing the values used in assertions
  • you can't distinguish between "42" and 42, for example, because they tostring the same
  • "regular" arrays get printed like generic tables, instead of like {1, 1, 2, 3, 5}
  • both tables being printed in the same line are hard to compare, it would be easier if they were one under the other
  • there should probably be a limit of text printed per table, otherwise asserting on big maps would potentially blow up the test output

And ideally we could have the the color-coded comparison like with ExUnit, but that would probably require us to add more complexity to lust than it's worth.


I'm mainly leaving this issue as a placeholder and a note to myself - I'd love to make a more comprehensive and well-formed fix when I have some time.

If you had some time to review that when it happens, @bjornbytes, and maybe merge in to lust if it works for you, I'd appreciate that. I'd love to contribute back to the library instead of running my own crappy fork, and I suspect even my final PR could probably use a thorough review - I've been writing Lua for less than a week now and I probably do a lot of silly stuff...

Hey, thanks for the issue. This is a good point and I agree that there should be more sophisticated table serialization. Feel free to take a stab at it when you have time, I'd be happy to merge it in.

One thing to keep in mind during this change is that tables can have a __tostring metamethod which allows overriding the tostring result for a table. lust should probably continue to respect that metamethod if it's set.

image

Added simple table comparison!