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