Expect Automation


expect automation

I needed a way to automate test of an application and decided to use expect.

The follow expect script show various expect examples.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/usr/bin/expect -f 

puts "DISPLAY: $env(DISPLAY)"

proc function_name { VARIABLE1 VARIABLE2 } {
  puts "$VARIABLE1"
  puts "$VARIABLE2"
  
  set result [ expr { $VARIABLE1 + $VARIABLE2 } ]
  
  if { $result > 5.0 } {
    puts "$result"
  } else {
    puts "Nice"
  }
}

function_name 3.3 2.7
sleep 0.2
function_name 3.3 1.2

proc multiply { ARRAY } {
  upvar $ARRAY input
  array set output {}

  for { set i 0 } { $i < [ array size input ] } { incr i 1 } {
    set output($i) [ expr { $input($i) * 2.0 } ]
  }
  return [ array get output ]
}

array set numbers {}
set numbers(0) 3
set numbers(1) 7

array set numbers_updated [ multiply numbers ] 
parray numbers_updated

set timeout 10
spawn date
expect {
  -re "\[0-9]+:\[0-9]+"   { set time $expect_out(0,string) }
  timeout                 { puts "timed out"; exit }
  eof                     { puts "eof"; exit }
}

puts "Clock is: $time"

Output from script:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
DISPLAY: :0
3.3
2.7
6.0
3.3
1.2
Nice
numbers_updated(0) = 6.0
numbers_updated(1) = 14.0
spawn date
Fri 09 Apr 2021 08:22:06 PM CEST
Clock is: 08:22