test-lib-functions.sh 28.6 KB
Newer Older
1 2
# Library of functions shared by all tests scripts, included by
# test-lib.sh.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#
# Copyright (c) 2005 Junio C Hamano
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see http://www.gnu.org/licenses/ .

# The semantics of the editor variables are that of invoking
# sh -c "$EDITOR \"$@\"" files ...
#
# If our trash directory contains shell metacharacters, they will be
# interpreted if we just set $EDITOR directly, so do a little dance with
# environment variables to work around this.
#
# In particular, quoting isn't enough, as the path may contain the same quote
# that we're using.
test_set_editor () {
	FAKE_EDITOR="$1"
	export FAKE_EDITOR
	EDITOR='"$FAKE_EDITOR"'
	export EDITOR
}

35 36 37 38 39
test_set_index_version () {
    GIT_INDEX_VERSION="$1"
    export GIT_INDEX_VERSION
}

40 41 42 43 44
test_decode_color () {
	awk '
		function name(n) {
			if (n == 0) return "RESET";
			if (n == 1) return "BOLD";
45 46
			if (n == 2) return "FAINT";
			if (n == 3) return "ITALIC";
47
			if (n == 7) return "REVERSE";
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
			if (n == 30) return "BLACK";
			if (n == 31) return "RED";
			if (n == 32) return "GREEN";
			if (n == 33) return "YELLOW";
			if (n == 34) return "BLUE";
			if (n == 35) return "MAGENTA";
			if (n == 36) return "CYAN";
			if (n == 37) return "WHITE";
			if (n == 40) return "BLACK";
			if (n == 41) return "BRED";
			if (n == 42) return "BGREEN";
			if (n == 43) return "BYELLOW";
			if (n == 44) return "BBLUE";
			if (n == 45) return "BMAGENTA";
			if (n == 46) return "BCYAN";
			if (n == 47) return "BWHITE";
		}
		{
			while (match($0, /\033\[[0-9;]*m/) != 0) {
				printf "%s<", substr($0, 1, RSTART-1);
				codes = substr($0, RSTART+2, RLENGTH-3);
				if (length(codes) == 0)
					printf "%s", name(0)
				else {
					n = split(codes, ary, ";");
					sep = "";
					for (i = 1; i <= n; i++) {
						printf "%s%s", sep, name(ary[i]);
						sep = ";"
					}
				}
				printf ">";
				$0 = substr($0, RSTART + RLENGTH, length($0) - RSTART - RLENGTH + 1);
			}
			print
		}
	'
}

87 88 89 90
lf_to_nul () {
	perl -pe 'y/\012/\000/'
}

91
nul_to_q () {
92
	perl -pe 'y/\000/Q/'
93 94 95
}

q_to_nul () {
96
	perl -pe 'y/Q/\000/'
97 98 99 100 101 102 103 104 105 106
}

q_to_cr () {
	tr Q '\015'
}

q_to_tab () {
	tr Q '\011'
}

107 108
qz_to_tab_space () {
	tr QZ '\011\040'
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
}

append_cr () {
	sed -e 's/$/Q/' | tr Q '\015'
}

remove_cr () {
	tr '\015' Q | sed -e 's/Q$//'
}

# In some bourne shell implementations, the "unset" builtin returns
# nonzero status when a variable to be unset was not set in the first
# place.
#
# Use sane_unset when that should not be considered an error.

sane_unset () {
	unset "$@"
	return 0
}

test_tick () {
	if test -z "${test_tick+set}"
	then
		test_tick=1112911993
	else
		test_tick=$(($test_tick + 60))
	fi
	GIT_COMMITTER_DATE="$test_tick -0700"
	GIT_AUTHOR_DATE="$test_tick -0700"
	export GIT_COMMITTER_DATE GIT_AUTHOR_DATE
}

142
# Stop execution and start a shell. This is useful for debugging tests.
143 144 145 146
#
# Be sure to remove all invocations of this command before submitting.

test_pause () {
147
	"$SHELL_PATH" <&6 >&5 2>&7
148 149
}

150 151
# Wrap git with a debugger. Adding this to a command can make it easier
# to understand what is going on in a failing test.
152
#
153 154 155 156
# Examples:
#     debug git checkout master
#     debug --debugger=nemiver git $ARGS
#     debug -d "valgrind --tool=memcheck --track-origins=yes" git $ARGS
157
debug () {
158 159 160 161 162 163 164 165 166 167 168 169 170 171
	case "$1" in
	-d)
		GIT_DEBUGGER="$2" &&
		shift 2
		;;
	--debugger=*)
		GIT_DEBUGGER="${1#*=}" &&
		shift 1
		;;
	*)
		GIT_DEBUGGER=1
		;;
	esac &&
	GIT_DEBUGGER="${GIT_DEBUGGER}" "$@" <&6 >&5 2>&7
172 173
}

174 175
# Call test_commit with the arguments
# [-C <directory>] <message> [<file> [<contents> [<tag>]]]"
176 177
#
# This will commit a file with the given contents and the given commit
178
# message, and tag the resulting commit with the given tag name.
179
#
180
# <file>, <contents>, and <tag> all default to <message>.
181 182 183
#
# If the first argument is "-C", the second argument is used as a path for
# the git invocations.
184 185

test_commit () {
186
	notick= &&
187
	signoff= &&
188
	indir= &&
189 190 191 192 193 194 195 196 197
	while test $# != 0
	do
		case "$1" in
		--notick)
			notick=yes
			;;
		--signoff)
			signoff="$1"
			;;
198 199 200 201
		-C)
			indir="$2"
			shift
			;;
202 203 204 205
		*)
			break
			;;
		esac
206
		shift
207
	done &&
208
	indir=${indir:+"$indir"/} &&
209
	file=${2:-"$1.t"} &&
210 211
	echo "${3-$1}" > "$indir$file" &&
	git ${indir:+ -C "$indir"} add "$file" &&
212 213 214 215
	if test -z "$notick"
	then
		test_tick
	fi &&
216 217
	git ${indir:+ -C "$indir"} commit $signoff -m "$1" &&
	git ${indir:+ -C "$indir"} tag "${4:-$1}"
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
}

# Call test_merge with the arguments "<message> <commit>", where <commit>
# can be a tag pointing to the commit-to-merge.

test_merge () {
	test_tick &&
	git merge -m "$1" "$2" &&
	git tag "$1"
}

# This function helps systems where core.filemode=false is set.
# Use it instead of plain 'chmod +x' to set or unset the executable bit
# of a file in the working directory and add it to the index.

test_chmod () {
	chmod "$@" &&
	git update-index --add "--chmod=$@"
}

238 239 240 241 242
# Get the modebits from a file.
test_modebits () {
	ls -l "$1" | sed -e 's|^\(..........\).*|\1|'
}

243 244
# Unset a configuration variable, but don't fail if it doesn't exist.
test_unconfig () {
245 246 247 248 249 250 251 252
	config_dir=
	if test "$1" = -C
	then
		shift
		config_dir=$1
		shift
	fi
	git ${config_dir:+-C "$config_dir"} config --unset-all "$@"
253 254 255 256 257 258 259 260 261 262 263
	config_status=$?
	case "$config_status" in
	5) # ok, nothing to unset
		config_status=0
		;;
	esac
	return $config_status
}

# Set git config, automatically unsetting it after the test is over.
test_config () {
264 265 266 267 268 269 270 271 272
	config_dir=
	if test "$1" = -C
	then
		shift
		config_dir=$1
		shift
	fi
	test_when_finished "test_unconfig ${config_dir:+-C '$config_dir'} '$1'" &&
	git ${config_dir:+-C "$config_dir"} config "$@"
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
}

test_config_global () {
	test_when_finished "test_unconfig --global '$1'" &&
	git config --global "$@"
}

write_script () {
	{
		echo "#!${2-"$SHELL_PATH"}" &&
		cat
	} >"$1" &&
	chmod +x "$1"
}

# Use test_set_prereq to tell that a particular prerequisite is available.
# The prerequisite can later be checked for in two ways:
#
# - Explicitly using test_have_prereq.
#
# - Implicitly by specifying the prerequisite tag in the calls to
#   test_expect_{success,failure,code}.
#
# The single parameter is the prerequisite tag (a simple word, in all
# capital letters by convention).

299 300 301 302 303
test_unset_prereq () {
	! test_have_prereq "$1" ||
	satisfied_prereq="${satisfied_prereq% $1 *} ${satisfied_prereq#* $1 }"
}

304
test_set_prereq () {
305 306 307 308 309 310 311 312
	case "$1" in
	!*)
		test_unset_prereq "${1#!}"
		;;
	*)
		satisfied_prereq="$satisfied_prereq$1 "
		;;
	esac
313
}
314
satisfied_prereq=" "
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
lazily_testable_prereq= lazily_tested_prereq=

# Usage: test_lazy_prereq PREREQ 'script'
test_lazy_prereq () {
	lazily_testable_prereq="$lazily_testable_prereq$1 "
	eval test_prereq_lazily_$1=\$2
}

test_run_lazy_prereq_ () {
	script='
mkdir -p "$TRASH_DIRECTORY/prereq-test-dir" &&
(
	cd "$TRASH_DIRECTORY/prereq-test-dir" &&'"$2"'
)'
	say >&3 "checking prerequisite: $1"
	say >&3 "$script"
	test_eval_ "$script"
	eval_ret=$?
	rm -rf "$TRASH_DIRECTORY/prereq-test-dir"
	if test "$eval_ret" = 0; then
		say >&3 "prerequisite $1 ok"
	else
		say >&3 "prerequisite $1 not satisfied"
	fi
	return $eval_ret
}
341 342 343 344 345 346 347 348 349 350 351 352 353 354

test_have_prereq () {
	# prerequisites can be concatenated with ','
	save_IFS=$IFS
	IFS=,
	set -- $*
	IFS=$save_IFS

	total_prereq=0
	ok_prereq=0
	missing_prereq=

	for prerequisite
	do
355 356 357 358 359 360 361 362 363
		case "$prerequisite" in
		!*)
			negative_prereq=t
			prerequisite=${prerequisite#!}
			;;
		*)
			negative_prereq=
		esac

364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
		case " $lazily_tested_prereq " in
		*" $prerequisite "*)
			;;
		*)
			case " $lazily_testable_prereq " in
			*" $prerequisite "*)
				eval "script=\$test_prereq_lazily_$prerequisite" &&
				if test_run_lazy_prereq_ "$prerequisite" "$script"
				then
					test_set_prereq $prerequisite
				fi
				lazily_tested_prereq="$lazily_tested_prereq$prerequisite "
			esac
			;;
		esac

380
		total_prereq=$(($total_prereq + 1))
381
		case "$satisfied_prereq" in
382
		*" $prerequisite "*)
383 384 385 386 387 388 389 390
			satisfied_this_prereq=t
			;;
		*)
			satisfied_this_prereq=
		esac

		case "$satisfied_this_prereq,$negative_prereq" in
		t,|,t)
391 392 393
			ok_prereq=$(($ok_prereq + 1))
			;;
		*)
394 395 396
			# Keep a list of missing prerequisites; restore
			# the negative marker if necessary.
			prerequisite=${negative_prereq:+!}$prerequisite
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
			if test -z "$missing_prereq"
			then
				missing_prereq=$prerequisite
			else
				missing_prereq="$prerequisite,$missing_prereq"
			fi
		esac
	done

	test $total_prereq = $ok_prereq
}

test_declared_prereq () {
	case ",$test_prereq," in
	*,$1,*)
		return 0
		;;
	esac
	return 1
}

418 419 420 421 422 423
test_verify_prereq () {
	test -z "$test_prereq" ||
	expr >/dev/null "$test_prereq" : '[A-Z0-9_,!]*$' ||
	error "bug in the test script: '$test_prereq' does not look like a prereq"
}

424
test_expect_failure () {
425
	test_start_
426 427 428
	test "$#" = 3 && { test_prereq=$1; shift; } || test_prereq=
	test "$#" = 2 ||
	error "bug in the test script: not 2 or 3 parameters to test-expect-failure"
429
	test_verify_prereq
430 431 432 433 434 435 436 437 438 439 440
	export test_prereq
	if ! test_skip "$@"
	then
		say >&3 "checking known breakage: $2"
		if test_run_ "$2" expecting_failure
		then
			test_known_broken_ok_ "$1"
		else
			test_known_broken_failure_ "$1"
		fi
	fi
441
	test_finish_
442 443 444
}

test_expect_success () {
445
	test_start_
446 447 448
	test "$#" = 3 && { test_prereq=$1; shift; } || test_prereq=
	test "$#" = 2 ||
	error "bug in the test script: not 2 or 3 parameters to test-expect-success"
449
	test_verify_prereq
450 451 452 453 454 455 456 457 458 459 460
	export test_prereq
	if ! test_skip "$@"
	then
		say >&3 "expecting success: $2"
		if test_run_ "$2"
		then
			test_ok_ "$1"
		else
			test_failure_ "$@"
		fi
	fi
461
	test_finish_
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
}

# test_external runs external test scripts that provide continuous
# test output about their progress, and succeeds/fails on
# zero/non-zero exit code.  It outputs the test output on stdout even
# in non-verbose mode, and announces the external script with "# run
# <n>: ..." before running it.  When providing relative paths, keep in
# mind that all scripts run in "trash directory".
# Usage: test_external description command arguments...
# Example: test_external 'Perl API' perl ../path/to/test.pl
test_external () {
	test "$#" = 4 && { test_prereq=$1; shift; } || test_prereq=
	test "$#" = 3 ||
	error >&5 "bug in the test script: not 3 or 4 parameters to test_external"
	descr="$1"
	shift
478
	test_verify_prereq
479 480 481 482 483 484 485 486 487 488 489 490 491
	export test_prereq
	if ! test_skip "$descr" "$@"
	then
		# Announce the script to reduce confusion about the
		# test output that follows.
		say_color "" "# run $test_count: $descr ($*)"
		# Export TEST_DIRECTORY, TRASH_DIRECTORY and GIT_TEST_LONG
		# to be able to use them in script
		export TEST_DIRECTORY TRASH_DIRECTORY GIT_TEST_LONG
		# Run command; redirect its stderr to &4 as in
		# test_run_, but keep its stdout on our stdout even in
		# non-verbose mode.
		"$@" 2>&4
492
		if test "$?" = 0
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
		then
			if test $test_external_has_tap -eq 0; then
				test_ok_ "$descr"
			else
				say_color "" "# test_external test $descr was ok"
				test_success=$(($test_success + 1))
			fi
		else
			if test $test_external_has_tap -eq 0; then
				test_failure_ "$descr" "$@"
			else
				say_color error "# test_external test $descr failed: $@"
				test_failure=$(($test_failure + 1))
			fi
		fi
	fi
}

# Like test_external, but in addition tests that the command generated
# no output on stderr.
test_external_without_stderr () {
	# The temporary file has no (and must have no) security
	# implications.
	tmp=${TMPDIR:-/tmp}
	stderr="$tmp/git-external-stderr.$$.tmp"
	test_external "$@" 4> "$stderr"
519
	test -f "$stderr" || error "Internal error: $stderr disappeared."
520 521 522
	descr="no stderr: $1"
	shift
	say >&3 "# expecting no stderr from previous command"
523 524
	if test ! -s "$stderr"
	then
525 526 527 528 529 530 531 532 533
		rm "$stderr"

		if test $test_external_has_tap -eq 0; then
			test_ok_ "$descr"
		else
			say_color "" "# test_external_without_stderr test $descr was ok"
			test_success=$(($test_success + 1))
		fi
	else
534 535 536
		if test "$verbose" = t
		then
			output=$(echo; echo "# Stderr is:"; cat "$stderr")
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
		else
			output=
		fi
		# rm first in case test_failure exits.
		rm "$stderr"
		if test $test_external_has_tap -eq 0; then
			test_failure_ "$descr" "$@" "$output"
		else
			say_color error "# test_external_without_stderr test $descr failed: $@: $output"
			test_failure=$(($test_failure + 1))
		fi
	fi
}

# debugging-friendly alternatives to "test [-f|-d|-e]"
# The commands test the existence or non-existence of $1. $2 can be
# given to provide a more precise diagnosis.
test_path_is_file () {
555
	if ! test -f "$1"
556
	then
557
		echo "File $1 doesn't exist. $2"
558 559 560 561 562
		false
	fi
}

test_path_is_dir () {
563
	if ! test -d "$1"
564
	then
565
		echo "Directory $1 doesn't exist. $2"
566 567 568 569
		false
	fi
}

570 571 572 573 574 575 576 577
test_path_exists () {
	if ! test -e "$1"
	then
		echo "Path $1 doesn't exist. $2"
		false
	fi
}

J
Jens Lehmann 已提交
578 579 580 581 582 583 584 585 586 587 588
# Check if the directory exists and is empty as expected, barf otherwise.
test_dir_is_empty () {
	test_path_is_dir "$1" &&
	if test -n "$(ls -a1 "$1" | egrep -v '^\.\.?$')"
	then
		echo "Directory '$1' is not empty, it contains:"
		ls -la "$1"
		return 1
	fi
}

589
test_path_is_missing () {
590
	if test -e "$1"
591 592 593
	then
		echo "Path exists:"
		ls -ld "$1"
594 595
		if test $# -ge 1
		then
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
			echo "$*"
		fi
		false
	fi
}

# test_line_count checks that a file has the number of lines it
# ought to. For example:
#
#	test_expect_success 'produce exactly one line of output' '
#		do something >output &&
#		test_line_count = 1 output
#	'
#
# is like "test $(wc -l <output) = 1" except that it passes the
# output through when the number of lines is wrong.

test_line_count () {
	if test $# != 3
	then
		error "bug in the test script: not 3 parameters to test_line_count"
	elif ! test $(wc -l <"$3") "$1" "$2"
	then
		echo "test_line_count: line count for $3 !$1 $2"
		cat "$3"
		return 1
	fi
}

625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
# Returns success if a comma separated string of keywords ($1) contains a
# given keyword ($2).
# Examples:
# `list_contains "foo,bar" bar` returns 0
# `list_contains "foo" bar` returns 1

list_contains () {
	case ",$1," in
	*,$2,*)
		return 0
		;;
	esac
	return 1
}

640 641 642 643 644 645 646 647 648 649 650
# This is not among top-level (test_expect_success | test_expect_failure)
# but is a prefix that can be used in the test script, like:
#
#	test_expect_success 'complain and die' '
#           do something &&
#           do something else &&
#	    test_must_fail git checkout ../outerspace
#	'
#
# Writing this as "! git checkout ../outerspace" is wrong, because
# the failure could be due to a segv.  We want a controlled failure.
651 652 653 654 655 656 657 658
#
# Accepts the following options:
#
#   ok=<signal-name>[,<...>]:
#     Don't treat an exit caused by the given signal as error.
#     Multiple signals can be specified as a comma separated list.
#     Currently recognized signal names are: sigpipe, success.
#     (Don't use 'success', use 'test_might_fail' instead.)
659 660

test_must_fail () {
661 662 663 664 665 666 667 668 669
	case "$1" in
	ok=*)
		_test_ok=${1#ok=}
		shift
		;;
	*)
		_test_ok=
		;;
	esac
670
	"$@" 2>&7
671
	exit_code=$?
672 673
	if test $exit_code -eq 0 && ! list_contains "$_test_ok" success
	then
674
		echo >&4 "test_must_fail: command succeeded: $*"
675
		return 1
676
	elif test_match_signal 13 $exit_code && list_contains "$_test_ok" sigpipe
677 678
	then
		return 0
679 680
	elif test $exit_code -gt 129 && test $exit_code -le 192
	then
681
		echo >&4 "test_must_fail: died by signal $(($exit_code - 128)): $*"
682
		return 1
683 684
	elif test $exit_code -eq 127
	then
685
		echo >&4 "test_must_fail: command not found: $*"
686
		return 1
687 688
	elif test $exit_code -eq 126
	then
689
		echo >&4 "test_must_fail: valgrind error: $*"
690
		return 1
691 692
	fi
	return 0
693
} 7>&2 2>&4
694 695 696 697 698 699 700 701 702 703 704

# Similar to test_must_fail, but tolerates success, too.  This is
# meant to be used in contexts like:
#
#	test_expect_success 'some command works without configuration' '
#		test_might_fail git config --unset all.configuration &&
#		do something
#	'
#
# Writing "git config --unset all.configuration || :" would be wrong,
# because we want to notice if it fails due to segv.
705 706
#
# Accepts the same options as test_must_fail.
707 708

test_might_fail () {
709 710
	test_must_fail ok=success "$@" 2>&7
} 7>&2 2>&4
711 712 713 714 715 716 717 718 719 720 721

# Similar to test_must_fail and test_might_fail, but check that a
# given command exited with a given exit code. Meant to be used as:
#
#	test_expect_success 'Merge with d/f conflicts' '
#		test_expect_code 1 git merge "merge msg" B master
#	'

test_expect_code () {
	want_code=$1
	shift
722
	"$@" 2>&7
723 724 725 726 727 728
	exit_code=$?
	if test $exit_code = $want_code
	then
		return 0
	fi

729
	echo >&4 "test_expect_code: command exited with $exit_code, we wanted $want_code $*"
730
	return 1
731
} 7>&2 2>&4
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749

# test_cmp is a helper function to compare actual and expected output.
# You can use it like:
#
#	test_expect_success 'foo works' '
#		echo expected >expected &&
#		foo >actual &&
#		test_cmp expected actual
#	'
#
# This could be written as either "cmp" or "diff -u", but:
# - cmp's output is not nearly as easy to read as diff -u
# - not all diff versions understand "-u"

test_cmp() {
	$GIT_TEST_CMP "$@"
}

750 751 752 753 754 755
# test_cmp_bin - helper to compare binary files

test_cmp_bin() {
	cmp "$@"
}

756 757 758 759 760 761 762 763 764 765 766 767 768 769
# Use this instead of test_cmp to compare files that contain expected and
# actual output from git commands that can be translated.  When running
# under GETTEXT_POISON this pretends that the command produced expected
# results.
test_i18ncmp () {
	test -n "$GETTEXT_POISON" || test_cmp "$@"
}

# Use this instead of "grep expected-string actual" to see if the
# output from a git command that can be translated either contains an
# expected string, or does not contain an unwanted one.  When running
# under GETTEXT_POISON this pretends that the command produced expected
# results.
test_i18ngrep () {
770 771 772 773 774 775 776 777 778 779 780 781
	eval "last_arg=\${$#}"

	test -f "$last_arg" ||
	error "bug in the test script: test_i18ngrep requires a file" \
	      "to read as the last parameter"

	if test $# -lt 2 ||
	   { test "x!" = "x$1" && test $# -lt 3 ; }
	then
		error "bug in the test script: too few parameters to test_i18ngrep"
	fi

782 783
	if test -n "$GETTEXT_POISON"
	then
784 785 786 787 788
		# pretend success
		return 0
	fi

	if test "x!" = "x$1"
789 790
	then
		shift
791 792
		! grep "$@" && return 0

793
		echo >&4 "error: '! grep $@' did find a match in:"
794
	else
795 796
		grep "$@" && return 0

797
		echo >&4 "error: 'grep $@' didn't find a match in:"
798
	fi
799 800 801

	if test -s "$last_arg"
	then
802
		cat >&4 "$last_arg"
803
	else
804
		echo >&4 "<File '$last_arg' is empty>"
805 806 807
	fi

	return 1
808 809
}

810 811 812 813 814
# Call any command "$@" but be more verbose about its
# failure. This is handy for commands like "test" which do
# not output anything when they fail.
verbose () {
	"$@" && return 0
815
	echo >&4 "command failed: $(git rev-parse --sq-quote "$@")"
816 817 818
	return 1
}

J
Junio C Hamano 已提交
819 820 821 822
# Check if the file expected to be empty is indeed empty, and barfs
# otherwise.

test_must_be_empty () {
823 824
	test_path_is_file "$1" &&
	if test -s "$1"
J
Junio C Hamano 已提交
825 826 827 828 829 830 831
	then
		echo "'$1' is not empty, it contains:"
		cat "$1"
		return 1
	fi
}

832 833 834 835 836 837 838
# Tests that its two parameters refer to the same revision
test_cmp_rev () {
	git rev-parse --verify "$1" >expect.rev &&
	git rev-parse --verify "$2" >actual.rev &&
	test_cmp expect.rev actual.rev
}

839 840
# Print a sequence of integers in increasing order, either with
# two arguments (start and end):
M
Michał Kiedrowicz 已提交
841
#
842 843 844 845
#     test_seq 1 5 -- outputs 1 2 3 4 5 one line at a time
#
# or with one argument (end), in which case it starts counting
# from 1.
M
Michał Kiedrowicz 已提交
846 847 848 849 850 851 852

test_seq () {
	case $# in
	1)	set 1 "$@" ;;
	2)	;;
	*)	error "bug in the test script: not 1 or 2 parameters to test_seq" ;;
	esac
853 854 855 856 857 858
	test_seq_counter__=$1
	while test "$test_seq_counter__" -le "$2"
	do
		echo "$test_seq_counter__"
		test_seq_counter__=$(( $test_seq_counter__ + 1 ))
	done
M
Michał Kiedrowicz 已提交
859 860
}

861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
# This function can be used to schedule some commands to be run
# unconditionally at the end of the test to restore sanity:
#
#	test_expect_success 'test core.capslock' '
#		git config core.capslock true &&
#		test_when_finished "git config --unset core.capslock" &&
#		hello world
#	'
#
# That would be roughly equivalent to
#
#	test_expect_success 'test core.capslock' '
#		git config core.capslock true &&
#		hello world
#		git config --unset core.capslock
#	'
#
# except that the greeting and config --unset must both succeed for
# the test to pass.
#
# Note that under --immediate mode, no clean-up is done to help diagnose
# what went wrong.

test_when_finished () {
885 886 887 888 889
	# We cannot detect when we are in a subshell in general, but by
	# doing so on Bash is better than nothing (the test will
	# silently pass on other shells).
	test "${BASH_SUBSHELL-0}" = 0 ||
	error "bug in test script: test_when_finished does nothing in a subshell"
890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
	test_cleanup="{ $*
		} && (exit \"\$eval_ret\"); eval_ret=\$?; $test_cleanup"
}

# Most tests can use the created repository, but some may need to create more.
# Usage: test_create_repo <directory>
test_create_repo () {
	test "$#" = 1 ||
	error "bug in the test script: not 1 parameter to test-create-repo"
	repo="$1"
	mkdir -p "$repo"
	(
		cd "$repo" || error "Cannot setup test environment"
		"$GIT_EXEC_PATH/git-init" "--template=$GIT_BUILD_DIR/templates/blt/" >&3 2>&4 ||
		error "cannot run git init -- have you built things yet?"
		mv .git/hooks .git/hooks-disabled
	) || exit
}
J
Johannes Sixt 已提交
908 909 910 911 912 913 914 915 916 917 918 919 920 921

# This function helps on symlink challenged file systems when it is not
# important that the file system entry is a symbolic link.
# Use test_ln_s_add instead of "ln -s x y && git add y" to add a
# symbolic link entry y to the index.

test_ln_s_add () {
	if test_have_prereq SYMLINKS
	then
		ln -s "$1" "$2" &&
		git update-index --add "$2"
	else
		printf '%s' "$1" >"$2" &&
		ln_s_obj=$(git hash-object -w "$2") &&
922 923 924
		git update-index --add --cacheinfo 120000 $ln_s_obj "$2" &&
		# pick up stat info from the file
		git update-index "$2"
J
Johannes Sixt 已提交
925 926
	fi
}
927

928 929 930 931 932
# This function writes out its parameters, one per line
test_write_lines () {
	printf "%s\n" "$@"
}

933
perl () {
934 935
	command "$PERL_PATH" "$@" 2>&7
} 7>&2 2>&4
936

937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
# Is the value one of the various ways to spell a boolean true/false?
test_normalize_bool () {
	git -c magic.variable="$1" config --bool magic.variable 2>/dev/null
}

# Given a variable $1, normalize the value of it to one of "true",
# "false", or "auto" and store the result to it.
#
#     test_tristate GIT_TEST_HTTPD
#
# A variable set to an empty string is set to 'false'.
# A variable set to 'false' or 'auto' keeps its value.
# Anything else is set to 'true'.
# An unset variable defaults to 'auto'.
#
# The last rule is to allow people to set the variable to an empty
# string and export it to decline testing the particular feature
# for versions both before and after this change.  We used to treat
# both unset and empty variable as a signal for "do not test" and
# took any non-empty string as "please test".

test_tristate () {
	if eval "test x\"\${$1+isset}\" = xisset"
	then
		# explicitly set
		eval "
			case \"\$$1\" in
			'')	$1=false ;;
			auto)	;;
			*)	$1=\$(test_normalize_bool \$$1 || echo true) ;;
			esac
		"
	else
		eval "$1=auto"
	fi
}

# Exit the test suite, either by skipping all remaining tests or by
# exiting with an error. If "$1" is "auto", we then we assume we were
# opportunistically trying to set up some tests and we skip. If it is
# "true", then we report a failure.
#
# The error/skip message should be given by $2.
#
test_skip_or_die () {
	case "$1" in
	auto)
		skip_all=$2
		test_done
		;;
	true)
		error "$2"
		;;
	*)
		error "BUG: test tristate is '$1' (real error: $2)"
	esac
}

995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
# The following mingw_* functions obey POSIX shell syntax, but are actually
# bash scripts, and are meant to be used only with bash on Windows.

# A test_cmp function that treats LF and CRLF equal and avoids to fork
# diff when possible.
mingw_test_cmp () {
	# Read text into shell variables and compare them. If the results
	# are different, use regular diff to report the difference.
	local test_cmp_a= test_cmp_b=

	# When text came from stdin (one argument is '-') we must feed it
	# to diff.
	local stdin_for_diff=

	# Since it is difficult to detect the difference between an
	# empty input file and a failure to read the files, we go straight
	# to diff if one of the inputs is empty.
	if test -s "$1" && test -s "$2"
	then
		# regular case: both files non-empty
		mingw_read_file_strip_cr_ test_cmp_a <"$1"
		mingw_read_file_strip_cr_ test_cmp_b <"$2"
	elif test -s "$1" && test "$2" = -
	then
		# read 2nd file from stdin
		mingw_read_file_strip_cr_ test_cmp_a <"$1"
		mingw_read_file_strip_cr_ test_cmp_b
		stdin_for_diff='<<<"$test_cmp_b"'
	elif test "$1" = - && test -s "$2"
	then
		# read 1st file from stdin
		mingw_read_file_strip_cr_ test_cmp_a
		mingw_read_file_strip_cr_ test_cmp_b <"$2"
		stdin_for_diff='<<<"$test_cmp_a"'
	fi
	test -n "$test_cmp_a" &&
	test -n "$test_cmp_b" &&
	test "$test_cmp_a" = "$test_cmp_b" ||
	eval "diff -u \"\$@\" $stdin_for_diff"
}

# $1 is the name of the shell variable to fill in
mingw_read_file_strip_cr_ () {
	# Read line-wise using LF as the line separator
	# and use IFS to strip CR.
	local line
	while :
	do
		if IFS=$'\r' read -r -d $'\n' line
		then
			# good
			line=$line$'\n'
		else
			# we get here at EOF, but also if the last line
			# was not terminated by LF; in the latter case,
			# some text was read
			if test -z "$line"
			then
				# EOF, really
				break
			fi
		fi
		eval "$1=\$$1\$line"
	done
}
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074

# Like "env FOO=BAR some-program", but run inside a subshell, which means
# it also works for shell functions (though those functions cannot impact
# the environment outside of the test_env invocation).
test_env () {
	(
		while test $# -gt 0
		do
			case "$1" in
			*=*)
				eval "${1%%=*}=\${1#*=}"
				eval "export ${1%%=*}"
				shift
				;;
			*)
1075
				"$@" 2>&7
1076 1077 1078 1079 1080
				exit
				;;
			esac
		done
	)
1081
} 7>&2 2>&4
1082

1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
# Returns true if the numeric exit code in "$2" represents the expected signal
# in "$1". Signals should be given numerically.
test_match_signal () {
	if test "$2" = "$((128 + $1))"
	then
		# POSIX
		return 0
	elif test "$2" = "$((256 + $1))"
	then
		# ksh
		return 0
	fi
	return 1
}
1097

1098 1099 1100 1101 1102 1103 1104 1105
# Read up to "$1" bytes (or to EOF) from stdin and write them to stdout.
test_copy_bytes () {
	perl -e '
		my $len = $ARGV[1];
		while ($len > 0) {
			my $s;
			my $nread = sysread(STDIN, $s, $len);
			die "cannot read: $!" unless defined($nread);
J
Jeff King 已提交
1106
			last unless $nread;
1107 1108 1109 1110 1111
			print $s;
			$len -= $nread;
		}
	' - "$1"
}
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122

# run "$@" inside a non-git directory
nongit () {
	test -d non-repo ||
	mkdir non-repo ||
	return 1

	(
		GIT_CEILING_DIRECTORIES=$(pwd) &&
		export GIT_CEILING_DIRECTORIES &&
		cd non-repo &&
1123
		"$@" 2>&7
1124
	)
1125
} 7>&2 2>&4
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159

# convert stdin to pktline representation; note that empty input becomes an
# empty packet, not a flush packet (for that you can just print 0000 yourself).
packetize() {
	cat >packetize.tmp &&
	len=$(wc -c <packetize.tmp) &&
	printf '%04x%s' "$(($len + 4))" &&
	cat packetize.tmp &&
	rm -f packetize.tmp
}

# Parse the input as a series of pktlines, writing the result to stdout.
# Sideband markers are removed automatically, and the output is routed to
# stderr if appropriate.
#
# NUL bytes are converted to "\\0" for ease of parsing with text tools.
depacketize () {
	perl -e '
		while (read(STDIN, $len, 4) == 4) {
			if ($len eq "0000") {
				print "FLUSH\n";
			} else {
				read(STDIN, $buf, hex($len) - 4);
				$buf =~ s/\0/\\0/g;
				if ($buf =~ s/^[\x2\x3]//) {
					print STDERR $buf;
				} else {
					$buf =~ s/^\x1//;
					print $buf;
				}
			}
		}
	'
}
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228

# Set the hash algorithm in use to $1.  Only useful when testing the testsuite.
test_set_hash () {
	test_hash_algo="$1"
}

# Detect the hash algorithm in use.
test_detect_hash () {
	# Currently we only support SHA-1, but in the future this function will
	# actually detect the algorithm in use.
	test_hash_algo='sha1'
}

# Load common hash metadata and common placeholder object IDs for use with
# test_oid.
test_oid_init () {
	test -n "$test_hash_algo" || test_detect_hash &&
	test_oid_cache <"$TEST_DIRECTORY/oid-info/hash-info" &&
	test_oid_cache <"$TEST_DIRECTORY/oid-info/oid"
}

# Load key-value pairs from stdin suitable for use with test_oid.  Blank lines
# and lines starting with "#" are ignored.  Keys must be shell identifier
# characters.
#
# Examples:
# rawsz sha1:20
# rawsz sha256:32
test_oid_cache () {
	local tag rest k v &&

	{ test -n "$test_hash_algo" || test_detect_hash; } &&
	while read tag rest
	do
		case $tag in
		\#*)
			continue;;
		?*)
			# non-empty
			;;
		*)
			# blank line
			continue;;
		esac &&

		k="${rest%:*}" &&
		v="${rest#*:}" &&

		if ! expr "$k" : '[a-z0-9][a-z0-9]*$' >/dev/null
		then
			error 'bug in the test script: bad hash algorithm'
		fi &&
		eval "test_oid_${k}_$tag=\"\$v\""
	done
}

# Look up a per-hash value based on a key ($1).  The value must have been loaded
# by test_oid_init or test_oid_cache.
test_oid () {
	local var="test_oid_${test_hash_algo}_$1" &&

	# If the variable is unset, we must be missing an entry for this
	# key-hash pair, so exit with an error.
	if eval "test -z \"\${$var+set}\""
	then
		error "bug in the test script: undefined key '$1'" >&2
	fi &&
	eval "printf '%s' \"\${$var}\""
}