470605c116631af8d1950d6615f63e53e93d5416
[debian/gzip] / tests / init.sh
1 # source this file; set up for tests
2
3 # Copyright (C) 2009-2017 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 <https://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, keeping the temporary directory:
49 #   $ make check TESTS=test-foo.sh KEEP=yes
50 #
51 # Running a single test, with single-stepping:
52 #   1. Go into a sub-shell:
53 #   $ bash
54 #   2. Set relevant environment variables from TESTS_ENVIRONMENT in the
55 #      Makefile:
56 #   $ export srcdir=../../tests # this is an example
57 #   3. Execute the commands from the test, copy&pasting them one by one:
58 #   $ . "$srcdir/init.sh"; path_prepend_ .
59 #   ...
60 #   4. Finally
61 #   $ exit
62
63 ME_=`expr "./$0" : '.*/\(.*\)$'`
64
65 # We use a trap below for cleanup.  This requires us to go through
66 # hoops to get the right exit status transported through the handler.
67 # So use 'Exit STATUS' instead of 'exit STATUS' inside of the tests.
68 # Turn off errexit here so that we don't trip the bug with OSF1/Tru64
69 # sh inside this function.
70 Exit () { set +e; (exit $1); exit $1; }
71
72 # Print warnings (e.g., about skipped and failed tests) to this file number.
73 # Override by defining to say, 9, in init.cfg, and putting say,
74 #   export ...ENVVAR_SETTINGS...; $(SHELL) 9>&2
75 # in the definition of TESTS_ENVIRONMENT in your tests/Makefile.am file.
76 # This is useful when using automake's parallel tests mode, to print
77 # the reason for skip/failure to console, rather than to the .log files.
78 : ${stderr_fileno_=2}
79
80 # Note that correct expansion of "$*" depends on IFS starting with ' '.
81 # Always write the full diagnostic to stderr.
82 # When stderr_fileno_ is not 2, also emit the first line of the
83 # diagnostic to that file descriptor.
84 warn_ ()
85 {
86   # If IFS does not start with ' ', set it and emit the warning in a subshell.
87   case $IFS in
88     ' '*) printf '%s\n' "$*" >&2
89           test $stderr_fileno_ = 2 \
90             || { printf '%s\n' "$*" | sed 1q >&$stderr_fileno_ ; } ;;
91     *) (IFS=' '; warn_ "$@");;
92   esac
93 }
94 fail_ () { warn_ "$ME_: failed test: $@"; Exit 1; }
95 skip_ () { warn_ "$ME_: skipped test: $@"; Exit 77; }
96 fatal_ () { warn_ "$ME_: hard error: $@"; Exit 99; }
97 framework_failure_ () { warn_ "$ME_: set-up failure: $@"; Exit 99; }
98
99 # This is used to simplify checking of the return value
100 # which is useful when ensuring a command fails as desired.
101 # I.e., just doing `command ... &&fail=1` will not catch
102 # a segfault in command for example.  With this helper you
103 # instead check an explicit exit code like
104 #   returns_ 1 command ... || fail
105 returns_ () {
106   # Disable tracing so it doesn't interfere with stderr of the wrapped command
107   { set +x; } 2>/dev/null
108
109   local exp_exit="$1"
110   shift
111   "$@"
112   test $? -eq $exp_exit && ret_=0 || ret_=1
113
114   if test "$VERBOSE" = yes && test "$gl_set_x_corrupts_stderr_" = false; then
115     set -x
116   fi
117   { return $ret_; } 2>/dev/null
118 }
119
120 # Sanitize this shell to POSIX mode, if possible.
121 DUALCASE=1; export DUALCASE
122 if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
123   emulate sh
124   NULLCMD=:
125   alias -g '${1+"$@"}'='"$@"'
126   setopt NO_GLOB_SUBST
127 else
128   case `(set -o) 2>/dev/null` in
129     *posix*) set -o posix ;;
130   esac
131 fi
132
133 # We require $(...) support unconditionally.
134 # We require non-surprising "local" semantics (this eliminates dash).
135 # This takes the admittedly draconian step of eliminating dash, because the
136 # assignment tab=$(printf '\t') works fine, yet preceding it with "local "
137 # transforms it into an assignment that sets the variable to the empty string.
138 # That is too counter-intuitive, and can lead to subtle run-time malfunction.
139 # The example below is less subtle in that with dash, it evokes the run-time
140 # exception "dash: 1: local: 1: bad variable name".
141 # We require a few additional shell features only when $EXEEXT is nonempty,
142 # in order to support automatic $EXEEXT emulation:
143 # - hyphen-containing alias names
144 # - we prefer to use ${var#...} substitution, rather than having
145 #   to work around lack of support for that feature.
146 # The following code attempts to find a shell with support for these features.
147 # If the current shell passes the test, we're done.  Otherwise, test other
148 # shells until we find one that passes.  If one is found, re-exec it.
149 # If no acceptable shell is found, skip the current test.
150 #
151 # The "...set -x; P=1 true 2>err..." test is to disqualify any shell that
152 # emits "P=1" into err, as /bin/sh from SunOS 5.11 and OpenBSD 4.7 do.
153 #
154 # Use "9" to indicate success (rather than 0), in case some shell acts
155 # like Solaris 10's /bin/sh but exits successfully instead of with status 2.
156
157 # Eval this code in a subshell to determine a shell's suitability.
158 # 10 - passes all tests; ok to use
159 #  9 - ok, but enabling "set -x" corrupts app stderr; prefer higher score
160 #  ? - not ok
161 gl_shell_test_script_='
162 test $(echo y) = y || exit 1
163 f_local_() { local v=1; }; f_local_ || exit 1
164 f_dash_local_fail_() { local t=$(printf " 1"); }; f_dash_local_fail_
165 score_=10
166 if test "$VERBOSE" = yes; then
167   test -n "$( (exec 3>&1; set -x; P=1 true 2>&3) 2> /dev/null)" && score_=9
168 fi
169 test -z "$EXEEXT" && exit $score_
170 shopt -s expand_aliases
171 alias a-b="echo zoo"
172 v=abx
173      test ${v%x} = ab \
174   && test ${v#a} = bx \
175   && test $(a-b) = zoo \
176   && exit $score_
177 '
178
179 if test "x$1" = "x--no-reexec"; then
180   shift
181 else
182   # Assume a working shell.  Export to subshells (setup_ needs this).
183   gl_set_x_corrupts_stderr_=false
184   export gl_set_x_corrupts_stderr_
185
186   # Record the first marginally acceptable shell.
187   marginal_=
188
189   # Search for a shell that meets our requirements.
190   for re_shell_ in __current__ "${CONFIG_SHELL:-no_shell}" \
191       /bin/sh bash dash zsh pdksh fail
192   do
193     test "$re_shell_" = no_shell && continue
194
195     # If we've made it all the way to the sentinel, "fail" without
196     # finding even a marginal shell, skip this test.
197     if test "$re_shell_" = fail; then
198       test -z "$marginal_" && skip_ failed to find an adequate shell
199       re_shell_=$marginal_
200       break
201     fi
202
203     # When testing the current shell, simply "eval" the test code.
204     # Otherwise, run it via $re_shell_ -c ...
205     if test "$re_shell_" = __current__; then
206       # 'eval'ing this code makes Solaris 10's /bin/sh exit with
207       # $? set to 2.  It does not evaluate any of the code after the
208       # "unexpected" first '('.  Thus, we must run it in a subshell.
209       ( eval "$gl_shell_test_script_" ) > /dev/null 2>&1
210     else
211       "$re_shell_" -c "$gl_shell_test_script_" 2>/dev/null
212     fi
213
214     st_=$?
215
216     # $re_shell_ works just fine.  Use it.
217     if test $st_ = 10; then
218       gl_set_x_corrupts_stderr_=false
219       break
220     fi
221
222     # If this is our first marginally acceptable shell, remember it.
223     if test "$st_:$marginal_" = 9: ; then
224       marginal_="$re_shell_"
225       gl_set_x_corrupts_stderr_=true
226     fi
227   done
228
229   if test "$re_shell_" != __current__; then
230     # Found a usable shell.  Preserve -v and -x.
231     case $- in
232       *v*x* | *x*v*) opts_=-vx ;;
233       *v*) opts_=-v ;;
234       *x*) opts_=-x ;;
235       *) opts_= ;;
236     esac
237     re_shell=$re_shell_
238     export re_shell
239     exec "$re_shell_" $opts_ "$0" --no-reexec "$@"
240     echo "$ME_: exec failed" 1>&2
241     exit 127
242   fi
243 fi
244
245 # If this is bash, turn off all aliases.
246 test -n "$BASH_VERSION" && unalias -a
247
248 # Note that when supporting $EXEEXT (transparently mapping from PROG_NAME to
249 # PROG_NAME.exe), we want to support hyphen-containing names like test-acos.
250 # That is part of the shell-selection test above.  Why use aliases rather
251 # than functions?  Because support for hyphen-containing aliases is more
252 # widespread than that for hyphen-containing function names.
253 test -n "$EXEEXT" && shopt -s expand_aliases
254
255 # Enable glibc's malloc-perturbing option.
256 # This is useful for exposing code that depends on the fact that
257 # malloc-related functions often return memory that is mostly zeroed.
258 # If you have the time and cycles, use valgrind to do an even better job.
259 : ${MALLOC_PERTURB_=87}
260 export MALLOC_PERTURB_
261
262 # This is a stub function that is run upon trap (upon regular exit and
263 # interrupt).  Override it with a per-test function, e.g., to unmount
264 # a partition, or to undo any other global state changes.
265 cleanup_ () { :; }
266
267 # Emit a header similar to that from diff -u;  Print the simulated "diff"
268 # command so that the order of arguments is clear.  Don't bother with @@ lines.
269 emit_diff_u_header_ ()
270 {
271   printf '%s\n' "diff -u $*" \
272     "--- $1     1970-01-01" \
273     "+++ $2     1970-01-01"
274 }
275
276 # Arrange not to let diff or cmp operate on /dev/null,
277 # since on some systems (at least OSF/1 5.1), that doesn't work.
278 # When there are not two arguments, or no argument is /dev/null, return 2.
279 # When one argument is /dev/null and the other is not empty,
280 # cat the nonempty file to stderr and return 1.
281 # Otherwise, return 0.
282 compare_dev_null_ ()
283 {
284   test $# = 2 || return 2
285
286   if test "x$1" = x/dev/null; then
287     test -s "$2" || return 0
288     emit_diff_u_header_ "$@"; sed 's/^/+/' "$2"
289     return 1
290   fi
291
292   if test "x$2" = x/dev/null; then
293     test -s "$1" || return 0
294     emit_diff_u_header_ "$@"; sed 's/^/-/' "$1"
295     return 1
296   fi
297
298   return 2
299 }
300
301 for diff_opt_ in -u -U3 -c '' no; do
302   test "$diff_opt_" != no &&
303     diff_out_=`exec 2>/dev/null; diff $diff_opt_ "$0" "$0" < /dev/null` &&
304     break
305 done
306 if test "$diff_opt_" != no; then
307   if test -z "$diff_out_"; then
308     compare_ () { diff $diff_opt_ "$@"; }
309   else
310     compare_ ()
311     {
312       # If no differences were found, AIX and HP-UX 'diff' produce output
313       # like "No differences encountered".  Hide this output.
314       diff $diff_opt_ "$@" > diff.out
315       diff_status_=$?
316       test $diff_status_ -eq 0 || cat diff.out || diff_status_=2
317       rm -f diff.out || diff_status_=2
318       return $diff_status_
319     }
320   fi
321 elif cmp -s /dev/null /dev/null 2>/dev/null; then
322   compare_ () { cmp -s "$@"; }
323 else
324   compare_ () { cmp "$@"; }
325 fi
326
327 # Usage: compare EXPECTED ACTUAL
328 #
329 # Given compare_dev_null_'s preprocessing, defer to compare_ if 2 or more.
330 # Otherwise, propagate $? to caller: any diffs have already been printed.
331 compare ()
332 {
333   # This looks like it can be factored to use a simple "case $?"
334   # after unchecked compare_dev_null_ invocation, but that would
335   # fail in a "set -e" environment.
336   if compare_dev_null_ "$@"; then
337     return 0
338   else
339     case $? in
340       1) return 1;;
341       *) compare_ "$@";;
342     esac
343   fi
344 }
345
346 # An arbitrary prefix to help distinguish test directories.
347 testdir_prefix_ () { printf gt; }
348
349 # Run the user-overridable cleanup_ function, remove the temporary
350 # directory and exit with the incoming value of $?.
351 remove_tmp_ ()
352 {
353   __st=$?
354   cleanup_
355   if test "$KEEP" = yes; then
356     echo "Not removing temporary directory $test_dir_"
357   else
358     # cd out of the directory we're about to remove
359     cd "$initial_cwd_" || cd / || cd /tmp
360     chmod -R u+rwx "$test_dir_"
361     # If removal fails and exit status was to be 0, then change it to 1.
362     rm -rf "$test_dir_" || { test $__st = 0 && __st=1; }
363   fi
364   exit $__st
365 }
366
367 # Given a directory name, DIR, if every entry in it that matches *.exe
368 # contains only the specified bytes (see the case stmt below), then print
369 # a space-separated list of those names and return 0.  Otherwise, don't
370 # print anything and return 1.  Naming constraints apply also to DIR.
371 find_exe_basenames_ ()
372 {
373   feb_dir_=$1
374   feb_fail_=0
375   feb_result_=
376   feb_sp_=
377   for feb_file_ in $feb_dir_/*.exe; do
378     # If there was no *.exe file, or there existed a file named "*.exe" that
379     # was deleted between the above glob expansion and the existence test
380     # below, just skip it.
381     test "x$feb_file_" = "x$feb_dir_/*.exe" && test ! -f "$feb_file_" \
382       && continue
383     # Exempt [.exe, since we can't create a function by that name, yet
384     # we can't invoke [ by PATH search anyways due to shell builtins.
385     test "x$feb_file_" = "x$feb_dir_/[.exe" && continue
386     case $feb_file_ in
387       *[!-a-zA-Z/0-9_.+]*) feb_fail_=1; break;;
388       *) # Remove leading file name components as well as the .exe suffix.
389          feb_file_=${feb_file_##*/}
390          feb_file_=${feb_file_%.exe}
391          feb_result_="$feb_result_$feb_sp_$feb_file_";;
392     esac
393     feb_sp_=' '
394   done
395   test $feb_fail_ = 0 && printf %s "$feb_result_"
396   return $feb_fail_
397 }
398
399 # Consider the files in directory, $1.
400 # For each file name of the form PROG.exe, create an alias named
401 # PROG that simply invokes PROG.exe, then return 0.  If any selected
402 # file name or the directory name, $1, contains an unexpected character,
403 # define no alias and return 1.
404 create_exe_shims_ ()
405 {
406   case $EXEEXT in
407     '') return 0 ;;
408     .exe) ;;
409     *) echo "$0: unexpected \$EXEEXT value: $EXEEXT" 1>&2; return 1 ;;
410   esac
411
412   base_names_=`find_exe_basenames_ $1` \
413     || { echo "$0 (exe_shim): skipping directory: $1" 1>&2; return 0; }
414
415   if test -n "$base_names_"; then
416     for base_ in $base_names_; do
417       alias "$base_"="$base_$EXEEXT"
418     done
419   fi
420
421   return 0
422 }
423
424 # Use this function to prepend to PATH an absolute name for each
425 # specified, possibly-$initial_cwd_-relative, directory.
426 path_prepend_ ()
427 {
428   while test $# != 0; do
429     path_dir_=$1
430     case $path_dir_ in
431       '') fail_ "invalid path dir: '$1'";;
432       /*) abs_path_dir_=$path_dir_;;
433       *) abs_path_dir_=$initial_cwd_/$path_dir_;;
434     esac
435     case $abs_path_dir_ in
436       *:*) fail_ "invalid path dir: '$abs_path_dir_'";;
437     esac
438     PATH="$abs_path_dir_:$PATH"
439
440     # Create an alias, FOO, for each FOO.exe in this directory.
441     create_exe_shims_ "$abs_path_dir_" \
442       || fail_ "something failed (above): $abs_path_dir_"
443     shift
444   done
445   export PATH
446 }
447
448 setup_ ()
449 {
450   if test "$VERBOSE" = yes; then
451     # Test whether set -x may cause the selected shell to corrupt an
452     # application's stderr.  Many do, including zsh-4.3.10 and the /bin/sh
453     # from SunOS 5.11, OpenBSD 4.7 and Irix 5.x and 6.5.
454     # If enabling verbose output this way would cause trouble, simply
455     # issue a warning and refrain.
456     if $gl_set_x_corrupts_stderr_; then
457       warn_ "using SHELL=$SHELL with 'set -x' corrupts stderr"
458     else
459       set -x
460     fi
461   fi
462
463   initial_cwd_=$PWD
464
465   pfx_=`testdir_prefix_`
466   test_dir_=`mktempd_ "$initial_cwd_" "$pfx_-$ME_.XXXX"` \
467     || fail_ "failed to create temporary directory in $initial_cwd_"
468   cd "$test_dir_" || fail_ "failed to cd to temporary directory"
469
470   # As autoconf-generated configure scripts do, ensure that IFS
471   # is defined initially, so that saving and restoring $IFS works.
472   gl_init_sh_nl_='
473 '
474   IFS=" ""      $gl_init_sh_nl_"
475
476   # This trap statement, along with a trap on 0 below, ensure that the
477   # temporary directory, $test_dir_, is removed upon exit as well as
478   # upon receipt of any of the listed signals.
479   for sig_ in 1 2 3 13 15; do
480     eval "trap 'Exit $(expr $sig_ + 128)' $sig_"
481   done
482 }
483
484 # Create a temporary directory, much like mktemp -d does.
485 # Written by Jim Meyering.
486 #
487 # Usage: mktempd_ /tmp phoey.XXXXXXXXXX
488 #
489 # First, try to use the mktemp program.
490 # Failing that, we'll roll our own mktemp-like function:
491 #  - try to get random bytes from /dev/urandom
492 #  - failing that, generate output from a combination of quickly-varying
493 #      sources and gzip.  Ignore non-varying gzip header, and extract
494 #      "random" bits from there.
495 #  - given those bits, map to file-name bytes using tr, and try to create
496 #      the desired directory.
497 #  - make only $MAX_TRIES_ attempts
498
499 # Helper function.  Print $N pseudo-random bytes from a-zA-Z0-9.
500 rand_bytes_ ()
501 {
502   n_=$1
503
504   # Maybe try openssl rand -base64 $n_prime_|tr '+/=\012' abcd first?
505   # But if they have openssl, they probably have mktemp, too.
506
507   chars_=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
508   dev_rand_=/dev/urandom
509   if test -r "$dev_rand_"; then
510     # Note: 256-length($chars_) == 194; 3 copies of $chars_ is 186 + 8 = 194.
511     dd ibs=$n_ count=1 if=$dev_rand_ 2>/dev/null \
512       | LC_ALL=C tr -c $chars_ 01234567$chars_$chars_$chars_
513     return
514   fi
515
516   n_plus_50_=`expr $n_ + 50`
517   cmds_='date; date +%N; free; who -a; w; ps auxww; ps ef; netstat -n'
518   data_=` (eval "$cmds_") 2>&1 | gzip `
519
520   # Ensure that $data_ has length at least 50+$n_
521   while :; do
522     len_=`echo "$data_"|wc -c`
523     test $n_plus_50_ -le $len_ && break;
524     data_=` (echo "$data_"; eval "$cmds_") 2>&1 | gzip `
525   done
526
527   echo "$data_" \
528     | dd bs=1 skip=50 count=$n_ 2>/dev/null \
529     | LC_ALL=C tr -c $chars_ 01234567$chars_$chars_$chars_
530 }
531
532 mktempd_ ()
533 {
534   case $# in
535   2);;
536   *) fail_ "Usage: mktempd_ DIR TEMPLATE";;
537   esac
538
539   destdir_=$1
540   template_=$2
541
542   MAX_TRIES_=4
543
544   # Disallow any trailing slash on specified destdir:
545   # it would subvert the post-mktemp "case"-based destdir test.
546   case $destdir_ in
547   / | //) destdir_slash_=$destdir;;
548   */) fail_ "invalid destination dir: remove trailing slash(es)";;
549   *) destdir_slash_=$destdir_/;;
550   esac
551
552   case $template_ in
553   *XXXX) ;;
554   *) fail_ \
555        "invalid template: $template_ (must have a suffix of at least 4 X's)";;
556   esac
557
558   # First, try to use mktemp.
559   d=`unset TMPDIR; { mktemp -d -t -p "$destdir_" "$template_"; } 2>/dev/null` &&
560
561   # The resulting name must be in the specified directory.
562   case $d in "$destdir_slash_"*) :;; *) false;; esac &&
563
564   # It must have created the directory.
565   test -d "$d" &&
566
567   # It must have 0700 permissions.  Handle sticky "S" bits.
568   perms=`ls -dgo "$d" 2>/dev/null` &&
569   case $perms in drwx--[-S]---*) :;; *) false;; esac && {
570     echo "$d"
571     return
572   }
573
574   # If we reach this point, we'll have to create a directory manually.
575
576   # Get a copy of the template without its suffix of X's.
577   base_template_=`echo "$template_"|sed 's/XX*$//'`
578
579   # Calculate how many X's we've just removed.
580   template_length_=`echo "$template_" | wc -c`
581   nx_=`echo "$base_template_" | wc -c`
582   nx_=`expr $template_length_ - $nx_`
583
584   err_=
585   i_=1
586   while :; do
587     X_=`rand_bytes_ $nx_`
588     candidate_dir_="$destdir_slash_$base_template_$X_"
589     err_=`mkdir -m 0700 "$candidate_dir_" 2>&1` \
590       && { echo "$candidate_dir_"; return; }
591     test $MAX_TRIES_ -le $i_ && break;
592     i_=`expr $i_ + 1`
593   done
594   fail_ "$err_"
595 }
596
597 # If you want to override the testdir_prefix_ function,
598 # or to add more utility functions, use this file.
599 test -f "$srcdir/init.cfg" \
600   && . "$srcdir/init.cfg"
601
602 setup_ "$@"
603 # This trap is here, rather than in the setup_ function, because some
604 # shells run the exit trap at shell function exit, rather than script exit.
605 trap remove_tmp_ 0