init.sh: suggest to use skip_ and fail_ functions in comments
[gnulib.git] / tests / init.sh
1 # source this file; set up for tests
2
3 # Copyright (C) 2009 Free Software Foundation, Inc.
4
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14
15 # You should have received a copy of the GNU General Public License
16 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18 # Using this file in a test
19 # =========================
20 #
21 # The typical skeleton of a test looks like this:
22 #
23 #   #!/bin/sh
24 #   : ${srcdir=.}
25 #   . "$srcdir/init.sh" --set-path=.
26 #   Execute some commands.
27 #   Note that these commands are executed in a subdirectory, therefore you
28 #   need to prepend "../" to relative filenames in the build directory.
29 #   Set the exit code 0 for success, 77 for skipped, or 1 or other for failure.
30 #   Use the skip_ and fail_ functions to print a diagnostic and then exit
31 #   with the corresponding exit code.
32 #   Exit $?
33
34 # Executing a test that uses this file
35 # ====================================
36 #
37 # Running a single test:
38 #   $ make check TESTS=test-foo.sh
39 #
40 # Running a single test, with verbose output:
41 #   $ make check TESTS=test-foo.sh VERBOSE=yes
42 #
43 # Running a single test, with single-stepping:
44 #   1. Go into a sub-shell:
45 #   $ bash
46 #   2. Set relevant environment variables from TESTS_ENVIRONMENT in the
47 #      Makefile:
48 #   $ export srcdir=../../tests # this is an example
49 #   3. Execute the commands from the test, copy&pasting them one by one:
50 #   $ . "$srcdir/init.sh" --set-path=.
51 #   ...
52 #   4. Finally
53 #   $ exit
54
55 # We use a trap below for cleanup.  This requires us to go through
56 # hoops to get the right exit status transported through the handler.
57 # So use `Exit STATUS' instead of `exit STATUS' inside of the tests.
58 # Turn off errexit here so that we don't trip the bug with OSF1/Tru64
59 # sh inside this function.
60 Exit () { set +e; (exit $1); exit $1; }
61
62 fail_() { echo "$ME_: failed test: $@" 1>&2; Exit 1; }
63 skip_() { echo "$ME_: skipped test: $@" 1>&2; Exit 77; }
64
65 # This is a stub function that is run upon trap (upon regular exit and
66 # interrupt).  Override it with a per-test function, e.g., to unmount
67 # a partition, or to undo any other global state changes.
68 cleanup_() { :; }
69
70 if ( diff --version < /dev/null 2>&1 | grep GNU ) 2>&1 > /dev/null; then
71   compare() { diff -u "$@"; }
72 elif ( cmp --version < /dev/null 2>&1 | grep GNU ) 2>&1 > /dev/null; then
73   compare() { cmp -s "$@"; }
74 else
75   compare() { cmp "$@"; }
76 fi
77
78 # An arbitrary prefix to help distinguish test directories.
79 testdir_prefix_() { printf gt; }
80
81 # Run the user-overridable cleanup_ function, remove the temporary
82 # directory and exit with the incoming value of $?.
83 remove_tmp_()
84 {
85   __st=$?
86   cleanup_
87   # cd out of the directory we're about to remove
88   cd "$initial_cwd_" || cd / || cd /tmp
89   chmod -R u+rwx "$test_dir_"
90   # If removal fails and exit status was to be 0, then change it to 1.
91   rm -rf "$test_dir_" || { test $__st = 0 && __st=1; }
92   exit $__st
93 }
94
95 setup_()
96 {
97   test "$VERBOSE" = yes && set -x
98
99   # Honor one or more --set-path=. options (i.e., or --set-path=../src).
100   # Use this option to prepend to PATH an absolute name for the
101   # specified, possibly-relative, directory.
102   while test $# != 0; do
103     case $1 in
104       --set-path=*)
105         path_dir_=${1#--set-path=}
106         test -z "$path_dir_" && fail_ "missing argument to --set-path="
107         abs_path_dir_=`cd "$path_dir_" && echo "$PWD" || exit 1` \
108             || fail_ "invalid path dir: $path_dir"
109         PATH="$abs_path_dir_:$PATH"
110         export PATH
111         shift
112         ;;
113       *) fail_ "unrecognized option: $1"
114         ;;
115     esac
116   done
117
118   initial_cwd_=$PWD
119   ME_=`expr "./$0" : '.*/\(.*\)$'`
120
121   pfx_=`testdir_prefix_`
122   test_dir_=`mktempd_ "$initial_cwd_" "$pfx_-$ME_.XXXX"` \
123     || fail_ "failed to create temporary directory in $initial_cwd_"
124   cd "$test_dir_"
125
126   # This pair of trap statements ensures that the temporary directory,
127   # $test_dir_, is removed upon exit as well as upon catchable signal.
128   trap remove_tmp_ 0
129   trap 'Exit $?' 1 2 13 15
130 }
131
132 # Create a temporary directory, much like mktemp -d does.
133 # Written by Jim Meyering.
134 #
135 # Usage: mktempd_ /tmp phoey.XXXXXXXXXX
136 #
137 # First, try to use the mktemp program.
138 # Failing that, we'll roll our own mktemp-like function:
139 #  - try to get random bytes from /dev/urandom
140 #  - failing that, generate output from a combination of quickly-varying
141 #      sources and gzip.  Ignore non-varying gzip header, and extract
142 #      "random" bits from there.
143 #  - given those bits, map to file-name bytes using tr, and try to create
144 #      the desired directory.
145 #  - make only $MAX_TRIES_ attempts
146
147 # Helper function.  Print $N pseudo-random bytes from a-zA-Z0-9.
148 rand_bytes_()
149 {
150   n_=$1
151
152   # Maybe try openssl rand -base64 $n_prime_|tr '+/=\012' abcd first?
153   # But if they have openssl, they probably have mktemp, too.
154
155   chars_=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
156   dev_rand_=/dev/urandom
157   if test -r "$dev_rand_"; then
158     # Note: 256-length($chars_) == 194; 3 copies of $chars_ is 186 + 8 = 194.
159     dd ibs=$n_ count=1 if=$dev_rand_ 2>/dev/null \
160       | tr -c $chars_ 01234567$chars_$chars_$chars_
161     return
162   fi
163
164   n_plus_50_=`expr $n_ + 50`
165   cmds_='date; date +%N; free; who -a; w; ps auxww; ps ef; netstat -n'
166   data_=` (eval "$cmds_") 2>&1 | gzip `
167
168   # Ensure that $data_ has length at least 50+$n_
169   while :; do
170     len_=`echo "$data_"|wc -c`
171     test $n_plus_50_ -le $len_ && break;
172     data_=` (echo "$data_"; eval "$cmds_") 2>&1 | gzip `
173   done
174
175   echo "$data_" \
176     | dd bs=1 skip=50 count=$n_ 2>/dev/null \
177     | tr -c $chars_ 01234567$chars_$chars_$chars_
178 }
179
180 mktempd_()
181 {
182   case $# in
183   2);;
184   *) fail_ "Usage: $ME DIR TEMPLATE";;
185   esac
186
187   destdir_=$1
188   template_=$2
189
190   MAX_TRIES_=4
191
192   # Disallow any trailing slash on specified destdir:
193   # it would subvert the post-mktemp "case"-based destdir test.
194   case $destdir_ in
195   /) ;;
196   */) fail_ "invalid destination dir: remove trailing slash(es)";;
197   esac
198
199   case $template_ in
200   *XXXX) ;;
201   *) fail_ "invalid template: $template_ (must have a suffix of at least 4 X's)";;
202   esac
203
204   fail=0
205
206   # First, try to use mktemp.
207   d=`env -u TMPDIR mktemp -d -t -p "$destdir_" "$template_" 2>/dev/null` \
208     || fail=1
209
210   # The resulting name must be in the specified directory.
211   case $d in "$destdir_"*);; *) fail=1;; esac
212
213   # It must have created the directory.
214   test -d "$d" || fail=1
215
216   # It must have 0700 permissions.  Handle sticky "S" bits.
217   perms=`ls -dgo "$d" 2>/dev/null|tr S -` || fail=1
218   case $perms in drwx------*) ;; *) fail=1;; esac
219
220   test $fail = 0 && {
221     echo "$d"
222     return
223   }
224
225   # If we reach this point, we'll have to create a directory manually.
226
227   # Get a copy of the template without its suffix of X's.
228   base_template_=`echo "$template_"|sed 's/XX*$//'`
229
230   # Calculate how many X's we've just removed.
231   template_length_=`echo "$template_" | wc -c`
232   nx_=`echo "$base_template_" | wc -c`
233   nx_=`expr $template_length_ - $nx_`
234
235   err_=
236   i_=1
237   while :; do
238     X_=`rand_bytes_ $nx_`
239     candidate_dir_="$destdir_/$base_template_$X_"
240     err_=`mkdir -m 0700 "$candidate_dir_" 2>&1` \
241       && { echo "$candidate_dir_"; return; }
242     test $MAX_TRIES_ -le $i_ && break;
243     i_=`expr $i_ + 1`
244   done
245   fail_ "$err_"
246 }
247
248 # If you want to override the testdir_prefix_ function,
249 # or to add more utility functions, use this file.
250 test -f "$srcdir/init.cfg" \
251   && . "$srcdir/init.cfg"
252
253 setup_ "$@"