dza
dza

Reputation: 1504

Unit-testing expect script

I have an expect script that I would like to do unit-tests for, but I'm unsure how to go about it.

My initial thought was to override keychain, lpass and bw somehow, but I have no idea how to do this without modifying the original script, in my other tests I have overridden functions with shell function stubs and set PATH='' in some cases. I guess I could test all the 3 executed commands manually, but that doesn't really test the project as a whole and leaves some code untested which is vital to the functionality.

#!/usr/bin/expect --
set manager [lindex $argv 0]
# strip manager part
set argv [lrange $argv 1 end]
spawn -noecho keychain --quick --quiet --agents ssh {*}$argv
foreach key $argv {
  if {$manager == "lastpass"} {
    set pass [exec lpass show --name $key --field=Passphrase | tr -d '\n']
  }
  if {$manager == "bitwarden"} {
    set pass [exec bw get password $key | tr -d '\n']
  }
  expect ":"
  send "$pass\r"
}
interact

Any suggestions would be be highly appreciated!

Upvotes: 0

Views: 493

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137567

For unit testing, you can just put a directory at the start of the PATH with mock scripts for the keychain, lpass and bw commands. After all, in a unit test you're just really checking that the code in the script itself is plausible and doesn't contain stupid errors. Yes, there are other ways of doing that, but mocking the commands via a PATH tweak is definitely the easiest and most effective way.

However, this is definitely a case where the useful testing is integration testing where you run against the real commands. Of course, you might do that in some sort of testing environment; a VM (especially something comparatively lightweight like Docker) might help here.

You do not need to test whether exec and spawn obey the PATH. That's someone else's job and definitely is tested!

Upvotes: 1

Related Questions