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