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