OILS / stdlib / ysh / no-quotes.ysh View on Github | oilshell.org

127 lines, 60 significant
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}
8source $LIB_OSH/two.sh
9
10nq-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
37nq-run() {
38 ### capture status only
39
40 local -n out_status=$1
41 shift
42
43 local __status
44
45 # Tricky: turn errexit off so we can capture it, but turn it on against
46 set +o errexit
47 ( set -o errexit; "$@" )
48 __status=$?
49 set -o errexit
50
51 out_status=$__status
52}
53
54proc nq-capture(; out; ; block) {
55 ### capture status and stderr
56
57 var stdout = ''
58 try {
59 eval (block) | read --all (&stdout)
60 }
61 # TODO: if 'block' contains a pipeline, we lose this agic var
62 var result = {status: _pipeline_status[0], stdout}
63
64 #echo 'result-1'
65 #pp line (result)
66
67 call out->setValue(result)
68}
69
70proc nq-capture-2(; out; ; block) {
71 ### capture status and stderr
72
73 var stderr = ''
74 try {
75 eval (block) 2>&1 | read --all (&stderr)
76 }
77 #pp line (_pipeline_status)
78
79 var result = {status: _pipeline_status[0], stderr}
80 #echo 'result-2'
81 #pp line (result)
82
83 call out->setValue(result)
84}
85
86# 'byo test' can set this?
87: ${NQ_TEST_TEMP=/tmp}
88
89nq-redir() {
90 ### capture status and stdout
91
92 local -n out_status=$1
93 local -n out_stdout_file=$2
94 shift 2
95
96 local __status
97 local __stdout_file=$NQ_TEST_TEMP/nq-redir-$$.txt
98
99 # Tricky: turn errexit off so we can capture it, but turn it on against
100 set +o errexit
101 ( set -o errexit; "$@" ) > $__stdout_file
102 __status=$?
103 set -o errexit
104
105 out_status=$__status
106 out_stdout_file=$__stdout_file
107}
108
109nq-redir-2() {
110 ### capture status and stdout
111
112 local -n out_status=$1
113 local -n out_stderr_file=$2
114 shift 2
115
116 local __status
117 local __stderr_file=$NQ_TEST_TEMP/nq-redir-$$.txt
118
119 # Tricky: turn errexit off so we can capture it, but turn it on against
120 set +o errexit
121 ( set -o errexit; "$@" ) 2> $__stderr_file
122 __status=$?
123 set -o errexit
124
125 out_status=$__status
126 out_stderr_file=$__stderr_file
127}