I'm planning a project with multiple modules, and I was looking for a nice solution to run all existing unit tests in the project at once. I came up with the following idea: I can run nim --define:testing main.nim
and use the following template as a wrapper for all my unit tests.
# located in some general utils module:
template runUnitTests*(code: stmt): stmt =
when defined(testing):
echo "Running units test in ..."
code
This seems to be working well so far.
As a minor tweak, I was wondering if I can actually print out the file name which is calling the runUnitTests
template. Is there any reflection mechanism to get the source file name at compile time?
Nim connects to the C compilation process in order to compile the C source code that was generated by it. This means that the Nim compiler depends on an external C compiler, such as GCC or Clang. The result of the compilation is an executable that's specific to the CPU architecture and OS it was compiled on.
On Linux we can run our program by typing ./helloworld in the terminal, and on Windows we do it by typing helloworld.exe . c is telling Nim to compile the file, and -r is telling it to run it immediately. To see all compiler options, type nim --help in your terminal.
The default nimcache directory has changed from the current working directory to: $HOME/. cache/nim/<project_name> for Linux and MacOS. $HOME/nimcache/<project_name> for Windows.
instantiationInfo seems to be what you want: http://nim-lang.org/docs/system.html#instantiationInfo,
template filename: string = instantiationInfo().filename
echo filename()
The template currentSourcePath from the system module returns the path of the current source by using a special compiler built-in, called instantiationInfo
.
In your case, you need to print the locations of callers of your template, which means you'll have to use instantiationInfo directly with its default stack index argument of -1 (meaning one position up in the stack, or the caller):
# located in some general utils module:
template runUnitTests*(code: stmt): stmt =
when defined(testing):
echo "Running units test in ", instantiationInfo(-1).filename
code
It's worth mentioning that the Nim compiler itself uses a similar technique with this module, which get automatically imported in all other modules by applying a switch in nim.cfg:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With