#include in Expect脚本

时间:2014-05-19 10:37:11

标签: linux unix scripting automation expect

所以我在制作带有期望脚本的TestCase时遇到了麻烦,我喜欢10个TestCase,它们都以相同的"函数开始和结束。比如登录和注销或关闭某些标志,是否有可能包含它们或从我的脚本远程执行它们,如spawn login.exp或更好地将它们放入函数中?

TC01.exp

#!/usr/bin/expect -f
set timeout 5

#example of getting arguments passed from command line..
#not necessarily the best practice for passwords though...
set server [lindex $argv 0]
set user [lindex $argv 1]
set pass [lindex $argv 2]
set no [lindex $argv 3]
set counter 0

# connect to server via ssh, login, and su to root
send_user "connecting to $server\n"
spawn ssh $user@$server

#login handles cases:
#   login with keys (no user/pass)
#   user/pass
#   login with keys (first time verification)
expect {
  "> " { }
  "$ " { }

  "assword: " { 
        send "$pass\n" 
        expect {
          "> " { }
          "$ " { }
          "assword: " { 
                    send_user "\nLogin failed\n" 
                                    incr counter 1
                    exit 5

                }
        }
  }
  "(yes/no)? " { 
        send "yes\n"
        expect {
          "> " { }
          "$ " { }
        }
  }
 default {
        send_user "Login failed\n"
        incr counter 1
        exit
  }
}


#TEST CASE HERE


#login out
send "exit\n"

expect {
    "> " {}
    default {}
}


if { $counter > 0 } {
    send_user "\nTestCase finished with some errors!\nFAILED!!!\nERRORS $counter\n";
    exit 4;
}

send_user "\nTestCase finished with SUCCESS!\nERRORS: $counter\n";

所以我想将login和count_error作为函数,所以我可以像这样创建我的测试用例:

TC01.exp

#!/usr/bin/expect -f
set timeout 5
set server [lindex $argv 0]
set user [lindex $argv 1]
set pass [lindex $argv 2]
set no [lindex $argv 3]
set counter 0


login($server, $user, $pass)

#TestCase

Errors($counter)
exit

1 个答案:

答案 0 :(得分:1)

Expect实际上是Tcl,其中包含一些绑定到pty和fork()的内容。所有内容都在http://tcl.tk上有详细描述 Tcl中的函数使用proc(look here)完成,例如:

lib.tcl

proc login {server user pass} {
  # Your expect code goes here
  return $errorCount
}
proc errors {errorCount} { 
  if {$errorCount > 0} {
    # Your error handling code here
  }
}

试验:

#!/usr/bin/env expect
source lib.tcl
set errors [login $server $user $pass]
# your test case here
errors $errors