aboutsummaryrefslogtreecommitdiff
path: root/testlib.sh
blob: e65b257e28582f4ed54fdcd0a5b2364bd053e35b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/bin/bash
# 2008 Junichi Uekawa <dancer@debian.org>

set -e 

# library for functional unit-testing in bash.

TESTLIB_FAILS=0
TESTLIB_TESTS=0

testlib_echo() {
    case "$1" in
	OK)
	    # no output is probably good.
    	    ;;
	FAIL)
	    shift
	    echo "[FAIL]" "$@" >&2 
	    TESTLIB_FAILS=$((TESTLIB_FAILS+1))
	    ;;
    esac
    TESTLIB_TESTS=$((TESTLIB_TESTS+1))
}

testlib_summary() {
    echo "$0: Ran ${TESTLIB_TESTS} tests and $((TESTLIB_TESTS - TESTLIB_FAILS)) succeeded, ${TESTLIB_FAILS} failed"
    if [ $TESTLIB_FAILS != 0 ]; then
	echo '================='
	echo 'Testsuite FAILED!'
	echo "  $0"
	echo '================='
	exit 1
    fi
    exit 0
}

expect_success() {
    # run the test in subshell
    if (
	"$@"
	); then
	testlib_echo "OK" "$1" 
    else
	testlib_echo "FAIL" "$1" 
    fi
}

expect_fail() {
    # run the test in subshell
    if (
	"$@"
	); then
	testlib_echo "FAIL" "$1"
    else
	testlib_echo "OK" "$1"
    fi
}

expect_output() {
    # run the test in subshell
    local val result
    val="$1"; shift 
    result="$( ( "$@" 2>&1 ) )"|| true
    if [ "${result}" = "${val}" ]; then
	testlib_echo "OK" "$1"
    else
	testlib_echo "FAIL" "$1 reason: [${result}] != [${val}]" 
    fi
}

#   Write your functions test_xxxx and call them at the end with their expected result code:
# . ./testlib.sh
# expect_success test_success
# expect_success test_fail
# expect_success test_options "hello world"
# testlib_summary