OILS / stdlib / osh / testing.sh View on Github | oilshell.org

99 lines, 55 significant
1#!/usr/bin/env bash
2#
3# Testing library for bash and OSH.
4#
5# Capture status/stdout/stderr, and sh-assert.
6
7source stdlib/osh/two.sh
8
9sh-assert() {
10 ### Must be run with errexit off
11
12 if ! test "$@"; then
13 # old message
14 # note: it's extremely weird that we use -1 and 0, but that seems to be how
15 # bash works.
16 #die "${BASH_SOURCE[-1]}:${BASH_LINENO[0]}: sh-assertn '$@' failed"
17
18 die "line ${BASH_LINENO[0]}: sh-assert '$@' failed"
19 fi
20}
21
22capture-command() {
23 ### capture status and stdout
24
25 local -n out_status=$1
26 local -n out_stdout=$2
27 shift 2
28
29 local __status
30 local __stdout
31
32 # Tricky: turn errexit off so we can capture it, but turn it on against
33 set +o errexit
34 __stdout=$(set -o errexit; "$@")
35 __status=$?
36 set -o errexit
37
38 out_status=$__status
39 out_stdout=$__stdout
40}
41
42capture-command-2() {
43 ### capture status and stderr
44
45 # This is almost identical to the above
46
47 local -n out_status=$1
48 local -n out_stderr=$2
49 shift 2
50
51 local __status
52 local __stderr
53
54 # Tricky: turn errexit off so we can capture it, but turn it on against
55 set +o errexit
56 __stderr=$(set -o errexit; "$@" 2>&1)
57 __status=$?
58 set -o errexit
59
60 out_status=$__status
61 out_stderr=$__stderr
62}
63
64_demo-stderr() {
65 echo zzz "$@" >& 2
66 return 99
67}
68
69test-capture-command() {
70 local status stdout
71 capture-command status stdout \
72 echo hi
73
74 sh-assert 0 = "$status"
75 sh-assert 'hi' = "$stdout"
76
77 local stderr
78 capture-command-2 status stderr \
79 _demo-stderr yyy
80
81 #echo "stderr: [$stderr]"
82
83 sh-assert 99 = "$status"
84 sh-assert 'zzz yyy' = "$stderr"
85
86 capture-command status stdout \
87 _demo-stderr aaa
88
89 #echo "stderr: [$stderr]"
90
91 sh-assert 99 = "$status"
92 sh-assert '' = "$stdout"
93}
94
95name=$(basename $0)
96if test "$name" = 'testing.sh'; then
97 "$@"
98fi
99