unittest_light.nim 1.4 KB

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