]> git.ipfire.org Git - thirdparty/git.git/blob - t/test-lib-functions.sh
Merge branch 'ab/make-optim-noop'
[thirdparty/git.git] / t / test-lib-functions.sh
1 # Library of functions shared by all tests scripts, included by
2 # test-lib.sh.
3 #
4 # Copyright (c) 2005 Junio C Hamano
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see http://www.gnu.org/licenses/ .
18
19 # The semantics of the editor variables are that of invoking
20 # sh -c "$EDITOR \"$@\"" files ...
21 #
22 # If our trash directory contains shell metacharacters, they will be
23 # interpreted if we just set $EDITOR directly, so do a little dance with
24 # environment variables to work around this.
25 #
26 # In particular, quoting isn't enough, as the path may contain the same quote
27 # that we're using.
28 test_set_editor () {
29 FAKE_EDITOR="$1"
30 export FAKE_EDITOR
31 EDITOR='"$FAKE_EDITOR"'
32 export EDITOR
33 }
34
35 test_decode_color () {
36 awk '
37 function name(n) {
38 if (n == 0) return "RESET";
39 if (n == 1) return "BOLD";
40 if (n == 2) return "FAINT";
41 if (n == 3) return "ITALIC";
42 if (n == 7) return "REVERSE";
43 if (n == 30) return "BLACK";
44 if (n == 31) return "RED";
45 if (n == 32) return "GREEN";
46 if (n == 33) return "YELLOW";
47 if (n == 34) return "BLUE";
48 if (n == 35) return "MAGENTA";
49 if (n == 36) return "CYAN";
50 if (n == 37) return "WHITE";
51 if (n == 40) return "BLACK";
52 if (n == 41) return "BRED";
53 if (n == 42) return "BGREEN";
54 if (n == 43) return "BYELLOW";
55 if (n == 44) return "BBLUE";
56 if (n == 45) return "BMAGENTA";
57 if (n == 46) return "BCYAN";
58 if (n == 47) return "BWHITE";
59 }
60 {
61 while (match($0, /\033\[[0-9;]*m/) != 0) {
62 printf "%s<", substr($0, 1, RSTART-1);
63 codes = substr($0, RSTART+2, RLENGTH-3);
64 if (length(codes) == 0)
65 printf "%s", name(0)
66 else {
67 n = split(codes, ary, ";");
68 sep = "";
69 for (i = 1; i <= n; i++) {
70 printf "%s%s", sep, name(ary[i]);
71 sep = ";"
72 }
73 }
74 printf ">";
75 $0 = substr($0, RSTART + RLENGTH, length($0) - RSTART - RLENGTH + 1);
76 }
77 print
78 }
79 '
80 }
81
82 lf_to_nul () {
83 perl -pe 'y/\012/\000/'
84 }
85
86 nul_to_q () {
87 perl -pe 'y/\000/Q/'
88 }
89
90 q_to_nul () {
91 perl -pe 'y/Q/\000/'
92 }
93
94 q_to_cr () {
95 tr Q '\015'
96 }
97
98 q_to_tab () {
99 tr Q '\011'
100 }
101
102 qz_to_tab_space () {
103 tr QZ '\011\040'
104 }
105
106 append_cr () {
107 sed -e 's/$/Q/' | tr Q '\015'
108 }
109
110 remove_cr () {
111 tr '\015' Q | sed -e 's/Q$//'
112 }
113
114 # In some bourne shell implementations, the "unset" builtin returns
115 # nonzero status when a variable to be unset was not set in the first
116 # place.
117 #
118 # Use sane_unset when that should not be considered an error.
119
120 sane_unset () {
121 unset "$@"
122 return 0
123 }
124
125 test_tick () {
126 if test -z "${test_tick+set}"
127 then
128 test_tick=1112911993
129 else
130 test_tick=$(($test_tick + 60))
131 fi
132 GIT_COMMITTER_DATE="$test_tick -0700"
133 GIT_AUTHOR_DATE="$test_tick -0700"
134 export GIT_COMMITTER_DATE GIT_AUTHOR_DATE
135 }
136
137 # Stop execution and start a shell. This is useful for debugging tests.
138 #
139 # Be sure to remove all invocations of this command before submitting.
140 # WARNING: the shell invoked by this helper does not have the same environment
141 # as the one running the tests (shell variables and functions are not
142 # available, and the options below further modify the environment). As such,
143 # commands copied from a test script might behave differently than when
144 # running the test.
145 #
146 # Usage: test_pause [options]
147 # -t
148 # Use your original TERM instead of test-lib.sh's "dumb".
149 # This usually restores color output in the invoked shell.
150 # -s
151 # Invoke $SHELL instead of $TEST_SHELL_PATH.
152 # -h
153 # Use your original HOME instead of test-lib.sh's "$TRASH_DIRECTORY".
154 # This allows you to use your regular shell environment and Git aliases.
155 # CAUTION: running commands copied from a test script into the paused shell
156 # might result in files in your HOME being overwritten.
157 # -a
158 # Shortcut for -t -s -h
159
160 test_pause () {
161 PAUSE_TERM=$TERM &&
162 PAUSE_SHELL=$TEST_SHELL_PATH &&
163 PAUSE_HOME=$HOME &&
164 while test $# != 0
165 do
166 case "$1" in
167 -t)
168 PAUSE_TERM="$USER_TERM"
169 ;;
170 -s)
171 PAUSE_SHELL="$SHELL"
172 ;;
173 -h)
174 PAUSE_HOME="$USER_HOME"
175 ;;
176 -a)
177 PAUSE_TERM="$USER_TERM"
178 PAUSE_SHELL="$SHELL"
179 PAUSE_HOME="$USER_HOME"
180 ;;
181 *)
182 break
183 ;;
184 esac
185 shift
186 done &&
187 TERM="$PAUSE_TERM" HOME="$PAUSE_HOME" "$PAUSE_SHELL" <&6 >&5 2>&7
188 }
189
190 # Wrap git with a debugger. Adding this to a command can make it easier
191 # to understand what is going on in a failing test.
192 #
193 # Usage: debug [options] <git command>
194 # -d <debugger>
195 # --debugger=<debugger>
196 # Use <debugger> instead of GDB
197 # -t
198 # Use your original TERM instead of test-lib.sh's "dumb".
199 # This usually restores color output in the debugger.
200 # WARNING: the command being debugged might behave differently than when
201 # running the test.
202 #
203 # Examples:
204 # debug git checkout master
205 # debug --debugger=nemiver git $ARGS
206 # debug -d "valgrind --tool=memcheck --track-origins=yes" git $ARGS
207 debug () {
208 GIT_DEBUGGER=1 &&
209 DEBUG_TERM=$TERM &&
210 while test $# != 0
211 do
212 case "$1" in
213 -t)
214 DEBUG_TERM="$USER_TERM"
215 ;;
216 -d)
217 GIT_DEBUGGER="$2" &&
218 shift
219 ;;
220 --debugger=*)
221 GIT_DEBUGGER="${1#*=}"
222 ;;
223 *)
224 break
225 ;;
226 esac
227 shift
228 done &&
229
230 dotfiles=".gdbinit .lldbinit"
231
232 for dotfile in $dotfiles
233 do
234 dotfile="$USER_HOME/$dotfile" &&
235 test -f "$dotfile" && cp "$dotfile" "$HOME" || :
236 done &&
237
238 TERM="$DEBUG_TERM" GIT_DEBUGGER="${GIT_DEBUGGER}" "$@" <&6 >&5 2>&7 &&
239
240 for dotfile in $dotfiles
241 do
242 rm -f "$HOME/$dotfile"
243 done
244 }
245
246 # Usage: test_commit [options] <message> [<file> [<contents> [<tag>]]]
247 # -C <dir>:
248 # Run all git commands in directory <dir>
249 # --notick
250 # Do not call test_tick before making a commit
251 # --append
252 # Use ">>" instead of ">" when writing "<contents>" to "<file>"
253 # --printf
254 # Use "printf" instead of "echo" when writing "<contents>" to
255 # "<file>", use this to write escape sequences such as "\0", a
256 # trailing "\n" won't be added automatically. This option
257 # supports nothing but the FORMAT of printf(1), i.e. no custom
258 # ARGUMENT(s).
259 # --signoff
260 # Invoke "git commit" with --signoff
261 # --author <author>
262 # Invoke "git commit" with --author <author>
263 # --no-tag
264 # Do not tag the resulting commit
265 # --annotate
266 # Create an annotated tag with "--annotate -m <message>". Calls
267 # test_tick between making the commit and tag, unless --notick
268 # is given.
269 #
270 # This will commit a file with the given contents and the given commit
271 # message, and tag the resulting commit with the given tag name.
272 #
273 # <file>, <contents>, and <tag> all default to <message>.
274
275 test_commit () {
276 notick= &&
277 echo=echo &&
278 append= &&
279 author= &&
280 signoff= &&
281 indir= &&
282 tag=light &&
283 while test $# != 0
284 do
285 case "$1" in
286 --notick)
287 notick=yes
288 ;;
289 --printf)
290 echo=printf
291 ;;
292 --append)
293 append=yes
294 ;;
295 --author)
296 author="$2"
297 shift
298 ;;
299 --signoff)
300 signoff="$1"
301 ;;
302 --date)
303 notick=yes
304 GIT_COMMITTER_DATE="$2"
305 GIT_AUTHOR_DATE="$2"
306 shift
307 ;;
308 -C)
309 indir="$2"
310 shift
311 ;;
312 --no-tag)
313 tag=none
314 ;;
315 --annotate)
316 tag=annotate
317 ;;
318 *)
319 break
320 ;;
321 esac
322 shift
323 done &&
324 indir=${indir:+"$indir"/} &&
325 file=${2:-"$1.t"} &&
326 if test -n "$append"
327 then
328 $echo "${3-$1}" >>"$indir$file"
329 else
330 $echo "${3-$1}" >"$indir$file"
331 fi &&
332 git ${indir:+ -C "$indir"} add "$file" &&
333 if test -z "$notick"
334 then
335 test_tick
336 fi &&
337 git ${indir:+ -C "$indir"} commit \
338 ${author:+ --author "$author"} \
339 $signoff -m "$1" &&
340 case "$tag" in
341 none)
342 ;;
343 light)
344 git ${indir:+ -C "$indir"} tag "${4:-$1}"
345 ;;
346 annotate)
347 if test -z "$notick"
348 then
349 test_tick
350 fi &&
351 git ${indir:+ -C "$indir"} tag -a -m "$1" "${4:-$1}"
352 ;;
353 esac
354 }
355
356 # Call test_merge with the arguments "<message> <commit>", where <commit>
357 # can be a tag pointing to the commit-to-merge.
358
359 test_merge () {
360 label="$1" &&
361 shift &&
362 test_tick &&
363 git merge -m "$label" "$@" &&
364 git tag "$label"
365 }
366
367 # Efficiently create <nr> commits, each with a unique number (from 1 to <nr>
368 # by default) in the commit message.
369 #
370 # Usage: test_commit_bulk [options] <nr>
371 # -C <dir>:
372 # Run all git commands in directory <dir>
373 # --ref=<n>:
374 # ref on which to create commits (default: HEAD)
375 # --start=<n>:
376 # number commit messages from <n> (default: 1)
377 # --message=<msg>:
378 # use <msg> as the commit mesasge (default: "commit %s")
379 # --filename=<fn>:
380 # modify <fn> in each commit (default: %s.t)
381 # --contents=<string>:
382 # place <string> in each file (default: "content %s")
383 # --id=<string>:
384 # shorthand to use <string> and %s in message, filename, and contents
385 #
386 # The message, filename, and contents strings are evaluated by printf, with the
387 # first "%s" replaced by the current commit number. So you can do:
388 #
389 # test_commit_bulk --filename=file --contents="modification %s"
390 #
391 # to have every commit touch the same file, but with unique content.
392 #
393 test_commit_bulk () {
394 tmpfile=.bulk-commit.input
395 indir=.
396 ref=HEAD
397 n=1
398 message='commit %s'
399 filename='%s.t'
400 contents='content %s'
401 while test $# -gt 0
402 do
403 case "$1" in
404 -C)
405 indir=$2
406 shift
407 ;;
408 --ref=*)
409 ref=${1#--*=}
410 ;;
411 --start=*)
412 n=${1#--*=}
413 ;;
414 --message=*)
415 message=${1#--*=}
416 ;;
417 --filename=*)
418 filename=${1#--*=}
419 ;;
420 --contents=*)
421 contents=${1#--*=}
422 ;;
423 --id=*)
424 message="${1#--*=} %s"
425 filename="${1#--*=}-%s.t"
426 contents="${1#--*=} %s"
427 ;;
428 -*)
429 BUG "invalid test_commit_bulk option: $1"
430 ;;
431 *)
432 break
433 ;;
434 esac
435 shift
436 done
437 total=$1
438
439 add_from=
440 if git -C "$indir" rev-parse --quiet --verify "$ref"
441 then
442 add_from=t
443 fi
444
445 while test "$total" -gt 0
446 do
447 test_tick &&
448 echo "commit $ref"
449 printf 'author %s <%s> %s\n' \
450 "$GIT_AUTHOR_NAME" \
451 "$GIT_AUTHOR_EMAIL" \
452 "$GIT_AUTHOR_DATE"
453 printf 'committer %s <%s> %s\n' \
454 "$GIT_COMMITTER_NAME" \
455 "$GIT_COMMITTER_EMAIL" \
456 "$GIT_COMMITTER_DATE"
457 echo "data <<EOF"
458 printf "$message\n" $n
459 echo "EOF"
460 if test -n "$add_from"
461 then
462 echo "from $ref^0"
463 add_from=
464 fi
465 printf "M 644 inline $filename\n" $n
466 echo "data <<EOF"
467 printf "$contents\n" $n
468 echo "EOF"
469 echo
470 n=$((n + 1))
471 total=$((total - 1))
472 done >"$tmpfile"
473
474 git -C "$indir" \
475 -c fastimport.unpacklimit=0 \
476 fast-import <"$tmpfile" || return 1
477
478 # This will be left in place on failure, which may aid debugging.
479 rm -f "$tmpfile"
480
481 # If we updated HEAD, then be nice and update the index and working
482 # tree, too.
483 if test "$ref" = "HEAD"
484 then
485 git -C "$indir" checkout -f HEAD || return 1
486 fi
487
488 }
489
490 # This function helps systems where core.filemode=false is set.
491 # Use it instead of plain 'chmod +x' to set or unset the executable bit
492 # of a file in the working directory and add it to the index.
493
494 test_chmod () {
495 chmod "$@" &&
496 git update-index --add "--chmod=$@"
497 }
498
499 # Get the modebits from a file or directory, ignoring the setgid bit (g+s).
500 # This bit is inherited by subdirectories at their creation. So we remove it
501 # from the returning string to prevent callers from having to worry about the
502 # state of the bit in the test directory.
503 #
504 test_modebits () {
505 ls -ld "$1" | sed -e 's|^\(..........\).*|\1|' \
506 -e 's|^\(......\)S|\1-|' -e 's|^\(......\)s|\1x|'
507 }
508
509 # Unset a configuration variable, but don't fail if it doesn't exist.
510 test_unconfig () {
511 config_dir=
512 if test "$1" = -C
513 then
514 shift
515 config_dir=$1
516 shift
517 fi
518 git ${config_dir:+-C "$config_dir"} config --unset-all "$@"
519 config_status=$?
520 case "$config_status" in
521 5) # ok, nothing to unset
522 config_status=0
523 ;;
524 esac
525 return $config_status
526 }
527
528 # Set git config, automatically unsetting it after the test is over.
529 test_config () {
530 config_dir=
531 if test "$1" = -C
532 then
533 shift
534 config_dir=$1
535 shift
536 fi
537 test_when_finished "test_unconfig ${config_dir:+-C '$config_dir'} '$1'" &&
538 git ${config_dir:+-C "$config_dir"} config "$@"
539 }
540
541 test_config_global () {
542 test_when_finished "test_unconfig --global '$1'" &&
543 git config --global "$@"
544 }
545
546 write_script () {
547 {
548 echo "#!${2-"$SHELL_PATH"}" &&
549 cat
550 } >"$1" &&
551 chmod +x "$1"
552 }
553
554 # Use test_set_prereq to tell that a particular prerequisite is available.
555 # The prerequisite can later be checked for in two ways:
556 #
557 # - Explicitly using test_have_prereq.
558 #
559 # - Implicitly by specifying the prerequisite tag in the calls to
560 # test_expect_{success,failure} and test_external{,_without_stderr}.
561 #
562 # The single parameter is the prerequisite tag (a simple word, in all
563 # capital letters by convention).
564
565 test_unset_prereq () {
566 ! test_have_prereq "$1" ||
567 satisfied_prereq="${satisfied_prereq% $1 *} ${satisfied_prereq#* $1 }"
568 }
569
570 test_set_prereq () {
571 if test -n "$GIT_TEST_FAIL_PREREQS_INTERNAL"
572 then
573 case "$1" in
574 # The "!" case is handled below with
575 # test_unset_prereq()
576 !*)
577 ;;
578 # (Temporary?) whitelist of things we can't easily
579 # pretend not to support
580 SYMLINKS)
581 ;;
582 # Inspecting whether GIT_TEST_FAIL_PREREQS is on
583 # should be unaffected.
584 FAIL_PREREQS)
585 ;;
586 *)
587 return
588 esac
589 fi
590
591 case "$1" in
592 !*)
593 test_unset_prereq "${1#!}"
594 ;;
595 *)
596 satisfied_prereq="$satisfied_prereq$1 "
597 ;;
598 esac
599 }
600 satisfied_prereq=" "
601 lazily_testable_prereq= lazily_tested_prereq=
602
603 # Usage: test_lazy_prereq PREREQ 'script'
604 test_lazy_prereq () {
605 lazily_testable_prereq="$lazily_testable_prereq$1 "
606 eval test_prereq_lazily_$1=\$2
607 }
608
609 test_run_lazy_prereq_ () {
610 script='
611 mkdir -p "$TRASH_DIRECTORY/prereq-test-dir-'"$1"'" &&
612 (
613 cd "$TRASH_DIRECTORY/prereq-test-dir-'"$1"'" &&'"$2"'
614 )'
615 say >&3 "checking prerequisite: $1"
616 say >&3 "$script"
617 test_eval_ "$script"
618 eval_ret=$?
619 rm -rf "$TRASH_DIRECTORY/prereq-test-dir-$1"
620 if test "$eval_ret" = 0; then
621 say >&3 "prerequisite $1 ok"
622 else
623 say >&3 "prerequisite $1 not satisfied"
624 fi
625 return $eval_ret
626 }
627
628 test_have_prereq () {
629 # prerequisites can be concatenated with ','
630 save_IFS=$IFS
631 IFS=,
632 set -- $*
633 IFS=$save_IFS
634
635 total_prereq=0
636 ok_prereq=0
637 missing_prereq=
638
639 for prerequisite
640 do
641 case "$prerequisite" in
642 !*)
643 negative_prereq=t
644 prerequisite=${prerequisite#!}
645 ;;
646 *)
647 negative_prereq=
648 esac
649
650 case " $lazily_tested_prereq " in
651 *" $prerequisite "*)
652 ;;
653 *)
654 case " $lazily_testable_prereq " in
655 *" $prerequisite "*)
656 eval "script=\$test_prereq_lazily_$prerequisite" &&
657 if test_run_lazy_prereq_ "$prerequisite" "$script"
658 then
659 test_set_prereq $prerequisite
660 fi
661 lazily_tested_prereq="$lazily_tested_prereq$prerequisite "
662 esac
663 ;;
664 esac
665
666 total_prereq=$(($total_prereq + 1))
667 case "$satisfied_prereq" in
668 *" $prerequisite "*)
669 satisfied_this_prereq=t
670 ;;
671 *)
672 satisfied_this_prereq=
673 esac
674
675 case "$satisfied_this_prereq,$negative_prereq" in
676 t,|,t)
677 ok_prereq=$(($ok_prereq + 1))
678 ;;
679 *)
680 # Keep a list of missing prerequisites; restore
681 # the negative marker if necessary.
682 prerequisite=${negative_prereq:+!}$prerequisite
683
684 # Abort if this prereq was marked as required
685 if test -n "$GIT_TEST_REQUIRE_PREREQ"
686 then
687 case " $GIT_TEST_REQUIRE_PREREQ " in
688 *" $prerequisite "*)
689 BAIL_OUT "required prereq $prerequisite failed"
690 ;;
691 esac
692 fi
693
694 if test -z "$missing_prereq"
695 then
696 missing_prereq=$prerequisite
697 else
698 missing_prereq="$prerequisite,$missing_prereq"
699 fi
700 esac
701 done
702
703 test $total_prereq = $ok_prereq
704 }
705
706 test_declared_prereq () {
707 case ",$test_prereq," in
708 *,$1,*)
709 return 0
710 ;;
711 esac
712 return 1
713 }
714
715 test_verify_prereq () {
716 test -z "$test_prereq" ||
717 expr >/dev/null "$test_prereq" : '[A-Z0-9_,!]*$' ||
718 BUG "'$test_prereq' does not look like a prereq"
719 }
720
721 test_expect_failure () {
722 test_start_
723 test "$#" = 3 && { test_prereq=$1; shift; } || test_prereq=
724 test "$#" = 2 ||
725 BUG "not 2 or 3 parameters to test-expect-failure"
726 test_verify_prereq
727 export test_prereq
728 if ! test_skip "$@"
729 then
730 say >&3 "checking known breakage of $TEST_NUMBER.$test_count '$1': $2"
731 if test_run_ "$2" expecting_failure
732 then
733 test_known_broken_ok_ "$1"
734 else
735 test_known_broken_failure_ "$1"
736 fi
737 fi
738 test_finish_
739 }
740
741 test_expect_success () {
742 test_start_
743 test "$#" = 3 && { test_prereq=$1; shift; } || test_prereq=
744 test "$#" = 2 ||
745 BUG "not 2 or 3 parameters to test-expect-success"
746 test_verify_prereq
747 export test_prereq
748 if ! test_skip "$@"
749 then
750 say >&3 "expecting success of $TEST_NUMBER.$test_count '$1': $2"
751 if test_run_ "$2"
752 then
753 test_ok_ "$1"
754 else
755 test_failure_ "$@"
756 fi
757 fi
758 test_finish_
759 }
760
761 # test_external runs external test scripts that provide continuous
762 # test output about their progress, and succeeds/fails on
763 # zero/non-zero exit code. It outputs the test output on stdout even
764 # in non-verbose mode, and announces the external script with "# run
765 # <n>: ..." before running it. When providing relative paths, keep in
766 # mind that all scripts run in "trash directory".
767 # Usage: test_external description command arguments...
768 # Example: test_external 'Perl API' perl ../path/to/test.pl
769 test_external () {
770 test "$#" = 4 && { test_prereq=$1; shift; } || test_prereq=
771 test "$#" = 3 ||
772 BUG "not 3 or 4 parameters to test_external"
773 descr="$1"
774 shift
775 test_verify_prereq
776 export test_prereq
777 if ! test_skip "$descr" "$@"
778 then
779 # Announce the script to reduce confusion about the
780 # test output that follows.
781 say_color "" "# run $test_count: $descr ($*)"
782 # Export TEST_DIRECTORY, TRASH_DIRECTORY and GIT_TEST_LONG
783 # to be able to use them in script
784 export TEST_DIRECTORY TRASH_DIRECTORY GIT_TEST_LONG
785 # Run command; redirect its stderr to &4 as in
786 # test_run_, but keep its stdout on our stdout even in
787 # non-verbose mode.
788 "$@" 2>&4
789 if test "$?" = 0
790 then
791 if test $test_external_has_tap -eq 0; then
792 test_ok_ "$descr"
793 else
794 say_color "" "# test_external test $descr was ok"
795 test_success=$(($test_success + 1))
796 fi
797 else
798 if test $test_external_has_tap -eq 0; then
799 test_failure_ "$descr" "$@"
800 else
801 say_color error "# test_external test $descr failed: $@"
802 test_failure=$(($test_failure + 1))
803 fi
804 fi
805 fi
806 }
807
808 # Like test_external, but in addition tests that the command generated
809 # no output on stderr.
810 test_external_without_stderr () {
811 # The temporary file has no (and must have no) security
812 # implications.
813 tmp=${TMPDIR:-/tmp}
814 stderr="$tmp/git-external-stderr.$$.tmp"
815 test_external "$@" 4> "$stderr"
816 test -f "$stderr" || error "Internal error: $stderr disappeared."
817 descr="no stderr: $1"
818 shift
819 say >&3 "# expecting no stderr from previous command"
820 if test ! -s "$stderr"
821 then
822 rm "$stderr"
823
824 if test $test_external_has_tap -eq 0; then
825 test_ok_ "$descr"
826 else
827 say_color "" "# test_external_without_stderr test $descr was ok"
828 test_success=$(($test_success + 1))
829 fi
830 else
831 if test "$verbose" = t
832 then
833 output=$(echo; echo "# Stderr is:"; cat "$stderr")
834 else
835 output=
836 fi
837 # rm first in case test_failure exits.
838 rm "$stderr"
839 if test $test_external_has_tap -eq 0; then
840 test_failure_ "$descr" "$@" "$output"
841 else
842 say_color error "# test_external_without_stderr test $descr failed: $@: $output"
843 test_failure=$(($test_failure + 1))
844 fi
845 fi
846 }
847
848 # debugging-friendly alternatives to "test [-f|-d|-e]"
849 # The commands test the existence or non-existence of $1
850 test_path_is_file () {
851 test "$#" -ne 1 && BUG "1 param"
852 if ! test -f "$1"
853 then
854 echo "File $1 doesn't exist"
855 false
856 fi
857 }
858
859 test_path_is_file_not_symlink () {
860 test "$#" -ne 1 && BUG "1 param"
861 test_path_is_file "$1" &&
862 if test -h "$1"
863 then
864 echo "$1 shouldn't be a symbolic link"
865 false
866 fi
867 }
868
869 test_path_is_dir () {
870 test "$#" -ne 1 && BUG "1 param"
871 if ! test -d "$1"
872 then
873 echo "Directory $1 doesn't exist"
874 false
875 fi
876 }
877
878 test_path_is_dir_not_symlink () {
879 test "$#" -ne 1 && BUG "1 param"
880 test_path_is_dir "$1" &&
881 if test -h "$1"
882 then
883 echo "$1 shouldn't be a symbolic link"
884 false
885 fi
886 }
887
888 test_path_exists () {
889 test "$#" -ne 1 && BUG "1 param"
890 if ! test -e "$1"
891 then
892 echo "Path $1 doesn't exist"
893 false
894 fi
895 }
896
897 test_path_is_symlink () {
898 test "$#" -ne 1 && BUG "1 param"
899 if ! test -h "$1"
900 then
901 echo "Symbolic link $1 doesn't exist"
902 false
903 fi
904 }
905
906 # Check if the directory exists and is empty as expected, barf otherwise.
907 test_dir_is_empty () {
908 test "$#" -ne 1 && BUG "1 param"
909 test_path_is_dir "$1" &&
910 if test -n "$(ls -a1 "$1" | egrep -v '^\.\.?$')"
911 then
912 echo "Directory '$1' is not empty, it contains:"
913 ls -la "$1"
914 return 1
915 fi
916 }
917
918 # Check if the file exists and has a size greater than zero
919 test_file_not_empty () {
920 test "$#" = 2 && BUG "2 param"
921 if ! test -s "$1"
922 then
923 echo "'$1' is not a non-empty file."
924 false
925 fi
926 }
927
928 test_path_is_missing () {
929 test "$#" -ne 1 && BUG "1 param"
930 if test -e "$1"
931 then
932 echo "Path exists:"
933 ls -ld "$1"
934 if test $# -ge 1
935 then
936 echo "$*"
937 fi
938 false
939 fi
940 }
941
942 # test_line_count checks that a file has the number of lines it
943 # ought to. For example:
944 #
945 # test_expect_success 'produce exactly one line of output' '
946 # do something >output &&
947 # test_line_count = 1 output
948 # '
949 #
950 # is like "test $(wc -l <output) = 1" except that it passes the
951 # output through when the number of lines is wrong.
952
953 test_line_count () {
954 if test $# != 3
955 then
956 BUG "not 3 parameters to test_line_count"
957 elif ! test $(wc -l <"$3") "$1" "$2"
958 then
959 echo "test_line_count: line count for $3 !$1 $2"
960 cat "$3"
961 return 1
962 fi
963 }
964
965 # SYNOPSIS:
966 # test_stdout_line_count <bin-ops> <value> <cmd> [<args>...]
967 #
968 # test_stdout_line_count checks that the output of a command has the number
969 # of lines it ought to. For example:
970 #
971 # test_stdout_line_count = 3 git ls-files -u
972 # test_stdout_line_count -gt 10 ls
973 test_stdout_line_count () {
974 local ops val trashdir &&
975 if test "$#" -le 3
976 then
977 BUG "expect 3 or more arguments"
978 fi &&
979 ops="$1" &&
980 val="$2" &&
981 shift 2 &&
982 if ! trashdir="$(git rev-parse --git-dir)/trash"; then
983 BUG "expect to be run inside a worktree"
984 fi &&
985 mkdir -p "$trashdir" &&
986 "$@" >"$trashdir/output" &&
987 test_line_count "$ops" "$val" "$trashdir/output"
988 }
989
990
991 test_file_size () {
992 test "$#" -ne 1 && BUG "1 param"
993 test-tool path-utils file-size "$1"
994 }
995
996 # Returns success if a comma separated string of keywords ($1) contains a
997 # given keyword ($2).
998 # Examples:
999 # `list_contains "foo,bar" bar` returns 0
1000 # `list_contains "foo" bar` returns 1
1001
1002 list_contains () {
1003 case ",$1," in
1004 *,$2,*)
1005 return 0
1006 ;;
1007 esac
1008 return 1
1009 }
1010
1011 # Returns success if the arguments indicate that a command should be
1012 # accepted by test_must_fail(). If the command is run with env, the env
1013 # and its corresponding variable settings will be stripped before we
1014 # test the command being run.
1015 test_must_fail_acceptable () {
1016 if test "$1" = "env"
1017 then
1018 shift
1019 while test $# -gt 0
1020 do
1021 case "$1" in
1022 *?=*)
1023 shift
1024 ;;
1025 *)
1026 break
1027 ;;
1028 esac
1029 done
1030 fi
1031
1032 case "$1" in
1033 git|__git*|test-tool|test_terminal)
1034 return 0
1035 ;;
1036 *)
1037 return 1
1038 ;;
1039 esac
1040 }
1041
1042 # This is not among top-level (test_expect_success | test_expect_failure)
1043 # but is a prefix that can be used in the test script, like:
1044 #
1045 # test_expect_success 'complain and die' '
1046 # do something &&
1047 # do something else &&
1048 # test_must_fail git checkout ../outerspace
1049 # '
1050 #
1051 # Writing this as "! git checkout ../outerspace" is wrong, because
1052 # the failure could be due to a segv. We want a controlled failure.
1053 #
1054 # Accepts the following options:
1055 #
1056 # ok=<signal-name>[,<...>]:
1057 # Don't treat an exit caused by the given signal as error.
1058 # Multiple signals can be specified as a comma separated list.
1059 # Currently recognized signal names are: sigpipe, success.
1060 # (Don't use 'success', use 'test_might_fail' instead.)
1061 #
1062 # Do not use this to run anything but "git" and other specific testable
1063 # commands (see test_must_fail_acceptable()). We are not in the
1064 # business of vetting system supplied commands -- in other words, this
1065 # is wrong:
1066 #
1067 # test_must_fail grep pattern output
1068 #
1069 # Instead use '!':
1070 #
1071 # ! grep pattern output
1072
1073 test_must_fail () {
1074 case "$1" in
1075 ok=*)
1076 _test_ok=${1#ok=}
1077 shift
1078 ;;
1079 *)
1080 _test_ok=
1081 ;;
1082 esac
1083 if ! test_must_fail_acceptable "$@"
1084 then
1085 echo >&7 "test_must_fail: only 'git' is allowed: $*"
1086 return 1
1087 fi
1088 "$@" 2>&7
1089 exit_code=$?
1090 if test $exit_code -eq 0 && ! list_contains "$_test_ok" success
1091 then
1092 echo >&4 "test_must_fail: command succeeded: $*"
1093 return 1
1094 elif test_match_signal 13 $exit_code && list_contains "$_test_ok" sigpipe
1095 then
1096 return 0
1097 elif test $exit_code -gt 129 && test $exit_code -le 192
1098 then
1099 echo >&4 "test_must_fail: died by signal $(($exit_code - 128)): $*"
1100 return 1
1101 elif test $exit_code -eq 127
1102 then
1103 echo >&4 "test_must_fail: command not found: $*"
1104 return 1
1105 elif test $exit_code -eq 126
1106 then
1107 echo >&4 "test_must_fail: valgrind error: $*"
1108 return 1
1109 fi
1110 return 0
1111 } 7>&2 2>&4
1112
1113 # Similar to test_must_fail, but tolerates success, too. This is
1114 # meant to be used in contexts like:
1115 #
1116 # test_expect_success 'some command works without configuration' '
1117 # test_might_fail git config --unset all.configuration &&
1118 # do something
1119 # '
1120 #
1121 # Writing "git config --unset all.configuration || :" would be wrong,
1122 # because we want to notice if it fails due to segv.
1123 #
1124 # Accepts the same options as test_must_fail.
1125
1126 test_might_fail () {
1127 test_must_fail ok=success "$@" 2>&7
1128 } 7>&2 2>&4
1129
1130 # Similar to test_must_fail and test_might_fail, but check that a
1131 # given command exited with a given exit code. Meant to be used as:
1132 #
1133 # test_expect_success 'Merge with d/f conflicts' '
1134 # test_expect_code 1 git merge "merge msg" B master
1135 # '
1136
1137 test_expect_code () {
1138 want_code=$1
1139 shift
1140 "$@" 2>&7
1141 exit_code=$?
1142 if test $exit_code = $want_code
1143 then
1144 return 0
1145 fi
1146
1147 echo >&4 "test_expect_code: command exited with $exit_code, we wanted $want_code $*"
1148 return 1
1149 } 7>&2 2>&4
1150
1151 # test_cmp is a helper function to compare actual and expected output.
1152 # You can use it like:
1153 #
1154 # test_expect_success 'foo works' '
1155 # echo expected >expected &&
1156 # foo >actual &&
1157 # test_cmp expected actual
1158 # '
1159 #
1160 # This could be written as either "cmp" or "diff -u", but:
1161 # - cmp's output is not nearly as easy to read as diff -u
1162 # - not all diff versions understand "-u"
1163
1164 test_cmp () {
1165 test "$#" -ne 2 && BUG "2 param"
1166 eval "$GIT_TEST_CMP" '"$@"'
1167 }
1168
1169 # Check that the given config key has the expected value.
1170 #
1171 # test_cmp_config [-C <dir>] <expected-value>
1172 # [<git-config-options>...] <config-key>
1173 #
1174 # for example to check that the value of core.bar is foo
1175 #
1176 # test_cmp_config foo core.bar
1177 #
1178 test_cmp_config () {
1179 local GD &&
1180 if test "$1" = "-C"
1181 then
1182 shift &&
1183 GD="-C $1" &&
1184 shift
1185 fi &&
1186 printf "%s\n" "$1" >expect.config &&
1187 shift &&
1188 git $GD config "$@" >actual.config &&
1189 test_cmp expect.config actual.config
1190 }
1191
1192 # test_cmp_bin - helper to compare binary files
1193
1194 test_cmp_bin () {
1195 test "$#" -ne 2 && BUG "2 param"
1196 cmp "$@"
1197 }
1198
1199 # Wrapper for grep which used to be used for
1200 # GIT_TEST_GETTEXT_POISON=false. Only here as a shim for other
1201 # in-flight changes. Should not be used and will be removed soon.
1202 test_i18ngrep () {
1203 eval "last_arg=\${$#}"
1204
1205 test -f "$last_arg" ||
1206 BUG "test_i18ngrep requires a file to read as the last parameter"
1207
1208 if test $# -lt 2 ||
1209 { test "x!" = "x$1" && test $# -lt 3 ; }
1210 then
1211 BUG "too few parameters to test_i18ngrep"
1212 fi
1213
1214 if test "x!" = "x$1"
1215 then
1216 shift
1217 ! grep "$@" && return 0
1218
1219 echo >&4 "error: '! grep $@' did find a match in:"
1220 else
1221 grep "$@" && return 0
1222
1223 echo >&4 "error: 'grep $@' didn't find a match in:"
1224 fi
1225
1226 if test -s "$last_arg"
1227 then
1228 cat >&4 "$last_arg"
1229 else
1230 echo >&4 "<File '$last_arg' is empty>"
1231 fi
1232
1233 return 1
1234 }
1235
1236 # Call any command "$@" but be more verbose about its
1237 # failure. This is handy for commands like "test" which do
1238 # not output anything when they fail.
1239 verbose () {
1240 "$@" && return 0
1241 echo >&4 "command failed: $(git rev-parse --sq-quote "$@")"
1242 return 1
1243 }
1244
1245 # Check if the file expected to be empty is indeed empty, and barfs
1246 # otherwise.
1247
1248 test_must_be_empty () {
1249 test "$#" -ne 1 && BUG "1 param"
1250 test_path_is_file "$1" &&
1251 if test -s "$1"
1252 then
1253 echo "'$1' is not empty, it contains:"
1254 cat "$1"
1255 return 1
1256 fi
1257 }
1258
1259 # Tests that its two parameters refer to the same revision, or if '!' is
1260 # provided first, that its other two parameters refer to different
1261 # revisions.
1262 test_cmp_rev () {
1263 local op='=' wrong_result=different
1264
1265 if test $# -ge 1 && test "x$1" = 'x!'
1266 then
1267 op='!='
1268 wrong_result='the same'
1269 shift
1270 fi
1271 if test $# != 2
1272 then
1273 BUG "test_cmp_rev requires two revisions, but got $#"
1274 else
1275 local r1 r2
1276 r1=$(git rev-parse --verify "$1") &&
1277 r2=$(git rev-parse --verify "$2") || return 1
1278
1279 if ! test "$r1" "$op" "$r2"
1280 then
1281 cat >&4 <<-EOF
1282 error: two revisions point to $wrong_result objects:
1283 '$1': $r1
1284 '$2': $r2
1285 EOF
1286 return 1
1287 fi
1288 fi
1289 }
1290
1291 # Compare paths respecting core.ignoreCase
1292 test_cmp_fspath () {
1293 if test "x$1" = "x$2"
1294 then
1295 return 0
1296 fi
1297
1298 if test true != "$(git config --get --type=bool core.ignorecase)"
1299 then
1300 return 1
1301 fi
1302
1303 test "x$(echo "$1" | tr A-Z a-z)" = "x$(echo "$2" | tr A-Z a-z)"
1304 }
1305
1306 # Print a sequence of integers in increasing order, either with
1307 # two arguments (start and end):
1308 #
1309 # test_seq 1 5 -- outputs 1 2 3 4 5 one line at a time
1310 #
1311 # or with one argument (end), in which case it starts counting
1312 # from 1.
1313
1314 test_seq () {
1315 case $# in
1316 1) set 1 "$@" ;;
1317 2) ;;
1318 *) BUG "not 1 or 2 parameters to test_seq" ;;
1319 esac
1320 test_seq_counter__=$1
1321 while test "$test_seq_counter__" -le "$2"
1322 do
1323 echo "$test_seq_counter__"
1324 test_seq_counter__=$(( $test_seq_counter__ + 1 ))
1325 done
1326 }
1327
1328 # This function can be used to schedule some commands to be run
1329 # unconditionally at the end of the test to restore sanity:
1330 #
1331 # test_expect_success 'test core.capslock' '
1332 # git config core.capslock true &&
1333 # test_when_finished "git config --unset core.capslock" &&
1334 # hello world
1335 # '
1336 #
1337 # That would be roughly equivalent to
1338 #
1339 # test_expect_success 'test core.capslock' '
1340 # git config core.capslock true &&
1341 # hello world
1342 # git config --unset core.capslock
1343 # '
1344 #
1345 # except that the greeting and config --unset must both succeed for
1346 # the test to pass.
1347 #
1348 # Note that under --immediate mode, no clean-up is done to help diagnose
1349 # what went wrong.
1350
1351 test_when_finished () {
1352 # We cannot detect when we are in a subshell in general, but by
1353 # doing so on Bash is better than nothing (the test will
1354 # silently pass on other shells).
1355 test "${BASH_SUBSHELL-0}" = 0 ||
1356 BUG "test_when_finished does nothing in a subshell"
1357 test_cleanup="{ $*
1358 } && (exit \"\$eval_ret\"); eval_ret=\$?; $test_cleanup"
1359 }
1360
1361 # This function can be used to schedule some commands to be run
1362 # unconditionally at the end of the test script, e.g. to stop a daemon:
1363 #
1364 # test_expect_success 'test git daemon' '
1365 # git daemon &
1366 # daemon_pid=$! &&
1367 # test_atexit 'kill $daemon_pid' &&
1368 # hello world
1369 # '
1370 #
1371 # The commands will be executed before the trash directory is removed,
1372 # i.e. the atexit commands will still be able to access any pidfiles or
1373 # socket files.
1374 #
1375 # Note that these commands will be run even when a test script run
1376 # with '--immediate' fails. Be careful with your atexit commands to
1377 # minimize any changes to the failed state.
1378
1379 test_atexit () {
1380 # We cannot detect when we are in a subshell in general, but by
1381 # doing so on Bash is better than nothing (the test will
1382 # silently pass on other shells).
1383 test "${BASH_SUBSHELL-0}" = 0 ||
1384 BUG "test_atexit does nothing in a subshell"
1385 test_atexit_cleanup="{ $*
1386 } && (exit \"\$eval_ret\"); eval_ret=\$?; $test_atexit_cleanup"
1387 }
1388
1389 # Deprecated wrapper for "git init", use "git init" directly instead
1390 # Usage: test_create_repo <directory>
1391 test_create_repo () {
1392 git init "$@"
1393 }
1394
1395 # This function helps on symlink challenged file systems when it is not
1396 # important that the file system entry is a symbolic link.
1397 # Use test_ln_s_add instead of "ln -s x y && git add y" to add a
1398 # symbolic link entry y to the index.
1399
1400 test_ln_s_add () {
1401 if test_have_prereq SYMLINKS
1402 then
1403 ln -s "$1" "$2" &&
1404 git update-index --add "$2"
1405 else
1406 printf '%s' "$1" >"$2" &&
1407 ln_s_obj=$(git hash-object -w "$2") &&
1408 git update-index --add --cacheinfo 120000 $ln_s_obj "$2" &&
1409 # pick up stat info from the file
1410 git update-index "$2"
1411 fi
1412 }
1413
1414 # This function writes out its parameters, one per line
1415 test_write_lines () {
1416 printf "%s\n" "$@"
1417 }
1418
1419 perl () {
1420 command "$PERL_PATH" "$@" 2>&7
1421 } 7>&2 2>&4
1422
1423 # Given the name of an environment variable with a bool value, normalize
1424 # its value to a 0 (true) or 1 (false or empty string) return code.
1425 #
1426 # test_bool_env GIT_TEST_HTTPD <default-value>
1427 #
1428 # Return with code corresponding to the given default value if the variable
1429 # is unset.
1430 # Abort the test script if either the value of the variable or the default
1431 # are not valid bool values.
1432
1433 test_bool_env () {
1434 if test $# != 2
1435 then
1436 BUG "test_bool_env requires two parameters (variable name and default value)"
1437 fi
1438
1439 git env--helper --type=bool --default="$2" --exit-code "$1"
1440 ret=$?
1441 case $ret in
1442 0|1) # unset or valid bool value
1443 ;;
1444 *) # invalid bool value or something unexpected
1445 error >&7 "test_bool_env requires bool values both for \$$1 and for the default fallback"
1446 ;;
1447 esac
1448 return $ret
1449 }
1450
1451 # Exit the test suite, either by skipping all remaining tests or by
1452 # exiting with an error. If our prerequisite variable $1 falls back
1453 # on a default assume we were opportunistically trying to set up some
1454 # tests and we skip. If it is explicitly "true", then we report a failure.
1455 #
1456 # The error/skip message should be given by $2.
1457 #
1458 test_skip_or_die () {
1459 if ! test_bool_env "$1" false
1460 then
1461 skip_all=$2
1462 test_done
1463 fi
1464 error "$2"
1465 }
1466
1467 # The following mingw_* functions obey POSIX shell syntax, but are actually
1468 # bash scripts, and are meant to be used only with bash on Windows.
1469
1470 # A test_cmp function that treats LF and CRLF equal and avoids to fork
1471 # diff when possible.
1472 mingw_test_cmp () {
1473 # Read text into shell variables and compare them. If the results
1474 # are different, use regular diff to report the difference.
1475 local test_cmp_a= test_cmp_b=
1476
1477 # When text came from stdin (one argument is '-') we must feed it
1478 # to diff.
1479 local stdin_for_diff=
1480
1481 # Since it is difficult to detect the difference between an
1482 # empty input file and a failure to read the files, we go straight
1483 # to diff if one of the inputs is empty.
1484 if test -s "$1" && test -s "$2"
1485 then
1486 # regular case: both files non-empty
1487 mingw_read_file_strip_cr_ test_cmp_a <"$1"
1488 mingw_read_file_strip_cr_ test_cmp_b <"$2"
1489 elif test -s "$1" && test "$2" = -
1490 then
1491 # read 2nd file from stdin
1492 mingw_read_file_strip_cr_ test_cmp_a <"$1"
1493 mingw_read_file_strip_cr_ test_cmp_b
1494 stdin_for_diff='<<<"$test_cmp_b"'
1495 elif test "$1" = - && test -s "$2"
1496 then
1497 # read 1st file from stdin
1498 mingw_read_file_strip_cr_ test_cmp_a
1499 mingw_read_file_strip_cr_ test_cmp_b <"$2"
1500 stdin_for_diff='<<<"$test_cmp_a"'
1501 fi
1502 test -n "$test_cmp_a" &&
1503 test -n "$test_cmp_b" &&
1504 test "$test_cmp_a" = "$test_cmp_b" ||
1505 eval "diff -u \"\$@\" $stdin_for_diff"
1506 }
1507
1508 # $1 is the name of the shell variable to fill in
1509 mingw_read_file_strip_cr_ () {
1510 # Read line-wise using LF as the line separator
1511 # and use IFS to strip CR.
1512 local line
1513 while :
1514 do
1515 if IFS=$'\r' read -r -d $'\n' line
1516 then
1517 # good
1518 line=$line$'\n'
1519 else
1520 # we get here at EOF, but also if the last line
1521 # was not terminated by LF; in the latter case,
1522 # some text was read
1523 if test -z "$line"
1524 then
1525 # EOF, really
1526 break
1527 fi
1528 fi
1529 eval "$1=\$$1\$line"
1530 done
1531 }
1532
1533 # Like "env FOO=BAR some-program", but run inside a subshell, which means
1534 # it also works for shell functions (though those functions cannot impact
1535 # the environment outside of the test_env invocation).
1536 test_env () {
1537 (
1538 while test $# -gt 0
1539 do
1540 case "$1" in
1541 *=*)
1542 eval "${1%%=*}=\${1#*=}"
1543 eval "export ${1%%=*}"
1544 shift
1545 ;;
1546 *)
1547 "$@" 2>&7
1548 exit
1549 ;;
1550 esac
1551 done
1552 )
1553 } 7>&2 2>&4
1554
1555 # Returns true if the numeric exit code in "$2" represents the expected signal
1556 # in "$1". Signals should be given numerically.
1557 test_match_signal () {
1558 if test "$2" = "$((128 + $1))"
1559 then
1560 # POSIX
1561 return 0
1562 elif test "$2" = "$((256 + $1))"
1563 then
1564 # ksh
1565 return 0
1566 fi
1567 return 1
1568 }
1569
1570 # Read up to "$1" bytes (or to EOF) from stdin and write them to stdout.
1571 test_copy_bytes () {
1572 perl -e '
1573 my $len = $ARGV[1];
1574 while ($len > 0) {
1575 my $s;
1576 my $nread = sysread(STDIN, $s, $len);
1577 die "cannot read: $!" unless defined($nread);
1578 last unless $nread;
1579 print $s;
1580 $len -= $nread;
1581 }
1582 ' - "$1"
1583 }
1584
1585 # run "$@" inside a non-git directory
1586 nongit () {
1587 test -d non-repo ||
1588 mkdir non-repo ||
1589 return 1
1590
1591 (
1592 GIT_CEILING_DIRECTORIES=$(pwd) &&
1593 export GIT_CEILING_DIRECTORIES &&
1594 cd non-repo &&
1595 "$@" 2>&7
1596 )
1597 } 7>&2 2>&4
1598
1599 # These functions are historical wrappers around "test-tool pkt-line"
1600 # for older tests. Use "test-tool pkt-line" itself in new tests.
1601 packetize () {
1602 if test $# -gt 0
1603 then
1604 packet="$*"
1605 printf '%04x%s' "$((4 + ${#packet}))" "$packet"
1606 else
1607 test-tool pkt-line pack
1608 fi
1609 }
1610
1611 packetize_raw () {
1612 test-tool pkt-line pack-raw-stdin
1613 }
1614
1615 depacketize () {
1616 test-tool pkt-line unpack
1617 }
1618
1619 # Converts base-16 data into base-8. The output is given as a sequence of
1620 # escaped octals, suitable for consumption by 'printf'.
1621 hex2oct () {
1622 perl -ne 'printf "\\%03o", hex for /../g'
1623 }
1624
1625 # Set the hash algorithm in use to $1. Only useful when testing the testsuite.
1626 test_set_hash () {
1627 test_hash_algo="$1"
1628 }
1629
1630 # Detect the hash algorithm in use.
1631 test_detect_hash () {
1632 test_hash_algo="${GIT_TEST_DEFAULT_HASH:-sha1}"
1633 }
1634
1635 # Load common hash metadata and common placeholder object IDs for use with
1636 # test_oid.
1637 test_oid_init () {
1638 test -n "$test_hash_algo" || test_detect_hash &&
1639 test_oid_cache <"$TEST_DIRECTORY/oid-info/hash-info" &&
1640 test_oid_cache <"$TEST_DIRECTORY/oid-info/oid"
1641 }
1642
1643 # Load key-value pairs from stdin suitable for use with test_oid. Blank lines
1644 # and lines starting with "#" are ignored. Keys must be shell identifier
1645 # characters.
1646 #
1647 # Examples:
1648 # rawsz sha1:20
1649 # rawsz sha256:32
1650 test_oid_cache () {
1651 local tag rest k v &&
1652
1653 { test -n "$test_hash_algo" || test_detect_hash; } &&
1654 while read tag rest
1655 do
1656 case $tag in
1657 \#*)
1658 continue;;
1659 ?*)
1660 # non-empty
1661 ;;
1662 *)
1663 # blank line
1664 continue;;
1665 esac &&
1666
1667 k="${rest%:*}" &&
1668 v="${rest#*:}" &&
1669
1670 if ! expr "$k" : '[a-z0-9][a-z0-9]*$' >/dev/null
1671 then
1672 BUG 'bad hash algorithm'
1673 fi &&
1674 eval "test_oid_${k}_$tag=\"\$v\""
1675 done
1676 }
1677
1678 # Look up a per-hash value based on a key ($1). The value must have been loaded
1679 # by test_oid_init or test_oid_cache.
1680 test_oid () {
1681 local algo="${test_hash_algo}" &&
1682
1683 case "$1" in
1684 --hash=*)
1685 algo="${1#--hash=}" &&
1686 shift;;
1687 *)
1688 ;;
1689 esac &&
1690
1691 local var="test_oid_${algo}_$1" &&
1692
1693 # If the variable is unset, we must be missing an entry for this
1694 # key-hash pair, so exit with an error.
1695 if eval "test -z \"\${$var+set}\""
1696 then
1697 BUG "undefined key '$1'"
1698 fi &&
1699 eval "printf '%s' \"\${$var}\""
1700 }
1701
1702 # Insert a slash into an object ID so it can be used to reference a location
1703 # under ".git/objects". For example, "deadbeef..." becomes "de/adbeef..".
1704 test_oid_to_path () {
1705 local basename=${1#??}
1706 echo "${1%$basename}/$basename"
1707 }
1708
1709 # Choose a port number based on the test script's number and store it in
1710 # the given variable name, unless that variable already contains a number.
1711 test_set_port () {
1712 local var=$1 port
1713
1714 if test $# -ne 1 || test -z "$var"
1715 then
1716 BUG "test_set_port requires a variable name"
1717 fi
1718
1719 eval port=\$$var
1720 case "$port" in
1721 "")
1722 # No port is set in the given env var, use the test
1723 # number as port number instead.
1724 # Remove not only the leading 't', but all leading zeros
1725 # as well, so the arithmetic below won't (mis)interpret
1726 # a test number like '0123' as an octal value.
1727 port=${this_test#${this_test%%[1-9]*}}
1728 if test "${port:-0}" -lt 1024
1729 then
1730 # root-only port, use a larger one instead.
1731 port=$(($port + 10000))
1732 fi
1733 ;;
1734 *[!0-9]*|0*)
1735 error >&7 "invalid port number: $port"
1736 ;;
1737 *)
1738 # The user has specified the port.
1739 ;;
1740 esac
1741
1742 # Make sure that parallel '--stress' test jobs get different
1743 # ports.
1744 port=$(($port + ${GIT_TEST_STRESS_JOB_NR:-0}))
1745 eval $var=$port
1746 }
1747
1748 # Tests for the hidden file attribute on Windows
1749 test_path_is_hidden () {
1750 test_have_prereq MINGW ||
1751 BUG "test_path_is_hidden can only be used on Windows"
1752
1753 # Use the output of `attrib`, ignore the absolute path
1754 case "$("$SYSTEMROOT"/system32/attrib "$1")" in *H*?:*) return 0;; esac
1755 return 1
1756 }
1757
1758 # Check that the given command was invoked as part of the
1759 # trace2-format trace on stdin.
1760 #
1761 # test_subcommand [!] <command> <args>... < <trace>
1762 #
1763 # For example, to look for an invocation of "git upload-pack
1764 # /path/to/repo"
1765 #
1766 # GIT_TRACE2_EVENT=event.log git fetch ... &&
1767 # test_subcommand git upload-pack "$PATH" <event.log
1768 #
1769 # If the first parameter passed is !, this instead checks that
1770 # the given command was not called.
1771 #
1772 test_subcommand () {
1773 local negate=
1774 if test "$1" = "!"
1775 then
1776 negate=t
1777 shift
1778 fi
1779
1780 local expr=$(printf '"%s",' "$@")
1781 expr="${expr%,}"
1782
1783 if test -n "$negate"
1784 then
1785 ! grep "\[$expr\]"
1786 else
1787 grep "\[$expr\]"
1788 fi
1789 }
1790
1791 # Check that the given command was invoked as part of the
1792 # trace2-format trace on stdin, but without an exact set of
1793 # arguments.
1794 #
1795 # test_subcommand [!] <command> <args>... < <trace>
1796 #
1797 # For example, to look for an invocation of "git pack-objects"
1798 # with the "--honor-pack-keep" argument, use
1799 #
1800 # GIT_TRACE2_EVENT=event.log git repack ... &&
1801 # test_subcommand git pack-objects --honor-pack-keep <event.log
1802 #
1803 # If the first parameter passed is !, this instead checks that
1804 # the given command was not called.
1805 #
1806 test_subcommand_inexact () {
1807 local negate=
1808 if test "$1" = "!"
1809 then
1810 negate=t
1811 shift
1812 fi
1813
1814 local expr=$(printf '"%s".*' "$@")
1815 expr="${expr%,}"
1816
1817 if test -n "$negate"
1818 then
1819 ! grep "\"event\":\"child_start\".*\[$expr\]"
1820 else
1821 grep "\"event\":\"child_start\".*\[$expr\]"
1822 fi
1823 }
1824
1825 # Check that the given command was invoked as part of the
1826 # trace2-format trace on stdin.
1827 #
1828 # test_region [!] <category> <label> git <command> <args>...
1829 #
1830 # For example, to look for trace2_region_enter("index", "do_read_index", repo)
1831 # in an invocation of "git checkout HEAD~1", run
1832 #
1833 # GIT_TRACE2_EVENT="$(pwd)/trace.txt" GIT_TRACE2_EVENT_NESTING=10 \
1834 # git checkout HEAD~1 &&
1835 # test_region index do_read_index <trace.txt
1836 #
1837 # If the first parameter passed is !, this instead checks that
1838 # the given region was not entered.
1839 #
1840 test_region () {
1841 local expect_exit=0
1842 if test "$1" = "!"
1843 then
1844 expect_exit=1
1845 shift
1846 fi
1847
1848 grep -e '"region_enter".*"category":"'"$1"'","label":"'"$2"\" "$3"
1849 exitcode=$?
1850
1851 if test $exitcode != $expect_exit
1852 then
1853 return 1
1854 fi
1855
1856 grep -e '"region_leave".*"category":"'"$1"'","label":"'"$2"\" "$3"
1857 exitcode=$?
1858
1859 if test $exitcode != $expect_exit
1860 then
1861 return 1
1862 fi
1863
1864 return 0
1865 }
1866
1867 # Print the destination of symlink(s) provided as arguments. Basically
1868 # the same as the readlink command, but it's not available everywhere.
1869 test_readlink () {
1870 perl -le 'print readlink($_) for @ARGV' "$@"
1871 }
1872
1873 # Set mtime to a fixed "magic" timestamp in mid February 2009, before we
1874 # run an operation that may or may not touch the file. If the file was
1875 # touched, its timestamp will not accidentally have such an old timestamp,
1876 # as long as your filesystem clock is reasonably correct. To verify the
1877 # timestamp, follow up with test_is_magic_mtime.
1878 #
1879 # An optional increment to the magic timestamp may be specified as second
1880 # argument.
1881 test_set_magic_mtime () {
1882 local inc=${2:-0} &&
1883 local mtime=$((1234567890 + $inc)) &&
1884 test-tool chmtime =$mtime "$1" &&
1885 test_is_magic_mtime "$1" $inc
1886 }
1887
1888 # Test whether the given file has the "magic" mtime set. This is meant to
1889 # be used in combination with test_set_magic_mtime.
1890 #
1891 # An optional increment to the magic timestamp may be specified as second
1892 # argument. Usually, this should be the same increment which was used for
1893 # the associated test_set_magic_mtime.
1894 test_is_magic_mtime () {
1895 local inc=${2:-0} &&
1896 local mtime=$((1234567890 + $inc)) &&
1897 echo $mtime >.git/test-mtime-expect &&
1898 test-tool chmtime --get "$1" >.git/test-mtime-actual &&
1899 test_cmp .git/test-mtime-expect .git/test-mtime-actual
1900 local ret=$?
1901 rm -f .git/test-mtime-expect
1902 rm -f .git/test-mtime-actual
1903 return $ret
1904 }