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