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