【问题标题】:Unit Testing in Nim: Is it possible to get the name of a source file at compile time?Nim 中的单元测试:是否可以在编译时获取源文件的名称?
【发布时间】:2015-04-01 18:41:53
【问题描述】:

我正在计划一个包含多个模块的项目,并且我正在寻找一个很好的解决方案来一次运行项目中的所有现有单元测试。我想出了以下想法:我可以运行 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 模板的文件名。有没有什么反射机制可以在编译时获取源文件名?

【问题讨论】:

    标签: unit-testing templates nim-lang


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,就是这样!一个小提示:我必须直接在runUnitTests 模板中调用instantiationInfo().filename。如果我在 utils.nim 模块中创建此 filename 模板并从 runUnitTests 模板中调用此第二个模板,则输出始终为 utils.nim(看起来嵌套模板会影响堆栈行信息)。
    【解决方案2】:

    来自系统模块的模板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 编译器本身使用与this module 类似的技术,通过应用switch in nim.cfg 自动导入所有其他模块:

    【讨论】:

      猜你喜欢
      • 2010-09-19
      • 1970-01-01
      • 2014-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      • 2012-03-28
      相关资源
      最近更新 更多