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