1 ;;; ert.el --- Emacs Lisp Regression Testing -*- lexical-binding: t -*-
3 ;; Copyright (C) 2007-2008, 2010-2017 Free Software Foundation, Inc.
5 ;; Author: Christian Ohler <ohler@gnu.org>
6 ;; Keywords: lisp, tools
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;; ERT is a tool for automated testing in Emacs Lisp. Its main
26 ;; features are facilities for defining and running test cases and
27 ;; reporting the results as well as for debugging test failures
30 ;; The main entry points are `ert-deftest', which is similar to
31 ;; `defun' but defines a test, and `ert-run-tests-interactively',
32 ;; which runs tests and offers an interactive interface for inspecting
33 ;; results and debugging. There is also
34 ;; `ert-run-tests-batch-and-exit' for non-interactive use.
36 ;; The body of `ert-deftest' forms resembles a function body, but the
37 ;; additional operators `should', `should-not', `should-error' and
38 ;; `skip-unless' are available. `should' is similar to cl's `assert',
39 ;; but signals a different error when its condition is violated that
40 ;; is caught and processed by ERT. In addition, it analyzes its
41 ;; argument form and records information that helps debugging
42 ;; (`assert' tries to do something similar when its second argument
43 ;; SHOW-ARGS is true, but `should' is more sophisticated). For
44 ;; information on `should-not' and `should-error', see their
45 ;; docstrings. `skip-unless' skips the test immediately without
46 ;; processing further, this is useful for checking the test
47 ;; environment (like availability of features, external binaries, etc).
49 ;; See ERT's info manual as well as the docstrings for more details.
50 ;; To compile the manual, run `makeinfo ert.texinfo' in the ERT
51 ;; directory, then C-u M-x info ert.info in Emacs to view it.
53 ;; To see some examples of tests written in ERT, see its self-tests in
54 ;; ert-tests.el. Some of these are tricky due to the bootstrapping
55 ;; problem of writing tests for a testing tool, others test simple
56 ;; functions and are straightforward.
69 ;;; UI customization options.
72 "ERT, the Emacs Lisp regression testing tool."
76 (defface ert-test-result-expected
'((((class color
) (background light
))
78 (((class color
) (background dark
))
79 :background
"green3"))
80 "Face used for expected results in the ERT results buffer."
83 (defface ert-test-result-unexpected
'((((class color
) (background light
))
85 (((class color
) (background dark
))
87 "Face used for unexpected results in the ERT results buffer."
91 ;;; Copies/reimplementations of cl functions.
93 (defun ert-equal-including-properties (a b
)
94 "Return t if A and B have similar structure and contents.
96 This is like `equal-including-properties' except that it compares
97 the property values of text properties structurally (by
98 recursing) rather than with `eq'. Perhaps this is what
99 `equal-including-properties' should do in the first place; see
100 Emacs bug 6581 at URL `http://debbugs.gnu.org/cgi/bugreport.cgi?bug=6581'."
101 ;; This implementation is inefficient. Rather than making it
102 ;; efficient, let's hope bug 6581 gets fixed so that we can delete
104 (not (ert--explain-equal-including-properties a b
)))
107 ;;; Defining and locating tests.
109 ;; The data structure that represents a test case.
110 (cl-defstruct ert-test
113 (body (cl-assert nil
))
114 (most-recent-result nil
)
115 (expected-result-type ':passed
)
118 (defun ert-test-boundp (symbol)
119 "Return non-nil if SYMBOL names a test."
120 (and (get symbol
'ert--test
) t
))
122 (defun ert-get-test (symbol)
123 "If SYMBOL names a test, return that. Signal an error otherwise."
124 (unless (ert-test-boundp symbol
) (error "No test named `%S'" symbol
))
125 (get symbol
'ert--test
))
127 (defun ert-set-test (symbol definition
)
128 "Make SYMBOL name the test DEFINITION, and return DEFINITION."
129 (when (eq symbol
'nil
)
130 ;; We disallow nil since `ert-test-at-point' and related functions
131 ;; want to return a test name, but also need an out-of-band value
132 ;; on failure. Nil is the most natural out-of-band value; using 0
133 ;; or "" or signaling an error would be too awkward.
135 ;; Note that nil is still a valid value for the `name' slot in
136 ;; ert-test objects. It designates an anonymous test.
137 (error "Attempt to define a test named nil"))
138 (put symbol
'ert--test definition
)
139 ;; Register in load-history, so `symbol-file' can find us, and so
140 ;; unload-feature can unload our tests.
141 (cl-pushnew `(ert-deftest .
,symbol
) current-load-list
:test
#'equal
)
144 (cl-defmethod loadhist-unload-element ((x (head ert-deftest
)))
145 (let ((name (cdr x
)))
146 (put name
'ert--test nil
)))
148 (defun ert-make-test-unbound (symbol)
149 "Make SYMBOL name no test. Return SYMBOL."
150 (cl-remprop symbol
'ert--test
)
153 (defun ert--parse-keys-and-body (keys-and-body)
154 "Split KEYS-AND-BODY into keyword-and-value pairs and the remaining body.
156 KEYS-AND-BODY should have the form of a property list, with the
157 exception that only keywords are permitted as keys and that the
158 tail -- the body -- is a list of forms that does not start with a
161 Returns a two-element list containing the keys-and-values plist
163 (let ((extracted-key-accu '())
164 (remaining keys-and-body
))
165 (while (keywordp (car-safe remaining
))
166 (let ((keyword (pop remaining
)))
167 (unless (consp remaining
)
168 (error "Value expected after keyword %S in %S"
169 keyword keys-and-body
))
170 (when (assoc keyword extracted-key-accu
)
171 (warn "Keyword %S appears more than once in %S" keyword
173 (push (cons keyword
(pop remaining
)) extracted-key-accu
)))
174 (setq extracted-key-accu
(nreverse extracted-key-accu
))
175 (list (cl-loop for
(key . value
) in extracted-key-accu
181 (cl-defmacro ert-deftest
(name () &body docstring-keys-and-body
)
182 "Define NAME (a symbol) as a test.
184 BODY is evaluated as a `progn' when the test is run. It should
185 signal a condition on failure or just return if the test passes.
187 `should', `should-not', `should-error' and `skip-unless' are
188 useful for assertions in BODY.
190 Use `ert' to run tests interactively.
192 Tests that are expected to fail can be marked as such
193 using :expected-result. See `ert-test-result-type-p' for a
194 description of valid values for RESULT-TYPE.
196 \(fn NAME () [DOCSTRING] [:expected-result RESULT-TYPE] \
197 [:tags \\='(TAG...)] BODY...)"
198 (declare (debug (&define
:name test
199 name sexp
[&optional stringp
]
200 [&rest keywordp sexp
] def-body
))
203 (let ((documentation nil
)
204 (documentation-supplied-p nil
))
205 (when (stringp (car docstring-keys-and-body
))
206 (setq documentation
(pop docstring-keys-and-body
)
207 documentation-supplied-p t
))
208 (cl-destructuring-bind
209 ((&key
(expected-result nil expected-result-supplied-p
)
210 (tags nil tags-supplied-p
))
212 (ert--parse-keys-and-body docstring-keys-and-body
)
213 `(cl-macrolet ((skip-unless (form) `(ert--skip-unless ,form
)))
217 ,@(when documentation-supplied-p
218 `(:documentation
,documentation
))
219 ,@(when expected-result-supplied-p
220 `(:expected-result-type
,expected-result
))
221 ,@(when tags-supplied-p
223 :body
(lambda () ,@body
)))
226 ;; We use these `put' forms in addition to the (declare (indent)) in
227 ;; the defmacro form since the `declare' alone does not lead to
228 ;; correct indentation before the .el/.elc file is loaded.
229 ;; Autoloading these `put' forms solves this.
232 ;; TODO(ohler): Figure out what these mean and make sure they are correct.
233 (put 'ert-deftest
'lisp-indent-function
2)
234 (put 'ert-info
'lisp-indent-function
1))
236 (defvar ert--find-test-regexp
237 (concat "^\\s-*(ert-deftest"
238 find-function-space-re
240 "The regexp the `find-function' mechanisms use for finding test definitions.")
243 (define-error 'ert-test-failed
"Test failed")
244 (define-error 'ert-test-skipped
"Test skipped")
247 "Terminate the current test and mark it passed. Does not return."
248 (throw 'ert--pass nil
))
250 (defun ert-fail (data)
251 "Terminate the current test and mark it failed. Does not return.
252 DATA is displayed to the user and should state the reason of the failure."
253 (signal 'ert-test-failed
(list data
)))
255 (defun ert-skip (data)
256 "Terminate the current test and mark it skipped. Does not return.
257 DATA is displayed to the user and should state the reason for skipping."
258 (signal 'ert-test-skipped
(list data
)))
261 ;;; The `should' macros.
263 (defvar ert--should-execution-observer nil
)
265 (defun ert--signal-should-execution (form-description)
266 "Tell the current `should' form observer (if any) about FORM-DESCRIPTION."
267 (when ert--should-execution-observer
268 (funcall ert--should-execution-observer form-description
)))
270 (defun ert--special-operator-p (thing)
271 "Return non-nil if THING is a symbol naming a special operator."
273 (let ((definition (indirect-function thing
)))
274 (and (subrp definition
)
275 (eql (cdr (subr-arity definition
)) 'unevalled
)))))
277 (defun ert--expand-should-1 (whole form inner-expander
)
278 "Helper function for the `should' macro and its variants."
280 (macroexpand form
(append (bound-and-true-p
281 byte-compile-macro-environment
)
283 ((boundp 'macroexpand-all-environment
)
284 macroexpand-all-environment
)
285 ((boundp 'cl-macro-environment
)
286 cl-macro-environment
))))))
288 ((or (atom form
) (ert--special-operator-p (car form
)))
289 (let ((value (cl-gensym "value-")))
290 `(let ((,value
(cl-gensym "ert-form-evaluation-aborted-")))
291 ,(funcall inner-expander
293 `(list ',whole
:form
',form
:value
,value
)
297 (let ((fn-name (car form
))
298 (arg-forms (cdr form
)))
299 (cl-assert (or (symbolp fn-name
)
301 (eql (car fn-name
) 'lambda
)
302 (listp (cdr fn-name
)))))
303 (let ((fn (cl-gensym "fn-"))
304 (args (cl-gensym "args-"))
305 (value (cl-gensym "value-"))
306 (default-value (cl-gensym "ert-form-evaluation-aborted-")))
307 `(let ((,fn
(function ,fn-name
))
308 (,args
(list ,@arg-forms
)))
309 (let ((,value
',default-value
))
310 ,(funcall inner-expander
311 `(setq ,value
(apply ,fn
,args
))
312 `(nconc (list ',whole
)
313 (list :form
`(,,fn
,@,args
))
314 (unless (eql ,value
',default-value
)
315 (list :value
,value
))
317 (and (symbolp ',fn-name
)
318 (get ',fn-name
'ert-explainer
))))
321 (apply -explainer-
,args
)))))
325 (defun ert--expand-should (whole form inner-expander
)
326 "Helper function for the `should' macro and its variants.
328 Analyzes FORM and returns an expression that has the same
329 semantics under evaluation but records additional debugging
332 INNER-EXPANDER should be a function and is called with two
333 arguments: INNER-FORM and FORM-DESCRIPTION-FORM, where INNER-FORM
334 is an expression equivalent to FORM, and FORM-DESCRIPTION-FORM is
335 an expression that returns a description of FORM. INNER-EXPANDER
336 should return code that calls INNER-FORM and performs the checks
337 and error signaling specific to the particular variant of
338 `should'. The code that INNER-EXPANDER returns must not call
339 FORM-DESCRIPTION-FORM before it has called INNER-FORM."
340 (ert--expand-should-1
342 (lambda (inner-form form-description-form value-var
)
343 (let ((form-description (cl-gensym "form-description-")))
344 `(let (,form-description
)
345 ,(funcall inner-expander
348 (setq ,form-description
,form-description-form
)
349 (ert--signal-should-execution ,form-description
))
353 (cl-defmacro should
(form)
354 "Evaluate FORM. If it returns nil, abort the current test as failed.
356 Returns the value of FORM."
358 (ert--expand-should `(should ,form
) form
359 (lambda (inner-form form-description-form _value-var
)
361 (ert-fail ,form-description-form
)))))
363 (cl-defmacro should-not
(form)
364 "Evaluate FORM. If it returns non-nil, abort the current test as failed.
368 (ert--expand-should `(should-not ,form
) form
369 (lambda (inner-form form-description-form _value-var
)
370 `(unless (not ,inner-form
)
371 (ert-fail ,form-description-form
)))))
373 (defun ert--should-error-handle-error (form-description-fn
374 condition type exclude-subtypes
)
375 "Helper function for `should-error'.
377 Determines whether CONDITION matches TYPE and EXCLUDE-SUBTYPES,
378 and aborts the current test as failed if it doesn't."
379 (let ((signaled-conditions (get (car condition
) 'error-conditions
))
380 (handled-conditions (pcase-exhaustive type
382 ((pred symbolp
) (list type
)))))
383 (cl-assert signaled-conditions
)
384 (unless (cl-intersection signaled-conditions handled-conditions
)
386 (funcall form-description-fn
)
389 :fail-reason
(concat "the error signaled did not"
390 " have the expected type")))))
391 (when exclude-subtypes
392 (unless (member (car condition
) handled-conditions
)
394 (funcall form-description-fn
)
397 :fail-reason
(concat "the error signaled was a subtype"
398 " of the expected type"))))))))
400 ;; FIXME: The expansion will evaluate the keyword args (if any) in
401 ;; nonstandard order.
402 (cl-defmacro should-error
(form &rest keys
&key type exclude-subtypes
)
403 "Evaluate FORM and check that it signals an error.
405 The error signaled needs to match TYPE. TYPE should be a list
406 of condition names. (It can also be a non-nil symbol, which is
407 equivalent to a singleton list containing that symbol.) If
408 EXCLUDE-SUBTYPES is nil, the error matches TYPE if one of its
409 condition names is an element of TYPE. If EXCLUDE-SUBTYPES is
410 non-nil, the error matches TYPE if it is an element of TYPE.
412 If the error matches, returns (ERROR-SYMBOL . DATA) from the
413 error. If not, or if no error was signaled, abort the test as
416 (unless type
(setq type
''error
))
418 `(should-error ,form
,@keys
)
420 (lambda (inner-form form-description-form value-var
)
421 (let ((errorp (cl-gensym "errorp"))
422 (form-description-fn (cl-gensym "form-description-fn-")))
424 (,form-description-fn
(lambda () ,form-description-form
)))
425 (condition-case -condition-
427 ;; We can't use ,type here because we want to evaluate it.
430 (ert--should-error-handle-error ,form-description-fn
432 ,type
,exclude-subtypes
)
433 (setq ,value-var -condition-
)))
436 (funcall ,form-description-fn
)
438 :fail-reason
"did not signal an error")))))))))
440 (cl-defmacro ert--skip-unless
(form)
441 "Evaluate FORM. If it returns nil, skip the current test.
442 Errors during evaluation are caught and handled like nil."
444 (ert--expand-should `(skip-unless ,form
) form
445 (lambda (inner-form form-description-form _value-var
)
446 `(unless (ignore-errors ,inner-form
)
447 (ert-skip ,form-description-form
)))))
450 ;;; Explanation of `should' failures.
452 ;; TODO(ohler): Rework explanations so that they are displayed in a
453 ;; similar way to `ert-info' messages; in particular, allow text
454 ;; buttons in explanations that give more detail or open an ediff
455 ;; buffer. Perhaps explanations should be reported through `ert-info'
456 ;; rather than as part of the condition.
458 (defun ert--proper-list-p (x)
459 "Return non-nil if X is a proper list, nil otherwise."
461 for firstp
= t then nil
462 for fast
= x then
(cddr fast
)
463 for slow
= x then
(cdr slow
) do
464 (when (null fast
) (cl-return t
))
465 (when (not (consp fast
)) (cl-return nil
))
466 (when (null (cdr fast
)) (cl-return t
))
467 (when (not (consp (cdr fast
))) (cl-return nil
))
468 (when (and (not firstp
) (eq fast slow
)) (cl-return nil
))))
470 (defun ert--explain-format-atom (x)
471 "Format the atom X for `ert--explain-equal'."
473 ((pred characterp
) (list x
(format "#x%x" x
) (format "?%c" x
)))
474 ((pred integerp
) (list x
(format "#x%x" x
)))
477 (defun ert--explain-equal-rec (a b
)
478 "Return a programmer-readable explanation of why A and B are not `equal'.
479 Returns nil if they are."
480 (if (not (equal (type-of a
) (type-of b
)))
481 `(different-types ,a
,b
)
484 (let ((a-proper-p (ert--proper-list-p a
))
485 (b-proper-p (ert--proper-list-p b
)))
486 (if (not (eql (not a-proper-p
) (not b-proper-p
)))
487 `(one-list-proper-one-improper ,a
,b
)
489 (if (not (equal (length a
) (length b
)))
490 `(proper-lists-of-different-length ,(length a
) ,(length b
)
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 `(list-elt ,i
,xi
)))
499 finally
(cl-assert (equal a b
) t
)))
500 (let ((car-x (ert--explain-equal-rec (car a
) (car b
))))
503 (let ((cdr-x (ert--explain-equal-rec (cdr a
) (cdr b
))))
506 (cl-assert (equal a b
) t
)
509 (if (not (equal (length a
) (length b
)))
510 `(arrays-of-different-length ,(length a
) ,(length b
)
512 ,@(unless (char-table-p a
)
514 ,(cl-mismatch a b
:test
'equal
))))
515 (cl-loop for i from
0
518 for xi
= (ert--explain-equal-rec ai bi
)
519 do
(when xi
(cl-return `(array-elt ,i
,xi
)))
520 finally
(cl-assert (equal a b
) t
))))
522 (if (not (equal a b
))
523 (if (and (symbolp a
) (symbolp b
) (string= a b
))
524 `(different-symbols-with-the-same-name ,a
,b
)
525 `(different-atoms ,(ert--explain-format-atom a
)
526 ,(ert--explain-format-atom b
)))
529 (defun ert--explain-equal (a b
)
530 "Explainer function for `equal'."
531 ;; Do a quick comparison in C to avoid running our expensive
532 ;; comparison when possible.
535 (ert--explain-equal-rec a b
)))
536 (put 'equal
'ert-explainer
'ert--explain-equal
)
538 (defun ert--significant-plist-keys (plist)
539 "Return the keys of PLIST that have non-null values, in order."
540 (cl-assert (zerop (mod (length plist
) 2)) t
)
541 (cl-loop for
(key value . rest
) on plist by
#'cddr
542 unless
(or (null value
) (memq key accu
)) collect key into accu
543 finally
(cl-return accu
)))
545 (defun ert--plist-difference-explanation (a b
)
546 "Return a programmer-readable explanation of why A and B are different plists.
548 Returns nil if they are equivalent, i.e., have the same value for
549 each key, where absent values are treated as nil. The order of
550 key/value pairs in each list does not matter."
551 (cl-assert (zerop (mod (length a
) 2)) t
)
552 (cl-assert (zerop (mod (length b
) 2)) t
)
553 ;; Normalizing the plists would be another way to do this but it
554 ;; requires a total ordering on all lisp objects (since any object
555 ;; is valid as a text property key). Perhaps defining such an
556 ;; ordering is useful in other contexts, too, but it's a lot of
557 ;; work, so let's punt on it for now.
558 (let* ((keys-a (ert--significant-plist-keys a
))
559 (keys-b (ert--significant-plist-keys b
))
560 (keys-in-a-not-in-b (cl-set-difference keys-a keys-b
:test
'eq
))
561 (keys-in-b-not-in-a (cl-set-difference keys-b keys-a
:test
'eq
)))
562 (cl-flet ((explain-with-key (key)
563 (let ((value-a (plist-get a key
))
564 (value-b (plist-get b key
)))
565 (cl-assert (not (equal value-a value-b
)) t
)
566 `(different-properties-for-key
567 ,key
,(ert--explain-equal-including-properties value-a
569 (cond (keys-in-a-not-in-b
570 (explain-with-key (car keys-in-a-not-in-b
)))
572 (explain-with-key (car keys-in-b-not-in-a
)))
574 (cl-loop for key in keys-a
575 when
(not (equal (plist-get a key
) (plist-get b key
)))
576 return
(explain-with-key key
)))))))
578 (defun ert--abbreviate-string (s len suffixp
)
579 "Shorten string S to at most LEN chars.
581 If SUFFIXP is non-nil, returns a suffix of S, otherwise a prefix."
582 (let ((n (length s
)))
586 (substring s
(- n len
)))
588 (substring s
0 len
)))))
590 ;; TODO(ohler): Once bug 6581 is fixed, rename this to
591 ;; `ert--explain-equal-including-properties-rec' and add a fast-path
592 ;; wrapper like `ert--explain-equal'.
593 (defun ert--explain-equal-including-properties (a b
)
594 "Explainer function for `ert-equal-including-properties'.
596 Returns a programmer-readable explanation of why A and B are not
597 `ert-equal-including-properties', or nil if they are."
598 (if (not (equal a b
))
599 (ert--explain-equal a b
)
600 (cl-assert (stringp a
) t
)
601 (cl-assert (stringp b
) t
)
602 (cl-assert (eql (length a
) (length b
)) t
)
603 (cl-loop for i from
0 to
(length a
)
604 for props-a
= (text-properties-at i a
)
605 for props-b
= (text-properties-at i b
)
606 for difference
= (ert--plist-difference-explanation
609 (cl-return `(char ,i
,(substring-no-properties a i
(1+ i
))
612 ,(ert--abbreviate-string
613 (substring-no-properties a
0 i
)
616 ,(ert--abbreviate-string
617 (substring-no-properties a
(1+ i
))
619 ;; TODO(ohler): Get `equal-including-properties' fixed in
620 ;; Emacs, delete `ert-equal-including-properties', and
621 ;; re-enable this assertion.
622 ;;finally (cl-assert (equal-including-properties a b) t)
624 (put 'ert-equal-including-properties
626 'ert--explain-equal-including-properties
)
629 ;;; Implementation of `ert-info'.
631 ;; TODO(ohler): The name `info' clashes with
632 ;; `ert--test-execution-info'. One or both should be renamed.
633 (defvar ert--infos
'()
634 "The stack of `ert-info' infos that currently apply.
636 Bound dynamically. This is a list of (PREFIX . MESSAGE) pairs.")
638 (cl-defmacro ert-info
((message-form &key
((:prefix prefix-form
) "Info: "))
640 "Evaluate MESSAGE-FORM and BODY, and report the message if BODY fails.
642 To be used within ERT tests. MESSAGE-FORM should evaluate to a
643 string that will be displayed together with the test result if
644 the test fails. PREFIX-FORM should evaluate to a string as well
645 and is displayed in front of the value of MESSAGE-FORM."
646 (declare (debug ((form &rest
[sexp form
]) body
))
648 `(let ((ert--infos (cons (cons ,prefix-form
,message-form
) ert--infos
)))
653 ;;; Facilities for running a single test.
655 (defvar ert-debug-on-error nil
656 "Non-nil means enter debugger when a test fails or terminates with an error.")
658 ;; The data structures that represent the result of running a test.
659 (cl-defstruct ert-test-result
663 (cl-defstruct (ert-test-passed (:include ert-test-result
)))
664 (cl-defstruct (ert-test-result-with-condition (:include ert-test-result
))
665 (condition (cl-assert nil
))
666 (backtrace (cl-assert nil
))
667 (infos (cl-assert nil
)))
668 (cl-defstruct (ert-test-quit (:include ert-test-result-with-condition
)))
669 (cl-defstruct (ert-test-failed (:include ert-test-result-with-condition
)))
670 (cl-defstruct (ert-test-skipped (:include ert-test-result-with-condition
)))
671 (cl-defstruct (ert-test-aborted-with-non-local-exit
672 (:include ert-test-result
)))
674 (defun ert--print-backtrace (backtrace do-xrefs
)
675 "Format the backtrace BACKTRACE to the current buffer."
676 (let ((print-escape-newlines t
)
679 (debugger-insert-backtrace backtrace do-xrefs
)))
681 ;; A container for the state of the execution of a single test and
682 ;; environment data needed during its execution.
683 (cl-defstruct ert--test-execution-info
684 (test (cl-assert nil
))
685 (result (cl-assert nil
))
686 ;; A thunk that may be called when RESULT has been set to its final
687 ;; value and test execution should be terminated. Should not
689 (exit-continuation (cl-assert nil
))
690 ;; The binding of `debugger' outside of the execution of the test.
692 ;; The binding of `ert-debug-on-error' that is in effect for the
693 ;; execution of the current test. We store it to avoid being
694 ;; affected by any new bindings the test itself may establish. (I
695 ;; don't remember whether this feature is important.)
698 (defun ert--run-test-debugger (info args
)
699 "During a test run, `debugger' is bound to a closure that calls this function.
701 This function records failures and errors and either terminates
702 the test silently or calls the interactive debugger, as
705 INFO is the ert--test-execution-info corresponding to this test
706 run. ARGS are the arguments to `debugger'."
707 (cl-destructuring-bind (first-debugger-arg &rest more-debugger-args
)
709 (cl-ecase first-debugger-arg
710 ((lambda debug t exit nil
)
711 (apply (ert--test-execution-info-next-debugger info
) args
))
713 (let* ((condition (car more-debugger-args
))
714 (type (cl-case (car condition
)
716 ((ert-test-skipped) 'skipped
)
717 (otherwise 'failed
)))
718 ;; We store the backtrace in the result object for
719 ;; `ert-results-pop-to-backtrace-for-test-at-point'.
720 ;; This means we have to limit `print-level' and
721 ;; `print-length' when printing result objects. That
722 ;; might not be worth while when we can also use
723 ;; `ert-results-rerun-test-debugging-errors-at-point',
724 ;; (i.e., when running interactively) but having the
725 ;; backtrace ready for printing is important for batch
728 ;; Grab the frames starting from `signal', frames below
729 ;; that are all from the debugger.
730 (backtrace (backtrace-frames 'signal
))
731 (infos (reverse ert--infos
)))
732 (setf (ert--test-execution-info-result info
)
735 (make-ert-test-quit :condition condition
739 (make-ert-test-skipped :condition condition
743 (make-ert-test-failed :condition condition
746 ;; Work around Emacs's heuristic (in eval.c) for detecting
747 ;; errors in the debugger.
748 (cl-incf num-nonmacro-input-events
)
749 ;; FIXME: We should probably implement more fine-grained
750 ;; control a la non-t `debug-on-error' here.
752 ((ert--test-execution-info-ert-debug-on-error info
)
753 (apply (ert--test-execution-info-next-debugger info
) args
))
755 (funcall (ert--test-execution-info-exit-continuation info
)))))))
757 (defun ert--run-test-internal (test-execution-info)
758 "Low-level function to run a test according to TEST-EXECUTION-INFO.
760 This mainly sets up debugger-related bindings."
761 (setf (ert--test-execution-info-next-debugger test-execution-info
) debugger
762 (ert--test-execution-info-ert-debug-on-error test-execution-info
)
765 ;; For now, each test gets its own temp buffer and its own
766 ;; window excursion, just to be safe. If this turns out to be
767 ;; too expensive, we can remove it.
769 (save-window-excursion
770 (let ((debugger (lambda (&rest args
)
771 (ert--run-test-debugger test-execution-info
775 ;; FIXME: Do we need to store the old binding of this
776 ;; and consider it in `ert--run-test-debugger'?
777 (debug-ignored-errors nil
)
779 (funcall (ert-test-body (ert--test-execution-info-test
780 test-execution-info
))))))
782 (setf (ert--test-execution-info-result test-execution-info
)
783 (make-ert-test-passed))
786 (defun ert--force-message-log-buffer-truncation ()
787 "Immediately truncate *Messages* buffer according to `message-log-max'.
789 This can be useful after reducing the value of `message-log-max'."
790 (with-current-buffer (messages-buffer)
791 ;; This is a reimplementation of this part of message_dolog() in xdisp.c:
792 ;; if (NATNUMP (Vmessage_log_max))
794 ;; scan_newline (Z, Z_BYTE, BEG, BEG_BYTE,
795 ;; -XFASTINT (Vmessage_log_max) - 1, 0);
796 ;; del_range_both (BEG, BEG_BYTE, PT, PT_BYTE, 0);
798 (when (and (integerp message-log-max
) (>= message-log-max
0))
799 (let ((begin (point-min))
801 (goto-char (point-max))
802 (forward-line (- message-log-max
))
804 (inhibit-read-only t
))
805 (delete-region begin end
)))))
807 (defvar ert--running-tests nil
808 "List of tests that are currently in execution.
810 This list is empty while no test is running, has one element
811 while a test is running, two elements while a test run from
812 inside a test is running, etc. The list is in order of nesting,
813 innermost test first.
815 The elements are of type `ert-test'.")
817 (defun ert-run-test (ert-test)
820 Returns the result and stores it in ERT-TEST's `most-recent-result' slot."
821 (setf (ert-test-most-recent-result ert-test
) nil
)
824 (with-current-buffer (messages-buffer)
825 (point-max-marker))))
827 (let ((info (make-ert--test-execution-info
830 (make-ert-test-aborted-with-non-local-exit)
831 :exit-continuation
(lambda ()
832 (cl-return-from error nil
))))
833 (should-form-accu (list)))
835 (let ((ert--should-execution-observer
836 (lambda (form-description)
837 (push form-description should-form-accu
)))
839 (ert--running-tests (cons ert-test ert--running-tests
)))
840 (ert--run-test-internal info
))
841 (let ((result (ert--test-execution-info-result info
)))
842 (setf (ert-test-result-messages result
)
843 (with-current-buffer (messages-buffer)
844 (buffer-substring begin-marker
(point-max))))
845 (ert--force-message-log-buffer-truncation)
846 (setq should-form-accu
(nreverse should-form-accu
))
847 (setf (ert-test-result-should-forms result
)
849 (setf (ert-test-most-recent-result ert-test
) result
))))
850 (set-marker begin-marker nil
))))
851 (ert-test-most-recent-result ert-test
))
853 (defun ert-running-test ()
854 "Return the top-level test currently executing."
855 (car (last ert--running-tests
)))
860 (defun ert-test-result-type-p (result result-type
)
861 "Return non-nil if RESULT matches type RESULT-TYPE.
865 nil -- Never matches.
867 :failed, :passed, :skipped -- Matches corresponding results.
868 \(and TYPES...) -- Matches if all TYPES match.
869 \(or TYPES...) -- Matches if some TYPES match.
870 \(not TYPE) -- Matches if TYPE does not match.
871 \(satisfies PREDICATE) -- Matches if PREDICATE returns true when called with
873 ;; It would be easy to add `member' and `eql' types etc., but I
874 ;; haven't bothered yet.
875 (pcase-exhaustive result-type
878 (:failed
(ert-test-failed-p result
))
879 (:passed
(ert-test-passed-p result
))
880 (:skipped
(ert-test-skipped-p result
))
881 (`(,operator .
,operands
)
884 (cl-case (length operands
)
887 (and (ert-test-result-type-p result
(car operands
))
888 (ert-test-result-type-p result
`(and ,@(cdr operands
)))))))
890 (cl-case (length operands
)
893 (or (ert-test-result-type-p result
(car operands
))
894 (ert-test-result-type-p result
`(or ,@(cdr operands
)))))))
896 (cl-assert (eql (length operands
) 1))
897 (not (ert-test-result-type-p result
(car operands
))))
899 (cl-assert (eql (length operands
) 1))
900 (funcall (car operands
) result
))))))
902 (defun ert-test-result-expected-p (test result
)
903 "Return non-nil if TEST's expected result type matches RESULT."
905 (ert-test-result-type-p result
:skipped
)
906 (ert-test-result-type-p result
(ert-test-expected-result-type test
))))
908 (defun ert-select-tests (selector universe
)
909 "Return a list of tests that match SELECTOR.
911 UNIVERSE specifies the set of tests to select from; it should be a list
912 of tests, or t, which refers to all tests named by symbols in `obarray'.
916 nil -- Selects the empty set.
917 t -- Selects UNIVERSE.
918 :new -- Selects all tests that have not been run yet.
919 :failed, :passed -- Select tests according to their most recent result.
920 :expected, :unexpected -- Select tests according to their most recent result.
921 a string -- A regular expression selecting all tests with matching names.
922 a test -- (i.e., an object of the ert-test data-type) Selects that test.
923 a symbol -- Selects the test that the symbol names, errors if none.
924 \(member TESTS...) -- Selects the elements of TESTS, a list of tests
925 or symbols naming tests.
926 \(eql TEST) -- Selects TEST, a test or a symbol naming a test.
927 \(and SELECTORS...) -- Selects the tests that match all SELECTORS.
928 \(or SELECTORS...) -- Selects the tests that match any of the SELECTORS.
929 \(not SELECTOR) -- Selects all tests that do not match SELECTOR.
930 \(tag TAG) -- Selects all tests that have TAG on their tags list.
931 A tag is an arbitrary label you can apply when you define a test.
932 \(satisfies PREDICATE) -- Selects all tests that satisfy PREDICATE.
933 PREDICATE is a function that takes an ert-test object as argument,
934 and returns non-nil if it is selected.
936 Only selectors that require a superset of tests, such
937 as (satisfies ...), strings, :new, etc. make use of UNIVERSE.
938 Selectors that do not, such as (member ...), just return the
939 set implied by them without checking whether it is really
940 contained in UNIVERSE."
941 ;; This code needs to match the cases in
942 ;; `ert-insert-human-readable-selector'.
943 (pcase-exhaustive selector
945 ('t
(pcase-exhaustive universe
946 ((pred listp
) universe
)
947 (`t
(ert-select-tests "" universe
))))
948 (:new
(ert-select-tests
949 `(satisfies ,(lambda (test)
950 (null (ert-test-most-recent-result test
))))
952 (:failed
(ert-select-tests
953 `(satisfies ,(lambda (test)
954 (ert-test-result-type-p
955 (ert-test-most-recent-result test
)
958 (:passed
(ert-select-tests
959 `(satisfies ,(lambda (test)
960 (ert-test-result-type-p
961 (ert-test-most-recent-result test
)
964 (:expected
(ert-select-tests
967 (ert-test-result-expected-p
969 (ert-test-most-recent-result test
))))
971 (:unexpected
(ert-select-tests `(not :expected
) universe
))
973 (pcase-exhaustive universe
974 (`t
(mapcar #'ert-get-test
975 (apropos-internal selector
#'ert-test-boundp
)))
977 (cl-remove-if-not (lambda (test)
978 (and (ert-test-name test
)
979 (string-match selector
981 (ert-test-name test
)))))
983 ((pred ert-test-p
) (list selector
))
985 (cl-assert (ert-test-boundp selector
))
986 (list (ert-get-test selector
)))
987 (`(,operator .
,operands
)
990 (mapcar (lambda (purported-test)
991 (pcase-exhaustive purported-test
993 (cl-assert (ert-test-boundp purported-test
))
994 (ert-get-test purported-test
))
995 ((pred ert-test-p
) purported-test
)))
998 (cl-assert (eql (length operands
) 1))
999 (ert-select-tests `(member ,@operands
) universe
))
1001 ;; Do these definitions of AND, NOT and OR satisfy de
1002 ;; Morgan's laws? Should they?
1003 (cl-case (length operands
)
1004 (0 (ert-select-tests 't universe
))
1005 (t (ert-select-tests `(and ,@(cdr operands
))
1006 (ert-select-tests (car operands
)
1009 (cl-assert (eql (length operands
) 1))
1010 (let ((all-tests (ert-select-tests 't universe
)))
1011 (cl-set-difference all-tests
1012 (ert-select-tests (car operands
)
1015 (cl-case (length operands
)
1016 (0 (ert-select-tests 'nil universe
))
1017 (t (cl-union (ert-select-tests (car operands
) universe
)
1018 (ert-select-tests `(or ,@(cdr operands
))
1021 (cl-assert (eql (length operands
) 1))
1022 (let ((tag (car operands
)))
1023 (ert-select-tests `(satisfies
1025 (member tag
(ert-test-tags test
))))
1028 (cl-assert (eql (length operands
) 1))
1029 (cl-remove-if-not (car operands
)
1030 (ert-select-tests 't universe
)))))))
1032 (defun ert--insert-human-readable-selector (selector)
1033 "Insert a human-readable presentation of SELECTOR into the current buffer."
1034 ;; This is needed to avoid printing the (huge) contents of the
1035 ;; `backtrace' slot of the result objects in the
1036 ;; `most-recent-result' slots of test case objects in (eql ...) or
1037 ;; (member ...) selectors.
1038 (cl-labels ((rec (selector)
1039 ;; This code needs to match the cases in
1040 ;; `ert-select-tests'.
1041 (pcase-exhaustive selector
1043 ;; 'nil 't :new :failed :passed :expected :unexpected
1048 (if (ert-test-name selector
)
1049 (make-symbol (format "<%S>" (ert-test-name selector
)))
1050 (make-symbol "<unnamed test>")))
1051 (`(,operator .
,operands
)
1053 ((or 'member
'eql
'and
'not
'or
)
1054 `(,operator
,@(mapcar #'rec operands
)))
1055 ((or 'tag
'satisfies
)
1057 (insert (format "%S" (rec selector
)))))
1060 ;;; Facilities for running a whole set of tests.
1062 ;; The data structure that contains the set of tests being executed
1063 ;; during one particular test run, their results, the state of the
1064 ;; execution, and some statistics.
1066 ;; The data about results and expected results of tests may seem
1067 ;; redundant here, since the test objects also carry such information.
1068 ;; However, the information in the test objects may be more recent, it
1069 ;; may correspond to a different test run. We need the information
1070 ;; that corresponds to this run in order to be able to update the
1071 ;; statistics correctly when a test is re-run interactively and has a
1072 ;; different result than before.
1073 (cl-defstruct ert--stats
1074 (selector (cl-assert nil
))
1075 ;; The tests, in order.
1076 (tests (cl-assert nil
) :type vector
)
1077 ;; A map of test names (or the test objects themselves for unnamed
1078 ;; tests) to indices into the `tests' vector.
1079 (test-map (cl-assert nil
) :type hash-table
)
1080 ;; The results of the tests during this run, in order.
1081 (test-results (cl-assert nil
) :type vector
)
1082 ;; The start times of the tests, in order, as reported by
1084 (test-start-times (cl-assert nil
) :type vector
)
1085 ;; The end times of the tests, in order, as reported by
1087 (test-end-times (cl-assert nil
) :type vector
)
1089 (passed-unexpected 0)
1091 (failed-unexpected 0)
1097 ;; The time at or after which the next redisplay should occur, as a
1099 (next-redisplay 0.0))
1101 (defun ert-stats-completed-expected (stats)
1102 "Return the number of tests in STATS that had expected results."
1103 (+ (ert--stats-passed-expected stats
)
1104 (ert--stats-failed-expected stats
)))
1106 (defun ert-stats-completed-unexpected (stats)
1107 "Return the number of tests in STATS that had unexpected results."
1108 (+ (ert--stats-passed-unexpected stats
)
1109 (ert--stats-failed-unexpected stats
)))
1111 (defun ert-stats-skipped (stats)
1112 "Number of tests in STATS that have skipped."
1113 (ert--stats-skipped stats
))
1115 (defun ert-stats-completed (stats)
1116 "Number of tests in STATS that have run so far."
1117 (+ (ert-stats-completed-expected stats
)
1118 (ert-stats-completed-unexpected stats
)
1119 (ert-stats-skipped stats
)))
1121 (defun ert-stats-total (stats)
1122 "Number of tests in STATS, regardless of whether they have run yet."
1123 (length (ert--stats-tests stats
)))
1125 ;; The stats object of the current run, dynamically bound. This is
1126 ;; used for the mode line progress indicator.
1127 (defvar ert--current-run-stats nil
)
1129 (defun ert--stats-test-key (test)
1130 "Return the key used for TEST in the test map of ert--stats objects.
1132 Returns the name of TEST if it has one, or TEST itself otherwise."
1133 (or (ert-test-name test
) test
))
1135 (defun ert--stats-set-test-and-result (stats pos test result
)
1136 "Change STATS by replacing the test at position POS with TEST and RESULT.
1138 Also changes the counters in STATS to match."
1139 (let* ((tests (ert--stats-tests stats
))
1140 (results (ert--stats-test-results stats
))
1141 (old-test (aref tests pos
))
1142 (map (ert--stats-test-map stats
)))
1143 (cl-flet ((update (d)
1144 (if (ert-test-result-expected-p (aref tests pos
)
1146 (cl-etypecase (aref results pos
)
1148 (cl-incf (ert--stats-passed-expected stats
) d
))
1150 (cl-incf (ert--stats-failed-expected stats
) d
))
1152 (cl-incf (ert--stats-skipped stats
) d
))
1154 (ert-test-aborted-with-non-local-exit)
1156 (cl-etypecase (aref results pos
)
1158 (cl-incf (ert--stats-passed-unexpected stats
) d
))
1160 (cl-incf (ert--stats-failed-unexpected stats
) d
))
1162 (cl-incf (ert--stats-skipped stats
) d
))
1164 (ert-test-aborted-with-non-local-exit)
1166 ;; Adjust counters to remove the result that is currently in stats.
1168 ;; Put new test and result into stats.
1169 (setf (aref tests pos
) test
1170 (aref results pos
) result
)
1171 (remhash (ert--stats-test-key old-test
) map
)
1172 (setf (gethash (ert--stats-test-key test
) map
) pos
)
1173 ;; Adjust counters to match new result.
1177 (defun ert--make-stats (tests selector
)
1178 "Create a new `ert--stats' object for running TESTS.
1180 SELECTOR is the selector that was used to select TESTS."
1181 (setq tests
(cl-coerce tests
'vector
))
1182 (let ((map (make-hash-table :size
(length tests
))))
1183 (cl-loop for i from
0
1184 for test across tests
1185 for key
= (ert--stats-test-key test
) do
1186 (cl-assert (not (gethash key map
)))
1187 (setf (gethash key map
) i
))
1188 (make-ert--stats :selector selector
1191 :test-results
(make-vector (length tests
) nil
)
1192 :test-start-times
(make-vector (length tests
) nil
)
1193 :test-end-times
(make-vector (length tests
) nil
))))
1195 (defun ert-run-or-rerun-test (stats test listener
)
1196 ;; checkdoc-order: nil
1197 "Run the single test TEST and record the result using STATS and LISTENER."
1198 (let ((ert--current-run-stats stats
)
1199 (pos (ert--stats-test-pos stats test
)))
1200 (ert--stats-set-test-and-result stats pos test nil
)
1201 ;; Call listener after setting/before resetting
1202 ;; (ert--stats-current-test stats); the listener might refresh the
1203 ;; mode line display, and if the value is not set yet/any more
1204 ;; during this refresh, the mode line will flicker unnecessarily.
1205 (setf (ert--stats-current-test stats
) test
)
1206 (funcall listener
'test-started stats test
)
1207 (setf (ert-test-most-recent-result test
) nil
)
1208 (setf (aref (ert--stats-test-start-times stats
) pos
) (current-time))
1211 (setf (aref (ert--stats-test-end-times stats
) pos
) (current-time))
1212 (let ((result (ert-test-most-recent-result test
)))
1213 (ert--stats-set-test-and-result stats pos test result
)
1214 (funcall listener
'test-ended stats test result
))
1215 (setf (ert--stats-current-test stats
) nil
))))
1217 (defun ert-run-tests (selector listener
&optional interactively
)
1218 "Run the tests specified by SELECTOR, sending progress updates to LISTENER."
1219 (let* ((tests (ert-select-tests selector t
))
1220 (stats (ert--make-stats tests selector
)))
1221 (setf (ert--stats-start-time stats
) (current-time))
1222 (funcall listener
'run-started stats
)
1225 (let ((ert--current-run-stats stats
))
1226 (force-mode-line-update)
1228 (cl-loop for test in tests do
1229 (ert-run-or-rerun-test stats test listener
)
1230 (when (and interactively
1232 (ert-test-most-recent-result test
))
1233 (y-or-n-p "Abort testing? "))
1235 finally
(setq abortedp nil
))
1236 (setf (ert--stats-aborted-p stats
) abortedp
)
1237 (setf (ert--stats-end-time stats
) (current-time))
1238 (funcall listener
'run-ended stats abortedp
)))
1239 (force-mode-line-update))
1242 (defun ert--stats-test-pos (stats test
)
1243 ;; checkdoc-order: nil
1244 "Return the position (index) of TEST in the run represented by STATS."
1245 (gethash (ert--stats-test-key test
) (ert--stats-test-map stats
)))
1248 ;;; Formatting functions shared across UIs.
1250 (defun ert--format-time-iso8601 (time)
1251 "Format TIME in the variant of ISO 8601 used for timestamps in ERT."
1252 (format-time-string "%Y-%m-%d %T%z" time
))
1254 (defun ert-char-for-test-result (result expectedp
)
1255 "Return a character that represents the test result RESULT.
1257 EXPECTEDP specifies whether the result was expected."
1258 (let ((s (cl-etypecase result
1259 (ert-test-passed ".P")
1260 (ert-test-failed "fF")
1261 (ert-test-skipped "sS")
1263 (ert-test-aborted-with-non-local-exit "aA")
1264 (ert-test-quit "qQ"))))
1265 (elt s
(if expectedp
0 1))))
1267 (defun ert-string-for-test-result (result expectedp
)
1268 "Return a string that represents the test result RESULT.
1270 EXPECTEDP specifies whether the result was expected."
1271 (let ((s (cl-etypecase result
1272 (ert-test-passed '("passed" "PASSED"))
1273 (ert-test-failed '("failed" "FAILED"))
1274 (ert-test-skipped '("skipped" "SKIPPED"))
1275 (null '("unknown" "UNKNOWN"))
1276 (ert-test-aborted-with-non-local-exit '("aborted" "ABORTED"))
1277 (ert-test-quit '("quit" "QUIT")))))
1278 (elt s
(if expectedp
0 1))))
1280 (defun ert--pp-with-indentation-and-newline (object)
1281 "Pretty-print OBJECT, indenting it to the current column of point.
1282 Ensures a final newline is inserted."
1283 (let ((begin (point))
1284 (pp-escape-newlines nil
))
1285 (pp object
(current-buffer))
1286 (unless (bolp) (insert "\n"))
1291 (defun ert--insert-infos (result)
1292 "Insert `ert-info' infos from RESULT into current buffer.
1294 RESULT must be an `ert-test-result-with-condition'."
1295 (cl-check-type result ert-test-result-with-condition
)
1296 (dolist (info (ert-test-result-with-condition-infos result
))
1297 (cl-destructuring-bind (prefix . message
) info
1298 (let ((begin (point))
1299 (indentation (make-string (+ (length prefix
) 4) ?\s
))
1303 (insert message
"\n")
1304 (setq end
(point-marker))
1308 (while (< (point) end
)
1309 (insert indentation
)
1311 (when end
(set-marker end nil
)))))))
1314 ;;; Running tests in batch mode.
1316 (defvar ert-batch-backtrace-right-margin
70
1317 "The maximum line length for printing backtraces in `ert-run-tests-batch'.")
1320 (defun ert-run-tests-batch (&optional selector
)
1321 "Run the tests specified by SELECTOR, printing results to the terminal.
1323 SELECTOR works as described in `ert-select-tests', except if
1324 SELECTOR is nil, in which case all tests rather than none will be
1325 run; this makes the command line \"emacs -batch -l my-tests.el -f
1326 ert-run-tests-batch-and-exit\" useful.
1328 Returns the stats object."
1329 (unless selector
(setq selector
't
))
1332 (lambda (event-type &rest event-args
)
1333 (cl-ecase event-type
1335 (cl-destructuring-bind (stats) event-args
1336 (message "Running %s tests (%s)"
1337 (length (ert--stats-tests stats
))
1338 (ert--format-time-iso8601 (ert--stats-start-time stats
)))))
1340 (cl-destructuring-bind (stats abortedp
) event-args
1341 (let ((unexpected (ert-stats-completed-unexpected stats
))
1342 (skipped (ert-stats-skipped stats
))
1343 (expected-failures (ert--stats-failed-expected stats
)))
1344 (message "\n%sRan %s tests, %s results as expected%s%s (%s)%s\n"
1348 (ert-stats-total stats
)
1349 (ert-stats-completed-expected stats
)
1350 (if (zerop unexpected
)
1352 (format ", %s unexpected" unexpected
))
1355 (format ", %s skipped" skipped
))
1356 (ert--format-time-iso8601 (ert--stats-end-time stats
))
1357 (if (zerop expected-failures
)
1359 (format "\n%s expected failures" expected-failures
)))
1360 (unless (zerop unexpected
)
1361 (message "%s unexpected results:" unexpected
)
1362 (cl-loop for test across
(ert--stats-tests stats
)
1363 for result
= (ert-test-most-recent-result test
) do
1364 (when (not (ert-test-result-expected-p test result
))
1366 (ert-string-for-test-result result nil
)
1367 (ert-test-name test
))))
1369 (unless (zerop skipped
)
1370 (message "%s skipped results:" skipped
)
1371 (cl-loop for test across
(ert--stats-tests stats
)
1372 for result
= (ert-test-most-recent-result test
) do
1373 (when (ert-test-result-type-p result
:skipped
)
1375 (ert-string-for-test-result result nil
)
1376 (ert-test-name test
))))
1377 (message "%s" "")))))
1381 (cl-destructuring-bind (stats test result
) event-args
1382 (unless (ert-test-result-expected-p test result
)
1383 (cl-etypecase result
1385 (message "Test %S passed unexpectedly" (ert-test-name test
)))
1386 (ert-test-result-with-condition
1387 (message "Test %S backtrace:" (ert-test-name test
))
1389 (ert--print-backtrace
1390 (ert-test-result-with-condition-backtrace result
)
1392 (goto-char (point-min))
1394 (let ((start (point))
1395 (end (progn (end-of-line) (point))))
1397 (+ start ert-batch-backtrace-right-margin
)))
1398 (message "%s" (buffer-substring-no-properties
1402 (ert--insert-infos result
)
1404 (let ((print-escape-newlines t
)
1407 (ert--pp-with-indentation-and-newline
1408 (ert-test-result-with-condition-condition result
)))
1409 (goto-char (1- (point-max)))
1410 (cl-assert (looking-at "\n"))
1412 (message "Test %S condition:" (ert-test-name test
))
1413 (message "%s" (buffer-string))))
1414 (ert-test-aborted-with-non-local-exit
1415 (message "Test %S aborted with non-local exit"
1416 (ert-test-name test
)))
1418 (message "Quit during %S" (ert-test-name test
)))))
1419 (let* ((max (prin1-to-string (length (ert--stats-tests stats
))))
1420 (format-string (concat "%9s %"
1421 (prin1-to-string (length max
))
1423 (message format-string
1424 (ert-string-for-test-result result
1425 (ert-test-result-expected-p
1427 (1+ (ert--stats-test-pos stats test
))
1428 (ert-test-name test
)))))))
1432 (defun ert-run-tests-batch-and-exit (&optional selector
)
1433 "Like `ert-run-tests-batch', but exits Emacs when done.
1435 The exit status will be 0 if all test results were as expected, 1
1436 on unexpected results, or 2 if the tool detected an error outside
1437 of the tests (e.g. invalid SELECTOR or bug in the code that runs
1440 (user-error "This function is only for use in batch mode"))
1441 ;; Better crash loudly than attempting to recover from undefined
1443 (setq attempt-stack-overflow-recovery nil
1444 attempt-orderly-shutdown-on-fatal-signal nil
)
1446 (let ((stats (ert-run-tests-batch selector
)))
1447 (kill-emacs (if (zerop (ert-stats-completed-unexpected stats
)) 0 1)))
1450 (message "Error running tests")
1455 (defun ert-summarize-tests-batch-and-exit ()
1456 "Summarize the results of testing.
1457 Expects to be called in batch mode, with logfiles as command-line arguments.
1458 The logfiles should have the `ert-run-tests-batch' format. When finished,
1459 this exits Emacs, with status as per `ert-run-tests-batch-and-exit'."
1461 (user-error "This function is only for use in batch mode"))
1462 ;; Better crash loudly than attempting to recover from undefined
1464 (setq attempt-stack-overflow-recovery nil
1465 attempt-orderly-shutdown-on-fatal-signal nil
)
1466 (let ((nlogs (length command-line-args-left
))
1467 (ntests 0) (nrun 0) (nexpected 0) (nunexpected 0) (nskipped 0)
1468 nnotrun logfile notests badtests unexpected skipped
)
1470 (while (setq logfile
(pop command-line-args-left
))
1472 (when (file-readable-p logfile
) (insert-file-contents logfile
))
1473 (if (not (re-search-forward "^Running \\([0-9]+\\) tests" nil t
))
1474 (push logfile notests
)
1475 (setq ntests
(+ ntests
(string-to-number (match-string 1))))
1476 (if (not (re-search-forward "^\\(Aborted: \\)?\
1477 Ran \\([0-9]+\\) tests, \\([0-9]+\\) results as expected\
1478 \\(?:, \\([0-9]+\\) unexpected\\)?\
1479 \\(?:, \\([0-9]+\\) skipped\\)?" nil t
))
1480 (push logfile badtests
)
1481 (if (match-string 1) (push logfile badtests
))
1482 (setq nrun
(+ nrun
(string-to-number (match-string 2)))
1483 nexpected
(+ nexpected
(string-to-number (match-string 3))))
1484 (when (match-string 4)
1485 (push logfile unexpected
)
1486 (setq nunexpected
(+ nunexpected
1487 (string-to-number (match-string 4)))))
1488 (when (match-string 5)
1489 (push logfile skipped
)
1490 (setq nskipped
(+ nskipped
1491 (string-to-number (match-string 5)))))))))
1492 (setq nnotrun
(- ntests nrun
))
1493 (message "\nSUMMARY OF TEST RESULTS")
1494 (message "-----------------------")
1495 (message "Files examined: %d" nlogs
)
1496 (message "Ran %d tests%s, %d results as expected%s%s"
1498 (if (zerop nnotrun
) "" (format ", %d failed to run" nnotrun
))
1500 (if (zerop nunexpected
)
1502 (format ", %d unexpected" nunexpected
))
1503 (if (zerop nskipped
)
1505 (format ", %d skipped" nskipped
)))
1507 (message "%d files did not contain any tests:" (length notests
))
1508 (mapc (lambda (l) (message " %s" l
)) notests
))
1510 (message "%d files did not finish:" (length badtests
))
1511 (mapc (lambda (l) (message " %s" l
)) badtests
))
1513 (message "%d files contained unexpected results:" (length unexpected
))
1514 (mapc (lambda (l) (message " %s" l
)) unexpected
))
1515 ;; More details on hydra, where the logs are harder to get to.
1516 (when (and (getenv "EMACS_HYDRA_CI")
1517 (not (zerop (+ nunexpected nskipped
))))
1518 (message "\nDETAILS")
1521 (dolist (x (list (list skipped
"skipped" "SKIPPED")
1522 (list unexpected
"unexpected" "FAILED")))
1525 (insert-file-contents l
)
1527 (when (re-search-forward (format "^[ \t]*[0-9]+ %s results:"
1530 (while (and (zerop (forward-line 1))
1531 (looking-at (format "^[ \t]*%s" (nth 2 x
))))
1532 (message "%s" (buffer-substring (line-beginning-position)
1533 (line-end-position))))))
1535 (kill-emacs (cond ((or notests badtests
(not (zerop nnotrun
))) 2)
1539 ;;; Utility functions for load/unload actions.
1541 (defun ert--activate-font-lock-keywords ()
1542 "Activate font-lock keywords for some of ERT's symbols."
1543 (font-lock-add-keywords
1545 '(("(\\(\\<ert-deftest\\)\\>\\s *\\(\\(?:\\sw\\|\\s_\\)+\\)?"
1546 (1 font-lock-keyword-face nil t
)
1547 (2 font-lock-function-name-face nil t
)))))
1549 (cl-defun ert--remove-from-list (list-var element
&key key test
)
1550 "Remove ELEMENT from the value of LIST-VAR if present.
1552 This can be used as an inverse of `add-to-list'."
1553 (unless key
(setq key
#'identity
))
1554 (unless test
(setq test
#'equal
))
1555 (setf (symbol-value list-var
)
1557 (symbol-value list-var
)
1562 ;;; Some basic interactive functions.
1564 (defun ert-read-test-name (prompt &optional default history
1565 add-default-to-prompt
)
1566 "Read the name of a test and return it as a symbol.
1568 Prompt with PROMPT. If DEFAULT is a valid test name, use it as a
1569 default. HISTORY is the history to use; see `completing-read'.
1570 If ADD-DEFAULT-TO-PROMPT is non-nil, PROMPT will be modified to
1571 include the default, if any.
1573 Signals an error if no test name was read."
1574 (cl-etypecase default
1575 (string (let ((symbol (intern-soft default
)))
1576 (unless (and symbol
(ert-test-boundp symbol
))
1577 (setq default nil
))))
1578 (symbol (setq default
1579 (if (ert-test-boundp default
)
1580 (symbol-name default
)
1582 (ert-test (setq default
(ert-test-name default
))))
1583 (when add-default-to-prompt
1584 (setq prompt
(if (null default
)
1585 (format "%s: " prompt
)
1586 (format "%s (default %s): " prompt default
))))
1587 (let ((input (completing-read prompt obarray
#'ert-test-boundp
1588 t nil history default nil
)))
1589 ;; completing-read returns an empty string if default was nil and
1590 ;; the user just hit enter.
1591 (let ((sym (intern-soft input
)))
1592 (if (ert-test-boundp sym
)
1594 (user-error "Input does not name a test")))))
1596 (defun ert-read-test-name-at-point (prompt)
1597 "Read the name of a test and return it as a symbol.
1598 As a default, use the symbol at point, or the test at point if in
1599 the ERT results buffer. Prompt with PROMPT, augmented with the
1601 (ert-read-test-name prompt
(ert-test-at-point) nil t
))
1603 (defun ert-find-test-other-window (test-name)
1604 "Find, in another window, the definition of TEST-NAME."
1605 (interactive (list (ert-read-test-name-at-point "Find test definition: ")))
1606 (find-function-do-it test-name
'ert-deftest
'switch-to-buffer-other-window
))
1608 (defun ert-delete-test (test-name)
1609 "Make the test TEST-NAME unbound.
1611 Nothing more than an interactive interface to `ert-make-test-unbound'."
1612 (interactive (list (ert-read-test-name-at-point "Delete test")))
1613 (ert-make-test-unbound test-name
))
1615 (defun ert-delete-all-tests ()
1616 "Make all symbols in `obarray' name no test."
1618 (when (called-interactively-p 'any
)
1619 (unless (y-or-n-p "Delete all tests? ")
1620 (user-error "Aborted")))
1621 ;; We can't use `ert-select-tests' here since that gives us only
1622 ;; test objects, and going from them back to the test name symbols
1623 ;; can fail if the `ert-test' defstruct has been redefined.
1624 (mapc #'ert-make-test-unbound
(apropos-internal "" #'ert-test-boundp
))
1628 ;;; Display of test progress and results.
1630 ;; An entry in the results buffer ewoc. There is one entry per test.
1631 (cl-defstruct ert--ewoc-entry
1632 (test (cl-assert nil
))
1633 ;; If the result of this test was expected, its ewoc entry is hidden
1635 (hidden-p (cl-assert nil
))
1636 ;; An ewoc entry may be collapsed to hide details such as the error
1639 ;; I'm not sure the ability to expand and collapse entries is still
1640 ;; a useful feature.
1642 ;; By default, the ewoc entry presents the error condition with
1643 ;; certain limits on how much to print (`print-level',
1644 ;; `print-length'). The user can interactively switch to a set of
1646 (extended-printer-limits-p nil
))
1648 ;; Variables local to the results buffer.
1651 (defvar ert--results-ewoc
)
1652 ;; The stats object.
1653 (defvar ert--results-stats
)
1654 ;; A string with one character per test. Each character represents
1655 ;; the result of the corresponding test. The string is displayed near
1656 ;; the top of the buffer and serves as a progress bar.
1657 (defvar ert--results-progress-bar-string
)
1658 ;; The position where the progress bar button begins.
1659 (defvar ert--results-progress-bar-button-begin
)
1660 ;; The test result listener that updates the buffer when tests are run.
1661 (defvar ert--results-listener
)
1663 (defun ert-insert-test-name-button (test-name)
1664 "Insert a button that links to TEST-NAME."
1665 (insert-text-button (format "%S" test-name
)
1666 :type
'ert--test-name-button
1667 'ert-test-name test-name
))
1669 (defun ert--results-format-expected-unexpected (expected unexpected
)
1670 "Return a string indicating EXPECTED expected results, UNEXPECTED unexpected."
1671 (if (zerop unexpected
)
1672 (format "%s" expected
)
1673 (format "%s (%s unexpected)" (+ expected unexpected
) unexpected
)))
1675 (defun ert--results-update-ewoc-hf (ewoc stats
)
1676 "Update the header and footer of EWOC to show certain information from STATS.
1678 Also sets `ert--results-progress-bar-button-begin'."
1679 (let ((run-count (ert-stats-completed stats
))
1680 (results-buffer (current-buffer))
1681 ;; Need to save buffer-local value.
1682 (font-lock font-lock-mode
))
1687 (insert "Selector: ")
1688 (ert--insert-human-readable-selector (ert--stats-selector stats
))
1691 (format (concat "Passed: %s\n"
1695 (ert--results-format-expected-unexpected
1696 (ert--stats-passed-expected stats
)
1697 (ert--stats-passed-unexpected stats
))
1698 (ert--results-format-expected-unexpected
1699 (ert--stats-failed-expected stats
)
1700 (ert--stats-failed-unexpected stats
))
1701 (ert-stats-skipped stats
)
1703 (ert-stats-total stats
)))
1705 (format "Started at: %s\n"
1706 (ert--format-time-iso8601 (ert--stats-start-time stats
))))
1707 ;; FIXME: This is ugly. Need to properly define invariants of
1708 ;; the `stats' data structure.
1709 (let ((state (cond ((ert--stats-aborted-p stats
) 'aborted
)
1710 ((ert--stats-current-test stats
) 'running
)
1711 ((ert--stats-end-time stats
) 'finished
)
1717 (cond ((ert--stats-current-test stats
)
1718 (insert "Aborted during test: ")
1719 (ert-insert-test-name-button
1720 (ert-test-name (ert--stats-current-test stats
))))
1722 (insert "Aborted."))))
1724 (cl-assert (ert--stats-current-test stats
))
1725 (insert "Running test: ")
1726 (ert-insert-test-name-button (ert-test-name
1727 (ert--stats-current-test stats
))))
1729 (cl-assert (not (ert--stats-current-test stats
)))
1730 (insert "Finished.")))
1732 (if (ert--stats-end-time stats
)
1735 (if (ert--stats-aborted-p stats
)
1738 (ert--format-time-iso8601 (ert--stats-end-time stats
))))
1741 (let ((progress-bar-string (with-current-buffer results-buffer
1742 ert--results-progress-bar-string
)))
1743 (let ((progress-bar-button-begin
1744 (insert-text-button progress-bar-string
1745 :type
'ert--results-progress-bar-button
1746 'face
(or (and font-lock
1747 (ert-face-for-stats stats
))
1749 ;; The header gets copied verbatim to the results buffer,
1750 ;; and all positions remain the same, so
1751 ;; `progress-bar-button-begin' will be the right position
1752 ;; even in the results buffer.
1753 (with-current-buffer results-buffer
1754 (set (make-local-variable 'ert--results-progress-bar-button-begin
)
1755 progress-bar-button-begin
))))
1760 ;; We actually want an empty footer, but that would trigger a bug
1761 ;; in ewoc, sometimes clearing the entire buffer. (It's possible
1762 ;; that this bug has been fixed since this has been tested; we
1763 ;; should test it again.)
1767 (defvar ert-test-run-redisplay-interval-secs
.1
1768 "How many seconds ERT should wait between redisplays while running tests.
1770 While running tests, ERT shows the current progress, and this variable
1771 determines how frequently the progress display is updated.")
1773 (defun ert--results-update-stats-display (ewoc stats
)
1774 "Update EWOC and the mode line to show data from STATS."
1775 ;; TODO(ohler): investigate using `make-progress-reporter'.
1776 (ert--results-update-ewoc-hf ewoc stats
)
1777 (force-mode-line-update)
1779 (setf (ert--stats-next-redisplay stats
)
1780 (+ (float-time) ert-test-run-redisplay-interval-secs
)))
1782 (defun ert--results-update-stats-display-maybe (ewoc stats
)
1783 "Call `ert--results-update-stats-display' if not called recently.
1785 EWOC and STATS are arguments for `ert--results-update-stats-display'."
1786 (when (>= (float-time) (ert--stats-next-redisplay stats
))
1787 (ert--results-update-stats-display ewoc stats
)))
1789 (defun ert--tests-running-mode-line-indicator ()
1790 "Return a string for the mode line that shows the test run progress."
1791 (let* ((stats ert--current-run-stats
)
1792 (tests-total (ert-stats-total stats
))
1793 (tests-completed (ert-stats-completed stats
)))
1794 (if (>= tests-completed tests-total
)
1795 (format " ERT(%s/%s,finished)" tests-completed tests-total
)
1796 (format " ERT(%s/%s):%s"
1797 (1+ tests-completed
)
1799 (if (null (ert--stats-current-test stats
))
1802 (ert-test-name (ert--stats-current-test stats
))))))))
1804 (defun ert--make-xrefs-region (begin end
)
1805 "Attach cross-references to function names between BEGIN and END.
1807 BEGIN and END specify a region in the current buffer."
1811 (goto-char (+ (point) 2))
1812 (skip-syntax-forward "^w_")
1814 (let* ((beg (point))
1815 (end (progn (skip-syntax-forward "w_") (point)))
1816 (sym (intern-soft (buffer-substring-no-properties
1818 (file (and sym
(symbol-file sym
'defun
))))
1821 ;; help-xref-button needs to operate on something matched
1822 ;; by a regexp, so set that up for it.
1823 (re-search-forward "\\(\\sw\\|\\s_\\)+")
1824 (help-xref-button 0 'help-function-def sym file
)))
1827 (defun ert--string-first-line (s)
1828 "Return the first line of S, or S if it contains no newlines.
1830 The return value does not include the line terminator."
1831 (substring s
0 (cl-position ?
\n s
)))
1833 (defun ert-face-for-test-result (expectedp)
1834 "Return a face that shows whether a test result was expected or unexpected.
1836 If EXPECTEDP is nil, returns the face for unexpected results; if
1837 non-nil, returns the face for expected results.."
1838 (if expectedp
'ert-test-result-expected
'ert-test-result-unexpected
))
1840 (defun ert-face-for-stats (stats)
1841 "Return a face that represents STATS."
1842 (cond ((ert--stats-aborted-p stats
) 'nil
)
1843 ((cl-plusp (ert-stats-completed-unexpected stats
))
1844 (ert-face-for-test-result nil
))
1845 ((eql (ert-stats-completed-expected stats
) (ert-stats-total stats
))
1846 (ert-face-for-test-result t
))
1849 (defun ert--print-test-for-ewoc (entry)
1850 "The ewoc print function for ewoc test entries. ENTRY is the entry to print."
1851 (let* ((test (ert--ewoc-entry-test entry
))
1852 (stats ert--results-stats
)
1853 (result (let ((pos (ert--stats-test-pos stats test
)))
1855 (aref (ert--stats-test-results stats
) pos
)))
1856 (hiddenp (ert--ewoc-entry-hidden-p entry
))
1857 (expandedp (ert--ewoc-entry-expanded-p entry
))
1858 (extended-printer-limits-p (ert--ewoc-entry-extended-printer-limits-p
1862 (let ((expectedp (ert-test-result-expected-p test result
)))
1863 (insert-text-button (format "%c" (ert-char-for-test-result
1865 :type
'ert--results-expand-collapse-button
1866 'face
(or (and font-lock-mode
1867 (ert-face-for-test-result
1871 (ert-insert-test-name-button (ert-test-name test
))
1873 (when (and expandedp
(not (eql result
'nil
)))
1874 (when (ert-test-documentation test
)
1877 (ert--string-first-line
1878 (substitute-command-keys
1879 (ert-test-documentation test
)))
1880 'font-lock-face
'font-lock-doc-face
)
1882 (cl-etypecase result
1884 (if (ert-test-result-expected-p test result
)
1885 (insert " passed\n")
1886 (insert " passed unexpectedly\n"))
1888 (ert-test-result-with-condition
1889 (ert--insert-infos result
)
1890 (let ((print-escape-newlines t
)
1891 (print-level (if extended-printer-limits-p
12 6))
1892 (print-length (if extended-printer-limits-p
100 10)))
1894 (let ((begin (point)))
1895 (ert--pp-with-indentation-and-newline
1896 (ert-test-result-with-condition-condition result
))
1897 (ert--make-xrefs-region begin
(point)))))
1898 (ert-test-aborted-with-non-local-exit
1899 (insert " aborted\n"))
1901 (insert " quit\n")))
1905 (defun ert--results-font-lock-function (enabledp)
1906 "Redraw the ERT results buffer after font-lock-mode was switched on or off.
1908 ENABLEDP is true if font-lock-mode is switched on, false
1910 (ert--results-update-ewoc-hf ert--results-ewoc ert--results-stats
)
1911 (ewoc-refresh ert--results-ewoc
)
1912 (font-lock-default-function enabledp
))
1914 (defun ert--setup-results-buffer (stats listener buffer-name
)
1915 "Set up a test results buffer.
1917 STATS is the stats object; LISTENER is the results listener;
1918 BUFFER-NAME, if non-nil, is the buffer name to use."
1919 (unless buffer-name
(setq buffer-name
"*ert*"))
1920 (let ((buffer (get-buffer-create buffer-name
)))
1921 (with-current-buffer buffer
1922 (let ((inhibit-read-only t
))
1923 (buffer-disable-undo)
1926 ;; Erase buffer again in case switching out of the previous
1927 ;; mode inserted anything. (This happens e.g. when switching
1928 ;; from ert-results-mode to ert-results-mode when
1929 ;; font-lock-mode turns itself off in change-major-mode-hook.)
1931 (set (make-local-variable 'font-lock-function
)
1932 'ert--results-font-lock-function
)
1933 (let ((ewoc (ewoc-create 'ert--print-test-for-ewoc nil nil t
)))
1934 (set (make-local-variable 'ert--results-ewoc
) ewoc
)
1935 (set (make-local-variable 'ert--results-stats
) stats
)
1936 (set (make-local-variable 'ert--results-progress-bar-string
)
1937 (make-string (ert-stats-total stats
)
1938 (ert-char-for-test-result nil t
)))
1939 (set (make-local-variable 'ert--results-listener
) listener
)
1940 (cl-loop for test across
(ert--stats-tests stats
) do
1941 (ewoc-enter-last ewoc
1942 (make-ert--ewoc-entry :test test
1944 (ert--results-update-ewoc-hf ert--results-ewoc ert--results-stats
)
1945 (goto-char (1- (point-max)))
1949 (defvar ert--selector-history nil
1950 "List of recent test selectors read from terminal.")
1952 ;; Should OUTPUT-BUFFER-NAME and MESSAGE-FN really be arguments here?
1953 ;; They are needed only for our automated self-tests at the moment.
1954 ;; Or should there be some other mechanism?
1956 (defun ert-run-tests-interactively (selector
1957 &optional output-buffer-name message-fn
)
1958 "Run the tests specified by SELECTOR and display the results in a buffer.
1960 SELECTOR works as described in `ert-select-tests'.
1961 OUTPUT-BUFFER-NAME and MESSAGE-FN should normally be nil; they
1962 are used for automated self-tests and specify which buffer to use
1963 and how to display message."
1965 (list (let ((default (if ert--selector-history
1966 ;; Can't use `first' here as this form is
1967 ;; not compiled, and `first' is not
1968 ;; defined without cl.
1969 (car ert--selector-history
)
1972 (completing-read (if (null default
)
1974 (format "Run tests (default %s): " default
))
1975 obarray
#'ert-test-boundp nil nil
1976 'ert--selector-history default nil
)))
1978 (unless message-fn
(setq message-fn
'message
))
1979 (let ((output-buffer-name output-buffer-name
)
1982 (message-fn message-fn
))
1984 (lambda (event-type &rest event-args
)
1985 (cl-ecase event-type
1987 (cl-destructuring-bind (stats) event-args
1988 (setq buffer
(ert--setup-results-buffer stats
1990 output-buffer-name
))
1991 (pop-to-buffer buffer
)))
1993 (cl-destructuring-bind (stats abortedp
) event-args
1995 "%sRan %s tests, %s results were as expected%s%s"
1999 (ert-stats-total stats
)
2000 (ert-stats-completed-expected stats
)
2002 (ert-stats-completed-unexpected stats
)))
2003 (if (zerop unexpected
)
2005 (format ", %s unexpected" unexpected
)))
2007 (ert-stats-skipped stats
)))
2010 (format ", %s skipped" skipped
))))
2011 (ert--results-update-stats-display (with-current-buffer buffer
2015 (cl-destructuring-bind (stats test
) event-args
2016 (with-current-buffer buffer
2017 (let* ((ewoc ert--results-ewoc
)
2018 (pos (ert--stats-test-pos stats test
))
2019 (node (ewoc-nth ewoc pos
)))
2021 (setf (ert--ewoc-entry-test (ewoc-data node
)) test
)
2022 (aset ert--results-progress-bar-string pos
2023 (ert-char-for-test-result nil t
))
2024 (ert--results-update-stats-display-maybe ewoc stats
)
2025 (ewoc-invalidate ewoc node
)))))
2027 (cl-destructuring-bind (stats test result
) event-args
2028 (with-current-buffer buffer
2029 (let* ((ewoc ert--results-ewoc
)
2030 (pos (ert--stats-test-pos stats test
))
2031 (node (ewoc-nth ewoc pos
)))
2032 (when (ert--ewoc-entry-hidden-p (ewoc-data node
))
2033 (setf (ert--ewoc-entry-hidden-p (ewoc-data node
))
2034 (ert-test-result-expected-p test result
)))
2035 (aset ert--results-progress-bar-string pos
2036 (ert-char-for-test-result result
2037 (ert-test-result-expected-p
2039 (ert--results-update-stats-display-maybe ewoc stats
)
2040 (ewoc-invalidate ewoc node
))))))))
2041 (ert-run-tests selector listener t
)))
2044 (defalias 'ert
'ert-run-tests-interactively
)
2047 ;;; Simple view mode for auxiliary information like stack traces or
2048 ;;; messages. Mainly binds "q" for quit.
2050 (define-derived-mode ert-simple-view-mode special-mode
"ERT-View"
2051 "Major mode for viewing auxiliary information in ERT.")
2053 ;;; Commands and button actions for the results buffer.
2055 (define-derived-mode ert-results-mode special-mode
"ERT-Results"
2056 "Major mode for viewing results of ERT test runs.")
2058 (cl-loop for
(key binding
) in
2059 '( ;; Stuff that's not in the menu.
2060 ("\t" forward-button
)
2061 ([backtab] backward-button)
2062 ("j" ert-results-jump-between-summary-and-result)
2063 ("L" ert-results-toggle-printer-limits-for-test-at-point)
2064 ("n" ert-results-next-test)
2065 ("p" ert-results-previous-test)
2066 ;; Stuff that is in the menu.
2067 ("R" ert-results-rerun-all-tests)
2068 ("r" ert-results-rerun-test-at-point)
2069 ("d" ert-results-rerun-test-at-point-debugging-errors)
2070 ("." ert-results-find-test-at-point-other-window)
2071 ("b" ert-results-pop-to-backtrace-for-test-at-point)
2072 ("m" ert-results-pop-to-messages-for-test-at-point)
2073 ("l" ert-results-pop-to-should-forms-for-test-at-point)
2074 ("h" ert-results-describe-test-at-point)
2075 ("D" ert-delete-test)
2076 ("T" ert-results-pop-to-timings)
2079 (define-key ert-results-mode-map key binding))
2081 (easy-menu-define ert-results-mode-menu ert-results-mode-map
2082 "Menu for `ert-results-mode'."
2084 ["Re-run all tests" ert-results-rerun-all-tests]
2086 ;; FIXME? Why are there (at least) 3 different ways to decide if
2087 ;; there is a test at point?
2088 ["Re-run test" ert-results-rerun-test-at-point
2089 :active (car (ert--results-test-at-point-allow-redefinition))]
2090 ["Debug test" ert-results-rerun-test-at-point-debugging-errors
2091 :active (car (ert--results-test-at-point-allow-redefinition))]
2092 ["Show test definition" ert-results-find-test-at-point-other-window
2093 :active (ert-test-at-point)]
2095 ["Show backtrace" ert-results-pop-to-backtrace-for-test-at-point
2096 :active (ert--results-test-at-point-no-redefinition)]
2097 ["Show messages" ert-results-pop-to-messages-for-test-at-point
2098 :active (ert--results-test-at-point-no-redefinition)]
2099 ["Show `should' forms" ert-results-pop-to-should-forms-for-test-at-point
2100 :active (ert--results-test-at-point-no-redefinition)]
2101 ["Describe test" ert-results-describe-test-at-point
2102 :active (ert--results-test-at-point-no-redefinition)]
2104 ["Delete test" ert-delete-test]
2106 ["Show execution time of each test" ert-results-pop-to-timings]
2109 (define-button-type 'ert--results-progress-bar-button
2110 'action #'ert--results-progress-bar-button-action
2111 'help-echo "mouse-2, RET: Reveal test result")
2113 (define-button-type 'ert--test-name-button
2114 'action #'ert--test-name-button-action
2115 'help-echo "mouse-2, RET: Find test definition")
2117 (define-button-type 'ert--results-expand-collapse-button
2118 'action #'ert--results-expand-collapse-button-action
2119 'help-echo "mouse-2, RET: Expand/collapse test result")
2121 (defun ert--results-test-node-or-null-at-point ()
2122 "If point is on a valid ewoc node, return it; return nil otherwise.
2124 To be used in the ERT results buffer."
2125 (let* ((ewoc ert--results-ewoc)
2126 (node (ewoc-locate ewoc)))
2127 ;; `ewoc-locate' will return an arbitrary node when point is on
2128 ;; header or footer, or when all nodes are invisible. So we need
2129 ;; to validate its return value here.
2131 ;; Update: I'm seeing nil being returned in some cases now,
2132 ;; perhaps this has been changed?
2134 (>= (point) (ewoc-location node))
2135 (not (ert--ewoc-entry-hidden-p (ewoc-data node))))
2139 (defun ert--results-test-node-at-point ()
2140 "If point is on a valid ewoc node, return it; signal an error otherwise.
2142 To be used in the ERT results buffer."
2143 (or (ert--results-test-node-or-null-at-point)
2144 (user-error "No test at point")))
2146 (defun ert-results-next-test ()
2147 "Move point to the next test.
2149 To be used in the ERT results buffer."
2151 (ert--results-move (ewoc-locate ert--results-ewoc) 'ewoc-next
2154 (defun ert-results-previous-test ()
2155 "Move point to the previous test.
2157 To be used in the ERT results buffer."
2159 (ert--results-move (ewoc-locate ert--results-ewoc) 'ewoc-prev
2162 (defun ert--results-move (node ewoc-fn error-message)
2163 "Move point from NODE to the previous or next node.
2165 EWOC-FN specifies the direction and should be either `ewoc-prev'
2166 or `ewoc-next'. If there are no more nodes in that direction, a
2167 user-error is signaled with the message ERROR-MESSAGE."
2169 (setq node (funcall ewoc-fn ert--results-ewoc node))
2171 (user-error "%s" error-message))
2172 (unless (ert--ewoc-entry-hidden-p (ewoc-data node))
2173 (goto-char (ewoc-location node))
2176 (defun ert--results-expand-collapse-button-action (_button)
2177 "Expand or collapse the test node BUTTON belongs to."
2178 (let* ((ewoc ert--results-ewoc)
2179 (node (save-excursion
2180 (goto-char (ert--button-action-position))
2181 (ert--results-test-node-at-point)))
2182 (entry (ewoc-data node)))
2183 (setf (ert--ewoc-entry-expanded-p entry)
2184 (not (ert--ewoc-entry-expanded-p entry)))
2185 (ewoc-invalidate ewoc node)))
2187 (defun ert-results-find-test-at-point-other-window ()
2188 "Find the definition of the test at point in another window.
2190 To be used in the ERT results buffer."
2192 (let ((name (ert-test-at-point)))
2194 (user-error "No test at point"))
2195 (ert-find-test-other-window name)))
2197 (defun ert--test-name-button-action (button)
2198 "Find the definition of the test BUTTON belongs to, in another window."
2199 (let ((name (button-get button 'ert-test-name)))
2200 (ert-find-test-other-window name)))
2202 (defun ert--ewoc-position (ewoc node)
2203 ;; checkdoc-order: nil
2204 "Return the position of NODE in EWOC, or nil if NODE is not in EWOC."
2205 (cl-loop for i from 0
2206 for node-here = (ewoc-nth ewoc 0) then (ewoc-next ewoc node-here)
2207 do (when (eql node node-here)
2209 finally (cl-return nil)))
2211 (defun ert-results-jump-between-summary-and-result ()
2212 "Jump back and forth between the test run summary and individual test results.
2214 From an ewoc node, jumps to the character that represents the
2215 same test in the progress bar, and vice versa.
2217 To be used in the ERT results buffer."
2218 ;; Maybe this command isn't actually needed much, but if it is, it
2219 ;; seems like an indication that the UI design is not optimal. If
2220 ;; jumping back and forth between a summary at the top of the buffer
2221 ;; and the error log in the remainder of the buffer is useful, then
2222 ;; the summary apparently needs to be easily accessible from the
2223 ;; error log, and perhaps it would be better to have it in a
2224 ;; separate buffer to keep it visible.
2226 (let ((ewoc ert--results-ewoc)
2227 (progress-bar-begin ert--results-progress-bar-button-begin))
2228 (cond ((ert--results-test-node-or-null-at-point)
2229 (let* ((node (ert--results-test-node-at-point))
2230 (pos (ert--ewoc-position ewoc node)))
2231 (goto-char (+ progress-bar-begin pos))))
2232 ((and (<= progress-bar-begin (point))
2233 (< (point) (button-end (button-at progress-bar-begin))))
2234 (let* ((node (ewoc-nth ewoc (- (point) progress-bar-begin)))
2235 (entry (ewoc-data node)))
2236 (when (ert--ewoc-entry-hidden-p entry)
2237 (setf (ert--ewoc-entry-hidden-p entry) nil)
2238 (ewoc-invalidate ewoc node))
2239 (ewoc-goto-node ewoc node)))
2241 (goto-char progress-bar-begin)))))
2243 (defun ert-test-at-point ()
2244 "Return the name of the test at point as a symbol, or nil if none."
2245 (or (and (eql major-mode 'ert-results-mode)
2246 (let ((test (ert--results-test-at-point-no-redefinition)))
2247 (and test (ert-test-name test))))
2248 (let* ((thing (thing-at-point 'symbol))
2249 (sym (intern-soft thing)))
2250 (and (ert-test-boundp sym)
2253 (defun ert--results-test-at-point-no-redefinition (&optional error)
2254 "Return the test at point, or nil.
2255 If optional argument ERROR is non-nil, signal an error rather than return nil.
2256 To be used in the ERT results buffer."
2257 (cl-assert (eql major-mode 'ert-results-mode))
2259 (if (ert--results-test-node-or-null-at-point)
2260 (let* ((node (ert--results-test-node-at-point))
2261 (test (ert--ewoc-entry-test (ewoc-data node))))
2263 (let ((progress-bar-begin ert--results-progress-bar-button-begin))
2264 (when (and (<= progress-bar-begin (point))
2265 (< (point) (button-end (button-at progress-bar-begin))))
2266 (let* ((test-index (- (point) progress-bar-begin))
2267 (test (aref (ert--stats-tests ert--results-stats)
2270 (if error (user-error "No test at point"))))
2272 (defun ert--results-test-at-point-allow-redefinition ()
2273 "Look up the test at point, and check whether it has been redefined.
2275 To be used in the ERT results buffer.
2277 Returns a list of two elements: the test (or nil) and a symbol
2278 specifying whether the test has been redefined.
2280 If a new test has been defined with the same name as the test at
2281 point, replaces the test at point with the new test, and returns
2282 the new test and the symbol `redefined'.
2284 If the test has been deleted, returns the old test and the symbol
2287 If the test is still current, returns the test and the symbol nil.
2289 If there is no test at point, returns a list with two nils."
2290 (let ((test (ert--results-test-at-point-no-redefinition)))
2293 ((null (ert-test-name test))
2296 (let* ((name (ert-test-name test))
2297 (new-test (and (ert-test-boundp name)
2298 (ert-get-test name))))
2299 (cond ((eql test new-test)
2304 (ert--results-update-after-test-redefinition
2305 (ert--stats-test-pos ert--results-stats test)
2307 `(,new-test redefined))))))))
2309 (defun ert--results-update-after-test-redefinition (pos new-test)
2310 "Update results buffer after the test at pos POS has been redefined.
2312 Also updates the stats object. NEW-TEST is the new test
2314 (let* ((stats ert--results-stats)
2315 (ewoc ert--results-ewoc)
2316 (node (ewoc-nth ewoc pos))
2317 (entry (ewoc-data node)))
2318 (ert--stats-set-test-and-result stats pos new-test nil)
2319 (setf (ert--ewoc-entry-test entry) new-test
2320 (aref ert--results-progress-bar-string pos) (ert-char-for-test-result
2322 (ewoc-invalidate ewoc node))
2325 (defun ert--button-action-position ()
2326 "The buffer position where the last button action was triggered."
2327 (cond ((integerp last-command-event)
2329 ((eventp last-command-event)
2330 (posn-point (event-start last-command-event)))
2331 (t (cl-assert nil))))
2333 (defun ert--results-progress-bar-button-action (_button)
2334 "Jump to details for the test represented by the character clicked in BUTTON."
2335 (goto-char (ert--button-action-position))
2336 (ert-results-jump-between-summary-and-result))
2338 (defun ert-results-rerun-all-tests ()
2339 "Re-run all tests, using the same selector.
2341 To be used in the ERT results buffer."
2343 (cl-assert (eql major-mode 'ert-results-mode))
2344 (let ((selector (ert--stats-selector ert--results-stats)))
2345 (ert-run-tests-interactively selector (buffer-name))))
2347 (defun ert-results-rerun-test-at-point ()
2348 "Re-run the test at point.
2350 To be used in the ERT results buffer."
2352 (cl-destructuring-bind (test redefinition-state)
2353 (ert--results-test-at-point-allow-redefinition)
2355 (user-error "No test at point"))
2356 (let* ((stats ert--results-stats)
2357 (progress-message (format "Running %stest %S"
2358 (cl-ecase redefinition-state
2360 (redefined "new definition of ")
2361 (deleted "deleted "))
2362 (ert-test-name test))))
2363 ;; Need to save and restore point manually here: When point is on
2364 ;; the first visible ewoc entry while the header is updated, point
2365 ;; moves to the top of the buffer. This is undesirable, and a
2366 ;; simple `save-excursion' doesn't prevent it.
2367 (let ((point (point)))
2371 (message "%s..." progress-message)
2372 (ert-run-or-rerun-test stats test
2373 ert--results-listener))
2374 (ert--results-update-stats-display ert--results-ewoc stats)
2377 (let ((result (ert-test-most-recent-result test)))
2378 (ert-string-for-test-result
2379 result (ert-test-result-expected-p test result)))))
2380 (goto-char point))))))
2382 (defun ert-results-rerun-test-at-point-debugging-errors ()
2383 "Re-run the test at point with `ert-debug-on-error' bound to t.
2385 To be used in the ERT results buffer."
2387 (let ((ert-debug-on-error t))
2388 (ert-results-rerun-test-at-point)))
2390 (defun ert-results-pop-to-backtrace-for-test-at-point ()
2391 "Display the backtrace for the test at point.
2393 To be used in the ERT results buffer."
2395 (let* ((test (ert--results-test-at-point-no-redefinition t))
2396 (stats ert--results-stats)
2397 (pos (ert--stats-test-pos stats test))
2398 (result (aref (ert--stats-test-results stats) pos)))
2399 (cl-etypecase result
2400 (ert-test-passed (error "Test passed, no backtrace available"))
2401 (ert-test-result-with-condition
2402 (let ((backtrace (ert-test-result-with-condition-backtrace result))
2403 (buffer (get-buffer-create "*ERT Backtrace*")))
2404 (pop-to-buffer buffer)
2405 (let ((inhibit-read-only t))
2406 (buffer-disable-undo)
2408 (ert-simple-view-mode)
2409 (set-buffer-multibyte t) ; mimic debugger-setup-buffer
2410 (setq truncate-lines t)
2411 (ert--print-backtrace backtrace t)
2412 (goto-char (point-min))
2413 (insert (substitute-command-keys "Backtrace for test `"))
2414 (ert-insert-test-name-button (ert-test-name test))
2415 (insert (substitute-command-keys "':\n"))))))))
2417 (defun ert-results-pop-to-messages-for-test-at-point ()
2418 "Display the part of the *Messages* buffer generated during the test at point.
2420 To be used in the ERT results buffer."
2422 (let* ((test (ert--results-test-at-point-no-redefinition t))
2423 (stats ert--results-stats)
2424 (pos (ert--stats-test-pos stats test))
2425 (result (aref (ert--stats-test-results stats) pos)))
2426 (let ((buffer (get-buffer-create "*ERT Messages*")))
2427 (pop-to-buffer buffer)
2428 (let ((inhibit-read-only t))
2429 (buffer-disable-undo)
2431 (ert-simple-view-mode)
2432 (insert (ert-test-result-messages result))
2433 (goto-char (point-min))
2434 (insert (substitute-command-keys "Messages for test `"))
2435 (ert-insert-test-name-button (ert-test-name test))
2436 (insert (substitute-command-keys "':\n"))))))
2438 (defun ert-results-pop-to-should-forms-for-test-at-point ()
2439 "Display the list of `should' forms executed during the test at point.
2441 To be used in the ERT results buffer."
2443 (let* ((test (ert--results-test-at-point-no-redefinition t))
2444 (stats ert--results-stats)
2445 (pos (ert--stats-test-pos stats test))
2446 (result (aref (ert--stats-test-results stats) pos)))
2447 (let ((buffer (get-buffer-create "*ERT list of should forms*")))
2448 (pop-to-buffer buffer)
2449 (let ((inhibit-read-only t))
2450 (buffer-disable-undo)
2452 (ert-simple-view-mode)
2453 (if (null (ert-test-result-should-forms result))
2454 (insert "\n(No should forms during this test.)\n")
2455 (cl-loop for form-description
2456 in (ert-test-result-should-forms result)
2459 (insert (format "%s: " i))
2460 (let ((begin (point)))
2461 (ert--pp-with-indentation-and-newline form-description)
2462 (ert--make-xrefs-region begin (point)))))
2463 (goto-char (point-min))
2464 (insert (substitute-command-keys
2465 "`should' forms executed during test `"))
2466 (ert-insert-test-name-button (ert-test-name test))
2467 (insert (substitute-command-keys "':\n"))
2469 (insert (concat "(Values are shallow copies and may have "
2470 "looked different during the test if they\n"
2471 "have been modified destructively.)\n"))
2472 (forward-line 1)))))
2474 (defun ert-results-toggle-printer-limits-for-test-at-point ()
2475 "Toggle how much of the condition to print for the test at point.
2477 To be used in the ERT results buffer."
2479 (let* ((ewoc ert--results-ewoc)
2480 (node (ert--results-test-node-at-point))
2481 (entry (ewoc-data node)))
2482 (setf (ert--ewoc-entry-extended-printer-limits-p entry)
2483 (not (ert--ewoc-entry-extended-printer-limits-p entry)))
2484 (ewoc-invalidate ewoc node)))
2486 (defun ert-results-pop-to-timings ()
2487 "Display test timings for the last run.
2489 To be used in the ERT results buffer."
2491 (let* ((stats ert--results-stats)
2492 (buffer (get-buffer-create "*ERT timings*"))
2493 (data (cl-loop for test across (ert--stats-tests stats)
2494 for start-time across (ert--stats-test-start-times
2496 for end-time across (ert--stats-test-end-times stats)
2498 (float-time (time-subtract
2499 end-time start-time))))))
2500 (setq data (sort data (lambda (a b)
2501 (> (cl-second a) (cl-second b)))))
2502 (pop-to-buffer buffer)
2503 (let ((inhibit-read-only t))
2504 (buffer-disable-undo)
2506 (ert-simple-view-mode)
2508 (insert "(No data)\n")
2509 (insert (format "%-3s %8s %8s\n" "" "time" "cumul"))
2510 (cl-loop for (test time) in data
2511 for cumul-time = time then (+ cumul-time time)
2514 (insert (format "%3s: %8.3f %8.3f " i time cumul-time))
2515 (ert-insert-test-name-button (ert-test-name test))
2517 (goto-char (point-min))
2518 (insert "Tests by run time (seconds):\n\n")
2522 (defun ert-describe-test (test-or-test-name)
2523 "Display the documentation for TEST-OR-TEST-NAME (a symbol or ert-test)."
2524 (interactive (list (ert-read-test-name-at-point "Describe test")))
2525 (when (< emacs-major-version 24)
2526 (user-error "Requires Emacs 24 or later"))
2529 (cl-etypecase test-or-test-name
2530 (symbol (setq test-name test-or-test-name
2531 test-definition (ert-get-test test-or-test-name)))
2532 (ert-test (setq test-name (ert-test-name test-or-test-name)
2533 test-definition test-or-test-name)))
2534 (help-setup-xref (list #'ert-describe-test test-or-test-name)
2535 (called-interactively-p 'interactive))
2537 (with-help-window (help-buffer)
2538 (with-current-buffer (help-buffer)
2539 (insert (if test-name (format "%S" test-name) "<anonymous test>"))
2540 (insert " is a test")
2541 (let ((file-name (and test-name
2542 (symbol-file test-name 'ert-deftest))))
2544 (insert (format-message " defined in `%s'"
2545 (file-name-nondirectory file-name)))
2547 (re-search-backward (substitute-command-keys "`\\([^`']+\\)'")
2549 (help-xref-button 1 'help-function-def test-name file-name)))
2551 (fill-region-as-paragraph (point-min) (point))
2553 (unless (and (ert-test-boundp test-name)
2554 (eql (ert-get-test test-name) test-definition))
2555 (let ((begin (point)))
2556 (insert "Note: This test has been redefined or deleted, "
2557 "this documentation refers to an old definition.")
2558 (fill-region-as-paragraph begin (point)))
2560 (insert (substitute-command-keys
2561 (or (ert-test-documentation test-definition)
2562 "It is not documented."))
2565 (defun ert-results-describe-test-at-point ()
2566 "Display the documentation of the test at point.
2568 To be used in the ERT results buffer."
2570 (ert-describe-test (ert--results-test-at-point-no-redefinition t)))
2573 ;;; Actions on load/unload.
2575 (add-to-list 'find-function-regexp-alist '(ert-deftest . ert--find-test-regexp))
2576 (add-to-list 'minor-mode-alist '(ert--current-run-stats
2578 (ert--tests-running-mode-line-indicator))))
2579 (add-hook 'emacs-lisp-mode-hook #'ert--activate-font-lock-keywords)
2581 (defun ert--unload-function ()
2582 "Unload function to undo the side-effects of loading ert.el."
2583 (ert--remove-from-list 'find-function-regexp-alist 'ert-deftest :key #'car)
2584 (ert--remove-from-list 'minor-mode-alist 'ert--current-run-stats :key #'car)
2585 (ert--remove-from-list 'emacs-lisp-mode-hook
2586 'ert--activate-font-lock-keywords)
2589 (defvar ert-unload-hook '())
2590 (add-hook 'ert-unload-hook #'ert--unload-function)
2595 ;;; ert.el ends here