为期待的每场比赛做一个动作

时间:2010-09-21 10:58:36

标签: tcl expect

我总是期待noob。

我正在编写测试用例的expect脚本,我想计算字符串“Ok”的出现次数,并对以下输出中的每次出现执行操作:

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

我的期待块怎么样?

2 个答案:

答案 0 :(得分:3)

我会重写您的代码以删除while循环:

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
}

请注意,Tcl正则表达式要么完全贪婪,要么完全不贪婪。我使用\r\n(.+)\r\n来捕获“在节点上重新加载配置...”之后的行。但是.+部分不得包含换行符,因此必须非贪婪。因此,node_patt中的每个量词都必须是非贪婪的。

答案 1 :(得分:1)

代码最终看起来像这样(一个简单的循环):

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"