1 | #!/usr/bin/env bash
|
2 | #
|
3 | # Testing library for bash and OSH.
|
4 | #
|
5 | # Capture status/stdout/stderr, and nq-assert those values.
|
6 |
|
7 | : ${LIB_OSH=stdlib/osh}
|
8 | source $LIB_OSH/two.sh
|
9 |
|
10 | nq-assert() {
|
11 | ### Assertion with same syntax as shell 'test'
|
12 |
|
13 | if ! test "$@"; then
|
14 | die "line ${BASH_LINENO[0]}: nq-assert $(printf '%q ' "$@") failed"
|
15 | fi
|
16 | }
|
17 |
|
18 | # Problem: we want to capture status and stdout at the same time
|
19 | #
|
20 | # We use:
|
21 | #
|
22 | # __stdout=$(set -o errexit; "$@")
|
23 | # __status=$?
|
24 | #
|
25 | # However, we lose the trailing \n, since that's how command subs work.
|
26 |
|
27 | # Here is another possibility:
|
28 | #
|
29 | # shopt -s lastpipe # need this too
|
30 | # ( set -o errexit; "$@" ) | read -r -d __stdout
|
31 | # __status=${PIPESTATUS[0]}
|
32 | # shopt -u lastpipe
|
33 | #
|
34 | # But this feels complex for just the \n issue, which can be easily worked
|
35 | # around.
|
36 |
|
37 | nq-capture() {
|
38 | ### capture status and stdout
|
39 |
|
40 | local -n out_status=$1
|
41 | local -n out_stdout=$2
|
42 | shift 2
|
43 |
|
44 | local __status
|
45 | local __stdout
|
46 |
|
47 | # Tricky: turn errexit off so we can capture it, but turn it on against
|
48 | set +o errexit
|
49 | __stdout=$(set -o errexit; "$@")
|
50 | __status=$?
|
51 | set -o errexit
|
52 |
|
53 | out_status=$__status
|
54 | out_stdout=$__stdout
|
55 | }
|
56 |
|
57 | nq-capture-2() {
|
58 | ### capture status and stderr
|
59 |
|
60 | # This is almost identical to the above
|
61 |
|
62 | local -n out_status=$1
|
63 | local -n out_stderr=$2
|
64 | shift 2
|
65 |
|
66 | local __status
|
67 | local __stderr
|
68 |
|
69 | # Tricky: turn errexit off so we can capture it, but turn it on against
|
70 | set +o errexit
|
71 | __stderr=$(set -o errexit; "$@" 2>&1)
|
72 | __status=$?
|
73 | set -o errexit
|
74 |
|
75 | out_status=$__status
|
76 | out_stderr=$__stderr
|
77 | }
|
78 |
|
79 | _demo-stderr() {
|
80 | echo zzz "$@" >& 2
|
81 | return 99
|
82 | }
|
83 |
|
84 | test-nq-capture() {
|
85 | local status stdout
|
86 | nq-capture status stdout \
|
87 | echo -n hi
|
88 | nq-assert 0 = "$status"
|
89 | nq-assert 'hi' = "$stdout"
|
90 |
|
91 | nq-capture status stdout \
|
92 | echo hi
|
93 | nq-assert 0 = "$status"
|
94 | # Note that we LOSE the last newline!
|
95 | #nq-assert $'hi\n' = "$stdout"
|
96 |
|
97 | local stderr
|
98 | nq-capture-2 status stderr \
|
99 | _demo-stderr yyy
|
100 |
|
101 | #echo "stderr: [$stderr]"
|
102 |
|
103 | nq-assert 99 = "$status"
|
104 | nq-assert 'zzz yyy' = "$stderr"
|
105 |
|
106 | nq-capture status stdout \
|
107 | _demo-stderr aaa
|
108 |
|
109 | #echo "stderr: [$stderr]"
|
110 |
|
111 | nq-assert 99 = "$status"
|
112 | nq-assert '' = "$stdout"
|
113 | }
|
114 |
|
115 | name=$(basename $0)
|
116 | if test "$name" = 'no-quotes.sh'; then
|
117 | "$@"
|
118 | fi
|