made_in_india
made_in_india

Reputation: 2277

Access value of the variable in TCL

I have similar code for writing unit test where I need to check the value of a variable.

#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

Is there any way, that I can access the value of the variable "sig" as I can not change the first script.

Upvotes: 1

Views: 444

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137787

You have a problem. The problem is that in the first script, sig is a local variable that vanishes when the call to test terminates. You can't examine it afterwards. As it happens, the result of test is the value assigned to sig; I don't know whether you can count on that for testing purposes. If that's sufficient, you can do this (assuming you have Tcl 8.5; for 8.4 you need a helper procedure instead of the apply term):

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
}}}

This intercepts (just like with aspect-oriented programming) the result of test and saves it to the global sig variable. What it doesn't do though is correct for the problem in the tested code: the assignment is to a variable that goes away immediately after.


If you're doing lots of testing, consider using the tcltest to do the work. That's the package that is used to test Tcl itself, and it lets you write a test of the result of executing a script very easily:

# 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

Upvotes: 3

Related Questions