summary refs log tree commit diff stats
path: root/compiler/unittest_light.nim
blob: d9842b3994c9154711c3f9448483b6511c100e43 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# note: consider merging tests/assert/testhelper.nim here.

proc mismatch*[T](lhs: T, rhs: T): string =
  ## Simplified version of `unittest.require` that satisfies a common use case,
  ## while avoiding pulling too many dependencies. On failure, diagnostic
  ## information is provided that in particular makes it easy to spot
  ## whitespace mismatches and where the mismatch is.
  proc replaceInvisible(s: string): string =
    for a in s:
      case a
      of '\n': result.add "\\n\n"
      else: result.add a

  proc quoted(s: string): string = result.addQuoted s

  result.add "\n"
  result.add "lhs:{" & replaceInvisible(
      $lhs) & "}\nrhs:{" & replaceInvisible($rhs) & "}\n"
  when compiles(lhs.len):
    if lhs.len != rhs.len:
      result.add "lhs.len: " & $lhs.len & " rhs.len: " & $rhs.len & "\n"
    when compiles(lhs[0]):
      var i = 0
      while i < lhs.len and i < rhs.len:
        if lhs[i] != rhs[i]: break
        i.inc
      result.add "first mismatch index: " & $i & "\n"
      if i < lhs.len and i < rhs.len:
        result.add "lhs[i]: {" & quoted($lhs[i]) & "}\nrhs[i]: {" & quoted(
            $rhs[i]) & "}\n"
      result.add "lhs[0..<i]:{" & replaceInvisible($lhs[
          0..<i]) & "}"

proc assertEquals*[T](lhs: T, rhs: T) =
  when false: # can be useful for debugging to see all that's fed to this.
    echo "----" & $lhs
  if lhs!=rhs:
    doAssert false, mismatch(lhs, rhs)