t / test-lib-functions.shon commit Merge branch 'pw/prompt-cherry-pick-revert-fix' (8a4acc5)
   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.
  28test_set_editor () {
  29        FAKE_EDITOR="$1"
  30        export FAKE_EDITOR
  31        EDITOR='"$FAKE_EDITOR"'
  32        export EDITOR
  33}
  34
  35test_set_index_version () {
  36    GIT_INDEX_VERSION="$1"
  37    export GIT_INDEX_VERSION
  38}
  39
  40test_decode_color () {
  41        awk '
  42                function name(n) {
  43                        if (n == 0) return "RESET";
  44                        if (n == 1) return "BOLD";
  45                        if (n == 2) return "FAINT";
  46                        if (n == 3) return "ITALIC";
  47                        if (n == 7) return "REVERSE";
  48                        if (n == 30) return "BLACK";
  49                        if (n == 31) return "RED";
  50                        if (n == 32) return "GREEN";
  51                        if (n == 33) return "YELLOW";
  52                        if (n == 34) return "BLUE";
  53                        if (n == 35) return "MAGENTA";
  54                        if (n == 36) return "CYAN";
  55                        if (n == 37) return "WHITE";
  56                        if (n == 40) return "BLACK";
  57                        if (n == 41) return "BRED";
  58                        if (n == 42) return "BGREEN";
  59                        if (n == 43) return "BYELLOW";
  60                        if (n == 44) return "BBLUE";
  61                        if (n == 45) return "BMAGENTA";
  62                        if (n == 46) return "BCYAN";
  63                        if (n == 47) return "BWHITE";
  64                }
  65                {
  66                        while (match($0, /\033\[[0-9;]*m/) != 0) {
  67                                printf "%s<", substr($0, 1, RSTART-1);
  68                                codes = substr($0, RSTART+2, RLENGTH-3);
  69                                if (length(codes) == 0)
  70                                        printf "%s", name(0)
  71                                else {
  72                                        n = split(codes, ary, ";");
  73                                        sep = "";
  74                                        for (i = 1; i <= n; i++) {
  75                                                printf "%s%s", sep, name(ary[i]);
  76                                                sep = ";"
  77                                        }
  78                                }
  79                                printf ">";
  80                                $0 = substr($0, RSTART + RLENGTH, length($0) - RSTART - RLENGTH + 1);
  81                        }
  82                        print
  83                }
  84        '
  85}
  86
  87lf_to_nul () {
  88        perl -pe 'y/\012/\000/'
  89}
  90
  91nul_to_q () {
  92        perl -pe 'y/\000/Q/'
  93}
  94
  95q_to_nul () {
  96        perl -pe 'y/Q/\000/'
  97}
  98
  99q_to_cr () {
 100        tr Q '\015'
 101}
 102
 103q_to_tab () {
 104        tr Q '\011'
 105}
 106
 107qz_to_tab_space () {
 108        tr QZ '\011\040'
 109}
 110
 111append_cr () {
 112        sed -e 's/$/Q/' | tr Q '\015'
 113}
 114
 115remove_cr () {
 116        tr '\015' Q | sed -e 's/Q$//'
 117}
 118
 119# Generate an output of $1 bytes of all zeroes (NULs, not ASCII zeroes).
 120# If $1 is 'infinity', output forever or until the receiving pipe stops reading,
 121# whichever comes first.
 122generate_zero_bytes () {
 123        test-tool genzeros "$@"
 124}
 125
 126# In some bourne shell implementations, the "unset" builtin returns
 127# nonzero status when a variable to be unset was not set in the first
 128# place.
 129#
 130# Use sane_unset when that should not be considered an error.
 131
 132sane_unset () {
 133        unset "$@"
 134        return 0
 135}
 136
 137test_tick () {
 138        if test -z "${test_tick+set}"
 139        then
 140                test_tick=1112911993
 141        else
 142                test_tick=$(($test_tick + 60))
 143        fi
 144        GIT_COMMITTER_DATE="$test_tick -0700"
 145        GIT_AUTHOR_DATE="$test_tick -0700"
 146        export GIT_COMMITTER_DATE GIT_AUTHOR_DATE
 147}
 148
 149# Stop execution and start a shell. This is useful for debugging tests.
 150#
 151# Be sure to remove all invocations of this command before submitting.
 152
 153test_pause () {
 154        "$SHELL_PATH" <&6 >&5 2>&7
 155}
 156
 157# Wrap git with a debugger. Adding this to a command can make it easier
 158# to understand what is going on in a failing test.
 159#
 160# Examples:
 161#     debug git checkout master
 162#     debug --debugger=nemiver git $ARGS
 163#     debug -d "valgrind --tool=memcheck --track-origins=yes" git $ARGS
 164debug () {
 165        case "$1" in
 166        -d)
 167                GIT_DEBUGGER="$2" &&
 168                shift 2
 169                ;;
 170        --debugger=*)
 171                GIT_DEBUGGER="${1#*=}" &&
 172                shift 1
 173                ;;
 174        *)
 175                GIT_DEBUGGER=1
 176                ;;
 177        esac &&
 178        GIT_DEBUGGER="${GIT_DEBUGGER}" "$@" <&6 >&5 2>&7
 179}
 180
 181# Call test_commit with the arguments
 182# [-C <directory>] <message> [<file> [<contents> [<tag>]]]"
 183#
 184# This will commit a file with the given contents and the given commit
 185# message, and tag the resulting commit with the given tag name.
 186#
 187# <file>, <contents>, and <tag> all default to <message>.
 188#
 189# If the first argument is "-C", the second argument is used as a path for
 190# the git invocations.
 191
 192test_commit () {
 193        notick= &&
 194        signoff= &&
 195        indir= &&
 196        while test $# != 0
 197        do
 198                case "$1" in
 199                --notick)
 200                        notick=yes
 201                        ;;
 202                --signoff)
 203                        signoff="$1"
 204                        ;;
 205                -C)
 206                        indir="$2"
 207                        shift
 208                        ;;
 209                *)
 210                        break
 211                        ;;
 212                esac
 213                shift
 214        done &&
 215        indir=${indir:+"$indir"/} &&
 216        file=${2:-"$1.t"} &&
 217        echo "${3-$1}" > "$indir$file" &&
 218        git ${indir:+ -C "$indir"} add "$file" &&
 219        if test -z "$notick"
 220        then
 221                test_tick
 222        fi &&
 223        git ${indir:+ -C "$indir"} commit $signoff -m "$1" &&
 224        git ${indir:+ -C "$indir"} tag "${4:-$1}"
 225}
 226
 227# Call test_merge with the arguments "<message> <commit>", where <commit>
 228# can be a tag pointing to the commit-to-merge.
 229
 230test_merge () {
 231        test_tick &&
 232        git merge -m "$1" "$2" &&
 233        git tag "$1"
 234}
 235
 236# This function helps systems where core.filemode=false is set.
 237# Use it instead of plain 'chmod +x' to set or unset the executable bit
 238# of a file in the working directory and add it to the index.
 239
 240test_chmod () {
 241        chmod "$@" &&
 242        git update-index --add "--chmod=$@"
 243}
 244
 245# Get the modebits from a file.
 246test_modebits () {
 247        ls -l "$1" | sed -e 's|^\(..........\).*|\1|'
 248}
 249
 250# Unset a configuration variable, but don't fail if it doesn't exist.
 251test_unconfig () {
 252        config_dir=
 253        if test "$1" = -C
 254        then
 255                shift
 256                config_dir=$1
 257                shift
 258        fi
 259        git ${config_dir:+-C "$config_dir"} config --unset-all "$@"
 260        config_status=$?
 261        case "$config_status" in
 262        5) # ok, nothing to unset
 263                config_status=0
 264                ;;
 265        esac
 266        return $config_status
 267}
 268
 269# Set git config, automatically unsetting it after the test is over.
 270test_config () {
 271        config_dir=
 272        if test "$1" = -C
 273        then
 274                shift
 275                config_dir=$1
 276                shift
 277        fi
 278        test_when_finished "test_unconfig ${config_dir:+-C '$config_dir'} '$1'" &&
 279        git ${config_dir:+-C "$config_dir"} config "$@"
 280}
 281
 282test_config_global () {
 283        test_when_finished "test_unconfig --global '$1'" &&
 284        git config --global "$@"
 285}
 286
 287write_script () {
 288        {
 289                echo "#!${2-"$SHELL_PATH"}" &&
 290                cat
 291        } >"$1" &&
 292        chmod +x "$1"
 293}
 294
 295# Use test_set_prereq to tell that a particular prerequisite is available.
 296# The prerequisite can later be checked for in two ways:
 297#
 298# - Explicitly using test_have_prereq.
 299#
 300# - Implicitly by specifying the prerequisite tag in the calls to
 301#   test_expect_{success,failure,code}.
 302#
 303# The single parameter is the prerequisite tag (a simple word, in all
 304# capital letters by convention).
 305
 306test_unset_prereq () {
 307        ! test_have_prereq "$1" ||
 308        satisfied_prereq="${satisfied_prereq% $1 *} ${satisfied_prereq#* $1 }"
 309}
 310
 311test_set_prereq () {
 312        if test -n "$GIT_TEST_FAIL_PREREQS"
 313        then
 314                case "$1" in
 315                # The "!" case is handled below with
 316                # test_unset_prereq()
 317                !*)
 318                        ;;
 319                # (Temporary?) whitelist of things we can't easily
 320                # pretend not to support
 321                SYMLINKS)
 322                        ;;
 323                # Inspecting whether GIT_TEST_FAIL_PREREQS is on
 324                # should be unaffected.
 325                FAIL_PREREQS)
 326                        ;;
 327                *)
 328                        return
 329                esac
 330        fi
 331
 332        case "$1" in
 333        !*)
 334                test_unset_prereq "${1#!}"
 335                ;;
 336        *)
 337                satisfied_prereq="$satisfied_prereq$1 "
 338                ;;
 339        esac
 340}
 341satisfied_prereq=" "
 342lazily_testable_prereq= lazily_tested_prereq=
 343
 344# Usage: test_lazy_prereq PREREQ 'script'
 345test_lazy_prereq () {
 346        lazily_testable_prereq="$lazily_testable_prereq$1 "
 347        eval test_prereq_lazily_$1=\$2
 348}
 349
 350test_run_lazy_prereq_ () {
 351        script='
 352mkdir -p "$TRASH_DIRECTORY/prereq-test-dir" &&
 353(
 354        cd "$TRASH_DIRECTORY/prereq-test-dir" &&'"$2"'
 355)'
 356        say >&3 "checking prerequisite: $1"
 357        say >&3 "$script"
 358        test_eval_ "$script"
 359        eval_ret=$?
 360        rm -rf "$TRASH_DIRECTORY/prereq-test-dir"
 361        if test "$eval_ret" = 0; then
 362                say >&3 "prerequisite $1 ok"
 363        else
 364                say >&3 "prerequisite $1 not satisfied"
 365        fi
 366        return $eval_ret
 367}
 368
 369test_have_prereq () {
 370        # prerequisites can be concatenated with ','
 371        save_IFS=$IFS
 372        IFS=,
 373        set -- $*
 374        IFS=$save_IFS
 375
 376        total_prereq=0
 377        ok_prereq=0
 378        missing_prereq=
 379
 380        for prerequisite
 381        do
 382                case "$prerequisite" in
 383                !*)
 384                        negative_prereq=t
 385                        prerequisite=${prerequisite#!}
 386                        ;;
 387                *)
 388                        negative_prereq=
 389                esac
 390
 391                case " $lazily_tested_prereq " in
 392                *" $prerequisite "*)
 393                        ;;
 394                *)
 395                        case " $lazily_testable_prereq " in
 396                        *" $prerequisite "*)
 397                                eval "script=\$test_prereq_lazily_$prerequisite" &&
 398                                if test_run_lazy_prereq_ "$prerequisite" "$script"
 399                                then
 400                                        test_set_prereq $prerequisite
 401                                fi
 402                                lazily_tested_prereq="$lazily_tested_prereq$prerequisite "
 403                        esac
 404                        ;;
 405                esac
 406
 407                total_prereq=$(($total_prereq + 1))
 408                case "$satisfied_prereq" in
 409                *" $prerequisite "*)
 410                        satisfied_this_prereq=t
 411                        ;;
 412                *)
 413                        satisfied_this_prereq=
 414                esac
 415
 416                case "$satisfied_this_prereq,$negative_prereq" in
 417                t,|,t)
 418                        ok_prereq=$(($ok_prereq + 1))
 419                        ;;
 420                *)
 421                        # Keep a list of missing prerequisites; restore
 422                        # the negative marker if necessary.
 423                        prerequisite=${negative_prereq:+!}$prerequisite
 424                        if test -z "$missing_prereq"
 425                        then
 426                                missing_prereq=$prerequisite
 427                        else
 428                                missing_prereq="$prerequisite,$missing_prereq"
 429                        fi
 430                esac
 431        done
 432
 433        test $total_prereq = $ok_prereq
 434}
 435
 436test_declared_prereq () {
 437        case ",$test_prereq," in
 438        *,$1,*)
 439                return 0
 440                ;;
 441        esac
 442        return 1
 443}
 444
 445test_verify_prereq () {
 446        test -z "$test_prereq" ||
 447        expr >/dev/null "$test_prereq" : '[A-Z0-9_,!]*$' ||
 448        BUG "'$test_prereq' does not look like a prereq"
 449}
 450
 451test_expect_failure () {
 452        test_start_
 453        test "$#" = 3 && { test_prereq=$1; shift; } || test_prereq=
 454        test "$#" = 2 ||
 455        BUG "not 2 or 3 parameters to test-expect-failure"
 456        test_verify_prereq
 457        export test_prereq
 458        if ! test_skip "$@"
 459        then
 460                say >&3 "checking known breakage: $2"
 461                if test_run_ "$2" expecting_failure
 462                then
 463                        test_known_broken_ok_ "$1"
 464                else
 465                        test_known_broken_failure_ "$1"
 466                fi
 467        fi
 468        test_finish_
 469}
 470
 471test_expect_success () {
 472        test_start_
 473        test "$#" = 3 && { test_prereq=$1; shift; } || test_prereq=
 474        test "$#" = 2 ||
 475        BUG "not 2 or 3 parameters to test-expect-success"
 476        test_verify_prereq
 477        export test_prereq
 478        if ! test_skip "$@"
 479        then
 480                say >&3 "expecting success: $2"
 481                if test_run_ "$2"
 482                then
 483                        test_ok_ "$1"
 484                else
 485                        test_failure_ "$@"
 486                fi
 487        fi
 488        test_finish_
 489}
 490
 491# test_external runs external test scripts that provide continuous
 492# test output about their progress, and succeeds/fails on
 493# zero/non-zero exit code.  It outputs the test output on stdout even
 494# in non-verbose mode, and announces the external script with "# run
 495# <n>: ..." before running it.  When providing relative paths, keep in
 496# mind that all scripts run in "trash directory".
 497# Usage: test_external description command arguments...
 498# Example: test_external 'Perl API' perl ../path/to/test.pl
 499test_external () {
 500        test "$#" = 4 && { test_prereq=$1; shift; } || test_prereq=
 501        test "$#" = 3 ||
 502        BUG "not 3 or 4 parameters to test_external"
 503        descr="$1"
 504        shift
 505        test_verify_prereq
 506        export test_prereq
 507        if ! test_skip "$descr" "$@"
 508        then
 509                # Announce the script to reduce confusion about the
 510                # test output that follows.
 511                say_color "" "# run $test_count: $descr ($*)"
 512                # Export TEST_DIRECTORY, TRASH_DIRECTORY and GIT_TEST_LONG
 513                # to be able to use them in script
 514                export TEST_DIRECTORY TRASH_DIRECTORY GIT_TEST_LONG
 515                # Run command; redirect its stderr to &4 as in
 516                # test_run_, but keep its stdout on our stdout even in
 517                # non-verbose mode.
 518                "$@" 2>&4
 519                if test "$?" = 0
 520                then
 521                        if test $test_external_has_tap -eq 0; then
 522                                test_ok_ "$descr"
 523                        else
 524                                say_color "" "# test_external test $descr was ok"
 525                                test_success=$(($test_success + 1))
 526                        fi
 527                else
 528                        if test $test_external_has_tap -eq 0; then
 529                                test_failure_ "$descr" "$@"
 530                        else
 531                                say_color error "# test_external test $descr failed: $@"
 532                                test_failure=$(($test_failure + 1))
 533                        fi
 534                fi
 535        fi
 536}
 537
 538# Like test_external, but in addition tests that the command generated
 539# no output on stderr.
 540test_external_without_stderr () {
 541        # The temporary file has no (and must have no) security
 542        # implications.
 543        tmp=${TMPDIR:-/tmp}
 544        stderr="$tmp/git-external-stderr.$$.tmp"
 545        test_external "$@" 4> "$stderr"
 546        test -f "$stderr" || error "Internal error: $stderr disappeared."
 547        descr="no stderr: $1"
 548        shift
 549        say >&3 "# expecting no stderr from previous command"
 550        if test ! -s "$stderr"
 551        then
 552                rm "$stderr"
 553
 554                if test $test_external_has_tap -eq 0; then
 555                        test_ok_ "$descr"
 556                else
 557                        say_color "" "# test_external_without_stderr test $descr was ok"
 558                        test_success=$(($test_success + 1))
 559                fi
 560        else
 561                if test "$verbose" = t
 562                then
 563                        output=$(echo; echo "# Stderr is:"; cat "$stderr")
 564                else
 565                        output=
 566                fi
 567                # rm first in case test_failure exits.
 568                rm "$stderr"
 569                if test $test_external_has_tap -eq 0; then
 570                        test_failure_ "$descr" "$@" "$output"
 571                else
 572                        say_color error "# test_external_without_stderr test $descr failed: $@: $output"
 573                        test_failure=$(($test_failure + 1))
 574                fi
 575        fi
 576}
 577
 578# debugging-friendly alternatives to "test [-f|-d|-e]"
 579# The commands test the existence or non-existence of $1. $2 can be
 580# given to provide a more precise diagnosis.
 581test_path_is_file () {
 582        if ! test -f "$1"
 583        then
 584                echo "File $1 doesn't exist. $2"
 585                false
 586        fi
 587}
 588
 589test_path_is_dir () {
 590        if ! test -d "$1"
 591        then
 592                echo "Directory $1 doesn't exist. $2"
 593                false
 594        fi
 595}
 596
 597test_path_exists () {
 598        if ! test -e "$1"
 599        then
 600                echo "Path $1 doesn't exist. $2"
 601                false
 602        fi
 603}
 604
 605# Check if the directory exists and is empty as expected, barf otherwise.
 606test_dir_is_empty () {
 607        test_path_is_dir "$1" &&
 608        if test -n "$(ls -a1 "$1" | egrep -v '^\.\.?$')"
 609        then
 610                echo "Directory '$1' is not empty, it contains:"
 611                ls -la "$1"
 612                return 1
 613        fi
 614}
 615
 616# Check if the file exists and has a size greater than zero
 617test_file_not_empty () {
 618        if ! test -s "$1"
 619        then
 620                echo "'$1' is not a non-empty file."
 621                false
 622        fi
 623}
 624
 625test_path_is_missing () {
 626        if test -e "$1"
 627        then
 628                echo "Path exists:"
 629                ls -ld "$1"
 630                if test $# -ge 1
 631                then
 632                        echo "$*"
 633                fi
 634                false
 635        fi
 636}
 637
 638# test_line_count checks that a file has the number of lines it
 639# ought to. For example:
 640#
 641#       test_expect_success 'produce exactly one line of output' '
 642#               do something >output &&
 643#               test_line_count = 1 output
 644#       '
 645#
 646# is like "test $(wc -l <output) = 1" except that it passes the
 647# output through when the number of lines is wrong.
 648
 649test_line_count () {
 650        if test $# != 3
 651        then
 652                BUG "not 3 parameters to test_line_count"
 653        elif ! test $(wc -l <"$3") "$1" "$2"
 654        then
 655                echo "test_line_count: line count for $3 !$1 $2"
 656                cat "$3"
 657                return 1
 658        fi
 659}
 660
 661# Returns success if a comma separated string of keywords ($1) contains a
 662# given keyword ($2).
 663# Examples:
 664# `list_contains "foo,bar" bar` returns 0
 665# `list_contains "foo" bar` returns 1
 666
 667list_contains () {
 668        case ",$1," in
 669        *,$2,*)
 670                return 0
 671                ;;
 672        esac
 673        return 1
 674}
 675
 676# This is not among top-level (test_expect_success | test_expect_failure)
 677# but is a prefix that can be used in the test script, like:
 678#
 679#       test_expect_success 'complain and die' '
 680#           do something &&
 681#           do something else &&
 682#           test_must_fail git checkout ../outerspace
 683#       '
 684#
 685# Writing this as "! git checkout ../outerspace" is wrong, because
 686# the failure could be due to a segv.  We want a controlled failure.
 687#
 688# Accepts the following options:
 689#
 690#   ok=<signal-name>[,<...>]:
 691#     Don't treat an exit caused by the given signal as error.
 692#     Multiple signals can be specified as a comma separated list.
 693#     Currently recognized signal names are: sigpipe, success.
 694#     (Don't use 'success', use 'test_might_fail' instead.)
 695
 696test_must_fail () {
 697        case "$1" in
 698        ok=*)
 699                _test_ok=${1#ok=}
 700                shift
 701                ;;
 702        *)
 703                _test_ok=
 704                ;;
 705        esac
 706        "$@" 2>&7
 707        exit_code=$?
 708        if test $exit_code -eq 0 && ! list_contains "$_test_ok" success
 709        then
 710                echo >&4 "test_must_fail: command succeeded: $*"
 711                return 1
 712        elif test_match_signal 13 $exit_code && list_contains "$_test_ok" sigpipe
 713        then
 714                return 0
 715        elif test $exit_code -gt 129 && test $exit_code -le 192
 716        then
 717                echo >&4 "test_must_fail: died by signal $(($exit_code - 128)): $*"
 718                return 1
 719        elif test $exit_code -eq 127
 720        then
 721                echo >&4 "test_must_fail: command not found: $*"
 722                return 1
 723        elif test $exit_code -eq 126
 724        then
 725                echo >&4 "test_must_fail: valgrind error: $*"
 726                return 1
 727        fi
 728        return 0
 729} 7>&2 2>&4
 730
 731# Similar to test_must_fail, but tolerates success, too.  This is
 732# meant to be used in contexts like:
 733#
 734#       test_expect_success 'some command works without configuration' '
 735#               test_might_fail git config --unset all.configuration &&
 736#               do something
 737#       '
 738#
 739# Writing "git config --unset all.configuration || :" would be wrong,
 740# because we want to notice if it fails due to segv.
 741#
 742# Accepts the same options as test_must_fail.
 743
 744test_might_fail () {
 745        test_must_fail ok=success "$@" 2>&7
 746} 7>&2 2>&4
 747
 748# Similar to test_must_fail and test_might_fail, but check that a
 749# given command exited with a given exit code. Meant to be used as:
 750#
 751#       test_expect_success 'Merge with d/f conflicts' '
 752#               test_expect_code 1 git merge "merge msg" B master
 753#       '
 754
 755test_expect_code () {
 756        want_code=$1
 757        shift
 758        "$@" 2>&7
 759        exit_code=$?
 760        if test $exit_code = $want_code
 761        then
 762                return 0
 763        fi
 764
 765        echo >&4 "test_expect_code: command exited with $exit_code, we wanted $want_code $*"
 766        return 1
 767} 7>&2 2>&4
 768
 769# test_cmp is a helper function to compare actual and expected output.
 770# You can use it like:
 771#
 772#       test_expect_success 'foo works' '
 773#               echo expected >expected &&
 774#               foo >actual &&
 775#               test_cmp expected actual
 776#       '
 777#
 778# This could be written as either "cmp" or "diff -u", but:
 779# - cmp's output is not nearly as easy to read as diff -u
 780# - not all diff versions understand "-u"
 781
 782test_cmp() {
 783        $GIT_TEST_CMP "$@"
 784}
 785
 786# Check that the given config key has the expected value.
 787#
 788#    test_cmp_config [-C <dir>] <expected-value>
 789#                    [<git-config-options>...] <config-key>
 790#
 791# for example to check that the value of core.bar is foo
 792#
 793#    test_cmp_config foo core.bar
 794#
 795test_cmp_config() {
 796        local GD &&
 797        if test "$1" = "-C"
 798        then
 799                shift &&
 800                GD="-C $1" &&
 801                shift
 802        fi &&
 803        printf "%s\n" "$1" >expect.config &&
 804        shift &&
 805        git $GD config "$@" >actual.config &&
 806        test_cmp expect.config actual.config
 807}
 808
 809# test_cmp_bin - helper to compare binary files
 810
 811test_cmp_bin() {
 812        cmp "$@"
 813}
 814
 815# Use this instead of test_cmp to compare files that contain expected and
 816# actual output from git commands that can be translated.  When running
 817# under GIT_TEST_GETTEXT_POISON this pretends that the command produced expected
 818# results.
 819test_i18ncmp () {
 820        ! test_have_prereq C_LOCALE_OUTPUT || test_cmp "$@"
 821}
 822
 823# Use this instead of "grep expected-string actual" to see if the
 824# output from a git command that can be translated either contains an
 825# expected string, or does not contain an unwanted one.  When running
 826# under GIT_TEST_GETTEXT_POISON this pretends that the command produced expected
 827# results.
 828test_i18ngrep () {
 829        eval "last_arg=\${$#}"
 830
 831        test -f "$last_arg" ||
 832        BUG "test_i18ngrep requires a file to read as the last parameter"
 833
 834        if test $# -lt 2 ||
 835           { test "x!" = "x$1" && test $# -lt 3 ; }
 836        then
 837                BUG "too few parameters to test_i18ngrep"
 838        fi
 839
 840        if test_have_prereq !C_LOCALE_OUTPUT
 841        then
 842                # pretend success
 843                return 0
 844        fi
 845
 846        if test "x!" = "x$1"
 847        then
 848                shift
 849                ! grep "$@" && return 0
 850
 851                echo >&4 "error: '! grep $@' did find a match in:"
 852        else
 853                grep "$@" && return 0
 854
 855                echo >&4 "error: 'grep $@' didn't find a match in:"
 856        fi
 857
 858        if test -s "$last_arg"
 859        then
 860                cat >&4 "$last_arg"
 861        else
 862                echo >&4 "<File '$last_arg' is empty>"
 863        fi
 864
 865        return 1
 866}
 867
 868# Call any command "$@" but be more verbose about its
 869# failure. This is handy for commands like "test" which do
 870# not output anything when they fail.
 871verbose () {
 872        "$@" && return 0
 873        echo >&4 "command failed: $(git rev-parse --sq-quote "$@")"
 874        return 1
 875}
 876
 877# Check if the file expected to be empty is indeed empty, and barfs
 878# otherwise.
 879
 880test_must_be_empty () {
 881        test_path_is_file "$1" &&
 882        if test -s "$1"
 883        then
 884                echo "'$1' is not empty, it contains:"
 885                cat "$1"
 886                return 1
 887        fi
 888}
 889
 890# Tests that its two parameters refer to the same revision
 891test_cmp_rev () {
 892        if test $# != 2
 893        then
 894                error "bug in the test script: test_cmp_rev requires two revisions, but got $#"
 895        else
 896                local r1 r2
 897                r1=$(git rev-parse --verify "$1") &&
 898                r2=$(git rev-parse --verify "$2") &&
 899                if test "$r1" != "$r2"
 900                then
 901                        cat >&4 <<-EOF
 902                        error: two revisions point to different objects:
 903                          '$1': $r1
 904                          '$2': $r2
 905                        EOF
 906                        return 1
 907                fi
 908        fi
 909}
 910
 911# Compare paths respecting core.ignoreCase
 912test_cmp_fspath () {
 913        if test "x$1" = "x$2"
 914        then
 915                return 0
 916        fi
 917
 918        if test true != "$(git config --get --type=bool core.ignorecase)"
 919        then
 920                return 1
 921        fi
 922
 923        test "x$(echo "$1" | tr A-Z a-z)" =  "x$(echo "$2" | tr A-Z a-z)"
 924}
 925
 926# Print a sequence of integers in increasing order, either with
 927# two arguments (start and end):
 928#
 929#     test_seq 1 5 -- outputs 1 2 3 4 5 one line at a time
 930#
 931# or with one argument (end), in which case it starts counting
 932# from 1.
 933
 934test_seq () {
 935        case $# in
 936        1)      set 1 "$@" ;;
 937        2)      ;;
 938        *)      BUG "not 1 or 2 parameters to test_seq" ;;
 939        esac
 940        test_seq_counter__=$1
 941        while test "$test_seq_counter__" -le "$2"
 942        do
 943                echo "$test_seq_counter__"
 944                test_seq_counter__=$(( $test_seq_counter__ + 1 ))
 945        done
 946}
 947
 948# This function can be used to schedule some commands to be run
 949# unconditionally at the end of the test to restore sanity:
 950#
 951#       test_expect_success 'test core.capslock' '
 952#               git config core.capslock true &&
 953#               test_when_finished "git config --unset core.capslock" &&
 954#               hello world
 955#       '
 956#
 957# That would be roughly equivalent to
 958#
 959#       test_expect_success 'test core.capslock' '
 960#               git config core.capslock true &&
 961#               hello world
 962#               git config --unset core.capslock
 963#       '
 964#
 965# except that the greeting and config --unset must both succeed for
 966# the test to pass.
 967#
 968# Note that under --immediate mode, no clean-up is done to help diagnose
 969# what went wrong.
 970
 971test_when_finished () {
 972        # We cannot detect when we are in a subshell in general, but by
 973        # doing so on Bash is better than nothing (the test will
 974        # silently pass on other shells).
 975        test "${BASH_SUBSHELL-0}" = 0 ||
 976        BUG "test_when_finished does nothing in a subshell"
 977        test_cleanup="{ $*
 978                } && (exit \"\$eval_ret\"); eval_ret=\$?; $test_cleanup"
 979}
 980
 981# This function can be used to schedule some commands to be run
 982# unconditionally at the end of the test script, e.g. to stop a daemon:
 983#
 984#       test_expect_success 'test git daemon' '
 985#               git daemon &
 986#               daemon_pid=$! &&
 987#               test_atexit 'kill $daemon_pid' &&
 988#               hello world
 989#       '
 990#
 991# The commands will be executed before the trash directory is removed,
 992# i.e. the atexit commands will still be able to access any pidfiles or
 993# socket files.
 994#
 995# Note that these commands will be run even when a test script run
 996# with '--immediate' fails.  Be careful with your atexit commands to
 997# minimize any changes to the failed state.
 998
 999test_atexit () {
1000        # We cannot detect when we are in a subshell in general, but by
1001        # doing so on Bash is better than nothing (the test will
1002        # silently pass on other shells).
1003        test "${BASH_SUBSHELL-0}" = 0 ||
1004        error "bug in test script: test_atexit does nothing in a subshell"
1005        test_atexit_cleanup="{ $*
1006                } && (exit \"\$eval_ret\"); eval_ret=\$?; $test_atexit_cleanup"
1007}
1008
1009# Most tests can use the created repository, but some may need to create more.
1010# Usage: test_create_repo <directory>
1011test_create_repo () {
1012        test "$#" = 1 ||
1013        BUG "not 1 parameter to test-create-repo"
1014        repo="$1"
1015        mkdir -p "$repo"
1016        (
1017                cd "$repo" || error "Cannot setup test environment"
1018                "${GIT_TEST_INSTALLED:-$GIT_EXEC_PATH}/git$X" init \
1019                        "--template=$GIT_BUILD_DIR/templates/blt/" >&3 2>&4 ||
1020                error "cannot run git init -- have you built things yet?"
1021                mv .git/hooks .git/hooks-disabled
1022        ) || exit
1023}
1024
1025# This function helps on symlink challenged file systems when it is not
1026# important that the file system entry is a symbolic link.
1027# Use test_ln_s_add instead of "ln -s x y && git add y" to add a
1028# symbolic link entry y to the index.
1029
1030test_ln_s_add () {
1031        if test_have_prereq SYMLINKS
1032        then
1033                ln -s "$1" "$2" &&
1034                git update-index --add "$2"
1035        else
1036                printf '%s' "$1" >"$2" &&
1037                ln_s_obj=$(git hash-object -w "$2") &&
1038                git update-index --add --cacheinfo 120000 $ln_s_obj "$2" &&
1039                # pick up stat info from the file
1040                git update-index "$2"
1041        fi
1042}
1043
1044# This function writes out its parameters, one per line
1045test_write_lines () {
1046        printf "%s\n" "$@"
1047}
1048
1049perl () {
1050        command "$PERL_PATH" "$@" 2>&7
1051} 7>&2 2>&4
1052
1053# Is the value one of the various ways to spell a boolean true/false?
1054test_normalize_bool () {
1055        git -c magic.variable="$1" config --bool magic.variable 2>/dev/null
1056}
1057
1058# Given a variable $1, normalize the value of it to one of "true",
1059# "false", or "auto" and store the result to it.
1060#
1061#     test_tristate GIT_TEST_HTTPD
1062#
1063# A variable set to an empty string is set to 'false'.
1064# A variable set to 'false' or 'auto' keeps its value.
1065# Anything else is set to 'true'.
1066# An unset variable defaults to 'auto'.
1067#
1068# The last rule is to allow people to set the variable to an empty
1069# string and export it to decline testing the particular feature
1070# for versions both before and after this change.  We used to treat
1071# both unset and empty variable as a signal for "do not test" and
1072# took any non-empty string as "please test".
1073
1074test_tristate () {
1075        if eval "test x\"\${$1+isset}\" = xisset"
1076        then
1077                # explicitly set
1078                eval "
1079                        case \"\$$1\" in
1080                        '')     $1=false ;;
1081                        auto)   ;;
1082                        *)      $1=\$(test_normalize_bool \$$1 || echo true) ;;
1083                        esac
1084                "
1085        else
1086                eval "$1=auto"
1087        fi
1088}
1089
1090# Exit the test suite, either by skipping all remaining tests or by
1091# exiting with an error. If "$1" is "auto", we then we assume we were
1092# opportunistically trying to set up some tests and we skip. If it is
1093# "true", then we report a failure.
1094#
1095# The error/skip message should be given by $2.
1096#
1097test_skip_or_die () {
1098        case "$1" in
1099        auto)
1100                skip_all=$2
1101                test_done
1102                ;;
1103        true)
1104                error "$2"
1105                ;;
1106        *)
1107                error "BUG: test tristate is '$1' (real error: $2)"
1108        esac
1109}
1110
1111# The following mingw_* functions obey POSIX shell syntax, but are actually
1112# bash scripts, and are meant to be used only with bash on Windows.
1113
1114# A test_cmp function that treats LF and CRLF equal and avoids to fork
1115# diff when possible.
1116mingw_test_cmp () {
1117        # Read text into shell variables and compare them. If the results
1118        # are different, use regular diff to report the difference.
1119        local test_cmp_a= test_cmp_b=
1120
1121        # When text came from stdin (one argument is '-') we must feed it
1122        # to diff.
1123        local stdin_for_diff=
1124
1125        # Since it is difficult to detect the difference between an
1126        # empty input file and a failure to read the files, we go straight
1127        # to diff if one of the inputs is empty.
1128        if test -s "$1" && test -s "$2"
1129        then
1130                # regular case: both files non-empty
1131                mingw_read_file_strip_cr_ test_cmp_a <"$1"
1132                mingw_read_file_strip_cr_ test_cmp_b <"$2"
1133        elif test -s "$1" && test "$2" = -
1134        then
1135                # read 2nd file from stdin
1136                mingw_read_file_strip_cr_ test_cmp_a <"$1"
1137                mingw_read_file_strip_cr_ test_cmp_b
1138                stdin_for_diff='<<<"$test_cmp_b"'
1139        elif test "$1" = - && test -s "$2"
1140        then
1141                # read 1st file from stdin
1142                mingw_read_file_strip_cr_ test_cmp_a
1143                mingw_read_file_strip_cr_ test_cmp_b <"$2"
1144                stdin_for_diff='<<<"$test_cmp_a"'
1145        fi
1146        test -n "$test_cmp_a" &&
1147        test -n "$test_cmp_b" &&
1148        test "$test_cmp_a" = "$test_cmp_b" ||
1149        eval "diff -u \"\$@\" $stdin_for_diff"
1150}
1151
1152# $1 is the name of the shell variable to fill in
1153mingw_read_file_strip_cr_ () {
1154        # Read line-wise using LF as the line separator
1155        # and use IFS to strip CR.
1156        local line
1157        while :
1158        do
1159                if IFS=$'\r' read -r -d $'\n' line
1160                then
1161                        # good
1162                        line=$line$'\n'
1163                else
1164                        # we get here at EOF, but also if the last line
1165                        # was not terminated by LF; in the latter case,
1166                        # some text was read
1167                        if test -z "$line"
1168                        then
1169                                # EOF, really
1170                                break
1171                        fi
1172                fi
1173                eval "$1=\$$1\$line"
1174        done
1175}
1176
1177# Like "env FOO=BAR some-program", but run inside a subshell, which means
1178# it also works for shell functions (though those functions cannot impact
1179# the environment outside of the test_env invocation).
1180test_env () {
1181        (
1182                while test $# -gt 0
1183                do
1184                        case "$1" in
1185                        *=*)
1186                                eval "${1%%=*}=\${1#*=}"
1187                                eval "export ${1%%=*}"
1188                                shift
1189                                ;;
1190                        *)
1191                                "$@" 2>&7
1192                                exit
1193                                ;;
1194                        esac
1195                done
1196        )
1197} 7>&2 2>&4
1198
1199# Returns true if the numeric exit code in "$2" represents the expected signal
1200# in "$1". Signals should be given numerically.
1201test_match_signal () {
1202        if test "$2" = "$((128 + $1))"
1203        then
1204                # POSIX
1205                return 0
1206        elif test "$2" = "$((256 + $1))"
1207        then
1208                # ksh
1209                return 0
1210        fi
1211        return 1
1212}
1213
1214# Read up to "$1" bytes (or to EOF) from stdin and write them to stdout.
1215test_copy_bytes () {
1216        perl -e '
1217                my $len = $ARGV[1];
1218                while ($len > 0) {
1219                        my $s;
1220                        my $nread = sysread(STDIN, $s, $len);
1221                        die "cannot read: $!" unless defined($nread);
1222                        last unless $nread;
1223                        print $s;
1224                        $len -= $nread;
1225                }
1226        ' - "$1"
1227}
1228
1229# run "$@" inside a non-git directory
1230nongit () {
1231        test -d non-repo ||
1232        mkdir non-repo ||
1233        return 1
1234
1235        (
1236                GIT_CEILING_DIRECTORIES=$(pwd) &&
1237                export GIT_CEILING_DIRECTORIES &&
1238                cd non-repo &&
1239                "$@" 2>&7
1240        )
1241} 7>&2 2>&4
1242
1243# convert stdin to pktline representation; note that empty input becomes an
1244# empty packet, not a flush packet (for that you can just print 0000 yourself).
1245packetize() {
1246        cat >packetize.tmp &&
1247        len=$(wc -c <packetize.tmp) &&
1248        printf '%04x%s' "$(($len + 4))" &&
1249        cat packetize.tmp &&
1250        rm -f packetize.tmp
1251}
1252
1253# Parse the input as a series of pktlines, writing the result to stdout.
1254# Sideband markers are removed automatically, and the output is routed to
1255# stderr if appropriate.
1256#
1257# NUL bytes are converted to "\\0" for ease of parsing with text tools.
1258depacketize () {
1259        perl -e '
1260                while (read(STDIN, $len, 4) == 4) {
1261                        if ($len eq "0000") {
1262                                print "FLUSH\n";
1263                        } else {
1264                                read(STDIN, $buf, hex($len) - 4);
1265                                $buf =~ s/\0/\\0/g;
1266                                if ($buf =~ s/^[\x2\x3]//) {
1267                                        print STDERR $buf;
1268                                } else {
1269                                        $buf =~ s/^\x1//;
1270                                        print $buf;
1271                                }
1272                        }
1273                }
1274        '
1275}
1276
1277# Converts base-16 data into base-8. The output is given as a sequence of
1278# escaped octals, suitable for consumption by 'printf'.
1279hex2oct () {
1280        perl -ne 'printf "\\%03o", hex for /../g'
1281}
1282
1283# Set the hash algorithm in use to $1.  Only useful when testing the testsuite.
1284test_set_hash () {
1285        test_hash_algo="$1"
1286}
1287
1288# Detect the hash algorithm in use.
1289test_detect_hash () {
1290        # Currently we only support SHA-1, but in the future this function will
1291        # actually detect the algorithm in use.
1292        test_hash_algo='sha1'
1293}
1294
1295# Load common hash metadata and common placeholder object IDs for use with
1296# test_oid.
1297test_oid_init () {
1298        test -n "$test_hash_algo" || test_detect_hash &&
1299        test_oid_cache <"$TEST_DIRECTORY/oid-info/hash-info" &&
1300        test_oid_cache <"$TEST_DIRECTORY/oid-info/oid"
1301}
1302
1303# Load key-value pairs from stdin suitable for use with test_oid.  Blank lines
1304# and lines starting with "#" are ignored.  Keys must be shell identifier
1305# characters.
1306#
1307# Examples:
1308# rawsz sha1:20
1309# rawsz sha256:32
1310test_oid_cache () {
1311        local tag rest k v &&
1312
1313        { test -n "$test_hash_algo" || test_detect_hash; } &&
1314        while read tag rest
1315        do
1316                case $tag in
1317                \#*)
1318                        continue;;
1319                ?*)
1320                        # non-empty
1321                        ;;
1322                *)
1323                        # blank line
1324                        continue;;
1325                esac &&
1326
1327                k="${rest%:*}" &&
1328                v="${rest#*:}" &&
1329
1330                if ! expr "$k" : '[a-z0-9][a-z0-9]*$' >/dev/null
1331                then
1332                        BUG 'bad hash algorithm'
1333                fi &&
1334                eval "test_oid_${k}_$tag=\"\$v\""
1335        done
1336}
1337
1338# Look up a per-hash value based on a key ($1).  The value must have been loaded
1339# by test_oid_init or test_oid_cache.
1340test_oid () {
1341        local var="test_oid_${test_hash_algo}_$1" &&
1342
1343        # If the variable is unset, we must be missing an entry for this
1344        # key-hash pair, so exit with an error.
1345        if eval "test -z \"\${$var+set}\""
1346        then
1347                BUG "undefined key '$1'"
1348        fi &&
1349        eval "printf '%s' \"\${$var}\""
1350}
1351
1352# Choose a port number based on the test script's number and store it in
1353# the given variable name, unless that variable already contains a number.
1354test_set_port () {
1355        local var=$1 port
1356
1357        if test $# -ne 1 || test -z "$var"
1358        then
1359                BUG "test_set_port requires a variable name"
1360        fi
1361
1362        eval port=\$$var
1363        case "$port" in
1364        "")
1365                # No port is set in the given env var, use the test
1366                # number as port number instead.
1367                # Remove not only the leading 't', but all leading zeros
1368                # as well, so the arithmetic below won't (mis)interpret
1369                # a test number like '0123' as an octal value.
1370                port=${this_test#${this_test%%[1-9]*}}
1371                if test "${port:-0}" -lt 1024
1372                then
1373                        # root-only port, use a larger one instead.
1374                        port=$(($port + 10000))
1375                fi
1376                ;;
1377        *[!0-9]*|0*)
1378                error >&7 "invalid port number: $port"
1379                ;;
1380        *)
1381                # The user has specified the port.
1382                ;;
1383        esac
1384
1385        # Make sure that parallel '--stress' test jobs get different
1386        # ports.
1387        port=$(($port + ${GIT_TEST_STRESS_JOB_NR:-0}))
1388        eval $var=$port
1389}