Programming/Bash/Unit Testing

From Dev Wiki
< Programming‎ | Bash
Revision as of 20:58, 25 October 2020 by Brodriguez (talk | contribs) (Import contents from bash page)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

The UnitTesting I've found in Bash is to use Bats. Full description found at https://opensource.com/article/19/2/testing-bash-bats.

Effectively, first add Git Submodules:

git submodule add https://github.com/sstephenson/bats tests/libs/bats
git submodule add https://github.com/ztombol/bats-assert tests/libs/bats-assert
git submodule add https://github.com/ztombol/bats-support tests/libs/bats-support
git commit


Functions

Can initialize functions that run at the start and end of every test with:

###
 # This will run at the start of every test.
 ##
setup () {
    # Setup logic here.
}

###
 # This will run at the end of every test.
 ##
teardown () {
    # Teardown logic here.
}

Create actual tests with:

@test "<name_of_test>" {
    # Test logic here.
}

Assertion Statements

As of writing this, possible assertion statements appear to be:

# Assert success.
assert <command>

# Assert failure.
refute <command>

# Assert two values are equal.
assert_equal <val_1> <val_2>

# Assert function succeeds (returns 0).
assert_success <function_call>

# Assert function fails (returns 1).
assert_failure <function_call>

# Assert that a variable called ${output} matches the expected value.
assert_output <expected_value>

# Assert that a variable called ${output} does not match the expected value.
refute_output <expected_value>

# Assert that a given line appears in "output".

ToDo: is this a variable? Or actual echo output?
assert_line <line_to_match>

# Assert that a given line does not appear in "output".

ToDo: is this a variable? Or actual echo output?
refute_line <line_to_match>

Other Assertions

It's possible to also do assertions via standard if statement syntax. Simply include the condition clause but nothing else.

Ex:

# Check if ${my_var} is equal to 5.
[[ ${my_var} == 5 ]]

# Check if ${my_var} does not match the string "This is a string."
[[ ${my_var} != "This is a string." ]]

# Check if ${some_number} is greater than 5.
[[ ${some_number} > 5 ]]

If any of these checks were to fail, then the test itself would stop on the given line and return a failure.