Expect Script – How to Detect Timeouts

automated-testingautomationexpect

Consider an expect script that spawns a command and waits for a sequence of events. We use this to test software. I'm trying to always get a failure return value from the script when there is a timeout.

spawn some-command

set timeout 10

expect "First message"
expect "Other message"

This script will always return 0 (success) even when the timeout hits. The only way to handle timeouts is to convert every expect statement with:

expect {
    timeout { exit 1 }
    eof     { exit 1 }
    "First message"
}

But this quickly becomes unwieldy. Are there any simplifications? Is there an expect option that makes early timeout / eof fatal errors?

Best Answer

Commenting on meuh's answer, expect_before takes the same arguments as expect, so you can write it like this:

expect_before {
    timeout { puts "timeout"; exit 2 }
    eof     { puts "eof";     exit 1 }
}
# ...
expect "First message"