I did this for working through the grep
challenge and it meant I could refactor the app and add new features faster and with high confidence.
Admittedly the program just reads from stdin, and only exits 0 or 1, so it’s easy to write as many tests as you want for all the regex patterns your heart desires. (I didn’t bother writing automated tests when going through http-server
.) So while this may not be worth it for all challenges, a quick and dirty test script might be useful for those wanting to re-test things more frequently, prevent regressions from a refactor, or make sure all cases are covered before hitting git push
.
Here’s what I started with for the grep
challenge:
#!/usr/bin/env bash
echo "Compiling program"
go build -o _temp/main cmd/mygrep/main.go
echo "Running tests..."
# This `expr AND expr OR expr` form takes
# advantage of short-circuiting to conditionally
# print the result of the test.
echo "aaabbbccc" | _temp/main -E "bc" && {
echo "Passed"
} || {
echo "Failed"
}
# Note that the messages must be flipped
# when we expect to find no match
echo "aaabbbccc" | _temp/main -E "bcccc" && {
echo "Failed"
} || {
echo "Passed"
}
echo "Cleaning up"
rm -rf _temp
echo "Finished"
And as exercises for the reader
- Print the inputs to see which tests are passing and failing.
- Print debugging help on failing cases. (I printed the command to run the program with the failing inputs along with my
--debug
flag.) - Convert the test-running code into functions.
- Count up passes, fails, and total number of test cases.
- Add colors to more easily see pass vs. fail in the terminal output.