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