Skip to content

Instantly share code, notes, and snippets.

@klmr
Created March 31, 2012 21:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save klmr/2268486 to your computer and use it in GitHub Desktop.
Save klmr/2268486 to your computer and use it in GitHub Desktop.
Unit test harness for failed compile-time assertions
#!/bin/bash
set -e
set -u
# This script runs assertions that should fail at compile-time.
# This precludes the use of a conventional test runner. Instead, we build a
# harness and capture whether specific test cases compile successfully or
# not.
# Some preliminary definitions.
BIN_NAME=failed_asserts_test_harness
SOURCE_NAME=$BIN_NAME.cpp
PREFIX='// Put any includes etc. here.
int main() {'
SUFFIX='}'
buildandrun() {
echo "$PREFIX$1$SUFFIX" > $SOURCE_NAME;
make $BIN_NAME > /dev/null 2>&1 && ./$BIN_NAME;
RESULT=$?;
rm -f $BIN_NAME $SOURCE_NAME;
return $RESULT;
}
# First, check that the test harness actually compiles fine.
if ! buildandrun 'int test_harness_check();'; then
echo 'FATAL ERROR: Test harness not working.';
exit 1;
fi
# The actual test cases reside in a sub-folder called 'fail'
TESTS=(fail/*.cpp)
# The test runner.
FAILED=0
for TEST in "${TESTS[@]}"; do
if buildandrun "$(cat "$TEST")"; then
NAME=$(echo "$TEST" | sed 's|^fail/\(.*\).cpp|\1|')
echo Test '`'$NAME'`' compiled, but shouldn"'"t.
FAILED=$((FAILED+1));
fi
done
if [ $FAILED -eq 0 ]; then
echo "[Testing completed. All ${#TESTS[@]} test cases passed]"
exit 0
else
echo
echo "[Testing completed. $FAILED of ${#TESTS[@]} test cases failed]"
exit 2
fi
// Example of a failed test …
int* px = 1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment