]> git.notmuchmail.org Git - notmuch/blob - test/test-lib.sh
test: renamed test scripts to format T\d\d\d-name.sh
[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=${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         template[date]=$(TZ=UTC printf "%(%a, %d %b %Y %T %z)T\n" \
378                         $((978709437 - gen_msg_cnt)))
379     fi
380
381     additional_headers=""
382     if [ ! -z "${template[header]}" ]; then
383         additional_headers="${template[header]}
384 ${additional_headers}"
385     fi
386
387     if [ ! -z "${template[reply-to]}" ]; then
388         additional_headers="Reply-To: ${template[reply-to]}
389 ${additional_headers}"
390     fi
391
392     if [ ! -z "${template[in-reply-to]}" ]; then
393         additional_headers="In-Reply-To: ${template[in-reply-to]}
394 ${additional_headers}"
395     fi
396
397     if [ ! -z "${template[cc]}" ]; then
398         additional_headers="Cc: ${template[cc]}
399 ${additional_headers}"
400     fi
401
402     if [ ! -z "${template[bcc]}" ]; then
403         additional_headers="Bcc: ${template[bcc]}
404 ${additional_headers}"
405     fi
406
407     if [ ! -z "${template[references]}" ]; then
408         additional_headers="References: ${template[references]}
409 ${additional_headers}"
410     fi
411
412     if [ ! -z "${template[content-type]}" ]; then
413         additional_headers="Content-Type: ${template[content-type]}
414 ${additional_headers}"
415     fi
416
417     if [ ! -z "${template[content-transfer-encoding]}" ]; then
418         additional_headers="Content-Transfer-Encoding: ${template[content-transfer-encoding]}
419 ${additional_headers}"
420     fi
421
422     # Note that in the way we're setting it above and using it below,
423     # `additional_headers' will also serve as the header / body separator
424     # (empty line in between).
425
426     cat <<EOF >"$gen_msg_filename"
427 From: ${template[from]}
428 To: ${template[to]}
429 Message-Id: <${gen_msg_id}>
430 Subject: ${template[subject]}
431 Date: ${template[date]}
432 ${additional_headers}
433 ${template[body]}
434 EOF
435 }
436
437 # Generate a new message and add it to the database.
438 #
439 # All of the arguments and return values supported by generate_message
440 # are also supported here, so see that function for details.
441 add_message ()
442 {
443     generate_message "$@" &&
444     notmuch new > /dev/null
445 }
446
447 # Deliver a message with emacs and add it to the database
448 #
449 # Uses emacs to generate and deliver a message to the mail store.
450 # Accepts arbitrary extra emacs/elisp functions to modify the message
451 # before sending, which is useful to doing things like attaching files
452 # to the message and encrypting/signing.
453 emacs_deliver_message ()
454 {
455     local subject="$1"
456     local body="$2"
457     shift 2
458     # before we can send a message, we have to prepare the FCC maildir
459     mkdir -p "$MAIL_DIR"/sent/{cur,new,tmp}
460     # eval'ing smtp-dummy --background will set smtp_dummy_pid
461     smtp_dummy_pid=
462     eval `$TEST_DIRECTORY/smtp-dummy --background sent_message`
463     test -n "$smtp_dummy_pid" || return 1
464
465     test_emacs \
466         "(let ((message-send-mail-function 'message-smtpmail-send-it)
467                (mail-host-address \"example.com\")
468                (smtpmail-smtp-server \"localhost\")
469                (smtpmail-smtp-service \"25025\"))
470            (notmuch-mua-mail)
471            (message-goto-to)
472            (insert \"test_suite@notmuchmail.org\nDate: 01 Jan 2000 12:00:00 -0000\")
473            (message-goto-subject)
474            (insert \"${subject}\")
475            (message-goto-body)
476            (insert \"${body}\")
477            $@
478            (message-send-and-exit))"
479
480     # In case message was sent properly, client waits for confirmation
481     # before exiting and resuming control here; therefore making sure
482     # that server exits by sending (KILL) signal to it is safe.
483     kill -9 $smtp_dummy_pid
484     notmuch new >/dev/null
485 }
486
487 # Pretend to deliver a message with emacs. Really save it to a file
488 # and add it to the database
489 #
490 # Uses emacs to generate and deliver a message to the mail store.
491 # Accepts arbitrary extra emacs/elisp functions to modify the message
492 # before sending, which is useful to doing things like attaching files
493 # to the message and encrypting/signing.
494 emacs_fcc_message ()
495 {
496     local subject="$1"
497     local body="$2"
498     shift 2
499     # before we can send a message, we have to prepare the FCC maildir
500     mkdir -p "$MAIL_DIR"/sent/{cur,new,tmp}
501
502     test_emacs \
503         "(let ((message-send-mail-function (lambda () t))
504                (mail-host-address \"example.com\"))
505            (notmuch-mua-mail)
506            (message-goto-to)
507            (insert \"test_suite@notmuchmail.org\nDate: 01 Jan 2000 12:00:00 -0000\")
508            (message-goto-subject)
509            (insert \"${subject}\")
510            (message-goto-body)
511            (insert \"${body}\")
512            $@
513            (message-send-and-exit))" || return 1
514     notmuch new >/dev/null
515 }
516
517 # Generate a corpus of email and add it to the database.
518 #
519 # This corpus is fixed, (it happens to be 50 messages from early in
520 # the history of the notmuch mailing list), which allows for reliably
521 # testing commands that need to operate on a not-totally-trivial
522 # number of messages.
523 add_email_corpus ()
524 {
525     rm -rf ${MAIL_DIR}
526     if [ -d $TEST_DIRECTORY/corpus.mail ]; then
527         cp -a $TEST_DIRECTORY/corpus.mail ${MAIL_DIR}
528     else
529         cp -a $TEST_DIRECTORY/corpus ${MAIL_DIR}
530         notmuch new >/dev/null
531         cp -a ${MAIL_DIR} $TEST_DIRECTORY/corpus.mail
532     fi
533 }
534
535 test_begin_subtest ()
536 {
537     if [ -n "$inside_subtest" ]; then
538         exec 1>&6 2>&7          # Restore stdout and stderr
539         error "bug in test script: Missing test_expect_equal in ${BASH_SOURCE[1]}:${BASH_LINENO[0]}"
540     fi
541     test_subtest_name="$1"
542     test_reset_state_
543     # Remember stdout and stderr file descriptors and redirect test
544     # output to the previously prepared file descriptors 3 and 4 (see
545     # below)
546     if test "$verbose" != "t"; then exec 4>test.output 3>&4; fi
547     exec 6>&1 7>&2 >&3 2>&4
548     inside_subtest=t
549 }
550
551 # Pass test if two arguments match
552 #
553 # Note: Unlike all other test_expect_* functions, this function does
554 # not accept a test name. Instead, the caller should call
555 # test_begin_subtest before calling this function in order to set the
556 # name.
557 test_expect_equal ()
558 {
559         exec 1>&6 2>&7          # Restore stdout and stderr
560         inside_subtest=
561         test "$#" = 3 && { prereq=$1; shift; } || prereq=
562         test "$#" = 2 ||
563         error "bug in the test script: not 2 or 3 parameters to test_expect_equal"
564
565         output="$1"
566         expected="$2"
567         if ! test_skip "$test_subtest_name"
568         then
569                 if [ "$output" = "$expected" ]; then
570                         test_ok_
571                 else
572                         testname=$this_test.$test_count
573                         echo "$expected" > $testname.expected
574                         echo "$output" > $testname.output
575                         test_failure_ "$(diff -u $testname.expected $testname.output)"
576                 fi
577     fi
578 }
579
580 # Like test_expect_equal, but takes two filenames.
581 test_expect_equal_file ()
582 {
583         exec 1>&6 2>&7          # Restore stdout and stderr
584         inside_subtest=
585         test "$#" = 3 && { prereq=$1; shift; } || prereq=
586         test "$#" = 2 ||
587         error "bug in the test script: not 2 or 3 parameters to test_expect_equal"
588
589         file1="$1"
590         basename1=`basename "$file1"`
591         file2="$2"
592         basename2=`basename "$file2"`
593         if ! test_skip "$test_subtest_name"
594         then
595                 if diff -q "$file1" "$file2" >/dev/null ; then
596                         test_ok_
597                 else
598                         testname=$this_test.$test_count
599                         cp "$file1" "$testname.$basename1"
600                         cp "$file2" "$testname.$basename2"
601                         test_failure_ "$(diff -u "$testname.$basename1" "$testname.$basename2")"
602                 fi
603     fi
604 }
605
606 # Like test_expect_equal, but arguments are JSON expressions to be
607 # canonicalized before diff'ing.  If an argument cannot be parsed, it
608 # is used unchanged so that there's something to diff against.
609 test_expect_equal_json () {
610     # The test suite forces LC_ALL=C, but this causes Python 3 to
611     # decode stdin as ASCII.  We need to read JSON in UTF-8, so
612     # override Python's stdio encoding defaults.
613     output=$(echo "$1" | PYTHONIOENCODING=utf-8 python -mjson.tool \
614         || echo "$1")
615     expected=$(echo "$2" | PYTHONIOENCODING=utf-8 python -mjson.tool \
616         || echo "$2")
617     shift 2
618     test_expect_equal "$output" "$expected" "$@"
619 }
620
621 test_emacs_expect_t () {
622         test "$#" = 2 && { prereq=$1; shift; } || prereq=
623         test "$#" = 1 ||
624         error "bug in the test script: not 1 or 2 parameters to test_emacs_expect_t"
625
626         # Run the test.
627         if ! test_skip "$test_subtest_name"
628         then
629                 test_emacs "(notmuch-test-run $1)" >/dev/null
630
631                 # Restore state after the test.
632                 exec 1>&6 2>&7          # Restore stdout and stderr
633                 inside_subtest=
634
635                 # Report success/failure.
636                 result=$(cat OUTPUT)
637                 if [ "$result" = t ]
638                 then
639                         test_ok_
640                 else
641                         test_failure_ "${result}"
642                 fi
643         else
644                 # Restore state after the (non) test.
645                 exec 1>&6 2>&7          # Restore stdout and stderr
646                 inside_subtest=
647         fi
648 }
649
650 NOTMUCH_NEW ()
651 {
652     notmuch new "${@}" | grep -v -E -e '^Processed [0-9]*( total)? file|Found [0-9]* total file'
653 }
654
655 notmuch_search_sanitize ()
656 {
657     perl -pe 's/("?thread"?: ?)("?)................("?)/\1\2XXX\3/'
658 }
659
660 NOTMUCH_SHOW_FILENAME_SQUELCH='s,filename:.*/mail,filename:/XXX/mail,'
661 notmuch_show_sanitize ()
662 {
663     sed -e "$NOTMUCH_SHOW_FILENAME_SQUELCH"
664 }
665 notmuch_show_sanitize_all ()
666 {
667     sed \
668         -e 's| filename:.*| filename:XXXXX|' \
669         -e 's| id:[^ ]* | id:XXXXX |' | \
670         notmuch_date_sanitize
671 }
672
673 notmuch_json_show_sanitize ()
674 {
675     sed \
676         -e 's|"id": "[^"]*",|"id": "XXXXX",|g' \
677         -e 's|"Date": "Fri, 05 Jan 2001 [^"]*0000"|"Date": "GENERATED_DATE"|g' \
678         -e 's|"filename": "/[^"]*",|"filename": "YYYYY",|g' \
679         -e 's|"timestamp": 97.......|"timestamp": 42|g'
680 }
681
682 notmuch_emacs_error_sanitize ()
683 {
684     local command=$1
685     shift
686     for file in "$@"; do
687         echo "=== $file ==="
688         cat "$file"
689     done | sed  \
690         -e 's/^\[.*\]$/[XXX]/' \
691         -e "s|^\(command: \)\{0,1\}/.*/$command|\1YYY/$command|"
692 }
693
694 notmuch_date_sanitize ()
695 {
696     sed \
697         -e 's/^Date: Fri, 05 Jan 2001 .*0000/Date: GENERATED_DATE/'
698 }
699 # End of notmuch helper functions
700
701 # Use test_set_prereq to tell that a particular prerequisite is available.
702 # The prerequisite can later be checked for in two ways:
703 #
704 # - Explicitly using test_have_prereq.
705 #
706 # - Implicitly by specifying the prerequisite tag in the calls to
707 #   test_expect_{success,failure,code}.
708 #
709 # The single parameter is the prerequisite tag (a simple word, in all
710 # capital letters by convention).
711
712 test_set_prereq () {
713         satisfied="$satisfied$1 "
714 }
715 satisfied=" "
716
717 test_have_prereq () {
718         case $satisfied in
719         *" $1 "*)
720                 : yes, have it ;;
721         *)
722                 ! : nope ;;
723         esac
724 }
725
726 declare -A test_missing_external_prereq_
727 declare -A test_subtest_missing_external_prereq_
728
729 # declare prerequisite for the given external binary
730 test_declare_external_prereq () {
731         binary="$1"
732         test "$#" = 2 && name=$2 || name="$binary(1)"
733
734         if ! hash $binary 2>/dev/null; then
735                 test_missing_external_prereq_["${binary}"]=t
736                 eval "
737 $binary () {
738         test_subtest_missing_external_prereq_[\"${name}\"]=t
739         false
740 }"
741         fi
742 }
743
744 # Explicitly require external prerequisite.  Useful when binary is
745 # called indirectly (e.g. from emacs).
746 # Returns success if dependency is available, failure otherwise.
747 test_require_external_prereq () {
748         binary="$1"
749         if [[ ${test_missing_external_prereq_["${binary}"]} == t ]]; then
750                 # dependency is missing, call the replacement function to note it
751                 eval "$binary"
752         else
753                 true
754         fi
755 }
756
757 # You are not expected to call test_ok_ and test_failure_ directly, use
758 # the text_expect_* functions instead.
759
760 test_ok_ () {
761         if test "$test_subtest_known_broken_" = "t"; then
762                 test_known_broken_ok_
763                 return
764         fi
765         test_success=$(($test_success + 1))
766         if test -n "$NOTMUCH_TEST_QUIET"; then
767                 return 0
768         fi
769         say_color pass "%-6s" "PASS"
770         echo " $test_subtest_name"
771 }
772
773 test_failure_ () {
774         if test "$test_subtest_known_broken_" = "t"; then
775                 test_known_broken_failure_ "$@"
776                 return
777         fi
778         test_failure=$(($test_failure + 1))
779         print_test_description
780         test_failure_message_ "FAIL" "$test_subtest_name" "$@"
781         test "$immediate" = "" || { GIT_EXIT_OK=t; exit 1; }
782         return 1
783 }
784
785 test_failure_message_ () {
786         say_color error "%-6s" "$1"
787         echo " $2"
788         shift 2
789         echo "$@" | sed -e 's/^/        /'
790         if test "$verbose" != "t"; then cat test.output; fi
791 }
792
793 test_known_broken_ok_ () {
794         test_reset_state_
795         test_fixed=$(($test_fixed+1))
796         say_color pass "%-6s" "FIXED"
797         echo " $test_subtest_name"
798 }
799
800 test_known_broken_failure_ () {
801         test_reset_state_
802         test_broken=$(($test_broken+1))
803         test_failure_message_ "BROKEN" "$test_subtest_name" "$@"
804         return 1
805 }
806
807 test_debug () {
808         test "$debug" = "" || eval "$1"
809 }
810
811 test_run_ () {
812         test_cleanup=:
813         if test "$verbose" != "t"; then exec 4>test.output 3>&4; fi
814         eval >&3 2>&4 "$1"
815         eval_ret=$?
816         eval >&3 2>&4 "$test_cleanup"
817         return 0
818 }
819
820 test_skip () {
821         test_count=$(($test_count+1))
822         to_skip=
823         for skp in $NOTMUCH_SKIP_TESTS
824         do
825                 case $this_test.$test_count in
826                 $skp)
827                         to_skip=t
828                 esac
829         done
830         if test -z "$to_skip" && test -n "$prereq" &&
831            ! test_have_prereq "$prereq"
832         then
833                 to_skip=t
834         fi
835         case "$to_skip" in
836         t)
837                 test_report_skip_ "$@"
838                 ;;
839         *)
840                 test_check_missing_external_prereqs_ "$@"
841                 ;;
842         esac
843 }
844
845 test_check_missing_external_prereqs_ () {
846         if [[ ${#test_subtest_missing_external_prereq_[@]} != 0 ]]; then
847                 say_color skip >&1 "missing prerequisites: "
848                 echo ${!test_subtest_missing_external_prereq_[@]} >&1
849                 test_report_skip_ "$@"
850         else
851                 false
852         fi
853 }
854
855 test_report_skip_ () {
856         test_reset_state_
857         say_color skip >&3 "skipping test:"
858         echo " $@" >&3
859         say_color skip "%-6s" "SKIP"
860         echo " $1"
861 }
862
863 test_subtest_known_broken () {
864         test_subtest_known_broken_=t
865 }
866
867 test_expect_success () {
868         test "$#" = 3 && { prereq=$1; shift; } || prereq=
869         test "$#" = 2 ||
870         error "bug in the test script: not 2 or 3 parameters to test-expect-success"
871         test_subtest_name="$1"
872         test_reset_state_
873         if ! test_skip "$@"
874         then
875                 test_run_ "$2"
876                 run_ret="$?"
877                 # test_run_ may update missing external prerequisites
878                 test_check_missing_external_prereqs_ "$@" ||
879                 if [ "$run_ret" = 0 -a "$eval_ret" = 0 ]
880                 then
881                         test_ok_
882                 else
883                         test_failure_ "$2"
884                 fi
885         fi
886 }
887
888 test_expect_code () {
889         test "$#" = 4 && { prereq=$1; shift; } || prereq=
890         test "$#" = 3 ||
891         error "bug in the test script: not 3 or 4 parameters to test-expect-code"
892         test_subtest_name="$2"
893         test_reset_state_
894         if ! test_skip "$@"
895         then
896                 test_run_ "$3"
897                 run_ret="$?"
898                 # test_run_ may update missing external prerequisites,
899                 test_check_missing_external_prereqs_ "$@" ||
900                 if [ "$run_ret" = 0 -a "$eval_ret" = "$1" ]
901                 then
902                         test_ok_
903                 else
904                         test_failure_ "exit code $eval_ret, expected $1" "$3"
905                 fi
906         fi
907 }
908
909 # test_external runs external test scripts that provide continuous
910 # test output about their progress, and succeeds/fails on
911 # zero/non-zero exit code.  It outputs the test output on stdout even
912 # in non-verbose mode, and announces the external script with "* run
913 # <n>: ..." before running it.  When providing relative paths, keep in
914 # mind that all scripts run in "trash directory".
915 # Usage: test_external description command arguments...
916 # Example: test_external 'Perl API' perl ../path/to/test.pl
917 test_external () {
918         test "$#" = 4 && { prereq=$1; shift; } || prereq=
919         test "$#" = 3 ||
920         error >&5 "bug in the test script: not 3 or 4 parameters to test_external"
921         test_subtest_name="$1"
922         shift
923         test_reset_state_
924         if ! test_skip "$test_subtest_name" "$@"
925         then
926                 # Announce the script to reduce confusion about the
927                 # test output that follows.
928                 say_color "" " run $test_count: $descr ($*)"
929                 # Run command; redirect its stderr to &4 as in
930                 # test_run_, but keep its stdout on our stdout even in
931                 # non-verbose mode.
932                 "$@" 2>&4
933                 if [ "$?" = 0 ]
934                 then
935                         test_ok_
936                 else
937                         test_failure_ "$@"
938                 fi
939         fi
940 }
941
942 # Like test_external, but in addition tests that the command generated
943 # no output on stderr.
944 test_external_without_stderr () {
945         # The temporary file has no (and must have no) security
946         # implications.
947         tmp="$TMPDIR"; if [ -z "$tmp" ]; then tmp=/tmp; fi
948         stderr="$tmp/git-external-stderr.$$.tmp"
949         test_external "$@" 4> "$stderr"
950         [ -f "$stderr" ] || error "Internal error: $stderr disappeared."
951         test_subtest_name="no stderr: $1"
952         shift
953         if [ ! -s "$stderr" ]; then
954                 rm "$stderr"
955                 test_ok_
956         else
957                 if [ "$verbose" = t ]; then
958                         output=`echo; echo Stderr is:; cat "$stderr"`
959                 else
960                         output=
961                 fi
962                 # rm first in case test_failure exits.
963                 rm "$stderr"
964                 test_failure_ "$@" "$output"
965         fi
966 }
967
968 # This is not among top-level (test_expect_success)
969 # but is a prefix that can be used in the test script, like:
970 #
971 #       test_expect_success 'complain and die' '
972 #           do something &&
973 #           do something else &&
974 #           test_must_fail git checkout ../outerspace
975 #       '
976 #
977 # Writing this as "! git checkout ../outerspace" is wrong, because
978 # the failure could be due to a segv.  We want a controlled failure.
979
980 test_must_fail () {
981         "$@"
982         test $? -gt 0 -a $? -le 129 -o $? -gt 192
983 }
984
985 # test_cmp is a helper function to compare actual and expected output.
986 # You can use it like:
987 #
988 #       test_expect_success 'foo works' '
989 #               echo expected >expected &&
990 #               foo >actual &&
991 #               test_cmp expected actual
992 #       '
993 #
994 # This could be written as either "cmp" or "diff -u", but:
995 # - cmp's output is not nearly as easy to read as diff -u
996 # - not all diff versions understand "-u"
997
998 test_cmp() {
999         $GIT_TEST_CMP "$@"
1000 }
1001
1002 # This function can be used to schedule some commands to be run
1003 # unconditionally at the end of the test to restore sanity:
1004 #
1005 #       test_expect_success 'test core.capslock' '
1006 #               git config core.capslock true &&
1007 #               test_when_finished "git config --unset core.capslock" &&
1008 #               hello world
1009 #       '
1010 #
1011 # That would be roughly equivalent to
1012 #
1013 #       test_expect_success 'test core.capslock' '
1014 #               git config core.capslock true &&
1015 #               hello world
1016 #               git config --unset core.capslock
1017 #       '
1018 #
1019 # except that the greeting and config --unset must both succeed for
1020 # the test to pass.
1021
1022 test_when_finished () {
1023         test_cleanup="{ $*
1024                 } && (exit \"\$eval_ret\"); eval_ret=\$?; $test_cleanup"
1025 }
1026
1027 test_done () {
1028         GIT_EXIT_OK=t
1029         test_results_dir="$TEST_DIRECTORY/test-results"
1030         mkdir -p "$test_results_dir"
1031         test_results_path="$test_results_dir/$this_test"
1032
1033         echo "total $test_count" >> $test_results_path
1034         echo "success $test_success" >> $test_results_path
1035         echo "fixed $test_fixed" >> $test_results_path
1036         echo "broken $test_broken" >> $test_results_path
1037         echo "failed $test_failure" >> $test_results_path
1038         echo "" >> $test_results_path
1039
1040         [ -n "$EMACS_SERVER" ] && test_emacs '(kill-emacs)'
1041
1042         if [ "$test_failure" = "0" ]; then
1043             if [ "$test_broken" = "0" ]; then
1044                 rm -rf "$remove_tmp"
1045             fi
1046             exit 0
1047         else
1048             exit 1
1049         fi
1050 }
1051
1052 emacs_generate_script () {
1053         # Construct a little test script here for the benefit of the user,
1054         # (who can easily run "run_emacs" to get the same emacs environment
1055         # for investigating any failures).
1056         cat <<EOF >"$TMP_DIRECTORY/run_emacs"
1057 #!/bin/sh
1058 export PATH=$PATH
1059 export NOTMUCH_CONFIG=$NOTMUCH_CONFIG
1060
1061 # Here's what we are using here:
1062 #
1063 # --no-init-file        Don't load users ~/.emacs
1064 #
1065 # --no-site-file        Don't load the site-wide startup stuff
1066 #
1067 # --directory           Ensure that the local elisp sources are found
1068 #
1069 # --load                Force loading of notmuch.el and test-lib.el
1070
1071 exec ${TEST_EMACS} --no-init-file --no-site-file \
1072         --directory "$TEST_DIRECTORY/../emacs" --load notmuch.el \
1073         --directory "$TEST_DIRECTORY" --load test-lib.el \
1074         "\$@"
1075 EOF
1076         chmod a+x "$TMP_DIRECTORY/run_emacs"
1077 }
1078
1079 test_emacs () {
1080         # test dependencies beforehand to avoid the waiting loop below
1081         missing_dependencies=
1082         test_require_external_prereq dtach || missing_dependencies=1
1083         test_require_external_prereq emacs || missing_dependencies=1
1084         test_require_external_prereq ${TEST_EMACSCLIENT} || missing_dependencies=1
1085         test -z "$missing_dependencies" || return
1086
1087         if [ -z "$EMACS_SERVER" ]; then
1088                 emacs_tests="${this_test}.el"
1089                 if [ -f "$TEST_DIRECTORY/$emacs_tests" ]; then
1090                         load_emacs_tests="--eval '(load \"$emacs_tests\")'"
1091                 else
1092                         load_emacs_tests=
1093                 fi
1094                 server_name="notmuch-test-suite-$$"
1095                 # start a detached session with an emacs server
1096                 # user's TERM (or 'vt100' in case user's TERM is unset, empty
1097                 # or 'dumb') is given to dtach which assumes a minimally
1098                 # VT100-compatible terminal -- and emacs inherits that
1099                 TERM=$DTACH_TERM dtach -n "$TEST_TMPDIR/emacs-dtach-socket.$$" \
1100                         sh -c "stty rows 24 cols 80; exec '$TMP_DIRECTORY/run_emacs' \
1101                                 --no-window-system \
1102                                 $load_emacs_tests \
1103                                 --eval '(setq server-name \"$server_name\")' \
1104                                 --eval '(server-start)' \
1105                                 --eval '(orphan-watchdog $$)'" || return
1106                 EMACS_SERVER="$server_name"
1107                 # wait until the emacs server is up
1108                 until test_emacs '()' >/dev/null 2>/dev/null; do
1109                         sleep 1
1110                 done
1111         fi
1112
1113         # Clear test-output output file.  Most Emacs tests end with a
1114         # call to (test-output).  If the test code fails with an
1115         # exception before this call, the output file won't get
1116         # updated.  Since we don't want to compare against an output
1117         # file from another test, so start out with an empty file.
1118         rm -f OUTPUT
1119         touch OUTPUT
1120
1121         ${TEST_EMACSCLIENT} --socket-name="$EMACS_SERVER" --eval "(progn $@)"
1122 }
1123
1124 test_python() {
1125         export LD_LIBRARY_PATH=$TEST_DIRECTORY/../lib
1126         export PYTHONPATH=$TEST_DIRECTORY/../bindings/python
1127
1128         # Some distros (e.g. Arch Linux) ship Python 2.* as /usr/bin/python2,
1129         # most others as /usr/bin/python. So first try python2, and fallback to
1130         # python if python2 doesn't exist.
1131         cmd=python2
1132         [[ ${test_missing_external_prereq_[python2]} == t ]] && cmd=python
1133
1134         (echo "import sys; _orig_stdout=sys.stdout; sys.stdout=open('OUTPUT', 'w')"; cat) \
1135                 | $cmd -
1136 }
1137
1138 # Creates a script that counts how much time it is executed and calls
1139 # notmuch.  $notmuch_counter_command is set to the path to the
1140 # generated script.  Use notmuch_counter_value() function to get the
1141 # current counter value.
1142 notmuch_counter_reset () {
1143         notmuch_counter_command="$TMP_DIRECTORY/notmuch_counter"
1144         if [ ! -x "$notmuch_counter_command" ]; then
1145                 notmuch_counter_state_path="$TMP_DIRECTORY/notmuch_counter.state"
1146                 cat >"$notmuch_counter_command" <<EOF || return
1147 #!/bin/sh
1148
1149 read count < "$notmuch_counter_state_path"
1150 echo \$((count + 1)) > "$notmuch_counter_state_path"
1151
1152 exec notmuch "\$@"
1153 EOF
1154                 chmod +x "$notmuch_counter_command" || return
1155         fi
1156
1157         echo 0 > "$notmuch_counter_state_path"
1158 }
1159
1160 # Returns the current notmuch counter value.
1161 notmuch_counter_value () {
1162         if [ -r "$notmuch_counter_state_path" ]; then
1163                 read count < "$notmuch_counter_state_path"
1164         else
1165                 count=0
1166         fi
1167         echo $count
1168 }
1169
1170 test_reset_state_ () {
1171         test -z "$test_init_done_" && test_init_
1172
1173         test_subtest_known_broken_=
1174         test_subtest_missing_external_prereq_=()
1175 }
1176
1177 # called once before the first subtest
1178 test_init_ () {
1179         test_init_done_=t
1180
1181         # skip all tests if there were external prerequisites missing during init
1182         test_check_missing_external_prereqs_ "all tests in $this_test" && test_done
1183 }
1184
1185
1186 . ./test-lib-common.sh
1187
1188 emacs_generate_script
1189
1190
1191 # Use -P to resolve symlinks in our working directory so that the cwd
1192 # in subprocesses like git equals our $PWD (for pathname comparisons).
1193 cd -P "$test" || error "Cannot setup test environment"
1194
1195 if test "$verbose" = "t"
1196 then
1197         exec 4>&2 3>&1
1198 else
1199         exec 4>test.output 3>&4
1200 fi
1201
1202 for skp in $NOTMUCH_SKIP_TESTS
1203 do
1204         to_skip=
1205         for skp in $NOTMUCH_SKIP_TESTS
1206         do
1207                 case "$this_test" in
1208                 $skp)
1209                         to_skip=t
1210                 esac
1211         done
1212         case "$to_skip" in
1213         t)
1214                 say_color skip >&3 "skipping test $this_test altogether"
1215                 say_color skip "skip all tests in $this_test"
1216                 test_done
1217         esac
1218 done
1219
1220 # Provide an implementation of the 'yes' utility
1221 yes () {
1222         if test $# = 0
1223         then
1224                 y=y
1225         else
1226                 y="$*"
1227         fi
1228
1229         while echo "$y"
1230         do
1231                 :
1232         done
1233 }
1234
1235 # Fix some commands on Windows
1236 case $(uname -s) in
1237 *MINGW*)
1238         # Windows has its own (incompatible) sort and find
1239         sort () {
1240                 /usr/bin/sort "$@"
1241         }
1242         find () {
1243                 /usr/bin/find "$@"
1244         }
1245         sum () {
1246                 md5sum "$@"
1247         }
1248         # git sees Windows-style pwd
1249         pwd () {
1250                 builtin pwd -W
1251         }
1252         # no POSIX permissions
1253         # backslashes in pathspec are converted to '/'
1254         # exec does not inherit the PID
1255         ;;
1256 *)
1257         test_set_prereq POSIXPERM
1258         test_set_prereq BSLASHPSPEC
1259         test_set_prereq EXECKEEPSPID
1260         ;;
1261 esac
1262
1263 test -z "$NO_PERL" && test_set_prereq PERL
1264 test -z "$NO_PYTHON" && test_set_prereq PYTHON
1265
1266 # test whether the filesystem supports symbolic links
1267 ln -s x y 2>/dev/null && test -h y 2>/dev/null && test_set_prereq SYMLINKS
1268 rm -f y
1269
1270 # declare prerequisites for external binaries used in tests
1271 test_declare_external_prereq dtach
1272 test_declare_external_prereq emacs
1273 test_declare_external_prereq ${TEST_EMACSCLIENT}
1274 test_declare_external_prereq gdb
1275 test_declare_external_prereq gpg
1276 test_declare_external_prereq python
1277 test_declare_external_prereq python2