Script zum automatischen Testen eines Programms mit festgelegten Inputs und Outputs

Um in Systems Programming automatisch Tests der letzten C Exercise durchführen zu können, wurde ein kleines Script praktisch, welches automatisch die eigene Binary für alle input.txt Dateien überprüft. Man legt es neben zwei Ordner namens „input“ und „output“, welche die passenden Dateien für die Tests beinhalten (wie im gegebenen Beispielordner)

# Aufruf
./test.sh build/minesweeper

Das Script ist hier in einem eigenen Gist enthalten, im folgenden als Auszug dabei und als Archiv auch als Datei an diesen Artikel angehängt.

#! /usr/bin/env bash

# This test script tries all inputs and compares them with
# their respective outputs. Supply it with
# the name of the executable.

name=$1

# Color Constants
SUCCESS_COLOR='\033[0;32m'
ERROR_COLOR='\033[0;31m'
NO_COLOR='\033[0m'

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )"

if [ "$#" -ne 1 ]; then
    echo "Must supply path to minesweeper executable!"
    exit
fi

if [[ ! -x "$name" ]]; then
    echo "The file must be the executable!"
    exit
fi

echo "Running tests for binary in \"$name\"."
echo "Path of tests: \"$DIR\""

for file in $DIR/input/*.txt; do
    testname="${file##*/}"
    outputname="${testname/input/output}"

    expected=$(cat $DIR/output/$outputname)
    result=$($name $file)

    (diff <(echo "$result") <(echo "$expected") && printf "${SUCCESS_COLOR}Test in $file ran successful! $NO_COLOR \n") || printf "${ERROR_COLOR}Test in $file failed! $NO_COLOR\n"
done