msedzins / bashUT

Unit tests in bash - example

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Purpose

Example of lightweight approach to writing unit tests for bash scripts.

Consists of:

  1. functions.sh - set of bash fuctions
  2. functions_test.sh - set of unit tests

Key points

  1. Stubbing calls to external functions
function terraform { 
    cat terraform_response_vm_list.txt
    }  

Note: Sometimes might be also useful to export function definitions to sub-shell with:

export -f function_name
  1. Stopping tests with proper message when any of the assertions is not met
set -e

function validate_status {
    if [[ $? != 0 ]]; then
        echo "Tests failed"
    else
        echo "Tests succeeded."
    fi

}
trap validate_status EXIT 
  1. Finding out whether the script was sourced or called directly
#if true means that script was not run with "source" command
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]
then
  echo "Some action"  
fi

About

Unit tests in bash - example


Languages

Language:Shell 100.0%