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