在TCL中访问变量的值

时间:2012-09-05 08:19:10

标签: unit-testing tcl

我有类似的代码用于编写单元测试,我需要检查变量的值。

#first.tcl
proc test {a} {
   if {$a < 10} {
      set sig 0
   } else {
      set sig 1
   }
} 
#second.tcl unit testing script
source "first.tcl"
test 10
expect 1 equal to $sig
test 5
expect 0 equal to $sig

有没有办法,我可以访问变量“sig”的值,因为我无法更改第一个脚本。

1 个答案:

答案 0 :(得分:3)

你有问题。问题是在第一个脚本中,sig是一个本地变量,当对test的调用终止时,该变量就会消失。之后你无法检查它。碰巧的是,test的结果是分配给sig的值;我不知道您是否可以依靠它进行测试。如果这就足够了,你可以这样做(假设你有Tcl 8.5;对于8.4你需要一个辅助程序而不是apply术语):

source first.tcl
trace add execution test leave {apply {{cmd code result op} {
    # Copy the result of [test] to the global sig variable
    global sig
    set sig $result
}}}

这截取(就像面向方面编程一样)test的结果并将其保存到全局 sig变量。但它没有做的事情对于测试代码中的问题是正确的:赋值是一个在之后立即消失的变量。


如果您正在进行大量测试,请考虑使用tcltest来完成工作。这是用于测试Tcl本身的包,它允许您非常轻松地编写执行脚本结果的测试:

# Setup of test harness
package require tcltest
source first.tcl

# The tests
tcltest::test test-1.1 {check if larger} -body {
    test 10
} -result 1
tcltest::test test-1.2 {check if smaller} -body {
    test 5
} -result 0

# Produce the final report
tcltest::cleanupTests