Bats Concepts

From NovaOrdis Knowledge Base
Revision as of 16:30, 3 October 2019 by Ovidiu (talk | contribs) (→‎Test)
Jump to navigation Jump to search

Internal

Overview

Shell scripts can be tested easier if the functionality is broken into many small, reusable and independently testable functions.

A library of such function can be tested by sourcing the library into the BATS test and run the functions as their usual calling layer would invoke them.

Test

An individual test is placed into a @test-annotated code block.

@test "something" {

    run my-command status
    [[ ${status} -eq 0 ]]
    [[ ${output} =~ We[[:space:]]are[[:space:]]good ]]
}

The label that follows @test may include spaces.

Tests are executed in the order they're specified in the file.

BATS uses exec to run each @test block as a separate subprocess. This makes it possible to export environment variables and even functions in one @test without affecting the other @tests or polluting the current shell session.

Run a Command and Check the Status and Output

some_command=....
[...]
run ${some_command}
[[ ${status} -eq 0 ]]
[[ ${output} =~ .*Stack[[:space:]]test[[:space:]]is[[:space:]]stable[[:space:]]and[[:space:]]running* ]]

${output}

$(output) coalesce lines:

some_command=....
[...]
run ${some_command}
[[ ${output} =~ .*Stack[[:space:]]test[[:space:]]is[[:space:]]stable[[:space:]]and[[:space:]]running* ]]

${lines}

Setup/Teardown

If the BATS script includes setup() and teardown() functions, they are automatically executed by BATS before and after each test block runs.