Skip to content

Add tests #6

Open
Open
@rvalitov

Description

To write tests for a Bash script and measure code coverage, you can use the following tools:

1. Testing Bash 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

  1. Install Bats:

    git clone https://github.com/bats-core/bats-core.git
    cd bats-core
    ./install.sh /usr/local
  2. Write a test file (test_script.bats):

    #!/usr/bin/env bats
    
    @test "Check script output" {
        result=$(./my_script.sh)
        [ "$result" = "Expected output" ]
    }
  3. Run the test:

    bats test_script.bats
  4. 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:

  1. Runs tests using Bats
  2. Collects code coverage using kcov
  3. 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions