unittest_light.nim 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  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. 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, msg = "") =
  31. if lhs != rhs:
  32. doAssert false, mismatch(lhs, rhs) & '\n' & msg