5

我正在计划一个包含多个模块的项目,并且我正在寻找一个很好的解决方案来一次运行项目中的所有现有单元测试。我想出了以下想法:我可以运行nim --define:testing main.nim并使用以下模板作为我所有单元测试的包装器。

# located in some general utils module:
template runUnitTests*(code: stmt): stmt =
  when defined(testing):
    echo "Running units test in ..."
    code

到目前为止,这似乎运作良好。

作为一个小调整,我想知道我是否真的可以打印出调用runUnitTests模板的文件名。是否有任何反射机制可以在编译时获取源文件名?

4

2 回答 2

5

instantiationInfo 似乎是你想要的:http: //nim-lang.org/docs/system.html#instantiationInfo

template filename: string = instantiationInfo().filename

echo filename()
于 2015-04-01T19:26:03.077 回答
5

来自系统模块的模板currentSourcePath通过使用一个特殊的内置编译器返回当前源的路径,称为instantiationInfo.

在您的情况下,您需要打印模板调用者的位置,这意味着您必须直接使用instantiationInfo,其默认堆栈索引参数为 -1 (意味着堆栈中的一个位置,或调用者):

# located in some general utils module:
template runUnitTests*(code: stmt): stmt =
  when defined(testing):
    echo "Running units test in ", instantiationInfo(-1).filename
    code

值得一提的是,Nim 编译器本身对 这个模块使用了类似的技术,通过在 nim.cfg 中应用一个开关,它会自动导入所有其他模块:

于 2015-04-06T13:15:20.147 回答