1 ;;; ert.el --- Emacs Lisp Regression Testing -*- lexical-binding: t -*-
3 ;; Copyright (C) 2007-2008, 2010-2013 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' and `should-error' are
38 ;; available. `should' is similar to cl's `assert', but signals a
39 ;; different error when its condition is violated that is caught and
40 ;; processed by ERT. In addition, it analyzes its argument form and
41 ;; records information that helps debugging (`assert' tries to do
42 ;; something similar when its second argument SHOW-ARGS is true, but
43 ;; `should' is more sophisticated). For information on `should-not'
44 ;; and `should-error', see their docstrings.
46 ;; See ERT's info manual as well as the docstrings for more details.
47 ;; To compile the manual, run `makeinfo ert.texinfo' in the ERT
48 ;; directory, then C-u M-x info ert.info in Emacs to view it.
50 ;; To see some examples of tests written in ERT, see its self-tests in
51 ;; ert-tests.el. Some of these are tricky due to the bootstrapping
52 ;; problem of writing tests for a testing tool, others test simple
53 ;; functions and are straightforward.
57 (eval-when-compile (require 'cl-lib
))
66 ;;; UI customization options.
69 "ERT, the Emacs Lisp regression testing tool."
73 (defface ert-test-result-expected
'((((class color
) (background light
))
75 (((class color
) (background dark
))
76 :background
"green3"))
77 "Face used for expected results in the ERT results buffer."
80 (defface ert-test-result-unexpected
'((((class color
) (background light
))
82 (((class color
) (background dark
))
84 "Face used for unexpected results in the ERT results buffer."
88 ;;; Copies/reimplementations of cl functions.
90 (defun ert--cl-do-remf (plist tag
)
91 "Copy of `cl-do-remf'. Modify PLIST by removing TAG."
92 (let ((p (cdr plist
)))
93 (while (and (cdr p
) (not (eq (car (cdr p
)) tag
))) (setq p
(cdr (cdr p
))))
94 (and (cdr p
) (progn (setcdr p
(cdr (cdr (cdr p
)))) t
))))
96 (defun ert--remprop (sym tag
)
97 "Copy of `cl-remprop'. Modify SYM's plist by removing TAG."
98 (let ((plist (symbol-plist sym
)))
99 (if (and plist
(eq tag
(car plist
)))
100 (progn (setplist sym
(cdr (cdr plist
))) t
)
101 (ert--cl-do-remf plist tag
))))
103 (defun ert--remove-if-not (ert-pred ert-list
)
104 "A reimplementation of `remove-if-not'.
106 ERT-PRED is a predicate, ERT-LIST is the input list."
107 (cl-loop for ert-x in ert-list
108 if
(funcall ert-pred ert-x
)
111 (defun ert--intersection (a b
)
112 "A reimplementation of `intersection'. Intersect the sets A and B.
114 Elements are compared using `eql'."
119 (defun ert--set-difference (a b
)
120 "A reimplementation of `set-difference'. Subtract the set B from the set A.
122 Elements are compared using `eql'."
127 (defun ert--set-difference-eq (a b
)
128 "A reimplementation of `set-difference'. Subtract the set B from the set A.
130 Elements are compared using `eq'."
135 (defun ert--union (a b
)
136 "A reimplementation of `union'. Compute the union of the sets A and B.
138 Elements are compared using `eql'."
139 (append a
(ert--set-difference b a
)))
142 (defvar ert--gensym-counter
0))
145 (defun ert--gensym (&optional prefix
)
146 "Only allows string PREFIX, not compatible with CL."
147 (unless prefix
(setq prefix
"G"))
148 (make-symbol (format "%s%s"
150 (prog1 ert--gensym-counter
151 (cl-incf ert--gensym-counter
))))))
153 (defun ert--coerce-to-vector (x)
154 "Coerce X to a vector."
155 (when (char-table-p x
) (error "Not supported"))
160 (cl-defun ert--remove* (x list
&key key test
)
161 "Does not support all the keywords of remove*."
162 (unless key
(setq key
#'identity
))
163 (unless test
(setq test
#'eql
))
164 (cl-loop for y in list
165 unless
(funcall test x
(funcall key y
))
168 (defun ert--string-position (c s
)
169 "Return the position of the first occurrence of C in S, or nil if none."
170 (cl-loop for i from
0
172 when
(eql x c
) return i
))
174 (defun ert--mismatch (a b
)
175 "Return index of first element that differs between A and B.
177 Like `mismatch'. Uses `equal' for comparison."
178 (cond ((or (listp a
) (listp b
))
179 (ert--mismatch (ert--coerce-to-vector a
)
180 (ert--coerce-to-vector b
)))
181 ((> (length a
) (length b
))
184 (let ((la (length a
))
186 (cl-assert (arrayp a
) t
)
187 (cl-assert (arrayp b
) t
)
188 (cl-assert (<= la lb
) t
)
189 (cl-loop for i below la
190 when
(not (equal (aref a i
) (aref b i
))) return i
191 finally
(cl-return (if (/= la lb
)
193 (cl-assert (equal a b
) t
)
196 (defun ert--subseq (seq start
&optional end
)
197 "Return a subsequence of SEQ from START to END."
198 (when (char-table-p seq
) (error "Not supported"))
199 (let ((vector (substring (ert--coerce-to-vector seq
) start end
)))
202 (string (concat vector
))
203 (list (append vector nil
))
204 (bool-vector (cl-loop with result
205 = (make-bool-vector (length vector
) nil
)
206 for i below
(length vector
) do
207 (setf (aref result i
) (aref vector i
))
208 finally
(cl-return result
)))
209 (char-table (cl-assert nil
)))))
211 (defun ert-equal-including-properties (a b
)
212 "Return t if A and B have similar structure and contents.
214 This is like `equal-including-properties' except that it compares
215 the property values of text properties structurally (by
216 recursing) rather than with `eq'. Perhaps this is what
217 `equal-including-properties' should do in the first place; see
218 Emacs bug 6581 at URL `http://debbugs.gnu.org/cgi/bugreport.cgi?bug=6581'."
219 ;; This implementation is inefficient. Rather than making it
220 ;; efficient, let's hope bug 6581 gets fixed so that we can delete
222 (not (ert--explain-equal-including-properties a b
)))
225 ;;; Defining and locating tests.
227 ;; The data structure that represents a test case.
228 (cl-defstruct ert-test
231 (body (cl-assert nil
))
232 (most-recent-result nil
)
233 (expected-result-type ':passed
)
236 (defun ert-test-boundp (symbol)
237 "Return non-nil if SYMBOL names a test."
238 (and (get symbol
'ert--test
) t
))
240 (defun ert-get-test (symbol)
241 "If SYMBOL names a test, return that. Signal an error otherwise."
242 (unless (ert-test-boundp symbol
) (error "No test named `%S'" symbol
))
243 (get symbol
'ert--test
))
245 (defun ert-set-test (symbol definition
)
246 "Make SYMBOL name the test DEFINITION, and return DEFINITION."
247 (when (eq symbol
'nil
)
248 ;; We disallow nil since `ert-test-at-point' and related functions
249 ;; want to return a test name, but also need an out-of-band value
250 ;; on failure. Nil is the most natural out-of-band value; using 0
251 ;; or "" or signaling an error would be too awkward.
253 ;; Note that nil is still a valid value for the `name' slot in
254 ;; ert-test objects. It designates an anonymous test.
255 (error "Attempt to define a test named nil"))
256 (put symbol
'ert--test definition
)
259 (defun ert-make-test-unbound (symbol)
260 "Make SYMBOL name no test. Return SYMBOL."
261 (ert--remprop symbol
'ert--test
)
264 (defun ert--parse-keys-and-body (keys-and-body)
265 "Split KEYS-AND-BODY into keyword-and-value pairs and the remaining body.
267 KEYS-AND-BODY should have the form of a property list, with the
268 exception that only keywords are permitted as keys and that the
269 tail -- the body -- is a list of forms that does not start with a
272 Returns a two-element list containing the keys-and-values plist
274 (let ((extracted-key-accu '())
275 (remaining keys-and-body
))
276 (while (keywordp (car-safe remaining
))
277 (let ((keyword (pop remaining
)))
278 (unless (consp remaining
)
279 (error "Value expected after keyword %S in %S"
280 keyword keys-and-body
))
281 (when (assoc keyword extracted-key-accu
)
282 (warn "Keyword %S appears more than once in %S" keyword
284 (push (cons keyword
(pop remaining
)) extracted-key-accu
)))
285 (setq extracted-key-accu
(nreverse extracted-key-accu
))
286 (list (cl-loop for
(key . value
) in extracted-key-accu
292 (cl-defmacro ert-deftest
(name () &body docstring-keys-and-body
)
293 "Define NAME (a symbol) as a test.
295 BODY is evaluated as a `progn' when the test is run. It should
296 signal a condition on failure or just return if the test passes.
298 `should', `should-not' and `should-error' are useful for
301 Use `ert' to run tests interactively.
303 Tests that are expected to fail can be marked as such
304 using :expected-result. See `ert-test-result-type-p' for a
305 description of valid values for RESULT-TYPE.
307 \(fn NAME () [DOCSTRING] [:expected-result RESULT-TYPE] \
308 \[:tags '(TAG...)] BODY...)"
309 (declare (debug (&define
:name test
310 name sexp
[&optional stringp
]
311 [&rest keywordp sexp
] def-body
))
314 (let ((documentation nil
)
315 (documentation-supplied-p nil
))
316 (when (stringp (car docstring-keys-and-body
))
317 (setq documentation
(pop docstring-keys-and-body
)
318 documentation-supplied-p t
))
319 (cl-destructuring-bind
320 ((&key
(expected-result nil expected-result-supplied-p
)
321 (tags nil tags-supplied-p
))
323 (ert--parse-keys-and-body docstring-keys-and-body
)
328 ,@(when documentation-supplied-p
329 `(:documentation
,documentation
))
330 ,@(when expected-result-supplied-p
331 `(:expected-result-type
,expected-result
))
332 ,@(when tags-supplied-p
334 :body
(lambda () ,@body
)))
335 ;; This hack allows `symbol-file' to associate `ert-deftest'
336 ;; forms with files, and therefore enables `find-function' to
337 ;; work with tests. However, it leads to warnings in
338 ;; `unload-feature', which doesn't know how to undefine tests
339 ;; and has no mechanism for extension.
340 (push '(ert-deftest .
,name
) current-load-list
)
343 ;; We use these `put' forms in addition to the (declare (indent)) in
344 ;; the defmacro form since the `declare' alone does not lead to
345 ;; correct indentation before the .el/.elc file is loaded.
346 ;; Autoloading these `put' forms solves this.
349 ;; TODO(ohler): Figure out what these mean and make sure they are correct.
350 (put 'ert-deftest
'lisp-indent-function
2)
351 (put 'ert-info
'lisp-indent-function
1))
353 (defvar ert--find-test-regexp
354 (concat "^\\s-*(ert-deftest"
355 find-function-space-re
357 "The regexp the `find-function' mechanisms use for finding test definitions.")
360 (put 'ert-test-failed
'error-conditions
'(error ert-test-failed
))
361 (put 'ert-test-failed
'error-message
"Test failed")
364 "Terminate the current test and mark it passed. Does not return."
365 (throw 'ert--pass nil
))
367 (defun ert-fail (data)
368 "Terminate the current test and mark it failed. Does not return.
369 DATA is displayed to the user and should state the reason of the failure."
370 (signal 'ert-test-failed
(list data
)))
373 ;;; The `should' macros.
375 (defvar ert--should-execution-observer nil
)
377 (defun ert--signal-should-execution (form-description)
378 "Tell the current `should' form observer (if any) about FORM-DESCRIPTION."
379 (when ert--should-execution-observer
380 (funcall ert--should-execution-observer form-description
)))
382 (defun ert--special-operator-p (thing)
383 "Return non-nil if THING is a symbol naming a special operator."
385 (let ((definition (indirect-function thing t
)))
386 (and (subrp definition
)
387 (eql (cdr (subr-arity definition
)) 'unevalled
)))))
389 (defun ert--expand-should-1 (whole form inner-expander
)
390 "Helper function for the `should' macro and its variants."
392 (macroexpand form
(cond
393 ((boundp 'macroexpand-all-environment
)
394 macroexpand-all-environment
)
395 ((boundp 'cl-macro-environment
)
396 cl-macro-environment
)))))
398 ((or (atom form
) (ert--special-operator-p (car form
)))
399 (let ((value (ert--gensym "value-")))
400 `(let ((,value
(ert--gensym "ert-form-evaluation-aborted-")))
401 ,(funcall inner-expander
403 `(list ',whole
:form
',form
:value
,value
)
407 (let ((fn-name (car form
))
408 (arg-forms (cdr form
)))
409 (cl-assert (or (symbolp fn-name
)
411 (eql (car fn-name
) 'lambda
)
412 (listp (cdr fn-name
)))))
413 (let ((fn (ert--gensym "fn-"))
414 (args (ert--gensym "args-"))
415 (value (ert--gensym "value-"))
416 (default-value (ert--gensym "ert-form-evaluation-aborted-")))
417 `(let ((,fn
(function ,fn-name
))
418 (,args
(list ,@arg-forms
)))
419 (let ((,value
',default-value
))
420 ,(funcall inner-expander
421 `(setq ,value
(apply ,fn
,args
))
422 `(nconc (list ',whole
)
423 (list :form
`(,,fn
,@,args
))
424 (unless (eql ,value
',default-value
)
425 (list :value
,value
))
427 (and (symbolp ',fn-name
)
428 (get ',fn-name
'ert-explainer
))))
431 (apply -explainer-
,args
)))))
435 (defun ert--expand-should (whole form inner-expander
)
436 "Helper function for the `should' macro and its variants.
438 Analyzes FORM and returns an expression that has the same
439 semantics under evaluation but records additional debugging
442 INNER-EXPANDER should be a function and is called with two
443 arguments: INNER-FORM and FORM-DESCRIPTION-FORM, where INNER-FORM
444 is an expression equivalent to FORM, and FORM-DESCRIPTION-FORM is
445 an expression that returns a description of FORM. INNER-EXPANDER
446 should return code that calls INNER-FORM and performs the checks
447 and error signaling specific to the particular variant of
448 `should'. The code that INNER-EXPANDER returns must not call
449 FORM-DESCRIPTION-FORM before it has called INNER-FORM."
450 (ert--expand-should-1
452 (lambda (inner-form form-description-form value-var
)
453 (let ((form-description (ert--gensym "form-description-")))
454 `(let (,form-description
)
455 ,(funcall inner-expander
458 (setq ,form-description
,form-description-form
)
459 (ert--signal-should-execution ,form-description
))
463 (cl-defmacro should
(form)
464 "Evaluate FORM. If it returns nil, abort the current test as failed.
466 Returns the value of FORM."
467 (ert--expand-should `(should ,form
) form
468 (lambda (inner-form form-description-form _value-var
)
470 (ert-fail ,form-description-form
)))))
472 (cl-defmacro should-not
(form)
473 "Evaluate FORM. If it returns non-nil, abort the current test as failed.
476 (ert--expand-should `(should-not ,form
) form
477 (lambda (inner-form form-description-form _value-var
)
478 `(unless (not ,inner-form
)
479 (ert-fail ,form-description-form
)))))
481 (defun ert--should-error-handle-error (form-description-fn
482 condition type exclude-subtypes
)
483 "Helper function for `should-error'.
485 Determines whether CONDITION matches TYPE and EXCLUDE-SUBTYPES,
486 and aborts the current test as failed if it doesn't."
487 (let ((signaled-conditions (get (car condition
) 'error-conditions
))
488 (handled-conditions (cl-etypecase type
490 (symbol (list type
)))))
491 (cl-assert signaled-conditions
)
492 (unless (ert--intersection signaled-conditions handled-conditions
)
494 (funcall form-description-fn
)
497 :fail-reason
(concat "the error signaled did not"
498 " have the expected type")))))
499 (when exclude-subtypes
500 (unless (member (car condition
) handled-conditions
)
502 (funcall form-description-fn
)
505 :fail-reason
(concat "the error signaled was a subtype"
506 " of the expected type"))))))))
508 ;; FIXME: The expansion will evaluate the keyword args (if any) in
509 ;; nonstandard order.
510 (cl-defmacro should-error
(form &rest keys
&key type exclude-subtypes
)
511 "Evaluate FORM and check that it signals an error.
513 The error signaled needs to match TYPE. TYPE should be a list
514 of condition names. (It can also be a non-nil symbol, which is
515 equivalent to a singleton list containing that symbol.) If
516 EXCLUDE-SUBTYPES is nil, the error matches TYPE if one of its
517 condition names is an element of TYPE. If EXCLUDE-SUBTYPES is
518 non-nil, the error matches TYPE if it is an element of TYPE.
520 If the error matches, returns (ERROR-SYMBOL . DATA) from the
521 error. If not, or if no error was signaled, abort the test as
523 (unless type
(setq type
''error
))
525 `(should-error ,form
,@keys
)
527 (lambda (inner-form form-description-form value-var
)
528 (let ((errorp (ert--gensym "errorp"))
529 (form-description-fn (ert--gensym "form-description-fn-")))
531 (,form-description-fn
(lambda () ,form-description-form
)))
532 (condition-case -condition-
534 ;; We can't use ,type here because we want to evaluate it.
537 (ert--should-error-handle-error ,form-description-fn
539 ,type
,exclude-subtypes
)
540 (setq ,value-var -condition-
)))
543 (funcall ,form-description-fn
)
545 :fail-reason
"did not signal an error")))))))))
548 ;;; Explanation of `should' failures.
550 ;; TODO(ohler): Rework explanations so that they are displayed in a
551 ;; similar way to `ert-info' messages; in particular, allow text
552 ;; buttons in explanations that give more detail or open an ediff
553 ;; buffer. Perhaps explanations should be reported through `ert-info'
554 ;; rather than as part of the condition.
556 (defun ert--proper-list-p (x)
557 "Return non-nil if X is a proper list, nil otherwise."
559 for firstp
= t then nil
560 for fast
= x then
(cddr fast
)
561 for slow
= x then
(cdr slow
) do
562 (when (null fast
) (cl-return t
))
563 (when (not (consp fast
)) (cl-return nil
))
564 (when (null (cdr fast
)) (cl-return t
))
565 (when (not (consp (cdr fast
))) (cl-return nil
))
566 (when (and (not firstp
) (eq fast slow
)) (cl-return nil
))))
568 (defun ert--explain-format-atom (x)
569 "Format the atom X for `ert--explain-equal'."
571 (character (list x
(format "#x%x" x
) (format "?%c" x
)))
572 (fixnum (list x
(format "#x%x" x
)))
575 (defun ert--explain-equal-rec (a b
)
576 "Return a programmer-readable explanation of why A and B are not `equal'.
577 Returns nil if they are."
578 (if (not (equal (type-of a
) (type-of b
)))
579 `(different-types ,a
,b
)
582 (let ((a-proper-p (ert--proper-list-p a
))
583 (b-proper-p (ert--proper-list-p b
)))
584 (if (not (eql (not a-proper-p
) (not b-proper-p
)))
585 `(one-list-proper-one-improper ,a
,b
)
587 (if (not (equal (length a
) (length b
)))
588 `(proper-lists-of-different-length ,(length a
) ,(length b
)
591 ,(ert--mismatch a b
))
592 (cl-loop for i from
0
595 for xi
= (ert--explain-equal-rec ai bi
)
596 do
(when xi
(cl-return `(list-elt ,i
,xi
)))
597 finally
(cl-assert (equal a b
) t
)))
598 (let ((car-x (ert--explain-equal-rec (car a
) (car b
))))
601 (let ((cdr-x (ert--explain-equal-rec (cdr a
) (cdr b
))))
604 (cl-assert (equal a b
) t
)
606 (array (if (not (equal (length a
) (length b
)))
607 `(arrays-of-different-length ,(length a
) ,(length b
)
609 ,@(unless (char-table-p a
)
611 ,(ert--mismatch a b
))))
612 (cl-loop for i from
0
615 for xi
= (ert--explain-equal-rec ai bi
)
616 do
(when xi
(cl-return `(array-elt ,i
,xi
)))
617 finally
(cl-assert (equal a b
) t
))))
618 (atom (if (not (equal a b
))
619 (if (and (symbolp a
) (symbolp b
) (string= a b
))
620 `(different-symbols-with-the-same-name ,a
,b
)
621 `(different-atoms ,(ert--explain-format-atom a
)
622 ,(ert--explain-format-atom b
)))
625 (defun ert--explain-equal (a b
)
626 "Explainer function for `equal'."
627 ;; Do a quick comparison in C to avoid running our expensive
628 ;; comparison when possible.
631 (ert--explain-equal-rec a b
)))
632 (put 'equal
'ert-explainer
'ert--explain-equal
)
634 (defun ert--significant-plist-keys (plist)
635 "Return the keys of PLIST that have non-null values, in order."
636 (cl-assert (zerop (mod (length plist
) 2)) t
)
637 (cl-loop for
(key value . rest
) on plist by
#'cddr
638 unless
(or (null value
) (memq key accu
)) collect key into accu
639 finally
(cl-return accu
)))
641 (defun ert--plist-difference-explanation (a b
)
642 "Return a programmer-readable explanation of why A and B are different plists.
644 Returns nil if they are equivalent, i.e., have the same value for
645 each key, where absent values are treated as nil. The order of
646 key/value pairs in each list does not matter."
647 (cl-assert (zerop (mod (length a
) 2)) t
)
648 (cl-assert (zerop (mod (length b
) 2)) t
)
649 ;; Normalizing the plists would be another way to do this but it
650 ;; requires a total ordering on all lisp objects (since any object
651 ;; is valid as a text property key). Perhaps defining such an
652 ;; ordering is useful in other contexts, too, but it's a lot of
653 ;; work, so let's punt on it for now.
654 (let* ((keys-a (ert--significant-plist-keys a
))
655 (keys-b (ert--significant-plist-keys b
))
656 (keys-in-a-not-in-b (ert--set-difference-eq keys-a keys-b
))
657 (keys-in-b-not-in-a (ert--set-difference-eq keys-b keys-a
)))
658 (cl-flet ((explain-with-key (key)
659 (let ((value-a (plist-get a key
))
660 (value-b (plist-get b key
)))
661 (cl-assert (not (equal value-a value-b
)) t
)
662 `(different-properties-for-key
663 ,key
,(ert--explain-equal-including-properties value-a
665 (cond (keys-in-a-not-in-b
666 (explain-with-key (car keys-in-a-not-in-b
)))
668 (explain-with-key (car keys-in-b-not-in-a
)))
670 (cl-loop for key in keys-a
671 when
(not (equal (plist-get a key
) (plist-get b key
)))
672 return
(explain-with-key key
)))))))
674 (defun ert--abbreviate-string (s len suffixp
)
675 "Shorten string S to at most LEN chars.
677 If SUFFIXP is non-nil, returns a suffix of S, otherwise a prefix."
678 (let ((n (length s
)))
682 (substring s
(- n len
)))
684 (substring s
0 len
)))))
686 ;; TODO(ohler): Once bug 6581 is fixed, rename this to
687 ;; `ert--explain-equal-including-properties-rec' and add a fast-path
688 ;; wrapper like `ert--explain-equal'.
689 (defun ert--explain-equal-including-properties (a b
)
690 "Explainer function for `ert-equal-including-properties'.
692 Returns a programmer-readable explanation of why A and B are not
693 `ert-equal-including-properties', or nil if they are."
694 (if (not (equal a b
))
695 (ert--explain-equal a b
)
696 (cl-assert (stringp a
) t
)
697 (cl-assert (stringp b
) t
)
698 (cl-assert (eql (length a
) (length b
)) t
)
699 (cl-loop for i from
0 to
(length a
)
700 for props-a
= (text-properties-at i a
)
701 for props-b
= (text-properties-at i b
)
702 for difference
= (ert--plist-difference-explanation
705 (cl-return `(char ,i
,(substring-no-properties a i
(1+ i
))
708 ,(ert--abbreviate-string
709 (substring-no-properties a
0 i
)
712 ,(ert--abbreviate-string
713 (substring-no-properties a
(1+ i
))
715 ;; TODO(ohler): Get `equal-including-properties' fixed in
716 ;; Emacs, delete `ert-equal-including-properties', and
717 ;; re-enable this assertion.
718 ;;finally (cl-assert (equal-including-properties a b) t)
720 (put 'ert-equal-including-properties
722 'ert--explain-equal-including-properties
)
725 ;;; Implementation of `ert-info'.
727 ;; TODO(ohler): The name `info' clashes with
728 ;; `ert--test-execution-info'. One or both should be renamed.
729 (defvar ert--infos
'()
730 "The stack of `ert-info' infos that currently apply.
732 Bound dynamically. This is a list of (PREFIX . MESSAGE) pairs.")
734 (cl-defmacro ert-info
((message-form &key
((:prefix prefix-form
) "Info: "))
736 "Evaluate MESSAGE-FORM and BODY, and report the message if BODY fails.
738 To be used within ERT tests. MESSAGE-FORM should evaluate to a
739 string that will be displayed together with the test result if
740 the test fails. PREFIX-FORM should evaluate to a string as well
741 and is displayed in front of the value of MESSAGE-FORM."
742 (declare (debug ((form &rest
[sexp form
]) body
))
744 `(let ((ert--infos (cons (cons ,prefix-form
,message-form
) ert--infos
)))
749 ;;; Facilities for running a single test.
751 (defvar ert-debug-on-error nil
752 "Non-nil means enter debugger when a test fails or terminates with an error.")
754 ;; The data structures that represent the result of running a test.
755 (cl-defstruct ert-test-result
759 (cl-defstruct (ert-test-passed (:include ert-test-result
)))
760 (cl-defstruct (ert-test-result-with-condition (:include ert-test-result
))
761 (condition (cl-assert nil
))
762 (backtrace (cl-assert nil
))
763 (infos (cl-assert nil
)))
764 (cl-defstruct (ert-test-quit (:include ert-test-result-with-condition
)))
765 (cl-defstruct (ert-test-failed (:include ert-test-result-with-condition
)))
766 (cl-defstruct (ert-test-aborted-with-non-local-exit
767 (:include ert-test-result
)))
770 (defun ert--record-backtrace ()
771 "Record the current backtrace (as a list) and return it."
772 ;; Since the backtrace is stored in the result object, result
773 ;; objects must only be printed with appropriate limits
774 ;; (`print-level' and `print-length') in place. For interactive
775 ;; use, the cost of ensuring this possibly outweighs the advantage
776 ;; of storing the backtrace for
777 ;; `ert-results-pop-to-backtrace-for-test-at-point' given that we
778 ;; already have `ert-results-rerun-test-debugging-errors-at-point'.
779 ;; For batch use, however, printing the backtrace may be useful.
781 ;; 6 is the number of frames our own debugger adds (when
782 ;; compiled; more when interpreted). FIXME: Need to describe a
783 ;; procedure for determining this constant.
785 for frame
= (backtrace-frame i
)
789 (defun ert--print-backtrace (backtrace)
790 "Format the backtrace BACKTRACE to the current buffer."
791 ;; This is essentially a reimplementation of Fbacktrace
792 ;; (src/eval.c), but for a saved backtrace, not the current one.
793 (let ((print-escape-newlines t
)
796 (dolist (frame backtrace
)
797 (cl-ecase (car frame
)
800 (cl-destructuring-bind (special-operator &rest arg-forms
)
803 (format " %S\n" (cons special-operator arg-forms
)))))
806 (cl-destructuring-bind (fn &rest args
) (cdr frame
)
807 (insert (format " %S(" fn
))
808 (cl-loop for firstp
= t then nil
812 (insert (format "%S" arg
)))
815 ;; A container for the state of the execution of a single test and
816 ;; environment data needed during its execution.
817 (cl-defstruct ert--test-execution-info
818 (test (cl-assert nil
))
819 (result (cl-assert nil
))
820 ;; A thunk that may be called when RESULT has been set to its final
821 ;; value and test execution should be terminated. Should not
823 (exit-continuation (cl-assert nil
))
824 ;; The binding of `debugger' outside of the execution of the test.
826 ;; The binding of `ert-debug-on-error' that is in effect for the
827 ;; execution of the current test. We store it to avoid being
828 ;; affected by any new bindings the test itself may establish. (I
829 ;; don't remember whether this feature is important.)
832 (defun ert--run-test-debugger (info args
)
833 "During a test run, `debugger' is bound to a closure that calls this function.
835 This function records failures and errors and either terminates
836 the test silently or calls the interactive debugger, as
839 INFO is the ert--test-execution-info corresponding to this test
840 run. ARGS are the arguments to `debugger'."
841 (cl-destructuring-bind (first-debugger-arg &rest more-debugger-args
)
843 (cl-ecase first-debugger-arg
844 ((lambda debug t exit nil
)
845 (apply (ert--test-execution-info-next-debugger info
) args
))
847 (let* ((condition (car more-debugger-args
))
848 (type (cl-case (car condition
)
850 (otherwise 'failed
)))
851 (backtrace (ert--record-backtrace))
852 (infos (reverse ert--infos
)))
853 (setf (ert--test-execution-info-result info
)
856 (make-ert-test-quit :condition condition
860 (make-ert-test-failed :condition condition
863 ;; Work around Emacs's heuristic (in eval.c) for detecting
864 ;; errors in the debugger.
865 (cl-incf num-nonmacro-input-events
)
866 ;; FIXME: We should probably implement more fine-grained
867 ;; control a la non-t `debug-on-error' here.
869 ((ert--test-execution-info-ert-debug-on-error info
)
870 (apply (ert--test-execution-info-next-debugger info
) args
))
872 (funcall (ert--test-execution-info-exit-continuation info
)))))))
874 (defun ert--run-test-internal (test-execution-info)
875 "Low-level function to run a test according to TEST-EXECUTION-INFO.
877 This mainly sets up debugger-related bindings."
878 (setf (ert--test-execution-info-next-debugger test-execution-info
) debugger
879 (ert--test-execution-info-ert-debug-on-error test-execution-info
)
882 ;; For now, each test gets its own temp buffer and its own
883 ;; window excursion, just to be safe. If this turns out to be
884 ;; too expensive, we can remove it.
886 (save-window-excursion
887 (let ((debugger (lambda (&rest args
)
888 (ert--run-test-debugger test-execution-info
892 ;; FIXME: Do we need to store the old binding of this
893 ;; and consider it in `ert--run-test-debugger'?
894 (debug-ignored-errors nil
)
896 (funcall (ert-test-body (ert--test-execution-info-test
897 test-execution-info
))))))
899 (setf (ert--test-execution-info-result test-execution-info
)
900 (make-ert-test-passed))
903 (defun ert--force-message-log-buffer-truncation ()
904 "Immediately truncate *Messages* buffer according to `message-log-max'.
906 This can be useful after reducing the value of `message-log-max'."
907 (with-current-buffer (get-buffer-create "*Messages*")
908 ;; This is a reimplementation of this part of message_dolog() in xdisp.c:
909 ;; if (NATNUMP (Vmessage_log_max))
911 ;; scan_newline (Z, Z_BYTE, BEG, BEG_BYTE,
912 ;; -XFASTINT (Vmessage_log_max) - 1, 0);
913 ;; del_range_both (BEG, BEG_BYTE, PT, PT_BYTE, 0);
915 (when (and (integerp message-log-max
) (>= message-log-max
0))
916 (let ((begin (point-min))
918 (goto-char (point-max))
919 (forward-line (- message-log-max
))
921 (delete-region begin end
)))))
923 (defvar ert--running-tests nil
924 "List of tests that are currently in execution.
926 This list is empty while no test is running, has one element
927 while a test is running, two elements while a test run from
928 inside a test is running, etc. The list is in order of nesting,
929 innermost test first.
931 The elements are of type `ert-test'.")
933 (defun ert-run-test (ert-test)
936 Returns the result and stores it in ERT-TEST's `most-recent-result' slot."
937 (setf (ert-test-most-recent-result ert-test
) nil
)
940 (with-current-buffer (get-buffer-create "*Messages*")
941 (point-max-marker))))
943 (let ((info (make-ert--test-execution-info
946 (make-ert-test-aborted-with-non-local-exit)
947 :exit-continuation
(lambda ()
948 (cl-return-from error nil
))))
949 (should-form-accu (list)))
951 (let ((ert--should-execution-observer
952 (lambda (form-description)
953 (push form-description should-form-accu
)))
955 (ert--running-tests (cons ert-test ert--running-tests
)))
956 (ert--run-test-internal info
))
957 (let ((result (ert--test-execution-info-result info
)))
958 (setf (ert-test-result-messages result
)
959 (with-current-buffer (get-buffer-create "*Messages*")
960 (buffer-substring begin-marker
(point-max))))
961 (ert--force-message-log-buffer-truncation)
962 (setq should-form-accu
(nreverse should-form-accu
))
963 (setf (ert-test-result-should-forms result
)
965 (setf (ert-test-most-recent-result ert-test
) result
))))
966 (set-marker begin-marker nil
))))
967 (ert-test-most-recent-result ert-test
))
969 (defun ert-running-test ()
970 "Return the top-level test currently executing."
971 (car (last ert--running-tests
)))
976 (defun ert-test-result-type-p (result result-type
)
977 "Return non-nil if RESULT matches type RESULT-TYPE.
981 nil -- Never matches.
983 :failed, :passed -- Matches corresponding results.
984 \(and TYPES...\) -- Matches if all TYPES match.
985 \(or TYPES...\) -- Matches if some TYPES match.
986 \(not TYPE\) -- Matches if TYPE does not match.
987 \(satisfies PREDICATE\) -- Matches if PREDICATE returns true when called with
989 ;; It would be easy to add `member' and `eql' types etc., but I
990 ;; haven't bothered yet.
991 (cl-etypecase result-type
994 ((member :failed
) (ert-test-failed-p result
))
995 ((member :passed
) (ert-test-passed-p result
))
997 (cl-destructuring-bind (operator &rest operands
) result-type
1000 (cl-case (length operands
)
1003 (and (ert-test-result-type-p result
(car operands
))
1004 (ert-test-result-type-p result
`(and ,@(cdr operands
)))))))
1006 (cl-case (length operands
)
1009 (or (ert-test-result-type-p result
(car operands
))
1010 (ert-test-result-type-p result
`(or ,@(cdr operands
)))))))
1012 (cl-assert (eql (length operands
) 1))
1013 (not (ert-test-result-type-p result
(car operands
))))
1015 (cl-assert (eql (length operands
) 1))
1016 (funcall (car operands
) result
)))))))
1018 (defun ert-test-result-expected-p (test result
)
1019 "Return non-nil if TEST's expected result type matches RESULT."
1020 (ert-test-result-type-p result
(ert-test-expected-result-type test
)))
1022 (defun ert-select-tests (selector universe
)
1023 "Return a list of tests that match SELECTOR.
1025 UNIVERSE specifies the set of tests to select from; it should be a list
1026 of tests, or t, which refers to all tests named by symbols in `obarray'.
1030 nil -- Selects the empty set.
1031 t -- Selects UNIVERSE.
1032 :new -- Selects all tests that have not been run yet.
1033 :failed, :passed -- Select tests according to their most recent result.
1034 :expected, :unexpected -- Select tests according to their most recent result.
1035 a string -- A regular expression selecting all tests with matching names.
1036 a test -- (i.e., an object of the ert-test data-type) Selects that test.
1037 a symbol -- Selects the test that the symbol names, errors if none.
1038 \(member TESTS...) -- Selects the elements of TESTS, a list of tests
1039 or symbols naming tests.
1040 \(eql TEST\) -- Selects TEST, a test or a symbol naming a test.
1041 \(and SELECTORS...) -- Selects the tests that match all SELECTORS.
1042 \(or SELECTORS...) -- Selects the tests that match any of the SELECTORS.
1043 \(not SELECTOR) -- Selects all tests that do not match SELECTOR.
1044 \(tag TAG) -- Selects all tests that have TAG on their tags list.
1045 A tag is an arbitrary label you can apply when you define a test.
1046 \(satisfies PREDICATE) -- Selects all tests that satisfy PREDICATE.
1047 PREDICATE is a function that takes an ert-test object as argument,
1048 and returns non-nil if it is selected.
1050 Only selectors that require a superset of tests, such
1051 as (satisfies ...), strings, :new, etc. make use of UNIVERSE.
1052 Selectors that do not, such as (member ...), just return the
1053 set implied by them without checking whether it is really
1054 contained in UNIVERSE."
1055 ;; This code needs to match the etypecase in
1056 ;; `ert-insert-human-readable-selector'.
1057 (cl-etypecase selector
1059 ((member t
) (cl-etypecase universe
1061 ((member t
) (ert-select-tests "" universe
))))
1062 ((member :new
) (ert-select-tests
1063 `(satisfies ,(lambda (test)
1064 (null (ert-test-most-recent-result test
))))
1066 ((member :failed
) (ert-select-tests
1067 `(satisfies ,(lambda (test)
1068 (ert-test-result-type-p
1069 (ert-test-most-recent-result test
)
1072 ((member :passed
) (ert-select-tests
1073 `(satisfies ,(lambda (test)
1074 (ert-test-result-type-p
1075 (ert-test-most-recent-result test
)
1078 ((member :expected
) (ert-select-tests
1081 (ert-test-result-expected-p
1083 (ert-test-most-recent-result test
))))
1085 ((member :unexpected
) (ert-select-tests `(not :expected
) universe
))
1087 (cl-etypecase universe
1088 ((member t
) (mapcar #'ert-get-test
1089 (apropos-internal selector
#'ert-test-boundp
)))
1090 (list (ert--remove-if-not (lambda (test)
1091 (and (ert-test-name test
)
1092 (string-match selector
1093 (ert-test-name test
))))
1095 (ert-test (list selector
))
1097 (cl-assert (ert-test-boundp selector
))
1098 (list (ert-get-test selector
)))
1100 (cl-destructuring-bind (operator &rest operands
) selector
1103 (mapcar (lambda (purported-test)
1104 (cl-etypecase purported-test
1105 (symbol (cl-assert (ert-test-boundp purported-test
))
1106 (ert-get-test purported-test
))
1107 (ert-test purported-test
)))
1110 (cl-assert (eql (length operands
) 1))
1111 (ert-select-tests `(member ,@operands
) universe
))
1113 ;; Do these definitions of AND, NOT and OR satisfy de
1114 ;; Morgan's laws? Should they?
1115 (cl-case (length operands
)
1116 (0 (ert-select-tests 't universe
))
1117 (t (ert-select-tests `(and ,@(cdr operands
))
1118 (ert-select-tests (car operands
)
1121 (cl-assert (eql (length operands
) 1))
1122 (let ((all-tests (ert-select-tests 't universe
)))
1123 (ert--set-difference all-tests
1124 (ert-select-tests (car operands
)
1127 (cl-case (length operands
)
1128 (0 (ert-select-tests 'nil universe
))
1129 (t (ert--union (ert-select-tests (car operands
) universe
)
1130 (ert-select-tests `(or ,@(cdr operands
))
1133 (cl-assert (eql (length operands
) 1))
1134 (let ((tag (car operands
)))
1135 (ert-select-tests `(satisfies
1137 (member tag
(ert-test-tags test
))))
1140 (cl-assert (eql (length operands
) 1))
1141 (ert--remove-if-not (car operands
)
1142 (ert-select-tests 't universe
))))))))
1144 (defun ert--insert-human-readable-selector (selector)
1145 "Insert a human-readable presentation of SELECTOR into the current buffer."
1146 ;; This is needed to avoid printing the (huge) contents of the
1147 ;; `backtrace' slot of the result objects in the
1148 ;; `most-recent-result' slots of test case objects in (eql ...) or
1149 ;; (member ...) selectors.
1150 (cl-labels ((rec (selector)
1151 ;; This code needs to match the etypecase in
1152 ;; `ert-select-tests'.
1153 (cl-etypecase selector
1155 :new
:failed
:passed
1156 :expected
:unexpected
)
1161 (if (ert-test-name selector
)
1162 (make-symbol (format "<%S>" (ert-test-name selector
)))
1163 (make-symbol "<unnamed test>")))
1165 (cl-destructuring-bind (operator &rest operands
) selector
1167 ((member eql and not or
)
1168 `(,operator
,@(mapcar #'rec operands
)))
1169 ((member tag satisfies
)
1171 (insert (format "%S" (rec selector
)))))
1174 ;;; Facilities for running a whole set of tests.
1176 ;; The data structure that contains the set of tests being executed
1177 ;; during one particular test run, their results, the state of the
1178 ;; execution, and some statistics.
1180 ;; The data about results and expected results of tests may seem
1181 ;; redundant here, since the test objects also carry such information.
1182 ;; However, the information in the test objects may be more recent, it
1183 ;; may correspond to a different test run. We need the information
1184 ;; that corresponds to this run in order to be able to update the
1185 ;; statistics correctly when a test is re-run interactively and has a
1186 ;; different result than before.
1187 (cl-defstruct ert--stats
1188 (selector (cl-assert nil
))
1189 ;; The tests, in order.
1190 (tests (cl-assert nil
) :type vector
)
1191 ;; A map of test names (or the test objects themselves for unnamed
1192 ;; tests) to indices into the `tests' vector.
1193 (test-map (cl-assert nil
) :type hash-table
)
1194 ;; The results of the tests during this run, in order.
1195 (test-results (cl-assert nil
) :type vector
)
1196 ;; The start times of the tests, in order, as reported by
1198 (test-start-times (cl-assert nil
) :type vector
)
1199 ;; The end times of the tests, in order, as reported by
1201 (test-end-times (cl-assert nil
) :type vector
)
1203 (passed-unexpected 0)
1205 (failed-unexpected 0)
1210 ;; The time at or after which the next redisplay should occur, as a
1212 (next-redisplay 0.0))
1214 (defun ert-stats-completed-expected (stats)
1215 "Return the number of tests in STATS that had expected results."
1216 (+ (ert--stats-passed-expected stats
)
1217 (ert--stats-failed-expected stats
)))
1219 (defun ert-stats-completed-unexpected (stats)
1220 "Return the number of tests in STATS that had unexpected results."
1221 (+ (ert--stats-passed-unexpected stats
)
1222 (ert--stats-failed-unexpected stats
)))
1224 (defun ert-stats-completed (stats)
1225 "Number of tests in STATS that have run so far."
1226 (+ (ert-stats-completed-expected stats
)
1227 (ert-stats-completed-unexpected stats
)))
1229 (defun ert-stats-total (stats)
1230 "Number of tests in STATS, regardless of whether they have run yet."
1231 (length (ert--stats-tests stats
)))
1233 ;; The stats object of the current run, dynamically bound. This is
1234 ;; used for the mode line progress indicator.
1235 (defvar ert--current-run-stats nil
)
1237 (defun ert--stats-test-key (test)
1238 "Return the key used for TEST in the test map of ert--stats objects.
1240 Returns the name of TEST if it has one, or TEST itself otherwise."
1241 (or (ert-test-name test
) test
))
1243 (defun ert--stats-set-test-and-result (stats pos test result
)
1244 "Change STATS by replacing the test at position POS with TEST and RESULT.
1246 Also changes the counters in STATS to match."
1247 (let* ((tests (ert--stats-tests stats
))
1248 (results (ert--stats-test-results stats
))
1249 (old-test (aref tests pos
))
1250 (map (ert--stats-test-map stats
)))
1251 (cl-flet ((update (d)
1252 (if (ert-test-result-expected-p (aref tests pos
)
1254 (cl-etypecase (aref results pos
)
1256 (cl-incf (ert--stats-passed-expected stats
) d
))
1258 (cl-incf (ert--stats-failed-expected stats
) d
))
1260 (ert-test-aborted-with-non-local-exit)
1262 (cl-etypecase (aref results pos
)
1264 (cl-incf (ert--stats-passed-unexpected stats
) d
))
1266 (cl-incf (ert--stats-failed-unexpected stats
) d
))
1268 (ert-test-aborted-with-non-local-exit)
1270 ;; Adjust counters to remove the result that is currently in stats.
1272 ;; Put new test and result into stats.
1273 (setf (aref tests pos
) test
1274 (aref results pos
) result
)
1275 (remhash (ert--stats-test-key old-test
) map
)
1276 (setf (gethash (ert--stats-test-key test
) map
) pos
)
1277 ;; Adjust counters to match new result.
1281 (defun ert--make-stats (tests selector
)
1282 "Create a new `ert--stats' object for running TESTS.
1284 SELECTOR is the selector that was used to select TESTS."
1285 (setq tests
(ert--coerce-to-vector tests
))
1286 (let ((map (make-hash-table :size
(length tests
))))
1287 (cl-loop for i from
0
1288 for test across tests
1289 for key
= (ert--stats-test-key test
) do
1290 (cl-assert (not (gethash key map
)))
1291 (setf (gethash key map
) i
))
1292 (make-ert--stats :selector selector
1295 :test-results
(make-vector (length tests
) nil
)
1296 :test-start-times
(make-vector (length tests
) nil
)
1297 :test-end-times
(make-vector (length tests
) nil
))))
1299 (defun ert-run-or-rerun-test (stats test listener
)
1300 ;; checkdoc-order: nil
1301 "Run the single test TEST and record the result using STATS and LISTENER."
1302 (let ((ert--current-run-stats stats
)
1303 (pos (ert--stats-test-pos stats test
)))
1304 (ert--stats-set-test-and-result stats pos test nil
)
1305 ;; Call listener after setting/before resetting
1306 ;; (ert--stats-current-test stats); the listener might refresh the
1307 ;; mode line display, and if the value is not set yet/any more
1308 ;; during this refresh, the mode line will flicker unnecessarily.
1309 (setf (ert--stats-current-test stats
) test
)
1310 (funcall listener
'test-started stats test
)
1311 (setf (ert-test-most-recent-result test
) nil
)
1312 (setf (aref (ert--stats-test-start-times stats
) pos
) (current-time))
1315 (setf (aref (ert--stats-test-end-times stats
) pos
) (current-time))
1316 (let ((result (ert-test-most-recent-result test
)))
1317 (ert--stats-set-test-and-result stats pos test result
)
1318 (funcall listener
'test-ended stats test result
))
1319 (setf (ert--stats-current-test stats
) nil
))))
1321 (defun ert-run-tests (selector listener
)
1322 "Run the tests specified by SELECTOR, sending progress updates to LISTENER."
1323 (let* ((tests (ert-select-tests selector t
))
1324 (stats (ert--make-stats tests selector
)))
1325 (setf (ert--stats-start-time stats
) (current-time))
1326 (funcall listener
'run-started stats
)
1329 (let ((ert--current-run-stats stats
))
1330 (force-mode-line-update)
1333 (cl-loop for test in tests do
1334 (ert-run-or-rerun-test stats test listener
))
1335 (setq abortedp nil
))
1336 (setf (ert--stats-aborted-p stats
) abortedp
)
1337 (setf (ert--stats-end-time stats
) (current-time))
1338 (funcall listener
'run-ended stats abortedp
)))
1339 (force-mode-line-update))
1342 (defun ert--stats-test-pos (stats test
)
1343 ;; checkdoc-order: nil
1344 "Return the position (index) of TEST in the run represented by STATS."
1345 (gethash (ert--stats-test-key test
) (ert--stats-test-map stats
)))
1348 ;;; Formatting functions shared across UIs.
1350 (defun ert--format-time-iso8601 (time)
1351 "Format TIME in the variant of ISO 8601 used for timestamps in ERT."
1352 (format-time-string "%Y-%m-%d %T%z" time
))
1354 (defun ert-char-for-test-result (result expectedp
)
1355 "Return a character that represents the test result RESULT.
1357 EXPECTEDP specifies whether the result was expected."
1358 (let ((s (cl-etypecase result
1359 (ert-test-passed ".P")
1360 (ert-test-failed "fF")
1362 (ert-test-aborted-with-non-local-exit "aA")
1363 (ert-test-quit "qQ"))))
1364 (elt s
(if expectedp
0 1))))
1366 (defun ert-string-for-test-result (result expectedp
)
1367 "Return a string that represents the test result RESULT.
1369 EXPECTEDP specifies whether the result was expected."
1370 (let ((s (cl-etypecase result
1371 (ert-test-passed '("passed" "PASSED"))
1372 (ert-test-failed '("failed" "FAILED"))
1373 (null '("unknown" "UNKNOWN"))
1374 (ert-test-aborted-with-non-local-exit '("aborted" "ABORTED"))
1375 (ert-test-quit '("quit" "QUIT")))))
1376 (elt s
(if expectedp
0 1))))
1378 (defun ert--pp-with-indentation-and-newline (object)
1379 "Pretty-print OBJECT, indenting it to the current column of point.
1380 Ensures a final newline is inserted."
1381 (let ((begin (point)))
1382 (pp object
(current-buffer))
1383 (unless (bolp) (insert "\n"))
1388 (defun ert--insert-infos (result)
1389 "Insert `ert-info' infos from RESULT into current buffer.
1391 RESULT must be an `ert-test-result-with-condition'."
1392 (cl-check-type result ert-test-result-with-condition
)
1393 (dolist (info (ert-test-result-with-condition-infos result
))
1394 (cl-destructuring-bind (prefix . message
) info
1395 (let ((begin (point))
1396 (indentation (make-string (+ (length prefix
) 4) ?\s
))
1400 (insert message
"\n")
1401 (setq end
(copy-marker (point)))
1405 (while (< (point) end
)
1406 (insert indentation
)
1408 (when end
(set-marker end nil
)))))))
1411 ;;; Running tests in batch mode.
1413 (defvar ert-batch-backtrace-right-margin
70
1414 "The maximum line length for printing backtraces in `ert-run-tests-batch'.")
1417 (defun ert-run-tests-batch (&optional selector
)
1418 "Run the tests specified by SELECTOR, printing results to the terminal.
1420 SELECTOR works as described in `ert-select-tests', except if
1421 SELECTOR is nil, in which case all tests rather than none will be
1422 run; this makes the command line \"emacs -batch -l my-tests.el -f
1423 ert-run-tests-batch-and-exit\" useful.
1425 Returns the stats object."
1426 (unless selector
(setq selector
't
))
1429 (lambda (event-type &rest event-args
)
1430 (cl-ecase event-type
1432 (cl-destructuring-bind (stats) event-args
1433 (message "Running %s tests (%s)"
1434 (length (ert--stats-tests stats
))
1435 (ert--format-time-iso8601 (ert--stats-start-time stats
)))))
1437 (cl-destructuring-bind (stats abortedp
) event-args
1438 (let ((unexpected (ert-stats-completed-unexpected stats
))
1439 (expected-failures (ert--stats-failed-expected stats
)))
1440 (message "\n%sRan %s tests, %s results as expected%s (%s)%s\n"
1444 (ert-stats-total stats
)
1445 (ert-stats-completed-expected stats
)
1446 (if (zerop unexpected
)
1448 (format ", %s unexpected" unexpected
))
1449 (ert--format-time-iso8601 (ert--stats-end-time stats
))
1450 (if (zerop expected-failures
)
1452 (format "\n%s expected failures" expected-failures
)))
1453 (unless (zerop unexpected
)
1454 (message "%s unexpected results:" unexpected
)
1455 (cl-loop for test across
(ert--stats-tests stats
)
1456 for result
= (ert-test-most-recent-result test
) do
1457 (when (not (ert-test-result-expected-p test result
))
1459 (ert-string-for-test-result result nil
)
1460 (ert-test-name test
))))
1461 (message "%s" "")))))
1465 (cl-destructuring-bind (stats test result
) event-args
1466 (unless (ert-test-result-expected-p test result
)
1467 (cl-etypecase result
1469 (message "Test %S passed unexpectedly" (ert-test-name test
)))
1470 (ert-test-result-with-condition
1471 (message "Test %S backtrace:" (ert-test-name test
))
1473 (ert--print-backtrace (ert-test-result-with-condition-backtrace
1475 (goto-char (point-min))
1477 (let ((start (point))
1478 (end (progn (end-of-line) (point))))
1480 (+ start ert-batch-backtrace-right-margin
)))
1481 (message "%s" (buffer-substring-no-properties
1485 (ert--insert-infos result
)
1487 (let ((print-escape-newlines t
)
1490 (ert--pp-with-indentation-and-newline
1491 (ert-test-result-with-condition-condition result
)))
1492 (goto-char (1- (point-max)))
1493 (cl-assert (looking-at "\n"))
1495 (message "Test %S condition:" (ert-test-name test
))
1496 (message "%s" (buffer-string))))
1497 (ert-test-aborted-with-non-local-exit
1498 (message "Test %S aborted with non-local exit"
1499 (ert-test-name test
)))
1501 (message "Quit during %S" (ert-test-name test
)))))
1502 (let* ((max (prin1-to-string (length (ert--stats-tests stats
))))
1503 (format-string (concat "%9s %"
1504 (prin1-to-string (length max
))
1506 (message format-string
1507 (ert-string-for-test-result result
1508 (ert-test-result-expected-p
1510 (1+ (ert--stats-test-pos stats test
))
1511 (ert-test-name test
)))))))))
1514 (defun ert-run-tests-batch-and-exit (&optional selector
)
1515 "Like `ert-run-tests-batch', but exits Emacs when done.
1517 The exit status will be 0 if all test results were as expected, 1
1518 on unexpected results, or 2 if the tool detected an error outside
1519 of the tests (e.g. invalid SELECTOR or bug in the code that runs
1522 (let ((stats (ert-run-tests-batch selector
)))
1523 (kill-emacs (if (zerop (ert-stats-completed-unexpected stats
)) 0 1)))
1526 (message "Error running tests")
1531 ;;; Utility functions for load/unload actions.
1533 (defun ert--activate-font-lock-keywords ()
1534 "Activate font-lock keywords for some of ERT's symbols."
1535 (font-lock-add-keywords
1537 '(("(\\(\\<ert-deftest\\)\\>\\s *\\(\\sw+\\)?"
1538 (1 font-lock-keyword-face nil t
)
1539 (2 font-lock-function-name-face nil t
)))))
1541 (cl-defun ert--remove-from-list (list-var element
&key key test
)
1542 "Remove ELEMENT from the value of LIST-VAR if present.
1544 This can be used as an inverse of `add-to-list'."
1545 (unless key
(setq key
#'identity
))
1546 (unless test
(setq test
#'equal
))
1547 (setf (symbol-value list-var
)
1548 (ert--remove* element
1549 (symbol-value list-var
)
1554 ;;; Some basic interactive functions.
1556 (defun ert-read-test-name (prompt &optional default history
1557 add-default-to-prompt
)
1558 "Read the name of a test and return it as a symbol.
1560 Prompt with PROMPT. If DEFAULT is a valid test name, use it as a
1561 default. HISTORY is the history to use; see `completing-read'.
1562 If ADD-DEFAULT-TO-PROMPT is non-nil, PROMPT will be modified to
1563 include the default, if any.
1565 Signals an error if no test name was read."
1566 (cl-etypecase default
1567 (string (let ((symbol (intern-soft default
)))
1568 (unless (and symbol
(ert-test-boundp symbol
))
1569 (setq default nil
))))
1570 (symbol (setq default
1571 (if (ert-test-boundp default
)
1572 (symbol-name default
)
1574 (ert-test (setq default
(ert-test-name default
))))
1575 (when add-default-to-prompt
1576 (setq prompt
(if (null default
)
1577 (format "%s: " prompt
)
1578 (format "%s (default %s): " prompt default
))))
1579 (let ((input (completing-read prompt obarray
#'ert-test-boundp
1580 t nil history default nil
)))
1581 ;; completing-read returns an empty string if default was nil and
1582 ;; the user just hit enter.
1583 (let ((sym (intern-soft input
)))
1584 (if (ert-test-boundp sym
)
1586 (error "Input does not name a test")))))
1588 (defun ert-read-test-name-at-point (prompt)
1589 "Read the name of a test and return it as a symbol.
1590 As a default, use the symbol at point, or the test at point if in
1591 the ERT results buffer. Prompt with PROMPT, augmented with the
1593 (ert-read-test-name prompt
(ert-test-at-point) nil t
))
1595 (defun ert-find-test-other-window (test-name)
1596 "Find, in another window, the definition of TEST-NAME."
1597 (interactive (list (ert-read-test-name-at-point "Find test definition: ")))
1598 (find-function-do-it test-name
'ert-deftest
'switch-to-buffer-other-window
))
1600 (defun ert-delete-test (test-name)
1601 "Make the test TEST-NAME unbound.
1603 Nothing more than an interactive interface to `ert-make-test-unbound'."
1604 (interactive (list (ert-read-test-name-at-point "Delete test")))
1605 (ert-make-test-unbound test-name
))
1607 (defun ert-delete-all-tests ()
1608 "Make all symbols in `obarray' name no test."
1610 (when (called-interactively-p 'any
)
1611 (unless (y-or-n-p "Delete all tests? ")
1613 ;; We can't use `ert-select-tests' here since that gives us only
1614 ;; test objects, and going from them back to the test name symbols
1615 ;; can fail if the `ert-test' defstruct has been redefined.
1616 (mapc #'ert-make-test-unbound
(apropos-internal "" #'ert-test-boundp
))
1620 ;;; Display of test progress and results.
1622 ;; An entry in the results buffer ewoc. There is one entry per test.
1623 (cl-defstruct ert--ewoc-entry
1624 (test (cl-assert nil
))
1625 ;; If the result of this test was expected, its ewoc entry is hidden
1627 (hidden-p (cl-assert nil
))
1628 ;; An ewoc entry may be collapsed to hide details such as the error
1631 ;; I'm not sure the ability to expand and collapse entries is still
1632 ;; a useful feature.
1634 ;; By default, the ewoc entry presents the error condition with
1635 ;; certain limits on how much to print (`print-level',
1636 ;; `print-length'). The user can interactively switch to a set of
1638 (extended-printer-limits-p nil
))
1640 ;; Variables local to the results buffer.
1643 (defvar ert--results-ewoc
)
1644 ;; The stats object.
1645 (defvar ert--results-stats
)
1646 ;; A string with one character per test. Each character represents
1647 ;; the result of the corresponding test. The string is displayed near
1648 ;; the top of the buffer and serves as a progress bar.
1649 (defvar ert--results-progress-bar-string
)
1650 ;; The position where the progress bar button begins.
1651 (defvar ert--results-progress-bar-button-begin
)
1652 ;; The test result listener that updates the buffer when tests are run.
1653 (defvar ert--results-listener
)
1655 (defun ert-insert-test-name-button (test-name)
1656 "Insert a button that links to TEST-NAME."
1657 (insert-text-button (format "%S" test-name
)
1658 :type
'ert--test-name-button
1659 'ert-test-name test-name
))
1661 (defun ert--results-format-expected-unexpected (expected unexpected
)
1662 "Return a string indicating EXPECTED expected results, UNEXPECTED unexpected."
1663 (if (zerop unexpected
)
1664 (format "%s" expected
)
1665 (format "%s (%s unexpected)" (+ expected unexpected
) unexpected
)))
1667 (defun ert--results-update-ewoc-hf (ewoc stats
)
1668 "Update the header and footer of EWOC to show certain information from STATS.
1670 Also sets `ert--results-progress-bar-button-begin'."
1671 (let ((run-count (ert-stats-completed stats
))
1672 (results-buffer (current-buffer))
1673 ;; Need to save buffer-local value.
1674 (font-lock font-lock-mode
))
1679 (insert "Selector: ")
1680 (ert--insert-human-readable-selector (ert--stats-selector stats
))
1683 (format (concat "Passed: %s\n"
1686 (ert--results-format-expected-unexpected
1687 (ert--stats-passed-expected stats
)
1688 (ert--stats-passed-unexpected stats
))
1689 (ert--results-format-expected-unexpected
1690 (ert--stats-failed-expected stats
)
1691 (ert--stats-failed-unexpected stats
))
1693 (ert-stats-total stats
)))
1695 (format "Started at: %s\n"
1696 (ert--format-time-iso8601 (ert--stats-start-time stats
))))
1697 ;; FIXME: This is ugly. Need to properly define invariants of
1698 ;; the `stats' data structure.
1699 (let ((state (cond ((ert--stats-aborted-p stats
) 'aborted
)
1700 ((ert--stats-current-test stats
) 'running
)
1701 ((ert--stats-end-time stats
) 'finished
)
1707 (cond ((ert--stats-current-test stats
)
1708 (insert "Aborted during test: ")
1709 (ert-insert-test-name-button
1710 (ert-test-name (ert--stats-current-test stats
))))
1712 (insert "Aborted."))))
1714 (cl-assert (ert--stats-current-test stats
))
1715 (insert "Running test: ")
1716 (ert-insert-test-name-button (ert-test-name
1717 (ert--stats-current-test stats
))))
1719 (cl-assert (not (ert--stats-current-test stats
)))
1720 (insert "Finished.")))
1722 (if (ert--stats-end-time stats
)
1725 (if (ert--stats-aborted-p stats
)
1728 (ert--format-time-iso8601 (ert--stats-end-time stats
))))
1731 (let ((progress-bar-string (with-current-buffer results-buffer
1732 ert--results-progress-bar-string
)))
1733 (let ((progress-bar-button-begin
1734 (insert-text-button progress-bar-string
1735 :type
'ert--results-progress-bar-button
1736 'face
(or (and font-lock
1737 (ert-face-for-stats stats
))
1739 ;; The header gets copied verbatim to the results buffer,
1740 ;; and all positions remain the same, so
1741 ;; `progress-bar-button-begin' will be the right position
1742 ;; even in the results buffer.
1743 (with-current-buffer results-buffer
1744 (set (make-local-variable 'ert--results-progress-bar-button-begin
)
1745 progress-bar-button-begin
))))
1750 ;; We actually want an empty footer, but that would trigger a bug
1751 ;; in ewoc, sometimes clearing the entire buffer. (It's possible
1752 ;; that this bug has been fixed since this has been tested; we
1753 ;; should test it again.)
1757 (defvar ert-test-run-redisplay-interval-secs
.1
1758 "How many seconds ERT should wait between redisplays while running tests.
1760 While running tests, ERT shows the current progress, and this variable
1761 determines how frequently the progress display is updated.")
1763 (defun ert--results-update-stats-display (ewoc stats
)
1764 "Update EWOC and the mode line to show data from STATS."
1765 ;; TODO(ohler): investigate using `make-progress-reporter'.
1766 (ert--results-update-ewoc-hf ewoc stats
)
1767 (force-mode-line-update)
1769 (setf (ert--stats-next-redisplay stats
)
1770 (+ (float-time) ert-test-run-redisplay-interval-secs
)))
1772 (defun ert--results-update-stats-display-maybe (ewoc stats
)
1773 "Call `ert--results-update-stats-display' if not called recently.
1775 EWOC and STATS are arguments for `ert--results-update-stats-display'."
1776 (when (>= (float-time) (ert--stats-next-redisplay stats
))
1777 (ert--results-update-stats-display ewoc stats
)))
1779 (defun ert--tests-running-mode-line-indicator ()
1780 "Return a string for the mode line that shows the test run progress."
1781 (let* ((stats ert--current-run-stats
)
1782 (tests-total (ert-stats-total stats
))
1783 (tests-completed (ert-stats-completed stats
)))
1784 (if (>= tests-completed tests-total
)
1785 (format " ERT(%s/%s,finished)" tests-completed tests-total
)
1786 (format " ERT(%s/%s):%s"
1787 (1+ tests-completed
)
1789 (if (null (ert--stats-current-test stats
))
1792 (ert-test-name (ert--stats-current-test stats
))))))))
1794 (defun ert--make-xrefs-region (begin end
)
1795 "Attach cross-references to function names between BEGIN and END.
1797 BEGIN and END specify a region in the current buffer."
1800 (narrow-to-region begin end
)
1801 ;; Inhibit optimization in `debugger-make-xrefs' that would
1802 ;; sometimes insert unrelated backtrace info into our buffer.
1803 (let ((debugger-previous-backtrace nil
))
1804 (debugger-make-xrefs)))))
1806 (defun ert--string-first-line (s)
1807 "Return the first line of S, or S if it contains no newlines.
1809 The return value does not include the line terminator."
1810 (substring s
0 (ert--string-position ?
\n s
)))
1812 (defun ert-face-for-test-result (expectedp)
1813 "Return a face that shows whether a test result was expected or unexpected.
1815 If EXPECTEDP is nil, returns the face for unexpected results; if
1816 non-nil, returns the face for expected results.."
1817 (if expectedp
'ert-test-result-expected
'ert-test-result-unexpected
))
1819 (defun ert-face-for-stats (stats)
1820 "Return a face that represents STATS."
1821 (cond ((ert--stats-aborted-p stats
) 'nil
)
1822 ((cl-plusp (ert-stats-completed-unexpected stats
))
1823 (ert-face-for-test-result nil
))
1824 ((eql (ert-stats-completed-expected stats
) (ert-stats-total stats
))
1825 (ert-face-for-test-result t
))
1828 (defun ert--print-test-for-ewoc (entry)
1829 "The ewoc print function for ewoc test entries. ENTRY is the entry to print."
1830 (let* ((test (ert--ewoc-entry-test entry
))
1831 (stats ert--results-stats
)
1832 (result (let ((pos (ert--stats-test-pos stats test
)))
1834 (aref (ert--stats-test-results stats
) pos
)))
1835 (hiddenp (ert--ewoc-entry-hidden-p entry
))
1836 (expandedp (ert--ewoc-entry-expanded-p entry
))
1837 (extended-printer-limits-p (ert--ewoc-entry-extended-printer-limits-p
1841 (let ((expectedp (ert-test-result-expected-p test result
)))
1842 (insert-text-button (format "%c" (ert-char-for-test-result
1844 :type
'ert--results-expand-collapse-button
1845 'face
(or (and font-lock-mode
1846 (ert-face-for-test-result
1850 (ert-insert-test-name-button (ert-test-name test
))
1852 (when (and expandedp
(not (eql result
'nil
)))
1853 (when (ert-test-documentation test
)
1856 (ert--string-first-line (ert-test-documentation test
))
1857 'font-lock-face
'font-lock-doc-face
)
1859 (cl-etypecase result
1861 (if (ert-test-result-expected-p test result
)
1862 (insert " passed\n")
1863 (insert " passed unexpectedly\n"))
1865 (ert-test-result-with-condition
1866 (ert--insert-infos result
)
1867 (let ((print-escape-newlines t
)
1868 (print-level (if extended-printer-limits-p
12 6))
1869 (print-length (if extended-printer-limits-p
100 10)))
1871 (let ((begin (point)))
1872 (ert--pp-with-indentation-and-newline
1873 (ert-test-result-with-condition-condition result
))
1874 (ert--make-xrefs-region begin
(point)))))
1875 (ert-test-aborted-with-non-local-exit
1876 (insert " aborted\n"))
1878 (insert " quit\n")))
1882 (defun ert--results-font-lock-function (enabledp)
1883 "Redraw the ERT results buffer after font-lock-mode was switched on or off.
1885 ENABLEDP is true if font-lock-mode is switched on, false
1887 (ert--results-update-ewoc-hf ert--results-ewoc ert--results-stats
)
1888 (ewoc-refresh ert--results-ewoc
)
1889 (font-lock-default-function enabledp
))
1891 (defun ert--setup-results-buffer (stats listener buffer-name
)
1892 "Set up a test results buffer.
1894 STATS is the stats object; LISTENER is the results listener;
1895 BUFFER-NAME, if non-nil, is the buffer name to use."
1896 (unless buffer-name
(setq buffer-name
"*ert*"))
1897 (let ((buffer (get-buffer-create buffer-name
)))
1898 (with-current-buffer buffer
1899 (let ((inhibit-read-only t
))
1900 (buffer-disable-undo)
1903 ;; Erase buffer again in case switching out of the previous
1904 ;; mode inserted anything. (This happens e.g. when switching
1905 ;; from ert-results-mode to ert-results-mode when
1906 ;; font-lock-mode turns itself off in change-major-mode-hook.)
1908 (set (make-local-variable 'font-lock-function
)
1909 'ert--results-font-lock-function
)
1910 (let ((ewoc (ewoc-create 'ert--print-test-for-ewoc nil nil t
)))
1911 (set (make-local-variable 'ert--results-ewoc
) ewoc
)
1912 (set (make-local-variable 'ert--results-stats
) stats
)
1913 (set (make-local-variable 'ert--results-progress-bar-string
)
1914 (make-string (ert-stats-total stats
)
1915 (ert-char-for-test-result nil t
)))
1916 (set (make-local-variable 'ert--results-listener
) listener
)
1917 (cl-loop for test across
(ert--stats-tests stats
) do
1918 (ewoc-enter-last ewoc
1919 (make-ert--ewoc-entry :test test
1921 (ert--results-update-ewoc-hf ert--results-ewoc ert--results-stats
)
1922 (goto-char (1- (point-max)))
1926 (defvar ert--selector-history nil
1927 "List of recent test selectors read from terminal.")
1929 ;; Should OUTPUT-BUFFER-NAME and MESSAGE-FN really be arguments here?
1930 ;; They are needed only for our automated self-tests at the moment.
1931 ;; Or should there be some other mechanism?
1933 (defun ert-run-tests-interactively (selector
1934 &optional output-buffer-name message-fn
)
1935 "Run the tests specified by SELECTOR and display the results in a buffer.
1937 SELECTOR works as described in `ert-select-tests'.
1938 OUTPUT-BUFFER-NAME and MESSAGE-FN should normally be nil; they
1939 are used for automated self-tests and specify which buffer to use
1940 and how to display message."
1942 (list (let ((default (if ert--selector-history
1943 ;; Can't use `first' here as this form is
1944 ;; not compiled, and `first' is not
1945 ;; defined without cl.
1946 (car ert--selector-history
)
1948 (read-from-minibuffer (if (null default
)
1950 (format "Run tests (default %s): " default
))
1951 nil nil t
'ert--selector-history
1954 (unless message-fn
(setq message-fn
'message
))
1955 (let ((output-buffer-name output-buffer-name
)
1958 (message-fn message-fn
))
1960 (lambda (event-type &rest event-args
)
1961 (cl-ecase event-type
1963 (cl-destructuring-bind (stats) event-args
1964 (setq buffer
(ert--setup-results-buffer stats
1966 output-buffer-name
))
1967 (pop-to-buffer buffer
)))
1969 (cl-destructuring-bind (stats abortedp
) event-args
1971 "%sRan %s tests, %s results were as expected%s"
1975 (ert-stats-total stats
)
1976 (ert-stats-completed-expected stats
)
1978 (ert-stats-completed-unexpected stats
)))
1979 (if (zerop unexpected
)
1981 (format ", %s unexpected" unexpected
))))
1982 (ert--results-update-stats-display (with-current-buffer buffer
1986 (cl-destructuring-bind (stats test
) event-args
1987 (with-current-buffer buffer
1988 (let* ((ewoc ert--results-ewoc
)
1989 (pos (ert--stats-test-pos stats test
))
1990 (node (ewoc-nth ewoc pos
)))
1992 (setf (ert--ewoc-entry-test (ewoc-data node
)) test
)
1993 (aset ert--results-progress-bar-string pos
1994 (ert-char-for-test-result nil t
))
1995 (ert--results-update-stats-display-maybe ewoc stats
)
1996 (ewoc-invalidate ewoc node
)))))
1998 (cl-destructuring-bind (stats test result
) event-args
1999 (with-current-buffer buffer
2000 (let* ((ewoc ert--results-ewoc
)
2001 (pos (ert--stats-test-pos stats test
))
2002 (node (ewoc-nth ewoc pos
)))
2003 (when (ert--ewoc-entry-hidden-p (ewoc-data node
))
2004 (setf (ert--ewoc-entry-hidden-p (ewoc-data node
))
2005 (ert-test-result-expected-p test result
)))
2006 (aset ert--results-progress-bar-string pos
2007 (ert-char-for-test-result result
2008 (ert-test-result-expected-p
2010 (ert--results-update-stats-display-maybe ewoc stats
)
2011 (ewoc-invalidate ewoc node
))))))))
2016 (defalias 'ert
'ert-run-tests-interactively
)
2019 ;;; Simple view mode for auxiliary information like stack traces or
2020 ;;; messages. Mainly binds "q" for quit.
2022 (define-derived-mode ert-simple-view-mode special-mode
"ERT-View"
2023 "Major mode for viewing auxiliary information in ERT.")
2025 ;;; Commands and button actions for the results buffer.
2027 (define-derived-mode ert-results-mode special-mode
"ERT-Results"
2028 "Major mode for viewing results of ERT test runs.")
2030 (cl-loop for
(key binding
) in
2031 '( ;; Stuff that's not in the menu.
2032 ("\t" forward-button
)
2033 ([backtab] backward-button)
2034 ("j" ert-results-jump-between-summary-and-result)
2035 ("L" ert-results-toggle-printer-limits-for-test-at-point)
2036 ("n" ert-results-next-test)
2037 ("p" ert-results-previous-test)
2038 ;; Stuff that is in the menu.
2039 ("R" ert-results-rerun-all-tests)
2040 ("r" ert-results-rerun-test-at-point)
2041 ("d" ert-results-rerun-test-at-point-debugging-errors)
2042 ("." ert-results-find-test-at-point-other-window)
2043 ("b" ert-results-pop-to-backtrace-for-test-at-point)
2044 ("m" ert-results-pop-to-messages-for-test-at-point)
2045 ("l" ert-results-pop-to-should-forms-for-test-at-point)
2046 ("h" ert-results-describe-test-at-point)
2047 ("D" ert-delete-test)
2048 ("T" ert-results-pop-to-timings)
2051 (define-key ert-results-mode-map key binding))
2053 (easy-menu-define ert-results-mode-menu ert-results-mode-map
2054 "Menu for `ert-results-mode'."
2056 ["Re-run all tests" ert-results-rerun-all-tests]
2058 ["Re-run test" ert-results-rerun-test-at-point]
2059 ["Debug test" ert-results-rerun-test-at-point-debugging-errors]
2060 ["Show test definition" ert-results-find-test-at-point-other-window]
2062 ["Show backtrace" ert-results-pop-to-backtrace-for-test-at-point]
2063 ["Show messages" ert-results-pop-to-messages-for-test-at-point]
2064 ["Show `should' forms" ert-results-pop-to-should-forms-for-test-at-point]
2065 ["Describe test" ert-results-describe-test-at-point]
2067 ["Delete test" ert-delete-test]
2069 ["Show execution time of each test" ert-results-pop-to-timings]
2072 (define-button-type 'ert--results-progress-bar-button
2073 'action #'ert--results-progress-bar-button-action
2074 'help-echo "mouse-2, RET: Reveal test result")
2076 (define-button-type 'ert--test-name-button
2077 'action #'ert--test-name-button-action
2078 'help-echo "mouse-2, RET: Find test definition")
2080 (define-button-type 'ert--results-expand-collapse-button
2081 'action #'ert--results-expand-collapse-button-action
2082 'help-echo "mouse-2, RET: Expand/collapse test result")
2084 (defun ert--results-test-node-or-null-at-point ()
2085 "If point is on a valid ewoc node, return it; return nil otherwise.
2087 To be used in the ERT results buffer."
2088 (let* ((ewoc ert--results-ewoc)
2089 (node (ewoc-locate ewoc)))
2090 ;; `ewoc-locate' will return an arbitrary node when point is on
2091 ;; header or footer, or when all nodes are invisible. So we need
2092 ;; to validate its return value here.
2094 ;; Update: I'm seeing nil being returned in some cases now,
2095 ;; perhaps this has been changed?
2097 (>= (point) (ewoc-location node))
2098 (not (ert--ewoc-entry-hidden-p (ewoc-data node))))
2102 (defun ert--results-test-node-at-point ()
2103 "If point is on a valid ewoc node, return it; signal an error otherwise.
2105 To be used in the ERT results buffer."
2106 (or (ert--results-test-node-or-null-at-point)
2107 (error "No test at point")))
2109 (defun ert-results-next-test ()
2110 "Move point to the next test.
2112 To be used in the ERT results buffer."
2114 (ert--results-move (ewoc-locate ert--results-ewoc) 'ewoc-next
2117 (defun ert-results-previous-test ()
2118 "Move point to the previous test.
2120 To be used in the ERT results buffer."
2122 (ert--results-move (ewoc-locate ert--results-ewoc) 'ewoc-prev
2125 (defun ert--results-move (node ewoc-fn error-message)
2126 "Move point from NODE to the previous or next node.
2128 EWOC-FN specifies the direction and should be either `ewoc-prev'
2129 or `ewoc-next'. If there are no more nodes in that direction, an
2130 error is signaled with the message ERROR-MESSAGE."
2132 (setq node (funcall ewoc-fn ert--results-ewoc node))
2134 (error "%s" error-message))
2135 (unless (ert--ewoc-entry-hidden-p (ewoc-data node))
2136 (goto-char (ewoc-location node))
2139 (defun ert--results-expand-collapse-button-action (_button)
2140 "Expand or collapse the test node BUTTON belongs to."
2141 (let* ((ewoc ert--results-ewoc)
2142 (node (save-excursion
2143 (goto-char (ert--button-action-position))
2144 (ert--results-test-node-at-point)))
2145 (entry (ewoc-data node)))
2146 (setf (ert--ewoc-entry-expanded-p entry)
2147 (not (ert--ewoc-entry-expanded-p entry)))
2148 (ewoc-invalidate ewoc node)))
2150 (defun ert-results-find-test-at-point-other-window ()
2151 "Find the definition of the test at point in another window.
2153 To be used in the ERT results buffer."
2155 (let ((name (ert-test-at-point)))
2157 (error "No test at point"))
2158 (ert-find-test-other-window name)))
2160 (defun ert--test-name-button-action (button)
2161 "Find the definition of the test BUTTON belongs to, in another window."
2162 (let ((name (button-get button 'ert-test-name)))
2163 (ert-find-test-other-window name)))
2165 (defun ert--ewoc-position (ewoc node)
2166 ;; checkdoc-order: nil
2167 "Return the position of NODE in EWOC, or nil if NODE is not in EWOC."
2168 (cl-loop for i from 0
2169 for node-here = (ewoc-nth ewoc 0) then (ewoc-next ewoc node-here)
2170 do (when (eql node node-here)
2172 finally (cl-return nil)))
2174 (defun ert-results-jump-between-summary-and-result ()
2175 "Jump back and forth between the test run summary and individual test results.
2177 From an ewoc node, jumps to the character that represents the
2178 same test in the progress bar, and vice versa.
2180 To be used in the ERT results buffer."
2181 ;; Maybe this command isn't actually needed much, but if it is, it
2182 ;; seems like an indication that the UI design is not optimal. If
2183 ;; jumping back and forth between a summary at the top of the buffer
2184 ;; and the error log in the remainder of the buffer is useful, then
2185 ;; the summary apparently needs to be easily accessible from the
2186 ;; error log, and perhaps it would be better to have it in a
2187 ;; separate buffer to keep it visible.
2189 (let ((ewoc ert--results-ewoc)
2190 (progress-bar-begin ert--results-progress-bar-button-begin))
2191 (cond ((ert--results-test-node-or-null-at-point)
2192 (let* ((node (ert--results-test-node-at-point))
2193 (pos (ert--ewoc-position ewoc node)))
2194 (goto-char (+ progress-bar-begin pos))))
2195 ((and (<= progress-bar-begin (point))
2196 (< (point) (button-end (button-at progress-bar-begin))))
2197 (let* ((node (ewoc-nth ewoc (- (point) progress-bar-begin)))
2198 (entry (ewoc-data node)))
2199 (when (ert--ewoc-entry-hidden-p entry)
2200 (setf (ert--ewoc-entry-hidden-p entry) nil)
2201 (ewoc-invalidate ewoc node))
2202 (ewoc-goto-node ewoc node)))
2204 (goto-char progress-bar-begin)))))
2206 (defun ert-test-at-point ()
2207 "Return the name of the test at point as a symbol, or nil if none."
2208 (or (and (eql major-mode 'ert-results-mode)
2209 (let ((test (ert--results-test-at-point-no-redefinition)))
2210 (and test (ert-test-name test))))
2211 (let* ((thing (thing-at-point 'symbol))
2212 (sym (intern-soft thing)))
2213 (and (ert-test-boundp sym)
2216 (defun ert--results-test-at-point-no-redefinition ()
2217 "Return the test at point, or nil.
2219 To be used in the ERT results buffer."
2220 (cl-assert (eql major-mode 'ert-results-mode))
2221 (if (ert--results-test-node-or-null-at-point)
2222 (let* ((node (ert--results-test-node-at-point))
2223 (test (ert--ewoc-entry-test (ewoc-data node))))
2225 (let ((progress-bar-begin ert--results-progress-bar-button-begin))
2226 (when (and (<= progress-bar-begin (point))
2227 (< (point) (button-end (button-at progress-bar-begin))))
2228 (let* ((test-index (- (point) progress-bar-begin))
2229 (test (aref (ert--stats-tests ert--results-stats)
2233 (defun ert--results-test-at-point-allow-redefinition ()
2234 "Look up the test at point, and check whether it has been redefined.
2236 To be used in the ERT results buffer.
2238 Returns a list of two elements: the test (or nil) and a symbol
2239 specifying whether the test has been redefined.
2241 If a new test has been defined with the same name as the test at
2242 point, replaces the test at point with the new test, and returns
2243 the new test and the symbol `redefined'.
2245 If the test has been deleted, returns the old test and the symbol
2248 If the test is still current, returns the test and the symbol nil.
2250 If there is no test at point, returns a list with two nils."
2251 (let ((test (ert--results-test-at-point-no-redefinition)))
2254 ((null (ert-test-name test))
2257 (let* ((name (ert-test-name test))
2258 (new-test (and (ert-test-boundp name)
2259 (ert-get-test name))))
2260 (cond ((eql test new-test)
2265 (ert--results-update-after-test-redefinition
2266 (ert--stats-test-pos ert--results-stats test)
2268 `(,new-test redefined))))))))
2270 (defun ert--results-update-after-test-redefinition (pos new-test)
2271 "Update results buffer after the test at pos POS has been redefined.
2273 Also updates the stats object. NEW-TEST is the new test
2275 (let* ((stats ert--results-stats)
2276 (ewoc ert--results-ewoc)
2277 (node (ewoc-nth ewoc pos))
2278 (entry (ewoc-data node)))
2279 (ert--stats-set-test-and-result stats pos new-test nil)
2280 (setf (ert--ewoc-entry-test entry) new-test
2281 (aref ert--results-progress-bar-string pos) (ert-char-for-test-result
2283 (ewoc-invalidate ewoc node))
2286 (defun ert--button-action-position ()
2287 "The buffer position where the last button action was triggered."
2288 (cond ((integerp last-command-event)
2290 ((eventp last-command-event)
2291 (posn-point (event-start last-command-event)))
2292 (t (cl-assert nil))))
2294 (defun ert--results-progress-bar-button-action (_button)
2295 "Jump to details for the test represented by the character clicked in BUTTON."
2296 (goto-char (ert--button-action-position))
2297 (ert-results-jump-between-summary-and-result))
2299 (defun ert-results-rerun-all-tests ()
2300 "Re-run all tests, using the same selector.
2302 To be used in the ERT results buffer."
2304 (cl-assert (eql major-mode 'ert-results-mode))
2305 (let ((selector (ert--stats-selector ert--results-stats)))
2306 (ert-run-tests-interactively selector (buffer-name))))
2308 (defun ert-results-rerun-test-at-point ()
2309 "Re-run the test at point.
2311 To be used in the ERT results buffer."
2313 (cl-destructuring-bind (test redefinition-state)
2314 (ert--results-test-at-point-allow-redefinition)
2316 (error "No test at point"))
2317 (let* ((stats ert--results-stats)
2318 (progress-message (format "Running %stest %S"
2319 (cl-ecase redefinition-state
2321 (redefined "new definition of ")
2322 (deleted "deleted "))
2323 (ert-test-name test))))
2324 ;; Need to save and restore point manually here: When point is on
2325 ;; the first visible ewoc entry while the header is updated, point
2326 ;; moves to the top of the buffer. This is undesirable, and a
2327 ;; simple `save-excursion' doesn't prevent it.
2328 (let ((point (point)))
2332 (message "%s..." progress-message)
2333 (ert-run-or-rerun-test stats test
2334 ert--results-listener))
2335 (ert--results-update-stats-display ert--results-ewoc stats)
2338 (let ((result (ert-test-most-recent-result test)))
2339 (ert-string-for-test-result
2340 result (ert-test-result-expected-p test result)))))
2341 (goto-char point))))))
2343 (defun ert-results-rerun-test-at-point-debugging-errors ()
2344 "Re-run the test at point with `ert-debug-on-error' bound to t.
2346 To be used in the ERT results buffer."
2348 (let ((ert-debug-on-error t))
2349 (ert-results-rerun-test-at-point)))
2351 (defun ert-results-pop-to-backtrace-for-test-at-point ()
2352 "Display the backtrace for the test at point.
2354 To be used in the ERT results buffer."
2356 (let* ((test (ert--results-test-at-point-no-redefinition))
2357 (stats ert--results-stats)
2358 (pos (ert--stats-test-pos stats test))
2359 (result (aref (ert--stats-test-results stats) pos)))
2360 (cl-etypecase result
2361 (ert-test-passed (error "Test passed, no backtrace available"))
2362 (ert-test-result-with-condition
2363 (let ((backtrace (ert-test-result-with-condition-backtrace result))
2364 (buffer (get-buffer-create "*ERT Backtrace*")))
2365 (pop-to-buffer buffer)
2366 (let ((inhibit-read-only t))
2367 (buffer-disable-undo)
2369 (ert-simple-view-mode)
2370 ;; Use unibyte because `debugger-setup-buffer' also does so.
2371 (set-buffer-multibyte nil)
2372 (setq truncate-lines t)
2373 (ert--print-backtrace backtrace)
2374 (debugger-make-xrefs)
2375 (goto-char (point-min))
2376 (insert "Backtrace for test `")
2377 (ert-insert-test-name-button (ert-test-name test))
2378 (insert "':\n")))))))
2380 (defun ert-results-pop-to-messages-for-test-at-point ()
2381 "Display the part of the *Messages* buffer generated during the test at point.
2383 To be used in the ERT results buffer."
2385 (let* ((test (ert--results-test-at-point-no-redefinition))
2386 (stats ert--results-stats)
2387 (pos (ert--stats-test-pos stats test))
2388 (result (aref (ert--stats-test-results stats) pos)))
2389 (let ((buffer (get-buffer-create "*ERT Messages*")))
2390 (pop-to-buffer buffer)
2391 (let ((inhibit-read-only t))
2392 (buffer-disable-undo)
2394 (ert-simple-view-mode)
2395 (insert (ert-test-result-messages result))
2396 (goto-char (point-min))
2397 (insert "Messages for test `")
2398 (ert-insert-test-name-button (ert-test-name test))
2401 (defun ert-results-pop-to-should-forms-for-test-at-point ()
2402 "Display the list of `should' forms executed during the test at point.
2404 To be used in the ERT results buffer."
2406 (let* ((test (ert--results-test-at-point-no-redefinition))
2407 (stats ert--results-stats)
2408 (pos (ert--stats-test-pos stats test))
2409 (result (aref (ert--stats-test-results stats) pos)))
2410 (let ((buffer (get-buffer-create "*ERT list of should forms*")))
2411 (pop-to-buffer buffer)
2412 (let ((inhibit-read-only t))
2413 (buffer-disable-undo)
2415 (ert-simple-view-mode)
2416 (if (null (ert-test-result-should-forms result))
2417 (insert "\n(No should forms during this test.)\n")
2418 (cl-loop for form-description
2419 in (ert-test-result-should-forms result)
2422 (insert (format "%s: " i))
2423 (let ((begin (point)))
2424 (ert--pp-with-indentation-and-newline form-description)
2425 (ert--make-xrefs-region begin (point)))))
2426 (goto-char (point-min))
2427 (insert "`should' forms executed during test `")
2428 (ert-insert-test-name-button (ert-test-name test))
2431 (insert (concat "(Values are shallow copies and may have "
2432 "looked different during the test if they\n"
2433 "have been modified destructively.)\n"))
2434 (forward-line 1)))))
2436 (defun ert-results-toggle-printer-limits-for-test-at-point ()
2437 "Toggle how much of the condition to print for the test at point.
2439 To be used in the ERT results buffer."
2441 (let* ((ewoc ert--results-ewoc)
2442 (node (ert--results-test-node-at-point))
2443 (entry (ewoc-data node)))
2444 (setf (ert--ewoc-entry-extended-printer-limits-p entry)
2445 (not (ert--ewoc-entry-extended-printer-limits-p entry)))
2446 (ewoc-invalidate ewoc node)))
2448 (defun ert-results-pop-to-timings ()
2449 "Display test timings for the last run.
2451 To be used in the ERT results buffer."
2453 (let* ((stats ert--results-stats)
2454 (buffer (get-buffer-create "*ERT timings*"))
2455 (data (cl-loop for test across (ert--stats-tests stats)
2456 for start-time across (ert--stats-test-start-times
2458 for end-time across (ert--stats-test-end-times stats)
2460 (float-time (subtract-time
2461 end-time start-time))))))
2462 (setq data (sort data (lambda (a b)
2463 (> (cl-second a) (cl-second b)))))
2464 (pop-to-buffer buffer)
2465 (let ((inhibit-read-only t))
2466 (buffer-disable-undo)
2468 (ert-simple-view-mode)
2470 (insert "(No data)\n")
2471 (insert (format "%-3s %8s %8s\n" "" "time" "cumul"))
2472 (cl-loop for (test time) in data
2473 for cumul-time = time then (+ cumul-time time)
2476 (insert (format "%3s: %8.3f %8.3f " i time cumul-time))
2477 (ert-insert-test-name-button (ert-test-name test))
2479 (goto-char (point-min))
2480 (insert "Tests by run time (seconds):\n\n")
2484 (defun ert-describe-test (test-or-test-name)
2485 "Display the documentation for TEST-OR-TEST-NAME (a symbol or ert-test)."
2486 (interactive (list (ert-read-test-name-at-point "Describe test")))
2487 (when (< emacs-major-version 24)
2488 (error "Requires Emacs 24"))
2491 (cl-etypecase test-or-test-name
2492 (symbol (setq test-name test-or-test-name
2493 test-definition (ert-get-test test-or-test-name)))
2494 (ert-test (setq test-name (ert-test-name test-or-test-name)
2495 test-definition test-or-test-name)))
2496 (help-setup-xref (list #'ert-describe-test test-or-test-name)
2497 (called-interactively-p 'interactive))
2499 (with-help-window (help-buffer)
2500 (with-current-buffer (help-buffer)
2501 (insert (if test-name (format "%S" test-name) "<anonymous test>"))
2502 (insert " is a test")
2503 (let ((file-name (and test-name
2504 (symbol-file test-name 'ert-deftest))))
2506 (insert " defined in `" (file-name-nondirectory file-name) "'")
2508 (re-search-backward "`\\([^`']+\\)'" nil t)
2509 (help-xref-button 1 'help-function-def test-name file-name)))
2511 (fill-region-as-paragraph (point-min) (point))
2513 (unless (and (ert-test-boundp test-name)
2514 (eql (ert-get-test test-name) test-definition))
2515 (let ((begin (point)))
2516 (insert "Note: This test has been redefined or deleted, "
2517 "this documentation refers to an old definition.")
2518 (fill-region-as-paragraph begin (point)))
2520 (insert (or (ert-test-documentation test-definition)
2521 "It is not documented.")
2524 (defun ert-results-describe-test-at-point ()
2525 "Display the documentation of the test at point.
2527 To be used in the ERT results buffer."
2529 (ert-describe-test (ert--results-test-at-point-no-redefinition)))
2532 ;;; Actions on load/unload.
2534 (add-to-list 'find-function-regexp-alist '(ert-deftest . ert--find-test-regexp))
2535 (add-to-list 'minor-mode-alist '(ert--current-run-stats
2537 (ert--tests-running-mode-line-indicator))))
2538 (add-to-list 'emacs-lisp-mode-hook 'ert--activate-font-lock-keywords)
2540 (defun ert--unload-function ()
2541 "Unload function to undo the side-effects of loading ert.el."
2542 (ert--remove-from-list 'find-function-regexp-alist 'ert-deftest :key #'car)
2543 (ert--remove-from-list 'minor-mode-alist 'ert--current-run-stats :key #'car)
2544 (ert--remove-from-list 'emacs-lisp-mode-hook
2545 'ert--activate-font-lock-keywords)
2548 (defvar ert-unload-hook '())
2549 (add-hook 'ert-unload-hook 'ert--unload-function)
2554 ;;; ert.el ends here