如何从测试本身获取 TCL 测试的名称

How to get name of TCL test from the test itself

我想知道您如何从测试本身找到您在 tcl 中 运行 的测试的名称?我在 google.

上找不到这个

我正在调用另一个过程并将调用它的测试的名称作为参数传递。所以我想知道哪个 tcl 命令可以为我做到这一点。

这不是一个鼓励的用例……但是如果您直接在测试中使用它,您可以使用 info frame 1 来获取信息。

proc example {contextTest} {
    puts "Called from $contextTest"
    return ok
}

tcltest::test foo-1.1 {testing the foo} {
    example [lindex [dict get [info frame 1] cmd] 1]
} ok

这假定您使用的是 Tcl 8.5 或更高版本,但 Tcl 8.5 是当前支持的最旧的 Tcl 版本,因此这是一个合理的限制。

我阅读了您的评论 ("source ... instade of my test name"),如下所示:您似乎 source 包含测试的 Tcl 脚本文件(以及 Donal 的检测 tcltest),而不是批处理 运行来自命令行的脚本:tclsh /path/to/your/file.tcl 在此设置中,将有一个额外的 ("eval") 堆栈框架,它会扭曲内省。

为了使 Donal 的工具更加健壮,我建议实际遍历 Tcl 堆栈并留意有效的 tcltest 框架。这可能如下所示:

package req tcltest

proc example {} {
    for {set i 1} {$i<=[info frame]} {incr i} {
        set frameInfo [info frame $i]
        set frameType [dict get $frameInfo type]
        set cmd [dict get $frameInfo cmd]

        if {$frameType eq "source" && [lindex $cmd 0] eq "tcltest::test"} {
           puts "Called from [lindex $cmd 1]"
           return ok
        }
    }

    return notok
}

tcltest::test foo-1.1 {testing the foo} {
    example
} ok

这将 return "Called from foo-1.1" 两者,当调用时:

$ tclsh test.tcl 
Called from foo-1.1

$ tclsh
% source test.tcl
Called from foo-1.1
% exit

使用的 Tcl 版本(8.5、8.6)不相关。但是,建议您升级到 8.6,8.5 已经到了生命周期的尽头。