Search code examples
linuxbashshelltestingspy

how to spy on linux binaries for testing of shell scripts


sorry if this is a duplicate, i had no idea what to search for...

my use case is more complex, but can be narrowed down to the following problem:

i want to run a bash script, which invokes all sorts of binaries, for example: grep. i want to assert that the binaries were invoked with the correct arguments. these assertions should be part of automated testing, i don't want to manually start checking things. this should go into ci cycle.

is there some standard way of doing this?

if not, i thought of moving all the binaries i wish to assert, replace them with a spy which first logs the arguments and then invokes the original binary and finally remove itself and return the original binary.

is this feasible? is there a better approach to the problem?


Solution

  • Just an idea, I didn't see this anywhere but:

    Unless you're using full paths to invoke those binaries, you could create mocks of those libraries, e.g., in your projects bin/ directory and make that directory be the first in your $PATH.

    export PATH="$PWD/bin:$PATH"
    

    To mock grep, for example, you could do:

    A helper executable to increment counts:

    #!/bin/bash
    #Usage: increment FILE_WITH_A_NUMBER
    touch "$1" #To create it if it doesn't exist
    NTIMES=$(( $(cat "$1") + 1 ))
    echo "$NTIMES" > "$1"
    

    A mock template (in bin/grep):

    #!/bin/bash
    
    increment ${BASH_SOURCE[0]}.log    #=> bin/grep.log
    
    #Possibly do some other stuff, such as log parameters
    
    #Return a mocked result
    echo "fake match"
    
    #Or delegate to the real thing:
    exec /usr/bin/grep "$@"