2010-09-21 58 views
0

我总是期待noob。对预期的每场比赛都采取行动

我写一想到剧本,我想算字符串“好”的出现次数,并从以下输出每次出现做一个动作一个测试用例:

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 

会如何我的期望块看起来像?

回答

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中的每个量词都必须是非贪婪的。

+0

工作就像一个时钟!日Thnx! – Codeape 2010-09-22 06:52:23

+2

请注意,Tcl的REs *不是*完全贪婪或不贪婪的,但是对于发生什么的规则是自动机理论的,除非在一些情况下非常难以理解(例如,先行约束,贪婪)。如果可能的话,只用一种类型的RE进行编写总是比较容易。 – 2010-09-22 12:58:50

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"