samdze / playdate-nim

Nim bindings with extra features for the Playdate SDK
66 stars 3 forks source link

Any guidance on unit tests? #42

Closed ninovanhooff closed 7 months ago

ninovanhooff commented 10 months ago

I see the main repo contains tests, but the playdate_example doesn't. The Nim docs mentoin the existence of the unittest module and the testament executable. Briefly tried testament, but I think it tried to compile my project for the host system (apple arm64) and failed. Decided not to dive into that rabbit hole. My testing requirements are simple:

My current approach uses a bunch of asserts, which are placed outside of the src folder. The runTests proc is wrapped in a catching function that prints a stacktrace to the playdate error console, which halts execution. Therefore, it only shows the first failed test

So I'm wondering whether there is a recommended approach for this, and what you think of my current approach: https://github.com/ninovanhooff/wheelsprung/tree/rider/

ninovanhooff commented 7 months ago

Here is a neat function that will print the expression under test, the expected value and the actual value

import strformat, strutils, macros

template check*(exp:untyped, expected: untyped, failureMsg:string="failed", indent:uint=0): void =
  let indentationStr = repeat(' ', indent)
  let expStr: string = astToStr(exp)
  var msg: string
  if exp != expected:
    msg = indentationStr & expStr & " .. " & failureMsg & "\n (expected: " & astToStr(expected) & ", actual: " & $exp & ")"
  else:
    msg = indentationStr & expStr & " .. passed"

  print(msg) # replace this by your print function

  check(1+2, 3) # "1 + 2 .. passed"
  check(1+1, 3) # "1 + 1 .. failed (expected: 3, actual: 2)"