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