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.
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-equal-including-properties (a b
)
91 "Return t if A and B have similar structure and contents.
93 This is like `equal-including-properties' except that it compares
94 the property values of text properties structurally (by
95 recursing) rather than with `eq'. Perhaps this is what
96 `equal-including-properties' should do in the first place; see
97 Emacs bug 6581 at URL `http://debbugs.gnu.org/cgi/bugreport.cgi?bug=6581'."
98 ;; This implementation is inefficient. Rather than making it
99 ;; efficient, let's hope bug 6581 gets fixed so that we can delete
101 (not (ert--explain-equal-including-properties a b
)))
104 ;;; Defining and locating tests.
106 ;; The data structure that represents a test case.
107 (cl-defstruct ert-test
110 (body (cl-assert nil
))
111 (most-recent-result nil
)
112 (expected-result-type ':passed
)
115 (defun ert-test-boundp (symbol)
116 "Return non-nil if SYMBOL names a test."
117 (and (get symbol
'ert--test
) t
))
119 (defun ert-get-test (symbol)
120 "If SYMBOL names a test, return that. Signal an error otherwise."
121 (unless (ert-test-boundp symbol
) (error "No test named `%S'" symbol
))
122 (get symbol
'ert--test
))
124 (defun ert-set-test (symbol definition
)
125 "Make SYMBOL name the test DEFINITION, and return DEFINITION."
126 (when (eq symbol
'nil
)
127 ;; We disallow nil since `ert-test-at-point' and related functions
128 ;; want to return a test name, but also need an out-of-band value
129 ;; on failure. Nil is the most natural out-of-band value; using 0
130 ;; or "" or signaling an error would be too awkward.
132 ;; Note that nil is still a valid value for the `name' slot in
133 ;; ert-test objects. It designates an anonymous test.
134 (error "Attempt to define a test named nil"))
135 (put symbol
'ert--test definition
)
138 (defun ert-make-test-unbound (symbol)
139 "Make SYMBOL name no test. Return SYMBOL."
140 (cl-remprop symbol
'ert--test
)
143 (defun ert--parse-keys-and-body (keys-and-body)
144 "Split KEYS-AND-BODY into keyword-and-value pairs and the remaining body.
146 KEYS-AND-BODY should have the form of a property list, with the
147 exception that only keywords are permitted as keys and that the
148 tail -- the body -- is a list of forms that does not start with a
151 Returns a two-element list containing the keys-and-values plist
153 (let ((extracted-key-accu '())
154 (remaining keys-and-body
))
155 (while (keywordp (car-safe remaining
))
156 (let ((keyword (pop remaining
)))
157 (unless (consp remaining
)
158 (error "Value expected after keyword %S in %S"
159 keyword keys-and-body
))
160 (when (assoc keyword extracted-key-accu
)
161 (warn "Keyword %S appears more than once in %S" keyword
163 (push (cons keyword
(pop remaining
)) extracted-key-accu
)))
164 (setq extracted-key-accu
(nreverse extracted-key-accu
))
165 (list (cl-loop for
(key . value
) in extracted-key-accu
171 (cl-defmacro ert-deftest
(name () &body docstring-keys-and-body
)
172 "Define NAME (a symbol) as a test.
174 BODY is evaluated as a `progn' when the test is run. It should
175 signal a condition on failure or just return if the test passes.
177 `should', `should-not' and `should-error' are useful for
180 Use `ert' to run tests interactively.
182 Tests that are expected to fail can be marked as such
183 using :expected-result. See `ert-test-result-type-p' for a
184 description of valid values for RESULT-TYPE.
186 \(fn NAME () [DOCSTRING] [:expected-result RESULT-TYPE] \
187 \[:tags '(TAG...)] BODY...)"
188 (declare (debug (&define
:name test
189 name sexp
[&optional stringp
]
190 [&rest keywordp sexp
] def-body
))
193 (let ((documentation nil
)
194 (documentation-supplied-p nil
))
195 (when (stringp (car docstring-keys-and-body
))
196 (setq documentation
(pop docstring-keys-and-body
)
197 documentation-supplied-p t
))
198 (cl-destructuring-bind
199 ((&key
(expected-result nil expected-result-supplied-p
)
200 (tags nil tags-supplied-p
))
202 (ert--parse-keys-and-body docstring-keys-and-body
)
207 ,@(when documentation-supplied-p
208 `(:documentation
,documentation
))
209 ,@(when expected-result-supplied-p
210 `(:expected-result-type
,expected-result
))
211 ,@(when tags-supplied-p
213 :body
(lambda () ,@body
)))
214 ;; This hack allows `symbol-file' to associate `ert-deftest'
215 ;; forms with files, and therefore enables `find-function' to
216 ;; work with tests. However, it leads to warnings in
217 ;; `unload-feature', which doesn't know how to undefine tests
218 ;; and has no mechanism for extension.
219 (push '(ert-deftest .
,name
) current-load-list
)
222 ;; We use these `put' forms in addition to the (declare (indent)) in
223 ;; the defmacro form since the `declare' alone does not lead to
224 ;; correct indentation before the .el/.elc file is loaded.
225 ;; Autoloading these `put' forms solves this.
228 ;; TODO(ohler): Figure out what these mean and make sure they are correct.
229 (put 'ert-deftest
'lisp-indent-function
2)
230 (put 'ert-info
'lisp-indent-function
1))
232 (defvar ert--find-test-regexp
233 (concat "^\\s-*(ert-deftest"
234 find-function-space-re
236 "The regexp the `find-function' mechanisms use for finding test definitions.")
239 (put 'ert-test-failed
'error-conditions
'(error ert-test-failed
))
240 (put 'ert-test-failed
'error-message
"Test failed")
243 "Terminate the current test and mark it passed. Does not return."
244 (throw 'ert--pass nil
))
246 (defun ert-fail (data)
247 "Terminate the current test and mark it failed. Does not return.
248 DATA is displayed to the user and should state the reason of the failure."
249 (signal 'ert-test-failed
(list data
)))
252 ;;; The `should' macros.
254 (defvar ert--should-execution-observer nil
)
256 (defun ert--signal-should-execution (form-description)
257 "Tell the current `should' form observer (if any) about FORM-DESCRIPTION."
258 (when ert--should-execution-observer
259 (funcall ert--should-execution-observer form-description
)))
261 (defun ert--special-operator-p (thing)
262 "Return non-nil if THING is a symbol naming a special operator."
264 (let ((definition (indirect-function thing t
)))
265 (and (subrp definition
)
266 (eql (cdr (subr-arity definition
)) 'unevalled
)))))
268 (defun ert--expand-should-1 (whole form inner-expander
)
269 "Helper function for the `should' macro and its variants."
271 (macroexpand form
(cond
272 ((boundp 'macroexpand-all-environment
)
273 macroexpand-all-environment
)
274 ((boundp 'cl-macro-environment
)
275 cl-macro-environment
)))))
277 ((or (atom form
) (ert--special-operator-p (car form
)))
278 (let ((value (cl-gensym "value-")))
279 `(let ((,value
(cl-gensym "ert-form-evaluation-aborted-")))
280 ,(funcall inner-expander
282 `(list ',whole
:form
',form
:value
,value
)
286 (let ((fn-name (car form
))
287 (arg-forms (cdr form
)))
288 (cl-assert (or (symbolp fn-name
)
290 (eql (car fn-name
) 'lambda
)
291 (listp (cdr fn-name
)))))
292 (let ((fn (cl-gensym "fn-"))
293 (args (cl-gensym "args-"))
294 (value (cl-gensym "value-"))
295 (default-value (cl-gensym "ert-form-evaluation-aborted-")))
296 `(let ((,fn
(function ,fn-name
))
297 (,args
(list ,@arg-forms
)))
298 (let ((,value
',default-value
))
299 ,(funcall inner-expander
300 `(setq ,value
(apply ,fn
,args
))
301 `(nconc (list ',whole
)
302 (list :form
`(,,fn
,@,args
))
303 (unless (eql ,value
',default-value
)
304 (list :value
,value
))
306 (and (symbolp ',fn-name
)
307 (get ',fn-name
'ert-explainer
))))
310 (apply -explainer-
,args
)))))
314 (defun ert--expand-should (whole form inner-expander
)
315 "Helper function for the `should' macro and its variants.
317 Analyzes FORM and returns an expression that has the same
318 semantics under evaluation but records additional debugging
321 INNER-EXPANDER should be a function and is called with two
322 arguments: INNER-FORM and FORM-DESCRIPTION-FORM, where INNER-FORM
323 is an expression equivalent to FORM, and FORM-DESCRIPTION-FORM is
324 an expression that returns a description of FORM. INNER-EXPANDER
325 should return code that calls INNER-FORM and performs the checks
326 and error signaling specific to the particular variant of
327 `should'. The code that INNER-EXPANDER returns must not call
328 FORM-DESCRIPTION-FORM before it has called INNER-FORM."
329 (ert--expand-should-1
331 (lambda (inner-form form-description-form value-var
)
332 (let ((form-description (cl-gensym "form-description-")))
333 `(let (,form-description
)
334 ,(funcall inner-expander
337 (setq ,form-description
,form-description-form
)
338 (ert--signal-should-execution ,form-description
))
342 (cl-defmacro should
(form)
343 "Evaluate FORM. If it returns nil, abort the current test as failed.
345 Returns the value of FORM."
347 (ert--expand-should `(should ,form
) form
348 (lambda (inner-form form-description-form _value-var
)
350 (ert-fail ,form-description-form
)))))
352 (cl-defmacro should-not
(form)
353 "Evaluate FORM. If it returns non-nil, abort the current test as failed.
357 (ert--expand-should `(should-not ,form
) form
358 (lambda (inner-form form-description-form _value-var
)
359 `(unless (not ,inner-form
)
360 (ert-fail ,form-description-form
)))))
362 (defun ert--should-error-handle-error (form-description-fn
363 condition type exclude-subtypes
)
364 "Helper function for `should-error'.
366 Determines whether CONDITION matches TYPE and EXCLUDE-SUBTYPES,
367 and aborts the current test as failed if it doesn't."
368 (let ((signaled-conditions (get (car condition
) 'error-conditions
))
369 (handled-conditions (cl-etypecase type
371 (symbol (list type
)))))
372 (cl-assert signaled-conditions
)
373 (unless (cl-intersection signaled-conditions handled-conditions
)
375 (funcall form-description-fn
)
378 :fail-reason
(concat "the error signaled did not"
379 " have the expected type")))))
380 (when exclude-subtypes
381 (unless (member (car condition
) handled-conditions
)
383 (funcall form-description-fn
)
386 :fail-reason
(concat "the error signaled was a subtype"
387 " of the expected type"))))))))
389 ;; FIXME: The expansion will evaluate the keyword args (if any) in
390 ;; nonstandard order.
391 (cl-defmacro should-error
(form &rest keys
&key type exclude-subtypes
)
392 "Evaluate FORM and check that it signals an error.
394 The error signaled needs to match TYPE. TYPE should be a list
395 of condition names. (It can also be a non-nil symbol, which is
396 equivalent to a singleton list containing that symbol.) If
397 EXCLUDE-SUBTYPES is nil, the error matches TYPE if one of its
398 condition names is an element of TYPE. If EXCLUDE-SUBTYPES is
399 non-nil, the error matches TYPE if it is an element of TYPE.
401 If the error matches, returns (ERROR-SYMBOL . DATA) from the
402 error. If not, or if no error was signaled, abort the test as
405 (unless type
(setq type
''error
))
407 `(should-error ,form
,@keys
)
409 (lambda (inner-form form-description-form value-var
)
410 (let ((errorp (cl-gensym "errorp"))
411 (form-description-fn (cl-gensym "form-description-fn-")))
413 (,form-description-fn
(lambda () ,form-description-form
)))
414 (condition-case -condition-
416 ;; We can't use ,type here because we want to evaluate it.
419 (ert--should-error-handle-error ,form-description-fn
421 ,type
,exclude-subtypes
)
422 (setq ,value-var -condition-
)))
425 (funcall ,form-description-fn
)
427 :fail-reason
"did not signal an error")))))))))
430 ;;; Explanation of `should' failures.
432 ;; TODO(ohler): Rework explanations so that they are displayed in a
433 ;; similar way to `ert-info' messages; in particular, allow text
434 ;; buttons in explanations that give more detail or open an ediff
435 ;; buffer. Perhaps explanations should be reported through `ert-info'
436 ;; rather than as part of the condition.
438 (defun ert--proper-list-p (x)
439 "Return non-nil if X is a proper list, nil otherwise."
441 for firstp
= t then nil
442 for fast
= x then
(cddr fast
)
443 for slow
= x then
(cdr slow
) do
444 (when (null fast
) (cl-return t
))
445 (when (not (consp fast
)) (cl-return nil
))
446 (when (null (cdr fast
)) (cl-return t
))
447 (when (not (consp (cdr fast
))) (cl-return nil
))
448 (when (and (not firstp
) (eq fast slow
)) (cl-return nil
))))
450 (defun ert--explain-format-atom (x)
451 "Format the atom X for `ert--explain-equal'."
453 (character (list x
(format "#x%x" x
) (format "?%c" x
)))
454 (fixnum (list x
(format "#x%x" x
)))
457 (defun ert--explain-equal-rec (a b
)
458 "Return a programmer-readable explanation of why A and B are not `equal'.
459 Returns nil if they are."
460 (if (not (equal (type-of a
) (type-of b
)))
461 `(different-types ,a
,b
)
464 (let ((a-proper-p (ert--proper-list-p a
))
465 (b-proper-p (ert--proper-list-p b
)))
466 (if (not (eql (not a-proper-p
) (not b-proper-p
)))
467 `(one-list-proper-one-improper ,a
,b
)
469 (if (not (equal (length a
) (length b
)))
470 `(proper-lists-of-different-length ,(length a
) ,(length b
)
473 ,(cl-mismatch a b
:test
'equal
))
474 (cl-loop for i from
0
477 for xi
= (ert--explain-equal-rec ai bi
)
478 do
(when xi
(cl-return `(list-elt ,i
,xi
)))
479 finally
(cl-assert (equal a b
) t
)))
480 (let ((car-x (ert--explain-equal-rec (car a
) (car b
))))
483 (let ((cdr-x (ert--explain-equal-rec (cdr a
) (cdr b
))))
486 (cl-assert (equal a b
) t
)
488 (array (if (not (equal (length a
) (length b
)))
489 `(arrays-of-different-length ,(length a
) ,(length b
)
491 ,@(unless (char-table-p a
)
493 ,(cl-mismatch a b
:test
'equal
))))
494 (cl-loop for i from
0
497 for xi
= (ert--explain-equal-rec ai bi
)
498 do
(when xi
(cl-return `(array-elt ,i
,xi
)))
499 finally
(cl-assert (equal a b
) t
))))
500 (atom (if (not (equal a b
))
501 (if (and (symbolp a
) (symbolp b
) (string= a b
))
502 `(different-symbols-with-the-same-name ,a
,b
)
503 `(different-atoms ,(ert--explain-format-atom a
)
504 ,(ert--explain-format-atom b
)))
507 (defun ert--explain-equal (a b
)
508 "Explainer function for `equal'."
509 ;; Do a quick comparison in C to avoid running our expensive
510 ;; comparison when possible.
513 (ert--explain-equal-rec a b
)))
514 (put 'equal
'ert-explainer
'ert--explain-equal
)
516 (defun ert--significant-plist-keys (plist)
517 "Return the keys of PLIST that have non-null values, in order."
518 (cl-assert (zerop (mod (length plist
) 2)) t
)
519 (cl-loop for
(key value . rest
) on plist by
#'cddr
520 unless
(or (null value
) (memq key accu
)) collect key into accu
521 finally
(cl-return accu
)))
523 (defun ert--plist-difference-explanation (a b
)
524 "Return a programmer-readable explanation of why A and B are different plists.
526 Returns nil if they are equivalent, i.e., have the same value for
527 each key, where absent values are treated as nil. The order of
528 key/value pairs in each list does not matter."
529 (cl-assert (zerop (mod (length a
) 2)) t
)
530 (cl-assert (zerop (mod (length b
) 2)) t
)
531 ;; Normalizing the plists would be another way to do this but it
532 ;; requires a total ordering on all lisp objects (since any object
533 ;; is valid as a text property key). Perhaps defining such an
534 ;; ordering is useful in other contexts, too, but it's a lot of
535 ;; work, so let's punt on it for now.
536 (let* ((keys-a (ert--significant-plist-keys a
))
537 (keys-b (ert--significant-plist-keys b
))
538 (keys-in-a-not-in-b (cl-set-difference keys-a keys-b
:test
'eq
))
539 (keys-in-b-not-in-a (cl-set-difference keys-b keys-a
:test
'eq
)))
540 (cl-flet ((explain-with-key (key)
541 (let ((value-a (plist-get a key
))
542 (value-b (plist-get b key
)))
543 (cl-assert (not (equal value-a value-b
)) t
)
544 `(different-properties-for-key
545 ,key
,(ert--explain-equal-including-properties value-a
547 (cond (keys-in-a-not-in-b
548 (explain-with-key (car keys-in-a-not-in-b
)))
550 (explain-with-key (car keys-in-b-not-in-a
)))
552 (cl-loop for key in keys-a
553 when
(not (equal (plist-get a key
) (plist-get b key
)))
554 return
(explain-with-key key
)))))))
556 (defun ert--abbreviate-string (s len suffixp
)
557 "Shorten string S to at most LEN chars.
559 If SUFFIXP is non-nil, returns a suffix of S, otherwise a prefix."
560 (let ((n (length s
)))
564 (substring s
(- n len
)))
566 (substring s
0 len
)))))
568 ;; TODO(ohler): Once bug 6581 is fixed, rename this to
569 ;; `ert--explain-equal-including-properties-rec' and add a fast-path
570 ;; wrapper like `ert--explain-equal'.
571 (defun ert--explain-equal-including-properties (a b
)
572 "Explainer function for `ert-equal-including-properties'.
574 Returns a programmer-readable explanation of why A and B are not
575 `ert-equal-including-properties', or nil if they are."
576 (if (not (equal a b
))
577 (ert--explain-equal a b
)
578 (cl-assert (stringp a
) t
)
579 (cl-assert (stringp b
) t
)
580 (cl-assert (eql (length a
) (length b
)) t
)
581 (cl-loop for i from
0 to
(length a
)
582 for props-a
= (text-properties-at i a
)
583 for props-b
= (text-properties-at i b
)
584 for difference
= (ert--plist-difference-explanation
587 (cl-return `(char ,i
,(substring-no-properties a i
(1+ i
))
590 ,(ert--abbreviate-string
591 (substring-no-properties a
0 i
)
594 ,(ert--abbreviate-string
595 (substring-no-properties a
(1+ i
))
597 ;; TODO(ohler): Get `equal-including-properties' fixed in
598 ;; Emacs, delete `ert-equal-including-properties', and
599 ;; re-enable this assertion.
600 ;;finally (cl-assert (equal-including-properties a b) t)
602 (put 'ert-equal-including-properties
604 'ert--explain-equal-including-properties
)
607 ;;; Implementation of `ert-info'.
609 ;; TODO(ohler): The name `info' clashes with
610 ;; `ert--test-execution-info'. One or both should be renamed.
611 (defvar ert--infos
'()
612 "The stack of `ert-info' infos that currently apply.
614 Bound dynamically. This is a list of (PREFIX . MESSAGE) pairs.")
616 (cl-defmacro ert-info
((message-form &key
((:prefix prefix-form
) "Info: "))
618 "Evaluate MESSAGE-FORM and BODY, and report the message if BODY fails.
620 To be used within ERT tests. MESSAGE-FORM should evaluate to a
621 string that will be displayed together with the test result if
622 the test fails. PREFIX-FORM should evaluate to a string as well
623 and is displayed in front of the value of MESSAGE-FORM."
624 (declare (debug ((form &rest
[sexp form
]) body
))
626 `(let ((ert--infos (cons (cons ,prefix-form
,message-form
) ert--infos
)))
631 ;;; Facilities for running a single test.
633 (defvar ert-debug-on-error nil
634 "Non-nil means enter debugger when a test fails or terminates with an error.")
636 ;; The data structures that represent the result of running a test.
637 (cl-defstruct ert-test-result
641 (cl-defstruct (ert-test-passed (:include ert-test-result
)))
642 (cl-defstruct (ert-test-result-with-condition (:include ert-test-result
))
643 (condition (cl-assert nil
))
644 (backtrace (cl-assert nil
))
645 (infos (cl-assert nil
)))
646 (cl-defstruct (ert-test-quit (:include ert-test-result-with-condition
)))
647 (cl-defstruct (ert-test-failed (:include ert-test-result-with-condition
)))
648 (cl-defstruct (ert-test-aborted-with-non-local-exit
649 (:include ert-test-result
)))
652 (defun ert--record-backtrace ()
653 "Record the current backtrace (as a list) and return it."
654 ;; Since the backtrace is stored in the result object, result
655 ;; objects must only be printed with appropriate limits
656 ;; (`print-level' and `print-length') in place. For interactive
657 ;; use, the cost of ensuring this possibly outweighs the advantage
658 ;; of storing the backtrace for
659 ;; `ert-results-pop-to-backtrace-for-test-at-point' given that we
660 ;; already have `ert-results-rerun-test-debugging-errors-at-point'.
661 ;; For batch use, however, printing the backtrace may be useful.
663 ;; 6 is the number of frames our own debugger adds (when
664 ;; compiled; more when interpreted). FIXME: Need to describe a
665 ;; procedure for determining this constant.
667 for frame
= (backtrace-frame i
)
671 (defun ert--print-backtrace (backtrace)
672 "Format the backtrace BACKTRACE to the current buffer."
673 ;; This is essentially a reimplementation of Fbacktrace
674 ;; (src/eval.c), but for a saved backtrace, not the current one.
675 (let ((print-escape-newlines t
)
678 (dolist (frame backtrace
)
679 (cl-ecase (car frame
)
682 (cl-destructuring-bind (special-operator &rest arg-forms
)
685 (format " %S\n" (cons special-operator arg-forms
)))))
688 (cl-destructuring-bind (fn &rest args
) (cdr frame
)
689 (insert (format " %S(" fn
))
690 (cl-loop for firstp
= t then nil
694 (insert (format "%S" arg
)))
697 ;; A container for the state of the execution of a single test and
698 ;; environment data needed during its execution.
699 (cl-defstruct ert--test-execution-info
700 (test (cl-assert nil
))
701 (result (cl-assert nil
))
702 ;; A thunk that may be called when RESULT has been set to its final
703 ;; value and test execution should be terminated. Should not
705 (exit-continuation (cl-assert nil
))
706 ;; The binding of `debugger' outside of the execution of the test.
708 ;; The binding of `ert-debug-on-error' that is in effect for the
709 ;; execution of the current test. We store it to avoid being
710 ;; affected by any new bindings the test itself may establish. (I
711 ;; don't remember whether this feature is important.)
714 (defun ert--run-test-debugger (info args
)
715 "During a test run, `debugger' is bound to a closure that calls this function.
717 This function records failures and errors and either terminates
718 the test silently or calls the interactive debugger, as
721 INFO is the ert--test-execution-info corresponding to this test
722 run. ARGS are the arguments to `debugger'."
723 (cl-destructuring-bind (first-debugger-arg &rest more-debugger-args
)
725 (cl-ecase first-debugger-arg
726 ((lambda debug t exit nil
)
727 (apply (ert--test-execution-info-next-debugger info
) args
))
729 (let* ((condition (car more-debugger-args
))
730 (type (cl-case (car condition
)
732 (otherwise 'failed
)))
733 (backtrace (ert--record-backtrace))
734 (infos (reverse ert--infos
)))
735 (setf (ert--test-execution-info-result info
)
738 (make-ert-test-quit :condition condition
742 (make-ert-test-failed :condition condition
745 ;; Work around Emacs's heuristic (in eval.c) for detecting
746 ;; errors in the debugger.
747 (cl-incf num-nonmacro-input-events
)
748 ;; FIXME: We should probably implement more fine-grained
749 ;; control a la non-t `debug-on-error' here.
751 ((ert--test-execution-info-ert-debug-on-error info
)
752 (apply (ert--test-execution-info-next-debugger info
) args
))
754 (funcall (ert--test-execution-info-exit-continuation info
)))))))
756 (defun ert--run-test-internal (test-execution-info)
757 "Low-level function to run a test according to TEST-EXECUTION-INFO.
759 This mainly sets up debugger-related bindings."
760 (setf (ert--test-execution-info-next-debugger test-execution-info
) debugger
761 (ert--test-execution-info-ert-debug-on-error test-execution-info
)
764 ;; For now, each test gets its own temp buffer and its own
765 ;; window excursion, just to be safe. If this turns out to be
766 ;; too expensive, we can remove it.
768 (save-window-excursion
769 (let ((debugger (lambda (&rest args
)
770 (ert--run-test-debugger test-execution-info
774 ;; FIXME: Do we need to store the old binding of this
775 ;; and consider it in `ert--run-test-debugger'?
776 (debug-ignored-errors nil
)
778 (funcall (ert-test-body (ert--test-execution-info-test
779 test-execution-info
))))))
781 (setf (ert--test-execution-info-result test-execution-info
)
782 (make-ert-test-passed))
785 (defun ert--force-message-log-buffer-truncation ()
786 "Immediately truncate *Messages* buffer according to `message-log-max'.
788 This can be useful after reducing the value of `message-log-max'."
789 (with-current-buffer (get-buffer-create "*Messages*")
790 ;; This is a reimplementation of this part of message_dolog() in xdisp.c:
791 ;; if (NATNUMP (Vmessage_log_max))
793 ;; scan_newline (Z, Z_BYTE, BEG, BEG_BYTE,
794 ;; -XFASTINT (Vmessage_log_max) - 1, 0);
795 ;; del_range_both (BEG, BEG_BYTE, PT, PT_BYTE, 0);
797 (when (and (integerp message-log-max
) (>= message-log-max
0))
798 (let ((begin (point-min))
800 (goto-char (point-max))
801 (forward-line (- message-log-max
))
803 (delete-region begin end
)))))
805 (defvar ert--running-tests nil
806 "List of tests that are currently in execution.
808 This list is empty while no test is running, has one element
809 while a test is running, two elements while a test run from
810 inside a test is running, etc. The list is in order of nesting,
811 innermost test first.
813 The elements are of type `ert-test'.")
815 (defun ert-run-test (ert-test)
818 Returns the result and stores it in ERT-TEST's `most-recent-result' slot."
819 (setf (ert-test-most-recent-result ert-test
) nil
)
822 (with-current-buffer (get-buffer-create "*Messages*")
823 (point-max-marker))))
825 (let ((info (make-ert--test-execution-info
828 (make-ert-test-aborted-with-non-local-exit)
829 :exit-continuation
(lambda ()
830 (cl-return-from error nil
))))
831 (should-form-accu (list)))
833 (let ((ert--should-execution-observer
834 (lambda (form-description)
835 (push form-description should-form-accu
)))
837 (ert--running-tests (cons ert-test ert--running-tests
)))
838 (ert--run-test-internal info
))
839 (let ((result (ert--test-execution-info-result info
)))
840 (setf (ert-test-result-messages result
)
841 (with-current-buffer (get-buffer-create "*Messages*")
842 (buffer-substring begin-marker
(point-max))))
843 (ert--force-message-log-buffer-truncation)
844 (setq should-form-accu
(nreverse should-form-accu
))
845 (setf (ert-test-result-should-forms result
)
847 (setf (ert-test-most-recent-result ert-test
) result
))))
848 (set-marker begin-marker nil
))))
849 (ert-test-most-recent-result ert-test
))
851 (defun ert-running-test ()
852 "Return the top-level test currently executing."
853 (car (last ert--running-tests
)))
858 (defun ert-test-result-type-p (result result-type
)
859 "Return non-nil if RESULT matches type RESULT-TYPE.
863 nil -- Never matches.
865 :failed, :passed -- Matches corresponding results.
866 \(and TYPES...\) -- Matches if all TYPES match.
867 \(or TYPES...\) -- Matches if some TYPES match.
868 \(not TYPE\) -- Matches if TYPE does not match.
869 \(satisfies PREDICATE\) -- Matches if PREDICATE returns true when called with
871 ;; It would be easy to add `member' and `eql' types etc., but I
872 ;; haven't bothered yet.
873 (cl-etypecase result-type
876 ((member :failed
) (ert-test-failed-p result
))
877 ((member :passed
) (ert-test-passed-p result
))
879 (cl-destructuring-bind (operator &rest operands
) result-type
882 (cl-case (length operands
)
885 (and (ert-test-result-type-p result
(car operands
))
886 (ert-test-result-type-p result
`(and ,@(cdr operands
)))))))
888 (cl-case (length operands
)
891 (or (ert-test-result-type-p result
(car operands
))
892 (ert-test-result-type-p result
`(or ,@(cdr operands
)))))))
894 (cl-assert (eql (length operands
) 1))
895 (not (ert-test-result-type-p result
(car operands
))))
897 (cl-assert (eql (length operands
) 1))
898 (funcall (car operands
) result
)))))))
900 (defun ert-test-result-expected-p (test result
)
901 "Return non-nil if TEST's expected result type matches RESULT."
902 (ert-test-result-type-p result
(ert-test-expected-result-type test
)))
904 (defun ert-select-tests (selector universe
)
905 "Return a list of tests that match SELECTOR.
907 UNIVERSE specifies the set of tests to select from; it should be a list
908 of tests, or t, which refers to all tests named by symbols in `obarray'.
912 nil -- Selects the empty set.
913 t -- Selects UNIVERSE.
914 :new -- Selects all tests that have not been run yet.
915 :failed, :passed -- Select tests according to their most recent result.
916 :expected, :unexpected -- Select tests according to their most recent result.
917 a string -- A regular expression selecting all tests with matching names.
918 a test -- (i.e., an object of the ert-test data-type) Selects that test.
919 a symbol -- Selects the test that the symbol names, errors if none.
920 \(member TESTS...) -- Selects the elements of TESTS, a list of tests
921 or symbols naming tests.
922 \(eql TEST\) -- Selects TEST, a test or a symbol naming a test.
923 \(and SELECTORS...) -- Selects the tests that match all SELECTORS.
924 \(or SELECTORS...) -- Selects the tests that match any of the SELECTORS.
925 \(not SELECTOR) -- Selects all tests that do not match SELECTOR.
926 \(tag TAG) -- Selects all tests that have TAG on their tags list.
927 A tag is an arbitrary label you can apply when you define a test.
928 \(satisfies PREDICATE) -- Selects all tests that satisfy PREDICATE.
929 PREDICATE is a function that takes an ert-test object as argument,
930 and returns non-nil if it is selected.
932 Only selectors that require a superset of tests, such
933 as (satisfies ...), strings, :new, etc. make use of UNIVERSE.
934 Selectors that do not, such as (member ...), just return the
935 set implied by them without checking whether it is really
936 contained in UNIVERSE."
937 ;; This code needs to match the etypecase in
938 ;; `ert-insert-human-readable-selector'.
939 (cl-etypecase selector
941 ((member t
) (cl-etypecase universe
943 ((member t
) (ert-select-tests "" universe
))))
944 ((member :new
) (ert-select-tests
945 `(satisfies ,(lambda (test)
946 (null (ert-test-most-recent-result test
))))
948 ((member :failed
) (ert-select-tests
949 `(satisfies ,(lambda (test)
950 (ert-test-result-type-p
951 (ert-test-most-recent-result test
)
954 ((member :passed
) (ert-select-tests
955 `(satisfies ,(lambda (test)
956 (ert-test-result-type-p
957 (ert-test-most-recent-result test
)
960 ((member :expected
) (ert-select-tests
963 (ert-test-result-expected-p
965 (ert-test-most-recent-result test
))))
967 ((member :unexpected
) (ert-select-tests `(not :expected
) universe
))
969 (cl-etypecase universe
970 ((member t
) (mapcar #'ert-get-test
971 (apropos-internal selector
#'ert-test-boundp
)))
972 (list (cl-remove-if-not (lambda (test)
973 (and (ert-test-name test
)
974 (string-match selector
975 (ert-test-name test
))))
977 (ert-test (list selector
))
979 (cl-assert (ert-test-boundp selector
))
980 (list (ert-get-test selector
)))
982 (cl-destructuring-bind (operator &rest operands
) selector
985 (mapcar (lambda (purported-test)
986 (cl-etypecase purported-test
987 (symbol (cl-assert (ert-test-boundp purported-test
))
988 (ert-get-test purported-test
))
989 (ert-test purported-test
)))
992 (cl-assert (eql (length operands
) 1))
993 (ert-select-tests `(member ,@operands
) universe
))
995 ;; Do these definitions of AND, NOT and OR satisfy de
996 ;; Morgan's laws? Should they?
997 (cl-case (length operands
)
998 (0 (ert-select-tests 't universe
))
999 (t (ert-select-tests `(and ,@(cdr operands
))
1000 (ert-select-tests (car operands
)
1003 (cl-assert (eql (length operands
) 1))
1004 (let ((all-tests (ert-select-tests 't universe
)))
1005 (cl-set-difference all-tests
1006 (ert-select-tests (car operands
)
1009 (cl-case (length operands
)
1010 (0 (ert-select-tests 'nil universe
))
1011 (t (cl-union (ert-select-tests (car operands
) universe
)
1012 (ert-select-tests `(or ,@(cdr operands
))
1015 (cl-assert (eql (length operands
) 1))
1016 (let ((tag (car operands
)))
1017 (ert-select-tests `(satisfies
1019 (member tag
(ert-test-tags test
))))
1022 (cl-assert (eql (length operands
) 1))
1023 (cl-remove-if-not (car operands
)
1024 (ert-select-tests 't universe
))))))))
1026 (defun ert--insert-human-readable-selector (selector)
1027 "Insert a human-readable presentation of SELECTOR into the current buffer."
1028 ;; This is needed to avoid printing the (huge) contents of the
1029 ;; `backtrace' slot of the result objects in the
1030 ;; `most-recent-result' slots of test case objects in (eql ...) or
1031 ;; (member ...) selectors.
1032 (cl-labels ((rec (selector)
1033 ;; This code needs to match the etypecase in
1034 ;; `ert-select-tests'.
1035 (cl-etypecase selector
1037 :new
:failed
:passed
1038 :expected
:unexpected
)
1043 (if (ert-test-name selector
)
1044 (make-symbol (format "<%S>" (ert-test-name selector
)))
1045 (make-symbol "<unnamed test>")))
1047 (cl-destructuring-bind (operator &rest operands
) selector
1049 ((member eql and not or
)
1050 `(,operator
,@(mapcar #'rec operands
)))
1051 ((member tag satisfies
)
1053 (insert (format "%S" (rec selector
)))))
1056 ;;; Facilities for running a whole set of tests.
1058 ;; The data structure that contains the set of tests being executed
1059 ;; during one particular test run, their results, the state of the
1060 ;; execution, and some statistics.
1062 ;; The data about results and expected results of tests may seem
1063 ;; redundant here, since the test objects also carry such information.
1064 ;; However, the information in the test objects may be more recent, it
1065 ;; may correspond to a different test run. We need the information
1066 ;; that corresponds to this run in order to be able to update the
1067 ;; statistics correctly when a test is re-run interactively and has a
1068 ;; different result than before.
1069 (cl-defstruct ert--stats
1070 (selector (cl-assert nil
))
1071 ;; The tests, in order.
1072 (tests (cl-assert nil
) :type vector
)
1073 ;; A map of test names (or the test objects themselves for unnamed
1074 ;; tests) to indices into the `tests' vector.
1075 (test-map (cl-assert nil
) :type hash-table
)
1076 ;; The results of the tests during this run, in order.
1077 (test-results (cl-assert nil
) :type vector
)
1078 ;; The start times of the tests, in order, as reported by
1080 (test-start-times (cl-assert nil
) :type vector
)
1081 ;; The end times of the tests, in order, as reported by
1083 (test-end-times (cl-assert nil
) :type vector
)
1085 (passed-unexpected 0)
1087 (failed-unexpected 0)
1092 ;; The time at or after which the next redisplay should occur, as a
1094 (next-redisplay 0.0))
1096 (defun ert-stats-completed-expected (stats)
1097 "Return the number of tests in STATS that had expected results."
1098 (+ (ert--stats-passed-expected stats
)
1099 (ert--stats-failed-expected stats
)))
1101 (defun ert-stats-completed-unexpected (stats)
1102 "Return the number of tests in STATS that had unexpected results."
1103 (+ (ert--stats-passed-unexpected stats
)
1104 (ert--stats-failed-unexpected stats
)))
1106 (defun ert-stats-completed (stats)
1107 "Number of tests in STATS that have run so far."
1108 (+ (ert-stats-completed-expected stats
)
1109 (ert-stats-completed-unexpected stats
)))
1111 (defun ert-stats-total (stats)
1112 "Number of tests in STATS, regardless of whether they have run yet."
1113 (length (ert--stats-tests stats
)))
1115 ;; The stats object of the current run, dynamically bound. This is
1116 ;; used for the mode line progress indicator.
1117 (defvar ert--current-run-stats nil
)
1119 (defun ert--stats-test-key (test)
1120 "Return the key used for TEST in the test map of ert--stats objects.
1122 Returns the name of TEST if it has one, or TEST itself otherwise."
1123 (or (ert-test-name test
) test
))
1125 (defun ert--stats-set-test-and-result (stats pos test result
)
1126 "Change STATS by replacing the test at position POS with TEST and RESULT.
1128 Also changes the counters in STATS to match."
1129 (let* ((tests (ert--stats-tests stats
))
1130 (results (ert--stats-test-results stats
))
1131 (old-test (aref tests pos
))
1132 (map (ert--stats-test-map stats
)))
1133 (cl-flet ((update (d)
1134 (if (ert-test-result-expected-p (aref tests pos
)
1136 (cl-etypecase (aref results pos
)
1138 (cl-incf (ert--stats-passed-expected stats
) d
))
1140 (cl-incf (ert--stats-failed-expected stats
) d
))
1142 (ert-test-aborted-with-non-local-exit)
1144 (cl-etypecase (aref results pos
)
1146 (cl-incf (ert--stats-passed-unexpected stats
) d
))
1148 (cl-incf (ert--stats-failed-unexpected stats
) d
))
1150 (ert-test-aborted-with-non-local-exit)
1152 ;; Adjust counters to remove the result that is currently in stats.
1154 ;; Put new test and result into stats.
1155 (setf (aref tests pos
) test
1156 (aref results pos
) result
)
1157 (remhash (ert--stats-test-key old-test
) map
)
1158 (setf (gethash (ert--stats-test-key test
) map
) pos
)
1159 ;; Adjust counters to match new result.
1163 (defun ert--make-stats (tests selector
)
1164 "Create a new `ert--stats' object for running TESTS.
1166 SELECTOR is the selector that was used to select TESTS."
1167 (setq tests
(cl-coerce tests
'vector
))
1168 (let ((map (make-hash-table :size
(length tests
))))
1169 (cl-loop for i from
0
1170 for test across tests
1171 for key
= (ert--stats-test-key test
) do
1172 (cl-assert (not (gethash key map
)))
1173 (setf (gethash key map
) i
))
1174 (make-ert--stats :selector selector
1177 :test-results
(make-vector (length tests
) nil
)
1178 :test-start-times
(make-vector (length tests
) nil
)
1179 :test-end-times
(make-vector (length tests
) nil
))))
1181 (defun ert-run-or-rerun-test (stats test listener
)
1182 ;; checkdoc-order: nil
1183 "Run the single test TEST and record the result using STATS and LISTENER."
1184 (let ((ert--current-run-stats stats
)
1185 (pos (ert--stats-test-pos stats test
)))
1186 (ert--stats-set-test-and-result stats pos test nil
)
1187 ;; Call listener after setting/before resetting
1188 ;; (ert--stats-current-test stats); the listener might refresh the
1189 ;; mode line display, and if the value is not set yet/any more
1190 ;; during this refresh, the mode line will flicker unnecessarily.
1191 (setf (ert--stats-current-test stats
) test
)
1192 (funcall listener
'test-started stats test
)
1193 (setf (ert-test-most-recent-result test
) nil
)
1194 (setf (aref (ert--stats-test-start-times stats
) pos
) (current-time))
1197 (setf (aref (ert--stats-test-end-times stats
) pos
) (current-time))
1198 (let ((result (ert-test-most-recent-result test
)))
1199 (ert--stats-set-test-and-result stats pos test result
)
1200 (funcall listener
'test-ended stats test result
))
1201 (setf (ert--stats-current-test stats
) nil
))))
1203 (defun ert-run-tests (selector listener
)
1204 "Run the tests specified by SELECTOR, sending progress updates to LISTENER."
1205 (let* ((tests (ert-select-tests selector t
))
1206 (stats (ert--make-stats tests selector
)))
1207 (setf (ert--stats-start-time stats
) (current-time))
1208 (funcall listener
'run-started stats
)
1211 (let ((ert--current-run-stats stats
))
1212 (force-mode-line-update)
1215 (cl-loop for test in tests do
1216 (ert-run-or-rerun-test stats test listener
))
1217 (setq abortedp nil
))
1218 (setf (ert--stats-aborted-p stats
) abortedp
)
1219 (setf (ert--stats-end-time stats
) (current-time))
1220 (funcall listener
'run-ended stats abortedp
)))
1221 (force-mode-line-update))
1224 (defun ert--stats-test-pos (stats test
)
1225 ;; checkdoc-order: nil
1226 "Return the position (index) of TEST in the run represented by STATS."
1227 (gethash (ert--stats-test-key test
) (ert--stats-test-map stats
)))
1230 ;;; Formatting functions shared across UIs.
1232 (defun ert--format-time-iso8601 (time)
1233 "Format TIME in the variant of ISO 8601 used for timestamps in ERT."
1234 (format-time-string "%Y-%m-%d %T%z" time
))
1236 (defun ert-char-for-test-result (result expectedp
)
1237 "Return a character that represents the test result RESULT.
1239 EXPECTEDP specifies whether the result was expected."
1240 (let ((s (cl-etypecase result
1241 (ert-test-passed ".P")
1242 (ert-test-failed "fF")
1244 (ert-test-aborted-with-non-local-exit "aA")
1245 (ert-test-quit "qQ"))))
1246 (elt s
(if expectedp
0 1))))
1248 (defun ert-string-for-test-result (result expectedp
)
1249 "Return a string that represents the test result RESULT.
1251 EXPECTEDP specifies whether the result was expected."
1252 (let ((s (cl-etypecase result
1253 (ert-test-passed '("passed" "PASSED"))
1254 (ert-test-failed '("failed" "FAILED"))
1255 (null '("unknown" "UNKNOWN"))
1256 (ert-test-aborted-with-non-local-exit '("aborted" "ABORTED"))
1257 (ert-test-quit '("quit" "QUIT")))))
1258 (elt s
(if expectedp
0 1))))
1260 (defun ert--pp-with-indentation-and-newline (object)
1261 "Pretty-print OBJECT, indenting it to the current column of point.
1262 Ensures a final newline is inserted."
1263 (let ((begin (point)))
1264 (pp object
(current-buffer))
1265 (unless (bolp) (insert "\n"))
1270 (defun ert--insert-infos (result)
1271 "Insert `ert-info' infos from RESULT into current buffer.
1273 RESULT must be an `ert-test-result-with-condition'."
1274 (cl-check-type result ert-test-result-with-condition
)
1275 (dolist (info (ert-test-result-with-condition-infos result
))
1276 (cl-destructuring-bind (prefix . message
) info
1277 (let ((begin (point))
1278 (indentation (make-string (+ (length prefix
) 4) ?\s
))
1282 (insert message
"\n")
1283 (setq end
(copy-marker (point)))
1287 (while (< (point) end
)
1288 (insert indentation
)
1290 (when end
(set-marker end nil
)))))))
1293 ;;; Running tests in batch mode.
1295 (defvar ert-batch-backtrace-right-margin
70
1296 "The maximum line length for printing backtraces in `ert-run-tests-batch'.")
1299 (defun ert-run-tests-batch (&optional selector
)
1300 "Run the tests specified by SELECTOR, printing results to the terminal.
1302 SELECTOR works as described in `ert-select-tests', except if
1303 SELECTOR is nil, in which case all tests rather than none will be
1304 run; this makes the command line \"emacs -batch -l my-tests.el -f
1305 ert-run-tests-batch-and-exit\" useful.
1307 Returns the stats object."
1308 (unless selector
(setq selector
't
))
1311 (lambda (event-type &rest event-args
)
1312 (cl-ecase event-type
1314 (cl-destructuring-bind (stats) event-args
1315 (message "Running %s tests (%s)"
1316 (length (ert--stats-tests stats
))
1317 (ert--format-time-iso8601 (ert--stats-start-time stats
)))))
1319 (cl-destructuring-bind (stats abortedp
) event-args
1320 (let ((unexpected (ert-stats-completed-unexpected stats
))
1321 (expected-failures (ert--stats-failed-expected stats
)))
1322 (message "\n%sRan %s tests, %s results as expected%s (%s)%s\n"
1326 (ert-stats-total stats
)
1327 (ert-stats-completed-expected stats
)
1328 (if (zerop unexpected
)
1330 (format ", %s unexpected" unexpected
))
1331 (ert--format-time-iso8601 (ert--stats-end-time stats
))
1332 (if (zerop expected-failures
)
1334 (format "\n%s expected failures" expected-failures
)))
1335 (unless (zerop unexpected
)
1336 (message "%s unexpected results:" unexpected
)
1337 (cl-loop for test across
(ert--stats-tests stats
)
1338 for result
= (ert-test-most-recent-result test
) do
1339 (when (not (ert-test-result-expected-p test result
))
1341 (ert-string-for-test-result result nil
)
1342 (ert-test-name test
))))
1343 (message "%s" "")))))
1347 (cl-destructuring-bind (stats test result
) event-args
1348 (unless (ert-test-result-expected-p test result
)
1349 (cl-etypecase result
1351 (message "Test %S passed unexpectedly" (ert-test-name test
)))
1352 (ert-test-result-with-condition
1353 (message "Test %S backtrace:" (ert-test-name test
))
1355 (ert--print-backtrace (ert-test-result-with-condition-backtrace
1357 (goto-char (point-min))
1359 (let ((start (point))
1360 (end (progn (end-of-line) (point))))
1362 (+ start ert-batch-backtrace-right-margin
)))
1363 (message "%s" (buffer-substring-no-properties
1367 (ert--insert-infos result
)
1369 (let ((print-escape-newlines t
)
1372 (ert--pp-with-indentation-and-newline
1373 (ert-test-result-with-condition-condition result
)))
1374 (goto-char (1- (point-max)))
1375 (cl-assert (looking-at "\n"))
1377 (message "Test %S condition:" (ert-test-name test
))
1378 (message "%s" (buffer-string))))
1379 (ert-test-aborted-with-non-local-exit
1380 (message "Test %S aborted with non-local exit"
1381 (ert-test-name test
)))
1383 (message "Quit during %S" (ert-test-name test
)))))
1384 (let* ((max (prin1-to-string (length (ert--stats-tests stats
))))
1385 (format-string (concat "%9s %"
1386 (prin1-to-string (length max
))
1388 (message format-string
1389 (ert-string-for-test-result result
1390 (ert-test-result-expected-p
1392 (1+ (ert--stats-test-pos stats test
))
1393 (ert-test-name test
)))))))))
1396 (defun ert-run-tests-batch-and-exit (&optional selector
)
1397 "Like `ert-run-tests-batch', but exits Emacs when done.
1399 The exit status will be 0 if all test results were as expected, 1
1400 on unexpected results, or 2 if the tool detected an error outside
1401 of the tests (e.g. invalid SELECTOR or bug in the code that runs
1404 (let ((stats (ert-run-tests-batch selector
)))
1405 (kill-emacs (if (zerop (ert-stats-completed-unexpected stats
)) 0 1)))
1408 (message "Error running tests")
1413 ;;; Utility functions for load/unload actions.
1415 (defun ert--activate-font-lock-keywords ()
1416 "Activate font-lock keywords for some of ERT's symbols."
1417 (font-lock-add-keywords
1419 '(("(\\(\\<ert-deftest\\)\\>\\s *\\(\\sw+\\)?"
1420 (1 font-lock-keyword-face nil t
)
1421 (2 font-lock-function-name-face nil t
)))))
1423 (cl-defun ert--remove-from-list (list-var element
&key key test
)
1424 "Remove ELEMENT from the value of LIST-VAR if present.
1426 This can be used as an inverse of `add-to-list'."
1427 (unless key
(setq key
#'identity
))
1428 (unless test
(setq test
#'equal
))
1429 (setf (symbol-value list-var
)
1431 (symbol-value list-var
)
1436 ;;; Some basic interactive functions.
1438 (defun ert-read-test-name (prompt &optional default history
1439 add-default-to-prompt
)
1440 "Read the name of a test and return it as a symbol.
1442 Prompt with PROMPT. If DEFAULT is a valid test name, use it as a
1443 default. HISTORY is the history to use; see `completing-read'.
1444 If ADD-DEFAULT-TO-PROMPT is non-nil, PROMPT will be modified to
1445 include the default, if any.
1447 Signals an error if no test name was read."
1448 (cl-etypecase default
1449 (string (let ((symbol (intern-soft default
)))
1450 (unless (and symbol
(ert-test-boundp symbol
))
1451 (setq default nil
))))
1452 (symbol (setq default
1453 (if (ert-test-boundp default
)
1454 (symbol-name default
)
1456 (ert-test (setq default
(ert-test-name default
))))
1457 (when add-default-to-prompt
1458 (setq prompt
(if (null default
)
1459 (format "%s: " prompt
)
1460 (format "%s (default %s): " prompt default
))))
1461 (let ((input (completing-read prompt obarray
#'ert-test-boundp
1462 t nil history default nil
)))
1463 ;; completing-read returns an empty string if default was nil and
1464 ;; the user just hit enter.
1465 (let ((sym (intern-soft input
)))
1466 (if (ert-test-boundp sym
)
1468 (error "Input does not name a test")))))
1470 (defun ert-read-test-name-at-point (prompt)
1471 "Read the name of a test and return it as a symbol.
1472 As a default, use the symbol at point, or the test at point if in
1473 the ERT results buffer. Prompt with PROMPT, augmented with the
1475 (ert-read-test-name prompt
(ert-test-at-point) nil t
))
1477 (defun ert-find-test-other-window (test-name)
1478 "Find, in another window, the definition of TEST-NAME."
1479 (interactive (list (ert-read-test-name-at-point "Find test definition: ")))
1480 (find-function-do-it test-name
'ert-deftest
'switch-to-buffer-other-window
))
1482 (defun ert-delete-test (test-name)
1483 "Make the test TEST-NAME unbound.
1485 Nothing more than an interactive interface to `ert-make-test-unbound'."
1486 (interactive (list (ert-read-test-name-at-point "Delete test")))
1487 (ert-make-test-unbound test-name
))
1489 (defun ert-delete-all-tests ()
1490 "Make all symbols in `obarray' name no test."
1492 (when (called-interactively-p 'any
)
1493 (unless (y-or-n-p "Delete all tests? ")
1495 ;; We can't use `ert-select-tests' here since that gives us only
1496 ;; test objects, and going from them back to the test name symbols
1497 ;; can fail if the `ert-test' defstruct has been redefined.
1498 (mapc #'ert-make-test-unbound
(apropos-internal "" #'ert-test-boundp
))
1502 ;;; Display of test progress and results.
1504 ;; An entry in the results buffer ewoc. There is one entry per test.
1505 (cl-defstruct ert--ewoc-entry
1506 (test (cl-assert nil
))
1507 ;; If the result of this test was expected, its ewoc entry is hidden
1509 (hidden-p (cl-assert nil
))
1510 ;; An ewoc entry may be collapsed to hide details such as the error
1513 ;; I'm not sure the ability to expand and collapse entries is still
1514 ;; a useful feature.
1516 ;; By default, the ewoc entry presents the error condition with
1517 ;; certain limits on how much to print (`print-level',
1518 ;; `print-length'). The user can interactively switch to a set of
1520 (extended-printer-limits-p nil
))
1522 ;; Variables local to the results buffer.
1525 (defvar ert--results-ewoc
)
1526 ;; The stats object.
1527 (defvar ert--results-stats
)
1528 ;; A string with one character per test. Each character represents
1529 ;; the result of the corresponding test. The string is displayed near
1530 ;; the top of the buffer and serves as a progress bar.
1531 (defvar ert--results-progress-bar-string
)
1532 ;; The position where the progress bar button begins.
1533 (defvar ert--results-progress-bar-button-begin
)
1534 ;; The test result listener that updates the buffer when tests are run.
1535 (defvar ert--results-listener
)
1537 (defun ert-insert-test-name-button (test-name)
1538 "Insert a button that links to TEST-NAME."
1539 (insert-text-button (format "%S" test-name
)
1540 :type
'ert--test-name-button
1541 'ert-test-name test-name
))
1543 (defun ert--results-format-expected-unexpected (expected unexpected
)
1544 "Return a string indicating EXPECTED expected results, UNEXPECTED unexpected."
1545 (if (zerop unexpected
)
1546 (format "%s" expected
)
1547 (format "%s (%s unexpected)" (+ expected unexpected
) unexpected
)))
1549 (defun ert--results-update-ewoc-hf (ewoc stats
)
1550 "Update the header and footer of EWOC to show certain information from STATS.
1552 Also sets `ert--results-progress-bar-button-begin'."
1553 (let ((run-count (ert-stats-completed stats
))
1554 (results-buffer (current-buffer))
1555 ;; Need to save buffer-local value.
1556 (font-lock font-lock-mode
))
1561 (insert "Selector: ")
1562 (ert--insert-human-readable-selector (ert--stats-selector stats
))
1565 (format (concat "Passed: %s\n"
1568 (ert--results-format-expected-unexpected
1569 (ert--stats-passed-expected stats
)
1570 (ert--stats-passed-unexpected stats
))
1571 (ert--results-format-expected-unexpected
1572 (ert--stats-failed-expected stats
)
1573 (ert--stats-failed-unexpected stats
))
1575 (ert-stats-total stats
)))
1577 (format "Started at: %s\n"
1578 (ert--format-time-iso8601 (ert--stats-start-time stats
))))
1579 ;; FIXME: This is ugly. Need to properly define invariants of
1580 ;; the `stats' data structure.
1581 (let ((state (cond ((ert--stats-aborted-p stats
) 'aborted
)
1582 ((ert--stats-current-test stats
) 'running
)
1583 ((ert--stats-end-time stats
) 'finished
)
1589 (cond ((ert--stats-current-test stats
)
1590 (insert "Aborted during test: ")
1591 (ert-insert-test-name-button
1592 (ert-test-name (ert--stats-current-test stats
))))
1594 (insert "Aborted."))))
1596 (cl-assert (ert--stats-current-test stats
))
1597 (insert "Running test: ")
1598 (ert-insert-test-name-button (ert-test-name
1599 (ert--stats-current-test stats
))))
1601 (cl-assert (not (ert--stats-current-test stats
)))
1602 (insert "Finished.")))
1604 (if (ert--stats-end-time stats
)
1607 (if (ert--stats-aborted-p stats
)
1610 (ert--format-time-iso8601 (ert--stats-end-time stats
))))
1613 (let ((progress-bar-string (with-current-buffer results-buffer
1614 ert--results-progress-bar-string
)))
1615 (let ((progress-bar-button-begin
1616 (insert-text-button progress-bar-string
1617 :type
'ert--results-progress-bar-button
1618 'face
(or (and font-lock
1619 (ert-face-for-stats stats
))
1621 ;; The header gets copied verbatim to the results buffer,
1622 ;; and all positions remain the same, so
1623 ;; `progress-bar-button-begin' will be the right position
1624 ;; even in the results buffer.
1625 (with-current-buffer results-buffer
1626 (set (make-local-variable 'ert--results-progress-bar-button-begin
)
1627 progress-bar-button-begin
))))
1632 ;; We actually want an empty footer, but that would trigger a bug
1633 ;; in ewoc, sometimes clearing the entire buffer. (It's possible
1634 ;; that this bug has been fixed since this has been tested; we
1635 ;; should test it again.)
1639 (defvar ert-test-run-redisplay-interval-secs
.1
1640 "How many seconds ERT should wait between redisplays while running tests.
1642 While running tests, ERT shows the current progress, and this variable
1643 determines how frequently the progress display is updated.")
1645 (defun ert--results-update-stats-display (ewoc stats
)
1646 "Update EWOC and the mode line to show data from STATS."
1647 ;; TODO(ohler): investigate using `make-progress-reporter'.
1648 (ert--results-update-ewoc-hf ewoc stats
)
1649 (force-mode-line-update)
1651 (setf (ert--stats-next-redisplay stats
)
1652 (+ (float-time) ert-test-run-redisplay-interval-secs
)))
1654 (defun ert--results-update-stats-display-maybe (ewoc stats
)
1655 "Call `ert--results-update-stats-display' if not called recently.
1657 EWOC and STATS are arguments for `ert--results-update-stats-display'."
1658 (when (>= (float-time) (ert--stats-next-redisplay stats
))
1659 (ert--results-update-stats-display ewoc stats
)))
1661 (defun ert--tests-running-mode-line-indicator ()
1662 "Return a string for the mode line that shows the test run progress."
1663 (let* ((stats ert--current-run-stats
)
1664 (tests-total (ert-stats-total stats
))
1665 (tests-completed (ert-stats-completed stats
)))
1666 (if (>= tests-completed tests-total
)
1667 (format " ERT(%s/%s,finished)" tests-completed tests-total
)
1668 (format " ERT(%s/%s):%s"
1669 (1+ tests-completed
)
1671 (if (null (ert--stats-current-test stats
))
1674 (ert-test-name (ert--stats-current-test stats
))))))))
1676 (defun ert--make-xrefs-region (begin end
)
1677 "Attach cross-references to function names between BEGIN and END.
1679 BEGIN and END specify a region in the current buffer."
1682 (narrow-to-region begin end
)
1683 ;; Inhibit optimization in `debugger-make-xrefs' that would
1684 ;; sometimes insert unrelated backtrace info into our buffer.
1685 (let ((debugger-previous-backtrace nil
))
1686 (debugger-make-xrefs)))))
1688 (defun ert--string-first-line (s)
1689 "Return the first line of S, or S if it contains no newlines.
1691 The return value does not include the line terminator."
1692 (substring s
0 (cl-position ?
\n s
)))
1694 (defun ert-face-for-test-result (expectedp)
1695 "Return a face that shows whether a test result was expected or unexpected.
1697 If EXPECTEDP is nil, returns the face for unexpected results; if
1698 non-nil, returns the face for expected results.."
1699 (if expectedp
'ert-test-result-expected
'ert-test-result-unexpected
))
1701 (defun ert-face-for-stats (stats)
1702 "Return a face that represents STATS."
1703 (cond ((ert--stats-aborted-p stats
) 'nil
)
1704 ((cl-plusp (ert-stats-completed-unexpected stats
))
1705 (ert-face-for-test-result nil
))
1706 ((eql (ert-stats-completed-expected stats
) (ert-stats-total stats
))
1707 (ert-face-for-test-result t
))
1710 (defun ert--print-test-for-ewoc (entry)
1711 "The ewoc print function for ewoc test entries. ENTRY is the entry to print."
1712 (let* ((test (ert--ewoc-entry-test entry
))
1713 (stats ert--results-stats
)
1714 (result (let ((pos (ert--stats-test-pos stats test
)))
1716 (aref (ert--stats-test-results stats
) pos
)))
1717 (hiddenp (ert--ewoc-entry-hidden-p entry
))
1718 (expandedp (ert--ewoc-entry-expanded-p entry
))
1719 (extended-printer-limits-p (ert--ewoc-entry-extended-printer-limits-p
1723 (let ((expectedp (ert-test-result-expected-p test result
)))
1724 (insert-text-button (format "%c" (ert-char-for-test-result
1726 :type
'ert--results-expand-collapse-button
1727 'face
(or (and font-lock-mode
1728 (ert-face-for-test-result
1732 (ert-insert-test-name-button (ert-test-name test
))
1734 (when (and expandedp
(not (eql result
'nil
)))
1735 (when (ert-test-documentation test
)
1738 (ert--string-first-line (ert-test-documentation test
))
1739 'font-lock-face
'font-lock-doc-face
)
1741 (cl-etypecase result
1743 (if (ert-test-result-expected-p test result
)
1744 (insert " passed\n")
1745 (insert " passed unexpectedly\n"))
1747 (ert-test-result-with-condition
1748 (ert--insert-infos result
)
1749 (let ((print-escape-newlines t
)
1750 (print-level (if extended-printer-limits-p
12 6))
1751 (print-length (if extended-printer-limits-p
100 10)))
1753 (let ((begin (point)))
1754 (ert--pp-with-indentation-and-newline
1755 (ert-test-result-with-condition-condition result
))
1756 (ert--make-xrefs-region begin
(point)))))
1757 (ert-test-aborted-with-non-local-exit
1758 (insert " aborted\n"))
1760 (insert " quit\n")))
1764 (defun ert--results-font-lock-function (enabledp)
1765 "Redraw the ERT results buffer after font-lock-mode was switched on or off.
1767 ENABLEDP is true if font-lock-mode is switched on, false
1769 (ert--results-update-ewoc-hf ert--results-ewoc ert--results-stats
)
1770 (ewoc-refresh ert--results-ewoc
)
1771 (font-lock-default-function enabledp
))
1773 (defun ert--setup-results-buffer (stats listener buffer-name
)
1774 "Set up a test results buffer.
1776 STATS is the stats object; LISTENER is the results listener;
1777 BUFFER-NAME, if non-nil, is the buffer name to use."
1778 (unless buffer-name
(setq buffer-name
"*ert*"))
1779 (let ((buffer (get-buffer-create buffer-name
)))
1780 (with-current-buffer buffer
1781 (let ((inhibit-read-only t
))
1782 (buffer-disable-undo)
1785 ;; Erase buffer again in case switching out of the previous
1786 ;; mode inserted anything. (This happens e.g. when switching
1787 ;; from ert-results-mode to ert-results-mode when
1788 ;; font-lock-mode turns itself off in change-major-mode-hook.)
1790 (set (make-local-variable 'font-lock-function
)
1791 'ert--results-font-lock-function
)
1792 (let ((ewoc (ewoc-create 'ert--print-test-for-ewoc nil nil t
)))
1793 (set (make-local-variable 'ert--results-ewoc
) ewoc
)
1794 (set (make-local-variable 'ert--results-stats
) stats
)
1795 (set (make-local-variable 'ert--results-progress-bar-string
)
1796 (make-string (ert-stats-total stats
)
1797 (ert-char-for-test-result nil t
)))
1798 (set (make-local-variable 'ert--results-listener
) listener
)
1799 (cl-loop for test across
(ert--stats-tests stats
) do
1800 (ewoc-enter-last ewoc
1801 (make-ert--ewoc-entry :test test
1803 (ert--results-update-ewoc-hf ert--results-ewoc ert--results-stats
)
1804 (goto-char (1- (point-max)))
1808 (defvar ert--selector-history nil
1809 "List of recent test selectors read from terminal.")
1811 ;; Should OUTPUT-BUFFER-NAME and MESSAGE-FN really be arguments here?
1812 ;; They are needed only for our automated self-tests at the moment.
1813 ;; Or should there be some other mechanism?
1815 (defun ert-run-tests-interactively (selector
1816 &optional output-buffer-name message-fn
)
1817 "Run the tests specified by SELECTOR and display the results in a buffer.
1819 SELECTOR works as described in `ert-select-tests'.
1820 OUTPUT-BUFFER-NAME and MESSAGE-FN should normally be nil; they
1821 are used for automated self-tests and specify which buffer to use
1822 and how to display message."
1824 (list (let ((default (if ert--selector-history
1825 ;; Can't use `first' here as this form is
1826 ;; not compiled, and `first' is not
1827 ;; defined without cl.
1828 (car ert--selector-history
)
1830 (read-from-minibuffer (if (null default
)
1832 (format "Run tests (default %s): " default
))
1833 nil nil t
'ert--selector-history
1836 (unless message-fn
(setq message-fn
'message
))
1837 (let ((output-buffer-name output-buffer-name
)
1840 (message-fn message-fn
))
1842 (lambda (event-type &rest event-args
)
1843 (cl-ecase event-type
1845 (cl-destructuring-bind (stats) event-args
1846 (setq buffer
(ert--setup-results-buffer stats
1848 output-buffer-name
))
1849 (pop-to-buffer buffer
)))
1851 (cl-destructuring-bind (stats abortedp
) event-args
1853 "%sRan %s tests, %s results were as expected%s"
1857 (ert-stats-total stats
)
1858 (ert-stats-completed-expected stats
)
1860 (ert-stats-completed-unexpected stats
)))
1861 (if (zerop unexpected
)
1863 (format ", %s unexpected" unexpected
))))
1864 (ert--results-update-stats-display (with-current-buffer buffer
1868 (cl-destructuring-bind (stats test
) event-args
1869 (with-current-buffer buffer
1870 (let* ((ewoc ert--results-ewoc
)
1871 (pos (ert--stats-test-pos stats test
))
1872 (node (ewoc-nth ewoc pos
)))
1874 (setf (ert--ewoc-entry-test (ewoc-data node
)) test
)
1875 (aset ert--results-progress-bar-string pos
1876 (ert-char-for-test-result nil t
))
1877 (ert--results-update-stats-display-maybe ewoc stats
)
1878 (ewoc-invalidate ewoc node
)))))
1880 (cl-destructuring-bind (stats test result
) event-args
1881 (with-current-buffer buffer
1882 (let* ((ewoc ert--results-ewoc
)
1883 (pos (ert--stats-test-pos stats test
))
1884 (node (ewoc-nth ewoc pos
)))
1885 (when (ert--ewoc-entry-hidden-p (ewoc-data node
))
1886 (setf (ert--ewoc-entry-hidden-p (ewoc-data node
))
1887 (ert-test-result-expected-p test result
)))
1888 (aset ert--results-progress-bar-string pos
1889 (ert-char-for-test-result result
1890 (ert-test-result-expected-p
1892 (ert--results-update-stats-display-maybe ewoc stats
)
1893 (ewoc-invalidate ewoc node
))))))))
1898 (defalias 'ert
'ert-run-tests-interactively
)
1901 ;;; Simple view mode for auxiliary information like stack traces or
1902 ;;; messages. Mainly binds "q" for quit.
1904 (define-derived-mode ert-simple-view-mode special-mode
"ERT-View"
1905 "Major mode for viewing auxiliary information in ERT.")
1907 ;;; Commands and button actions for the results buffer.
1909 (define-derived-mode ert-results-mode special-mode
"ERT-Results"
1910 "Major mode for viewing results of ERT test runs.")
1912 (cl-loop for
(key binding
) in
1913 '( ;; Stuff that's not in the menu.
1914 ("\t" forward-button
)
1915 ([backtab] backward-button)
1916 ("j" ert-results-jump-between-summary-and-result)
1917 ("L" ert-results-toggle-printer-limits-for-test-at-point)
1918 ("n" ert-results-next-test)
1919 ("p" ert-results-previous-test)
1920 ;; Stuff that is in the menu.
1921 ("R" ert-results-rerun-all-tests)
1922 ("r" ert-results-rerun-test-at-point)
1923 ("d" ert-results-rerun-test-at-point-debugging-errors)
1924 ("." ert-results-find-test-at-point-other-window)
1925 ("b" ert-results-pop-to-backtrace-for-test-at-point)
1926 ("m" ert-results-pop-to-messages-for-test-at-point)
1927 ("l" ert-results-pop-to-should-forms-for-test-at-point)
1928 ("h" ert-results-describe-test-at-point)
1929 ("D" ert-delete-test)
1930 ("T" ert-results-pop-to-timings)
1933 (define-key ert-results-mode-map key binding))
1935 (easy-menu-define ert-results-mode-menu ert-results-mode-map
1936 "Menu for `ert-results-mode'."
1938 ["Re-run all tests" ert-results-rerun-all-tests]
1940 ["Re-run test" ert-results-rerun-test-at-point]
1941 ["Debug test" ert-results-rerun-test-at-point-debugging-errors]
1942 ["Show test definition" ert-results-find-test-at-point-other-window]
1944 ["Show backtrace" ert-results-pop-to-backtrace-for-test-at-point]
1945 ["Show messages" ert-results-pop-to-messages-for-test-at-point]
1946 ["Show `should' forms" ert-results-pop-to-should-forms-for-test-at-point]
1947 ["Describe test" ert-results-describe-test-at-point]
1949 ["Delete test" ert-delete-test]
1951 ["Show execution time of each test" ert-results-pop-to-timings]
1954 (define-button-type 'ert--results-progress-bar-button
1955 'action #'ert--results-progress-bar-button-action
1956 'help-echo "mouse-2, RET: Reveal test result")
1958 (define-button-type 'ert--test-name-button
1959 'action #'ert--test-name-button-action
1960 'help-echo "mouse-2, RET: Find test definition")
1962 (define-button-type 'ert--results-expand-collapse-button
1963 'action #'ert--results-expand-collapse-button-action
1964 'help-echo "mouse-2, RET: Expand/collapse test result")
1966 (defun ert--results-test-node-or-null-at-point ()
1967 "If point is on a valid ewoc node, return it; return nil otherwise.
1969 To be used in the ERT results buffer."
1970 (let* ((ewoc ert--results-ewoc)
1971 (node (ewoc-locate ewoc)))
1972 ;; `ewoc-locate' will return an arbitrary node when point is on
1973 ;; header or footer, or when all nodes are invisible. So we need
1974 ;; to validate its return value here.
1976 ;; Update: I'm seeing nil being returned in some cases now,
1977 ;; perhaps this has been changed?
1979 (>= (point) (ewoc-location node))
1980 (not (ert--ewoc-entry-hidden-p (ewoc-data node))))
1984 (defun ert--results-test-node-at-point ()
1985 "If point is on a valid ewoc node, return it; signal an error otherwise.
1987 To be used in the ERT results buffer."
1988 (or (ert--results-test-node-or-null-at-point)
1989 (error "No test at point")))
1991 (defun ert-results-next-test ()
1992 "Move point to the next test.
1994 To be used in the ERT results buffer."
1996 (ert--results-move (ewoc-locate ert--results-ewoc) 'ewoc-next
1999 (defun ert-results-previous-test ()
2000 "Move point to the previous test.
2002 To be used in the ERT results buffer."
2004 (ert--results-move (ewoc-locate ert--results-ewoc) 'ewoc-prev
2007 (defun ert--results-move (node ewoc-fn error-message)
2008 "Move point from NODE to the previous or next node.
2010 EWOC-FN specifies the direction and should be either `ewoc-prev'
2011 or `ewoc-next'. If there are no more nodes in that direction, an
2012 error is signaled with the message ERROR-MESSAGE."
2014 (setq node (funcall ewoc-fn ert--results-ewoc node))
2016 (error "%s" error-message))
2017 (unless (ert--ewoc-entry-hidden-p (ewoc-data node))
2018 (goto-char (ewoc-location node))
2021 (defun ert--results-expand-collapse-button-action (_button)
2022 "Expand or collapse the test node BUTTON belongs to."
2023 (let* ((ewoc ert--results-ewoc)
2024 (node (save-excursion
2025 (goto-char (ert--button-action-position))
2026 (ert--results-test-node-at-point)))
2027 (entry (ewoc-data node)))
2028 (setf (ert--ewoc-entry-expanded-p entry)
2029 (not (ert--ewoc-entry-expanded-p entry)))
2030 (ewoc-invalidate ewoc node)))
2032 (defun ert-results-find-test-at-point-other-window ()
2033 "Find the definition of the test at point in another window.
2035 To be used in the ERT results buffer."
2037 (let ((name (ert-test-at-point)))
2039 (error "No test at point"))
2040 (ert-find-test-other-window name)))
2042 (defun ert--test-name-button-action (button)
2043 "Find the definition of the test BUTTON belongs to, in another window."
2044 (let ((name (button-get button 'ert-test-name)))
2045 (ert-find-test-other-window name)))
2047 (defun ert--ewoc-position (ewoc node)
2048 ;; checkdoc-order: nil
2049 "Return the position of NODE in EWOC, or nil if NODE is not in EWOC."
2050 (cl-loop for i from 0
2051 for node-here = (ewoc-nth ewoc 0) then (ewoc-next ewoc node-here)
2052 do (when (eql node node-here)
2054 finally (cl-return nil)))
2056 (defun ert-results-jump-between-summary-and-result ()
2057 "Jump back and forth between the test run summary and individual test results.
2059 From an ewoc node, jumps to the character that represents the
2060 same test in the progress bar, and vice versa.
2062 To be used in the ERT results buffer."
2063 ;; Maybe this command isn't actually needed much, but if it is, it
2064 ;; seems like an indication that the UI design is not optimal. If
2065 ;; jumping back and forth between a summary at the top of the buffer
2066 ;; and the error log in the remainder of the buffer is useful, then
2067 ;; the summary apparently needs to be easily accessible from the
2068 ;; error log, and perhaps it would be better to have it in a
2069 ;; separate buffer to keep it visible.
2071 (let ((ewoc ert--results-ewoc)
2072 (progress-bar-begin ert--results-progress-bar-button-begin))
2073 (cond ((ert--results-test-node-or-null-at-point)
2074 (let* ((node (ert--results-test-node-at-point))
2075 (pos (ert--ewoc-position ewoc node)))
2076 (goto-char (+ progress-bar-begin pos))))
2077 ((and (<= progress-bar-begin (point))
2078 (< (point) (button-end (button-at progress-bar-begin))))
2079 (let* ((node (ewoc-nth ewoc (- (point) progress-bar-begin)))
2080 (entry (ewoc-data node)))
2081 (when (ert--ewoc-entry-hidden-p entry)
2082 (setf (ert--ewoc-entry-hidden-p entry) nil)
2083 (ewoc-invalidate ewoc node))
2084 (ewoc-goto-node ewoc node)))
2086 (goto-char progress-bar-begin)))))
2088 (defun ert-test-at-point ()
2089 "Return the name of the test at point as a symbol, or nil if none."
2090 (or (and (eql major-mode 'ert-results-mode)
2091 (let ((test (ert--results-test-at-point-no-redefinition)))
2092 (and test (ert-test-name test))))
2093 (let* ((thing (thing-at-point 'symbol))
2094 (sym (intern-soft thing)))
2095 (and (ert-test-boundp sym)
2098 (defun ert--results-test-at-point-no-redefinition ()
2099 "Return the test at point, or nil.
2101 To be used in the ERT results buffer."
2102 (cl-assert (eql major-mode 'ert-results-mode))
2103 (if (ert--results-test-node-or-null-at-point)
2104 (let* ((node (ert--results-test-node-at-point))
2105 (test (ert--ewoc-entry-test (ewoc-data node))))
2107 (let ((progress-bar-begin ert--results-progress-bar-button-begin))
2108 (when (and (<= progress-bar-begin (point))
2109 (< (point) (button-end (button-at progress-bar-begin))))
2110 (let* ((test-index (- (point) progress-bar-begin))
2111 (test (aref (ert--stats-tests ert--results-stats)
2115 (defun ert--results-test-at-point-allow-redefinition ()
2116 "Look up the test at point, and check whether it has been redefined.
2118 To be used in the ERT results buffer.
2120 Returns a list of two elements: the test (or nil) and a symbol
2121 specifying whether the test has been redefined.
2123 If a new test has been defined with the same name as the test at
2124 point, replaces the test at point with the new test, and returns
2125 the new test and the symbol `redefined'.
2127 If the test has been deleted, returns the old test and the symbol
2130 If the test is still current, returns the test and the symbol nil.
2132 If there is no test at point, returns a list with two nils."
2133 (let ((test (ert--results-test-at-point-no-redefinition)))
2136 ((null (ert-test-name test))
2139 (let* ((name (ert-test-name test))
2140 (new-test (and (ert-test-boundp name)
2141 (ert-get-test name))))
2142 (cond ((eql test new-test)
2147 (ert--results-update-after-test-redefinition
2148 (ert--stats-test-pos ert--results-stats test)
2150 `(,new-test redefined))))))))
2152 (defun ert--results-update-after-test-redefinition (pos new-test)
2153 "Update results buffer after the test at pos POS has been redefined.
2155 Also updates the stats object. NEW-TEST is the new test
2157 (let* ((stats ert--results-stats)
2158 (ewoc ert--results-ewoc)
2159 (node (ewoc-nth ewoc pos))
2160 (entry (ewoc-data node)))
2161 (ert--stats-set-test-and-result stats pos new-test nil)
2162 (setf (ert--ewoc-entry-test entry) new-test
2163 (aref ert--results-progress-bar-string pos) (ert-char-for-test-result
2165 (ewoc-invalidate ewoc node))
2168 (defun ert--button-action-position ()
2169 "The buffer position where the last button action was triggered."
2170 (cond ((integerp last-command-event)
2172 ((eventp last-command-event)
2173 (posn-point (event-start last-command-event)))
2174 (t (cl-assert nil))))
2176 (defun ert--results-progress-bar-button-action (_button)
2177 "Jump to details for the test represented by the character clicked in BUTTON."
2178 (goto-char (ert--button-action-position))
2179 (ert-results-jump-between-summary-and-result))
2181 (defun ert-results-rerun-all-tests ()
2182 "Re-run all tests, using the same selector.
2184 To be used in the ERT results buffer."
2186 (cl-assert (eql major-mode 'ert-results-mode))
2187 (let ((selector (ert--stats-selector ert--results-stats)))
2188 (ert-run-tests-interactively selector (buffer-name))))
2190 (defun ert-results-rerun-test-at-point ()
2191 "Re-run the test at point.
2193 To be used in the ERT results buffer."
2195 (cl-destructuring-bind (test redefinition-state)
2196 (ert--results-test-at-point-allow-redefinition)
2198 (error "No test at point"))
2199 (let* ((stats ert--results-stats)
2200 (progress-message (format "Running %stest %S"
2201 (cl-ecase redefinition-state
2203 (redefined "new definition of ")
2204 (deleted "deleted "))
2205 (ert-test-name test))))
2206 ;; Need to save and restore point manually here: When point is on
2207 ;; the first visible ewoc entry while the header is updated, point
2208 ;; moves to the top of the buffer. This is undesirable, and a
2209 ;; simple `save-excursion' doesn't prevent it.
2210 (let ((point (point)))
2214 (message "%s..." progress-message)
2215 (ert-run-or-rerun-test stats test
2216 ert--results-listener))
2217 (ert--results-update-stats-display ert--results-ewoc stats)
2220 (let ((result (ert-test-most-recent-result test)))
2221 (ert-string-for-test-result
2222 result (ert-test-result-expected-p test result)))))
2223 (goto-char point))))))
2225 (defun ert-results-rerun-test-at-point-debugging-errors ()
2226 "Re-run the test at point with `ert-debug-on-error' bound to t.
2228 To be used in the ERT results buffer."
2230 (let ((ert-debug-on-error t))
2231 (ert-results-rerun-test-at-point)))
2233 (defun ert-results-pop-to-backtrace-for-test-at-point ()
2234 "Display the backtrace for the test at point.
2236 To be used in the ERT results buffer."
2238 (let* ((test (ert--results-test-at-point-no-redefinition))
2239 (stats ert--results-stats)
2240 (pos (ert--stats-test-pos stats test))
2241 (result (aref (ert--stats-test-results stats) pos)))
2242 (cl-etypecase result
2243 (ert-test-passed (error "Test passed, no backtrace available"))
2244 (ert-test-result-with-condition
2245 (let ((backtrace (ert-test-result-with-condition-backtrace result))
2246 (buffer (get-buffer-create "*ERT Backtrace*")))
2247 (pop-to-buffer buffer)
2248 (let ((inhibit-read-only t))
2249 (buffer-disable-undo)
2251 (ert-simple-view-mode)
2252 ;; Use unibyte because `debugger-setup-buffer' also does so.
2253 (set-buffer-multibyte nil)
2254 (setq truncate-lines t)
2255 (ert--print-backtrace backtrace)
2256 (debugger-make-xrefs)
2257 (goto-char (point-min))
2258 (insert "Backtrace for test `")
2259 (ert-insert-test-name-button (ert-test-name test))
2260 (insert "':\n")))))))
2262 (defun ert-results-pop-to-messages-for-test-at-point ()
2263 "Display the part of the *Messages* buffer generated during the test at point.
2265 To be used in the ERT results buffer."
2267 (let* ((test (ert--results-test-at-point-no-redefinition))
2268 (stats ert--results-stats)
2269 (pos (ert--stats-test-pos stats test))
2270 (result (aref (ert--stats-test-results stats) pos)))
2271 (let ((buffer (get-buffer-create "*ERT Messages*")))
2272 (pop-to-buffer buffer)
2273 (let ((inhibit-read-only t))
2274 (buffer-disable-undo)
2276 (ert-simple-view-mode)
2277 (insert (ert-test-result-messages result))
2278 (goto-char (point-min))
2279 (insert "Messages for test `")
2280 (ert-insert-test-name-button (ert-test-name test))
2283 (defun ert-results-pop-to-should-forms-for-test-at-point ()
2284 "Display the list of `should' forms executed during the test at point.
2286 To be used in the ERT results buffer."
2288 (let* ((test (ert--results-test-at-point-no-redefinition))
2289 (stats ert--results-stats)
2290 (pos (ert--stats-test-pos stats test))
2291 (result (aref (ert--stats-test-results stats) pos)))
2292 (let ((buffer (get-buffer-create "*ERT list of should forms*")))
2293 (pop-to-buffer buffer)
2294 (let ((inhibit-read-only t))
2295 (buffer-disable-undo)
2297 (ert-simple-view-mode)
2298 (if (null (ert-test-result-should-forms result))
2299 (insert "\n(No should forms during this test.)\n")
2300 (cl-loop for form-description
2301 in (ert-test-result-should-forms result)
2304 (insert (format "%s: " i))
2305 (let ((begin (point)))
2306 (ert--pp-with-indentation-and-newline form-description)
2307 (ert--make-xrefs-region begin (point)))))
2308 (goto-char (point-min))
2309 (insert "`should' forms executed during test `")
2310 (ert-insert-test-name-button (ert-test-name test))
2313 (insert (concat "(Values are shallow copies and may have "
2314 "looked different during the test if they\n"
2315 "have been modified destructively.)\n"))
2316 (forward-line 1)))))
2318 (defun ert-results-toggle-printer-limits-for-test-at-point ()
2319 "Toggle how much of the condition to print for the test at point.
2321 To be used in the ERT results buffer."
2323 (let* ((ewoc ert--results-ewoc)
2324 (node (ert--results-test-node-at-point))
2325 (entry (ewoc-data node)))
2326 (setf (ert--ewoc-entry-extended-printer-limits-p entry)
2327 (not (ert--ewoc-entry-extended-printer-limits-p entry)))
2328 (ewoc-invalidate ewoc node)))
2330 (defun ert-results-pop-to-timings ()
2331 "Display test timings for the last run.
2333 To be used in the ERT results buffer."
2335 (let* ((stats ert--results-stats)
2336 (buffer (get-buffer-create "*ERT timings*"))
2337 (data (cl-loop for test across (ert--stats-tests stats)
2338 for start-time across (ert--stats-test-start-times
2340 for end-time across (ert--stats-test-end-times stats)
2342 (float-time (subtract-time
2343 end-time start-time))))))
2344 (setq data (sort data (lambda (a b)
2345 (> (cl-second a) (cl-second b)))))
2346 (pop-to-buffer buffer)
2347 (let ((inhibit-read-only t))
2348 (buffer-disable-undo)
2350 (ert-simple-view-mode)
2352 (insert "(No data)\n")
2353 (insert (format "%-3s %8s %8s\n" "" "time" "cumul"))
2354 (cl-loop for (test time) in data
2355 for cumul-time = time then (+ cumul-time time)
2358 (insert (format "%3s: %8.3f %8.3f " i time cumul-time))
2359 (ert-insert-test-name-button (ert-test-name test))
2361 (goto-char (point-min))
2362 (insert "Tests by run time (seconds):\n\n")
2366 (defun ert-describe-test (test-or-test-name)
2367 "Display the documentation for TEST-OR-TEST-NAME (a symbol or ert-test)."
2368 (interactive (list (ert-read-test-name-at-point "Describe test")))
2369 (when (< emacs-major-version 24)
2370 (error "Requires Emacs 24"))
2373 (cl-etypecase test-or-test-name
2374 (symbol (setq test-name test-or-test-name
2375 test-definition (ert-get-test test-or-test-name)))
2376 (ert-test (setq test-name (ert-test-name test-or-test-name)
2377 test-definition test-or-test-name)))
2378 (help-setup-xref (list #'ert-describe-test test-or-test-name)
2379 (called-interactively-p 'interactive))
2381 (with-help-window (help-buffer)
2382 (with-current-buffer (help-buffer)
2383 (insert (if test-name (format "%S" test-name) "<anonymous test>"))
2384 (insert " is a test")
2385 (let ((file-name (and test-name
2386 (symbol-file test-name 'ert-deftest))))
2388 (insert " defined in `" (file-name-nondirectory file-name) "'")
2390 (re-search-backward "`\\([^`']+\\)'" nil t)
2391 (help-xref-button 1 'help-function-def test-name file-name)))
2393 (fill-region-as-paragraph (point-min) (point))
2395 (unless (and (ert-test-boundp test-name)
2396 (eql (ert-get-test test-name) test-definition))
2397 (let ((begin (point)))
2398 (insert "Note: This test has been redefined or deleted, "
2399 "this documentation refers to an old definition.")
2400 (fill-region-as-paragraph begin (point)))
2402 (insert (or (ert-test-documentation test-definition)
2403 "It is not documented.")
2406 (defun ert-results-describe-test-at-point ()
2407 "Display the documentation of the test at point.
2409 To be used in the ERT results buffer."
2411 (ert-describe-test (ert--results-test-at-point-no-redefinition)))
2414 ;;; Actions on load/unload.
2416 (add-to-list 'find-function-regexp-alist '(ert-deftest . ert--find-test-regexp))
2417 (add-to-list 'minor-mode-alist '(ert--current-run-stats
2419 (ert--tests-running-mode-line-indicator))))
2420 (add-to-list 'emacs-lisp-mode-hook 'ert--activate-font-lock-keywords)
2422 (defun ert--unload-function ()
2423 "Unload function to undo the side-effects of loading ert.el."
2424 (ert--remove-from-list 'find-function-regexp-alist 'ert-deftest :key #'car)
2425 (ert--remove-from-list 'minor-mode-alist 'ert--current-run-stats :key #'car)
2426 (ert--remove-from-list 'emacs-lisp-mode-hook
2427 'ert--activate-font-lock-keywords)
2430 (defvar ert-unload-hook '())
2431 (add-hook 'ert-unload-hook 'ert--unload-function)
2436 ;;; ert.el ends here