maint: update almost all copyright ranges to include 2011
[gnulib.git] / tests / init.sh
1 # source this file; set up for tests
2
3 # Copyright (C) 2009-2011 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=.}/init.sh"; path_prepend_ .
25 #   Execute some commands.
26 #   Note that these commands are executed in a subdirectory, therefore you
27 #   need to prepend "../" to relative filenames in the build directory.
28 #   Note that the "path_prepend_ ." is useful only if the body of your
29 #   test invokes programs residing in the initial directory.
30 #   For example, if the programs you want to test are in src/, and this test
31 #   script is named tests/test-1, then you would use "path_prepend_ ../src",
32 #   or perhaps export PATH='$(abs_top_builddir)/src$(PATH_SEPARATOR)'"$$PATH"
33 #   to all tests via automake's TESTS_ENVIRONMENT.
34 #   Set the exit code 0 for success, 77 for skipped, or 1 or other for failure.
35 #   Use the skip_ and fail_ functions to print a diagnostic and then exit
36 #   with the corresponding exit code.
37 #   Exit $?
38
39 # Executing a test that uses this file
40 # ====================================
41 #
42 # Running a single test:
43 #   $ make check TESTS=test-foo.sh
44 #
45 # Running a single test, with verbose output:
46 #   $ make check TESTS=test-foo.sh VERBOSE=yes
47 #
48 # Running a single test, with single-stepping:
49 #   1. Go into a sub-shell:
50 #   $ bash
51 #   2. Set relevant environment variables from TESTS_ENVIRONMENT in the
52 #      Makefile:
53 #   $ export srcdir=../../tests # this is an example
54 #   3. Execute the commands from the test, copy&pasting them one by one:
55 #   $ . "$srcdir/init.sh"; path_prepend_ .
56 #   ...
57 #   4. Finally
58 #   $ exit
59
60 ME_=`expr "./$0" : '.*/\(.*\)$'`
61
62 # We use a trap below for cleanup.  This requires us to go through
63 # hoops to get the right exit status transported through the handler.
64 # So use `Exit STATUS' instead of `exit STATUS' inside of the tests.
65 # Turn off errexit here so that we don't trip the bug with OSF1/Tru64
66 # sh inside this function.
67 Exit () { set +e; (exit $1); exit $1; }
68
69 # Print warnings (e.g., about skipped and failed tests) to this file number.
70 # Override by defining to say, 9, in init.cfg, and putting say,
71 # "export ...ENVVAR_SETTINGS...; exec 9>&2; $(SHELL)" in the definition
72 # of TESTS_ENVIRONMENT in your tests/Makefile.am file.
73 # This is useful when using automake's parallel tests mode, to print
74 # the reason for skip/failure to console, rather than to the .log files.
75 : ${stderr_fileno_=2}
76
77 warn_() { echo "$@" 1>&$stderr_fileno_; }
78 fail_() { warn_ "$ME_: failed test: $@"; Exit 1; }
79 skip_() { warn_ "$ME_: skipped test: $@"; Exit 77; }
80 framework_failure_() { warn_ "$ME_: set-up failure: $@"; Exit 99; }
81
82 # Sanitize this shell to POSIX mode, if possible.
83 DUALCASE=1; export DUALCASE
84 if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
85   emulate sh
86   NULLCMD=:
87   alias -g '${1+"$@"}'='"$@"'
88   setopt NO_GLOB_SUBST
89 else
90   case `(set -o) 2>/dev/null` in
91     *posix*) set -o posix ;;
92   esac
93 fi
94
95 # We require $(...) support unconditionally.
96 # We require a few additional shell features only when $EXEEXT is nonempty,
97 # in order to support automatic $EXEEXT emulation:
98 # - hyphen-containing alias names
99 # - we prefer to use ${var#...} substitution, rather than having
100 #   to work around lack of support for that feature.
101 # The following code attempts to find a shell with support for these features.
102 # If the current shell passes the test, we're done.  Otherwise, test other
103 # shells until we find one that passes.  If one is found, re-exec it.
104 # If no acceptable shell is found, skip the current test.
105 #
106 # The "...set -x; P=1 true 2>err..." test is to disqualify any shell that
107 # emits "P=1" into err, as /bin/sh from SunOS 5.11 and OpenBSD 4.7 do.
108 #
109 # Use "9" to indicate success (rather than 0), in case some shell acts
110 # like Solaris 10's /bin/sh but exits successfully instead of with status 2.
111
112 # Eval this code in a subshell to determine a shell's suitability.
113 # 10 - passes all tests; ok to use
114 #  9 - ok, but enabling "set -x" corrupts app stderr; prefer higher score
115 #  ? - not ok
116 gl_shell_test_script_='
117 test $(echo y) = y || exit 1
118 score_=10
119 if test "$VERBOSE" = yes; then
120   test -n "$( (exec 3>&1; set -x; P=1 true 2>&3) 2> /dev/null)" && score_=9
121 fi
122 test -z "$EXEEXT" && exit $score_
123 shopt -s expand_aliases
124 alias a-b="echo zoo"
125 v=abx
126      test ${v%x} = ab \
127   && test ${v#a} = bx \
128   && test $(a-b) = zoo \
129   && exit $score_
130 '
131
132 if test "x$1" = "x--no-reexec"; then
133   shift
134 else
135   # Assume a working shell.  Export to subshells (setup_ needs this).
136   gl_set_x_corrupts_stderr_=false
137   export gl_set_x_corrupts_stderr_
138
139   # Record the first marginally acceptable shell.
140   marginal_=
141
142   # Search for a shell that meets our requirements.
143   for re_shell_ in __current__ "${CONFIG_SHELL:-no_shell}" \
144       /bin/sh bash dash zsh pdksh fail
145   do
146     test "$re_shell_" = no_shell && continue
147
148     # If we've made it all the way to the sentinel, "fail" without
149     # finding even a marginal shell, skip this test.
150     if test "$re_shell_" = fail; then
151       test -z "$marginal_" && skip_ failed to find an adequate shell
152       re_shell_=$marginal_
153       break
154     fi
155
156     # When testing the current shell, simply "eval" the test code.
157     # Otherwise, run it via $re_shell_ -c ...
158     if test "$re_shell_" = __current__; then
159       # 'eval'ing this code makes Solaris 10's /bin/sh exit with
160       # $? set to 2.  It does not evaluate any of the code after the
161       # "unexpected" first `('.  Thus, we must run it in a subshell.
162       ( eval "$gl_shell_test_script_" ) > /dev/null 2>&1
163     else
164       "$re_shell_" -c "$gl_shell_test_script_" 2>/dev/null
165     fi
166
167     st_=$?
168
169     # $re_shell_ works just fine.  Use it.
170     test $st_ = 10 && break
171
172     # If this is our first marginally acceptable shell, remember it.
173     if test "$st_:$marginal_" = 9: ; then
174       marginal_="$re_shell_"
175       gl_set_x_corrupts_stderr_=true
176     fi
177   done
178
179   if test "$re_shell_" != __current__; then
180     # Found a usable shell.  Preserve -v and -x.
181     case $- in
182       *v*x* | *x*v*) opts_=-vx ;;
183       *v*) opts_=-v ;;
184       *x*) opts_=-x ;;
185       *) opts_= ;;
186     esac
187     exec "$re_shell_" $opts_ "$0" --no-reexec "$@"
188     echo "$ME_: exec failed" 1>&2
189     exit 127
190   fi
191 fi
192
193 test -n "$EXEEXT" && shopt -s expand_aliases
194
195 # Enable glibc's malloc-perturbing option.
196 # This is cheap and useful for exposing code that depends on the fact that
197 # malloc-related functions often return memory that is mostly zeroed.
198 # If you have the time and cycles, use valgrind to do an even better job.
199 : ${MALLOC_PERTURB_=87}
200 export MALLOC_PERTURB_
201
202 # This is a stub function that is run upon trap (upon regular exit and
203 # interrupt).  Override it with a per-test function, e.g., to unmount
204 # a partition, or to undo any other global state changes.
205 cleanup_() { :; }
206
207 if ( diff --version < /dev/null 2>&1 | grep GNU ) > /dev/null 2>&1; then
208   compare() { diff -u "$@"; }
209 elif ( cmp --version < /dev/null 2>&1 | grep GNU ) > /dev/null 2>&1; then
210   compare() { cmp -s "$@"; }
211 else
212   compare() { cmp "$@"; }
213 fi
214
215 # An arbitrary prefix to help distinguish test directories.
216 testdir_prefix_() { printf gt; }
217
218 # Run the user-overridable cleanup_ function, remove the temporary
219 # directory and exit with the incoming value of $?.
220 remove_tmp_()
221 {
222   __st=$?
223   cleanup_
224   # cd out of the directory we're about to remove
225   cd "$initial_cwd_" || cd / || cd /tmp
226   chmod -R u+rwx "$test_dir_"
227   # If removal fails and exit status was to be 0, then change it to 1.
228   rm -rf "$test_dir_" || { test $__st = 0 && __st=1; }
229   exit $__st
230 }
231
232 # Given a directory name, DIR, if every entry in it that matches *.exe
233 # contains only the specified bytes (see the case stmt below), then print
234 # a space-separated list of those names and return 0.  Otherwise, don't
235 # print anything and return 1.  Naming constraints apply also to DIR.
236 find_exe_basenames_()
237 {
238   feb_dir_=$1
239   feb_fail_=0
240   feb_result_=
241   feb_sp_=
242   for feb_file_ in $feb_dir_/*.exe; do
243     # If there was no *.exe file, or there existed a file named "*.exe" that
244     # was deleted between the above glob expansion and the existence test
245     # below, just skip it.
246     test "x$feb_file_" = "x$feb_dir_/*.exe" && test ! -f "$feb_file_" \
247       && continue
248     # Exempt [.exe, since we can't create a function by that name, yet
249     # we can't invoke [ by PATH search anyways due to shell builtins.
250     test "x$feb_file_" = "x$feb_dir_/[.exe" && continue
251     case $feb_file_ in
252       *[!-a-zA-Z/0-9_.+]*) feb_fail_=1; break;;
253       *) # Remove leading file name components as well as the .exe suffix.
254          feb_file_=${feb_file_##*/}
255          feb_file_=${feb_file_%.exe}
256          feb_result_="$feb_result_$feb_sp_$feb_file_";;
257     esac
258     feb_sp_=' '
259   done
260   test $feb_fail_ = 0 && printf %s "$feb_result_"
261   return $feb_fail_
262 }
263
264 # Consider the files in directory, $1.
265 # For each file name of the form PROG.exe, create an alias named
266 # PROG that simply invokes PROG.exe, then return 0.  If any selected
267 # file name or the directory name, $1, contains an unexpected character,
268 # define no alias and return 1.
269 create_exe_shims_()
270 {
271   case $EXEEXT in
272     '') return 0 ;;
273     .exe) ;;
274     *) echo "$0: unexpected \$EXEEXT value: $EXEEXT" 1>&2; return 1 ;;
275   esac
276
277   base_names_=`find_exe_basenames_ $1` \
278     || { echo "$0 (exe_shim): skipping directory: $1" 1>&2; return 0; }
279
280   if test -n "$base_names_"; then
281     for base_ in $base_names_; do
282       alias "$base_"="$base_$EXEEXT"
283     done
284   fi
285
286   return 0
287 }
288
289 # Use this function to prepend to PATH an absolute name for each
290 # specified, possibly-$initial_cwd_-relative, directory.
291 path_prepend_()
292 {
293   while test $# != 0; do
294     path_dir_=$1
295     case $path_dir_ in
296       '') fail_ "invalid path dir: '$1'";;
297       /*) abs_path_dir_=$path_dir_;;
298       *) abs_path_dir_=`cd "$initial_cwd_/$path_dir_" && echo "$PWD"` \
299            || fail_ "invalid path dir: $path_dir_";;
300     esac
301     case $abs_path_dir_ in
302       *:*) fail_ "invalid path dir: '$abs_path_dir_'";;
303     esac
304     PATH="$abs_path_dir_:$PATH"
305
306     # Create an alias, FOO, for each FOO.exe in this directory.
307     create_exe_shims_ "$abs_path_dir_" \
308       || fail_ "something failed (above): $abs_path_dir_"
309     shift
310   done
311   export PATH
312 }
313
314 setup_()
315 {
316   if test "$VERBOSE" = yes; then
317     # Test whether set -x may cause the selected shell to corrupt an
318     # application's stderr.  Many do, including zsh-4.3.10 and the /bin/sh
319     # from SunOS 5.11, OpenBSD 4.7 and Irix 5.x and 6.5.
320     # If enabling verbose output this way would cause trouble, simply
321     # issue a warning and refrain.
322     if $gl_set_x_corrupts_stderr_; then
323       warn_ "using SHELL=$SHELL with 'set -x' corrupts stderr"
324     else
325       set -x
326     fi
327   fi
328
329   initial_cwd_=$PWD
330   fail=0
331
332   pfx_=`testdir_prefix_`
333   test_dir_=`mktempd_ "$initial_cwd_" "$pfx_-$ME_.XXXX"` \
334     || fail_ "failed to create temporary directory in $initial_cwd_"
335   cd "$test_dir_"
336
337   # As autoconf-generated configure scripts do, ensure that IFS
338   # is defined initially, so that saving and restoring $IFS works.
339   gl_init_sh_nl_='
340 '
341   IFS=" ""      $gl_init_sh_nl_"
342
343   # This trap statement, along with a trap on 0 below, ensure that the
344   # temporary directory, $test_dir_, is removed upon exit as well as
345   # upon receipt of any of the listed signals.
346   for sig_ in 1 2 3 13 15; do
347     eval "trap 'Exit $(expr $sig_ + 128)' $sig_"
348   done
349 }
350
351 # Create a temporary directory, much like mktemp -d does.
352 # Written by Jim Meyering.
353 #
354 # Usage: mktempd_ /tmp phoey.XXXXXXXXXX
355 #
356 # First, try to use the mktemp program.
357 # Failing that, we'll roll our own mktemp-like function:
358 #  - try to get random bytes from /dev/urandom
359 #  - failing that, generate output from a combination of quickly-varying
360 #      sources and gzip.  Ignore non-varying gzip header, and extract
361 #      "random" bits from there.
362 #  - given those bits, map to file-name bytes using tr, and try to create
363 #      the desired directory.
364 #  - make only $MAX_TRIES_ attempts
365
366 # Helper function.  Print $N pseudo-random bytes from a-zA-Z0-9.
367 rand_bytes_()
368 {
369   n_=$1
370
371   # Maybe try openssl rand -base64 $n_prime_|tr '+/=\012' abcd first?
372   # But if they have openssl, they probably have mktemp, too.
373
374   chars_=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
375   dev_rand_=/dev/urandom
376   if test -r "$dev_rand_"; then
377     # Note: 256-length($chars_) == 194; 3 copies of $chars_ is 186 + 8 = 194.
378     dd ibs=$n_ count=1 if=$dev_rand_ 2>/dev/null \
379       | LC_ALL=C tr -c $chars_ 01234567$chars_$chars_$chars_
380     return
381   fi
382
383   n_plus_50_=`expr $n_ + 50`
384   cmds_='date; date +%N; free; who -a; w; ps auxww; ps ef; netstat -n'
385   data_=` (eval "$cmds_") 2>&1 | gzip `
386
387   # Ensure that $data_ has length at least 50+$n_
388   while :; do
389     len_=`echo "$data_"|wc -c`
390     test $n_plus_50_ -le $len_ && break;
391     data_=` (echo "$data_"; eval "$cmds_") 2>&1 | gzip `
392   done
393
394   echo "$data_" \
395     | dd bs=1 skip=50 count=$n_ 2>/dev/null \
396     | LC_ALL=C tr -c $chars_ 01234567$chars_$chars_$chars_
397 }
398
399 mktempd_()
400 {
401   case $# in
402   2);;
403   *) fail_ "Usage: $ME DIR TEMPLATE";;
404   esac
405
406   destdir_=$1
407   template_=$2
408
409   MAX_TRIES_=4
410
411   # Disallow any trailing slash on specified destdir:
412   # it would subvert the post-mktemp "case"-based destdir test.
413   case $destdir_ in
414   /) ;;
415   */) fail_ "invalid destination dir: remove trailing slash(es)";;
416   esac
417
418   case $template_ in
419   *XXXX) ;;
420   *) fail_ \
421        "invalid template: $template_ (must have a suffix of at least 4 X's)";;
422   esac
423
424   # First, try to use mktemp.
425   d=`unset TMPDIR; mktemp -d -t -p "$destdir_" "$template_" 2>/dev/null` \
426     || fail=1
427
428   # The resulting name must be in the specified directory.
429   case $d in "$destdir_"*);; *) fail=1;; esac
430
431   # It must have created the directory.
432   test -d "$d" || fail=1
433
434   # It must have 0700 permissions.  Handle sticky "S" bits.
435   perms=`ls -dgo "$d" 2>/dev/null|tr S -` || fail=1
436   case $perms in drwx------*) ;; *) fail=1;; esac
437
438   test $fail = 0 && {
439     echo "$d"
440     return
441   }
442
443   # If we reach this point, we'll have to create a directory manually.
444
445   # Get a copy of the template without its suffix of X's.
446   base_template_=`echo "$template_"|sed 's/XX*$//'`
447
448   # Calculate how many X's we've just removed.
449   template_length_=`echo "$template_" | wc -c`
450   nx_=`echo "$base_template_" | wc -c`
451   nx_=`expr $template_length_ - $nx_`
452
453   err_=
454   i_=1
455   while :; do
456     X_=`rand_bytes_ $nx_`
457     candidate_dir_="$destdir_/$base_template_$X_"
458     err_=`mkdir -m 0700 "$candidate_dir_" 2>&1` \
459       && { echo "$candidate_dir_"; return; }
460     test $MAX_TRIES_ -le $i_ && break;
461     i_=`expr $i_ + 1`
462   done
463   fail_ "$err_"
464 }
465
466 # If you want to override the testdir_prefix_ function,
467 # or to add more utility functions, use this file.
468 test -f "$srcdir/init.cfg" \
469   && . "$srcdir/init.cfg"
470
471 setup_ "$@"
472 # This trap is here, rather than in the setup_ function, because some
473 # shells run the exit trap at shell function exit, rather than script exit.
474 trap remove_tmp_ 0