The expect intance is kept in a class variable so that the tear down code can close it. This is important as Expect consumes pseudo-terminal and other resources that must be cleaned up.
Expect e; public void tearDown () { e.close (); }The test case proper then starts its program. Here the program is tee which just copies all of STDIN to STDOUT.
public void test () { // Create an instance of expect running "tee" e = new Expect ("tee");The tee program is then sent some input (the strings "catchthebi" and "rd"), and then the string was printed is checked. Several different matches are used, illustrating how partial matches can occur.
e.send ("catchthebi"); // Skip "catch", match "the", leaving "bi". e.expect ("the"); // Append "rd", making "bird". e.send ("rd"); // Match the "bird". e.expect ("bird");
// Create the shell, as sh e = new Expect (new String[] { "/bin/sh" }); // Match the initial prompt. This ensures that things are // blocked until the shell is fully running. As a side effect // it also discards all output so far. e.expect ("\\$ "); // Send a command to simplify the prompt, and then match it. // Notice how the matching pattern includes the // carrage-return, the new-line, and the promt. That ensures // that it doesn't accidently match the command. e.send ("PS1='\\$ '\r"); e.expect ("\r\n\\$ "); // Check out the terminal, again be careful to match the // prompt. e.send ("stty -a\r"); final StringBuffer g = new StringBuffer (); e.expect (new Match[] { new Regex ("\\s(-brkint)\\s.*\\$ ") { public void execute () { g.append (group (1)); } }, new Regex ("\\s(brkint)\\s.*\\$ ") { public void execute () { g.append (group (1)); } } }); assertEquals ("brk mode", "-brkint", g.toString ());