1 ;;; ert.el --- Emacs Lisp Regression Testing -*- lexical-binding: t -*-
3 ;; Copyright (C) 2007-2008, 2010-2016 Free Software Foundation, Inc.
5 ;; Author: Christian Ohler <ohler@gnu.org>
6 ;; Keywords: lisp, tools
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;; ERT is a tool for automated testing in Emacs Lisp. Its main
26 ;; features are facilities for defining and running test cases and
27 ;; reporting the results as well as for debugging test failures
30 ;; The main entry points are `ert-deftest', which is similar to
31 ;; `defun' but defines a test, and `ert-run-tests-interactively',
32 ;; which runs tests and offers an interactive interface for inspecting
33 ;; results and debugging. There is also
34 ;; `ert-run-tests-batch-and-exit' for non-interactive use.
36 ;; The body of `ert-deftest' forms resembles a function body, but the
37 ;; additional operators `should', `should-not', `should-error' and
38 ;; `skip-unless' are available. `should' is similar to cl's `assert',
39 ;; but signals a different error when its condition is violated that
40 ;; is caught and processed by ERT. In addition, it analyzes its
41 ;; argument form and records information that helps debugging
42 ;; (`assert' tries to do something similar when its second argument
43 ;; SHOW-ARGS is true, but `should' is more sophisticated). For
44 ;; information on `should-not' and `should-error', see their
45 ;; docstrings. `skip-unless' skips the test immediately without
46 ;; processing further, this is useful for checking the test
47 ;; environment (like availability of features, external binaries, etc).
49 ;; See ERT's info manual as well as the docstrings for more details.
50 ;; To compile the manual, run `makeinfo ert.texinfo' in the ERT
51 ;; directory, then C-u M-x info ert.info in Emacs to view it.
53 ;; To see some examples of tests written in ERT, see its self-tests in
54 ;; ert-tests.el. Some of these are tricky due to the bootstrapping
55 ;; problem of writing tests for a testing tool, others test simple
56 ;; functions and are straightforward.
69 ;;; UI customization options.
72 "ERT, the Emacs Lisp regression testing tool."
76 (defface ert-test-result-expected
'((((class color
) (background light
))
78 (((class color
) (background dark
))
79 :background
"green3"))
80 "Face used for expected results in the ERT results buffer."
83 (defface ert-test-result-unexpected
'((((class color
) (background light
))
85 (((class color
) (background dark
))
87 "Face used for unexpected results in the ERT results buffer."
91 ;;; Copies/reimplementations of cl functions.
93 (defun ert-equal-including-properties (a b
)
94 "Return t if A and B have similar structure and contents.
96 This is like `equal-including-properties' except that it compares
97 the property values of text properties structurally (by
98 recursing) rather than with `eq'. Perhaps this is what
99 `equal-including-properties' should do in the first place; see
100 Emacs bug 6581 at URL `http://debbugs.gnu.org/cgi/bugreport.cgi?bug=6581'."
101 ;; This implementation is inefficient. Rather than making it
102 ;; efficient, let's hope bug 6581 gets fixed so that we can delete
104 (not (ert--explain-equal-including-properties a b
)))
107 ;;; Defining and locating tests.
109 ;; The data structure that represents a test case.
110 (cl-defstruct ert-test
113 (body (cl-assert nil
))
114 (most-recent-result nil
)
115 (expected-result-type ':passed
)
118 (defun ert-test-boundp (symbol)
119 "Return non-nil if SYMBOL names a test."
120 (and (get symbol
'ert--test
) t
))
122 (defun ert-get-test (symbol)
123 "If SYMBOL names a test, return that. Signal an error otherwise."
124 (unless (ert-test-boundp symbol
) (error "No test named `%S'" symbol
))
125 (get symbol
'ert--test
))
127 (defun ert-set-test (symbol definition
)
128 "Make SYMBOL name the test DEFINITION, and return DEFINITION."
129 (when (eq symbol
'nil
)
130 ;; We disallow nil since `ert-test-at-point' and related functions
131 ;; want to return a test name, but also need an out-of-band value
132 ;; on failure. Nil is the most natural out-of-band value; using 0
133 ;; or "" or signaling an error would be too awkward.
135 ;; Note that nil is still a valid value for the `name' slot in
136 ;; ert-test objects. It designates an anonymous test.
137 (error "Attempt to define a test named nil"))
138 (put symbol
'ert--test definition
)
141 (defun ert-make-test-unbound (symbol)
142 "Make SYMBOL name no test. Return SYMBOL."
143 (cl-remprop symbol
'ert--test
)
146 (defun ert--parse-keys-and-body (keys-and-body)
147 "Split KEYS-AND-BODY into keyword-and-value pairs and the remaining body.
149 KEYS-AND-BODY should have the form of a property list, with the
150 exception that only keywords are permitted as keys and that the
151 tail -- the body -- is a list of forms that does not start with a
154 Returns a two-element list containing the keys-and-values plist
156 (let ((extracted-key-accu '())
157 (remaining keys-and-body
))
158 (while (keywordp (car-safe remaining
))
159 (let ((keyword (pop remaining
)))
160 (unless (consp remaining
)
161 (error "Value expected after keyword %S in %S"
162 keyword keys-and-body
))
163 (when (assoc keyword extracted-key-accu
)
164 (warn "Keyword %S appears more than once in %S" keyword
166 (push (cons keyword
(pop remaining
)) extracted-key-accu
)))
167 (setq extracted-key-accu
(nreverse extracted-key-accu
))
168 (list (cl-loop for
(key . value
) in extracted-key-accu
174 (cl-defmacro ert-deftest
(name () &body docstring-keys-and-body
)
175 "Define NAME (a symbol) as a test.
177 BODY is evaluated as a `progn' when the test is run. It should
178 signal a condition on failure or just return if the test passes.
180 `should', `should-not', `should-error' and `skip-unless' are
181 useful for assertions in BODY.
183 Use `ert' to run tests interactively.
185 Tests that are expected to fail can be marked as such
186 using :expected-result. See `ert-test-result-type-p' for a
187 description of valid values for RESULT-TYPE.
189 \(fn NAME () [DOCSTRING] [:expected-result RESULT-TYPE] \
190 [:tags \\='(TAG...)] BODY...)"
191 (declare (debug (&define
:name test
192 name sexp
[&optional stringp
]
193 [&rest keywordp sexp
] def-body
))
196 (let ((documentation nil
)
197 (documentation-supplied-p nil
))
198 (when (stringp (car docstring-keys-and-body
))
199 (setq documentation
(pop docstring-keys-and-body
)
200 documentation-supplied-p t
))
201 (cl-destructuring-bind
202 ((&key
(expected-result nil expected-result-supplied-p
)
203 (tags nil tags-supplied-p
))
205 (ert--parse-keys-and-body docstring-keys-and-body
)
206 `(cl-macrolet ((skip-unless (form) `(ert--skip-unless ,form
)))
210 ,@(when documentation-supplied-p
211 `(:documentation
,documentation
))
212 ,@(when expected-result-supplied-p
213 `(:expected-result-type
,expected-result
))
214 ,@(when tags-supplied-p
216 :body
(lambda () ,@body
)))
217 ;; This hack allows `symbol-file' to associate `ert-deftest'
218 ;; forms with files, and therefore enables `find-function' to
219 ;; work with tests. However, it leads to warnings in
220 ;; `unload-feature', which doesn't know how to undefine tests
221 ;; and has no mechanism for extension.
222 (push '(ert-deftest .
,name
) current-load-list
)
225 ;; We use these `put' forms in addition to the (declare (indent)) in
226 ;; the defmacro form since the `declare' alone does not lead to
227 ;; correct indentation before the .el/.elc file is loaded.
228 ;; Autoloading these `put' forms solves this.
231 ;; TODO(ohler): Figure out what these mean and make sure they are correct.
232 (put 'ert-deftest
'lisp-indent-function
2)
233 (put 'ert-info
'lisp-indent-function
1))
235 (defvar ert--find-test-regexp
236 (concat "^\\s-*(ert-deftest"
237 find-function-space-re
239 "The regexp the `find-function' mechanisms use for finding test definitions.")
242 (define-error 'ert-test-failed
"Test failed")
243 (define-error 'ert-test-skipped
"Test skipped")
246 "Terminate the current test and mark it passed. Does not return."
247 (throw 'ert--pass nil
))
249 (defun ert-fail (data)
250 "Terminate the current test and mark it failed. Does not return.
251 DATA is displayed to the user and should state the reason of the failure."
252 (signal 'ert-test-failed
(list data
)))
254 (defun ert-skip (data)
255 "Terminate the current test and mark it skipped. Does not return.
256 DATA is displayed to the user and should state the reason for skipping."
257 (signal 'ert-test-skipped
(list data
)))
260 ;;; The `should' macros.
262 (defvar ert--should-execution-observer nil
)
264 (defun ert--signal-should-execution (form-description)
265 "Tell the current `should' form observer (if any) about FORM-DESCRIPTION."
266 (when ert--should-execution-observer
267 (funcall ert--should-execution-observer form-description
)))
269 (defun ert--special-operator-p (thing)
270 "Return non-nil if THING is a symbol naming a special operator."
272 (let ((definition (indirect-function thing
)))
273 (and (subrp definition
)
274 (eql (cdr (subr-arity definition
)) 'unevalled
)))))
276 (defun ert--expand-should-1 (whole form inner-expander
)
277 "Helper function for the `should' macro and its variants."
279 (macroexpand form
(cond
280 ((boundp 'macroexpand-all-environment
)
281 macroexpand-all-environment
)
282 ((boundp 'cl-macro-environment
)
283 cl-macro-environment
)))))
285 ((or (atom form
) (ert--special-operator-p (car form
)))
286 (let ((value (cl-gensym "value-")))
287 `(let ((,value
(cl-gensym "ert-form-evaluation-aborted-")))
288 ,(funcall inner-expander
290 `(list ',whole
:form
',form
:value
,value
)
294 (let ((fn-name (car form
))
295 (arg-forms (cdr form
)))
296 (cl-assert (or (symbolp fn-name
)
298 (eql (car fn-name
) 'lambda
)
299 (listp (cdr fn-name
)))))
300 (let ((fn (cl-gensym "fn-"))
301 (args (cl-gensym "args-"))
302 (value (cl-gensym "value-"))
303 (default-value (cl-gensym "ert-form-evaluation-aborted-")))
304 `(let ((,fn
(function ,fn-name
))
305 (,args
(list ,@arg-forms
)))
306 (let ((,value
',default-value
))
307 ,(funcall inner-expander
308 `(setq ,value
(apply ,fn
,args
))
309 `(nconc (list ',whole
)
310 (list :form
`(,,fn
,@,args
))
311 (unless (eql ,value
',default-value
)
312 (list :value
,value
))
314 (and (symbolp ',fn-name
)
315 (get ',fn-name
'ert-explainer
))))
318 (apply -explainer-
,args
)))))
322 (defun ert--expand-should (whole form inner-expander
)
323 "Helper function for the `should' macro and its variants.
325 Analyzes FORM and returns an expression that has the same
326 semantics under evaluation but records additional debugging
329 INNER-EXPANDER should be a function and is called with two
330 arguments: INNER-FORM and FORM-DESCRIPTION-FORM, where INNER-FORM
331 is an expression equivalent to FORM, and FORM-DESCRIPTION-FORM is
332 an expression that returns a description of FORM. INNER-EXPANDER
333 should return code that calls INNER-FORM and performs the checks
334 and error signaling specific to the particular variant of
335 `should'. The code that INNER-EXPANDER returns must not call
336 FORM-DESCRIPTION-FORM before it has called INNER-FORM."
337 (ert--expand-should-1
339 (lambda (inner-form form-description-form value-var
)
340 (let ((form-description (cl-gensym "form-description-")))
341 `(let (,form-description
)
342 ,(funcall inner-expander
345 (setq ,form-description
,form-description-form
)
346 (ert--signal-should-execution ,form-description
))
350 (cl-defmacro should
(form)
351 "Evaluate FORM. If it returns nil, abort the current test as failed.
353 Returns the value of FORM."
355 (ert--expand-should `(should ,form
) form
356 (lambda (inner-form form-description-form _value-var
)
358 (ert-fail ,form-description-form
)))))
360 (cl-defmacro should-not
(form)
361 "Evaluate FORM. If it returns non-nil, abort the current test as failed.
365 (ert--expand-should `(should-not ,form
) form
366 (lambda (inner-form form-description-form _value-var
)
367 `(unless (not ,inner-form
)
368 (ert-fail ,form-description-form
)))))
370 (defun ert--should-error-handle-error (form-description-fn
371 condition type exclude-subtypes
)
372 "Helper function for `should-error'.
374 Determines whether CONDITION matches TYPE and EXCLUDE-SUBTYPES,
375 and aborts the current test as failed if it doesn't."
376 (let ((signaled-conditions (get (car condition
) 'error-conditions
))
377 (handled-conditions (pcase-exhaustive type
379 ((pred symbolp
) (list type
)))))
380 (cl-assert signaled-conditions
)
381 (unless (cl-intersection signaled-conditions handled-conditions
)
383 (funcall form-description-fn
)
386 :fail-reason
(concat "the error signaled did not"
387 " have the expected type")))))
388 (when exclude-subtypes
389 (unless (member (car condition
) handled-conditions
)
391 (funcall form-description-fn
)
394 :fail-reason
(concat "the error signaled was a subtype"
395 " of the expected type"))))))))
397 ;; FIXME: The expansion will evaluate the keyword args (if any) in
398 ;; nonstandard order.
399 (cl-defmacro should-error
(form &rest keys
&key type exclude-subtypes
)
400 "Evaluate FORM and check that it signals an error.
402 The error signaled needs to match TYPE. TYPE should be a list
403 of condition names. (It can also be a non-nil symbol, which is
404 equivalent to a singleton list containing that symbol.) If
405 EXCLUDE-SUBTYPES is nil, the error matches TYPE if one of its
406 condition names is an element of TYPE. If EXCLUDE-SUBTYPES is
407 non-nil, the error matches TYPE if it is an element of TYPE.
409 If the error matches, returns (ERROR-SYMBOL . DATA) from the
410 error. If not, or if no error was signaled, abort the test as
413 (unless type
(setq type
''error
))
415 `(should-error ,form
,@keys
)
417 (lambda (inner-form form-description-form value-var
)
418 (let ((errorp (cl-gensym "errorp"))
419 (form-description-fn (cl-gensym "form-description-fn-")))
421 (,form-description-fn
(lambda () ,form-description-form
)))
422 (condition-case -condition-
424 ;; We can't use ,type here because we want to evaluate it.
427 (ert--should-error-handle-error ,form-description-fn
429 ,type
,exclude-subtypes
)
430 (setq ,value-var -condition-
)))
433 (funcall ,form-description-fn
)
435 :fail-reason
"did not signal an error")))))))))
437 (cl-defmacro ert--skip-unless
(form)
438 "Evaluate FORM. If it returns nil, skip the current test.
439 Errors during evaluation are caught and handled like nil."
441 (ert--expand-should `(skip-unless ,form
) form
442 (lambda (inner-form form-description-form _value-var
)
443 `(unless (ignore-errors ,inner-form
)
444 (ert-skip ,form-description-form
)))))
447 ;;; Explanation of `should' failures.
449 ;; TODO(ohler): Rework explanations so that they are displayed in a
450 ;; similar way to `ert-info' messages; in particular, allow text
451 ;; buttons in explanations that give more detail or open an ediff
452 ;; buffer. Perhaps explanations should be reported through `ert-info'
453 ;; rather than as part of the condition.
455 (defun ert--proper-list-p (x)
456 "Return non-nil if X is a proper list, nil otherwise."
458 for firstp
= t then nil
459 for fast
= x then
(cddr fast
)
460 for slow
= x then
(cdr slow
) do
461 (when (null fast
) (cl-return t
))
462 (when (not (consp fast
)) (cl-return nil
))
463 (when (null (cdr fast
)) (cl-return t
))
464 (when (not (consp (cdr fast
))) (cl-return nil
))
465 (when (and (not firstp
) (eq fast slow
)) (cl-return nil
))))
467 (defun ert--explain-format-atom (x)
468 "Format the atom X for `ert--explain-equal'."
470 ((pred characterp
) (list x
(format "#x%x" x
) (format "?%c" x
)))
471 ((pred integerp
) (list x
(format "#x%x" x
)))
474 (defun ert--explain-equal-rec (a b
)
475 "Return a programmer-readable explanation of why A and B are not `equal'.
476 Returns nil if they are."
477 (if (not (equal (type-of a
) (type-of b
)))
478 `(different-types ,a
,b
)
481 (let ((a-proper-p (ert--proper-list-p a
))
482 (b-proper-p (ert--proper-list-p b
)))
483 (if (not (eql (not a-proper-p
) (not b-proper-p
)))
484 `(one-list-proper-one-improper ,a
,b
)
486 (if (not (equal (length a
) (length b
)))
487 `(proper-lists-of-different-length ,(length a
) ,(length b
)
490 ,(cl-mismatch a b
:test
'equal
))
491 (cl-loop for i from
0
494 for xi
= (ert--explain-equal-rec ai bi
)
495 do
(when xi
(cl-return `(list-elt ,i
,xi
)))
496 finally
(cl-assert (equal a b
) t
)))
497 (let ((car-x (ert--explain-equal-rec (car a
) (car b
))))
500 (let ((cdr-x (ert--explain-equal-rec (cdr a
) (cdr b
))))
503 (cl-assert (equal a b
) t
)
506 (if (not (equal (length a
) (length b
)))
507 `(arrays-of-different-length ,(length a
) ,(length b
)
509 ,@(unless (char-table-p a
)
511 ,(cl-mismatch a b
:test
'equal
))))
512 (cl-loop for i from
0
515 for xi
= (ert--explain-equal-rec ai bi
)
516 do
(when xi
(cl-return `(array-elt ,i
,xi
)))
517 finally
(cl-assert (equal a b
) t
))))
519 (if (not (equal a b
))
520 (if (and (symbolp a
) (symbolp b
) (string= a b
))
521 `(different-symbols-with-the-same-name ,a
,b
)
522 `(different-atoms ,(ert--explain-format-atom a
)
523 ,(ert--explain-format-atom b
)))
526 (defun ert--explain-equal (a b
)
527 "Explainer function for `equal'."
528 ;; Do a quick comparison in C to avoid running our expensive
529 ;; comparison when possible.
532 (ert--explain-equal-rec a b
)))
533 (put 'equal
'ert-explainer
'ert--explain-equal
)
535 (defun ert--significant-plist-keys (plist)
536 "Return the keys of PLIST that have non-null values, in order."
537 (cl-assert (zerop (mod (length plist
) 2)) t
)
538 (cl-loop for
(key value . rest
) on plist by
#'cddr
539 unless
(or (null value
) (memq key accu
)) collect key into accu
540 finally
(cl-return accu
)))
542 (defun ert--plist-difference-explanation (a b
)
543 "Return a programmer-readable explanation of why A and B are different plists.
545 Returns nil if they are equivalent, i.e., have the same value for
546 each key, where absent values are treated as nil. The order of
547 key/value pairs in each list does not matter."
548 (cl-assert (zerop (mod (length a
) 2)) t
)
549 (cl-assert (zerop (mod (length b
) 2)) t
)
550 ;; Normalizing the plists would be another way to do this but it
551 ;; requires a total ordering on all lisp objects (since any object
552 ;; is valid as a text property key). Perhaps defining such an
553 ;; ordering is useful in other contexts, too, but it's a lot of
554 ;; work, so let's punt on it for now.
555 (let* ((keys-a (ert--significant-plist-keys a
))
556 (keys-b (ert--significant-plist-keys b
))
557 (keys-in-a-not-in-b (cl-set-difference keys-a keys-b
:test
'eq
))
558 (keys-in-b-not-in-a (cl-set-difference keys-b keys-a
:test
'eq
)))
559 (cl-flet ((explain-with-key (key)
560 (let ((value-a (plist-get a key
))
561 (value-b (plist-get b key
)))
562 (cl-assert (not (equal value-a value-b
)) t
)
563 `(different-properties-for-key
564 ,key
,(ert--explain-equal-including-properties value-a
566 (cond (keys-in-a-not-in-b
567 (explain-with-key (car keys-in-a-not-in-b
)))
569 (explain-with-key (car keys-in-b-not-in-a
)))
571 (cl-loop for key in keys-a
572 when
(not (equal (plist-get a key
) (plist-get b key
)))
573 return
(explain-with-key key
)))))))
575 (defun ert--abbreviate-string (s len suffixp
)
576 "Shorten string S to at most LEN chars.
578 If SUFFIXP is non-nil, returns a suffix of S, otherwise a prefix."
579 (let ((n (length s
)))
583 (substring s
(- n len
)))
585 (substring s
0 len
)))))
587 ;; TODO(ohler): Once bug 6581 is fixed, rename this to
588 ;; `ert--explain-equal-including-properties-rec' and add a fast-path
589 ;; wrapper like `ert--explain-equal'.
590 (defun ert--explain-equal-including-properties (a b
)
591 "Explainer function for `ert-equal-including-properties'.
593 Returns a programmer-readable explanation of why A and B are not
594 `ert-equal-including-properties', or nil if they are."
595 (if (not (equal a b
))
596 (ert--explain-equal a b
)
597 (cl-assert (stringp a
) t
)
598 (cl-assert (stringp b
) t
)
599 (cl-assert (eql (length a
) (length b
)) t
)
600 (cl-loop for i from
0 to
(length a
)
601 for props-a
= (text-properties-at i a
)
602 for props-b
= (text-properties-at i b
)
603 for difference
= (ert--plist-difference-explanation
606 (cl-return `(char ,i
,(substring-no-properties a i
(1+ i
))
609 ,(ert--abbreviate-string
610 (substring-no-properties a
0 i
)
613 ,(ert--abbreviate-string
614 (substring-no-properties a
(1+ i
))
616 ;; TODO(ohler): Get `equal-including-properties' fixed in
617 ;; Emacs, delete `ert-equal-including-properties', and
618 ;; re-enable this assertion.
619 ;;finally (cl-assert (equal-including-properties a b) t)
621 (put 'ert-equal-including-properties
623 'ert--explain-equal-including-properties
)
626 ;;; Implementation of `ert-info'.
628 ;; TODO(ohler): The name `info' clashes with
629 ;; `ert--test-execution-info'. One or both should be renamed.
630 (defvar ert--infos
'()
631 "The stack of `ert-info' infos that currently apply.
633 Bound dynamically. This is a list of (PREFIX . MESSAGE) pairs.")
635 (cl-defmacro ert-info
((message-form &key
((:prefix prefix-form
) "Info: "))
637 "Evaluate MESSAGE-FORM and BODY, and report the message if BODY fails.
639 To be used within ERT tests. MESSAGE-FORM should evaluate to a
640 string that will be displayed together with the test result if
641 the test fails. PREFIX-FORM should evaluate to a string as well
642 and is displayed in front of the value of MESSAGE-FORM."
643 (declare (debug ((form &rest
[sexp form
]) body
))
645 `(let ((ert--infos (cons (cons ,prefix-form
,message-form
) ert--infos
)))
650 ;;; Facilities for running a single test.
652 (defvar ert-debug-on-error nil
653 "Non-nil means enter debugger when a test fails or terminates with an error.")
655 ;; The data structures that represent the result of running a test.
656 (cl-defstruct ert-test-result
660 (cl-defstruct (ert-test-passed (:include ert-test-result
)))
661 (cl-defstruct (ert-test-result-with-condition (:include ert-test-result
))
662 (condition (cl-assert nil
))
663 (backtrace (cl-assert nil
))
664 (infos (cl-assert nil
)))
665 (cl-defstruct (ert-test-quit (:include ert-test-result-with-condition
)))
666 (cl-defstruct (ert-test-failed (:include ert-test-result-with-condition
)))
667 (cl-defstruct (ert-test-skipped (:include ert-test-result-with-condition
)))
668 (cl-defstruct (ert-test-aborted-with-non-local-exit
669 (:include ert-test-result
)))
672 (defun ert--record-backtrace ()
673 "Record the current backtrace (as a list) and return it."
674 ;; Since the backtrace is stored in the result object, result
675 ;; objects must only be printed with appropriate limits
676 ;; (`print-level' and `print-length') in place. For interactive
677 ;; use, the cost of ensuring this possibly outweighs the advantage
678 ;; of storing the backtrace for
679 ;; `ert-results-pop-to-backtrace-for-test-at-point' given that we
680 ;; already have `ert-results-rerun-test-debugging-errors-at-point'.
681 ;; For batch use, however, printing the backtrace may be useful.
683 ;; 6 is the number of frames our own debugger adds (when
684 ;; compiled; more when interpreted). FIXME: Need to describe a
685 ;; procedure for determining this constant.
687 for frame
= (backtrace-frame i
)
691 (defun ert--print-backtrace (backtrace)
692 "Format the backtrace BACKTRACE to the current buffer."
693 ;; This is essentially a reimplementation of Fbacktrace
694 ;; (src/eval.c), but for a saved backtrace, not the current one.
695 (let ((print-escape-newlines t
)
698 (dolist (frame backtrace
)
699 (pcase-exhaustive frame
700 (`(nil ,special-operator .
,arg-forms
)
703 (format " %S\n" (cons special-operator arg-forms
))))
706 (insert (format " %S(" fn
))
707 (cl-loop for firstp
= t then nil
711 (insert (format "%S" arg
)))
714 ;; A container for the state of the execution of a single test and
715 ;; environment data needed during its execution.
716 (cl-defstruct ert--test-execution-info
717 (test (cl-assert nil
))
718 (result (cl-assert nil
))
719 ;; A thunk that may be called when RESULT has been set to its final
720 ;; value and test execution should be terminated. Should not
722 (exit-continuation (cl-assert nil
))
723 ;; The binding of `debugger' outside of the execution of the test.
725 ;; The binding of `ert-debug-on-error' that is in effect for the
726 ;; execution of the current test. We store it to avoid being
727 ;; affected by any new bindings the test itself may establish. (I
728 ;; don't remember whether this feature is important.)
731 (defun ert--run-test-debugger (info args
)
732 "During a test run, `debugger' is bound to a closure that calls this function.
734 This function records failures and errors and either terminates
735 the test silently or calls the interactive debugger, as
738 INFO is the ert--test-execution-info corresponding to this test
739 run. ARGS are the arguments to `debugger'."
740 (cl-destructuring-bind (first-debugger-arg &rest more-debugger-args
)
742 (cl-ecase first-debugger-arg
743 ((lambda debug t exit nil
)
744 (apply (ert--test-execution-info-next-debugger info
) args
))
746 (let* ((condition (car more-debugger-args
))
747 (type (cl-case (car condition
)
749 ((ert-test-skipped) 'skipped
)
750 (otherwise 'failed
)))
751 (backtrace (ert--record-backtrace))
752 (infos (reverse ert--infos
)))
753 (setf (ert--test-execution-info-result info
)
756 (make-ert-test-quit :condition condition
760 (make-ert-test-skipped :condition condition
764 (make-ert-test-failed :condition condition
767 ;; Work around Emacs's heuristic (in eval.c) for detecting
768 ;; errors in the debugger.
769 (cl-incf num-nonmacro-input-events
)
770 ;; FIXME: We should probably implement more fine-grained
771 ;; control a la non-t `debug-on-error' here.
773 ((ert--test-execution-info-ert-debug-on-error info
)
774 (apply (ert--test-execution-info-next-debugger info
) args
))
776 (funcall (ert--test-execution-info-exit-continuation info
)))))))
778 (defun ert--run-test-internal (test-execution-info)
779 "Low-level function to run a test according to TEST-EXECUTION-INFO.
781 This mainly sets up debugger-related bindings."
782 (setf (ert--test-execution-info-next-debugger test-execution-info
) debugger
783 (ert--test-execution-info-ert-debug-on-error test-execution-info
)
786 ;; For now, each test gets its own temp buffer and its own
787 ;; window excursion, just to be safe. If this turns out to be
788 ;; too expensive, we can remove it.
790 (save-window-excursion
791 (let ((debugger (lambda (&rest args
)
792 (ert--run-test-debugger test-execution-info
796 ;; FIXME: Do we need to store the old binding of this
797 ;; and consider it in `ert--run-test-debugger'?
798 (debug-ignored-errors nil
)
800 (funcall (ert-test-body (ert--test-execution-info-test
801 test-execution-info
))))))
803 (setf (ert--test-execution-info-result test-execution-info
)
804 (make-ert-test-passed))
807 (defun ert--force-message-log-buffer-truncation ()
808 "Immediately truncate *Messages* buffer according to `message-log-max'.
810 This can be useful after reducing the value of `message-log-max'."
811 (with-current-buffer (messages-buffer)
812 ;; This is a reimplementation of this part of message_dolog() in xdisp.c:
813 ;; if (NATNUMP (Vmessage_log_max))
815 ;; scan_newline (Z, Z_BYTE, BEG, BEG_BYTE,
816 ;; -XFASTINT (Vmessage_log_max) - 1, 0);
817 ;; del_range_both (BEG, BEG_BYTE, PT, PT_BYTE, 0);
819 (when (and (integerp message-log-max
) (>= message-log-max
0))
820 (let ((begin (point-min))
822 (goto-char (point-max))
823 (forward-line (- message-log-max
))
825 (inhibit-read-only t
))
826 (delete-region begin end
)))))
828 (defvar ert--running-tests nil
829 "List of tests that are currently in execution.
831 This list is empty while no test is running, has one element
832 while a test is running, two elements while a test run from
833 inside a test is running, etc. The list is in order of nesting,
834 innermost test first.
836 The elements are of type `ert-test'.")
838 (defun ert-run-test (ert-test)
841 Returns the result and stores it in ERT-TEST's `most-recent-result' slot."
842 (setf (ert-test-most-recent-result ert-test
) nil
)
845 (with-current-buffer (messages-buffer)
846 (point-max-marker))))
848 (let ((info (make-ert--test-execution-info
851 (make-ert-test-aborted-with-non-local-exit)
852 :exit-continuation
(lambda ()
853 (cl-return-from error nil
))))
854 (should-form-accu (list)))
856 (let ((ert--should-execution-observer
857 (lambda (form-description)
858 (push form-description should-form-accu
)))
860 (ert--running-tests (cons ert-test ert--running-tests
)))
861 (ert--run-test-internal info
))
862 (let ((result (ert--test-execution-info-result info
)))
863 (setf (ert-test-result-messages result
)
864 (with-current-buffer (messages-buffer)
865 (buffer-substring begin-marker
(point-max))))
866 (ert--force-message-log-buffer-truncation)
867 (setq should-form-accu
(nreverse should-form-accu
))
868 (setf (ert-test-result-should-forms result
)
870 (setf (ert-test-most-recent-result ert-test
) result
))))
871 (set-marker begin-marker nil
))))
872 (ert-test-most-recent-result ert-test
))
874 (defun ert-running-test ()
875 "Return the top-level test currently executing."
876 (car (last ert--running-tests
)))
881 (defun ert-test-result-type-p (result result-type
)
882 "Return non-nil if RESULT matches type RESULT-TYPE.
886 nil -- Never matches.
888 :failed, :passed, :skipped -- Matches corresponding results.
889 \(and TYPES...) -- Matches if all TYPES match.
890 \(or TYPES...) -- Matches if some TYPES match.
891 \(not TYPE) -- Matches if TYPE does not match.
892 \(satisfies PREDICATE) -- Matches if PREDICATE returns true when called with
894 ;; It would be easy to add `member' and `eql' types etc., but I
895 ;; haven't bothered yet.
896 (pcase-exhaustive result-type
899 (:failed
(ert-test-failed-p result
))
900 (:passed
(ert-test-passed-p result
))
901 (:skipped
(ert-test-skipped-p result
))
902 (`(,operator .
,operands
)
905 (cl-case (length operands
)
908 (and (ert-test-result-type-p result
(car operands
))
909 (ert-test-result-type-p result
`(and ,@(cdr operands
)))))))
911 (cl-case (length operands
)
914 (or (ert-test-result-type-p result
(car operands
))
915 (ert-test-result-type-p result
`(or ,@(cdr operands
)))))))
917 (cl-assert (eql (length operands
) 1))
918 (not (ert-test-result-type-p result
(car operands
))))
920 (cl-assert (eql (length operands
) 1))
921 (funcall (car operands
) result
))))))
923 (defun ert-test-result-expected-p (test result
)
924 "Return non-nil if TEST's expected result type matches RESULT."
926 (ert-test-result-type-p result
:skipped
)
927 (ert-test-result-type-p result
(ert-test-expected-result-type test
))))
929 (defun ert-select-tests (selector universe
)
930 "Return a list of tests that match SELECTOR.
932 UNIVERSE specifies the set of tests to select from; it should be a list
933 of tests, or t, which refers to all tests named by symbols in `obarray'.
937 nil -- Selects the empty set.
938 t -- Selects UNIVERSE.
939 :new -- Selects all tests that have not been run yet.
940 :failed, :passed -- Select tests according to their most recent result.
941 :expected, :unexpected -- Select tests according to their most recent result.
942 a string -- A regular expression selecting all tests with matching names.
943 a test -- (i.e., an object of the ert-test data-type) Selects that test.
944 a symbol -- Selects the test that the symbol names, errors if none.
945 \(member TESTS...) -- Selects the elements of TESTS, a list of tests
946 or symbols naming tests.
947 \(eql TEST) -- Selects TEST, a test or a symbol naming a test.
948 \(and SELECTORS...) -- Selects the tests that match all SELECTORS.
949 \(or SELECTORS...) -- Selects the tests that match any of the SELECTORS.
950 \(not SELECTOR) -- Selects all tests that do not match SELECTOR.
951 \(tag TAG) -- Selects all tests that have TAG on their tags list.
952 A tag is an arbitrary label you can apply when you define a test.
953 \(satisfies PREDICATE) -- Selects all tests that satisfy PREDICATE.
954 PREDICATE is a function that takes an ert-test object as argument,
955 and returns non-nil if it is selected.
957 Only selectors that require a superset of tests, such
958 as (satisfies ...), strings, :new, etc. make use of UNIVERSE.
959 Selectors that do not, such as (member ...), just return the
960 set implied by them without checking whether it is really
961 contained in UNIVERSE."
962 ;; This code needs to match the cases in
963 ;; `ert-insert-human-readable-selector'.
964 (pcase-exhaustive selector
966 ('t
(pcase-exhaustive universe
967 ((pred listp
) universe
)
968 (`t
(ert-select-tests "" universe
))))
969 (:new
(ert-select-tests
970 `(satisfies ,(lambda (test)
971 (null (ert-test-most-recent-result test
))))
973 (:failed
(ert-select-tests
974 `(satisfies ,(lambda (test)
975 (ert-test-result-type-p
976 (ert-test-most-recent-result test
)
979 (:passed
(ert-select-tests
980 `(satisfies ,(lambda (test)
981 (ert-test-result-type-p
982 (ert-test-most-recent-result test
)
985 (:expected
(ert-select-tests
988 (ert-test-result-expected-p
990 (ert-test-most-recent-result test
))))
992 (:unexpected
(ert-select-tests `(not :expected
) universe
))
994 (pcase-exhaustive universe
995 (`t
(mapcar #'ert-get-test
996 (apropos-internal selector
#'ert-test-boundp
)))
998 (cl-remove-if-not (lambda (test)
999 (and (ert-test-name test
)
1000 (string-match selector
1002 (ert-test-name test
)))))
1004 ((pred ert-test-p
) (list selector
))
1006 (cl-assert (ert-test-boundp selector
))
1007 (list (ert-get-test selector
)))
1008 (`(,operator .
,operands
)
1011 (mapcar (lambda (purported-test)
1012 (pcase-exhaustive purported-test
1014 (cl-assert (ert-test-boundp purported-test
))
1015 (ert-get-test purported-test
))
1016 ((pred ert-test-p
) purported-test
)))
1019 (cl-assert (eql (length operands
) 1))
1020 (ert-select-tests `(member ,@operands
) universe
))
1022 ;; Do these definitions of AND, NOT and OR satisfy de
1023 ;; Morgan's laws? Should they?
1024 (cl-case (length operands
)
1025 (0 (ert-select-tests 't universe
))
1026 (t (ert-select-tests `(and ,@(cdr operands
))
1027 (ert-select-tests (car operands
)
1030 (cl-assert (eql (length operands
) 1))
1031 (let ((all-tests (ert-select-tests 't universe
)))
1032 (cl-set-difference all-tests
1033 (ert-select-tests (car operands
)
1036 (cl-case (length operands
)
1037 (0 (ert-select-tests 'nil universe
))
1038 (t (cl-union (ert-select-tests (car operands
) universe
)
1039 (ert-select-tests `(or ,@(cdr operands
))
1042 (cl-assert (eql (length operands
) 1))
1043 (let ((tag (car operands
)))
1044 (ert-select-tests `(satisfies
1046 (member tag
(ert-test-tags test
))))
1049 (cl-assert (eql (length operands
) 1))
1050 (cl-remove-if-not (car operands
)
1051 (ert-select-tests 't universe
)))))))
1053 (defun ert--insert-human-readable-selector (selector)
1054 "Insert a human-readable presentation of SELECTOR into the current buffer."
1055 ;; This is needed to avoid printing the (huge) contents of the
1056 ;; `backtrace' slot of the result objects in the
1057 ;; `most-recent-result' slots of test case objects in (eql ...) or
1058 ;; (member ...) selectors.
1059 (cl-labels ((rec (selector)
1060 ;; This code needs to match the cases in
1061 ;; `ert-select-tests'.
1062 (pcase-exhaustive selector
1064 ;; 'nil 't :new :failed :passed :expected :unexpected
1069 (if (ert-test-name selector
)
1070 (make-symbol (format "<%S>" (ert-test-name selector
)))
1071 (make-symbol "<unnamed test>")))
1072 (`(,operator .
,operands
)
1074 ((or 'member
'eql
'and
'not
'or
)
1075 `(,operator
,@(mapcar #'rec operands
)))
1076 ((or 'tag
'satisfies
)
1078 (insert (format "%S" (rec selector
)))))
1081 ;;; Facilities for running a whole set of tests.
1083 ;; The data structure that contains the set of tests being executed
1084 ;; during one particular test run, their results, the state of the
1085 ;; execution, and some statistics.
1087 ;; The data about results and expected results of tests may seem
1088 ;; redundant here, since the test objects also carry such information.
1089 ;; However, the information in the test objects may be more recent, it
1090 ;; may correspond to a different test run. We need the information
1091 ;; that corresponds to this run in order to be able to update the
1092 ;; statistics correctly when a test is re-run interactively and has a
1093 ;; different result than before.
1094 (cl-defstruct ert--stats
1095 (selector (cl-assert nil
))
1096 ;; The tests, in order.
1097 (tests (cl-assert nil
) :type vector
)
1098 ;; A map of test names (or the test objects themselves for unnamed
1099 ;; tests) to indices into the `tests' vector.
1100 (test-map (cl-assert nil
) :type hash-table
)
1101 ;; The results of the tests during this run, in order.
1102 (test-results (cl-assert nil
) :type vector
)
1103 ;; The start times of the tests, in order, as reported by
1105 (test-start-times (cl-assert nil
) :type vector
)
1106 ;; The end times of the tests, in order, as reported by
1108 (test-end-times (cl-assert nil
) :type vector
)
1110 (passed-unexpected 0)
1112 (failed-unexpected 0)
1118 ;; The time at or after which the next redisplay should occur, as a
1120 (next-redisplay 0.0))
1122 (defun ert-stats-completed-expected (stats)
1123 "Return the number of tests in STATS that had expected results."
1124 (+ (ert--stats-passed-expected stats
)
1125 (ert--stats-failed-expected stats
)))
1127 (defun ert-stats-completed-unexpected (stats)
1128 "Return the number of tests in STATS that had unexpected results."
1129 (+ (ert--stats-passed-unexpected stats
)
1130 (ert--stats-failed-unexpected stats
)))
1132 (defun ert-stats-skipped (stats)
1133 "Number of tests in STATS that have skipped."
1134 (ert--stats-skipped stats
))
1136 (defun ert-stats-completed (stats)
1137 "Number of tests in STATS that have run so far."
1138 (+ (ert-stats-completed-expected stats
)
1139 (ert-stats-completed-unexpected stats
)
1140 (ert-stats-skipped stats
)))
1142 (defun ert-stats-total (stats)
1143 "Number of tests in STATS, regardless of whether they have run yet."
1144 (length (ert--stats-tests stats
)))
1146 ;; The stats object of the current run, dynamically bound. This is
1147 ;; used for the mode line progress indicator.
1148 (defvar ert--current-run-stats nil
)
1150 (defun ert--stats-test-key (test)
1151 "Return the key used for TEST in the test map of ert--stats objects.
1153 Returns the name of TEST if it has one, or TEST itself otherwise."
1154 (or (ert-test-name test
) test
))
1156 (defun ert--stats-set-test-and-result (stats pos test result
)
1157 "Change STATS by replacing the test at position POS with TEST and RESULT.
1159 Also changes the counters in STATS to match."
1160 (let* ((tests (ert--stats-tests stats
))
1161 (results (ert--stats-test-results stats
))
1162 (old-test (aref tests pos
))
1163 (map (ert--stats-test-map stats
)))
1164 (cl-flet ((update (d)
1165 (if (ert-test-result-expected-p (aref tests pos
)
1167 (cl-etypecase (aref results pos
)
1169 (cl-incf (ert--stats-passed-expected stats
) d
))
1171 (cl-incf (ert--stats-failed-expected stats
) d
))
1173 (cl-incf (ert--stats-skipped stats
) d
))
1175 (ert-test-aborted-with-non-local-exit)
1177 (cl-etypecase (aref results pos
)
1179 (cl-incf (ert--stats-passed-unexpected stats
) d
))
1181 (cl-incf (ert--stats-failed-unexpected stats
) d
))
1183 (cl-incf (ert--stats-skipped stats
) d
))
1185 (ert-test-aborted-with-non-local-exit)
1187 ;; Adjust counters to remove the result that is currently in stats.
1189 ;; Put new test and result into stats.
1190 (setf (aref tests pos
) test
1191 (aref results pos
) result
)
1192 (remhash (ert--stats-test-key old-test
) map
)
1193 (setf (gethash (ert--stats-test-key test
) map
) pos
)
1194 ;; Adjust counters to match new result.
1198 (defun ert--make-stats (tests selector
)
1199 "Create a new `ert--stats' object for running TESTS.
1201 SELECTOR is the selector that was used to select TESTS."
1202 (setq tests
(cl-coerce tests
'vector
))
1203 (let ((map (make-hash-table :size
(length tests
))))
1204 (cl-loop for i from
0
1205 for test across tests
1206 for key
= (ert--stats-test-key test
) do
1207 (cl-assert (not (gethash key map
)))
1208 (setf (gethash key map
) i
))
1209 (make-ert--stats :selector selector
1212 :test-results
(make-vector (length tests
) nil
)
1213 :test-start-times
(make-vector (length tests
) nil
)
1214 :test-end-times
(make-vector (length tests
) nil
))))
1216 (defun ert-run-or-rerun-test (stats test listener
)
1217 ;; checkdoc-order: nil
1218 "Run the single test TEST and record the result using STATS and LISTENER."
1219 (let ((ert--current-run-stats stats
)
1220 (pos (ert--stats-test-pos stats test
)))
1221 (ert--stats-set-test-and-result stats pos test nil
)
1222 ;; Call listener after setting/before resetting
1223 ;; (ert--stats-current-test stats); the listener might refresh the
1224 ;; mode line display, and if the value is not set yet/any more
1225 ;; during this refresh, the mode line will flicker unnecessarily.
1226 (setf (ert--stats-current-test stats
) test
)
1227 (funcall listener
'test-started stats test
)
1228 (setf (ert-test-most-recent-result test
) nil
)
1229 (setf (aref (ert--stats-test-start-times stats
) pos
) (current-time))
1232 (setf (aref (ert--stats-test-end-times stats
) pos
) (current-time))
1233 (let ((result (ert-test-most-recent-result test
)))
1234 (ert--stats-set-test-and-result stats pos test result
)
1235 (funcall listener
'test-ended stats test result
))
1236 (setf (ert--stats-current-test stats
) nil
))))
1238 (defun ert-run-tests (selector listener
)
1239 "Run the tests specified by SELECTOR, sending progress updates to LISTENER."
1240 (let* ((tests (ert-select-tests selector t
))
1241 (stats (ert--make-stats tests selector
)))
1242 (setf (ert--stats-start-time stats
) (current-time))
1243 (funcall listener
'run-started stats
)
1246 (let ((ert--current-run-stats stats
))
1247 (force-mode-line-update)
1250 (cl-loop for test in tests do
1251 (ert-run-or-rerun-test stats test listener
))
1252 (setq abortedp nil
))
1253 (setf (ert--stats-aborted-p stats
) abortedp
)
1254 (setf (ert--stats-end-time stats
) (current-time))
1255 (funcall listener
'run-ended stats abortedp
)))
1256 (force-mode-line-update))
1259 (defun ert--stats-test-pos (stats test
)
1260 ;; checkdoc-order: nil
1261 "Return the position (index) of TEST in the run represented by STATS."
1262 (gethash (ert--stats-test-key test
) (ert--stats-test-map stats
)))
1265 ;;; Formatting functions shared across UIs.
1267 (defun ert--format-time-iso8601 (time)
1268 "Format TIME in the variant of ISO 8601 used for timestamps in ERT."
1269 (format-time-string "%Y-%m-%d %T%z" time
))
1271 (defun ert-char-for-test-result (result expectedp
)
1272 "Return a character that represents the test result RESULT.
1274 EXPECTEDP specifies whether the result was expected."
1275 (let ((s (cl-etypecase result
1276 (ert-test-passed ".P")
1277 (ert-test-failed "fF")
1278 (ert-test-skipped "sS")
1280 (ert-test-aborted-with-non-local-exit "aA")
1281 (ert-test-quit "qQ"))))
1282 (elt s
(if expectedp
0 1))))
1284 (defun ert-string-for-test-result (result expectedp
)
1285 "Return a string that represents the test result RESULT.
1287 EXPECTEDP specifies whether the result was expected."
1288 (let ((s (cl-etypecase result
1289 (ert-test-passed '("passed" "PASSED"))
1290 (ert-test-failed '("failed" "FAILED"))
1291 (ert-test-skipped '("skipped" "SKIPPED"))
1292 (null '("unknown" "UNKNOWN"))
1293 (ert-test-aborted-with-non-local-exit '("aborted" "ABORTED"))
1294 (ert-test-quit '("quit" "QUIT")))))
1295 (elt s
(if expectedp
0 1))))
1297 (defun ert--pp-with-indentation-and-newline (object)
1298 "Pretty-print OBJECT, indenting it to the current column of point.
1299 Ensures a final newline is inserted."
1300 (let ((begin (point))
1301 (pp-escape-newlines nil
))
1302 (pp object
(current-buffer))
1303 (unless (bolp) (insert "\n"))
1308 (defun ert--insert-infos (result)
1309 "Insert `ert-info' infos from RESULT into current buffer.
1311 RESULT must be an `ert-test-result-with-condition'."
1312 (cl-check-type result ert-test-result-with-condition
)
1313 (dolist (info (ert-test-result-with-condition-infos result
))
1314 (cl-destructuring-bind (prefix . message
) info
1315 (let ((begin (point))
1316 (indentation (make-string (+ (length prefix
) 4) ?\s
))
1320 (insert message
"\n")
1321 (setq end
(point-marker))
1325 (while (< (point) end
)
1326 (insert indentation
)
1328 (when end
(set-marker end nil
)))))))
1331 ;;; Running tests in batch mode.
1333 (defvar ert-batch-backtrace-right-margin
70
1334 "The maximum line length for printing backtraces in `ert-run-tests-batch'.")
1337 (defun ert-run-tests-batch (&optional selector
)
1338 "Run the tests specified by SELECTOR, printing results to the terminal.
1340 SELECTOR works as described in `ert-select-tests', except if
1341 SELECTOR is nil, in which case all tests rather than none will be
1342 run; this makes the command line \"emacs -batch -l my-tests.el -f
1343 ert-run-tests-batch-and-exit\" useful.
1345 Returns the stats object."
1346 (unless selector
(setq selector
't
))
1349 (lambda (event-type &rest event-args
)
1350 (cl-ecase event-type
1352 (cl-destructuring-bind (stats) event-args
1353 (message "Running %s tests (%s)"
1354 (length (ert--stats-tests stats
))
1355 (ert--format-time-iso8601 (ert--stats-start-time stats
)))))
1357 (cl-destructuring-bind (stats abortedp
) event-args
1358 (let ((unexpected (ert-stats-completed-unexpected stats
))
1359 (skipped (ert-stats-skipped stats
))
1360 (expected-failures (ert--stats-failed-expected stats
)))
1361 (message "\n%sRan %s tests, %s results as expected%s%s (%s)%s\n"
1365 (ert-stats-total stats
)
1366 (ert-stats-completed-expected stats
)
1367 (if (zerop unexpected
)
1369 (format ", %s unexpected" unexpected
))
1372 (format ", %s skipped" skipped
))
1373 (ert--format-time-iso8601 (ert--stats-end-time stats
))
1374 (if (zerop expected-failures
)
1376 (format "\n%s expected failures" expected-failures
)))
1377 (unless (zerop unexpected
)
1378 (message "%s unexpected results:" unexpected
)
1379 (cl-loop for test across
(ert--stats-tests stats
)
1380 for result
= (ert-test-most-recent-result test
) do
1381 (when (not (ert-test-result-expected-p test result
))
1383 (ert-string-for-test-result result nil
)
1384 (ert-test-name test
))))
1386 (unless (zerop skipped
)
1387 (message "%s skipped results:" skipped
)
1388 (cl-loop for test across
(ert--stats-tests stats
)
1389 for result
= (ert-test-most-recent-result test
) do
1390 (when (ert-test-result-type-p result
:skipped
)
1392 (ert-string-for-test-result result nil
)
1393 (ert-test-name test
))))
1394 (message "%s" "")))))
1398 (cl-destructuring-bind (stats test result
) event-args
1399 (unless (ert-test-result-expected-p test result
)
1400 (cl-etypecase result
1402 (message "Test %S passed unexpectedly" (ert-test-name test
)))
1403 (ert-test-result-with-condition
1404 (message "Test %S backtrace:" (ert-test-name test
))
1406 (ert--print-backtrace (ert-test-result-with-condition-backtrace
1408 (goto-char (point-min))
1410 (let ((start (point))
1411 (end (progn (end-of-line) (point))))
1413 (+ start ert-batch-backtrace-right-margin
)))
1414 (message "%s" (buffer-substring-no-properties
1418 (ert--insert-infos result
)
1420 (let ((print-escape-newlines t
)
1423 (ert--pp-with-indentation-and-newline
1424 (ert-test-result-with-condition-condition result
)))
1425 (goto-char (1- (point-max)))
1426 (cl-assert (looking-at "\n"))
1428 (message "Test %S condition:" (ert-test-name test
))
1429 (message "%s" (buffer-string))))
1430 (ert-test-aborted-with-non-local-exit
1431 (message "Test %S aborted with non-local exit"
1432 (ert-test-name test
)))
1434 (message "Quit during %S" (ert-test-name test
)))))
1435 (let* ((max (prin1-to-string (length (ert--stats-tests stats
))))
1436 (format-string (concat "%9s %"
1437 (prin1-to-string (length max
))
1439 (message format-string
1440 (ert-string-for-test-result result
1441 (ert-test-result-expected-p
1443 (1+ (ert--stats-test-pos stats test
))
1444 (ert-test-name test
)))))))))
1447 (defun ert-run-tests-batch-and-exit (&optional selector
)
1448 "Like `ert-run-tests-batch', but exits Emacs when done.
1450 The exit status will be 0 if all test results were as expected, 1
1451 on unexpected results, or 2 if the tool detected an error outside
1452 of the tests (e.g. invalid SELECTOR or bug in the code that runs
1455 (let ((stats (ert-run-tests-batch selector
)))
1456 (kill-emacs (if (zerop (ert-stats-completed-unexpected stats
)) 0 1)))
1459 (message "Error running tests")
1464 (defun ert-summarize-tests-batch-and-exit ()
1465 "Summarize the results of testing.
1466 Expects to be called in batch mode, with logfiles as command-line arguments.
1467 The logfiles should have the `ert-run-tests-batch' format. When finished,
1468 this exits Emacs, with status as per `ert-run-tests-batch-and-exit'."
1470 (user-error "This function is only for use in batch mode"))
1471 (let ((nlogs (length command-line-args-left
))
1472 (ntests 0) (nrun 0) (nexpected 0) (nunexpected 0) (nskipped 0)
1473 nnotrun logfile notests badtests unexpected
)
1475 (while (setq logfile
(pop command-line-args-left
))
1477 (insert-file-contents logfile
)
1478 (if (not (re-search-forward "^Running \\([0-9]+\\) tests" nil t
))
1479 (push logfile notests
)
1480 (setq ntests
(+ ntests
(string-to-number (match-string 1))))
1481 (if (not (re-search-forward "^\\(Aborted: \\)?\
1482 Ran \\([0-9]+\\) tests, \\([0-9]+\\) results as expected\
1483 \\(?:, \\([0-9]+\\) unexpected\\)?\
1484 \\(?:, \\([0-9]+\\) skipped\\)?" nil t
))
1485 (push logfile badtests
)
1486 (if (match-string 1) (push logfile badtests
))
1487 (setq nrun
(+ nrun
(string-to-number (match-string 2)))
1488 nexpected
(+ nexpected
(string-to-number (match-string 3))))
1489 (when (match-string 4)
1490 (push logfile unexpected
)
1491 (setq nunexpected
(+ nunexpected
1492 (string-to-number (match-string 4)))))
1493 (if (match-string 5)
1494 (setq nskipped
(+ nskipped
1495 (string-to-number (match-string 5)))))))))
1496 (setq nnotrun
(- ntests nrun
))
1497 (message "\nSUMMARY OF TEST RESULTS")
1498 (message "-----------------------")
1499 (message "Files examined: %d" nlogs
)
1500 (message "Ran %d tests%s, %d results as expected%s%s"
1502 (if (zerop nnotrun
) "" (format ", %d failed to run" nnotrun
))
1504 (if (zerop nunexpected
)
1506 (format ", %d unexpected" nunexpected
))
1507 (if (zerop nskipped
)
1509 (format ", %d skipped" nskipped
)))
1511 (message "%d files did not contain any tests:" (length notests
))
1512 (mapc (lambda (l) (message " %s" l
)) notests
))
1514 (message "%d files did not finish:" (length badtests
))
1515 (mapc (lambda (l) (message " %s" l
)) badtests
))
1517 (message "%d files contained unexpected results:" (length unexpected
))
1518 (mapc (lambda (l) (message " %s" l
)) unexpected
))
1519 (kill-emacs (cond ((or notests badtests
(not (zerop nnotrun
))) 2)
1523 ;;; Utility functions for load/unload actions.
1525 (defun ert--activate-font-lock-keywords ()
1526 "Activate font-lock keywords for some of ERT's symbols."
1527 (font-lock-add-keywords
1529 '(("(\\(\\<ert-deftest\\)\\>\\s *\\(\\(?:\\sw\\|\\s_\\)+\\)?"
1530 (1 font-lock-keyword-face nil t
)
1531 (2 font-lock-function-name-face nil t
)))))
1533 (cl-defun ert--remove-from-list (list-var element
&key key test
)
1534 "Remove ELEMENT from the value of LIST-VAR if present.
1536 This can be used as an inverse of `add-to-list'."
1537 (unless key
(setq key
#'identity
))
1538 (unless test
(setq test
#'equal
))
1539 (setf (symbol-value list-var
)
1541 (symbol-value list-var
)
1546 ;;; Some basic interactive functions.
1548 (defun ert-read-test-name (prompt &optional default history
1549 add-default-to-prompt
)
1550 "Read the name of a test and return it as a symbol.
1552 Prompt with PROMPT. If DEFAULT is a valid test name, use it as a
1553 default. HISTORY is the history to use; see `completing-read'.
1554 If ADD-DEFAULT-TO-PROMPT is non-nil, PROMPT will be modified to
1555 include the default, if any.
1557 Signals an error if no test name was read."
1558 (cl-etypecase default
1559 (string (let ((symbol (intern-soft default
)))
1560 (unless (and symbol
(ert-test-boundp symbol
))
1561 (setq default nil
))))
1562 (symbol (setq default
1563 (if (ert-test-boundp default
)
1564 (symbol-name default
)
1566 (ert-test (setq default
(ert-test-name default
))))
1567 (when add-default-to-prompt
1568 (setq prompt
(if (null default
)
1569 (format "%s: " prompt
)
1570 (format "%s (default %s): " prompt default
))))
1571 (let ((input (completing-read prompt obarray
#'ert-test-boundp
1572 t nil history default nil
)))
1573 ;; completing-read returns an empty string if default was nil and
1574 ;; the user just hit enter.
1575 (let ((sym (intern-soft input
)))
1576 (if (ert-test-boundp sym
)
1578 (error "Input does not name a test")))))
1580 (defun ert-read-test-name-at-point (prompt)
1581 "Read the name of a test and return it as a symbol.
1582 As a default, use the symbol at point, or the test at point if in
1583 the ERT results buffer. Prompt with PROMPT, augmented with the
1585 (ert-read-test-name prompt
(ert-test-at-point) nil t
))
1587 (defun ert-find-test-other-window (test-name)
1588 "Find, in another window, the definition of TEST-NAME."
1589 (interactive (list (ert-read-test-name-at-point "Find test definition: ")))
1590 (find-function-do-it test-name
'ert-deftest
'switch-to-buffer-other-window
))
1592 (defun ert-delete-test (test-name)
1593 "Make the test TEST-NAME unbound.
1595 Nothing more than an interactive interface to `ert-make-test-unbound'."
1596 (interactive (list (ert-read-test-name-at-point "Delete test")))
1597 (ert-make-test-unbound test-name
))
1599 (defun ert-delete-all-tests ()
1600 "Make all symbols in `obarray' name no test."
1602 (when (called-interactively-p 'any
)
1603 (unless (y-or-n-p "Delete all tests? ")
1605 ;; We can't use `ert-select-tests' here since that gives us only
1606 ;; test objects, and going from them back to the test name symbols
1607 ;; can fail if the `ert-test' defstruct has been redefined.
1608 (mapc #'ert-make-test-unbound
(apropos-internal "" #'ert-test-boundp
))
1612 ;;; Display of test progress and results.
1614 ;; An entry in the results buffer ewoc. There is one entry per test.
1615 (cl-defstruct ert--ewoc-entry
1616 (test (cl-assert nil
))
1617 ;; If the result of this test was expected, its ewoc entry is hidden
1619 (hidden-p (cl-assert nil
))
1620 ;; An ewoc entry may be collapsed to hide details such as the error
1623 ;; I'm not sure the ability to expand and collapse entries is still
1624 ;; a useful feature.
1626 ;; By default, the ewoc entry presents the error condition with
1627 ;; certain limits on how much to print (`print-level',
1628 ;; `print-length'). The user can interactively switch to a set of
1630 (extended-printer-limits-p nil
))
1632 ;; Variables local to the results buffer.
1635 (defvar ert--results-ewoc
)
1636 ;; The stats object.
1637 (defvar ert--results-stats
)
1638 ;; A string with one character per test. Each character represents
1639 ;; the result of the corresponding test. The string is displayed near
1640 ;; the top of the buffer and serves as a progress bar.
1641 (defvar ert--results-progress-bar-string
)
1642 ;; The position where the progress bar button begins.
1643 (defvar ert--results-progress-bar-button-begin
)
1644 ;; The test result listener that updates the buffer when tests are run.
1645 (defvar ert--results-listener
)
1647 (defun ert-insert-test-name-button (test-name)
1648 "Insert a button that links to TEST-NAME."
1649 (insert-text-button (format "%S" test-name
)
1650 :type
'ert--test-name-button
1651 'ert-test-name test-name
))
1653 (defun ert--results-format-expected-unexpected (expected unexpected
)
1654 "Return a string indicating EXPECTED expected results, UNEXPECTED unexpected."
1655 (if (zerop unexpected
)
1656 (format "%s" expected
)
1657 (format "%s (%s unexpected)" (+ expected unexpected
) unexpected
)))
1659 (defun ert--results-update-ewoc-hf (ewoc stats
)
1660 "Update the header and footer of EWOC to show certain information from STATS.
1662 Also sets `ert--results-progress-bar-button-begin'."
1663 (let ((run-count (ert-stats-completed stats
))
1664 (results-buffer (current-buffer))
1665 ;; Need to save buffer-local value.
1666 (font-lock font-lock-mode
))
1671 (insert "Selector: ")
1672 (ert--insert-human-readable-selector (ert--stats-selector stats
))
1675 (format (concat "Passed: %s\n"
1679 (ert--results-format-expected-unexpected
1680 (ert--stats-passed-expected stats
)
1681 (ert--stats-passed-unexpected stats
))
1682 (ert--results-format-expected-unexpected
1683 (ert--stats-failed-expected stats
)
1684 (ert--stats-failed-unexpected stats
))
1685 (ert-stats-skipped stats
)
1687 (ert-stats-total stats
)))
1689 (format "Started at: %s\n"
1690 (ert--format-time-iso8601 (ert--stats-start-time stats
))))
1691 ;; FIXME: This is ugly. Need to properly define invariants of
1692 ;; the `stats' data structure.
1693 (let ((state (cond ((ert--stats-aborted-p stats
) 'aborted
)
1694 ((ert--stats-current-test stats
) 'running
)
1695 ((ert--stats-end-time stats
) 'finished
)
1701 (cond ((ert--stats-current-test stats
)
1702 (insert "Aborted during test: ")
1703 (ert-insert-test-name-button
1704 (ert-test-name (ert--stats-current-test stats
))))
1706 (insert "Aborted."))))
1708 (cl-assert (ert--stats-current-test stats
))
1709 (insert "Running test: ")
1710 (ert-insert-test-name-button (ert-test-name
1711 (ert--stats-current-test stats
))))
1713 (cl-assert (not (ert--stats-current-test stats
)))
1714 (insert "Finished.")))
1716 (if (ert--stats-end-time stats
)
1719 (if (ert--stats-aborted-p stats
)
1722 (ert--format-time-iso8601 (ert--stats-end-time stats
))))
1725 (let ((progress-bar-string (with-current-buffer results-buffer
1726 ert--results-progress-bar-string
)))
1727 (let ((progress-bar-button-begin
1728 (insert-text-button progress-bar-string
1729 :type
'ert--results-progress-bar-button
1730 'face
(or (and font-lock
1731 (ert-face-for-stats stats
))
1733 ;; The header gets copied verbatim to the results buffer,
1734 ;; and all positions remain the same, so
1735 ;; `progress-bar-button-begin' will be the right position
1736 ;; even in the results buffer.
1737 (with-current-buffer results-buffer
1738 (set (make-local-variable 'ert--results-progress-bar-button-begin
)
1739 progress-bar-button-begin
))))
1744 ;; We actually want an empty footer, but that would trigger a bug
1745 ;; in ewoc, sometimes clearing the entire buffer. (It's possible
1746 ;; that this bug has been fixed since this has been tested; we
1747 ;; should test it again.)
1751 (defvar ert-test-run-redisplay-interval-secs
.1
1752 "How many seconds ERT should wait between redisplays while running tests.
1754 While running tests, ERT shows the current progress, and this variable
1755 determines how frequently the progress display is updated.")
1757 (defun ert--results-update-stats-display (ewoc stats
)
1758 "Update EWOC and the mode line to show data from STATS."
1759 ;; TODO(ohler): investigate using `make-progress-reporter'.
1760 (ert--results-update-ewoc-hf ewoc stats
)
1761 (force-mode-line-update)
1763 (setf (ert--stats-next-redisplay stats
)
1764 (+ (float-time) ert-test-run-redisplay-interval-secs
)))
1766 (defun ert--results-update-stats-display-maybe (ewoc stats
)
1767 "Call `ert--results-update-stats-display' if not called recently.
1769 EWOC and STATS are arguments for `ert--results-update-stats-display'."
1770 (when (>= (float-time) (ert--stats-next-redisplay stats
))
1771 (ert--results-update-stats-display ewoc stats
)))
1773 (defun ert--tests-running-mode-line-indicator ()
1774 "Return a string for the mode line that shows the test run progress."
1775 (let* ((stats ert--current-run-stats
)
1776 (tests-total (ert-stats-total stats
))
1777 (tests-completed (ert-stats-completed stats
)))
1778 (if (>= tests-completed tests-total
)
1779 (format " ERT(%s/%s,finished)" tests-completed tests-total
)
1780 (format " ERT(%s/%s):%s"
1781 (1+ tests-completed
)
1783 (if (null (ert--stats-current-test stats
))
1786 (ert-test-name (ert--stats-current-test stats
))))))))
1788 (defun ert--make-xrefs-region (begin end
)
1789 "Attach cross-references to function names between BEGIN and END.
1791 BEGIN and END specify a region in the current buffer."
1794 (narrow-to-region begin end
)
1795 ;; Inhibit optimization in `debugger-make-xrefs' that would
1796 ;; sometimes insert unrelated backtrace info into our buffer.
1797 (let ((debugger-previous-backtrace nil
))
1798 (debugger-make-xrefs)))))
1800 (defun ert--string-first-line (s)
1801 "Return the first line of S, or S if it contains no newlines.
1803 The return value does not include the line terminator."
1804 (substring s
0 (cl-position ?
\n s
)))
1806 (defun ert-face-for-test-result (expectedp)
1807 "Return a face that shows whether a test result was expected or unexpected.
1809 If EXPECTEDP is nil, returns the face for unexpected results; if
1810 non-nil, returns the face for expected results.."
1811 (if expectedp
'ert-test-result-expected
'ert-test-result-unexpected
))
1813 (defun ert-face-for-stats (stats)
1814 "Return a face that represents STATS."
1815 (cond ((ert--stats-aborted-p stats
) 'nil
)
1816 ((cl-plusp (ert-stats-completed-unexpected stats
))
1817 (ert-face-for-test-result nil
))
1818 ((eql (ert-stats-completed-expected stats
) (ert-stats-total stats
))
1819 (ert-face-for-test-result t
))
1822 (defun ert--print-test-for-ewoc (entry)
1823 "The ewoc print function for ewoc test entries. ENTRY is the entry to print."
1824 (let* ((test (ert--ewoc-entry-test entry
))
1825 (stats ert--results-stats
)
1826 (result (let ((pos (ert--stats-test-pos stats test
)))
1828 (aref (ert--stats-test-results stats
) pos
)))
1829 (hiddenp (ert--ewoc-entry-hidden-p entry
))
1830 (expandedp (ert--ewoc-entry-expanded-p entry
))
1831 (extended-printer-limits-p (ert--ewoc-entry-extended-printer-limits-p
1835 (let ((expectedp (ert-test-result-expected-p test result
)))
1836 (insert-text-button (format "%c" (ert-char-for-test-result
1838 :type
'ert--results-expand-collapse-button
1839 'face
(or (and font-lock-mode
1840 (ert-face-for-test-result
1844 (ert-insert-test-name-button (ert-test-name test
))
1846 (when (and expandedp
(not (eql result
'nil
)))
1847 (when (ert-test-documentation test
)
1850 (ert--string-first-line
1851 (substitute-command-keys
1852 (ert-test-documentation test
)))
1853 'font-lock-face
'font-lock-doc-face
)
1855 (cl-etypecase result
1857 (if (ert-test-result-expected-p test result
)
1858 (insert " passed\n")
1859 (insert " passed unexpectedly\n"))
1861 (ert-test-result-with-condition
1862 (ert--insert-infos result
)
1863 (let ((print-escape-newlines t
)
1864 (print-level (if extended-printer-limits-p
12 6))
1865 (print-length (if extended-printer-limits-p
100 10)))
1867 (let ((begin (point)))
1868 (ert--pp-with-indentation-and-newline
1869 (ert-test-result-with-condition-condition result
))
1870 (ert--make-xrefs-region begin
(point)))))
1871 (ert-test-aborted-with-non-local-exit
1872 (insert " aborted\n"))
1874 (insert " quit\n")))
1878 (defun ert--results-font-lock-function (enabledp)
1879 "Redraw the ERT results buffer after font-lock-mode was switched on or off.
1881 ENABLEDP is true if font-lock-mode is switched on, false
1883 (ert--results-update-ewoc-hf ert--results-ewoc ert--results-stats
)
1884 (ewoc-refresh ert--results-ewoc
)
1885 (font-lock-default-function enabledp
))
1887 (defun ert--setup-results-buffer (stats listener buffer-name
)
1888 "Set up a test results buffer.
1890 STATS is the stats object; LISTENER is the results listener;
1891 BUFFER-NAME, if non-nil, is the buffer name to use."
1892 (unless buffer-name
(setq buffer-name
"*ert*"))
1893 (let ((buffer (get-buffer-create buffer-name
)))
1894 (with-current-buffer buffer
1895 (let ((inhibit-read-only t
))
1896 (buffer-disable-undo)
1899 ;; Erase buffer again in case switching out of the previous
1900 ;; mode inserted anything. (This happens e.g. when switching
1901 ;; from ert-results-mode to ert-results-mode when
1902 ;; font-lock-mode turns itself off in change-major-mode-hook.)
1904 (set (make-local-variable 'font-lock-function
)
1905 'ert--results-font-lock-function
)
1906 (let ((ewoc (ewoc-create 'ert--print-test-for-ewoc nil nil t
)))
1907 (set (make-local-variable 'ert--results-ewoc
) ewoc
)
1908 (set (make-local-variable 'ert--results-stats
) stats
)
1909 (set (make-local-variable 'ert--results-progress-bar-string
)
1910 (make-string (ert-stats-total stats
)
1911 (ert-char-for-test-result nil t
)))
1912 (set (make-local-variable 'ert--results-listener
) listener
)
1913 (cl-loop for test across
(ert--stats-tests stats
) do
1914 (ewoc-enter-last ewoc
1915 (make-ert--ewoc-entry :test test
1917 (ert--results-update-ewoc-hf ert--results-ewoc ert--results-stats
)
1918 (goto-char (1- (point-max)))
1922 (defvar ert--selector-history nil
1923 "List of recent test selectors read from terminal.")
1925 ;; Should OUTPUT-BUFFER-NAME and MESSAGE-FN really be arguments here?
1926 ;; They are needed only for our automated self-tests at the moment.
1927 ;; Or should there be some other mechanism?
1929 (defun ert-run-tests-interactively (selector
1930 &optional output-buffer-name message-fn
)
1931 "Run the tests specified by SELECTOR and display the results in a buffer.
1933 SELECTOR works as described in `ert-select-tests'.
1934 OUTPUT-BUFFER-NAME and MESSAGE-FN should normally be nil; they
1935 are used for automated self-tests and specify which buffer to use
1936 and how to display message."
1938 (list (let ((default (if ert--selector-history
1939 ;; Can't use `first' here as this form is
1940 ;; not compiled, and `first' is not
1941 ;; defined without cl.
1942 (car ert--selector-history
)
1945 (completing-read (if (null default
)
1947 (format "Run tests (default %s): " default
))
1948 obarray
#'ert-test-boundp nil nil
1949 'ert--selector-history default nil
)))
1951 (unless message-fn
(setq message-fn
'message
))
1952 (let ((output-buffer-name output-buffer-name
)
1955 (message-fn message-fn
))
1957 (lambda (event-type &rest event-args
)
1958 (cl-ecase event-type
1960 (cl-destructuring-bind (stats) event-args
1961 (setq buffer
(ert--setup-results-buffer stats
1963 output-buffer-name
))
1964 (pop-to-buffer buffer
)))
1966 (cl-destructuring-bind (stats abortedp
) event-args
1968 "%sRan %s tests, %s results were as expected%s%s"
1972 (ert-stats-total stats
)
1973 (ert-stats-completed-expected stats
)
1975 (ert-stats-completed-unexpected stats
)))
1976 (if (zerop unexpected
)
1978 (format ", %s unexpected" unexpected
)))
1980 (ert-stats-skipped stats
)))
1983 (format ", %s skipped" skipped
))))
1984 (ert--results-update-stats-display (with-current-buffer buffer
1988 (cl-destructuring-bind (stats test
) event-args
1989 (with-current-buffer buffer
1990 (let* ((ewoc ert--results-ewoc
)
1991 (pos (ert--stats-test-pos stats test
))
1992 (node (ewoc-nth ewoc pos
)))
1994 (setf (ert--ewoc-entry-test (ewoc-data node
)) test
)
1995 (aset ert--results-progress-bar-string pos
1996 (ert-char-for-test-result nil t
))
1997 (ert--results-update-stats-display-maybe ewoc stats
)
1998 (ewoc-invalidate ewoc node
)))))
2000 (cl-destructuring-bind (stats test result
) event-args
2001 (with-current-buffer buffer
2002 (let* ((ewoc ert--results-ewoc
)
2003 (pos (ert--stats-test-pos stats test
))
2004 (node (ewoc-nth ewoc pos
)))
2005 (when (ert--ewoc-entry-hidden-p (ewoc-data node
))
2006 (setf (ert--ewoc-entry-hidden-p (ewoc-data node
))
2007 (ert-test-result-expected-p test result
)))
2008 (aset ert--results-progress-bar-string pos
2009 (ert-char-for-test-result result
2010 (ert-test-result-expected-p
2012 (ert--results-update-stats-display-maybe ewoc stats
)
2013 (ewoc-invalidate ewoc node
))))))))
2018 (defalias 'ert
'ert-run-tests-interactively
)
2021 ;;; Simple view mode for auxiliary information like stack traces or
2022 ;;; messages. Mainly binds "q" for quit.
2024 (define-derived-mode ert-simple-view-mode special-mode
"ERT-View"
2025 "Major mode for viewing auxiliary information in ERT.")
2027 ;;; Commands and button actions for the results buffer.
2029 (define-derived-mode ert-results-mode special-mode
"ERT-Results"
2030 "Major mode for viewing results of ERT test runs.")
2032 (cl-loop for
(key binding
) in
2033 '( ;; Stuff that's not in the menu.
2034 ("\t" forward-button
)
2035 ([backtab] backward-button)
2036 ("j" ert-results-jump-between-summary-and-result)
2037 ("L" ert-results-toggle-printer-limits-for-test-at-point)
2038 ("n" ert-results-next-test)
2039 ("p" ert-results-previous-test)
2040 ;; Stuff that is in the menu.
2041 ("R" ert-results-rerun-all-tests)
2042 ("r" ert-results-rerun-test-at-point)
2043 ("d" ert-results-rerun-test-at-point-debugging-errors)
2044 ("." ert-results-find-test-at-point-other-window)
2045 ("b" ert-results-pop-to-backtrace-for-test-at-point)
2046 ("m" ert-results-pop-to-messages-for-test-at-point)
2047 ("l" ert-results-pop-to-should-forms-for-test-at-point)
2048 ("h" ert-results-describe-test-at-point)
2049 ("D" ert-delete-test)
2050 ("T" ert-results-pop-to-timings)
2053 (define-key ert-results-mode-map key binding))
2055 (easy-menu-define ert-results-mode-menu ert-results-mode-map
2056 "Menu for `ert-results-mode'."
2058 ["Re-run all tests" ert-results-rerun-all-tests]
2060 ["Re-run test" ert-results-rerun-test-at-point]
2061 ["Debug test" ert-results-rerun-test-at-point-debugging-errors]
2062 ["Show test definition" ert-results-find-test-at-point-other-window]
2064 ["Show backtrace" ert-results-pop-to-backtrace-for-test-at-point]
2065 ["Show messages" ert-results-pop-to-messages-for-test-at-point]
2066 ["Show `should' forms" ert-results-pop-to-should-forms-for-test-at-point]
2067 ["Describe test" ert-results-describe-test-at-point]
2069 ["Delete test" ert-delete-test]
2071 ["Show execution time of each test" ert-results-pop-to-timings]
2074 (define-button-type 'ert--results-progress-bar-button
2075 'action #'ert--results-progress-bar-button-action
2076 'help-echo "mouse-2, RET: Reveal test result")
2078 (define-button-type 'ert--test-name-button
2079 'action #'ert--test-name-button-action
2080 'help-echo "mouse-2, RET: Find test definition")
2082 (define-button-type 'ert--results-expand-collapse-button
2083 'action #'ert--results-expand-collapse-button-action
2084 'help-echo "mouse-2, RET: Expand/collapse test result")
2086 (defun ert--results-test-node-or-null-at-point ()
2087 "If point is on a valid ewoc node, return it; return nil otherwise.
2089 To be used in the ERT results buffer."
2090 (let* ((ewoc ert--results-ewoc)
2091 (node (ewoc-locate ewoc)))
2092 ;; `ewoc-locate' will return an arbitrary node when point is on
2093 ;; header or footer, or when all nodes are invisible. So we need
2094 ;; to validate its return value here.
2096 ;; Update: I'm seeing nil being returned in some cases now,
2097 ;; perhaps this has been changed?
2099 (>= (point) (ewoc-location node))
2100 (not (ert--ewoc-entry-hidden-p (ewoc-data node))))
2104 (defun ert--results-test-node-at-point ()
2105 "If point is on a valid ewoc node, return it; signal an error otherwise.
2107 To be used in the ERT results buffer."
2108 (or (ert--results-test-node-or-null-at-point)
2109 (error "No test at point")))
2111 (defun ert-results-next-test ()
2112 "Move point to the next test.
2114 To be used in the ERT results buffer."
2116 (ert--results-move (ewoc-locate ert--results-ewoc) 'ewoc-next
2119 (defun ert-results-previous-test ()
2120 "Move point to the previous test.
2122 To be used in the ERT results buffer."
2124 (ert--results-move (ewoc-locate ert--results-ewoc) 'ewoc-prev
2127 (defun ert--results-move (node ewoc-fn error-message)
2128 "Move point from NODE to the previous or next node.
2130 EWOC-FN specifies the direction and should be either `ewoc-prev'
2131 or `ewoc-next'. If there are no more nodes in that direction, a
2132 user-error is signaled with the message ERROR-MESSAGE."
2134 (setq node (funcall ewoc-fn ert--results-ewoc node))
2136 (user-error "%s" error-message))
2137 (unless (ert--ewoc-entry-hidden-p (ewoc-data node))
2138 (goto-char (ewoc-location node))
2141 (defun ert--results-expand-collapse-button-action (_button)
2142 "Expand or collapse the test node BUTTON belongs to."
2143 (let* ((ewoc ert--results-ewoc)
2144 (node (save-excursion
2145 (goto-char (ert--button-action-position))
2146 (ert--results-test-node-at-point)))
2147 (entry (ewoc-data node)))
2148 (setf (ert--ewoc-entry-expanded-p entry)
2149 (not (ert--ewoc-entry-expanded-p entry)))
2150 (ewoc-invalidate ewoc node)))
2152 (defun ert-results-find-test-at-point-other-window ()
2153 "Find the definition of the test at point in another window.
2155 To be used in the ERT results buffer."
2157 (let ((name (ert-test-at-point)))
2159 (error "No test at point"))
2160 (ert-find-test-other-window name)))
2162 (defun ert--test-name-button-action (button)
2163 "Find the definition of the test BUTTON belongs to, in another window."
2164 (let ((name (button-get button 'ert-test-name)))
2165 (ert-find-test-other-window name)))
2167 (defun ert--ewoc-position (ewoc node)
2168 ;; checkdoc-order: nil
2169 "Return the position of NODE in EWOC, or nil if NODE is not in EWOC."
2170 (cl-loop for i from 0
2171 for node-here = (ewoc-nth ewoc 0) then (ewoc-next ewoc node-here)
2172 do (when (eql node node-here)
2174 finally (cl-return nil)))
2176 (defun ert-results-jump-between-summary-and-result ()
2177 "Jump back and forth between the test run summary and individual test results.
2179 From an ewoc node, jumps to the character that represents the
2180 same test in the progress bar, and vice versa.
2182 To be used in the ERT results buffer."
2183 ;; Maybe this command isn't actually needed much, but if it is, it
2184 ;; seems like an indication that the UI design is not optimal. If
2185 ;; jumping back and forth between a summary at the top of the buffer
2186 ;; and the error log in the remainder of the buffer is useful, then
2187 ;; the summary apparently needs to be easily accessible from the
2188 ;; error log, and perhaps it would be better to have it in a
2189 ;; separate buffer to keep it visible.
2191 (let ((ewoc ert--results-ewoc)
2192 (progress-bar-begin ert--results-progress-bar-button-begin))
2193 (cond ((ert--results-test-node-or-null-at-point)
2194 (let* ((node (ert--results-test-node-at-point))
2195 (pos (ert--ewoc-position ewoc node)))
2196 (goto-char (+ progress-bar-begin pos))))
2197 ((and (<= progress-bar-begin (point))
2198 (< (point) (button-end (button-at progress-bar-begin))))
2199 (let* ((node (ewoc-nth ewoc (- (point) progress-bar-begin)))
2200 (entry (ewoc-data node)))
2201 (when (ert--ewoc-entry-hidden-p entry)
2202 (setf (ert--ewoc-entry-hidden-p entry) nil)
2203 (ewoc-invalidate ewoc node))
2204 (ewoc-goto-node ewoc node)))
2206 (goto-char progress-bar-begin)))))
2208 (defun ert-test-at-point ()
2209 "Return the name of the test at point as a symbol, or nil if none."
2210 (or (and (eql major-mode 'ert-results-mode)
2211 (let ((test (ert--results-test-at-point-no-redefinition)))
2212 (and test (ert-test-name test))))
2213 (let* ((thing (thing-at-point 'symbol))
2214 (sym (intern-soft thing)))
2215 (and (ert-test-boundp sym)
2218 (defun ert--results-test-at-point-no-redefinition ()
2219 "Return the test at point, or nil.
2221 To be used in the ERT results buffer."
2222 (cl-assert (eql major-mode 'ert-results-mode))
2223 (if (ert--results-test-node-or-null-at-point)
2224 (let* ((node (ert--results-test-node-at-point))
2225 (test (ert--ewoc-entry-test (ewoc-data node))))
2227 (let ((progress-bar-begin ert--results-progress-bar-button-begin))
2228 (when (and (<= progress-bar-begin (point))
2229 (< (point) (button-end (button-at progress-bar-begin))))
2230 (let* ((test-index (- (point) progress-bar-begin))
2231 (test (aref (ert--stats-tests ert--results-stats)
2235 (defun ert--results-test-at-point-allow-redefinition ()
2236 "Look up the test at point, and check whether it has been redefined.
2238 To be used in the ERT results buffer.
2240 Returns a list of two elements: the test (or nil) and a symbol
2241 specifying whether the test has been redefined.
2243 If a new test has been defined with the same name as the test at
2244 point, replaces the test at point with the new test, and returns
2245 the new test and the symbol `redefined'.
2247 If the test has been deleted, returns the old test and the symbol
2250 If the test is still current, returns the test and the symbol nil.
2252 If there is no test at point, returns a list with two nils."
2253 (let ((test (ert--results-test-at-point-no-redefinition)))
2256 ((null (ert-test-name test))
2259 (let* ((name (ert-test-name test))
2260 (new-test (and (ert-test-boundp name)
2261 (ert-get-test name))))
2262 (cond ((eql test new-test)
2267 (ert--results-update-after-test-redefinition
2268 (ert--stats-test-pos ert--results-stats test)
2270 `(,new-test redefined))))))))
2272 (defun ert--results-update-after-test-redefinition (pos new-test)
2273 "Update results buffer after the test at pos POS has been redefined.
2275 Also updates the stats object. NEW-TEST is the new test
2277 (let* ((stats ert--results-stats)
2278 (ewoc ert--results-ewoc)
2279 (node (ewoc-nth ewoc pos))
2280 (entry (ewoc-data node)))
2281 (ert--stats-set-test-and-result stats pos new-test nil)
2282 (setf (ert--ewoc-entry-test entry) new-test
2283 (aref ert--results-progress-bar-string pos) (ert-char-for-test-result
2285 (ewoc-invalidate ewoc node))
2288 (defun ert--button-action-position ()
2289 "The buffer position where the last button action was triggered."
2290 (cond ((integerp last-command-event)
2292 ((eventp last-command-event)
2293 (posn-point (event-start last-command-event)))
2294 (t (cl-assert nil))))
2296 (defun ert--results-progress-bar-button-action (_button)
2297 "Jump to details for the test represented by the character clicked in BUTTON."
2298 (goto-char (ert--button-action-position))
2299 (ert-results-jump-between-summary-and-result))
2301 (defun ert-results-rerun-all-tests ()
2302 "Re-run all tests, using the same selector.
2304 To be used in the ERT results buffer."
2306 (cl-assert (eql major-mode 'ert-results-mode))
2307 (let ((selector (ert--stats-selector ert--results-stats)))
2308 (ert-run-tests-interactively selector (buffer-name))))
2310 (defun ert-results-rerun-test-at-point ()
2311 "Re-run the test at point.
2313 To be used in the ERT results buffer."
2315 (cl-destructuring-bind (test redefinition-state)
2316 (ert--results-test-at-point-allow-redefinition)
2318 (error "No test at point"))
2319 (let* ((stats ert--results-stats)
2320 (progress-message (format "Running %stest %S"
2321 (cl-ecase redefinition-state
2323 (redefined "new definition of ")
2324 (deleted "deleted "))
2325 (ert-test-name test))))
2326 ;; Need to save and restore point manually here: When point is on
2327 ;; the first visible ewoc entry while the header is updated, point
2328 ;; moves to the top of the buffer. This is undesirable, and a
2329 ;; simple `save-excursion' doesn't prevent it.
2330 (let ((point (point)))
2334 (message "%s..." progress-message)
2335 (ert-run-or-rerun-test stats test
2336 ert--results-listener))
2337 (ert--results-update-stats-display ert--results-ewoc stats)
2340 (let ((result (ert-test-most-recent-result test)))
2341 (ert-string-for-test-result
2342 result (ert-test-result-expected-p test result)))))
2343 (goto-char point))))))
2345 (defun ert-results-rerun-test-at-point-debugging-errors ()
2346 "Re-run the test at point with `ert-debug-on-error' bound to t.
2348 To be used in the ERT results buffer."
2350 (let ((ert-debug-on-error t))
2351 (ert-results-rerun-test-at-point)))
2353 (defun ert-results-pop-to-backtrace-for-test-at-point ()
2354 "Display the backtrace for the test at point.
2356 To be used in the ERT results buffer."
2358 (let* ((test (ert--results-test-at-point-no-redefinition))
2359 (stats ert--results-stats)
2360 (pos (ert--stats-test-pos stats test))
2361 (result (aref (ert--stats-test-results stats) pos)))
2362 (cl-etypecase result
2363 (ert-test-passed (error "Test passed, no backtrace available"))
2364 (ert-test-result-with-condition
2365 (let ((backtrace (ert-test-result-with-condition-backtrace result))
2366 (buffer (get-buffer-create "*ERT Backtrace*")))
2367 (pop-to-buffer buffer)
2368 (let ((inhibit-read-only t))
2369 (buffer-disable-undo)
2371 (ert-simple-view-mode)
2372 ;; Use unibyte because `debugger-setup-buffer' also does so.
2373 (set-buffer-multibyte nil)
2374 (setq truncate-lines t)
2375 (ert--print-backtrace backtrace)
2376 (debugger-make-xrefs)
2377 (goto-char (point-min))
2378 (insert (substitute-command-keys "Backtrace for test `"))
2379 (ert-insert-test-name-button (ert-test-name test))
2380 (insert (substitute-command-keys "':\n"))))))))
2382 (defun ert-results-pop-to-messages-for-test-at-point ()
2383 "Display the part of the *Messages* buffer generated during the test at point.
2385 To be used in the ERT results buffer."
2387 (let* ((test (ert--results-test-at-point-no-redefinition))
2388 (stats ert--results-stats)
2389 (pos (ert--stats-test-pos stats test))
2390 (result (aref (ert--stats-test-results stats) pos)))
2391 (let ((buffer (get-buffer-create "*ERT Messages*")))
2392 (pop-to-buffer buffer)
2393 (let ((inhibit-read-only t))
2394 (buffer-disable-undo)
2396 (ert-simple-view-mode)
2397 (insert (ert-test-result-messages result))
2398 (goto-char (point-min))
2399 (insert (substitute-command-keys "Messages for test `"))
2400 (ert-insert-test-name-button (ert-test-name test))
2401 (insert (substitute-command-keys "':\n"))))))
2403 (defun ert-results-pop-to-should-forms-for-test-at-point ()
2404 "Display the list of `should' forms executed during the test at point.
2406 To be used in the ERT results buffer."
2408 (let* ((test (ert--results-test-at-point-no-redefinition))
2409 (stats ert--results-stats)
2410 (pos (ert--stats-test-pos stats test))
2411 (result (aref (ert--stats-test-results stats) pos)))
2412 (let ((buffer (get-buffer-create "*ERT list of should forms*")))
2413 (pop-to-buffer buffer)
2414 (let ((inhibit-read-only t))
2415 (buffer-disable-undo)
2417 (ert-simple-view-mode)
2418 (if (null (ert-test-result-should-forms result))
2419 (insert "\n(No should forms during this test.)\n")
2420 (cl-loop for form-description
2421 in (ert-test-result-should-forms result)
2424 (insert (format "%s: " i))
2425 (let ((begin (point)))
2426 (ert--pp-with-indentation-and-newline form-description)
2427 (ert--make-xrefs-region begin (point)))))
2428 (goto-char (point-min))
2429 (insert (substitute-command-keys
2430 "`should' forms executed during test `"))
2431 (ert-insert-test-name-button (ert-test-name test))
2432 (insert (substitute-command-keys "':\n"))
2434 (insert (concat "(Values are shallow copies and may have "
2435 "looked different during the test if they\n"
2436 "have been modified destructively.)\n"))
2437 (forward-line 1)))))
2439 (defun ert-results-toggle-printer-limits-for-test-at-point ()
2440 "Toggle how much of the condition to print for the test at point.
2442 To be used in the ERT results buffer."
2444 (let* ((ewoc ert--results-ewoc)
2445 (node (ert--results-test-node-at-point))
2446 (entry (ewoc-data node)))
2447 (setf (ert--ewoc-entry-extended-printer-limits-p entry)
2448 (not (ert--ewoc-entry-extended-printer-limits-p entry)))
2449 (ewoc-invalidate ewoc node)))
2451 (defun ert-results-pop-to-timings ()
2452 "Display test timings for the last run.
2454 To be used in the ERT results buffer."
2456 (let* ((stats ert--results-stats)
2457 (buffer (get-buffer-create "*ERT timings*"))
2458 (data (cl-loop for test across (ert--stats-tests stats)
2459 for start-time across (ert--stats-test-start-times
2461 for end-time across (ert--stats-test-end-times stats)
2463 (float-time (subtract-time
2464 end-time start-time))))))
2465 (setq data (sort data (lambda (a b)
2466 (> (cl-second a) (cl-second b)))))
2467 (pop-to-buffer buffer)
2468 (let ((inhibit-read-only t))
2469 (buffer-disable-undo)
2471 (ert-simple-view-mode)
2473 (insert "(No data)\n")
2474 (insert (format "%-3s %8s %8s\n" "" "time" "cumul"))
2475 (cl-loop for (test time) in data
2476 for cumul-time = time then (+ cumul-time time)
2479 (insert (format "%3s: %8.3f %8.3f " i time cumul-time))
2480 (ert-insert-test-name-button (ert-test-name test))
2482 (goto-char (point-min))
2483 (insert "Tests by run time (seconds):\n\n")
2487 (defun ert-describe-test (test-or-test-name)
2488 "Display the documentation for TEST-OR-TEST-NAME (a symbol or ert-test)."
2489 (interactive (list (ert-read-test-name-at-point "Describe test")))
2490 (when (< emacs-major-version 24)
2491 (error "Requires Emacs 24"))
2494 (cl-etypecase test-or-test-name
2495 (symbol (setq test-name test-or-test-name
2496 test-definition (ert-get-test test-or-test-name)))
2497 (ert-test (setq test-name (ert-test-name test-or-test-name)
2498 test-definition test-or-test-name)))
2499 (help-setup-xref (list #'ert-describe-test test-or-test-name)
2500 (called-interactively-p 'interactive))
2502 (with-help-window (help-buffer)
2503 (with-current-buffer (help-buffer)
2504 (insert (if test-name (format "%S" test-name) "<anonymous test>"))
2505 (insert " is a test")
2506 (let ((file-name (and test-name
2507 (symbol-file test-name 'ert-deftest))))
2509 (insert (format-message " defined in `%s'"
2510 (file-name-nondirectory file-name)))
2512 (re-search-backward (substitute-command-keys "`\\([^`']+\\)'")
2514 (help-xref-button 1 'help-function-def test-name file-name)))
2516 (fill-region-as-paragraph (point-min) (point))
2518 (unless (and (ert-test-boundp test-name)
2519 (eql (ert-get-test test-name) test-definition))
2520 (let ((begin (point)))
2521 (insert "Note: This test has been redefined or deleted, "
2522 "this documentation refers to an old definition.")
2523 (fill-region-as-paragraph begin (point)))
2525 (insert (substitute-command-keys
2526 (or (ert-test-documentation test-definition)
2527 "It is not documented."))
2530 (defun ert-results-describe-test-at-point ()
2531 "Display the documentation of the test at point.
2533 To be used in the ERT results buffer."
2535 (ert-describe-test (ert--results-test-at-point-no-redefinition)))
2538 ;;; Actions on load/unload.
2540 (add-to-list 'find-function-regexp-alist '(ert-deftest . ert--find-test-regexp))
2541 (add-to-list 'minor-mode-alist '(ert--current-run-stats
2543 (ert--tests-running-mode-line-indicator))))
2544 (add-hook 'emacs-lisp-mode-hook #'ert--activate-font-lock-keywords)
2546 (defun ert--unload-function ()
2547 "Unload function to undo the side-effects of loading ert.el."
2548 (ert--remove-from-list 'find-function-regexp-alist 'ert-deftest :key #'car)
2549 (ert--remove-from-list 'minor-mode-alist 'ert--current-run-stats :key #'car)
2550 (ert--remove-from-list 'emacs-lisp-mode-hook
2551 'ert--activate-font-lock-keywords)
2554 (defvar ert-unload-hook '())
2555 (add-hook 'ert-unload-hook #'ert--unload-function)
2560 ;;; ert.el ends here