Open
Description
To write tests for a Bash script and measure code coverage, you can use the following tools:
1. Testing Bash Scripts
- [Bats (Bash Automated Testing System)](https://github.com/bats-core/bats-core): A popular testing framework for Bash, using a TAP-compliant format.
- shUnit2: A lightweight unit-testing framework for shell scripts.
- assert.sh: A minimal Bash unit-testing framework with assertions.
- ShellSpec: A behavior-driven development (BDD) framework for shell scripts.
2. Code Coverage for Bash Scripts
- [kcov](https://github.com/SimonKagstrom/kcov): A tool that collects code coverage information for programs, including Bash scripts.
- bashcov: A wrapper around
kcov
, making it easier to use with Bash. - gcov (with shell coverage patches): Can be used, though
kcov
is more suitable for Bash.
How to Set Up Tests and Coverage
Using Bats and kcov
-
Install Bats:
git clone https://github.com/bats-core/bats-core.git cd bats-core ./install.sh /usr/local
-
Write a test file (
test_script.bats
):#!/usr/bin/env bats @test "Check script output" { result=$(./my_script.sh) [ "$result" = "Expected output" ] }
-
Run the test:
bats test_script.bats
-
Install kcov and generate coverage:
sudo apt-get install kcov # or use brew install kcov on macOS mkdir coverage kcov coverage/ ./my_script.sh
Below is a GitHub Actions workflow that:
- Runs tests using Bats
- Collects code coverage using kcov
- Uploads the coverage report as an artifact
📌 .github/workflows/test.yml
name: Bash Script Tests & Coverage
on:
push:
branches:
- main
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Install Dependencies (Bats & kcov)
run: |
sudo apt-get update
sudo apt-get install -y bats kcov
- name: Run Bats Tests
run: |
bats tests/
- name: Run Code Coverage with kcov
run: |
mkdir -p coverage
kcov --include-path=$(pwd) coverage ./my_script.sh
- name: Upload Coverage Report
uses: actions/upload-artifact@v4
with:
name: coverage-report
path: coverage/
📌 Explanation
✅ Triggers: Runs on push
to main
or any pull request
.
✅ Dependencies: Installs bats
(for testing) and kcov
(for coverage).
✅ Runs tests: Executes tests from the tests/
directory.
✅ Generates coverage: Runs kcov
and stores the report in coverage/
.
✅ Uploads coverage: Saves the coverage/
folder as a GitHub Actions artifact.
Activity