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.
You have a problem. The problem is that in the first script,
sigis a local variable that vanishes when the call totestterminates. You can’t examine it afterwards. As it happens, the result oftestis the value assigned tosig; 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 theapplyterm):This intercepts (just like with aspect-oriented programming) the result of
testand saves it to the globalsigvariable. 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: