1 ;;; ert.el --- Emacs Lisp Regression Testing
3 ;; Copyright (C) 2007-2008, 2010-2012 Free Software Foundation, Inc.
5 ;; Author: Christian Ohler <ohler@gnu.org>
6 ;; Keywords: lisp, tools
8 ;; This file is part of GNU Emacs.
10 ;; This program is free software: you can redistribute it and/or
11 ;; modify it under the terms of the GNU General Public License as
12 ;; published by the Free Software Foundation, either version 3 of the
13 ;; License, or (at your option) any later version.
15 ;; This program is distributed in the hope that it will be useful, but
16 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 ;; General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with this program. 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.
67 ;;; UI customization options.
70 "ERT, the Emacs Lisp regression testing tool."
74 (defface ert-test-result-expected
'((((class color
) (background light
))
76 (((class color
) (background dark
))
77 :background
"green3"))
78 "Face used for expected results in the ERT results buffer."
81 (defface ert-test-result-unexpected
'((((class color
) (background light
))
83 (((class color
) (background dark
))
85 "Face used for unexpected results in the ERT results buffer."
89 ;;; Copies/reimplementations of cl functions.
91 (defun ert--cl-do-remf (plist tag
)
92 "Copy of `cl-do-remf'. Modify PLIST by removing TAG."
93 (let ((p (cdr plist
)))
94 (while (and (cdr p
) (not (eq (car (cdr p
)) tag
))) (setq p
(cdr (cdr p
))))
95 (and (cdr p
) (progn (setcdr p
(cdr (cdr (cdr p
)))) t
))))
97 (defun ert--remprop (sym tag
)
98 "Copy of `cl-remprop'. Modify SYM's plist by removing TAG."
99 (let ((plist (symbol-plist sym
)))
100 (if (and plist
(eq tag
(car plist
)))
101 (progn (setplist sym
(cdr (cdr plist
))) t
)
102 (ert--cl-do-remf plist tag
))))
104 (defun ert--remove-if-not (ert-pred ert-list
)
105 "A reimplementation of `remove-if-not'.
107 ERT-PRED is a predicate, ERT-LIST is the input list."
108 (loop for ert-x in ert-list
109 if
(funcall ert-pred ert-x
)
112 (defun ert--intersection (a b
)
113 "A reimplementation of `intersection'. Intersect the sets A and B.
115 Elements are compared using `eql'."
120 (defun ert--set-difference (a b
)
121 "A reimplementation of `set-difference'. Subtract the set B from the set A.
123 Elements are compared using `eql'."
128 (defun ert--set-difference-eq (a b
)
129 "A reimplementation of `set-difference'. Subtract the set B from the set A.
131 Elements are compared using `eq'."
136 (defun ert--union (a b
)
137 "A reimplementation of `union'. Compute the union of the sets A and B.
139 Elements are compared using `eql'."
140 (append a
(ert--set-difference b a
)))
143 (defvar ert--gensym-counter
0))
146 (defun ert--gensym (&optional prefix
)
147 "Only allows string PREFIX, not compatible with CL."
148 (unless prefix
(setq prefix
"G"))
149 (make-symbol (format "%s%s"
151 (prog1 ert--gensym-counter
152 (incf ert--gensym-counter
))))))
154 (defun ert--coerce-to-vector (x)
155 "Coerce X to a vector."
156 (when (char-table-p x
) (error "Not supported"))
161 (defun* ert--remove
* (x list
&key key test
)
162 "Does not support all the keywords of remove*."
163 (unless key
(setq key
#'identity
))
164 (unless test
(setq test
#'eql
))
166 unless
(funcall test x
(funcall key y
))
169 (defun ert--string-position (c s
)
170 "Return the position of the first occurrence of C in S, or nil if none."
173 when
(eql x c
) return i
))
175 (defun ert--mismatch (a b
)
176 "Return index of first element that differs between A and B.
178 Like `mismatch'. Uses `equal' for comparison."
179 (cond ((or (listp a
) (listp b
))
180 (ert--mismatch (ert--coerce-to-vector a
)
181 (ert--coerce-to-vector b
)))
182 ((> (length a
) (length b
))
185 (let ((la (length a
))
187 (assert (arrayp a
) t
)
188 (assert (arrayp b
) t
)
189 (assert (<= la lb
) t
)
191 when
(not (equal (aref a i
) (aref b i
))) return i
192 finally
(return (if (/= la lb
)
194 (assert (equal a b
) t
)
197 (defun ert--subseq (seq start
&optional end
)
198 "Return a subsequence of SEQ from START to END."
199 (when (char-table-p seq
) (error "Not supported"))
200 (let ((vector (substring (ert--coerce-to-vector seq
) start end
)))
203 (string (concat vector
))
204 (list (append vector nil
))
205 (bool-vector (loop with result
= (make-bool-vector (length vector
) nil
)
206 for i below
(length vector
) do
207 (setf (aref result i
) (aref vector i
))
208 finally
(return result
)))
209 (char-table (assert nil
)))))
211 (defun ert-equal-including-properties (a b
)
212 "Return t if A and B have similar structure and contents.
214 This is like `equal-including-properties' except that it compares
215 the property values of text properties structurally (by
216 recursing) rather than with `eq'. Perhaps this is what
217 `equal-including-properties' should do in the first place; see
218 Emacs bug 6581 at URL `http://debbugs.gnu.org/cgi/bugreport.cgi?bug=6581'."
219 ;; This implementation is inefficient. Rather than making it
220 ;; efficient, let's hope bug 6581 gets fixed so that we can delete
222 (not (ert--explain-equal-including-properties a b
)))
225 ;;; Defining and locating tests.
227 ;; The data structure that represents a test case.
232 (most-recent-result nil
)
233 (expected-result-type ':passed
)
236 (defun ert-test-boundp (symbol)
237 "Return non-nil if SYMBOL names a test."
238 (and (get symbol
'ert--test
) t
))
240 (defun ert-get-test (symbol)
241 "If SYMBOL names a test, return that. Signal an error otherwise."
242 (unless (ert-test-boundp symbol
) (error "No test named `%S'" symbol
))
243 (get symbol
'ert--test
))
245 (defun ert-set-test (symbol definition
)
246 "Make SYMBOL name the test DEFINITION, and return DEFINITION."
247 (when (eq symbol
'nil
)
248 ;; We disallow nil since `ert-test-at-point' and related functions
249 ;; want to return a test name, but also need an out-of-band value
250 ;; on failure. Nil is the most natural out-of-band value; using 0
251 ;; or "" or signaling an error would be too awkward.
253 ;; Note that nil is still a valid value for the `name' slot in
254 ;; ert-test objects. It designates an anonymous test.
255 (error "Attempt to define a test named nil"))
256 (put symbol
'ert--test definition
)
259 (defun ert-make-test-unbound (symbol)
260 "Make SYMBOL name no test. Return SYMBOL."
261 (ert--remprop symbol
'ert--test
)
264 (defun ert--parse-keys-and-body (keys-and-body)
265 "Split KEYS-AND-BODY into keyword-and-value pairs and the remaining body.
267 KEYS-AND-BODY should have the form of a property list, with the
268 exception that only keywords are permitted as keys and that the
269 tail -- the body -- is a list of forms that does not start with a
272 Returns a two-element list containing the keys-and-values plist
274 (let ((extracted-key-accu '())
275 (remaining keys-and-body
))
276 (while (and (consp remaining
) (keywordp (first remaining
)))
277 (let ((keyword (pop remaining
)))
278 (unless (consp remaining
)
279 (error "Value expected after keyword %S in %S"
280 keyword keys-and-body
))
281 (when (assoc keyword extracted-key-accu
)
282 (warn "Keyword %S appears more than once in %S" keyword
284 (push (cons keyword
(pop remaining
)) extracted-key-accu
)))
285 (setq extracted-key-accu
(nreverse extracted-key-accu
))
286 (list (loop for
(key . value
) in extracted-key-accu
292 (defmacro* ert-deftest
(name () &body docstring-keys-and-body
)
293 "Define NAME (a symbol) as a test.
295 BODY is evaluated as a `progn' when the test is run. It should
296 signal a condition on failure or just return if the test passes.
298 `should', `should-not' and `should-error' are useful for
301 Use `ert' to run tests interactively.
303 Tests that are expected to fail can be marked as such
304 using :expected-result. See `ert-test-result-type-p' for a
305 description of valid values for RESULT-TYPE.
307 \(fn NAME () [DOCSTRING] [:expected-result RESULT-TYPE] \
308 \[:tags '(TAG...)] BODY...)"
309 (declare (debug (&define
:name test
310 name sexp
[&optional stringp
]
311 [&rest keywordp sexp
] def-body
))
314 (let ((documentation nil
)
315 (documentation-supplied-p nil
))
316 (when (stringp (first docstring-keys-and-body
))
317 (setq documentation
(pop docstring-keys-and-body
)
318 documentation-supplied-p t
))
319 (destructuring-bind ((&key
(expected-result nil expected-result-supplied-p
)
320 (tags nil tags-supplied-p
))
322 (ert--parse-keys-and-body docstring-keys-and-body
)
327 ,@(when documentation-supplied-p
328 `(:documentation
,documentation
))
329 ,@(when expected-result-supplied-p
330 `(:expected-result-type
,expected-result
))
331 ,@(when tags-supplied-p
333 :body
(lambda () ,@body
)))
334 ;; This hack allows `symbol-file' to associate `ert-deftest'
335 ;; forms with files, and therefore enables `find-function' to
336 ;; work with tests. However, it leads to warnings in
337 ;; `unload-feature', which doesn't know how to undefine tests
338 ;; and has no mechanism for extension.
339 (push '(ert-deftest .
,name
) current-load-list
)
342 ;; We use these `put' forms in addition to the (declare (indent)) in
343 ;; the defmacro form since the `declare' alone does not lead to
344 ;; correct indentation before the .el/.elc file is loaded.
345 ;; Autoloading these `put' forms solves this.
348 ;; TODO(ohler): Figure out what these mean and make sure they are correct.
349 (put 'ert-deftest
'lisp-indent-function
2)
350 (put 'ert-info
'lisp-indent-function
1))
352 (defvar ert--find-test-regexp
353 (concat "^\\s-*(ert-deftest"
354 find-function-space-re
356 "The regexp the `find-function' mechanisms use for finding test definitions.")
359 (put 'ert-test-failed
'error-conditions
'(error ert-test-failed
))
360 (put 'ert-test-failed
'error-message
"Test failed")
363 "Terminate the current test and mark it passed. Does not return."
364 (throw 'ert--pass nil
))
366 (defun ert-fail (data)
367 "Terminate the current test and mark it failed. Does not return.
368 DATA is displayed to the user and should state the reason of the failure."
369 (signal 'ert-test-failed
(list data
)))
372 ;;; The `should' macros.
374 (defvar ert--should-execution-observer nil
)
376 (defun ert--signal-should-execution (form-description)
377 "Tell the current `should' form observer (if any) about FORM-DESCRIPTION."
378 (when ert--should-execution-observer
379 (funcall ert--should-execution-observer form-description
)))
381 (defun ert--special-operator-p (thing)
382 "Return non-nil if THING is a symbol naming a special operator."
384 (let ((definition (indirect-function thing t
)))
385 (and (subrp definition
)
386 (eql (cdr (subr-arity definition
)) 'unevalled
)))))
388 (defun ert--expand-should-1 (whole form inner-expander
)
389 "Helper function for the `should' macro and its variants."
391 ;; If `cl-macroexpand' isn't bound, the code that we're
392 ;; compiling doesn't depend on cl and thus doesn't need an
393 ;; environment arg for `macroexpand'.
394 (if (fboundp 'cl-macroexpand
)
395 ;; Suppress warning about run-time call to cl function: we
396 ;; only call it if it's fboundp.
398 (cl-macroexpand form
(and (boundp 'cl-macro-environment
)
399 cl-macro-environment
)))
400 (macroexpand form
))))
402 ((or (atom form
) (ert--special-operator-p (car form
)))
403 (let ((value (ert--gensym "value-")))
404 `(let ((,value
(ert--gensym "ert-form-evaluation-aborted-")))
405 ,(funcall inner-expander
407 `(list ',whole
:form
',form
:value
,value
)
411 (let ((fn-name (car form
))
412 (arg-forms (cdr form
)))
413 (assert (or (symbolp fn-name
)
415 (eql (car fn-name
) 'lambda
)
416 (listp (cdr fn-name
)))))
417 (let ((fn (ert--gensym "fn-"))
418 (args (ert--gensym "args-"))
419 (value (ert--gensym "value-"))
420 (default-value (ert--gensym "ert-form-evaluation-aborted-")))
421 `(let ((,fn
(function ,fn-name
))
422 (,args
(list ,@arg-forms
)))
423 (let ((,value
',default-value
))
424 ,(funcall inner-expander
425 `(setq ,value
(apply ,fn
,args
))
426 `(nconc (list ',whole
)
427 (list :form
`(,,fn
,@,args
))
428 (unless (eql ,value
',default-value
)
429 (list :value
,value
))
431 (and (symbolp ',fn-name
)
432 (get ',fn-name
'ert-explainer
))))
435 (apply -explainer-
,args
)))))
439 (defun ert--expand-should (whole form inner-expander
)
440 "Helper function for the `should' macro and its variants.
442 Analyzes FORM and returns an expression that has the same
443 semantics under evaluation but records additional debugging
446 INNER-EXPANDER should be a function and is called with two
447 arguments: INNER-FORM and FORM-DESCRIPTION-FORM, where INNER-FORM
448 is an expression equivalent to FORM, and FORM-DESCRIPTION-FORM is
449 an expression that returns a description of FORM. INNER-EXPANDER
450 should return code that calls INNER-FORM and performs the checks
451 and error signaling specific to the particular variant of
452 `should'. The code that INNER-EXPANDER returns must not call
453 FORM-DESCRIPTION-FORM before it has called INNER-FORM."
454 (lexical-let ((inner-expander inner-expander
))
455 (ert--expand-should-1
457 (lambda (inner-form form-description-form value-var
)
458 (let ((form-description (ert--gensym "form-description-")))
459 `(let (,form-description
)
460 ,(funcall inner-expander
463 (setq ,form-description
,form-description-form
)
464 (ert--signal-should-execution ,form-description
))
468 (defmacro* should
(form)
469 "Evaluate FORM. If it returns nil, abort the current test as failed.
471 Returns the value of FORM."
472 (ert--expand-should `(should ,form
) form
473 (lambda (inner-form form-description-form value-var
)
475 (ert-fail ,form-description-form
)))))
477 (defmacro* should-not
(form)
478 "Evaluate FORM. If it returns non-nil, abort the current test as failed.
481 (ert--expand-should `(should-not ,form
) form
482 (lambda (inner-form form-description-form value-var
)
483 `(unless (not ,inner-form
)
484 (ert-fail ,form-description-form
)))))
486 (defun ert--should-error-handle-error (form-description-fn
487 condition type exclude-subtypes
)
488 "Helper function for `should-error'.
490 Determines whether CONDITION matches TYPE and EXCLUDE-SUBTYPES,
491 and aborts the current test as failed if it doesn't."
492 (let ((signaled-conditions (get (car condition
) 'error-conditions
))
493 (handled-conditions (etypecase type
495 (symbol (list type
)))))
496 (assert signaled-conditions
)
497 (unless (ert--intersection signaled-conditions handled-conditions
)
499 (funcall form-description-fn
)
502 :fail-reason
(concat "the error signaled did not"
503 " have the expected type")))))
504 (when exclude-subtypes
505 (unless (member (car condition
) handled-conditions
)
507 (funcall form-description-fn
)
510 :fail-reason
(concat "the error signaled was a subtype"
511 " of the expected type"))))))))
513 ;; FIXME: The expansion will evaluate the keyword args (if any) in
514 ;; nonstandard order.
515 (defmacro* should-error
(form &rest keys
&key type exclude-subtypes
)
516 "Evaluate FORM and check that it signals an error.
518 The error signaled needs to match TYPE. TYPE should be a list
519 of condition names. (It can also be a non-nil symbol, which is
520 equivalent to a singleton list containing that symbol.) If
521 EXCLUDE-SUBTYPES is nil, the error matches TYPE if one of its
522 condition names is an element of TYPE. If EXCLUDE-SUBTYPES is
523 non-nil, the error matches TYPE if it is an element of TYPE.
525 If the error matches, returns (ERROR-SYMBOL . DATA) from the
526 error. If not, or if no error was signaled, abort the test as
528 (unless type
(setq type
''error
))
530 `(should-error ,form
,@keys
)
532 (lambda (inner-form form-description-form value-var
)
533 (let ((errorp (ert--gensym "errorp"))
534 (form-description-fn (ert--gensym "form-description-fn-")))
536 (,form-description-fn
(lambda () ,form-description-form
)))
537 (condition-case -condition-
539 ;; We can't use ,type here because we want to evaluate it.
542 (ert--should-error-handle-error ,form-description-fn
544 ,type
,exclude-subtypes
)
545 (setq ,value-var -condition-
)))
548 (funcall ,form-description-fn
)
550 :fail-reason
"did not signal an error")))))))))
553 ;;; Explanation of `should' failures.
555 ;; TODO(ohler): Rework explanations so that they are displayed in a
556 ;; similar way to `ert-info' messages; in particular, allow text
557 ;; buttons in explanations that give more detail or open an ediff
558 ;; buffer. Perhaps explanations should be reported through `ert-info'
559 ;; rather than as part of the condition.
561 (defun ert--proper-list-p (x)
562 "Return non-nil if X is a proper list, nil otherwise."
564 for firstp
= t then nil
565 for fast
= x then
(cddr fast
)
566 for slow
= x then
(cdr slow
) do
567 (when (null fast
) (return t
))
568 (when (not (consp fast
)) (return nil
))
569 (when (null (cdr fast
)) (return t
))
570 (when (not (consp (cdr fast
))) (return nil
))
571 (when (and (not firstp
) (eq fast slow
)) (return nil
))))
573 (defun ert--explain-format-atom (x)
574 "Format the atom X for `ert--explain-equal'."
576 (fixnum (list x
(format "#x%x" x
) (format "?%c" x
)))
579 (defun ert--explain-equal-rec (a b
)
580 "Return a programmer-readable explanation of why A and B are not `equal'.
581 Returns nil if they are."
582 (if (not (equal (type-of a
) (type-of b
)))
583 `(different-types ,a
,b
)
586 (let ((a-proper-p (ert--proper-list-p a
))
587 (b-proper-p (ert--proper-list-p b
)))
588 (if (not (eql (not a-proper-p
) (not b-proper-p
)))
589 `(one-list-proper-one-improper ,a
,b
)
591 (if (not (equal (length a
) (length b
)))
592 `(proper-lists-of-different-length ,(length a
) ,(length b
)
595 ,(ert--mismatch a b
))
599 for xi
= (ert--explain-equal-rec ai bi
)
600 do
(when xi
(return `(list-elt ,i
,xi
)))
601 finally
(assert (equal a b
) t
)))
602 (let ((car-x (ert--explain-equal-rec (car a
) (car b
))))
605 (let ((cdr-x (ert--explain-equal-rec (cdr a
) (cdr b
))))
608 (assert (equal a b
) t
)
610 (array (if (not (equal (length a
) (length b
)))
611 `(arrays-of-different-length ,(length a
) ,(length b
)
613 ,@(unless (char-table-p a
)
615 ,(ert--mismatch a b
))))
619 for xi
= (ert--explain-equal-rec ai bi
)
620 do
(when xi
(return `(array-elt ,i
,xi
)))
621 finally
(assert (equal a b
) t
))))
622 (atom (if (not (equal a b
))
623 (if (and (symbolp a
) (symbolp b
) (string= a b
))
624 `(different-symbols-with-the-same-name ,a
,b
)
625 `(different-atoms ,(ert--explain-format-atom a
)
626 ,(ert--explain-format-atom b
)))
629 (defun ert--explain-equal (a b
)
630 "Explainer function for `equal'."
631 ;; Do a quick comparison in C to avoid running our expensive
632 ;; comparison when possible.
635 (ert--explain-equal-rec a b
)))
636 (put 'equal
'ert-explainer
'ert--explain-equal
)
638 (defun ert--significant-plist-keys (plist)
639 "Return the keys of PLIST that have non-null values, in order."
640 (assert (zerop (mod (length plist
) 2)) t
)
641 (loop for
(key value . rest
) on plist by
#'cddr
642 unless
(or (null value
) (memq key accu
)) collect key into accu
643 finally
(return accu
)))
645 (defun ert--plist-difference-explanation (a b
)
646 "Return a programmer-readable explanation of why A and B are different plists.
648 Returns nil if they are equivalent, i.e., have the same value for
649 each key, where absent values are treated as nil. The order of
650 key/value pairs in each list does not matter."
651 (assert (zerop (mod (length a
) 2)) t
)
652 (assert (zerop (mod (length b
) 2)) t
)
653 ;; Normalizing the plists would be another way to do this but it
654 ;; requires a total ordering on all lisp objects (since any object
655 ;; is valid as a text property key). Perhaps defining such an
656 ;; ordering is useful in other contexts, too, but it's a lot of
657 ;; work, so let's punt on it for now.
658 (let* ((keys-a (ert--significant-plist-keys a
))
659 (keys-b (ert--significant-plist-keys b
))
660 (keys-in-a-not-in-b (ert--set-difference-eq keys-a keys-b
))
661 (keys-in-b-not-in-a (ert--set-difference-eq keys-b keys-a
)))
662 (flet ((explain-with-key (key)
663 (let ((value-a (plist-get a key
))
664 (value-b (plist-get b key
)))
665 (assert (not (equal value-a value-b
)) t
)
666 `(different-properties-for-key
667 ,key
,(ert--explain-equal-including-properties value-a
669 (cond (keys-in-a-not-in-b
670 (explain-with-key (first keys-in-a-not-in-b
)))
672 (explain-with-key (first keys-in-b-not-in-a
)))
674 (loop for key in keys-a
675 when
(not (equal (plist-get a key
) (plist-get b key
)))
676 return
(explain-with-key key
)))))))
678 (defun ert--abbreviate-string (s len suffixp
)
679 "Shorten string S to at most LEN chars.
681 If SUFFIXP is non-nil, returns a suffix of S, otherwise a prefix."
682 (let ((n (length s
)))
686 (substring s
(- n len
)))
688 (substring s
0 len
)))))
690 ;; TODO(ohler): Once bug 6581 is fixed, rename this to
691 ;; `ert--explain-equal-including-properties-rec' and add a fast-path
692 ;; wrapper like `ert--explain-equal'.
693 (defun ert--explain-equal-including-properties (a b
)
694 "Explainer function for `ert-equal-including-properties'.
696 Returns a programmer-readable explanation of why A and B are not
697 `ert-equal-including-properties', or nil if they are."
698 (if (not (equal a b
))
699 (ert--explain-equal a b
)
700 (assert (stringp a
) t
)
701 (assert (stringp b
) t
)
702 (assert (eql (length a
) (length b
)) t
)
703 (loop for i from
0 to
(length a
)
704 for props-a
= (text-properties-at i a
)
705 for props-b
= (text-properties-at i b
)
706 for difference
= (ert--plist-difference-explanation props-a props-b
)
708 (return `(char ,i
,(substring-no-properties a i
(1+ i
))
711 ,(ert--abbreviate-string
712 (substring-no-properties a
0 i
)
715 ,(ert--abbreviate-string
716 (substring-no-properties a
(1+ i
))
718 ;; TODO(ohler): Get `equal-including-properties' fixed in
719 ;; Emacs, delete `ert-equal-including-properties', and
720 ;; re-enable this assertion.
721 ;;finally (assert (equal-including-properties a b) t)
723 (put 'ert-equal-including-properties
725 'ert--explain-equal-including-properties
)
728 ;;; Implementation of `ert-info'.
730 ;; TODO(ohler): The name `info' clashes with
731 ;; `ert--test-execution-info'. One or both should be renamed.
732 (defvar ert--infos
'()
733 "The stack of `ert-info' infos that currently apply.
735 Bound dynamically. This is a list of (PREFIX . MESSAGE) pairs.")
737 (defmacro* ert-info
((message-form &key
((:prefix prefix-form
) "Info: "))
739 "Evaluate MESSAGE-FORM and BODY, and report the message if BODY fails.
741 To be used within ERT tests. MESSAGE-FORM should evaluate to a
742 string that will be displayed together with the test result if
743 the test fails. PREFIX-FORM should evaluate to a string as well
744 and is displayed in front of the value of MESSAGE-FORM."
745 (declare (debug ((form &rest
[sexp form
]) body
))
747 `(let ((ert--infos (cons (cons ,prefix-form
,message-form
) ert--infos
)))
752 ;;; Facilities for running a single test.
754 (defvar ert-debug-on-error nil
755 "Non-nil means enter debugger when a test fails or terminates with an error.")
757 ;; The data structures that represent the result of running a test.
758 (defstruct ert-test-result
762 (defstruct (ert-test-passed (:include ert-test-result
)))
763 (defstruct (ert-test-result-with-condition (:include ert-test-result
))
764 (condition (assert nil
))
765 (backtrace (assert nil
))
766 (infos (assert nil
)))
767 (defstruct (ert-test-quit (:include ert-test-result-with-condition
)))
768 (defstruct (ert-test-failed (:include ert-test-result-with-condition
)))
769 (defstruct (ert-test-aborted-with-non-local-exit (:include ert-test-result
)))
772 (defun ert--record-backtrace ()
773 "Record the current backtrace (as a list) and return it."
774 ;; Since the backtrace is stored in the result object, result
775 ;; objects must only be printed with appropriate limits
776 ;; (`print-level' and `print-length') in place. For interactive
777 ;; use, the cost of ensuring this possibly outweighs the advantage
778 ;; of storing the backtrace for
779 ;; `ert-results-pop-to-backtrace-for-test-at-point' given that we
780 ;; already have `ert-results-rerun-test-debugging-errors-at-point'.
781 ;; For batch use, however, printing the backtrace may be useful.
783 ;; 6 is the number of frames our own debugger adds (when
784 ;; compiled; more when interpreted). FIXME: Need to describe a
785 ;; procedure for determining this constant.
787 for frame
= (backtrace-frame i
)
791 (defun ert--print-backtrace (backtrace)
792 "Format the backtrace BACKTRACE to the current buffer."
793 ;; This is essentially a reimplementation of Fbacktrace
794 ;; (src/eval.c), but for a saved backtrace, not the current one.
795 (let ((print-escape-newlines t
)
798 (dolist (frame backtrace
)
802 (destructuring-bind (special-operator &rest arg-forms
)
805 (format " %S\n" (list* special-operator arg-forms
)))))
808 (destructuring-bind (fn &rest args
) (cdr frame
)
809 (insert (format " %S(" fn
))
810 (loop for firstp
= t then nil
814 (insert (format "%S" arg
)))
817 ;; A container for the state of the execution of a single test and
818 ;; environment data needed during its execution.
819 (defstruct ert--test-execution-info
821 (result (assert nil
))
822 ;; A thunk that may be called when RESULT has been set to its final
823 ;; value and test execution should be terminated. Should not
825 (exit-continuation (assert nil
))
826 ;; The binding of `debugger' outside of the execution of the test.
828 ;; The binding of `ert-debug-on-error' that is in effect for the
829 ;; execution of the current test. We store it to avoid being
830 ;; affected by any new bindings the test itself may establish. (I
831 ;; don't remember whether this feature is important.)
834 (defun ert--run-test-debugger (info debugger-args
)
835 "During a test run, `debugger' is bound to a closure that calls this function.
837 This function records failures and errors and either terminates
838 the test silently or calls the interactive debugger, as
841 INFO is the ert--test-execution-info corresponding to this test
842 run. DEBUGGER-ARGS are the arguments to `debugger'."
843 (destructuring-bind (first-debugger-arg &rest more-debugger-args
)
845 (ecase first-debugger-arg
846 ((lambda debug t exit nil
)
847 (apply (ert--test-execution-info-next-debugger info
) debugger-args
))
849 (let* ((condition (first more-debugger-args
))
850 (type (case (car condition
)
852 (otherwise 'failed
)))
853 (backtrace (ert--record-backtrace))
854 (infos (reverse ert--infos
)))
855 (setf (ert--test-execution-info-result info
)
858 (make-ert-test-quit :condition condition
862 (make-ert-test-failed :condition condition
865 ;; Work around Emacs's heuristic (in eval.c) for detecting
866 ;; errors in the debugger.
867 (incf num-nonmacro-input-events
)
868 ;; FIXME: We should probably implement more fine-grained
869 ;; control a la non-t `debug-on-error' here.
871 ((ert--test-execution-info-ert-debug-on-error info
)
872 (apply (ert--test-execution-info-next-debugger info
) debugger-args
))
874 (funcall (ert--test-execution-info-exit-continuation info
)))))))
876 (defun ert--run-test-internal (ert-test-execution-info)
877 "Low-level function to run a test according to ERT-TEST-EXECUTION-INFO.
879 This mainly sets up debugger-related bindings."
880 (lexical-let ((info ert-test-execution-info
))
881 (setf (ert--test-execution-info-next-debugger info
) debugger
882 (ert--test-execution-info-ert-debug-on-error info
) ert-debug-on-error
)
884 ;; For now, each test gets its own temp buffer and its own
885 ;; window excursion, just to be safe. If this turns out to be
886 ;; too expensive, we can remove it.
888 (save-window-excursion
889 (let ((debugger (lambda (&rest debugger-args
)
890 (ert--run-test-debugger info debugger-args
)))
893 ;; FIXME: Do we need to store the old binding of this
894 ;; and consider it in `ert--run-test-debugger'?
895 (debug-ignored-errors nil
)
897 (funcall (ert-test-body (ert--test-execution-info-test info
))))))
899 (setf (ert--test-execution-info-result info
) (make-ert-test-passed)))
902 (defun ert--force-message-log-buffer-truncation ()
903 "Immediately truncate *Messages* buffer according to `message-log-max'.
905 This can be useful after reducing the value of `message-log-max'."
906 (with-current-buffer (get-buffer-create "*Messages*")
907 ;; This is a reimplementation of this part of message_dolog() in xdisp.c:
908 ;; if (NATNUMP (Vmessage_log_max))
910 ;; scan_newline (Z, Z_BYTE, BEG, BEG_BYTE,
911 ;; -XFASTINT (Vmessage_log_max) - 1, 0);
912 ;; del_range_both (BEG, BEG_BYTE, PT, PT_BYTE, 0);
914 (when (and (integerp message-log-max
) (>= message-log-max
0))
915 (let ((begin (point-min))
917 (goto-char (point-max))
918 (forward-line (- message-log-max
))
920 (delete-region begin end
)))))
922 (defvar ert--running-tests nil
923 "List of tests that are currently in execution.
925 This list is empty while no test is running, has one element
926 while a test is running, two elements while a test run from
927 inside a test is running, etc. The list is in order of nesting,
928 innermost test first.
930 The elements are of type `ert-test'.")
932 (defun ert-run-test (ert-test)
935 Returns the result and stores it in ERT-TEST's `most-recent-result' slot."
936 (setf (ert-test-most-recent-result ert-test
) nil
)
938 (lexical-let ((begin-marker
939 (with-current-buffer (get-buffer-create "*Messages*")
940 (set-marker (make-marker) (point-max)))))
942 (lexical-let ((info (make-ert--test-execution-info
945 (make-ert-test-aborted-with-non-local-exit)
946 :exit-continuation
(lambda ()
947 (return-from error nil
))))
948 (should-form-accu (list)))
950 (let ((ert--should-execution-observer
951 (lambda (form-description)
952 (push form-description should-form-accu
)))
954 (ert--running-tests (cons ert-test ert--running-tests
)))
955 (ert--run-test-internal info
))
956 (let ((result (ert--test-execution-info-result info
)))
957 (setf (ert-test-result-messages result
)
958 (with-current-buffer (get-buffer-create "*Messages*")
959 (buffer-substring begin-marker
(point-max))))
960 (ert--force-message-log-buffer-truncation)
961 (setq should-form-accu
(nreverse should-form-accu
))
962 (setf (ert-test-result-should-forms result
)
964 (setf (ert-test-most-recent-result ert-test
) result
))))
965 (set-marker begin-marker nil
))))
966 (ert-test-most-recent-result ert-test
))
968 (defun ert-running-test ()
969 "Return the top-level test currently executing."
970 (car (last ert--running-tests
)))
975 (defun ert-test-result-type-p (result result-type
)
976 "Return non-nil if RESULT matches type RESULT-TYPE.
980 nil -- Never matches.
982 :failed, :passed -- Matches corresponding results.
983 \(and TYPES...\) -- Matches if all TYPES match.
984 \(or TYPES...\) -- Matches if some TYPES match.
985 \(not TYPE\) -- Matches if TYPE does not match.
986 \(satisfies PREDICATE\) -- Matches if PREDICATE returns true when called with
988 ;; It would be easy to add `member' and `eql' types etc., but I
989 ;; haven't bothered yet.
990 (etypecase result-type
993 ((member :failed
) (ert-test-failed-p result
))
994 ((member :passed
) (ert-test-passed-p result
))
996 (destructuring-bind (operator &rest operands
) result-type
999 (case (length operands
)
1002 (and (ert-test-result-type-p result
(first operands
))
1003 (ert-test-result-type-p result
`(and ,@(rest operands
)))))))
1005 (case (length operands
)
1008 (or (ert-test-result-type-p result
(first operands
))
1009 (ert-test-result-type-p result
`(or ,@(rest operands
)))))))
1011 (assert (eql (length operands
) 1))
1012 (not (ert-test-result-type-p result
(first operands
))))
1014 (assert (eql (length operands
) 1))
1015 (funcall (first operands
) result
)))))))
1017 (defun ert-test-result-expected-p (test result
)
1018 "Return non-nil if TEST's expected result type matches RESULT."
1019 (ert-test-result-type-p result
(ert-test-expected-result-type test
)))
1021 (defun ert-select-tests (selector universe
)
1022 "Return a list of tests that match SELECTOR.
1024 UNIVERSE specifies the set of tests to select from; it should be a list
1025 of tests, or t, which refers to all tests named by symbols in `obarray'.
1029 nil -- Selects the empty set.
1030 t -- Selects UNIVERSE.
1031 :new -- Selects all tests that have not been run yet.
1032 :failed, :passed -- Select tests according to their most recent result.
1033 :expected, :unexpected -- Select tests according to their most recent result.
1034 a string -- A regular expression selecting all tests with matching names.
1035 a test -- (i.e., an object of the ert-test data-type) Selects that test.
1036 a symbol -- Selects the test that the symbol names, errors if none.
1037 \(member TESTS...) -- Selects the elements of TESTS, a list of tests
1038 or symbols naming tests.
1039 \(eql TEST\) -- Selects TEST, a test or a symbol naming a test.
1040 \(and SELECTORS...) -- Selects the tests that match all SELECTORS.
1041 \(or SELECTORS...) -- Selects the tests that match any of the SELECTORS.
1042 \(not SELECTOR) -- Selects all tests that do not match SELECTOR.
1043 \(tag TAG) -- Selects all tests that have TAG on their tags list.
1044 A tag is an arbitrary label you can apply when you define a test.
1045 \(satisfies PREDICATE) -- Selects all tests that satisfy PREDICATE.
1046 PREDICATE is a function that takes an ert-test object as argument,
1047 and returns non-nil if it is selected.
1049 Only selectors that require a superset of tests, such
1050 as (satisfies ...), strings, :new, etc. make use of UNIVERSE.
1051 Selectors that do not, such as (member ...), just return the
1052 set implied by them without checking whether it is really
1053 contained in UNIVERSE."
1054 ;; This code needs to match the etypecase in
1055 ;; `ert-insert-human-readable-selector'.
1058 ((member t
) (etypecase universe
1060 ((member t
) (ert-select-tests "" universe
))))
1061 ((member :new
) (ert-select-tests
1062 `(satisfies ,(lambda (test)
1063 (null (ert-test-most-recent-result test
))))
1065 ((member :failed
) (ert-select-tests
1066 `(satisfies ,(lambda (test)
1067 (ert-test-result-type-p
1068 (ert-test-most-recent-result test
)
1071 ((member :passed
) (ert-select-tests
1072 `(satisfies ,(lambda (test)
1073 (ert-test-result-type-p
1074 (ert-test-most-recent-result test
)
1077 ((member :expected
) (ert-select-tests
1080 (ert-test-result-expected-p
1082 (ert-test-most-recent-result test
))))
1084 ((member :unexpected
) (ert-select-tests `(not :expected
) universe
))
1087 ((member t
) (mapcar #'ert-get-test
1088 (apropos-internal selector
#'ert-test-boundp
)))
1089 (list (ert--remove-if-not (lambda (test)
1090 (and (ert-test-name test
)
1091 (string-match selector
1092 (ert-test-name test
))))
1094 (ert-test (list selector
))
1096 (assert (ert-test-boundp selector
))
1097 (list (ert-get-test selector
)))
1099 (destructuring-bind (operator &rest operands
) selector
1102 (mapcar (lambda (purported-test)
1103 (etypecase purported-test
1104 (symbol (assert (ert-test-boundp purported-test
))
1105 (ert-get-test purported-test
))
1106 (ert-test purported-test
)))
1109 (assert (eql (length operands
) 1))
1110 (ert-select-tests `(member ,@operands
) universe
))
1112 ;; Do these definitions of AND, NOT and OR satisfy de
1113 ;; Morgan's laws? Should they?
1114 (case (length operands
)
1115 (0 (ert-select-tests 't universe
))
1116 (t (ert-select-tests `(and ,@(rest operands
))
1117 (ert-select-tests (first operands
)
1120 (assert (eql (length operands
) 1))
1121 (let ((all-tests (ert-select-tests 't universe
)))
1122 (ert--set-difference all-tests
1123 (ert-select-tests (first operands
)
1126 (case (length operands
)
1127 (0 (ert-select-tests 'nil universe
))
1128 (t (ert--union (ert-select-tests (first operands
) universe
)
1129 (ert-select-tests `(or ,@(rest operands
))
1132 (assert (eql (length operands
) 1))
1133 (let ((tag (first operands
)))
1134 (ert-select-tests `(satisfies
1136 (member tag
(ert-test-tags test
))))
1139 (assert (eql (length operands
) 1))
1140 (ert--remove-if-not (first operands
)
1141 (ert-select-tests 't universe
))))))))
1143 (defun ert--insert-human-readable-selector (selector)
1144 "Insert a human-readable presentation of SELECTOR into the current buffer."
1145 ;; This is needed to avoid printing the (huge) contents of the
1146 ;; `backtrace' slot of the result objects in the
1147 ;; `most-recent-result' slots of test case objects in (eql ...) or
1148 ;; (member ...) selectors.
1149 (labels ((rec (selector)
1150 ;; This code needs to match the etypecase in `ert-select-tests'.
1153 :new
:failed
:passed
1154 :expected
:unexpected
)
1159 (if (ert-test-name selector
)
1160 (make-symbol (format "<%S>" (ert-test-name selector
)))
1161 (make-symbol "<unnamed test>")))
1163 (destructuring-bind (operator &rest operands
) selector
1165 ((member eql and not or
)
1166 `(,operator
,@(mapcar #'rec operands
)))
1167 ((member tag satisfies
)
1169 (insert (format "%S" (rec selector
)))))
1172 ;;; Facilities for running a whole set of tests.
1174 ;; The data structure that contains the set of tests being executed
1175 ;; during one particular test run, their results, the state of the
1176 ;; execution, and some statistics.
1178 ;; The data about results and expected results of tests may seem
1179 ;; redundant here, since the test objects also carry such information.
1180 ;; However, the information in the test objects may be more recent, it
1181 ;; may correspond to a different test run. We need the information
1182 ;; that corresponds to this run in order to be able to update the
1183 ;; statistics correctly when a test is re-run interactively and has a
1184 ;; different result than before.
1185 (defstruct ert--stats
1186 (selector (assert nil
))
1187 ;; The tests, in order.
1188 (tests (assert nil
) :type vector
)
1189 ;; A map of test names (or the test objects themselves for unnamed
1190 ;; tests) to indices into the `tests' vector.
1191 (test-map (assert nil
) :type hash-table
)
1192 ;; The results of the tests during this run, in order.
1193 (test-results (assert nil
) :type vector
)
1194 ;; The start times of the tests, in order, as reported by
1196 (test-start-times (assert nil
) :type vector
)
1197 ;; The end times of the tests, in order, as reported by
1199 (test-end-times (assert nil
) :type vector
)
1201 (passed-unexpected 0)
1203 (failed-unexpected 0)
1208 ;; The time at or after which the next redisplay should occur, as a
1210 (next-redisplay 0.0))
1212 (defun ert-stats-completed-expected (stats)
1213 "Return the number of tests in STATS that had expected results."
1214 (+ (ert--stats-passed-expected stats
)
1215 (ert--stats-failed-expected stats
)))
1217 (defun ert-stats-completed-unexpected (stats)
1218 "Return the number of tests in STATS that had unexpected results."
1219 (+ (ert--stats-passed-unexpected stats
)
1220 (ert--stats-failed-unexpected stats
)))
1222 (defun ert-stats-completed (stats)
1223 "Number of tests in STATS that have run so far."
1224 (+ (ert-stats-completed-expected stats
)
1225 (ert-stats-completed-unexpected stats
)))
1227 (defun ert-stats-total (stats)
1228 "Number of tests in STATS, regardless of whether they have run yet."
1229 (length (ert--stats-tests stats
)))
1231 ;; The stats object of the current run, dynamically bound. This is
1232 ;; used for the mode line progress indicator.
1233 (defvar ert--current-run-stats nil
)
1235 (defun ert--stats-test-key (test)
1236 "Return the key used for TEST in the test map of ert--stats objects.
1238 Returns the name of TEST if it has one, or TEST itself otherwise."
1239 (or (ert-test-name test
) test
))
1241 (defun ert--stats-set-test-and-result (stats pos test result
)
1242 "Change STATS by replacing the test at position POS with TEST and RESULT.
1244 Also changes the counters in STATS to match."
1245 (let* ((tests (ert--stats-tests stats
))
1246 (results (ert--stats-test-results stats
))
1247 (old-test (aref tests pos
))
1248 (map (ert--stats-test-map stats
)))
1250 (if (ert-test-result-expected-p (aref tests pos
)
1252 (etypecase (aref results pos
)
1253 (ert-test-passed (incf (ert--stats-passed-expected stats
) d
))
1254 (ert-test-failed (incf (ert--stats-failed-expected stats
) d
))
1256 (ert-test-aborted-with-non-local-exit)
1258 (etypecase (aref results pos
)
1259 (ert-test-passed (incf (ert--stats-passed-unexpected stats
) d
))
1260 (ert-test-failed (incf (ert--stats-failed-unexpected stats
) d
))
1262 (ert-test-aborted-with-non-local-exit)
1264 ;; Adjust counters to remove the result that is currently in stats.
1266 ;; Put new test and result into stats.
1267 (setf (aref tests pos
) test
1268 (aref results pos
) result
)
1269 (remhash (ert--stats-test-key old-test
) map
)
1270 (setf (gethash (ert--stats-test-key test
) map
) pos
)
1271 ;; Adjust counters to match new result.
1275 (defun ert--make-stats (tests selector
)
1276 "Create a new `ert--stats' object for running TESTS.
1278 SELECTOR is the selector that was used to select TESTS."
1279 (setq tests
(ert--coerce-to-vector tests
))
1280 (let ((map (make-hash-table :size
(length tests
))))
1282 for test across tests
1283 for key
= (ert--stats-test-key test
) do
1284 (assert (not (gethash key map
)))
1285 (setf (gethash key map
) i
))
1286 (make-ert--stats :selector selector
1289 :test-results
(make-vector (length tests
) nil
)
1290 :test-start-times
(make-vector (length tests
) nil
)
1291 :test-end-times
(make-vector (length tests
) nil
))))
1293 (defun ert-run-or-rerun-test (stats test listener
)
1294 ;; checkdoc-order: nil
1295 "Run the single test TEST and record the result using STATS and LISTENER."
1296 (let ((ert--current-run-stats stats
)
1297 (pos (ert--stats-test-pos stats test
)))
1298 (ert--stats-set-test-and-result stats pos test nil
)
1299 ;; Call listener after setting/before resetting
1300 ;; (ert--stats-current-test stats); the listener might refresh the
1301 ;; mode line display, and if the value is not set yet/any more
1302 ;; during this refresh, the mode line will flicker unnecessarily.
1303 (setf (ert--stats-current-test stats
) test
)
1304 (funcall listener
'test-started stats test
)
1305 (setf (ert-test-most-recent-result test
) nil
)
1306 (setf (aref (ert--stats-test-start-times stats
) pos
) (current-time))
1309 (setf (aref (ert--stats-test-end-times stats
) pos
) (current-time))
1310 (let ((result (ert-test-most-recent-result test
)))
1311 (ert--stats-set-test-and-result stats pos test result
)
1312 (funcall listener
'test-ended stats test result
))
1313 (setf (ert--stats-current-test stats
) nil
))))
1315 (defun ert-run-tests (selector listener
)
1316 "Run the tests specified by SELECTOR, sending progress updates to LISTENER."
1317 (let* ((tests (ert-select-tests selector t
))
1318 (stats (ert--make-stats tests selector
)))
1319 (setf (ert--stats-start-time stats
) (current-time))
1320 (funcall listener
'run-started stats
)
1323 (let ((ert--current-run-stats stats
))
1324 (force-mode-line-update)
1327 (loop for test in tests do
1328 (ert-run-or-rerun-test stats test listener
))
1329 (setq abortedp nil
))
1330 (setf (ert--stats-aborted-p stats
) abortedp
)
1331 (setf (ert--stats-end-time stats
) (current-time))
1332 (funcall listener
'run-ended stats abortedp
)))
1333 (force-mode-line-update))
1336 (defun ert--stats-test-pos (stats test
)
1337 ;; checkdoc-order: nil
1338 "Return the position (index) of TEST in the run represented by STATS."
1339 (gethash (ert--stats-test-key test
) (ert--stats-test-map stats
)))
1342 ;;; Formatting functions shared across UIs.
1344 (defun ert--format-time-iso8601 (time)
1345 "Format TIME in the variant of ISO 8601 used for timestamps in ERT."
1346 (format-time-string "%Y-%m-%d %T%z" time
))
1348 (defun ert-char-for-test-result (result expectedp
)
1349 "Return a character that represents the test result RESULT.
1351 EXPECTEDP specifies whether the result was expected."
1352 (let ((s (etypecase result
1353 (ert-test-passed ".P")
1354 (ert-test-failed "fF")
1356 (ert-test-aborted-with-non-local-exit "aA")
1357 (ert-test-quit "qQ"))))
1358 (elt s
(if expectedp
0 1))))
1360 (defun ert-string-for-test-result (result expectedp
)
1361 "Return a string that represents the test result RESULT.
1363 EXPECTEDP specifies whether the result was expected."
1364 (let ((s (etypecase result
1365 (ert-test-passed '("passed" "PASSED"))
1366 (ert-test-failed '("failed" "FAILED"))
1367 (null '("unknown" "UNKNOWN"))
1368 (ert-test-aborted-with-non-local-exit '("aborted" "ABORTED"))
1369 (ert-test-quit '("quit" "QUIT")))))
1370 (elt s
(if expectedp
0 1))))
1372 (defun ert--pp-with-indentation-and-newline (object)
1373 "Pretty-print OBJECT, indenting it to the current column of point.
1374 Ensures a final newline is inserted."
1375 (let ((begin (point)))
1376 (pp object
(current-buffer))
1377 (unless (bolp) (insert "\n"))
1382 (defun ert--insert-infos (result)
1383 "Insert `ert-info' infos from RESULT into current buffer.
1385 RESULT must be an `ert-test-result-with-condition'."
1386 (check-type result ert-test-result-with-condition
)
1387 (dolist (info (ert-test-result-with-condition-infos result
))
1388 (destructuring-bind (prefix . message
) info
1389 (let ((begin (point))
1390 (indentation (make-string (+ (length prefix
) 4) ?\s
))
1394 (insert message
"\n")
1395 (setq end
(copy-marker (point)))
1399 (while (< (point) end
)
1400 (insert indentation
)
1402 (when end
(set-marker end nil
)))))))
1405 ;;; Running tests in batch mode.
1407 (defvar ert-batch-backtrace-right-margin
70
1408 "The maximum line length for printing backtraces in `ert-run-tests-batch'.")
1411 (defun ert-run-tests-batch (&optional selector
)
1412 "Run the tests specified by SELECTOR, printing results to the terminal.
1414 SELECTOR works as described in `ert-select-tests', except if
1415 SELECTOR is nil, in which case all tests rather than none will be
1416 run; this makes the command line \"emacs -batch -l my-tests.el -f
1417 ert-run-tests-batch-and-exit\" useful.
1419 Returns the stats object."
1420 (unless selector
(setq selector
't
))
1423 (lambda (event-type &rest event-args
)
1426 (destructuring-bind (stats) event-args
1427 (message "Running %s tests (%s)"
1428 (length (ert--stats-tests stats
))
1429 (ert--format-time-iso8601 (ert--stats-start-time stats
)))))
1431 (destructuring-bind (stats abortedp
) event-args
1432 (let ((unexpected (ert-stats-completed-unexpected stats
))
1433 (expected-failures (ert--stats-failed-expected stats
)))
1434 (message "\n%sRan %s tests, %s results as expected%s (%s)%s\n"
1438 (ert-stats-total stats
)
1439 (ert-stats-completed-expected stats
)
1440 (if (zerop unexpected
)
1442 (format ", %s unexpected" unexpected
))
1443 (ert--format-time-iso8601 (ert--stats-end-time stats
))
1444 (if (zerop expected-failures
)
1446 (format "\n%s expected failures" expected-failures
)))
1447 (unless (zerop unexpected
)
1448 (message "%s unexpected results:" unexpected
)
1449 (loop for test across
(ert--stats-tests stats
)
1450 for result
= (ert-test-most-recent-result test
) do
1451 (when (not (ert-test-result-expected-p test result
))
1453 (ert-string-for-test-result result nil
)
1454 (ert-test-name test
))))
1455 (message "%s" "")))))
1459 (destructuring-bind (stats test result
) event-args
1460 (unless (ert-test-result-expected-p test result
)
1463 (message "Test %S passed unexpectedly" (ert-test-name test
)))
1464 (ert-test-result-with-condition
1465 (message "Test %S backtrace:" (ert-test-name test
))
1467 (ert--print-backtrace (ert-test-result-with-condition-backtrace
1469 (goto-char (point-min))
1471 (let ((start (point))
1472 (end (progn (end-of-line) (point))))
1474 (+ start ert-batch-backtrace-right-margin
)))
1475 (message "%s" (buffer-substring-no-properties
1479 (ert--insert-infos result
)
1481 (let ((print-escape-newlines t
)
1484 (ert--pp-with-indentation-and-newline
1485 (ert-test-result-with-condition-condition result
)))
1486 (goto-char (1- (point-max)))
1487 (assert (looking-at "\n"))
1489 (message "Test %S condition:" (ert-test-name test
))
1490 (message "%s" (buffer-string))))
1491 (ert-test-aborted-with-non-local-exit
1492 (message "Test %S aborted with non-local exit"
1493 (ert-test-name test
)))
1495 (message "Quit during %S" (ert-test-name test
)))))
1496 (let* ((max (prin1-to-string (length (ert--stats-tests stats
))))
1497 (format-string (concat "%9s %"
1498 (prin1-to-string (length max
))
1500 (message format-string
1501 (ert-string-for-test-result result
1502 (ert-test-result-expected-p
1504 (1+ (ert--stats-test-pos stats test
))
1505 (ert-test-name test
)))))))))
1508 (defun ert-run-tests-batch-and-exit (&optional selector
)
1509 "Like `ert-run-tests-batch', but exits Emacs when done.
1511 The exit status will be 0 if all test results were as expected, 1
1512 on unexpected results, or 2 if the tool detected an error outside
1513 of the tests (e.g. invalid SELECTOR or bug in the code that runs
1516 (let ((stats (ert-run-tests-batch selector
)))
1517 (kill-emacs (if (zerop (ert-stats-completed-unexpected stats
)) 0 1)))
1520 (message "Error running tests")
1525 ;;; Utility functions for load/unload actions.
1527 (defun ert--activate-font-lock-keywords ()
1528 "Activate font-lock keywords for some of ERT's symbols."
1529 (font-lock-add-keywords
1531 '(("(\\(\\<ert-deftest\\)\\>\\s *\\(\\sw+\\)?"
1532 (1 font-lock-keyword-face nil t
)
1533 (2 font-lock-function-name-face nil t
)))))
1535 (defun* ert--remove-from-list
(list-var element
&key key test
)
1536 "Remove ELEMENT from the value of LIST-VAR if present.
1538 This can be used as an inverse of `add-to-list'."
1539 (unless key
(setq key
#'identity
))
1540 (unless test
(setq test
#'equal
))
1541 (setf (symbol-value list-var
)
1542 (ert--remove* element
1543 (symbol-value list-var
)
1548 ;;; Some basic interactive functions.
1550 (defun ert-read-test-name (prompt &optional default history
1551 add-default-to-prompt
)
1552 "Read the name of a test and return it as a symbol.
1554 Prompt with PROMPT. If DEFAULT is a valid test name, use it as a
1555 default. HISTORY is the history to use; see `completing-read'.
1556 If ADD-DEFAULT-TO-PROMPT is non-nil, PROMPT will be modified to
1557 include the default, if any.
1559 Signals an error if no test name was read."
1561 (string (let ((symbol (intern-soft default
)))
1562 (unless (and symbol
(ert-test-boundp symbol
))
1563 (setq default nil
))))
1564 (symbol (setq default
1565 (if (ert-test-boundp default
)
1566 (symbol-name default
)
1568 (ert-test (setq default
(ert-test-name default
))))
1569 (when add-default-to-prompt
1570 (setq prompt
(if (null default
)
1571 (format "%s: " prompt
)
1572 (format "%s (default %s): " prompt default
))))
1573 (let ((input (completing-read prompt obarray
#'ert-test-boundp
1574 t nil history default nil
)))
1575 ;; completing-read returns an empty string if default was nil and
1576 ;; the user just hit enter.
1577 (let ((sym (intern-soft input
)))
1578 (if (ert-test-boundp sym
)
1580 (error "Input does not name a test")))))
1582 (defun ert-read-test-name-at-point (prompt)
1583 "Read the name of a test and return it as a symbol.
1584 As a default, use the symbol at point, or the test at point if in
1585 the ERT results buffer. Prompt with PROMPT, augmented with the
1587 (ert-read-test-name prompt
(ert-test-at-point) nil t
))
1589 (defun ert-find-test-other-window (test-name)
1590 "Find, in another window, the definition of TEST-NAME."
1591 (interactive (list (ert-read-test-name-at-point "Find test definition: ")))
1592 (find-function-do-it test-name
'ert-deftest
'switch-to-buffer-other-window
))
1594 (defun ert-delete-test (test-name)
1595 "Make the test TEST-NAME unbound.
1597 Nothing more than an interactive interface to `ert-make-test-unbound'."
1598 (interactive (list (ert-read-test-name-at-point "Delete test")))
1599 (ert-make-test-unbound test-name
))
1601 (defun ert-delete-all-tests ()
1602 "Make all symbols in `obarray' name no test."
1604 (when (called-interactively-p 'any
)
1605 (unless (y-or-n-p "Delete all tests? ")
1607 ;; We can't use `ert-select-tests' here since that gives us only
1608 ;; test objects, and going from them back to the test name symbols
1609 ;; can fail if the `ert-test' defstruct has been redefined.
1610 (mapc #'ert-make-test-unbound
(apropos-internal "" #'ert-test-boundp
))
1614 ;;; Display of test progress and results.
1616 ;; An entry in the results buffer ewoc. There is one entry per test.
1617 (defstruct ert--ewoc-entry
1619 ;; If the result of this test was expected, its ewoc entry is hidden
1621 (hidden-p (assert nil
))
1622 ;; An ewoc entry may be collapsed to hide details such as the error
1625 ;; I'm not sure the ability to expand and collapse entries is still
1626 ;; a useful feature.
1628 ;; By default, the ewoc entry presents the error condition with
1629 ;; certain limits on how much to print (`print-level',
1630 ;; `print-length'). The user can interactively switch to a set of
1632 (extended-printer-limits-p nil
))
1634 ;; Variables local to the results buffer.
1637 (defvar ert--results-ewoc
)
1638 ;; The stats object.
1639 (defvar ert--results-stats
)
1640 ;; A string with one character per test. Each character represents
1641 ;; the result of the corresponding test. The string is displayed near
1642 ;; the top of the buffer and serves as a progress bar.
1643 (defvar ert--results-progress-bar-string
)
1644 ;; The position where the progress bar button begins.
1645 (defvar ert--results-progress-bar-button-begin
)
1646 ;; The test result listener that updates the buffer when tests are run.
1647 (defvar ert--results-listener
)
1649 (defun ert-insert-test-name-button (test-name)
1650 "Insert a button that links to TEST-NAME."
1651 (insert-text-button (format "%S" test-name
)
1652 :type
'ert--test-name-button
1653 'ert-test-name test-name
))
1655 (defun ert--results-format-expected-unexpected (expected unexpected
)
1656 "Return a string indicating EXPECTED expected results, UNEXPECTED unexpected."
1657 (if (zerop unexpected
)
1658 (format "%s" expected
)
1659 (format "%s (%s unexpected)" (+ expected unexpected
) unexpected
)))
1661 (defun ert--results-update-ewoc-hf (ewoc stats
)
1662 "Update the header and footer of EWOC to show certain information from STATS.
1664 Also sets `ert--results-progress-bar-button-begin'."
1665 (let ((run-count (ert-stats-completed stats
))
1666 (results-buffer (current-buffer))
1667 ;; Need to save buffer-local value.
1668 (font-lock font-lock-mode
))
1673 (insert "Selector: ")
1674 (ert--insert-human-readable-selector (ert--stats-selector stats
))
1677 (format (concat "Passed: %s\n"
1680 (ert--results-format-expected-unexpected
1681 (ert--stats-passed-expected stats
)
1682 (ert--stats-passed-unexpected stats
))
1683 (ert--results-format-expected-unexpected
1684 (ert--stats-failed-expected stats
)
1685 (ert--stats-failed-unexpected stats
))
1687 (ert-stats-total stats
)))
1689 (format "Started at: %s\n"
1690 (ert--format-time-iso8601 (ert--stats-start-time stats
))))
1691 ;; FIXME: This is ugly. Need to properly define invariants of
1692 ;; the `stats' data structure.
1693 (let ((state (cond ((ert--stats-aborted-p stats
) 'aborted
)
1694 ((ert--stats-current-test stats
) 'running
)
1695 ((ert--stats-end-time stats
) 'finished
)
1701 (cond ((ert--stats-current-test stats
)
1702 (insert "Aborted during test: ")
1703 (ert-insert-test-name-button
1704 (ert-test-name (ert--stats-current-test stats
))))
1706 (insert "Aborted."))))
1708 (assert (ert--stats-current-test stats
))
1709 (insert "Running test: ")
1710 (ert-insert-test-name-button (ert-test-name
1711 (ert--stats-current-test stats
))))
1713 (assert (not (ert--stats-current-test stats
)))
1714 (insert "Finished.")))
1716 (if (ert--stats-end-time stats
)
1719 (if (ert--stats-aborted-p stats
)
1722 (ert--format-time-iso8601 (ert--stats-end-time stats
))))
1725 (let ((progress-bar-string (with-current-buffer results-buffer
1726 ert--results-progress-bar-string
)))
1727 (let ((progress-bar-button-begin
1728 (insert-text-button progress-bar-string
1729 :type
'ert--results-progress-bar-button
1730 'face
(or (and font-lock
1731 (ert-face-for-stats stats
))
1733 ;; The header gets copied verbatim to the results buffer,
1734 ;; and all positions remain the same, so
1735 ;; `progress-bar-button-begin' will be the right position
1736 ;; even in the results buffer.
1737 (with-current-buffer results-buffer
1738 (set (make-local-variable 'ert--results-progress-bar-button-begin
)
1739 progress-bar-button-begin
))))
1744 ;; We actually want an empty footer, but that would trigger a bug
1745 ;; in ewoc, sometimes clearing the entire buffer. (It's possible
1746 ;; that this bug has been fixed since this has been tested; we
1747 ;; should test it again.)
1751 (defvar ert-test-run-redisplay-interval-secs
.1
1752 "How many seconds ERT should wait between redisplays while running tests.
1754 While running tests, ERT shows the current progress, and this variable
1755 determines how frequently the progress display is updated.")
1757 (defun ert--results-update-stats-display (ewoc stats
)
1758 "Update EWOC and the mode line to show data from STATS."
1759 ;; TODO(ohler): investigate using `make-progress-reporter'.
1760 (ert--results-update-ewoc-hf ewoc stats
)
1761 (force-mode-line-update)
1763 (setf (ert--stats-next-redisplay stats
)
1764 (+ (float-time) ert-test-run-redisplay-interval-secs
)))
1766 (defun ert--results-update-stats-display-maybe (ewoc stats
)
1767 "Call `ert--results-update-stats-display' if not called recently.
1769 EWOC and STATS are arguments for `ert--results-update-stats-display'."
1770 (when (>= (float-time) (ert--stats-next-redisplay stats
))
1771 (ert--results-update-stats-display ewoc stats
)))
1773 (defun ert--tests-running-mode-line-indicator ()
1774 "Return a string for the mode line that shows the test run progress."
1775 (let* ((stats ert--current-run-stats
)
1776 (tests-total (ert-stats-total stats
))
1777 (tests-completed (ert-stats-completed stats
)))
1778 (if (>= tests-completed tests-total
)
1779 (format " ERT(%s/%s,finished)" tests-completed tests-total
)
1780 (format " ERT(%s/%s):%s"
1781 (1+ tests-completed
)
1783 (if (null (ert--stats-current-test stats
))
1786 (ert-test-name (ert--stats-current-test stats
))))))))
1788 (defun ert--make-xrefs-region (begin end
)
1789 "Attach cross-references to function names between BEGIN and END.
1791 BEGIN and END specify a region in the current buffer."
1794 (narrow-to-region begin end
)
1795 ;; Inhibit optimization in `debugger-make-xrefs' that would
1796 ;; sometimes insert unrelated backtrace info into our buffer.
1797 (let ((debugger-previous-backtrace nil
))
1798 (debugger-make-xrefs)))))
1800 (defun ert--string-first-line (s)
1801 "Return the first line of S, or S if it contains no newlines.
1803 The return value does not include the line terminator."
1804 (substring s
0 (ert--string-position ?
\n s
)))
1806 (defun ert-face-for-test-result (expectedp)
1807 "Return a face that shows whether a test result was expected or unexpected.
1809 If EXPECTEDP is nil, returns the face for unexpected results; if
1810 non-nil, returns the face for expected results.."
1811 (if expectedp
'ert-test-result-expected
'ert-test-result-unexpected
))
1813 (defun ert-face-for-stats (stats)
1814 "Return a face that represents STATS."
1815 (cond ((ert--stats-aborted-p stats
) 'nil
)
1816 ((plusp (ert-stats-completed-unexpected stats
))
1817 (ert-face-for-test-result nil
))
1818 ((eql (ert-stats-completed-expected stats
) (ert-stats-total stats
))
1819 (ert-face-for-test-result t
))
1822 (defun ert--print-test-for-ewoc (entry)
1823 "The ewoc print function for ewoc test entries. ENTRY is the entry to print."
1824 (let* ((test (ert--ewoc-entry-test entry
))
1825 (stats ert--results-stats
)
1826 (result (let ((pos (ert--stats-test-pos stats test
)))
1828 (aref (ert--stats-test-results stats
) pos
)))
1829 (hiddenp (ert--ewoc-entry-hidden-p entry
))
1830 (expandedp (ert--ewoc-entry-expanded-p entry
))
1831 (extended-printer-limits-p (ert--ewoc-entry-extended-printer-limits-p
1835 (let ((expectedp (ert-test-result-expected-p test result
)))
1836 (insert-text-button (format "%c" (ert-char-for-test-result
1838 :type
'ert--results-expand-collapse-button
1839 'face
(or (and font-lock-mode
1840 (ert-face-for-test-result
1844 (ert-insert-test-name-button (ert-test-name test
))
1846 (when (and expandedp
(not (eql result
'nil
)))
1847 (when (ert-test-documentation test
)
1850 (ert--string-first-line (ert-test-documentation test
))
1851 'font-lock-face
'font-lock-doc-face
)
1855 (if (ert-test-result-expected-p test result
)
1856 (insert " passed\n")
1857 (insert " passed unexpectedly\n"))
1859 (ert-test-result-with-condition
1860 (ert--insert-infos result
)
1861 (let ((print-escape-newlines t
)
1862 (print-level (if extended-printer-limits-p
12 6))
1863 (print-length (if extended-printer-limits-p
100 10)))
1865 (let ((begin (point)))
1866 (ert--pp-with-indentation-and-newline
1867 (ert-test-result-with-condition-condition result
))
1868 (ert--make-xrefs-region begin
(point)))))
1869 (ert-test-aborted-with-non-local-exit
1870 (insert " aborted\n"))
1872 (insert " quit\n")))
1876 (defun ert--results-font-lock-function (enabledp)
1877 "Redraw the ERT results buffer after font-lock-mode was switched on or off.
1879 ENABLEDP is true if font-lock-mode is switched on, false
1881 (ert--results-update-ewoc-hf ert--results-ewoc ert--results-stats
)
1882 (ewoc-refresh ert--results-ewoc
)
1883 (font-lock-default-function enabledp
))
1885 (defun ert--setup-results-buffer (stats listener buffer-name
)
1886 "Set up a test results buffer.
1888 STATS is the stats object; LISTENER is the results listener;
1889 BUFFER-NAME, if non-nil, is the buffer name to use."
1890 (unless buffer-name
(setq buffer-name
"*ert*"))
1891 (let ((buffer (get-buffer-create buffer-name
)))
1892 (with-current-buffer buffer
1893 (let ((inhibit-read-only t
))
1894 (buffer-disable-undo)
1897 ;; Erase buffer again in case switching out of the previous
1898 ;; mode inserted anything. (This happens e.g. when switching
1899 ;; from ert-results-mode to ert-results-mode when
1900 ;; font-lock-mode turns itself off in change-major-mode-hook.)
1902 (set (make-local-variable 'font-lock-function
)
1903 'ert--results-font-lock-function
)
1904 (let ((ewoc (ewoc-create 'ert--print-test-for-ewoc nil nil t
)))
1905 (set (make-local-variable 'ert--results-ewoc
) ewoc
)
1906 (set (make-local-variable 'ert--results-stats
) stats
)
1907 (set (make-local-variable 'ert--results-progress-bar-string
)
1908 (make-string (ert-stats-total stats
)
1909 (ert-char-for-test-result nil t
)))
1910 (set (make-local-variable 'ert--results-listener
) listener
)
1911 (loop for test across
(ert--stats-tests stats
) do
1912 (ewoc-enter-last ewoc
1913 (make-ert--ewoc-entry :test test
:hidden-p t
)))
1914 (ert--results-update-ewoc-hf ert--results-ewoc ert--results-stats
)
1915 (goto-char (1- (point-max)))
1919 (defvar ert--selector-history nil
1920 "List of recent test selectors read from terminal.")
1922 ;; Should OUTPUT-BUFFER-NAME and MESSAGE-FN really be arguments here?
1923 ;; They are needed only for our automated self-tests at the moment.
1924 ;; Or should there be some other mechanism?
1926 (defun ert-run-tests-interactively (selector
1927 &optional output-buffer-name message-fn
)
1928 "Run the tests specified by SELECTOR and display the results in a buffer.
1930 SELECTOR works as described in `ert-select-tests'.
1931 OUTPUT-BUFFER-NAME and MESSAGE-FN should normally be nil; they
1932 are used for automated self-tests and specify which buffer to use
1933 and how to display message."
1935 (list (let ((default (if ert--selector-history
1936 ;; Can't use `first' here as this form is
1937 ;; not compiled, and `first' is not
1938 ;; defined without cl.
1939 (car ert--selector-history
)
1941 (read-from-minibuffer (if (null default
)
1943 (format "Run tests (default %s): " default
))
1944 nil nil t
'ert--selector-history
1947 (unless message-fn
(setq message-fn
'message
))
1948 (lexical-let ((output-buffer-name output-buffer-name
)
1951 (message-fn message-fn
))
1953 (lambda (event-type &rest event-args
)
1956 (destructuring-bind (stats) event-args
1957 (setq buffer
(ert--setup-results-buffer stats
1959 output-buffer-name
))
1960 (pop-to-buffer buffer
)))
1962 (destructuring-bind (stats abortedp
) event-args
1964 "%sRan %s tests, %s results were as expected%s"
1968 (ert-stats-total stats
)
1969 (ert-stats-completed-expected stats
)
1971 (ert-stats-completed-unexpected stats
)))
1972 (if (zerop unexpected
)
1974 (format ", %s unexpected" unexpected
))))
1975 (ert--results-update-stats-display (with-current-buffer buffer
1979 (destructuring-bind (stats test
) event-args
1980 (with-current-buffer buffer
1981 (let* ((ewoc ert--results-ewoc
)
1982 (pos (ert--stats-test-pos stats test
))
1983 (node (ewoc-nth ewoc pos
)))
1985 (setf (ert--ewoc-entry-test (ewoc-data node
)) test
)
1986 (aset ert--results-progress-bar-string pos
1987 (ert-char-for-test-result nil t
))
1988 (ert--results-update-stats-display-maybe ewoc stats
)
1989 (ewoc-invalidate ewoc node
)))))
1991 (destructuring-bind (stats test result
) event-args
1992 (with-current-buffer buffer
1993 (let* ((ewoc ert--results-ewoc
)
1994 (pos (ert--stats-test-pos stats test
))
1995 (node (ewoc-nth ewoc pos
)))
1996 (when (ert--ewoc-entry-hidden-p (ewoc-data node
))
1997 (setf (ert--ewoc-entry-hidden-p (ewoc-data node
))
1998 (ert-test-result-expected-p test result
)))
1999 (aset ert--results-progress-bar-string pos
2000 (ert-char-for-test-result result
2001 (ert-test-result-expected-p
2003 (ert--results-update-stats-display-maybe ewoc stats
)
2004 (ewoc-invalidate ewoc node
))))))))
2009 (defalias 'ert
'ert-run-tests-interactively
)
2012 ;;; Simple view mode for auxiliary information like stack traces or
2013 ;;; messages. Mainly binds "q" for quit.
2015 (define-derived-mode ert-simple-view-mode special-mode
"ERT-View"
2016 "Major mode for viewing auxiliary information in ERT.")
2018 ;;; Commands and button actions for the results buffer.
2020 (define-derived-mode ert-results-mode special-mode
"ERT-Results"
2021 "Major mode for viewing results of ERT test runs.")
2023 (loop for
(key binding
) in
2024 '(;; Stuff that's not in the menu.
2025 ("\t" forward-button
)
2026 ([backtab] backward-button)
2027 ("j" ert-results-jump-between-summary-and-result)
2028 ("L" ert-results-toggle-printer-limits-for-test-at-point)
2029 ("n" ert-results-next-test)
2030 ("p" ert-results-previous-test)
2031 ;; Stuff that is in the menu.
2032 ("R" ert-results-rerun-all-tests)
2033 ("r" ert-results-rerun-test-at-point)
2034 ("d" ert-results-rerun-test-at-point-debugging-errors)
2035 ("." ert-results-find-test-at-point-other-window)
2036 ("b" ert-results-pop-to-backtrace-for-test-at-point)
2037 ("m" ert-results-pop-to-messages-for-test-at-point)
2038 ("l" ert-results-pop-to-should-forms-for-test-at-point)
2039 ("h" ert-results-describe-test-at-point)
2040 ("D" ert-delete-test)
2041 ("T" ert-results-pop-to-timings)
2044 (define-key ert-results-mode-map key binding))
2046 (easy-menu-define ert-results-mode-menu ert-results-mode-map
2047 "Menu for `ert-results-mode'."
2049 ["Re-run all tests" ert-results-rerun-all-tests]
2051 ["Re-run test" ert-results-rerun-test-at-point]
2052 ["Debug test" ert-results-rerun-test-at-point-debugging-errors]
2053 ["Show test definition" ert-results-find-test-at-point-other-window]
2055 ["Show backtrace" ert-results-pop-to-backtrace-for-test-at-point]
2056 ["Show messages" ert-results-pop-to-messages-for-test-at-point]
2057 ["Show `should' forms" ert-results-pop-to-should-forms-for-test-at-point]
2058 ["Describe test" ert-results-describe-test-at-point]
2060 ["Delete test" ert-delete-test]
2062 ["Show execution time of each test" ert-results-pop-to-timings]
2065 (define-button-type 'ert--results-progress-bar-button
2066 'action #'ert--results-progress-bar-button-action
2067 'help-echo "mouse-2, RET: Reveal test result")
2069 (define-button-type 'ert--test-name-button
2070 'action #'ert--test-name-button-action
2071 'help-echo "mouse-2, RET: Find test definition")
2073 (define-button-type 'ert--results-expand-collapse-button
2074 'action #'ert--results-expand-collapse-button-action
2075 'help-echo "mouse-2, RET: Expand/collapse test result")
2077 (defun ert--results-test-node-or-null-at-point ()
2078 "If point is on a valid ewoc node, return it; return nil otherwise.
2080 To be used in the ERT results buffer."
2081 (let* ((ewoc ert--results-ewoc)
2082 (node (ewoc-locate ewoc)))
2083 ;; `ewoc-locate' will return an arbitrary node when point is on
2084 ;; header or footer, or when all nodes are invisible. So we need
2085 ;; to validate its return value here.
2087 ;; Update: I'm seeing nil being returned in some cases now,
2088 ;; perhaps this has been changed?
2090 (>= (point) (ewoc-location node))
2091 (not (ert--ewoc-entry-hidden-p (ewoc-data node))))
2095 (defun ert--results-test-node-at-point ()
2096 "If point is on a valid ewoc node, return it; signal an error otherwise.
2098 To be used in the ERT results buffer."
2099 (or (ert--results-test-node-or-null-at-point)
2100 (error "No test at point")))
2102 (defun ert-results-next-test ()
2103 "Move point to the next test.
2105 To be used in the ERT results buffer."
2107 (ert--results-move (ewoc-locate ert--results-ewoc) 'ewoc-next
2110 (defun ert-results-previous-test ()
2111 "Move point to the previous test.
2113 To be used in the ERT results buffer."
2115 (ert--results-move (ewoc-locate ert--results-ewoc) 'ewoc-prev
2118 (defun ert--results-move (node ewoc-fn error-message)
2119 "Move point from NODE to the previous or next node.
2121 EWOC-FN specifies the direction and should be either `ewoc-prev'
2122 or `ewoc-next'. If there are no more nodes in that direction, an
2123 error is signaled with the message ERROR-MESSAGE."
2125 (setq node (funcall ewoc-fn ert--results-ewoc node))
2127 (error "%s" error-message))
2128 (unless (ert--ewoc-entry-hidden-p (ewoc-data node))
2129 (goto-char (ewoc-location node))
2132 (defun ert--results-expand-collapse-button-action (button)
2133 "Expand or collapse the test node BUTTON belongs to."
2134 (let* ((ewoc ert--results-ewoc)
2135 (node (save-excursion
2136 (goto-char (ert--button-action-position))
2137 (ert--results-test-node-at-point)))
2138 (entry (ewoc-data node)))
2139 (setf (ert--ewoc-entry-expanded-p entry)
2140 (not (ert--ewoc-entry-expanded-p entry)))
2141 (ewoc-invalidate ewoc node)))
2143 (defun ert-results-find-test-at-point-other-window ()
2144 "Find the definition of the test at point in another window.
2146 To be used in the ERT results buffer."
2148 (let ((name (ert-test-at-point)))
2150 (error "No test at point"))
2151 (ert-find-test-other-window name)))
2153 (defun ert--test-name-button-action (button)
2154 "Find the definition of the test BUTTON belongs to, in another window."
2155 (let ((name (button-get button 'ert-test-name)))
2156 (ert-find-test-other-window name)))
2158 (defun ert--ewoc-position (ewoc node)
2159 ;; checkdoc-order: nil
2160 "Return the position of NODE in EWOC, or nil if NODE is not in EWOC."
2162 for node-here = (ewoc-nth ewoc 0) then (ewoc-next ewoc node-here)
2163 do (when (eql node node-here)
2165 finally (return nil)))
2167 (defun ert-results-jump-between-summary-and-result ()
2168 "Jump back and forth between the test run summary and individual test results.
2170 From an ewoc node, jumps to the character that represents the
2171 same test in the progress bar, and vice versa.
2173 To be used in the ERT results buffer."
2174 ;; Maybe this command isn't actually needed much, but if it is, it
2175 ;; seems like an indication that the UI design is not optimal. If
2176 ;; jumping back and forth between a summary at the top of the buffer
2177 ;; and the error log in the remainder of the buffer is useful, then
2178 ;; the summary apparently needs to be easily accessible from the
2179 ;; error log, and perhaps it would be better to have it in a
2180 ;; separate buffer to keep it visible.
2182 (let ((ewoc ert--results-ewoc)
2183 (progress-bar-begin ert--results-progress-bar-button-begin))
2184 (cond ((ert--results-test-node-or-null-at-point)
2185 (let* ((node (ert--results-test-node-at-point))
2186 (pos (ert--ewoc-position ewoc node)))
2187 (goto-char (+ progress-bar-begin pos))))
2188 ((and (<= progress-bar-begin (point))
2189 (< (point) (button-end (button-at progress-bar-begin))))
2190 (let* ((node (ewoc-nth ewoc (- (point) progress-bar-begin)))
2191 (entry (ewoc-data node)))
2192 (when (ert--ewoc-entry-hidden-p entry)
2193 (setf (ert--ewoc-entry-hidden-p entry) nil)
2194 (ewoc-invalidate ewoc node))
2195 (ewoc-goto-node ewoc node)))
2197 (goto-char progress-bar-begin)))))
2199 (defun ert-test-at-point ()
2200 "Return the name of the test at point as a symbol, or nil if none."
2201 (or (and (eql major-mode 'ert-results-mode)
2202 (let ((test (ert--results-test-at-point-no-redefinition)))
2203 (and test (ert-test-name test))))
2204 (let* ((thing (thing-at-point 'symbol))
2205 (sym (intern-soft thing)))
2206 (and (ert-test-boundp sym)
2209 (defun ert--results-test-at-point-no-redefinition ()
2210 "Return the test at point, or nil.
2212 To be used in the ERT results buffer."
2213 (assert (eql major-mode 'ert-results-mode))
2214 (if (ert--results-test-node-or-null-at-point)
2215 (let* ((node (ert--results-test-node-at-point))
2216 (test (ert--ewoc-entry-test (ewoc-data node))))
2218 (let ((progress-bar-begin ert--results-progress-bar-button-begin))
2219 (when (and (<= progress-bar-begin (point))
2220 (< (point) (button-end (button-at progress-bar-begin))))
2221 (let* ((test-index (- (point) progress-bar-begin))
2222 (test (aref (ert--stats-tests ert--results-stats)
2226 (defun ert--results-test-at-point-allow-redefinition ()
2227 "Look up the test at point, and check whether it has been redefined.
2229 To be used in the ERT results buffer.
2231 Returns a list of two elements: the test (or nil) and a symbol
2232 specifying whether the test has been redefined.
2234 If a new test has been defined with the same name as the test at
2235 point, replaces the test at point with the new test, and returns
2236 the new test and the symbol `redefined'.
2238 If the test has been deleted, returns the old test and the symbol
2241 If the test is still current, returns the test and the symbol nil.
2243 If there is no test at point, returns a list with two nils."
2244 (let ((test (ert--results-test-at-point-no-redefinition)))
2247 ((null (ert-test-name test))
2250 (let* ((name (ert-test-name test))
2251 (new-test (and (ert-test-boundp name)
2252 (ert-get-test name))))
2253 (cond ((eql test new-test)
2258 (ert--results-update-after-test-redefinition
2259 (ert--stats-test-pos ert--results-stats test)
2261 `(,new-test redefined))))))))
2263 (defun ert--results-update-after-test-redefinition (pos new-test)
2264 "Update results buffer after the test at pos POS has been redefined.
2266 Also updates the stats object. NEW-TEST is the new test
2268 (let* ((stats ert--results-stats)
2269 (ewoc ert--results-ewoc)
2270 (node (ewoc-nth ewoc pos))
2271 (entry (ewoc-data node)))
2272 (ert--stats-set-test-and-result stats pos new-test nil)
2273 (setf (ert--ewoc-entry-test entry) new-test
2274 (aref ert--results-progress-bar-string pos) (ert-char-for-test-result
2276 (ewoc-invalidate ewoc node))
2279 (defun ert--button-action-position ()
2280 "The buffer position where the last button action was triggered."
2281 (cond ((integerp last-command-event)
2283 ((eventp last-command-event)
2284 (posn-point (event-start last-command-event)))
2287 (defun ert--results-progress-bar-button-action (button)
2288 "Jump to details for the test represented by the character clicked in BUTTON."
2289 (goto-char (ert--button-action-position))
2290 (ert-results-jump-between-summary-and-result))
2292 (defun ert-results-rerun-all-tests ()
2293 "Re-run all tests, using the same selector.
2295 To be used in the ERT results buffer."
2297 (assert (eql major-mode 'ert-results-mode))
2298 (let ((selector (ert--stats-selector ert--results-stats)))
2299 (ert-run-tests-interactively selector (buffer-name))))
2301 (defun ert-results-rerun-test-at-point ()
2302 "Re-run the test at point.
2304 To be used in the ERT results buffer."
2306 (destructuring-bind (test redefinition-state)
2307 (ert--results-test-at-point-allow-redefinition)
2309 (error "No test at point"))
2310 (let* ((stats ert--results-stats)
2311 (progress-message (format "Running %stest %S"
2312 (ecase redefinition-state
2314 (redefined "new definition of ")
2315 (deleted "deleted "))
2316 (ert-test-name test))))
2317 ;; Need to save and restore point manually here: When point is on
2318 ;; the first visible ewoc entry while the header is updated, point
2319 ;; moves to the top of the buffer. This is undesirable, and a
2320 ;; simple `save-excursion' doesn't prevent it.
2321 (let ((point (point)))
2325 (message "%s..." progress-message)
2326 (ert-run-or-rerun-test stats test
2327 ert--results-listener))
2328 (ert--results-update-stats-display ert--results-ewoc stats)
2331 (let ((result (ert-test-most-recent-result test)))
2332 (ert-string-for-test-result
2333 result (ert-test-result-expected-p test result)))))
2334 (goto-char point))))))
2336 (defun ert-results-rerun-test-at-point-debugging-errors ()
2337 "Re-run the test at point with `ert-debug-on-error' bound to t.
2339 To be used in the ERT results buffer."
2341 (let ((ert-debug-on-error t))
2342 (ert-results-rerun-test-at-point)))
2344 (defun ert-results-pop-to-backtrace-for-test-at-point ()
2345 "Display the backtrace for the test at point.
2347 To be used in the ERT results buffer."
2349 (let* ((test (ert--results-test-at-point-no-redefinition))
2350 (stats ert--results-stats)
2351 (pos (ert--stats-test-pos stats test))
2352 (result (aref (ert--stats-test-results stats) pos)))
2354 (ert-test-passed (error "Test passed, no backtrace available"))
2355 (ert-test-result-with-condition
2356 (let ((backtrace (ert-test-result-with-condition-backtrace result))
2357 (buffer (get-buffer-create "*ERT Backtrace*")))
2358 (pop-to-buffer buffer)
2359 (let ((inhibit-read-only t))
2360 (buffer-disable-undo)
2362 (ert-simple-view-mode)
2363 ;; Use unibyte because `debugger-setup-buffer' also does so.
2364 (set-buffer-multibyte nil)
2365 (setq truncate-lines t)
2366 (ert--print-backtrace backtrace)
2367 (debugger-make-xrefs)
2368 (goto-char (point-min))
2369 (insert "Backtrace for test `")
2370 (ert-insert-test-name-button (ert-test-name test))
2371 (insert "':\n")))))))
2373 (defun ert-results-pop-to-messages-for-test-at-point ()
2374 "Display the part of the *Messages* buffer generated during the test at point.
2376 To be used in the ERT results buffer."
2378 (let* ((test (ert--results-test-at-point-no-redefinition))
2379 (stats ert--results-stats)
2380 (pos (ert--stats-test-pos stats test))
2381 (result (aref (ert--stats-test-results stats) pos)))
2382 (let ((buffer (get-buffer-create "*ERT Messages*")))
2383 (pop-to-buffer buffer)
2384 (let ((inhibit-read-only t))
2385 (buffer-disable-undo)
2387 (ert-simple-view-mode)
2388 (insert (ert-test-result-messages result))
2389 (goto-char (point-min))
2390 (insert "Messages for test `")
2391 (ert-insert-test-name-button (ert-test-name test))
2394 (defun ert-results-pop-to-should-forms-for-test-at-point ()
2395 "Display the list of `should' forms executed during the test at point.
2397 To be used in the ERT results buffer."
2399 (let* ((test (ert--results-test-at-point-no-redefinition))
2400 (stats ert--results-stats)
2401 (pos (ert--stats-test-pos stats test))
2402 (result (aref (ert--stats-test-results stats) pos)))
2403 (let ((buffer (get-buffer-create "*ERT list of should forms*")))
2404 (pop-to-buffer buffer)
2405 (let ((inhibit-read-only t))
2406 (buffer-disable-undo)
2408 (ert-simple-view-mode)
2409 (if (null (ert-test-result-should-forms result))
2410 (insert "\n(No should forms during this test.)\n")
2411 (loop for form-description in (ert-test-result-should-forms result)
2414 (insert (format "%s: " i))
2415 (let ((begin (point)))
2416 (ert--pp-with-indentation-and-newline form-description)
2417 (ert--make-xrefs-region begin (point)))))
2418 (goto-char (point-min))
2419 (insert "`should' forms executed during test `")
2420 (ert-insert-test-name-button (ert-test-name test))
2423 (insert (concat "(Values are shallow copies and may have "
2424 "looked different during the test if they\n"
2425 "have been modified destructively.)\n"))
2426 (forward-line 1)))))
2428 (defun ert-results-toggle-printer-limits-for-test-at-point ()
2429 "Toggle how much of the condition to print for the test at point.
2431 To be used in the ERT results buffer."
2433 (let* ((ewoc ert--results-ewoc)
2434 (node (ert--results-test-node-at-point))
2435 (entry (ewoc-data node)))
2436 (setf (ert--ewoc-entry-extended-printer-limits-p entry)
2437 (not (ert--ewoc-entry-extended-printer-limits-p entry)))
2438 (ewoc-invalidate ewoc node)))
2440 (defun ert-results-pop-to-timings ()
2441 "Display test timings for the last run.
2443 To be used in the ERT results buffer."
2445 (let* ((stats ert--results-stats)
2446 (start-times (ert--stats-test-start-times stats))
2447 (end-times (ert--stats-test-end-times stats))
2448 (buffer (get-buffer-create "*ERT timings*"))
2449 (data (loop for test across (ert--stats-tests stats)
2450 for start-time across (ert--stats-test-start-times stats)
2451 for end-time across (ert--stats-test-end-times stats)
2453 (float-time (subtract-time end-time
2455 (setq data (sort data (lambda (a b)
2456 (> (second a) (second b)))))
2457 (pop-to-buffer buffer)
2458 (let ((inhibit-read-only t))
2459 (buffer-disable-undo)
2461 (ert-simple-view-mode)
2463 (insert "(No data)\n")
2464 (insert (format "%-3s %8s %8s\n" "" "time" "cumul"))
2465 (loop for (test time) in data
2466 for cumul-time = time then (+ cumul-time time)
2468 (let ((begin (point)))
2469 (insert (format "%3s: %8.3f %8.3f " i time cumul-time))
2470 (ert-insert-test-name-button (ert-test-name test))
2472 (goto-char (point-min))
2473 (insert "Tests by run time (seconds):\n\n")
2477 (defun ert-describe-test (test-or-test-name)
2478 "Display the documentation for TEST-OR-TEST-NAME (a symbol or ert-test)."
2479 (interactive (list (ert-read-test-name-at-point "Describe test")))
2480 (when (< emacs-major-version 24)
2481 (error "Requires Emacs 24"))
2484 (etypecase test-or-test-name
2485 (symbol (setq test-name test-or-test-name
2486 test-definition (ert-get-test test-or-test-name)))
2487 (ert-test (setq test-name (ert-test-name test-or-test-name)
2488 test-definition test-or-test-name)))
2489 (help-setup-xref (list #'ert-describe-test test-or-test-name)
2490 (called-interactively-p 'interactive))
2492 (with-help-window (help-buffer)
2493 (with-current-buffer (help-buffer)
2494 (insert (if test-name (format "%S" test-name) "<anonymous test>"))
2495 (insert " is a test")
2496 (let ((file-name (and test-name
2497 (symbol-file test-name 'ert-deftest))))
2499 (insert " defined in `" (file-name-nondirectory file-name) "'")
2501 (re-search-backward "`\\([^`']+\\)'" nil t)
2502 (help-xref-button 1 'help-function-def test-name file-name)))
2504 (fill-region-as-paragraph (point-min) (point))
2506 (unless (and (ert-test-boundp test-name)
2507 (eql (ert-get-test test-name) test-definition))
2508 (let ((begin (point)))
2509 (insert "Note: This test has been redefined or deleted, "
2510 "this documentation refers to an old definition.")
2511 (fill-region-as-paragraph begin (point)))
2513 (insert (or (ert-test-documentation test-definition)
2514 "It is not documented.")
2517 (defun ert-results-describe-test-at-point ()
2518 "Display the documentation of the test at point.
2520 To be used in the ERT results buffer."
2522 (ert-describe-test (ert--results-test-at-point-no-redefinition)))
2525 ;;; Actions on load/unload.
2527 (add-to-list 'find-function-regexp-alist '(ert-deftest . ert--find-test-regexp))
2528 (add-to-list 'minor-mode-alist '(ert--current-run-stats
2530 (ert--tests-running-mode-line-indicator))))
2531 (add-to-list 'emacs-lisp-mode-hook 'ert--activate-font-lock-keywords)
2533 (defun ert--unload-function ()
2534 "Unload function to undo the side-effects of loading ert.el."
2535 (ert--remove-from-list 'find-function-regexp-alist 'ert-deftest :key #'car)
2536 (ert--remove-from-list 'minor-mode-alist 'ert--current-run-stats :key #'car)
2537 (ert--remove-from-list 'emacs-lisp-mode-hook
2538 'ert--activate-font-lock-keywords)
2541 (defvar ert-unload-hook '())
2542 (add-hook 'ert-unload-hook 'ert--unload-function)
2547 ;;; ert.el ends here