blu*_*e10 4 templates unit-testing nim-lang
我正在计划一个包含多个模块的项目,我正在寻找一个很好的解决方案来同时运行项目中的所有现有单元测试.我提出了以下想法:我可以运行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
Run Code Online (Sandbox Code Playgroud)
到目前为止,这似乎运作良好.
作为一个小调整,我想知道我是否可以打印出调用runUnitTests模板的文件名.是否有任何反射机制在编译时获取源文件名?
InstantiationInfo 似乎是你想要的:http://nim-lang.org/docs/system.html#instantiationInfo,
template filename: string = instantiationInfo().filename
echo filename()
Run Code Online (Sandbox Code Playgroud)
系统模块中的模板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
Run Code Online (Sandbox Code Playgroud)
值得一提的是,Nim编译器本身使用与此模块类似的技术, 通过在nim.cfg中应用开关,可以自动导入所有其他模块:
| 归档时间: |
|
| 查看次数: |
620 次 |
| 最近记录: |