End-to-End command line tool testing with BATS and (auto)expect

BATS and (auto)expect to the rescue

It provides a simple way to verify that the UNIX programs you write behave as expected. Bats test file is a Bash script with special syntax for defining test cases. Under the hood, each test case is just a function with a description.

go mod init github.com/mygithubusername/justarandomprojectname
#!/usr/bin/env bats
▶ ./bats_testing.sh✓ 1 - Evaluating our cli1 test, 0 failures
▶ go run main.goEnter text: TestingTesting
go build -o mycli .
expect "Enter text: " { send "Testing\r" }
▶ ./myexpect.expspawn ./mycliEnter text: TestingTesting
go build -o mycli .
▶ autoexpect ./mycliautoexpect started, file is script.expEnter first name: PantelisEnter last name: KaramolegkosEnter job title: SREFirst Name: Pantelis, Last Name: Karamolegkos, Job Title: SREautoexpect done, file is script.exp
▶ ./script.expspawn ./mycliEnter first name: PantelisEnter last name: KaramolegkosEnter job title: SREFirst Name: Pantelis, Last Name: Karamolegkos, Job Title: SRE

Putting all the pieces together

▶ go build -o mycli .
▶ go run main.go -interactiveEnter first name: PantelisEnter last name: KaramolegkosEnter job title: SRE
▶ go run main.go -firstname Pantelis -lastname Karamolegkos -jobtitle SREFirst Name: Pantelis, Last Name: Karamolegkos, Job Title: SRE
▶ autoexpect ./mycli -interactiveautoexpect started, file is script.expEnter first name: PantelisEnter last name: KaramolegkosEnter job title: SREautoexpect done, file is script.exp
▶ ./bats_testing.sh✓ 1 - Testing non interactive mode of execution1 test, 0 failures
▶ ./bats_testing.sh✓ 1 - Testing interactive mode of execution✓ 2 - Testing creation of output file✓ 3 - Testing contents of the output file
▶ ./bats_testing.sh✓ 1 - Testing non interactive mode of execution✓ 2 - Testing interactive mode of execution✓ 3 - Testing creation of output file✓ 4 - Testing contents output file

Aftermath

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store