]> git.notmuchmail.org Git - notmuch/blob - test/test-lib.sh
test/test-lib.sh: use $test_subtest_name in all tests
[notmuch] / test / test-lib.sh
1 #
2 # Copyright (c) 2005 Junio C Hamano
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 2 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program.  If not, see http://www.gnu.org/licenses/ .
16
17 if [ ${BASH_VERSINFO[0]} -lt 4 ]; then
18     echo "Error: The notmuch test suite requires a bash version >= 4.0"
19     echo "due to use of associative arrays within the test suite."
20     echo "Please try again with a newer bash (or help us fix the"
21     echo "test suite to be more portable). Thanks."
22     exit 1
23 fi
24
25 # if --tee was passed, write the output not only to the terminal, but
26 # additionally to the file test-results/$BASENAME.out, too.
27 case "$GIT_TEST_TEE_STARTED, $* " in
28 done,*)
29         # do not redirect again
30         ;;
31 *' --tee '*|*' --va'*)
32         mkdir -p test-results
33         BASE=test-results/$(basename "$0" .sh)
34         (GIT_TEST_TEE_STARTED=done ${SHELL-sh} "$0" "$@" 2>&1;
35          echo $? > $BASE.exit) | tee $BASE.out
36         test "$(cat $BASE.exit)" = 0
37         exit
38         ;;
39 esac
40
41 # Keep the original TERM for say_color and test_emacs
42 ORIGINAL_TERM=$TERM
43
44 # dtach(1) provides more capable terminal environment to anything
45 # that requires more than dumb terminal...
46 [ x"${TERM:-dumb}" = xdumb ] && DTACH_TERM=vt100 || DTACH_TERM=$TERM
47
48 # For repeatability, reset the environment to known value.
49 LANG=C
50 LC_ALL=C
51 PAGER=cat
52 TZ=UTC
53 TERM=dumb
54 export LANG LC_ALL PAGER TERM TZ
55 GIT_TEST_CMP=${GIT_TEST_CMP:-diff -u}
56 if [[ ( -n "$TEST_EMACS" && -z "$TEST_EMACSCLIENT" ) || \
57       ( -z "$TEST_EMACS" && -n "$TEST_EMACSCLIENT" ) ]]; then
58     echo "error: must specify both or neither of TEST_EMACS and TEST_EMACSCLIENT" >&2
59     exit 1
60 fi
61 TEST_EMACS=${TEST_EMACS:-${EMACS:-emacs}}
62 TEST_EMACSCLIENT=${TEST_EMACSCLIENT:-emacsclient}
63
64 # Protect ourselves from common misconfiguration to export
65 # CDPATH into the environment
66 unset CDPATH
67
68 unset GREP_OPTIONS
69
70 # Convenience
71 #
72 # A regexp to match 5 and 40 hexdigits
73 _x05='[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]'
74 _x40="$_x05$_x05$_x05$_x05$_x05$_x05$_x05$_x05"
75
76 _x04='[0-9a-f][0-9a-f][0-9a-f][0-9a-f]'
77 _x32="$_x04$_x04$_x04$_x04$_x04$_x04$_x04$_x04"
78
79 # Each test should start with something like this, after copyright notices:
80 #
81 # test_description='Description of this test...
82 # This test checks if command xyzzy does the right thing...
83 # '
84 # . ./test-lib.sh
85 [ "x$ORIGINAL_TERM" != "xdumb" ] && (
86                 TERM=$ORIGINAL_TERM &&
87                 export TERM &&
88                 [ -t 1 ] &&
89                 tput bold >/dev/null 2>&1 &&
90                 tput setaf 1 >/dev/null 2>&1 &&
91                 tput sgr0 >/dev/null 2>&1
92         ) &&
93         color=t
94
95 while test "$#" -ne 0
96 do
97         case "$1" in
98         -d|--d|--de|--deb|--debu|--debug)
99                 debug=t; shift ;;
100         -i|--i|--im|--imm|--imme|--immed|--immedi|--immedia|--immediat|--immediate)
101                 immediate=t; shift ;;
102         -l|--l|--lo|--lon|--long|--long-|--long-t|--long-te|--long-tes|--long-test|--long-tests)
103                 GIT_TEST_LONG=t; export GIT_TEST_LONG; shift ;;
104         -h|--h|--he|--hel|--help)
105                 help=t; shift ;;
106         -v|--v|--ve|--ver|--verb|--verbo|--verbos|--verbose)
107                 verbose=t; shift ;;
108         -q|--q|--qu|--qui|--quie|--quiet)
109                 quiet=t; shift ;;
110         --with-dashes)
111                 with_dashes=t; shift ;;
112         --no-color)
113                 color=; shift ;;
114         --no-python)
115                 # noop now...
116                 shift ;;
117         --va|--val|--valg|--valgr|--valgri|--valgrin|--valgrind)
118                 valgrind=t; verbose=t; shift ;;
119         --tee)
120                 shift ;; # was handled already
121         --root=*)
122                 root=$(expr "z$1" : 'z[^=]*=\(.*\)')
123                 shift ;;
124         *)
125                 echo "error: unknown test option '$1'" >&2; exit 1 ;;
126         esac
127 done
128
129 if test -n "$debug"; then
130     print_subtest () {
131         printf " %-4s" "[$((test_count - 1))]"
132     }
133 else
134     print_subtest () {
135         true
136     }
137 fi
138
139 if test -n "$color"; then
140         say_color () {
141                 (
142                 TERM=$ORIGINAL_TERM
143                 export TERM
144                 case "$1" in
145                         error) tput bold; tput setaf 1;; # bold red
146                         skip)  tput bold; tput setaf 2;; # bold green
147                         pass)  tput setaf 2;;            # green
148                         info)  tput setaf 3;;            # brown
149                         *) test -n "$quiet" && return;;
150                 esac
151                 shift
152                 printf " "
153                 printf "$@"
154                 tput sgr0
155                 print_subtest
156                 )
157         }
158 else
159         say_color() {
160                 test -z "$1" && test -n "$quiet" && return
161                 shift
162                 printf " "
163                 printf "$@"
164                 print_subtest
165         }
166 fi
167
168 error () {
169         say_color error "error: $*\n"
170         GIT_EXIT_OK=t
171         exit 1
172 }
173
174 say () {
175         say_color info "$*"
176 }
177
178 test "${test_description}" != "" ||
179 error "Test script did not set test_description."
180
181 if test "$help" = "t"
182 then
183         echo "Tests ${test_description}"
184         exit 0
185 fi
186
187 echo $(basename "$0"): "Testing ${test_description}"
188
189 exec 5>&1
190
191 test_failure=0
192 test_count=0
193 test_fixed=0
194 test_broken=0
195 test_success=0
196
197 die () {
198         code=$?
199         rm -rf "$TEST_TMPDIR"
200         if test -n "$GIT_EXIT_OK"
201         then
202                 exit $code
203         else
204                 exec >&5
205                 say_color error '%-6s' FATAL
206                 echo " $test_subtest_name"
207                 echo
208                 echo "Unexpected exit while executing $0. Exit code $code."
209                 exit 1
210         fi
211 }
212
213 GIT_EXIT_OK=
214 # Note: TEST_TMPDIR *NOT* exported!
215 TEST_TMPDIR=$(mktemp -d "${TMPDIR:-/tmp}/notmuch-test-$$.XXXXXX")
216 trap 'die' EXIT
217
218 test_decode_color () {
219         sed     -e 's/.\[1m/<WHITE>/g' \
220                 -e 's/.\[31m/<RED>/g' \
221                 -e 's/.\[32m/<GREEN>/g' \
222                 -e 's/.\[33m/<YELLOW>/g' \
223                 -e 's/.\[34m/<BLUE>/g' \
224                 -e 's/.\[35m/<MAGENTA>/g' \
225                 -e 's/.\[36m/<CYAN>/g' \
226                 -e 's/.\[m/<RESET>/g'
227 }
228
229 q_to_nul () {
230         perl -pe 'y/Q/\000/'
231 }
232
233 q_to_cr () {
234         tr Q '\015'
235 }
236
237 append_cr () {
238         sed -e 's/$/Q/' | tr Q '\015'
239 }
240
241 remove_cr () {
242         tr '\015' Q | sed -e 's/Q$//'
243 }
244
245 # Generate a new message in the mail directory, with a unique message
246 # ID and subject. The message is not added to the index.
247 #
248 # After this function returns, the filename of the generated message
249 # is available as $gen_msg_filename and the message ID is available as
250 # $gen_msg_id .
251 #
252 # This function supports named parameters with the bash syntax for
253 # assigning a value to an associative array ([name]=value). The
254 # supported parameters are:
255 #
256 #  [dir]=directory/of/choice
257 #
258 #       Generate the message in directory 'directory/of/choice' within
259 #       the mail store. The directory will be created if necessary.
260 #
261 #  [filename]=name
262 #
263 #       Store the message in file 'name'. The default is to store it
264 #       in 'msg-<count>', where <count> is three-digit number of the
265 #       message.
266 #
267 #  [body]=text
268 #
269 #       Text to use as the body of the email message
270 #
271 #  '[from]="Some User <user@example.com>"'
272 #  '[to]="Some User <user@example.com>"'
273 #  '[subject]="Subject of email message"'
274 #  '[date]="RFC 822 Date"'
275 #
276 #       Values for email headers. If not provided, default values will
277 #       be generated instead.
278 #
279 #  '[cc]="Some User <user@example.com>"'
280 #  [reply-to]=some-address
281 #  [in-reply-to]=<message-id>
282 #  [references]=<message-id>
283 #  [content-type]=content-type-specification
284 #  '[header]=full header line, including keyword'
285 #
286 #       Additional values for email headers. If these are not provided
287 #       then the relevant headers will simply not appear in the
288 #       message.
289 #
290 #  '[id]=message-id'
291 #
292 #       Controls the message-id of the created message.
293 gen_msg_cnt=0
294 gen_msg_filename=""
295 gen_msg_id=""
296 generate_message ()
297 {
298     # This is our (bash-specific) magic for doing named parameters
299     local -A template="($@)"
300     local additional_headers
301
302     gen_msg_cnt=$((gen_msg_cnt + 1))
303     if [ -z "${template[filename]}" ]; then
304         gen_msg_name="msg-$(printf "%03d" $gen_msg_cnt)"
305     else
306         gen_msg_name=${template[filename]}
307     fi
308
309     if [ -z "${template[id]}" ]; then
310         gen_msg_id="${gen_msg_name%:2,*}@notmuch-test-suite"
311     else
312         gen_msg_id="${template[id]}"
313     fi
314
315     if [ -z "${template[dir]}" ]; then
316         gen_msg_filename="${MAIL_DIR}/$gen_msg_name"
317     else
318         gen_msg_filename="${MAIL_DIR}/${template[dir]}/$gen_msg_name"
319         mkdir -p "$(dirname "$gen_msg_filename")"
320     fi
321
322     if [ -z "${template[body]}" ]; then
323         template[body]="This is just a test message (#${gen_msg_cnt})"
324     fi
325
326     if [ -z "${template[from]}" ]; then
327         template[from]="Notmuch Test Suite <test_suite@notmuchmail.org>"
328     fi
329
330     if [ -z "${template[to]}" ]; then
331         template[to]="Notmuch Test Suite <test_suite@notmuchmail.org>"
332     fi
333
334     if [ -z "${template[subject]}" ]; then
335         if [ -n "$test_subtest_name" ]; then
336             template[subject]="$test_subtest_name"
337         else
338             template[subject]="Test message #${gen_msg_cnt}"
339         fi
340     fi
341
342     if [ -z "${template[date]}" ]; then
343         template[date]="Fri, 05 Jan 2001 15:43:57 +0000"
344     fi
345
346     additional_headers=""
347     if [ ! -z "${template[header]}" ]; then
348         additional_headers="${template[header]}
349 ${additional_headers}"
350     fi
351
352     if [ ! -z "${template[reply-to]}" ]; then
353         additional_headers="Reply-To: ${template[reply-to]}
354 ${additional_headers}"
355     fi
356
357     if [ ! -z "${template[in-reply-to]}" ]; then
358         additional_headers="In-Reply-To: ${template[in-reply-to]}
359 ${additional_headers}"
360     fi
361
362     if [ ! -z "${template[cc]}" ]; then
363         additional_headers="Cc: ${template[cc]}
364 ${additional_headers}"
365     fi
366
367     if [ ! -z "${template[bcc]}" ]; then
368         additional_headers="Bcc: ${template[bcc]}
369 ${additional_headers}"
370     fi
371
372     if [ ! -z "${template[references]}" ]; then
373         additional_headers="References: ${template[references]}
374 ${additional_headers}"
375     fi
376
377     if [ ! -z "${template[content-type]}" ]; then
378         additional_headers="Content-Type: ${template[content-type]}
379 ${additional_headers}"
380     fi
381
382     if [ ! -z "${template[content-transfer-encoding]}" ]; then
383         additional_headers="Content-Transfer-Encoding: ${template[content-transfer-encoding]}
384 ${additional_headers}"
385     fi
386
387     # Note that in the way we're setting it above and using it below,
388     # `additional_headers' will also serve as the header / body separator
389     # (empty line in between).
390
391     cat <<EOF >"$gen_msg_filename"
392 From: ${template[from]}
393 To: ${template[to]}
394 Message-Id: <${gen_msg_id}>
395 Subject: ${template[subject]}
396 Date: ${template[date]}
397 ${additional_headers}
398 ${template[body]}
399 EOF
400 }
401
402 # Generate a new message and add it to the database.
403 #
404 # All of the arguments and return values supported by generate_message
405 # are also supported here, so see that function for details.
406 add_message ()
407 {
408     generate_message "$@" &&
409     notmuch new > /dev/null
410 }
411
412 # Deliver a message with emacs and add it to the database
413 #
414 # Uses emacs to generate and deliver a message to the mail store.
415 # Accepts arbitrary extra emacs/elisp functions to modify the message
416 # before sending, which is useful to doing things like attaching files
417 # to the message and encrypting/signing.
418 emacs_deliver_message ()
419 {
420     local subject="$1"
421     local body="$2"
422     shift 2
423     # before we can send a message, we have to prepare the FCC maildir
424     mkdir -p "$MAIL_DIR"/sent/{cur,new,tmp}
425     # eval'ing smtp-dummy --background will set smtp_dummy_pid
426     smtp_dummy_pid=
427     eval `$TEST_DIRECTORY/smtp-dummy --background sent_message`
428     test -n "$smtp_dummy_pid" || return 1
429
430     test_emacs \
431         "(let ((message-send-mail-function 'message-smtpmail-send-it)
432                (smtpmail-smtp-server \"localhost\")
433                (smtpmail-smtp-service \"25025\"))
434            (notmuch-hello)
435            (notmuch-mua-mail)
436            (message-goto-to)
437            (insert \"test_suite@notmuchmail.org\nDate: 01 Jan 2000 12:00:00 -0000\")
438            (message-goto-subject)
439            (insert \"${subject}\")
440            (message-goto-body)
441            (insert \"${body}\")
442            $@
443            (message-send-and-exit))"
444
445     # In case message was sent properly, client waits for confirmation
446     # before exiting and resuming control here; therefore making sure
447     # that server exits by sending (KILL) signal to it is safe.
448     kill -9 $smtp_dummy_pid
449     notmuch new >/dev/null
450 }
451
452 # Generate a corpus of email and add it to the database.
453 #
454 # This corpus is fixed, (it happens to be 50 messages from early in
455 # the history of the notmuch mailing list), which allows for reliably
456 # testing commands that need to operate on a not-totally-trivial
457 # number of messages.
458 add_email_corpus ()
459 {
460     rm -rf ${MAIL_DIR}
461     if [ -d $TEST_DIRECTORY/corpus.mail ]; then
462         cp -a $TEST_DIRECTORY/corpus.mail ${MAIL_DIR}
463     else
464         cp -a $TEST_DIRECTORY/corpus ${MAIL_DIR}
465         notmuch new >/dev/null
466         cp -a ${MAIL_DIR} $TEST_DIRECTORY/corpus.mail
467     fi
468 }
469
470 test_begin_subtest ()
471 {
472     if [ -n "$inside_subtest" ]; then
473         exec 1>&6 2>&7          # Restore stdout and stderr
474         error "bug in test script: Missing test_expect_equal in ${BASH_SOURCE[1]}:${BASH_LINENO[0]}"
475     fi
476     test_subtest_name="$1"
477     test_reset_state_
478     # Remember stdout and stderr file descriptors and redirect test
479     # output to the previously prepared file descriptors 3 and 4 (see
480     # below)
481     if test "$verbose" != "t"; then exec 4>test.output 3>&4; fi
482     exec 6>&1 7>&2 >&3 2>&4
483     inside_subtest=t
484 }
485
486 # Pass test if two arguments match
487 #
488 # Note: Unlike all other test_expect_* functions, this function does
489 # not accept a test name. Instead, the caller should call
490 # test_begin_subtest before calling this function in order to set the
491 # name.
492 test_expect_equal ()
493 {
494         exec 1>&6 2>&7          # Restore stdout and stderr
495         inside_subtest=
496         test "$#" = 3 && { prereq=$1; shift; } || prereq=
497         test "$#" = 2 ||
498         error "bug in the test script: not 2 or 3 parameters to test_expect_equal"
499
500         output="$1"
501         expected="$2"
502         if ! test_skip "$test_subtest_name"
503         then
504                 if [ "$output" = "$expected" ]; then
505                         test_ok_
506                 else
507                         testname=$this_test.$test_count
508                         echo "$expected" > $testname.expected
509                         echo "$output" > $testname.output
510                         test_failure_ "$(diff -u $testname.expected $testname.output)"
511                 fi
512     fi
513 }
514
515 # Like test_expect_equal, but takes two filenames.
516 test_expect_equal_file ()
517 {
518         exec 1>&6 2>&7          # Restore stdout and stderr
519         inside_subtest=
520         test "$#" = 3 && { prereq=$1; shift; } || prereq=
521         test "$#" = 2 ||
522         error "bug in the test script: not 2 or 3 parameters to test_expect_equal"
523
524         file1="$1"
525         basename1=`basename "$file1"`
526         file2="$2"
527         basename2=`basename "$file2"`
528         if ! test_skip "$test_subtest_name"
529         then
530                 if diff -q "$file1" "$file2" >/dev/null ; then
531                         test_ok_
532                 else
533                         testname=$this_test.$test_count
534                         cp "$file1" "$testname.$basename1"
535                         cp "$file2" "$testname.$basename2"
536                         test_failure_ "$(diff -u "$testname.$basename1" "$testname.$basename2")"
537                 fi
538     fi
539 }
540
541 # Like test_expect_equal, but arguments are JSON expressions to be
542 # canonicalized before diff'ing.  If an argument cannot be parsed, it
543 # is used unchanged so that there's something to diff against.
544 test_expect_equal_json () {
545     # The test suite forces LC_ALL=C, but this causes Python 3 to
546     # decode stdin as ASCII.  We need to read JSON in UTF-8, so
547     # override Python's stdio encoding defaults.
548     output=$(echo "$1" | PYTHONIOENCODING=utf-8 python -mjson.tool \
549         || echo "$1")
550     expected=$(echo "$2" | PYTHONIOENCODING=utf-8 python -mjson.tool \
551         || echo "$2")
552     shift 2
553     test_expect_equal "$output" "$expected" "$@"
554 }
555
556 test_emacs_expect_t () {
557         test "$#" = 2 && { prereq=$1; shift; } || prereq=
558         test "$#" = 1 ||
559         error "bug in the test script: not 1 or 2 parameters to test_emacs_expect_t"
560
561         # Run the test.
562         if ! test_skip "$test_subtest_name"
563         then
564                 test_emacs "(notmuch-test-run $1)" >/dev/null
565
566                 # Restore state after the test.
567                 exec 1>&6 2>&7          # Restore stdout and stderr
568                 inside_subtest=
569
570                 # Report success/failure.
571                 result=$(cat OUTPUT)
572                 if [ "$result" = t ]
573                 then
574                         test_ok_
575                 else
576                         test_failure_ "${result}"
577                 fi
578         else
579                 # Restore state after the (non) test.
580                 exec 1>&6 2>&7          # Restore stdout and stderr
581                 inside_subtest=
582         fi
583 }
584
585 NOTMUCH_NEW ()
586 {
587     notmuch new "${@}" | grep -v -E -e '^Processed [0-9]*( total)? file|Found [0-9]* total file'
588 }
589
590 notmuch_search_sanitize ()
591 {
592     perl -pe 's/("?thread"?: ?)("?)................("?)/\1\2XXX\3/'
593 }
594
595 NOTMUCH_SHOW_FILENAME_SQUELCH='s,filename:.*/mail,filename:/XXX/mail,'
596 notmuch_show_sanitize ()
597 {
598     sed -e "$NOTMUCH_SHOW_FILENAME_SQUELCH"
599 }
600 notmuch_show_sanitize_all ()
601 {
602     sed \
603         -e 's| filename:.*| filename:XXXXX|' \
604         -e 's| id:[^ ]* | id:XXXXX |'
605 }
606
607 notmuch_json_show_sanitize ()
608 {
609     sed \
610         -e 's|"id": "[^"]*",|"id": "XXXXX",|g' \
611         -e 's|"filename": "/[^"]*",|"filename": "YYYYY",|g'
612 }
613
614 # End of notmuch helper functions
615
616 # Use test_set_prereq to tell that a particular prerequisite is available.
617 # The prerequisite can later be checked for in two ways:
618 #
619 # - Explicitly using test_have_prereq.
620 #
621 # - Implicitly by specifying the prerequisite tag in the calls to
622 #   test_expect_{success,failure,code}.
623 #
624 # The single parameter is the prerequisite tag (a simple word, in all
625 # capital letters by convention).
626
627 test_set_prereq () {
628         satisfied="$satisfied$1 "
629 }
630 satisfied=" "
631
632 test_have_prereq () {
633         case $satisfied in
634         *" $1 "*)
635                 : yes, have it ;;
636         *)
637                 ! : nope ;;
638         esac
639 }
640
641 declare -A test_missing_external_prereq_
642 declare -A test_subtest_missing_external_prereq_
643
644 # declare prerequisite for the given external binary
645 test_declare_external_prereq () {
646         binary="$1"
647         test "$#" = 2 && name=$2 || name="$binary(1)"
648
649         if ! hash $binary 2>/dev/null; then
650                 test_missing_external_prereq_["${binary}"]=t
651                 eval "
652 $binary () {
653         test_subtest_missing_external_prereq_[\"${name}\"]=t
654         false
655 }"
656         fi
657 }
658
659 # Explicitly require external prerequisite.  Useful when binary is
660 # called indirectly (e.g. from emacs).
661 # Returns success if dependency is available, failure otherwise.
662 test_require_external_prereq () {
663         binary="$1"
664         if [[ ${test_missing_external_prereq_["${binary}"]} == t ]]; then
665                 # dependency is missing, call the replacement function to note it
666                 eval "$binary"
667         else
668                 true
669         fi
670 }
671
672 # You are not expected to call test_ok_ and test_failure_ directly, use
673 # the text_expect_* functions instead.
674
675 test_ok_ () {
676         if test "$test_subtest_known_broken_" = "t"; then
677                 test_known_broken_ok_
678                 return
679         fi
680         test_success=$(($test_success + 1))
681         say_color pass "%-6s" "PASS"
682         echo " $test_subtest_name"
683 }
684
685 test_failure_ () {
686         if test "$test_subtest_known_broken_" = "t"; then
687                 test_known_broken_failure_ "$@"
688                 return
689         fi
690         test_failure=$(($test_failure + 1))
691         test_failure_message_ "FAIL" "$test_subtest_name" "$@"
692         test "$immediate" = "" || { GIT_EXIT_OK=t; exit 1; }
693         return 1
694 }
695
696 test_failure_message_ () {
697         say_color error "%-6s" "$1"
698         echo " $2"
699         shift 2
700         echo "$@" | sed -e 's/^/        /'
701         if test "$verbose" != "t"; then cat test.output; fi
702 }
703
704 test_known_broken_ok_ () {
705         test_reset_state_
706         test_fixed=$(($test_fixed+1))
707         say_color pass "%-6s" "FIXED"
708         echo " $test_subtest_name"
709 }
710
711 test_known_broken_failure_ () {
712         test_reset_state_
713         test_broken=$(($test_broken+1))
714         test_failure_message_ "BROKEN" "$test_subtest_name" "$@"
715         return 1
716 }
717
718 test_debug () {
719         test "$debug" = "" || eval "$1"
720 }
721
722 test_run_ () {
723         test_cleanup=:
724         if test "$verbose" != "t"; then exec 4>test.output 3>&4; fi
725         eval >&3 2>&4 "$1"
726         eval_ret=$?
727         eval >&3 2>&4 "$test_cleanup"
728         return 0
729 }
730
731 test_skip () {
732         test_count=$(($test_count+1))
733         to_skip=
734         for skp in $NOTMUCH_SKIP_TESTS
735         do
736                 case $this_test.$test_count in
737                 $skp)
738                         to_skip=t
739                 esac
740         done
741         if test -z "$to_skip" && test -n "$prereq" &&
742            ! test_have_prereq "$prereq"
743         then
744                 to_skip=t
745         fi
746         case "$to_skip" in
747         t)
748                 test_report_skip_ "$@"
749                 ;;
750         *)
751                 test_check_missing_external_prereqs_ "$@"
752                 ;;
753         esac
754 }
755
756 test_check_missing_external_prereqs_ () {
757         if [[ ${#test_subtest_missing_external_prereq_[@]} != 0 ]]; then
758                 say_color skip >&1 "missing prerequisites: "
759                 echo ${!test_subtest_missing_external_prereq_[@]} >&1
760                 test_report_skip_ "$@"
761         else
762                 false
763         fi
764 }
765
766 test_report_skip_ () {
767         test_reset_state_
768         say_color skip >&3 "skipping test:"
769         echo " $@" >&3
770         say_color skip "%-6s" "SKIP"
771         echo " $1"
772 }
773
774 test_subtest_known_broken () {
775         test_subtest_known_broken_=t
776 }
777
778 test_expect_success () {
779         test "$#" = 3 && { prereq=$1; shift; } || prereq=
780         test "$#" = 2 ||
781         error "bug in the test script: not 2 or 3 parameters to test-expect-success"
782         test_subtest_name="$1"
783         test_reset_state_
784         if ! test_skip "$@"
785         then
786                 test_run_ "$2"
787                 run_ret="$?"
788                 # test_run_ may update missing external prerequisites
789                 test_check_missing_external_prereqs_ "$@" ||
790                 if [ "$run_ret" = 0 -a "$eval_ret" = 0 ]
791                 then
792                         test_ok_
793                 else
794                         test_failure_ "$2"
795                 fi
796         fi
797 }
798
799 test_expect_code () {
800         test "$#" = 4 && { prereq=$1; shift; } || prereq=
801         test "$#" = 3 ||
802         error "bug in the test script: not 3 or 4 parameters to test-expect-code"
803         test_subtest_name="$2"
804         test_reset_state_
805         if ! test_skip "$@"
806         then
807                 test_run_ "$3"
808                 run_ret="$?"
809                 # test_run_ may update missing external prerequisites,
810                 test_check_missing_external_prereqs_ "$@" ||
811                 if [ "$run_ret" = 0 -a "$eval_ret" = "$1" ]
812                 then
813                         test_ok_
814                 else
815                         test_failure_ "exit code $eval_ret, expected $1" "$3"
816                 fi
817         fi
818 }
819
820 # test_external runs external test scripts that provide continuous
821 # test output about their progress, and succeeds/fails on
822 # zero/non-zero exit code.  It outputs the test output on stdout even
823 # in non-verbose mode, and announces the external script with "* run
824 # <n>: ..." before running it.  When providing relative paths, keep in
825 # mind that all scripts run in "trash directory".
826 # Usage: test_external description command arguments...
827 # Example: test_external 'Perl API' perl ../path/to/test.pl
828 test_external () {
829         test "$#" = 4 && { prereq=$1; shift; } || prereq=
830         test "$#" = 3 ||
831         error >&5 "bug in the test script: not 3 or 4 parameters to test_external"
832         test_subtest_name="$1"
833         shift
834         test_reset_state_
835         if ! test_skip "$test_subtest_name" "$@"
836         then
837                 # Announce the script to reduce confusion about the
838                 # test output that follows.
839                 say_color "" " run $test_count: $descr ($*)"
840                 # Run command; redirect its stderr to &4 as in
841                 # test_run_, but keep its stdout on our stdout even in
842                 # non-verbose mode.
843                 "$@" 2>&4
844                 if [ "$?" = 0 ]
845                 then
846                         test_ok_
847                 else
848                         test_failure_ "$@"
849                 fi
850         fi
851 }
852
853 # Like test_external, but in addition tests that the command generated
854 # no output on stderr.
855 test_external_without_stderr () {
856         # The temporary file has no (and must have no) security
857         # implications.
858         tmp="$TMPDIR"; if [ -z "$tmp" ]; then tmp=/tmp; fi
859         stderr="$tmp/git-external-stderr.$$.tmp"
860         test_external "$@" 4> "$stderr"
861         [ -f "$stderr" ] || error "Internal error: $stderr disappeared."
862         test_subtest_name="no stderr: $1"
863         shift
864         if [ ! -s "$stderr" ]; then
865                 rm "$stderr"
866                 test_ok_
867         else
868                 if [ "$verbose" = t ]; then
869                         output=`echo; echo Stderr is:; cat "$stderr"`
870                 else
871                         output=
872                 fi
873                 # rm first in case test_failure exits.
874                 rm "$stderr"
875                 test_failure_ "$@" "$output"
876         fi
877 }
878
879 # This is not among top-level (test_expect_success)
880 # but is a prefix that can be used in the test script, like:
881 #
882 #       test_expect_success 'complain and die' '
883 #           do something &&
884 #           do something else &&
885 #           test_must_fail git checkout ../outerspace
886 #       '
887 #
888 # Writing this as "! git checkout ../outerspace" is wrong, because
889 # the failure could be due to a segv.  We want a controlled failure.
890
891 test_must_fail () {
892         "$@"
893         test $? -gt 0 -a $? -le 129 -o $? -gt 192
894 }
895
896 # test_cmp is a helper function to compare actual and expected output.
897 # You can use it like:
898 #
899 #       test_expect_success 'foo works' '
900 #               echo expected >expected &&
901 #               foo >actual &&
902 #               test_cmp expected actual
903 #       '
904 #
905 # This could be written as either "cmp" or "diff -u", but:
906 # - cmp's output is not nearly as easy to read as diff -u
907 # - not all diff versions understand "-u"
908
909 test_cmp() {
910         $GIT_TEST_CMP "$@"
911 }
912
913 # This function can be used to schedule some commands to be run
914 # unconditionally at the end of the test to restore sanity:
915 #
916 #       test_expect_success 'test core.capslock' '
917 #               git config core.capslock true &&
918 #               test_when_finished "git config --unset core.capslock" &&
919 #               hello world
920 #       '
921 #
922 # That would be roughly equivalent to
923 #
924 #       test_expect_success 'test core.capslock' '
925 #               git config core.capslock true &&
926 #               hello world
927 #               git config --unset core.capslock
928 #       '
929 #
930 # except that the greeting and config --unset must both succeed for
931 # the test to pass.
932
933 test_when_finished () {
934         test_cleanup="{ $*
935                 } && (exit \"\$eval_ret\"); eval_ret=\$?; $test_cleanup"
936 }
937
938 test_done () {
939         GIT_EXIT_OK=t
940         test_results_dir="$TEST_DIRECTORY/test-results"
941         mkdir -p "$test_results_dir"
942         test_results_path="$test_results_dir/${0%.sh}"
943
944         echo "total $test_count" >> $test_results_path
945         echo "success $test_success" >> $test_results_path
946         echo "fixed $test_fixed" >> $test_results_path
947         echo "broken $test_broken" >> $test_results_path
948         echo "failed $test_failure" >> $test_results_path
949         echo "" >> $test_results_path
950
951         echo
952
953         [ -n "$EMACS_SERVER" ] && test_emacs '(kill-emacs)'
954
955         if [ "$test_failure" = "0" ]; then
956             if [ "$test_broken" = "0" ]; then
957                 rm -rf "$remove_tmp"
958             fi
959             exit 0
960         else
961             exit 1
962         fi
963 }
964
965 emacs_generate_script () {
966         # Construct a little test script here for the benefit of the user,
967         # (who can easily run "run_emacs" to get the same emacs environment
968         # for investigating any failures).
969         cat <<EOF >"$TMP_DIRECTORY/run_emacs"
970 #!/bin/sh
971 export PATH=$PATH
972 export NOTMUCH_CONFIG=$NOTMUCH_CONFIG
973
974 # Here's what we are using here:
975 #
976 # --no-init-file        Don't load users ~/.emacs
977 #
978 # --no-site-file        Don't load the site-wide startup stuff
979 #
980 # --directory           Ensure that the local elisp sources are found
981 #
982 # --load                Force loading of notmuch.el and test-lib.el
983
984 exec ${TEST_EMACS} --no-init-file --no-site-file \
985         --directory "$TEST_DIRECTORY/../emacs" --load notmuch.el \
986         --directory "$TEST_DIRECTORY" --load test-lib.el \
987         "\$@"
988 EOF
989         chmod a+x "$TMP_DIRECTORY/run_emacs"
990 }
991
992 test_emacs () {
993         # test dependencies beforehand to avoid the waiting loop below
994         missing_dependencies=
995         test_require_external_prereq dtach || missing_dependencies=1
996         test_require_external_prereq emacs || missing_dependencies=1
997         test_require_external_prereq ${TEST_EMACSCLIENT} || missing_dependencies=1
998         test -z "$missing_dependencies" || return
999
1000         if [ -z "$EMACS_SERVER" ]; then
1001                 emacs_tests="$(basename $0).el"
1002                 if [ -f "$TEST_DIRECTORY/$emacs_tests" ]; then
1003                         load_emacs_tests="--eval '(load \"$emacs_tests\")'"
1004                 else
1005                         load_emacs_tests=
1006                 fi
1007                 server_name="notmuch-test-suite-$$"
1008                 # start a detached session with an emacs server
1009                 # user's TERM (or 'vt100' in case user's TERM is unset, empty
1010                 # or 'dumb') is given to dtach which assumes a minimally
1011                 # VT100-compatible terminal -- and emacs inherits that
1012                 TERM=$DTACH_TERM dtach -n "$TEST_TMPDIR/emacs-dtach-socket.$$" \
1013                         sh -c "stty rows 24 cols 80; exec '$TMP_DIRECTORY/run_emacs' \
1014                                 --no-window-system \
1015                                 $load_emacs_tests \
1016                                 --eval '(setq server-name \"$server_name\")' \
1017                                 --eval '(server-start)' \
1018                                 --eval '(orphan-watchdog $$)'" || return
1019                 EMACS_SERVER="$server_name"
1020                 # wait until the emacs server is up
1021                 until test_emacs '()' >/dev/null 2>/dev/null; do
1022                         sleep 1
1023                 done
1024         fi
1025
1026         # Clear test-output output file.  Most Emacs tests end with a
1027         # call to (test-output).  If the test code fails with an
1028         # exception before this call, the output file won't get
1029         # updated.  Since we don't want to compare against an output
1030         # file from another test, so start out with an empty file.
1031         rm -f OUTPUT
1032         touch OUTPUT
1033
1034         ${TEST_EMACSCLIENT} --socket-name="$EMACS_SERVER" --eval "(progn $@)"
1035 }
1036
1037 test_python() {
1038         export LD_LIBRARY_PATH=$TEST_DIRECTORY/../lib
1039         export PYTHONPATH=$TEST_DIRECTORY/../bindings/python
1040
1041         # Some distros (e.g. Arch Linux) ship Python 2.* as /usr/bin/python2,
1042         # most others as /usr/bin/python. So first try python2, and fallback to
1043         # python if python2 doesn't exist.
1044         cmd=python2
1045         [[ ${test_missing_external_prereq_[python2]} == t ]] && cmd=python
1046
1047         (echo "import sys; _orig_stdout=sys.stdout; sys.stdout=open('OUTPUT', 'w')"; cat) \
1048                 | $cmd -
1049 }
1050
1051 # Creates a script that counts how much time it is executed and calls
1052 # notmuch.  $notmuch_counter_command is set to the path to the
1053 # generated script.  Use notmuch_counter_value() function to get the
1054 # current counter value.
1055 notmuch_counter_reset () {
1056         notmuch_counter_command="$TMP_DIRECTORY/notmuch_counter"
1057         if [ ! -x "$notmuch_counter_command" ]; then
1058                 notmuch_counter_state_path="$TMP_DIRECTORY/notmuch_counter.state"
1059                 cat >"$notmuch_counter_command" <<EOF || return
1060 #!/bin/sh
1061
1062 read count < "$notmuch_counter_state_path"
1063 echo \$((count + 1)) > "$notmuch_counter_state_path"
1064
1065 exec notmuch "\$@"
1066 EOF
1067                 chmod +x "$notmuch_counter_command" || return
1068         fi
1069
1070         echo 0 > "$notmuch_counter_state_path"
1071 }
1072
1073 # Returns the current notmuch counter value.
1074 notmuch_counter_value () {
1075         if [ -r "$notmuch_counter_state_path" ]; then
1076                 read count < "$notmuch_counter_state_path"
1077         else
1078                 count=0
1079         fi
1080         echo $count
1081 }
1082
1083 test_reset_state_ () {
1084         test -z "$test_init_done_" && test_init_
1085
1086         test_subtest_known_broken_=
1087         test_subtest_missing_external_prereq_=()
1088 }
1089
1090 # called once before the first subtest
1091 test_init_ () {
1092         test_init_done_=t
1093
1094         # skip all tests if there were external prerequisites missing during init
1095         test_check_missing_external_prereqs_ "all tests in $this_test" && test_done
1096 }
1097
1098
1099 . ./test-lib-common.sh
1100
1101 emacs_generate_script
1102
1103
1104 # Use -P to resolve symlinks in our working directory so that the cwd
1105 # in subprocesses like git equals our $PWD (for pathname comparisons).
1106 cd -P "$test" || error "Cannot setup test environment"
1107
1108 if test "$verbose" = "t"
1109 then
1110         exec 4>&2 3>&1
1111 else
1112         exec 4>test.output 3>&4
1113 fi
1114
1115 this_test=${0##*/}
1116 for skp in $NOTMUCH_SKIP_TESTS
1117 do
1118         to_skip=
1119         for skp in $NOTMUCH_SKIP_TESTS
1120         do
1121                 case "$this_test" in
1122                 $skp)
1123                         to_skip=t
1124                 esac
1125         done
1126         case "$to_skip" in
1127         t)
1128                 say_color skip >&3 "skipping test $this_test altogether"
1129                 say_color skip "skip all tests in $this_test"
1130                 test_done
1131         esac
1132 done
1133
1134 # Provide an implementation of the 'yes' utility
1135 yes () {
1136         if test $# = 0
1137         then
1138                 y=y
1139         else
1140                 y="$*"
1141         fi
1142
1143         while echo "$y"
1144         do
1145                 :
1146         done
1147 }
1148
1149 # Fix some commands on Windows
1150 case $(uname -s) in
1151 *MINGW*)
1152         # Windows has its own (incompatible) sort and find
1153         sort () {
1154                 /usr/bin/sort "$@"
1155         }
1156         find () {
1157                 /usr/bin/find "$@"
1158         }
1159         sum () {
1160                 md5sum "$@"
1161         }
1162         # git sees Windows-style pwd
1163         pwd () {
1164                 builtin pwd -W
1165         }
1166         # no POSIX permissions
1167         # backslashes in pathspec are converted to '/'
1168         # exec does not inherit the PID
1169         ;;
1170 *)
1171         test_set_prereq POSIXPERM
1172         test_set_prereq BSLASHPSPEC
1173         test_set_prereq EXECKEEPSPID
1174         ;;
1175 esac
1176
1177 test -z "$NO_PERL" && test_set_prereq PERL
1178 test -z "$NO_PYTHON" && test_set_prereq PYTHON
1179
1180 # test whether the filesystem supports symbolic links
1181 ln -s x y 2>/dev/null && test -h y 2>/dev/null && test_set_prereq SYMLINKS
1182 rm -f y
1183
1184 # declare prerequisites for external binaries used in tests
1185 test_declare_external_prereq dtach
1186 test_declare_external_prereq emacs
1187 test_declare_external_prereq ${TEST_EMACSCLIENT}
1188 test_declare_external_prereq gdb
1189 test_declare_external_prereq gpg
1190 test_declare_external_prereq python
1191 test_declare_external_prereq python2