unit-testingtemplatesnim-lang

Unit Testing in Nim: Is it possible to get the name of a source file at compile time?


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?


Solution

  • instantiationInfo seems to be what you want: http://nim-lang.org/docs/system.html#instantiationInfo,

    template filename: string = instantiationInfo().filename
    
    echo filename()