Search code examples
testingbats-core

Test creation of specific directory and its contents via bats


I am invoking an interactive cli tool I have created (using go but that's not in the question's scope).

I am performing integration tests on it using a combination of BATS and expect.

Here is the specific test suite:

@test "Running interactive test - providing clone directory parameter" {
    cd test_expect
    eval "./basic_interactive.exp"
}

The success of this step is the creation of a specific directory with pre-defined contents.

Since I am new to BATS I cannot find a way to somehow assert that the command

ls -1 /path/to/directory/that/is/supposed/to/be/created

will equal

file1
file2
file3

etc.

Any suggestions?

I have tried this

@test "Running interactive test - providing clone directory parameter" {
    cd test_expect
    eval "./basic_interactive.exp"
    eval "ls -1 path/to/directory/that/is/supposed/to/be/created"
    echo $output
}

but it does not print anything.


Solution

  • If I understand your question correctly, you basically want to run a command and validate the output, correct?

    Quoting from the BATS manual

    Bats includes a run helper that invokes its arguments as a command, saves the exit status and output into special global variables

    The two variables that are available inside a BATS test method to validate output are:

    • $output, which contains the combined contents of the command's standard output and standard error streams

    • the $lines array, for easily accessing individual lines of output

    Applying this to your example would give us:

    @test "Running interactive test - providing clone directory parameter" {
        cd test_expect
        ./basic_interactive.exp
    
        run ls -1 path/to/directory/that/is/supposed/to/be/created
    
        expected=$(cat <<-TXT
    file1
    file2
    file3
    TXT
    )
    
        [ "${output}" = "${expected}" ]
    }
    
    

    If you find yourself using BATS more often (or for more complex tests) you might consider using a dedicated asserts library (like bats-assert) to make your life a bit easier.

    (Especially the assert_output command is worth looking into, as it supports literal, partial, and regex matching).

    To understand why you are not seeing any output, you will need to read the section in the manual titled "Printing to the terminal". In short it boils down to output only being shown when redirected to file descriptor 3:

    @test "test with output to terminal" {
        echo "# This will show up when you run the test" >&3
    }