With help from several knowledgeable people I managed to write a very small unit test library, something roughly similar to D's unittest feature. It works for me (TM) with Nim 0.10.0 on Win64 and Mingw64 4.9.1.
The code (updated version: w/o warnings, some work done doing compile time, code duplication removed):
# ---- simple_unit_test.nim ---
import os, times
# Minimalistic unit test library.test
# In public domain.
#
# Possible improvements:
# * extract the source modification time only once per each file (if it is faster)
# * modify system.assert to find out it failed inside an unit test,
# if so then inform the user and print out unit test name
# * ensure it can be used when compiled as windows application (not console)
template TEST*(body : stmt) =
{.push warning[user]: off}
when defined (unit_tests):
body
when defined (recent_unit_tests):
const src_file_name = instantiation_info(-1, true).filename
const modification_time = int(get_last_modification_time(src_file_name))
const now = int(get_time())
if now - modification_time < 30 * 60: # test files modified during last 30 minutes
body
{.pop.}
template TEST*(name : string, body : stmt) = TEST(body)
# EOF
and can be used like this:
# --- b.nim ---
import simple_unit_test
proc a_func = echo "a_func"
TEST:
a_func()
# --- a.nim ---
import b
import simple_unit_test
proc foo = echo "foo"
TEST:
foo()
TEST "some name" :
foo()
proc bar = echo "bar"
TEST:
bar()
TEST "some name2":
bar()
proc will_crash =
echo "will_crash"
assert(false)
# uncomment to see how failed test looks like
#TEST:
# will_crash()
# EOF
Compilation options:
nim c a.nim # no unit tests
nim c -d:unit_tests a.nim # all unit tests are compiled and run
nim c -d:recent_unit_tests a.nim # runs tests from sources modified within last 1/2 h
Cool, thanks for sharing.
Turns out gorge wasn't necessary then... I thought you couldn't call importc functions, as I was getting:
Error: cannot 'importc' variable at compile time
but this seems to be because I had installed Nim using koch install. When I added path_to_nimsrc/bin to my PATH, everything worked as expected.
Hi, I know this is trivial, but would you mind including a license like MIT with the code? (Also it'd be cool to have it uploaded to a tiny repo on GitHub in case anyone wants to suggest small improvements)
P.S. Sorry for reviving a 5 year old thread :P