sh_test
is my most commonly used test rule by far. It is the easiest way to
write quick-and-dirty tests and works nearly everywhere. For anything beyond
the most trivial tests, I use Bazel’s Bash unit test framework. This explains
what the framework is and how to use it.
Within Bazel’s source code there exist a Bash unit test framework called
unittest.bash
. This framework allows you to write a test script as
a collection of test cases, each implemented as a Bash function. The
Bash unit test framework integrates nicely with Bazel, as it:
- Provides a series of assertions such as
assert_equals
andexpect_log
- Supports filtering test cases using
--test_filter
- Supports suite
set_up
andtear_down
functions - Ensures that each test is run in a new subshell and in its own directory
- Implements the Bazel test sharding protocol
Unlike bazel_tool’s runfiles.bash
, I have not figured out how to
refer to the Bash unittest framework directly, so I use the Bash unit
test framework as follows:
- Download
unittest.bash
andunittest_utils.sh
into their own directory, typically//tools/bash/unittest
- Wrap these two scripts into a
sh_library()
calledunittest
:
|
|
- Add the
unittest
library as a dependency to my test script:
|
|
- Use the Bash unit test framework within the test script:
|
|
To learn more about how to use Bash unit test framework, see the comments in
unittest.bash
.