unittest_light.nim 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import std/assertions
  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. result = ""
  8. proc replaceInvisible(s: string): string =
  9. result = ""
  10. for a in s:
  11. case a
  12. of '\n': result.add "\\n\n"
  13. else: result.add a
  14. proc quoted(s: string): string =
  15. result = ""
  16. result.addQuoted s
  17. result.add '\n'
  18. result.add "lhs:{" & replaceInvisible(
  19. $lhs) & "}\nrhs:{" & replaceInvisible($rhs) & "}\n"
  20. when compiles(lhs.len):
  21. if lhs.len != rhs.len:
  22. result.add "lhs.len: " & $lhs.len & " rhs.len: " & $rhs.len & '\n'
  23. when compiles(lhs[0]):
  24. var i = 0
  25. while i < lhs.len and i < rhs.len:
  26. if lhs[i] != rhs[i]: break
  27. i.inc
  28. result.add "first mismatch index: " & $i & '\n'
  29. if i < lhs.len and i < rhs.len:
  30. result.add "lhs[i]: {" & quoted($lhs[i]) & "}\nrhs[i]: {" & quoted(
  31. $rhs[i]) & "}\n"
  32. result.add "lhs[0..<i]:{" & replaceInvisible($lhs[
  33. 0..<i]) & '}'
  34. proc assertEquals*[T](lhs: T, rhs: T, msg = "") =
  35. if lhs != rhs:
  36. doAssert false, mismatch(lhs, rhs) & '\n' & msg