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