unittest_light.nim 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. proc mismatch*[T](lhs: T, rhs: T): string =
  2. ## Simplified version of `unittest.require` that satisfies a common use case,
  3. ## while avoiding pulling too many dependencies. On failure, diagnostic
  4. ## information is provided that in particular makes it easy to spot
  5. ## whitespace mismatches and where the mismatch is.
  6. proc replaceInvisible(s: string): string =
  7. for a in s:
  8. case a
  9. of '\n': result.add "\\n\n"
  10. else: result.add a
  11. proc quoted(s: string): string = result.addQuoted s
  12. result.add "\n"
  13. result.add "lhs:{" & replaceInvisible(
  14. $lhs) & "}\nrhs:{" & replaceInvisible($rhs) & "}\n"
  15. when compiles(lhs.len):
  16. if lhs.len != rhs.len:
  17. result.add "lhs.len: " & $lhs.len & " rhs.len: " & $rhs.len & "\n"
  18. when compiles(lhs[0]):
  19. var i = 0
  20. while i < lhs.len and i < rhs.len:
  21. if lhs[i] != rhs[i]: break
  22. i.inc
  23. result.add "first mismatch index: " & $i & "\n"
  24. if i < lhs.len and i < rhs.len:
  25. result.add "lhs[i]: {" & quoted($lhs[i]) & "}\nrhs[i]: {" & quoted(
  26. $rhs[i]) & "}\n"
  27. result.add "lhs[0..<i]:{" & replaceInvisible($lhs[
  28. 0..<i]) & "}"
  29. proc assertEquals*[T](lhs: T, rhs: T, msg = "") =
  30. when false: # can be useful for debugging to see all that's fed to this.
  31. echo "----" & $lhs
  32. if lhs!=rhs:
  33. doAssert false, mismatch(lhs, rhs) & "\n" & msg