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 (define-error 'ert-test-failed
"Test failed")
242 "Terminate the current test and mark it passed. Does not return."
243 (throw 'ert--pass nil
))
245 (defun ert-fail (data)
246 "Terminate the current test and mark it failed. Does not return.
247 DATA is displayed to the user and should state the reason of the failure."
248 (signal 'ert-test-failed
(list data
)))
251 ;;; The `should' macros.
253 (defvar ert--should-execution-observer nil
)
255 (defun ert--signal-should-execution (form-description)
256 "Tell the current `should' form observer (if any) about FORM-DESCRIPTION."
257 (when ert--should-execution-observer
258 (funcall ert--should-execution-observer form-description
)))
260 (defun ert--special-operator-p (thing)
261 "Return non-nil if THING is a symbol naming a special operator."
263 (let ((definition (indirect-function thing t
)))
264 (and (subrp definition
)
265 (eql (cdr (subr-arity definition
)) 'unevalled
)))))
267 (defun ert--expand-should-1 (whole form inner-expander
)
268 "Helper function for the `should' macro and its variants."
270 (macroexpand form
(cond
271 ((boundp 'macroexpand-all-environment
)
272 macroexpand-all-environment
)
273 ((boundp 'cl-macro-environment
)
274 cl-macro-environment
)))))
276 ((or (atom form
) (ert--special-operator-p (car form
)))
277 (let ((value (cl-gensym "value-")))
278 `(let ((,value
(cl-gensym "ert-form-evaluation-aborted-")))
279 ,(funcall inner-expander
281 `(list ',whole
:form
',form
:value
,value
)
285 (let ((fn-name (car form
))
286 (arg-forms (cdr form
)))
287 (cl-assert (or (symbolp fn-name
)
289 (eql (car fn-name
) 'lambda
)
290 (listp (cdr fn-name
)))))
291 (let ((fn (cl-gensym "fn-"))
292 (args (cl-gensym "args-"))
293 (value (cl-gensym "value-"))
294 (default-value (cl-gensym "ert-form-evaluation-aborted-")))
295 `(let ((,fn
(function ,fn-name
))
296 (,args
(list ,@arg-forms
)))
297 (let ((,value
',default-value
))
298 ,(funcall inner-expander
299 `(setq ,value
(apply ,fn
,args
))
300 `(nconc (list ',whole
)
301 (list :form
`(,,fn
,@,args
))
302 (unless (eql ,value
',default-value
)
303 (list :value
,value
))
305 (and (symbolp ',fn-name
)
306 (get ',fn-name
'ert-explainer
))))
309 (apply -explainer-
,args
)))))
313 (defun ert--expand-should (whole form inner-expander
)
314 "Helper function for the `should' macro and its variants.
316 Analyzes FORM and returns an expression that has the same
317 semantics under evaluation but records additional debugging
320 INNER-EXPANDER should be a function and is called with two
321 arguments: INNER-FORM and FORM-DESCRIPTION-FORM, where INNER-FORM
322 is an expression equivalent to FORM, and FORM-DESCRIPTION-FORM is
323 an expression that returns a description of FORM. INNER-EXPANDER
324 should return code that calls INNER-FORM and performs the checks
325 and error signaling specific to the particular variant of
326 `should'. The code that INNER-EXPANDER returns must not call
327 FORM-DESCRIPTION-FORM before it has called INNER-FORM."
328 (ert--expand-should-1
330 (lambda (inner-form form-description-form value-var
)
331 (let ((form-description (cl-gensym "form-description-")))
332 `(let (,form-description
)
333 ,(funcall inner-expander
336 (setq ,form-description
,form-description-form
)
337 (ert--signal-should-execution ,form-description
))
341 (cl-defmacro should
(form)
342 "Evaluate FORM. If it returns nil, abort the current test as failed.
344 Returns the value of FORM."
346 (ert--expand-should `(should ,form
) form
347 (lambda (inner-form form-description-form _value-var
)
349 (ert-fail ,form-description-form
)))))
351 (cl-defmacro should-not
(form)
352 "Evaluate FORM. If it returns non-nil, abort the current test as failed.
356 (ert--expand-should `(should-not ,form
) form
357 (lambda (inner-form form-description-form _value-var
)
358 `(unless (not ,inner-form
)
359 (ert-fail ,form-description-form
)))))
361 (defun ert--should-error-handle-error (form-description-fn
362 condition type exclude-subtypes
)
363 "Helper function for `should-error'.
365 Determines whether CONDITION matches TYPE and EXCLUDE-SUBTYPES,
366 and aborts the current test as failed if it doesn't."
367 (let ((signaled-conditions (get (car condition
) 'error-conditions
))
368 (handled-conditions (cl-etypecase type
370 (symbol (list type
)))))
371 (cl-assert signaled-conditions
)
372 (unless (cl-intersection signaled-conditions handled-conditions
)
374 (funcall form-description-fn
)
377 :fail-reason
(concat "the error signaled did not"
378 " have the expected type")))))
379 (when exclude-subtypes
380 (unless (member (car condition
) handled-conditions
)
382 (funcall form-description-fn
)
385 :fail-reason
(concat "the error signaled was a subtype"
386 " of the expected type"))))))))
388 ;; FIXME: The expansion will evaluate the keyword args (if any) in
389 ;; nonstandard order.
390 (cl-defmacro should-error
(form &rest keys
&key type exclude-subtypes
)
391 "Evaluate FORM and check that it signals an error.
393 The error signaled needs to match TYPE. TYPE should be a list
394 of condition names. (It can also be a non-nil symbol, which is
395 equivalent to a singleton list containing that symbol.) If
396 EXCLUDE-SUBTYPES is nil, the error matches TYPE if one of its
397 condition names is an element of TYPE. If EXCLUDE-SUBTYPES is
398 non-nil, the error matches TYPE if it is an element of TYPE.
400 If the error matches, returns (ERROR-SYMBOL . DATA) from the
401 error. If not, or if no error was signaled, abort the test as
404 (unless type
(setq type
''error
))
406 `(should-error ,form
,@keys
)
408 (lambda (inner-form form-description-form value-var
)
409 (let ((errorp (cl-gensym "errorp"))
410 (form-description-fn (cl-gensym "form-description-fn-")))
412 (,form-description-fn
(lambda () ,form-description-form
)))
413 (condition-case -condition-
415 ;; We can't use ,type here because we want to evaluate it.
418 (ert--should-error-handle-error ,form-description-fn
420 ,type
,exclude-subtypes
)
421 (setq ,value-var -condition-
)))
424 (funcall ,form-description-fn
)
426 :fail-reason
"did not signal an error")))))))))
429 ;;; Explanation of `should' failures.
431 ;; TODO(ohler): Rework explanations so that they are displayed in a
432 ;; similar way to `ert-info' messages; in particular, allow text
433 ;; buttons in explanations that give more detail or open an ediff
434 ;; buffer. Perhaps explanations should be reported through `ert-info'
435 ;; rather than as part of the condition.
437 (defun ert--proper-list-p (x)
438 "Return non-nil if X is a proper list, nil otherwise."
440 for firstp
= t then nil
441 for fast
= x then
(cddr fast
)
442 for slow
= x then
(cdr slow
) do
443 (when (null fast
) (cl-return t
))
444 (when (not (consp fast
)) (cl-return nil
))
445 (when (null (cdr fast
)) (cl-return t
))
446 (when (not (consp (cdr fast
))) (cl-return nil
))
447 (when (and (not firstp
) (eq fast slow
)) (cl-return nil
))))
449 (defun ert--explain-format-atom (x)
450 "Format the atom X for `ert--explain-equal'."
452 (character (list x
(format "#x%x" x
) (format "?%c" x
)))
453 (fixnum (list x
(format "#x%x" x
)))
456 (defun ert--explain-equal-rec (a b
)
457 "Return a programmer-readable explanation of why A and B are not `equal'.
458 Returns nil if they are."
459 (if (not (equal (type-of a
) (type-of b
)))
460 `(different-types ,a
,b
)
463 (let ((a-proper-p (ert--proper-list-p a
))
464 (b-proper-p (ert--proper-list-p b
)))
465 (if (not (eql (not a-proper-p
) (not b-proper-p
)))
466 `(one-list-proper-one-improper ,a
,b
)
468 (if (not (equal (length a
) (length b
)))
469 `(proper-lists-of-different-length ,(length a
) ,(length b
)
472 ,(cl-mismatch a b
:test
'equal
))
473 (cl-loop for i from
0
476 for xi
= (ert--explain-equal-rec ai bi
)
477 do
(when xi
(cl-return `(list-elt ,i
,xi
)))
478 finally
(cl-assert (equal a b
) t
)))
479 (let ((car-x (ert--explain-equal-rec (car a
) (car b
))))
482 (let ((cdr-x (ert--explain-equal-rec (cdr a
) (cdr b
))))
485 (cl-assert (equal a b
) t
)
487 (array (if (not (equal (length a
) (length b
)))
488 `(arrays-of-different-length ,(length a
) ,(length b
)
490 ,@(unless (char-table-p a
)
492 ,(cl-mismatch a b
:test
'equal
))))
493 (cl-loop for i from
0
496 for xi
= (ert--explain-equal-rec ai bi
)
497 do
(when xi
(cl-return `(array-elt ,i
,xi
)))
498 finally
(cl-assert (equal a b
) t
))))
499 (atom (if (not (equal a b
))
500 (if (and (symbolp a
) (symbolp b
) (string= a b
))
501 `(different-symbols-with-the-same-name ,a
,b
)
502 `(different-atoms ,(ert--explain-format-atom a
)
503 ,(ert--explain-format-atom b
)))
506 (defun ert--explain-equal (a b
)
507 "Explainer function for `equal'."
508 ;; Do a quick comparison in C to avoid running our expensive
509 ;; comparison when possible.
512 (ert--explain-equal-rec a b
)))
513 (put 'equal
'ert-explainer
'ert--explain-equal
)
515 (defun ert--significant-plist-keys (plist)
516 "Return the keys of PLIST that have non-null values, in order."
517 (cl-assert (zerop (mod (length plist
) 2)) t
)
518 (cl-loop for
(key value . rest
) on plist by
#'cddr
519 unless
(or (null value
) (memq key accu
)) collect key into accu
520 finally
(cl-return accu
)))
522 (defun ert--plist-difference-explanation (a b
)
523 "Return a programmer-readable explanation of why A and B are different plists.
525 Returns nil if they are equivalent, i.e., have the same value for
526 each key, where absent values are treated as nil. The order of
527 key/value pairs in each list does not matter."
528 (cl-assert (zerop (mod (length a
) 2)) t
)
529 (cl-assert (zerop (mod (length b
) 2)) t
)
530 ;; Normalizing the plists would be another way to do this but it
531 ;; requires a total ordering on all lisp objects (since any object
532 ;; is valid as a text property key). Perhaps defining such an
533 ;; ordering is useful in other contexts, too, but it's a lot of
534 ;; work, so let's punt on it for now.
535 (let* ((keys-a (ert--significant-plist-keys a
))
536 (keys-b (ert--significant-plist-keys b
))
537 (keys-in-a-not-in-b (cl-set-difference keys-a keys-b
:test
'eq
))
538 (keys-in-b-not-in-a (cl-set-difference keys-b keys-a
:test
'eq
)))
539 (cl-flet ((explain-with-key (key)
540 (let ((value-a (plist-get a key
))
541 (value-b (plist-get b key
)))
542 (cl-assert (not (equal value-a value-b
)) t
)
543 `(different-properties-for-key
544 ,key
,(ert--explain-equal-including-properties value-a
546 (cond (keys-in-a-not-in-b
547 (explain-with-key (car keys-in-a-not-in-b
)))
549 (explain-with-key (car keys-in-b-not-in-a
)))
551 (cl-loop for key in keys-a
552 when
(not (equal (plist-get a key
) (plist-get b key
)))
553 return
(explain-with-key key
)))))))
555 (defun ert--abbreviate-string (s len suffixp
)
556 "Shorten string S to at most LEN chars.
558 If SUFFIXP is non-nil, returns a suffix of S, otherwise a prefix."
559 (let ((n (length s
)))
563 (substring s
(- n len
)))
565 (substring s
0 len
)))))
567 ;; TODO(ohler): Once bug 6581 is fixed, rename this to
568 ;; `ert--explain-equal-including-properties-rec' and add a fast-path
569 ;; wrapper like `ert--explain-equal'.
570 (defun ert--explain-equal-including-properties (a b
)
571 "Explainer function for `ert-equal-including-properties'.
573 Returns a programmer-readable explanation of why A and B are not
574 `ert-equal-including-properties', or nil if they are."
575 (if (not (equal a b
))
576 (ert--explain-equal a b
)
577 (cl-assert (stringp a
) t
)
578 (cl-assert (stringp b
) t
)
579 (cl-assert (eql (length a
) (length b
)) t
)
580 (cl-loop for i from
0 to
(length a
)
581 for props-a
= (text-properties-at i a
)
582 for props-b
= (text-properties-at i b
)
583 for difference
= (ert--plist-difference-explanation
586 (cl-return `(char ,i
,(substring-no-properties a i
(1+ i
))
589 ,(ert--abbreviate-string
590 (substring-no-properties a
0 i
)
593 ,(ert--abbreviate-string
594 (substring-no-properties a
(1+ i
))
596 ;; TODO(ohler): Get `equal-including-properties' fixed in
597 ;; Emacs, delete `ert-equal-including-properties', and
598 ;; re-enable this assertion.
599 ;;finally (cl-assert (equal-including-properties a b) t)
601 (put 'ert-equal-including-properties
603 'ert--explain-equal-including-properties
)
606 ;;; Implementation of `ert-info'.
608 ;; TODO(ohler): The name `info' clashes with
609 ;; `ert--test-execution-info'. One or both should be renamed.
610 (defvar ert--infos
'()
611 "The stack of `ert-info' infos that currently apply.
613 Bound dynamically. This is a list of (PREFIX . MESSAGE) pairs.")
615 (cl-defmacro ert-info
((message-form &key
((:prefix prefix-form
) "Info: "))
617 "Evaluate MESSAGE-FORM and BODY, and report the message if BODY fails.
619 To be used within ERT tests. MESSAGE-FORM should evaluate to a
620 string that will be displayed together with the test result if
621 the test fails. PREFIX-FORM should evaluate to a string as well
622 and is displayed in front of the value of MESSAGE-FORM."
623 (declare (debug ((form &rest
[sexp form
]) body
))
625 `(let ((ert--infos (cons (cons ,prefix-form
,message-form
) ert--infos
)))
630 ;;; Facilities for running a single test.
632 (defvar ert-debug-on-error nil
633 "Non-nil means enter debugger when a test fails or terminates with an error.")
635 ;; The data structures that represent the result of running a test.
636 (cl-defstruct ert-test-result
640 (cl-defstruct (ert-test-passed (:include ert-test-result
)))
641 (cl-defstruct (ert-test-result-with-condition (:include ert-test-result
))
642 (condition (cl-assert nil
))
643 (backtrace (cl-assert nil
))
644 (infos (cl-assert nil
)))
645 (cl-defstruct (ert-test-quit (:include ert-test-result-with-condition
)))
646 (cl-defstruct (ert-test-failed (:include ert-test-result-with-condition
)))
647 (cl-defstruct (ert-test-aborted-with-non-local-exit
648 (:include ert-test-result
)))
651 (defun ert--record-backtrace ()
652 "Record the current backtrace (as a list) and return it."
653 ;; Since the backtrace is stored in the result object, result
654 ;; objects must only be printed with appropriate limits
655 ;; (`print-level' and `print-length') in place. For interactive
656 ;; use, the cost of ensuring this possibly outweighs the advantage
657 ;; of storing the backtrace for
658 ;; `ert-results-pop-to-backtrace-for-test-at-point' given that we
659 ;; already have `ert-results-rerun-test-debugging-errors-at-point'.
660 ;; For batch use, however, printing the backtrace may be useful.
662 ;; 6 is the number of frames our own debugger adds (when
663 ;; compiled; more when interpreted). FIXME: Need to describe a
664 ;; procedure for determining this constant.
666 for frame
= (backtrace-frame i
)
670 (defun ert--print-backtrace (backtrace)
671 "Format the backtrace BACKTRACE to the current buffer."
672 ;; This is essentially a reimplementation of Fbacktrace
673 ;; (src/eval.c), but for a saved backtrace, not the current one.
674 (let ((print-escape-newlines t
)
677 (dolist (frame backtrace
)
678 (cl-ecase (car frame
)
681 (cl-destructuring-bind (special-operator &rest arg-forms
)
684 (format " %S\n" (cons special-operator arg-forms
)))))
687 (cl-destructuring-bind (fn &rest args
) (cdr frame
)
688 (insert (format " %S(" fn
))
689 (cl-loop for firstp
= t then nil
693 (insert (format "%S" arg
)))
696 ;; A container for the state of the execution of a single test and
697 ;; environment data needed during its execution.
698 (cl-defstruct ert--test-execution-info
699 (test (cl-assert nil
))
700 (result (cl-assert nil
))
701 ;; A thunk that may be called when RESULT has been set to its final
702 ;; value and test execution should be terminated. Should not
704 (exit-continuation (cl-assert nil
))
705 ;; The binding of `debugger' outside of the execution of the test.
707 ;; The binding of `ert-debug-on-error' that is in effect for the
708 ;; execution of the current test. We store it to avoid being
709 ;; affected by any new bindings the test itself may establish. (I
710 ;; don't remember whether this feature is important.)
713 (defun ert--run-test-debugger (info args
)
714 "During a test run, `debugger' is bound to a closure that calls this function.
716 This function records failures and errors and either terminates
717 the test silently or calls the interactive debugger, as
720 INFO is the ert--test-execution-info corresponding to this test
721 run. ARGS are the arguments to `debugger'."
722 (cl-destructuring-bind (first-debugger-arg &rest more-debugger-args
)
724 (cl-ecase first-debugger-arg
725 ((lambda debug t exit nil
)
726 (apply (ert--test-execution-info-next-debugger info
) args
))
728 (let* ((condition (car more-debugger-args
))
729 (type (cl-case (car condition
)
731 (otherwise 'failed
)))
732 (backtrace (ert--record-backtrace))
733 (infos (reverse ert--infos
)))
734 (setf (ert--test-execution-info-result info
)
737 (make-ert-test-quit :condition condition
741 (make-ert-test-failed :condition condition
744 ;; Work around Emacs's heuristic (in eval.c) for detecting
745 ;; errors in the debugger.
746 (cl-incf num-nonmacro-input-events
)
747 ;; FIXME: We should probably implement more fine-grained
748 ;; control a la non-t `debug-on-error' here.
750 ((ert--test-execution-info-ert-debug-on-error info
)
751 (apply (ert--test-execution-info-next-debugger info
) args
))
753 (funcall (ert--test-execution-info-exit-continuation info
)))))))
755 (defun ert--run-test-internal (test-execution-info)
756 "Low-level function to run a test according to TEST-EXECUTION-INFO.
758 This mainly sets up debugger-related bindings."
759 (setf (ert--test-execution-info-next-debugger test-execution-info
) debugger
760 (ert--test-execution-info-ert-debug-on-error test-execution-info
)
763 ;; For now, each test gets its own temp buffer and its own
764 ;; window excursion, just to be safe. If this turns out to be
765 ;; too expensive, we can remove it.
767 (save-window-excursion
768 (let ((debugger (lambda (&rest args
)
769 (ert--run-test-debugger test-execution-info
773 ;; FIXME: Do we need to store the old binding of this
774 ;; and consider it in `ert--run-test-debugger'?
775 (debug-ignored-errors nil
)
777 (funcall (ert-test-body (ert--test-execution-info-test
778 test-execution-info
))))))
780 (setf (ert--test-execution-info-result test-execution-info
)
781 (make-ert-test-passed))
784 (defun ert--force-message-log-buffer-truncation ()
785 "Immediately truncate *Messages* buffer according to `message-log-max'.
787 This can be useful after reducing the value of `message-log-max'."
788 (with-current-buffer (get-buffer-create "*Messages*")
789 ;; This is a reimplementation of this part of message_dolog() in xdisp.c:
790 ;; if (NATNUMP (Vmessage_log_max))
792 ;; scan_newline (Z, Z_BYTE, BEG, BEG_BYTE,
793 ;; -XFASTINT (Vmessage_log_max) - 1, 0);
794 ;; del_range_both (BEG, BEG_BYTE, PT, PT_BYTE, 0);
796 (when (and (integerp message-log-max
) (>= message-log-max
0))
797 (let ((begin (point-min))
799 (goto-char (point-max))
800 (forward-line (- message-log-max
))
802 (delete-region begin end
)))))
804 (defvar ert--running-tests nil
805 "List of tests that are currently in execution.
807 This list is empty while no test is running, has one element
808 while a test is running, two elements while a test run from
809 inside a test is running, etc. The list is in order of nesting,
810 innermost test first.
812 The elements are of type `ert-test'.")
814 (defun ert-run-test (ert-test)
817 Returns the result and stores it in ERT-TEST's `most-recent-result' slot."
818 (setf (ert-test-most-recent-result ert-test
) nil
)
821 (with-current-buffer (get-buffer-create "*Messages*")
822 (point-max-marker))))
824 (let ((info (make-ert--test-execution-info
827 (make-ert-test-aborted-with-non-local-exit)
828 :exit-continuation
(lambda ()
829 (cl-return-from error nil
))))
830 (should-form-accu (list)))
832 (let ((ert--should-execution-observer
833 (lambda (form-description)
834 (push form-description should-form-accu
)))
836 (ert--running-tests (cons ert-test ert--running-tests
)))
837 (ert--run-test-internal info
))
838 (let ((result (ert--test-execution-info-result info
)))
839 (setf (ert-test-result-messages result
)
840 (with-current-buffer (get-buffer-create "*Messages*")
841 (buffer-substring begin-marker
(point-max))))
842 (ert--force-message-log-buffer-truncation)
843 (setq should-form-accu
(nreverse should-form-accu
))
844 (setf (ert-test-result-should-forms result
)
846 (setf (ert-test-most-recent-result ert-test
) result
))))
847 (set-marker begin-marker nil
))))
848 (ert-test-most-recent-result ert-test
))
850 (defun ert-running-test ()
851 "Return the top-level test currently executing."
852 (car (last ert--running-tests
)))
857 (defun ert-test-result-type-p (result result-type
)
858 "Return non-nil if RESULT matches type RESULT-TYPE.
862 nil -- Never matches.
864 :failed, :passed -- Matches corresponding results.
865 \(and TYPES...\) -- Matches if all TYPES match.
866 \(or TYPES...\) -- Matches if some TYPES match.
867 \(not TYPE\) -- Matches if TYPE does not match.
868 \(satisfies PREDICATE\) -- Matches if PREDICATE returns true when called with
870 ;; It would be easy to add `member' and `eql' types etc., but I
871 ;; haven't bothered yet.
872 (cl-etypecase result-type
875 ((member :failed
) (ert-test-failed-p result
))
876 ((member :passed
) (ert-test-passed-p result
))
878 (cl-destructuring-bind (operator &rest operands
) result-type
881 (cl-case (length operands
)
884 (and (ert-test-result-type-p result
(car operands
))
885 (ert-test-result-type-p result
`(and ,@(cdr operands
)))))))
887 (cl-case (length operands
)
890 (or (ert-test-result-type-p result
(car operands
))
891 (ert-test-result-type-p result
`(or ,@(cdr operands
)))))))
893 (cl-assert (eql (length operands
) 1))
894 (not (ert-test-result-type-p result
(car operands
))))
896 (cl-assert (eql (length operands
) 1))
897 (funcall (car operands
) result
)))))))
899 (defun ert-test-result-expected-p (test result
)
900 "Return non-nil if TEST's expected result type matches RESULT."
901 (ert-test-result-type-p result
(ert-test-expected-result-type test
)))
903 (defun ert-select-tests (selector universe
)
904 "Return a list of tests that match SELECTOR.
906 UNIVERSE specifies the set of tests to select from; it should be a list
907 of tests, or t, which refers to all tests named by symbols in `obarray'.
911 nil -- Selects the empty set.
912 t -- Selects UNIVERSE.
913 :new -- Selects all tests that have not been run yet.
914 :failed, :passed -- Select tests according to their most recent result.
915 :expected, :unexpected -- Select tests according to their most recent result.
916 a string -- A regular expression selecting all tests with matching names.
917 a test -- (i.e., an object of the ert-test data-type) Selects that test.
918 a symbol -- Selects the test that the symbol names, errors if none.
919 \(member TESTS...) -- Selects the elements of TESTS, a list of tests
920 or symbols naming tests.
921 \(eql TEST\) -- Selects TEST, a test or a symbol naming a test.
922 \(and SELECTORS...) -- Selects the tests that match all SELECTORS.
923 \(or SELECTORS...) -- Selects the tests that match any of the SELECTORS.
924 \(not SELECTOR) -- Selects all tests that do not match SELECTOR.
925 \(tag TAG) -- Selects all tests that have TAG on their tags list.
926 A tag is an arbitrary label you can apply when you define a test.
927 \(satisfies PREDICATE) -- Selects all tests that satisfy PREDICATE.
928 PREDICATE is a function that takes an ert-test object as argument,
929 and returns non-nil if it is selected.
931 Only selectors that require a superset of tests, such
932 as (satisfies ...), strings, :new, etc. make use of UNIVERSE.
933 Selectors that do not, such as (member ...), just return the
934 set implied by them without checking whether it is really
935 contained in UNIVERSE."
936 ;; This code needs to match the etypecase in
937 ;; `ert-insert-human-readable-selector'.
938 (cl-etypecase selector
940 ((member t
) (cl-etypecase universe
942 ((member t
) (ert-select-tests "" universe
))))
943 ((member :new
) (ert-select-tests
944 `(satisfies ,(lambda (test)
945 (null (ert-test-most-recent-result test
))))
947 ((member :failed
) (ert-select-tests
948 `(satisfies ,(lambda (test)
949 (ert-test-result-type-p
950 (ert-test-most-recent-result test
)
953 ((member :passed
) (ert-select-tests
954 `(satisfies ,(lambda (test)
955 (ert-test-result-type-p
956 (ert-test-most-recent-result test
)
959 ((member :expected
) (ert-select-tests
962 (ert-test-result-expected-p
964 (ert-test-most-recent-result test
))))
966 ((member :unexpected
) (ert-select-tests `(not :expected
) universe
))
968 (cl-etypecase universe
969 ((member t
) (mapcar #'ert-get-test
970 (apropos-internal selector
#'ert-test-boundp
)))
971 (list (cl-remove-if-not (lambda (test)
972 (and (ert-test-name test
)
973 (string-match selector
974 (ert-test-name test
))))
976 (ert-test (list selector
))
978 (cl-assert (ert-test-boundp selector
))
979 (list (ert-get-test selector
)))
981 (cl-destructuring-bind (operator &rest operands
) selector
984 (mapcar (lambda (purported-test)
985 (cl-etypecase purported-test
986 (symbol (cl-assert (ert-test-boundp purported-test
))
987 (ert-get-test purported-test
))
988 (ert-test purported-test
)))
991 (cl-assert (eql (length operands
) 1))
992 (ert-select-tests `(member ,@operands
) universe
))
994 ;; Do these definitions of AND, NOT and OR satisfy de
995 ;; Morgan's laws? Should they?
996 (cl-case (length operands
)
997 (0 (ert-select-tests 't universe
))
998 (t (ert-select-tests `(and ,@(cdr operands
))
999 (ert-select-tests (car operands
)
1002 (cl-assert (eql (length operands
) 1))
1003 (let ((all-tests (ert-select-tests 't universe
)))
1004 (cl-set-difference all-tests
1005 (ert-select-tests (car operands
)
1008 (cl-case (length operands
)
1009 (0 (ert-select-tests 'nil universe
))
1010 (t (cl-union (ert-select-tests (car operands
) universe
)
1011 (ert-select-tests `(or ,@(cdr operands
))
1014 (cl-assert (eql (length operands
) 1))
1015 (let ((tag (car operands
)))
1016 (ert-select-tests `(satisfies
1018 (member tag
(ert-test-tags test
))))
1021 (cl-assert (eql (length operands
) 1))
1022 (cl-remove-if-not (car operands
)
1023 (ert-select-tests 't universe
))))))))
1025 (defun ert--insert-human-readable-selector (selector)
1026 "Insert a human-readable presentation of SELECTOR into the current buffer."
1027 ;; This is needed to avoid printing the (huge) contents of the
1028 ;; `backtrace' slot of the result objects in the
1029 ;; `most-recent-result' slots of test case objects in (eql ...) or
1030 ;; (member ...) selectors.
1031 (cl-labels ((rec (selector)
1032 ;; This code needs to match the etypecase in
1033 ;; `ert-select-tests'.
1034 (cl-etypecase selector
1036 :new
:failed
:passed
1037 :expected
:unexpected
)
1042 (if (ert-test-name selector
)
1043 (make-symbol (format "<%S>" (ert-test-name selector
)))
1044 (make-symbol "<unnamed test>")))
1046 (cl-destructuring-bind (operator &rest operands
) selector
1048 ((member eql and not or
)
1049 `(,operator
,@(mapcar #'rec operands
)))
1050 ((member tag satisfies
)
1052 (insert (format "%S" (rec selector
)))))
1055 ;;; Facilities for running a whole set of tests.
1057 ;; The data structure that contains the set of tests being executed
1058 ;; during one particular test run, their results, the state of the
1059 ;; execution, and some statistics.
1061 ;; The data about results and expected results of tests may seem
1062 ;; redundant here, since the test objects also carry such information.
1063 ;; However, the information in the test objects may be more recent, it
1064 ;; may correspond to a different test run. We need the information
1065 ;; that corresponds to this run in order to be able to update the
1066 ;; statistics correctly when a test is re-run interactively and has a
1067 ;; different result than before.
1068 (cl-defstruct ert--stats
1069 (selector (cl-assert nil
))
1070 ;; The tests, in order.
1071 (tests (cl-assert nil
) :type vector
)
1072 ;; A map of test names (or the test objects themselves for unnamed
1073 ;; tests) to indices into the `tests' vector.
1074 (test-map (cl-assert nil
) :type hash-table
)
1075 ;; The results of the tests during this run, in order.
1076 (test-results (cl-assert nil
) :type vector
)
1077 ;; The start times of the tests, in order, as reported by
1079 (test-start-times (cl-assert nil
) :type vector
)
1080 ;; The end times of the tests, in order, as reported by
1082 (test-end-times (cl-assert nil
) :type vector
)
1084 (passed-unexpected 0)
1086 (failed-unexpected 0)
1091 ;; The time at or after which the next redisplay should occur, as a
1093 (next-redisplay 0.0))
1095 (defun ert-stats-completed-expected (stats)
1096 "Return the number of tests in STATS that had expected results."
1097 (+ (ert--stats-passed-expected stats
)
1098 (ert--stats-failed-expected stats
)))
1100 (defun ert-stats-completed-unexpected (stats)
1101 "Return the number of tests in STATS that had unexpected results."
1102 (+ (ert--stats-passed-unexpected stats
)
1103 (ert--stats-failed-unexpected stats
)))
1105 (defun ert-stats-completed (stats)
1106 "Number of tests in STATS that have run so far."
1107 (+ (ert-stats-completed-expected stats
)
1108 (ert-stats-completed-unexpected stats
)))
1110 (defun ert-stats-total (stats)
1111 "Number of tests in STATS, regardless of whether they have run yet."
1112 (length (ert--stats-tests stats
)))
1114 ;; The stats object of the current run, dynamically bound. This is
1115 ;; used for the mode line progress indicator.
1116 (defvar ert--current-run-stats nil
)
1118 (defun ert--stats-test-key (test)
1119 "Return the key used for TEST in the test map of ert--stats objects.
1121 Returns the name of TEST if it has one, or TEST itself otherwise."
1122 (or (ert-test-name test
) test
))
1124 (defun ert--stats-set-test-and-result (stats pos test result
)
1125 "Change STATS by replacing the test at position POS with TEST and RESULT.
1127 Also changes the counters in STATS to match."
1128 (let* ((tests (ert--stats-tests stats
))
1129 (results (ert--stats-test-results stats
))
1130 (old-test (aref tests pos
))
1131 (map (ert--stats-test-map stats
)))
1132 (cl-flet ((update (d)
1133 (if (ert-test-result-expected-p (aref tests pos
)
1135 (cl-etypecase (aref results pos
)
1137 (cl-incf (ert--stats-passed-expected stats
) d
))
1139 (cl-incf (ert--stats-failed-expected stats
) d
))
1141 (ert-test-aborted-with-non-local-exit)
1143 (cl-etypecase (aref results pos
)
1145 (cl-incf (ert--stats-passed-unexpected stats
) d
))
1147 (cl-incf (ert--stats-failed-unexpected stats
) d
))
1149 (ert-test-aborted-with-non-local-exit)
1151 ;; Adjust counters to remove the result that is currently in stats.
1153 ;; Put new test and result into stats.
1154 (setf (aref tests pos
) test
1155 (aref results pos
) result
)
1156 (remhash (ert--stats-test-key old-test
) map
)
1157 (setf (gethash (ert--stats-test-key test
) map
) pos
)
1158 ;; Adjust counters to match new result.
1162 (defun ert--make-stats (tests selector
)
1163 "Create a new `ert--stats' object for running TESTS.
1165 SELECTOR is the selector that was used to select TESTS."
1166 (setq tests
(cl-coerce tests
'vector
))
1167 (let ((map (make-hash-table :size
(length tests
))))
1168 (cl-loop for i from
0
1169 for test across tests
1170 for key
= (ert--stats-test-key test
) do
1171 (cl-assert (not (gethash key map
)))
1172 (setf (gethash key map
) i
))
1173 (make-ert--stats :selector selector
1176 :test-results
(make-vector (length tests
) nil
)
1177 :test-start-times
(make-vector (length tests
) nil
)
1178 :test-end-times
(make-vector (length tests
) nil
))))
1180 (defun ert-run-or-rerun-test (stats test listener
)
1181 ;; checkdoc-order: nil
1182 "Run the single test TEST and record the result using STATS and LISTENER."
1183 (let ((ert--current-run-stats stats
)
1184 (pos (ert--stats-test-pos stats test
)))
1185 (ert--stats-set-test-and-result stats pos test nil
)
1186 ;; Call listener after setting/before resetting
1187 ;; (ert--stats-current-test stats); the listener might refresh the
1188 ;; mode line display, and if the value is not set yet/any more
1189 ;; during this refresh, the mode line will flicker unnecessarily.
1190 (setf (ert--stats-current-test stats
) test
)
1191 (funcall listener
'test-started stats test
)
1192 (setf (ert-test-most-recent-result test
) nil
)
1193 (setf (aref (ert--stats-test-start-times stats
) pos
) (current-time))
1196 (setf (aref (ert--stats-test-end-times stats
) pos
) (current-time))
1197 (let ((result (ert-test-most-recent-result test
)))
1198 (ert--stats-set-test-and-result stats pos test result
)
1199 (funcall listener
'test-ended stats test result
))
1200 (setf (ert--stats-current-test stats
) nil
))))
1202 (defun ert-run-tests (selector listener
)
1203 "Run the tests specified by SELECTOR, sending progress updates to LISTENER."
1204 (let* ((tests (ert-select-tests selector t
))
1205 (stats (ert--make-stats tests selector
)))
1206 (setf (ert--stats-start-time stats
) (current-time))
1207 (funcall listener
'run-started stats
)
1210 (let ((ert--current-run-stats stats
))
1211 (force-mode-line-update)
1214 (cl-loop for test in tests do
1215 (ert-run-or-rerun-test stats test listener
))
1216 (setq abortedp nil
))
1217 (setf (ert--stats-aborted-p stats
) abortedp
)
1218 (setf (ert--stats-end-time stats
) (current-time))
1219 (funcall listener
'run-ended stats abortedp
)))
1220 (force-mode-line-update))
1223 (defun ert--stats-test-pos (stats test
)
1224 ;; checkdoc-order: nil
1225 "Return the position (index) of TEST in the run represented by STATS."
1226 (gethash (ert--stats-test-key test
) (ert--stats-test-map stats
)))
1229 ;;; Formatting functions shared across UIs.
1231 (defun ert--format-time-iso8601 (time)
1232 "Format TIME in the variant of ISO 8601 used for timestamps in ERT."
1233 (format-time-string "%Y-%m-%d %T%z" time
))
1235 (defun ert-char-for-test-result (result expectedp
)
1236 "Return a character that represents the test result RESULT.
1238 EXPECTEDP specifies whether the result was expected."
1239 (let ((s (cl-etypecase result
1240 (ert-test-passed ".P")
1241 (ert-test-failed "fF")
1243 (ert-test-aborted-with-non-local-exit "aA")
1244 (ert-test-quit "qQ"))))
1245 (elt s
(if expectedp
0 1))))
1247 (defun ert-string-for-test-result (result expectedp
)
1248 "Return a string that represents the test result RESULT.
1250 EXPECTEDP specifies whether the result was expected."
1251 (let ((s (cl-etypecase result
1252 (ert-test-passed '("passed" "PASSED"))
1253 (ert-test-failed '("failed" "FAILED"))
1254 (null '("unknown" "UNKNOWN"))
1255 (ert-test-aborted-with-non-local-exit '("aborted" "ABORTED"))
1256 (ert-test-quit '("quit" "QUIT")))))
1257 (elt s
(if expectedp
0 1))))
1259 (defun ert--pp-with-indentation-and-newline (object)
1260 "Pretty-print OBJECT, indenting it to the current column of point.
1261 Ensures a final newline is inserted."
1262 (let ((begin (point)))
1263 (pp object
(current-buffer))
1264 (unless (bolp) (insert "\n"))
1269 (defun ert--insert-infos (result)
1270 "Insert `ert-info' infos from RESULT into current buffer.
1272 RESULT must be an `ert-test-result-with-condition'."
1273 (cl-check-type result ert-test-result-with-condition
)
1274 (dolist (info (ert-test-result-with-condition-infos result
))
1275 (cl-destructuring-bind (prefix . message
) info
1276 (let ((begin (point))
1277 (indentation (make-string (+ (length prefix
) 4) ?\s
))
1281 (insert message
"\n")
1282 (setq end
(copy-marker (point)))
1286 (while (< (point) end
)
1287 (insert indentation
)
1289 (when end
(set-marker end nil
)))))))
1292 ;;; Running tests in batch mode.
1294 (defvar ert-batch-backtrace-right-margin
70
1295 "The maximum line length for printing backtraces in `ert-run-tests-batch'.")
1298 (defun ert-run-tests-batch (&optional selector
)
1299 "Run the tests specified by SELECTOR, printing results to the terminal.
1301 SELECTOR works as described in `ert-select-tests', except if
1302 SELECTOR is nil, in which case all tests rather than none will be
1303 run; this makes the command line \"emacs -batch -l my-tests.el -f
1304 ert-run-tests-batch-and-exit\" useful.
1306 Returns the stats object."
1307 (unless selector
(setq selector
't
))
1310 (lambda (event-type &rest event-args
)
1311 (cl-ecase event-type
1313 (cl-destructuring-bind (stats) event-args
1314 (message "Running %s tests (%s)"
1315 (length (ert--stats-tests stats
))
1316 (ert--format-time-iso8601 (ert--stats-start-time stats
)))))
1318 (cl-destructuring-bind (stats abortedp
) event-args
1319 (let ((unexpected (ert-stats-completed-unexpected stats
))
1320 (expected-failures (ert--stats-failed-expected stats
)))
1321 (message "\n%sRan %s tests, %s results as expected%s (%s)%s\n"
1325 (ert-stats-total stats
)
1326 (ert-stats-completed-expected stats
)
1327 (if (zerop unexpected
)
1329 (format ", %s unexpected" unexpected
))
1330 (ert--format-time-iso8601 (ert--stats-end-time stats
))
1331 (if (zerop expected-failures
)
1333 (format "\n%s expected failures" expected-failures
)))
1334 (unless (zerop unexpected
)
1335 (message "%s unexpected results:" unexpected
)
1336 (cl-loop for test across
(ert--stats-tests stats
)
1337 for result
= (ert-test-most-recent-result test
) do
1338 (when (not (ert-test-result-expected-p test result
))
1340 (ert-string-for-test-result result nil
)
1341 (ert-test-name test
))))
1342 (message "%s" "")))))
1346 (cl-destructuring-bind (stats test result
) event-args
1347 (unless (ert-test-result-expected-p test result
)
1348 (cl-etypecase result
1350 (message "Test %S passed unexpectedly" (ert-test-name test
)))
1351 (ert-test-result-with-condition
1352 (message "Test %S backtrace:" (ert-test-name test
))
1354 (ert--print-backtrace (ert-test-result-with-condition-backtrace
1356 (goto-char (point-min))
1358 (let ((start (point))
1359 (end (progn (end-of-line) (point))))
1361 (+ start ert-batch-backtrace-right-margin
)))
1362 (message "%s" (buffer-substring-no-properties
1366 (ert--insert-infos result
)
1368 (let ((print-escape-newlines t
)
1371 (ert--pp-with-indentation-and-newline
1372 (ert-test-result-with-condition-condition result
)))
1373 (goto-char (1- (point-max)))
1374 (cl-assert (looking-at "\n"))
1376 (message "Test %S condition:" (ert-test-name test
))
1377 (message "%s" (buffer-string))))
1378 (ert-test-aborted-with-non-local-exit
1379 (message "Test %S aborted with non-local exit"
1380 (ert-test-name test
)))
1382 (message "Quit during %S" (ert-test-name test
)))))
1383 (let* ((max (prin1-to-string (length (ert--stats-tests stats
))))
1384 (format-string (concat "%9s %"
1385 (prin1-to-string (length max
))
1387 (message format-string
1388 (ert-string-for-test-result result
1389 (ert-test-result-expected-p
1391 (1+ (ert--stats-test-pos stats test
))
1392 (ert-test-name test
)))))))))
1395 (defun ert-run-tests-batch-and-exit (&optional selector
)
1396 "Like `ert-run-tests-batch', but exits Emacs when done.
1398 The exit status will be 0 if all test results were as expected, 1
1399 on unexpected results, or 2 if the tool detected an error outside
1400 of the tests (e.g. invalid SELECTOR or bug in the code that runs
1403 (let ((stats (ert-run-tests-batch selector
)))
1404 (kill-emacs (if (zerop (ert-stats-completed-unexpected stats
)) 0 1)))
1407 (message "Error running tests")
1412 ;;; Utility functions for load/unload actions.
1414 (defun ert--activate-font-lock-keywords ()
1415 "Activate font-lock keywords for some of ERT's symbols."
1416 (font-lock-add-keywords
1418 '(("(\\(\\<ert-deftest\\)\\>\\s *\\(\\sw+\\)?"
1419 (1 font-lock-keyword-face nil t
)
1420 (2 font-lock-function-name-face nil t
)))))
1422 (cl-defun ert--remove-from-list (list-var element
&key key test
)
1423 "Remove ELEMENT from the value of LIST-VAR if present.
1425 This can be used as an inverse of `add-to-list'."
1426 (unless key
(setq key
#'identity
))
1427 (unless test
(setq test
#'equal
))
1428 (setf (symbol-value list-var
)
1430 (symbol-value list-var
)
1435 ;;; Some basic interactive functions.
1437 (defun ert-read-test-name (prompt &optional default history
1438 add-default-to-prompt
)
1439 "Read the name of a test and return it as a symbol.
1441 Prompt with PROMPT. If DEFAULT is a valid test name, use it as a
1442 default. HISTORY is the history to use; see `completing-read'.
1443 If ADD-DEFAULT-TO-PROMPT is non-nil, PROMPT will be modified to
1444 include the default, if any.
1446 Signals an error if no test name was read."
1447 (cl-etypecase default
1448 (string (let ((symbol (intern-soft default
)))
1449 (unless (and symbol
(ert-test-boundp symbol
))
1450 (setq default nil
))))
1451 (symbol (setq default
1452 (if (ert-test-boundp default
)
1453 (symbol-name default
)
1455 (ert-test (setq default
(ert-test-name default
))))
1456 (when add-default-to-prompt
1457 (setq prompt
(if (null default
)
1458 (format "%s: " prompt
)
1459 (format "%s (default %s): " prompt default
))))
1460 (let ((input (completing-read prompt obarray
#'ert-test-boundp
1461 t nil history default nil
)))
1462 ;; completing-read returns an empty string if default was nil and
1463 ;; the user just hit enter.
1464 (let ((sym (intern-soft input
)))
1465 (if (ert-test-boundp sym
)
1467 (error "Input does not name a test")))))
1469 (defun ert-read-test-name-at-point (prompt)
1470 "Read the name of a test and return it as a symbol.
1471 As a default, use the symbol at point, or the test at point if in
1472 the ERT results buffer. Prompt with PROMPT, augmented with the
1474 (ert-read-test-name prompt
(ert-test-at-point) nil t
))
1476 (defun ert-find-test-other-window (test-name)
1477 "Find, in another window, the definition of TEST-NAME."
1478 (interactive (list (ert-read-test-name-at-point "Find test definition: ")))
1479 (find-function-do-it test-name
'ert-deftest
'switch-to-buffer-other-window
))
1481 (defun ert-delete-test (test-name)
1482 "Make the test TEST-NAME unbound.
1484 Nothing more than an interactive interface to `ert-make-test-unbound'."
1485 (interactive (list (ert-read-test-name-at-point "Delete test")))
1486 (ert-make-test-unbound test-name
))
1488 (defun ert-delete-all-tests ()
1489 "Make all symbols in `obarray' name no test."
1491 (when (called-interactively-p 'any
)
1492 (unless (y-or-n-p "Delete all tests? ")
1494 ;; We can't use `ert-select-tests' here since that gives us only
1495 ;; test objects, and going from them back to the test name symbols
1496 ;; can fail if the `ert-test' defstruct has been redefined.
1497 (mapc #'ert-make-test-unbound
(apropos-internal "" #'ert-test-boundp
))
1501 ;;; Display of test progress and results.
1503 ;; An entry in the results buffer ewoc. There is one entry per test.
1504 (cl-defstruct ert--ewoc-entry
1505 (test (cl-assert nil
))
1506 ;; If the result of this test was expected, its ewoc entry is hidden
1508 (hidden-p (cl-assert nil
))
1509 ;; An ewoc entry may be collapsed to hide details such as the error
1512 ;; I'm not sure the ability to expand and collapse entries is still
1513 ;; a useful feature.
1515 ;; By default, the ewoc entry presents the error condition with
1516 ;; certain limits on how much to print (`print-level',
1517 ;; `print-length'). The user can interactively switch to a set of
1519 (extended-printer-limits-p nil
))
1521 ;; Variables local to the results buffer.
1524 (defvar ert--results-ewoc
)
1525 ;; The stats object.
1526 (defvar ert--results-stats
)
1527 ;; A string with one character per test. Each character represents
1528 ;; the result of the corresponding test. The string is displayed near
1529 ;; the top of the buffer and serves as a progress bar.
1530 (defvar ert--results-progress-bar-string
)
1531 ;; The position where the progress bar button begins.
1532 (defvar ert--results-progress-bar-button-begin
)
1533 ;; The test result listener that updates the buffer when tests are run.
1534 (defvar ert--results-listener
)
1536 (defun ert-insert-test-name-button (test-name)
1537 "Insert a button that links to TEST-NAME."
1538 (insert-text-button (format "%S" test-name
)
1539 :type
'ert--test-name-button
1540 'ert-test-name test-name
))
1542 (defun ert--results-format-expected-unexpected (expected unexpected
)
1543 "Return a string indicating EXPECTED expected results, UNEXPECTED unexpected."
1544 (if (zerop unexpected
)
1545 (format "%s" expected
)
1546 (format "%s (%s unexpected)" (+ expected unexpected
) unexpected
)))
1548 (defun ert--results-update-ewoc-hf (ewoc stats
)
1549 "Update the header and footer of EWOC to show certain information from STATS.
1551 Also sets `ert--results-progress-bar-button-begin'."
1552 (let ((run-count (ert-stats-completed stats
))
1553 (results-buffer (current-buffer))
1554 ;; Need to save buffer-local value.
1555 (font-lock font-lock-mode
))
1560 (insert "Selector: ")
1561 (ert--insert-human-readable-selector (ert--stats-selector stats
))
1564 (format (concat "Passed: %s\n"
1567 (ert--results-format-expected-unexpected
1568 (ert--stats-passed-expected stats
)
1569 (ert--stats-passed-unexpected stats
))
1570 (ert--results-format-expected-unexpected
1571 (ert--stats-failed-expected stats
)
1572 (ert--stats-failed-unexpected stats
))
1574 (ert-stats-total stats
)))
1576 (format "Started at: %s\n"
1577 (ert--format-time-iso8601 (ert--stats-start-time stats
))))
1578 ;; FIXME: This is ugly. Need to properly define invariants of
1579 ;; the `stats' data structure.
1580 (let ((state (cond ((ert--stats-aborted-p stats
) 'aborted
)
1581 ((ert--stats-current-test stats
) 'running
)
1582 ((ert--stats-end-time stats
) 'finished
)
1588 (cond ((ert--stats-current-test stats
)
1589 (insert "Aborted during test: ")
1590 (ert-insert-test-name-button
1591 (ert-test-name (ert--stats-current-test stats
))))
1593 (insert "Aborted."))))
1595 (cl-assert (ert--stats-current-test stats
))
1596 (insert "Running test: ")
1597 (ert-insert-test-name-button (ert-test-name
1598 (ert--stats-current-test stats
))))
1600 (cl-assert (not (ert--stats-current-test stats
)))
1601 (insert "Finished.")))
1603 (if (ert--stats-end-time stats
)
1606 (if (ert--stats-aborted-p stats
)
1609 (ert--format-time-iso8601 (ert--stats-end-time stats
))))
1612 (let ((progress-bar-string (with-current-buffer results-buffer
1613 ert--results-progress-bar-string
)))
1614 (let ((progress-bar-button-begin
1615 (insert-text-button progress-bar-string
1616 :type
'ert--results-progress-bar-button
1617 'face
(or (and font-lock
1618 (ert-face-for-stats stats
))
1620 ;; The header gets copied verbatim to the results buffer,
1621 ;; and all positions remain the same, so
1622 ;; `progress-bar-button-begin' will be the right position
1623 ;; even in the results buffer.
1624 (with-current-buffer results-buffer
1625 (set (make-local-variable 'ert--results-progress-bar-button-begin
)
1626 progress-bar-button-begin
))))
1631 ;; We actually want an empty footer, but that would trigger a bug
1632 ;; in ewoc, sometimes clearing the entire buffer. (It's possible
1633 ;; that this bug has been fixed since this has been tested; we
1634 ;; should test it again.)
1638 (defvar ert-test-run-redisplay-interval-secs
.1
1639 "How many seconds ERT should wait between redisplays while running tests.
1641 While running tests, ERT shows the current progress, and this variable
1642 determines how frequently the progress display is updated.")
1644 (defun ert--results-update-stats-display (ewoc stats
)
1645 "Update EWOC and the mode line to show data from STATS."
1646 ;; TODO(ohler): investigate using `make-progress-reporter'.
1647 (ert--results-update-ewoc-hf ewoc stats
)
1648 (force-mode-line-update)
1650 (setf (ert--stats-next-redisplay stats
)
1651 (+ (float-time) ert-test-run-redisplay-interval-secs
)))
1653 (defun ert--results-update-stats-display-maybe (ewoc stats
)
1654 "Call `ert--results-update-stats-display' if not called recently.
1656 EWOC and STATS are arguments for `ert--results-update-stats-display'."
1657 (when (>= (float-time) (ert--stats-next-redisplay stats
))
1658 (ert--results-update-stats-display ewoc stats
)))
1660 (defun ert--tests-running-mode-line-indicator ()
1661 "Return a string for the mode line that shows the test run progress."
1662 (let* ((stats ert--current-run-stats
)
1663 (tests-total (ert-stats-total stats
))
1664 (tests-completed (ert-stats-completed stats
)))
1665 (if (>= tests-completed tests-total
)
1666 (format " ERT(%s/%s,finished)" tests-completed tests-total
)
1667 (format " ERT(%s/%s):%s"
1668 (1+ tests-completed
)
1670 (if (null (ert--stats-current-test stats
))
1673 (ert-test-name (ert--stats-current-test stats
))))))))
1675 (defun ert--make-xrefs-region (begin end
)
1676 "Attach cross-references to function names between BEGIN and END.
1678 BEGIN and END specify a region in the current buffer."
1681 (narrow-to-region begin end
)
1682 ;; Inhibit optimization in `debugger-make-xrefs' that would
1683 ;; sometimes insert unrelated backtrace info into our buffer.
1684 (let ((debugger-previous-backtrace nil
))
1685 (debugger-make-xrefs)))))
1687 (defun ert--string-first-line (s)
1688 "Return the first line of S, or S if it contains no newlines.
1690 The return value does not include the line terminator."
1691 (substring s
0 (cl-position ?
\n s
)))
1693 (defun ert-face-for-test-result (expectedp)
1694 "Return a face that shows whether a test result was expected or unexpected.
1696 If EXPECTEDP is nil, returns the face for unexpected results; if
1697 non-nil, returns the face for expected results.."
1698 (if expectedp
'ert-test-result-expected
'ert-test-result-unexpected
))
1700 (defun ert-face-for-stats (stats)
1701 "Return a face that represents STATS."
1702 (cond ((ert--stats-aborted-p stats
) 'nil
)
1703 ((cl-plusp (ert-stats-completed-unexpected stats
))
1704 (ert-face-for-test-result nil
))
1705 ((eql (ert-stats-completed-expected stats
) (ert-stats-total stats
))
1706 (ert-face-for-test-result t
))
1709 (defun ert--print-test-for-ewoc (entry)
1710 "The ewoc print function for ewoc test entries. ENTRY is the entry to print."
1711 (let* ((test (ert--ewoc-entry-test entry
))
1712 (stats ert--results-stats
)
1713 (result (let ((pos (ert--stats-test-pos stats test
)))
1715 (aref (ert--stats-test-results stats
) pos
)))
1716 (hiddenp (ert--ewoc-entry-hidden-p entry
))
1717 (expandedp (ert--ewoc-entry-expanded-p entry
))
1718 (extended-printer-limits-p (ert--ewoc-entry-extended-printer-limits-p
1722 (let ((expectedp (ert-test-result-expected-p test result
)))
1723 (insert-text-button (format "%c" (ert-char-for-test-result
1725 :type
'ert--results-expand-collapse-button
1726 'face
(or (and font-lock-mode
1727 (ert-face-for-test-result
1731 (ert-insert-test-name-button (ert-test-name test
))
1733 (when (and expandedp
(not (eql result
'nil
)))
1734 (when (ert-test-documentation test
)
1737 (ert--string-first-line (ert-test-documentation test
))
1738 'font-lock-face
'font-lock-doc-face
)
1740 (cl-etypecase result
1742 (if (ert-test-result-expected-p test result
)
1743 (insert " passed\n")
1744 (insert " passed unexpectedly\n"))
1746 (ert-test-result-with-condition
1747 (ert--insert-infos result
)
1748 (let ((print-escape-newlines t
)
1749 (print-level (if extended-printer-limits-p
12 6))
1750 (print-length (if extended-printer-limits-p
100 10)))
1752 (let ((begin (point)))
1753 (ert--pp-with-indentation-and-newline
1754 (ert-test-result-with-condition-condition result
))
1755 (ert--make-xrefs-region begin
(point)))))
1756 (ert-test-aborted-with-non-local-exit
1757 (insert " aborted\n"))
1759 (insert " quit\n")))
1763 (defun ert--results-font-lock-function (enabledp)
1764 "Redraw the ERT results buffer after font-lock-mode was switched on or off.
1766 ENABLEDP is true if font-lock-mode is switched on, false
1768 (ert--results-update-ewoc-hf ert--results-ewoc ert--results-stats
)
1769 (ewoc-refresh ert--results-ewoc
)
1770 (font-lock-default-function enabledp
))
1772 (defun ert--setup-results-buffer (stats listener buffer-name
)
1773 "Set up a test results buffer.
1775 STATS is the stats object; LISTENER is the results listener;
1776 BUFFER-NAME, if non-nil, is the buffer name to use."
1777 (unless buffer-name
(setq buffer-name
"*ert*"))
1778 (let ((buffer (get-buffer-create buffer-name
)))
1779 (with-current-buffer buffer
1780 (let ((inhibit-read-only t
))
1781 (buffer-disable-undo)
1784 ;; Erase buffer again in case switching out of the previous
1785 ;; mode inserted anything. (This happens e.g. when switching
1786 ;; from ert-results-mode to ert-results-mode when
1787 ;; font-lock-mode turns itself off in change-major-mode-hook.)
1789 (set (make-local-variable 'font-lock-function
)
1790 'ert--results-font-lock-function
)
1791 (let ((ewoc (ewoc-create 'ert--print-test-for-ewoc nil nil t
)))
1792 (set (make-local-variable 'ert--results-ewoc
) ewoc
)
1793 (set (make-local-variable 'ert--results-stats
) stats
)
1794 (set (make-local-variable 'ert--results-progress-bar-string
)
1795 (make-string (ert-stats-total stats
)
1796 (ert-char-for-test-result nil t
)))
1797 (set (make-local-variable 'ert--results-listener
) listener
)
1798 (cl-loop for test across
(ert--stats-tests stats
) do
1799 (ewoc-enter-last ewoc
1800 (make-ert--ewoc-entry :test test
1802 (ert--results-update-ewoc-hf ert--results-ewoc ert--results-stats
)
1803 (goto-char (1- (point-max)))
1807 (defvar ert--selector-history nil
1808 "List of recent test selectors read from terminal.")
1810 ;; Should OUTPUT-BUFFER-NAME and MESSAGE-FN really be arguments here?
1811 ;; They are needed only for our automated self-tests at the moment.
1812 ;; Or should there be some other mechanism?
1814 (defun ert-run-tests-interactively (selector
1815 &optional output-buffer-name message-fn
)
1816 "Run the tests specified by SELECTOR and display the results in a buffer.
1818 SELECTOR works as described in `ert-select-tests'.
1819 OUTPUT-BUFFER-NAME and MESSAGE-FN should normally be nil; they
1820 are used for automated self-tests and specify which buffer to use
1821 and how to display message."
1823 (list (let ((default (if ert--selector-history
1824 ;; Can't use `first' here as this form is
1825 ;; not compiled, and `first' is not
1826 ;; defined without cl.
1827 (car ert--selector-history
)
1829 (read-from-minibuffer (if (null default
)
1831 (format "Run tests (default %s): " default
))
1832 nil nil t
'ert--selector-history
1835 (unless message-fn
(setq message-fn
'message
))
1836 (let ((output-buffer-name output-buffer-name
)
1839 (message-fn message-fn
))
1841 (lambda (event-type &rest event-args
)
1842 (cl-ecase event-type
1844 (cl-destructuring-bind (stats) event-args
1845 (setq buffer
(ert--setup-results-buffer stats
1847 output-buffer-name
))
1848 (pop-to-buffer buffer
)))
1850 (cl-destructuring-bind (stats abortedp
) event-args
1852 "%sRan %s tests, %s results were as expected%s"
1856 (ert-stats-total stats
)
1857 (ert-stats-completed-expected stats
)
1859 (ert-stats-completed-unexpected stats
)))
1860 (if (zerop unexpected
)
1862 (format ", %s unexpected" unexpected
))))
1863 (ert--results-update-stats-display (with-current-buffer buffer
1867 (cl-destructuring-bind (stats test
) event-args
1868 (with-current-buffer buffer
1869 (let* ((ewoc ert--results-ewoc
)
1870 (pos (ert--stats-test-pos stats test
))
1871 (node (ewoc-nth ewoc pos
)))
1873 (setf (ert--ewoc-entry-test (ewoc-data node
)) test
)
1874 (aset ert--results-progress-bar-string pos
1875 (ert-char-for-test-result nil t
))
1876 (ert--results-update-stats-display-maybe ewoc stats
)
1877 (ewoc-invalidate ewoc node
)))))
1879 (cl-destructuring-bind (stats test result
) event-args
1880 (with-current-buffer buffer
1881 (let* ((ewoc ert--results-ewoc
)
1882 (pos (ert--stats-test-pos stats test
))
1883 (node (ewoc-nth ewoc pos
)))
1884 (when (ert--ewoc-entry-hidden-p (ewoc-data node
))
1885 (setf (ert--ewoc-entry-hidden-p (ewoc-data node
))
1886 (ert-test-result-expected-p test result
)))
1887 (aset ert--results-progress-bar-string pos
1888 (ert-char-for-test-result result
1889 (ert-test-result-expected-p
1891 (ert--results-update-stats-display-maybe ewoc stats
)
1892 (ewoc-invalidate ewoc node
))))))))
1897 (defalias 'ert
'ert-run-tests-interactively
)
1900 ;;; Simple view mode for auxiliary information like stack traces or
1901 ;;; messages. Mainly binds "q" for quit.
1903 (define-derived-mode ert-simple-view-mode special-mode
"ERT-View"
1904 "Major mode for viewing auxiliary information in ERT.")
1906 ;;; Commands and button actions for the results buffer.
1908 (define-derived-mode ert-results-mode special-mode
"ERT-Results"
1909 "Major mode for viewing results of ERT test runs.")
1911 (cl-loop for
(key binding
) in
1912 '( ;; Stuff that's not in the menu.
1913 ("\t" forward-button
)
1914 ([backtab] backward-button)
1915 ("j" ert-results-jump-between-summary-and-result)
1916 ("L" ert-results-toggle-printer-limits-for-test-at-point)
1917 ("n" ert-results-next-test)
1918 ("p" ert-results-previous-test)
1919 ;; Stuff that is in the menu.
1920 ("R" ert-results-rerun-all-tests)
1921 ("r" ert-results-rerun-test-at-point)
1922 ("d" ert-results-rerun-test-at-point-debugging-errors)
1923 ("." ert-results-find-test-at-point-other-window)
1924 ("b" ert-results-pop-to-backtrace-for-test-at-point)
1925 ("m" ert-results-pop-to-messages-for-test-at-point)
1926 ("l" ert-results-pop-to-should-forms-for-test-at-point)
1927 ("h" ert-results-describe-test-at-point)
1928 ("D" ert-delete-test)
1929 ("T" ert-results-pop-to-timings)
1932 (define-key ert-results-mode-map key binding))
1934 (easy-menu-define ert-results-mode-menu ert-results-mode-map
1935 "Menu for `ert-results-mode'."
1937 ["Re-run all tests" ert-results-rerun-all-tests]
1939 ["Re-run test" ert-results-rerun-test-at-point]
1940 ["Debug test" ert-results-rerun-test-at-point-debugging-errors]
1941 ["Show test definition" ert-results-find-test-at-point-other-window]
1943 ["Show backtrace" ert-results-pop-to-backtrace-for-test-at-point]
1944 ["Show messages" ert-results-pop-to-messages-for-test-at-point]
1945 ["Show `should' forms" ert-results-pop-to-should-forms-for-test-at-point]
1946 ["Describe test" ert-results-describe-test-at-point]
1948 ["Delete test" ert-delete-test]
1950 ["Show execution time of each test" ert-results-pop-to-timings]
1953 (define-button-type 'ert--results-progress-bar-button
1954 'action #'ert--results-progress-bar-button-action
1955 'help-echo "mouse-2, RET: Reveal test result")
1957 (define-button-type 'ert--test-name-button
1958 'action #'ert--test-name-button-action
1959 'help-echo "mouse-2, RET: Find test definition")
1961 (define-button-type 'ert--results-expand-collapse-button
1962 'action #'ert--results-expand-collapse-button-action
1963 'help-echo "mouse-2, RET: Expand/collapse test result")
1965 (defun ert--results-test-node-or-null-at-point ()
1966 "If point is on a valid ewoc node, return it; return nil otherwise.
1968 To be used in the ERT results buffer."
1969 (let* ((ewoc ert--results-ewoc)
1970 (node (ewoc-locate ewoc)))
1971 ;; `ewoc-locate' will return an arbitrary node when point is on
1972 ;; header or footer, or when all nodes are invisible. So we need
1973 ;; to validate its return value here.
1975 ;; Update: I'm seeing nil being returned in some cases now,
1976 ;; perhaps this has been changed?
1978 (>= (point) (ewoc-location node))
1979 (not (ert--ewoc-entry-hidden-p (ewoc-data node))))
1983 (defun ert--results-test-node-at-point ()
1984 "If point is on a valid ewoc node, return it; signal an error otherwise.
1986 To be used in the ERT results buffer."
1987 (or (ert--results-test-node-or-null-at-point)
1988 (error "No test at point")))
1990 (defun ert-results-next-test ()
1991 "Move point to the next test.
1993 To be used in the ERT results buffer."
1995 (ert--results-move (ewoc-locate ert--results-ewoc) 'ewoc-next
1998 (defun ert-results-previous-test ()
1999 "Move point to the previous test.
2001 To be used in the ERT results buffer."
2003 (ert--results-move (ewoc-locate ert--results-ewoc) 'ewoc-prev
2006 (defun ert--results-move (node ewoc-fn error-message)
2007 "Move point from NODE to the previous or next node.
2009 EWOC-FN specifies the direction and should be either `ewoc-prev'
2010 or `ewoc-next'. If there are no more nodes in that direction, an
2011 error is signaled with the message ERROR-MESSAGE."
2013 (setq node (funcall ewoc-fn ert--results-ewoc node))
2015 (error "%s" error-message))
2016 (unless (ert--ewoc-entry-hidden-p (ewoc-data node))
2017 (goto-char (ewoc-location node))
2020 (defun ert--results-expand-collapse-button-action (_button)
2021 "Expand or collapse the test node BUTTON belongs to."
2022 (let* ((ewoc ert--results-ewoc)
2023 (node (save-excursion
2024 (goto-char (ert--button-action-position))
2025 (ert--results-test-node-at-point)))
2026 (entry (ewoc-data node)))
2027 (setf (ert--ewoc-entry-expanded-p entry)
2028 (not (ert--ewoc-entry-expanded-p entry)))
2029 (ewoc-invalidate ewoc node)))
2031 (defun ert-results-find-test-at-point-other-window ()
2032 "Find the definition of the test at point in another window.
2034 To be used in the ERT results buffer."
2036 (let ((name (ert-test-at-point)))
2038 (error "No test at point"))
2039 (ert-find-test-other-window name)))
2041 (defun ert--test-name-button-action (button)
2042 "Find the definition of the test BUTTON belongs to, in another window."
2043 (let ((name (button-get button 'ert-test-name)))
2044 (ert-find-test-other-window name)))
2046 (defun ert--ewoc-position (ewoc node)
2047 ;; checkdoc-order: nil
2048 "Return the position of NODE in EWOC, or nil if NODE is not in EWOC."
2049 (cl-loop for i from 0
2050 for node-here = (ewoc-nth ewoc 0) then (ewoc-next ewoc node-here)
2051 do (when (eql node node-here)
2053 finally (cl-return nil)))
2055 (defun ert-results-jump-between-summary-and-result ()
2056 "Jump back and forth between the test run summary and individual test results.
2058 From an ewoc node, jumps to the character that represents the
2059 same test in the progress bar, and vice versa.
2061 To be used in the ERT results buffer."
2062 ;; Maybe this command isn't actually needed much, but if it is, it
2063 ;; seems like an indication that the UI design is not optimal. If
2064 ;; jumping back and forth between a summary at the top of the buffer
2065 ;; and the error log in the remainder of the buffer is useful, then
2066 ;; the summary apparently needs to be easily accessible from the
2067 ;; error log, and perhaps it would be better to have it in a
2068 ;; separate buffer to keep it visible.
2070 (let ((ewoc ert--results-ewoc)
2071 (progress-bar-begin ert--results-progress-bar-button-begin))
2072 (cond ((ert--results-test-node-or-null-at-point)
2073 (let* ((node (ert--results-test-node-at-point))
2074 (pos (ert--ewoc-position ewoc node)))
2075 (goto-char (+ progress-bar-begin pos))))
2076 ((and (<= progress-bar-begin (point))
2077 (< (point) (button-end (button-at progress-bar-begin))))
2078 (let* ((node (ewoc-nth ewoc (- (point) progress-bar-begin)))
2079 (entry (ewoc-data node)))
2080 (when (ert--ewoc-entry-hidden-p entry)
2081 (setf (ert--ewoc-entry-hidden-p entry) nil)
2082 (ewoc-invalidate ewoc node))
2083 (ewoc-goto-node ewoc node)))
2085 (goto-char progress-bar-begin)))))
2087 (defun ert-test-at-point ()
2088 "Return the name of the test at point as a symbol, or nil if none."
2089 (or (and (eql major-mode 'ert-results-mode)
2090 (let ((test (ert--results-test-at-point-no-redefinition)))
2091 (and test (ert-test-name test))))
2092 (let* ((thing (thing-at-point 'symbol))
2093 (sym (intern-soft thing)))
2094 (and (ert-test-boundp sym)
2097 (defun ert--results-test-at-point-no-redefinition ()
2098 "Return the test at point, or nil.
2100 To be used in the ERT results buffer."
2101 (cl-assert (eql major-mode 'ert-results-mode))
2102 (if (ert--results-test-node-or-null-at-point)
2103 (let* ((node (ert--results-test-node-at-point))
2104 (test (ert--ewoc-entry-test (ewoc-data node))))
2106 (let ((progress-bar-begin ert--results-progress-bar-button-begin))
2107 (when (and (<= progress-bar-begin (point))
2108 (< (point) (button-end (button-at progress-bar-begin))))
2109 (let* ((test-index (- (point) progress-bar-begin))
2110 (test (aref (ert--stats-tests ert--results-stats)
2114 (defun ert--results-test-at-point-allow-redefinition ()
2115 "Look up the test at point, and check whether it has been redefined.
2117 To be used in the ERT results buffer.
2119 Returns a list of two elements: the test (or nil) and a symbol
2120 specifying whether the test has been redefined.
2122 If a new test has been defined with the same name as the test at
2123 point, replaces the test at point with the new test, and returns
2124 the new test and the symbol `redefined'.
2126 If the test has been deleted, returns the old test and the symbol
2129 If the test is still current, returns the test and the symbol nil.
2131 If there is no test at point, returns a list with two nils."
2132 (let ((test (ert--results-test-at-point-no-redefinition)))
2135 ((null (ert-test-name test))
2138 (let* ((name (ert-test-name test))
2139 (new-test (and (ert-test-boundp name)
2140 (ert-get-test name))))
2141 (cond ((eql test new-test)
2146 (ert--results-update-after-test-redefinition
2147 (ert--stats-test-pos ert--results-stats test)
2149 `(,new-test redefined))))))))
2151 (defun ert--results-update-after-test-redefinition (pos new-test)
2152 "Update results buffer after the test at pos POS has been redefined.
2154 Also updates the stats object. NEW-TEST is the new test
2156 (let* ((stats ert--results-stats)
2157 (ewoc ert--results-ewoc)
2158 (node (ewoc-nth ewoc pos))
2159 (entry (ewoc-data node)))
2160 (ert--stats-set-test-and-result stats pos new-test nil)
2161 (setf (ert--ewoc-entry-test entry) new-test
2162 (aref ert--results-progress-bar-string pos) (ert-char-for-test-result
2164 (ewoc-invalidate ewoc node))
2167 (defun ert--button-action-position ()
2168 "The buffer position where the last button action was triggered."
2169 (cond ((integerp last-command-event)
2171 ((eventp last-command-event)
2172 (posn-point (event-start last-command-event)))
2173 (t (cl-assert nil))))
2175 (defun ert--results-progress-bar-button-action (_button)
2176 "Jump to details for the test represented by the character clicked in BUTTON."
2177 (goto-char (ert--button-action-position))
2178 (ert-results-jump-between-summary-and-result))
2180 (defun ert-results-rerun-all-tests ()
2181 "Re-run all tests, using the same selector.
2183 To be used in the ERT results buffer."
2185 (cl-assert (eql major-mode 'ert-results-mode))
2186 (let ((selector (ert--stats-selector ert--results-stats)))
2187 (ert-run-tests-interactively selector (buffer-name))))
2189 (defun ert-results-rerun-test-at-point ()
2190 "Re-run the test at point.
2192 To be used in the ERT results buffer."
2194 (cl-destructuring-bind (test redefinition-state)
2195 (ert--results-test-at-point-allow-redefinition)
2197 (error "No test at point"))
2198 (let* ((stats ert--results-stats)
2199 (progress-message (format "Running %stest %S"
2200 (cl-ecase redefinition-state
2202 (redefined "new definition of ")
2203 (deleted "deleted "))
2204 (ert-test-name test))))
2205 ;; Need to save and restore point manually here: When point is on
2206 ;; the first visible ewoc entry while the header is updated, point
2207 ;; moves to the top of the buffer. This is undesirable, and a
2208 ;; simple `save-excursion' doesn't prevent it.
2209 (let ((point (point)))
2213 (message "%s..." progress-message)
2214 (ert-run-or-rerun-test stats test
2215 ert--results-listener))
2216 (ert--results-update-stats-display ert--results-ewoc stats)
2219 (let ((result (ert-test-most-recent-result test)))
2220 (ert-string-for-test-result
2221 result (ert-test-result-expected-p test result)))))
2222 (goto-char point))))))
2224 (defun ert-results-rerun-test-at-point-debugging-errors ()
2225 "Re-run the test at point with `ert-debug-on-error' bound to t.
2227 To be used in the ERT results buffer."
2229 (let ((ert-debug-on-error t))
2230 (ert-results-rerun-test-at-point)))
2232 (defun ert-results-pop-to-backtrace-for-test-at-point ()
2233 "Display the backtrace for the test at point.
2235 To be used in the ERT results buffer."
2237 (let* ((test (ert--results-test-at-point-no-redefinition))
2238 (stats ert--results-stats)
2239 (pos (ert--stats-test-pos stats test))
2240 (result (aref (ert--stats-test-results stats) pos)))
2241 (cl-etypecase result
2242 (ert-test-passed (error "Test passed, no backtrace available"))
2243 (ert-test-result-with-condition
2244 (let ((backtrace (ert-test-result-with-condition-backtrace result))
2245 (buffer (get-buffer-create "*ERT Backtrace*")))
2246 (pop-to-buffer buffer)
2247 (let ((inhibit-read-only t))
2248 (buffer-disable-undo)
2250 (ert-simple-view-mode)
2251 ;; Use unibyte because `debugger-setup-buffer' also does so.
2252 (set-buffer-multibyte nil)
2253 (setq truncate-lines t)
2254 (ert--print-backtrace backtrace)
2255 (debugger-make-xrefs)
2256 (goto-char (point-min))
2257 (insert "Backtrace for test `")
2258 (ert-insert-test-name-button (ert-test-name test))
2259 (insert "':\n")))))))
2261 (defun ert-results-pop-to-messages-for-test-at-point ()
2262 "Display the part of the *Messages* buffer generated during the test at point.
2264 To be used in the ERT results buffer."
2266 (let* ((test (ert--results-test-at-point-no-redefinition))
2267 (stats ert--results-stats)
2268 (pos (ert--stats-test-pos stats test))
2269 (result (aref (ert--stats-test-results stats) pos)))
2270 (let ((buffer (get-buffer-create "*ERT Messages*")))
2271 (pop-to-buffer buffer)
2272 (let ((inhibit-read-only t))
2273 (buffer-disable-undo)
2275 (ert-simple-view-mode)
2276 (insert (ert-test-result-messages result))
2277 (goto-char (point-min))
2278 (insert "Messages for test `")
2279 (ert-insert-test-name-button (ert-test-name test))
2282 (defun ert-results-pop-to-should-forms-for-test-at-point ()
2283 "Display the list of `should' forms executed during the test at point.
2285 To be used in the ERT results buffer."
2287 (let* ((test (ert--results-test-at-point-no-redefinition))
2288 (stats ert--results-stats)
2289 (pos (ert--stats-test-pos stats test))
2290 (result (aref (ert--stats-test-results stats) pos)))
2291 (let ((buffer (get-buffer-create "*ERT list of should forms*")))
2292 (pop-to-buffer buffer)
2293 (let ((inhibit-read-only t))
2294 (buffer-disable-undo)
2296 (ert-simple-view-mode)
2297 (if (null (ert-test-result-should-forms result))
2298 (insert "\n(No should forms during this test.)\n")
2299 (cl-loop for form-description
2300 in (ert-test-result-should-forms result)
2303 (insert (format "%s: " i))
2304 (let ((begin (point)))
2305 (ert--pp-with-indentation-and-newline form-description)
2306 (ert--make-xrefs-region begin (point)))))
2307 (goto-char (point-min))
2308 (insert "`should' forms executed during test `")
2309 (ert-insert-test-name-button (ert-test-name test))
2312 (insert (concat "(Values are shallow copies and may have "
2313 "looked different during the test if they\n"
2314 "have been modified destructively.)\n"))
2315 (forward-line 1)))))
2317 (defun ert-results-toggle-printer-limits-for-test-at-point ()
2318 "Toggle how much of the condition to print for the test at point.
2320 To be used in the ERT results buffer."
2322 (let* ((ewoc ert--results-ewoc)
2323 (node (ert--results-test-node-at-point))
2324 (entry (ewoc-data node)))
2325 (setf (ert--ewoc-entry-extended-printer-limits-p entry)
2326 (not (ert--ewoc-entry-extended-printer-limits-p entry)))
2327 (ewoc-invalidate ewoc node)))
2329 (defun ert-results-pop-to-timings ()
2330 "Display test timings for the last run.
2332 To be used in the ERT results buffer."
2334 (let* ((stats ert--results-stats)
2335 (buffer (get-buffer-create "*ERT timings*"))
2336 (data (cl-loop for test across (ert--stats-tests stats)
2337 for start-time across (ert--stats-test-start-times
2339 for end-time across (ert--stats-test-end-times stats)
2341 (float-time (subtract-time
2342 end-time start-time))))))
2343 (setq data (sort data (lambda (a b)
2344 (> (cl-second a) (cl-second b)))))
2345 (pop-to-buffer buffer)
2346 (let ((inhibit-read-only t))
2347 (buffer-disable-undo)
2349 (ert-simple-view-mode)
2351 (insert "(No data)\n")
2352 (insert (format "%-3s %8s %8s\n" "" "time" "cumul"))
2353 (cl-loop for (test time) in data
2354 for cumul-time = time then (+ cumul-time time)
2357 (insert (format "%3s: %8.3f %8.3f " i time cumul-time))
2358 (ert-insert-test-name-button (ert-test-name test))
2360 (goto-char (point-min))
2361 (insert "Tests by run time (seconds):\n\n")
2365 (defun ert-describe-test (test-or-test-name)
2366 "Display the documentation for TEST-OR-TEST-NAME (a symbol or ert-test)."
2367 (interactive (list (ert-read-test-name-at-point "Describe test")))
2368 (when (< emacs-major-version 24)
2369 (error "Requires Emacs 24"))
2372 (cl-etypecase test-or-test-name
2373 (symbol (setq test-name test-or-test-name
2374 test-definition (ert-get-test test-or-test-name)))
2375 (ert-test (setq test-name (ert-test-name test-or-test-name)
2376 test-definition test-or-test-name)))
2377 (help-setup-xref (list #'ert-describe-test test-or-test-name)
2378 (called-interactively-p 'interactive))
2380 (with-help-window (help-buffer)
2381 (with-current-buffer (help-buffer)
2382 (insert (if test-name (format "%S" test-name) "<anonymous test>"))
2383 (insert " is a test")
2384 (let ((file-name (and test-name
2385 (symbol-file test-name 'ert-deftest))))
2387 (insert " defined in `" (file-name-nondirectory file-name) "'")
2389 (re-search-backward "`\\([^`']+\\)'" nil t)
2390 (help-xref-button 1 'help-function-def test-name file-name)))
2392 (fill-region-as-paragraph (point-min) (point))
2394 (unless (and (ert-test-boundp test-name)
2395 (eql (ert-get-test test-name) test-definition))
2396 (let ((begin (point)))
2397 (insert "Note: This test has been redefined or deleted, "
2398 "this documentation refers to an old definition.")
2399 (fill-region-as-paragraph begin (point)))
2401 (insert (or (ert-test-documentation test-definition)
2402 "It is not documented.")
2405 (defun ert-results-describe-test-at-point ()
2406 "Display the documentation of the test at point.
2408 To be used in the ERT results buffer."
2410 (ert-describe-test (ert--results-test-at-point-no-redefinition)))
2413 ;;; Actions on load/unload.
2415 (add-to-list 'find-function-regexp-alist '(ert-deftest . ert--find-test-regexp))
2416 (add-to-list 'minor-mode-alist '(ert--current-run-stats
2418 (ert--tests-running-mode-line-indicator))))
2419 (add-to-list 'emacs-lisp-mode-hook 'ert--activate-font-lock-keywords)
2421 (defun ert--unload-function ()
2422 "Unload function to undo the side-effects of loading ert.el."
2423 (ert--remove-from-list 'find-function-regexp-alist 'ert-deftest :key #'car)
2424 (ert--remove-from-list 'minor-mode-alist 'ert--current-run-stats :key #'car)
2425 (ert--remove-from-list 'emacs-lisp-mode-hook
2426 'ert--activate-font-lock-keywords)
2429 (defvar ert-unload-hook '())
2430 (add-hook 'ert-unload-hook 'ert--unload-function)
2435 ;;; ert.el ends here