2010-09-21 30 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"