Search code examples
tclexpect

How to apply default to all expect commands?


Coding CLI unit tests using expect and would like to abstract following default block as it applies to all expect blocks.

default {
  test_failed
}

Example:

#!/usr/bin/expect

source ./test.exp

set passphrase "asdasd"
set secret "foo\nbar"

test_label "Should backup secret using Shamir Secret Sharing"

spawn qr-backup.sh --shamir-secret-sharing

expect {
  default {
    test_failed
  }
  -re {Format USB flash drive \(y or n\)\?} {
    sleep 0.1
    send "n\r"
  }
}

expect {
  default {
    test_failed
  }
  -re {\[sudo\] password for pi:} {
    sleep 0.1
    send "$env(password)\r"
  }
}

Solution

  • This is exactly what the expect_before and expect_after commands do. In this case it doesn't matter which one you use:

    #!/usr/bin/expect
    
    spawn qr-backup.sh --shamir-secret-sharing
    
    expect_after {
        default {
            test_failed
        }
    }
    
    expect {
        -ex {Format USB flash drive (y or n)? } {
            send "n\r"
        }
    }
    
    expect {
        -ex {[sudo] password for pi: } {
            send "$env(password)\r"
        }
    }