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