How to get name of TCL test from the test itself

白昼怎懂夜的黑 提交于 2019-12-13 15:18:31

问题


I was wondering how you would find the name of the test you're running in tcl from the test itself? I couldn't find this on google.

I'm calling another proc and passing the name of the test that is calling it, as an argument. So I would like to know which tcl command can do that for me.


回答1:


This isn't an encouraged use case… but you can use info frame 1 to get the information if you use it directly inside the test.

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

This assumes that you're using Tcl 8.5 or later, but Tcl 8.5 is the oldest currently-supported Tcl version so that's a reasonable restriction.




回答2:


I read your comments ("source ... instade of my test name") as follows: You seem to source the Tcl script file containing the tests (and Donal's instrumented tcltest), rather than batch-running the script from the command line: tclsh /path/to/your/file.tcl In this setting, there will be an extra ("eval") stack frame which distorts introspection.

To turn Donal's instrumentation more robust, I suggest actually walking the Tcl stack and watching out for a valid tcltest frame. This could look as follows:

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

This will return "Called from foo-1.1" both, when called as:

$ tclsh test.tcl 
Called from foo-1.1

and

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

The Tcl version used (8.5, 8.6) is not relevant. However, your are advised to upgrade to 8.6, 8.5 has reached its end of life.



来源:https://stackoverflow.com/questions/52995647/how-to-get-name-of-tcl-test-from-the-test-itself

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!