Skip to content

Autoexpect command on Linux (software testing)

The autoexpect command on Linux and expect can be extremely useful for testing software.

Imagine that you built a program in Shellscript, C, Python, Perl, or any other language that runs in the shell and interacts with the user, asking for parameters, and based on the parameters providing answers.

Well, testing this type of program can be tiring, since you will have to enter some parameters several times until your program is working as expected.

The expect command and autoexpect can be useful for doing this job.

To illustrate, look at the short script that asks for the user’s name, then the month of the year:

$ cat script <br></br>#! /bin/bash <br></br>echo “What's Your Name?” <br></br>read NAME <br></br>echo “What month of the year do you want to see the calendar?”

Read MES
echo “$NAME, here’s the calendar:”
cal $MES 2020 To execute the script, it is necessary to make it executable:

$ chmod +x script

When running it:

$. /script <br></br>What is your name? <br></br>Uira <br></br>Which month of the year do you want to see the calendar? <br></br>01 <br></br><br></br><br></br>Unira, here is the calendar: January 2020 if you have to go <br></br>1 2 3 4 <br></br>5 6 7 8 9 10 11 <br></br>12 13 14 15 16 17 18 <br></br>19 20 21 22 23 24 25

26 27 28 29 30 31 Imagine that you’re refining your code, and you have to test the program over and over again. Exhausting to do this manually.

To create a “self-test” of the execution of this script, without having to type the name and month at each execution, the autoexpect command can be used:

$ autoexpect. /script <br></br>autoexpect started, file is script.exp <br></br>What is your name? <br></br>Uira <br></br>Which month of the year do you want to see the calendar? <br></br>02 <br></br><br></br><br></br>Unira, here is the calendar: February 2020 if you have to go <br></br>1 <br></br>2 3 4 5 6 7 8 <br></br>9 10 11 12 13 14 15 ;

16 17 18 19 20 21 22
23 24 25 26 27 28 29

autoexpect done, file is script.exp The autoexpect program creates a file with the name of the script, followed by the extension .exp.

This generated file is a shellscript that uses the expect commands to read the output of your program, and send the counter responses.

Now, to test the small program, simply run the script.exp script:

$. /script.exp <br></br>spawn. /script <br></br>What is your name? <br></br>Uira <br></br>Which month of the year do you want to see the calendar? <br></br>02 <br></br><br></br><br></br>Unira, here is the calendar: February 2020 if you have to go <br></br>1 <br></br>2 3 4 5 6 7 8 <br></br>9 10 11 12 13 14 15 ;

16 17 18 19 20 21 22
23 24 25 26 27 28 29 This way, you won’t have to type anything anymore. Just improve and test your software.

Learn much more about Linux in our online course. You can register here. If you already have an account, or want to create one, just log in or create your user here.

Did you like it?

Share