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