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