TL;DR
Here is a template repository* that has continuous integration unit tests of shell files using Travis-CI: https://github.com/a-t-0/shell_unit_testing_template
Since the repo might some day disappear, here is the idea for reproducability. (Note that this is not necessarily the best way to do this, it is just a way I found to be working).
File Structure
The shell scripts are inside a /src/
folder. The unit tests are inside the /test/
folder. In /src/
there is a main.sh
which can call other shell scripts. The other shell scripts can consist of separately testable functions, for example the file active_function_string_manipulation.sh
. (included below)
To make it work, I needed to install support for bats
files which are the unit test files. This was done with the file install-bats-libs.sh
with content:
mkdir -p test/libs
git submodule add https://github.com/sstephenson/bats test/libs/bats
git submodule add https://github.com/ztombol/bats-support test/libs/bats-support
git submodule add https://github.com/ztombol/bats-assert test/libs/bats-assert
Shell Script
An example of a shell script in /src/ is:
active_function_string_manipulation.sh`.
##################################################################
# Purpose: Converts a string to lower case
# Arguments:
# $@ -> String to convert to lower case
##################################################################
function to_lower()
{
local str="$@"
local output
output=$(tr '[A-Z]' '[a-z]'<<<"${str}")
echo $output
}
to_lower "$@"
Unit Test
Unit tests are ran by a file called test.sh
in the root directory of the repository. It has content:
# Run this file to run all the tests, once
./test/libs/bats/bin/bats test/*.bats
An example would be the testing of: active_function_string_manipulation.sh
with: /test/test_active_function_string_manipulation.bats
:
#!./test/libs/bats/bin/bats
load 'libs/bats-support/load'
load 'libs/bats-assert/load'
@test "running the file in /src/active_function_string_manipulation.sh." {
input="This Is a TEST"
run ./src/active_function_string_manipulation.sh "This Is a TEST"
assert_output "this is a test"
}
Travis CI
The Travis CI is implemented using a yml
file which basically creates an environment and runs the tests in an automated environment. The file is named: .travis.yml
and contains:
language: bash
script:
- ./test.sh
Disclosure*
I am involved in building this repository, and it is the "for dummies/me"-implementation of the instructions in this article.
Note
I currently do not have much insight in how well this system scales, and I am currently not able to estimate whether this has the potential to be a "production ready" system, or whether it is suitable for such big projects, it is merely an automated unit testing environment for shell code.