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