tags:

views:

49

answers:

2

Hello, I am a total expect noob.

I am writing a expect script for a test case where I want to count the number of occurrences of the string "Ok" and do an action for every occurrence from the following output:

Reloading configuration on all nodes
Reloading configuration on node 1 (node1-c5)
OK
Reloading configuration on node 2 (node2-c5)
OK
Reloading configuration on node 3 (node3-c5)
OK
Reloading configuration on node 4 (node4-c5)
OK

How would my expect block look like?

+1  A: 

The code ended up looking like this (a simple loop):

send "cluster config -r -a \r"
set done 0
set number_ok 0
while {$done == 0} {
   set done 1
   expect {
      $ROOT_PROMPT { set done 1 }
      "ERROR" { cluster_exit 1 }
      -re "Reloading configuration on node.*\r" {
         set line "<$cmdline> $expect_out(0,string)"
         expect {
            $ROOT_PROMPT { set done 1 }
            "ERROR" { cluster_exit 1 }
            -re "Node * not found" { ok 0 "$line (not found)" }
            -re "Node * not responding, skipped" { ok 0 "$line (not responding)" }
            "OK" {
               ok 1 "$line"
               set number_ok [expr $number_ok + 1] 
               set done 0
            }
         }
      }
   }
}
diag "Done $done"
diag "Count $number_ok"
Codeape
+2  A: 

I'd rewrite your code to remove the while loop:

set number_ok 0
set node_patt "(Reloading configuration on node (\\d+?) \\((\[^)]+?)\\))\r\n(.+?)\r\n"

send "cluster config -r -a\r"
expect {
    ERROR {cluster_exit 1}
    -re $node_patt {
        set line "<$cmdline> $expect_out(1,string)"
        set node_num  $expect_out(2,string)
        set node_name $expect_out(3,string)
        set result    $expect_out(4,string)

        switch -regexp $result {
            "Node .+ not found" {
                ok 0 "$line (not found)"
            }
            "Node .+ not responding, skipped" {
                ok 0 "$line (not responding)"
            }
            OK {
                ok 1 $line
                incr number_ok
            }
        }
        exp_continue   ;# loop back to top of expect block
    }
    $ROOT_PROMPT  ;# no action, so fall out of the expect block
}

Note that Tcl regular expressions are either entirely greedy or entirely non-greedy. I use \r\n(.+)\r\n to capture the line following "Reloading configuration on node ...". However the .+ part must not contain newlines, so it has to be non-greedy. Thus, every quantifier in node_patt has to be non-greedy.

glenn jackman
Worked like a clock! Thnx!
Codeape
Note that Tcl's REs are *not* entirely greedy or non-greedy, but the rules for what is happening when are automata-theoretic and so very difficult to understand except in a few cases (e.g., lookahead constraints, which are always non-greedy). It's always easier to write using just one type of RE if you possibly can.
Donal Fellows