1 ;;; ert.el --- Emacs Lisp Regression Testing
3 ;; Copyright (C) 2007-2008, 2010-2011 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-not-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 signalling 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 funtion: 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 signalling 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 ((signalled-conditions (get (car condition
) 'error-conditions
))
493 (handled-conditions (etypecase type
495 (symbol (list type
)))))
496 (assert signalled-conditions
)
497 (unless (ert--intersection signalled-conditions handled-conditions
)
499 (funcall form-description-fn
)
502 :fail-reason
(concat "the error signalled 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 signalled 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 signalled 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 signalled, 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-not-equal'."
576 (fixnum (list x
(format "#x%x" x
) (format "?%c" x
)))
579 (defun ert--explain-not-equal (a b
)
580 "Explainer function for `equal'.
582 Returns a programmer-readable explanation of why A and B are not
583 `equal', or nil if they are."
584 (if (not (equal (type-of a
) (type-of b
)))
585 `(different-types ,a
,b
)
588 (let ((a-proper-p (ert--proper-list-p a
))
589 (b-proper-p (ert--proper-list-p b
)))
590 (if (not (eql (not a-proper-p
) (not b-proper-p
)))
591 `(one-list-proper-one-improper ,a
,b
)
593 (if (not (equal (length a
) (length b
)))
594 `(proper-lists-of-different-length ,(length a
) ,(length b
)
597 ,(ert--mismatch a b
))
601 for xi
= (ert--explain-not-equal ai bi
)
602 do
(when xi
(return `(list-elt ,i
,xi
)))
603 finally
(assert (equal a b
) t
)))
604 (let ((car-x (ert--explain-not-equal (car a
) (car b
))))
607 (let ((cdr-x (ert--explain-not-equal (cdr a
) (cdr b
))))
610 (assert (equal a b
) t
)
612 (array (if (not (equal (length a
) (length b
)))
613 `(arrays-of-different-length ,(length a
) ,(length b
)
615 ,@(unless (char-table-p a
)
617 ,(ert--mismatch a b
))))
621 for xi
= (ert--explain-not-equal ai bi
)
622 do
(when xi
(return `(array-elt ,i
,xi
)))
623 finally
(assert (equal a b
) t
))))
624 (atom (if (not (equal a b
))
625 (if (and (symbolp a
) (symbolp b
) (string= a b
))
626 `(different-symbols-with-the-same-name ,a
,b
)
627 `(different-atoms ,(ert--explain-format-atom a
)
628 ,(ert--explain-format-atom b
)))
630 (put 'equal
'ert-explainer
'ert--explain-not-equal
)
632 (defun ert--significant-plist-keys (plist)
633 "Return the keys of PLIST that have non-null values, in order."
634 (assert (zerop (mod (length plist
) 2)) t
)
635 (loop for
(key value . rest
) on plist by
#'cddr
636 unless
(or (null value
) (memq key accu
)) collect key into accu
637 finally
(return accu
)))
639 (defun ert--plist-difference-explanation (a b
)
640 "Return a programmer-readable explanation of why A and B are different plists.
642 Returns nil if they are equivalent, i.e., have the same value for
643 each key, where absent values are treated as nil. The order of
644 key/value pairs in each list does not matter."
645 (assert (zerop (mod (length a
) 2)) t
)
646 (assert (zerop (mod (length b
) 2)) t
)
647 ;; Normalizing the plists would be another way to do this but it
648 ;; requires a total ordering on all lisp objects (since any object
649 ;; is valid as a text property key). Perhaps defining such an
650 ;; ordering is useful in other contexts, too, but it's a lot of
651 ;; work, so let's punt on it for now.
652 (let* ((keys-a (ert--significant-plist-keys a
))
653 (keys-b (ert--significant-plist-keys b
))
654 (keys-in-a-not-in-b (ert--set-difference-eq keys-a keys-b
))
655 (keys-in-b-not-in-a (ert--set-difference-eq keys-b keys-a
)))
656 (flet ((explain-with-key (key)
657 (let ((value-a (plist-get a key
))
658 (value-b (plist-get b key
)))
659 (assert (not (equal value-a value-b
)) t
)
660 `(different-properties-for-key
661 ,key
,(ert--explain-not-equal-including-properties value-a
663 (cond (keys-in-a-not-in-b
664 (explain-with-key (first keys-in-a-not-in-b
)))
666 (explain-with-key (first keys-in-b-not-in-a
)))
668 (loop for key in keys-a
669 when
(not (equal (plist-get a key
) (plist-get b key
)))
670 return
(explain-with-key key
)))))))
672 (defun ert--abbreviate-string (s len suffixp
)
673 "Shorten string S to at most LEN chars.
675 If SUFFIXP is non-nil, returns a suffix of S, otherwise a prefix."
676 (let ((n (length s
)))
680 (substring s
(- n len
)))
682 (substring s
0 len
)))))
684 (defun ert--explain-not-equal-including-properties (a b
)
685 "Explainer function for `ert-equal-including-properties'.
687 Returns a programmer-readable explanation of why A and B are not
688 `ert-equal-including-properties', or nil if they are."
689 (if (not (equal a b
))
690 (ert--explain-not-equal a b
)
691 (assert (stringp a
) t
)
692 (assert (stringp b
) t
)
693 (assert (eql (length a
) (length b
)) t
)
694 (loop for i from
0 to
(length a
)
695 for props-a
= (text-properties-at i a
)
696 for props-b
= (text-properties-at i b
)
697 for difference
= (ert--plist-difference-explanation props-a props-b
)
699 (return `(char ,i
,(substring-no-properties a i
(1+ i
))
702 ,(ert--abbreviate-string
703 (substring-no-properties a
0 i
)
706 ,(ert--abbreviate-string
707 (substring-no-properties a
(1+ i
))
709 ;; TODO(ohler): Get `equal-including-properties' fixed in
710 ;; Emacs, delete `ert-equal-including-properties', and
711 ;; re-enable this assertion.
712 ;;finally (assert (equal-including-properties a b) t)
714 (put 'ert-equal-including-properties
716 'ert--explain-not-equal-including-properties
)
719 ;;; Implementation of `ert-info'.
721 ;; TODO(ohler): The name `info' clashes with
722 ;; `ert--test-execution-info'. One or both should be renamed.
723 (defvar ert--infos
'()
724 "The stack of `ert-info' infos that currently apply.
726 Bound dynamically. This is a list of (PREFIX . MESSAGE) pairs.")
728 (defmacro* ert-info
((message-form &key
((:prefix prefix-form
) "Info: "))
730 "Evaluate MESSAGE-FORM and BODY, and report the message if BODY fails.
732 To be used within ERT tests. MESSAGE-FORM should evaluate to a
733 string that will be displayed together with the test result if
734 the test fails. PREFIX-FORM should evaluate to a string as well
735 and is displayed in front of the value of MESSAGE-FORM."
736 (declare (debug ((form &rest
[sexp form
]) body
))
738 `(let ((ert--infos (cons (cons ,prefix-form
,message-form
) ert--infos
)))
743 ;;; Facilities for running a single test.
745 (defvar ert-debug-on-error nil
746 "Non-nil means enter debugger when a test fails or terminates with an error.")
748 ;; The data structures that represent the result of running a test.
749 (defstruct ert-test-result
753 (defstruct (ert-test-passed (:include ert-test-result
)))
754 (defstruct (ert-test-result-with-condition (:include ert-test-result
))
755 (condition (assert nil
))
756 (backtrace (assert nil
))
757 (infos (assert nil
)))
758 (defstruct (ert-test-quit (:include ert-test-result-with-condition
)))
759 (defstruct (ert-test-failed (:include ert-test-result-with-condition
)))
760 (defstruct (ert-test-aborted-with-non-local-exit (:include ert-test-result
)))
763 (defun ert--record-backtrace ()
764 "Record the current backtrace (as a list) and return it."
765 ;; Since the backtrace is stored in the result object, result
766 ;; objects must only be printed with appropriate limits
767 ;; (`print-level' and `print-length') in place. For interactive
768 ;; use, the cost of ensuring this possibly outweighs the advantage
769 ;; of storing the backtrace for
770 ;; `ert-results-pop-to-backtrace-for-test-at-point' given that we
771 ;; already have `ert-results-rerun-test-debugging-errors-at-point'.
772 ;; For batch use, however, printing the backtrace may be useful.
774 ;; 6 is the number of frames our own debugger adds (when
775 ;; compiled; more when interpreted). FIXME: Need to describe a
776 ;; procedure for determining this constant.
778 for frame
= (backtrace-frame i
)
782 (defun ert--print-backtrace (backtrace)
783 "Format the backtrace BACKTRACE to the current buffer."
784 ;; This is essentially a reimplementation of Fbacktrace
785 ;; (src/eval.c), but for a saved backtrace, not the current one.
786 (let ((print-escape-newlines t
)
789 (dolist (frame backtrace
)
793 (destructuring-bind (special-operator &rest arg-forms
)
796 (format " %S\n" (list* special-operator arg-forms
)))))
799 (destructuring-bind (fn &rest args
) (cdr frame
)
800 (insert (format " %S(" fn
))
801 (loop for firstp
= t then nil
805 (insert (format "%S" arg
)))
808 ;; A container for the state of the execution of a single test and
809 ;; environment data needed during its execution.
810 (defstruct ert--test-execution-info
812 (result (assert nil
))
813 ;; A thunk that may be called when RESULT has been set to its final
814 ;; value and test execution should be terminated. Should not
816 (exit-continuation (assert nil
))
817 ;; The binding of `debugger' outside of the execution of the test.
819 ;; The binding of `ert-debug-on-error' that is in effect for the
820 ;; execution of the current test. We store it to avoid being
821 ;; affected by any new bindings the test itself may establish. (I
822 ;; don't remember whether this feature is important.)
825 (defun ert--run-test-debugger (info debugger-args
)
826 "During a test run, `debugger' is bound to a closure that calls this function.
828 This function records failures and errors and either terminates
829 the test silently or calls the interactive debugger, as
832 INFO is the ert--test-execution-info corresponding to this test
833 run. DEBUGGER-ARGS are the arguments to `debugger'."
834 (destructuring-bind (first-debugger-arg &rest more-debugger-args
)
836 (ecase first-debugger-arg
837 ((lambda debug t exit nil
)
838 (apply (ert--test-execution-info-next-debugger info
) debugger-args
))
840 (let* ((condition (first more-debugger-args
))
841 (type (case (car condition
)
843 (otherwise 'failed
)))
844 (backtrace (ert--record-backtrace))
845 (infos (reverse ert--infos
)))
846 (setf (ert--test-execution-info-result info
)
849 (make-ert-test-quit :condition condition
853 (make-ert-test-failed :condition condition
856 ;; Work around Emacs' heuristic (in eval.c) for detecting
857 ;; errors in the debugger.
858 (incf num-nonmacro-input-events
)
859 ;; FIXME: We should probably implement more fine-grained
860 ;; control a la non-t `debug-on-error' here.
862 ((ert--test-execution-info-ert-debug-on-error info
)
863 (apply (ert--test-execution-info-next-debugger info
) debugger-args
))
865 (funcall (ert--test-execution-info-exit-continuation info
)))))))
867 (defun ert--run-test-internal (ert-test-execution-info)
868 "Low-level function to run a test according to ERT-TEST-EXECUTION-INFO.
870 This mainly sets up debugger-related bindings."
871 (lexical-let ((info ert-test-execution-info
))
872 (setf (ert--test-execution-info-next-debugger info
) debugger
873 (ert--test-execution-info-ert-debug-on-error info
) ert-debug-on-error
)
875 ;; For now, each test gets its own temp buffer and its own
876 ;; window excursion, just to be safe. If this turns out to be
877 ;; too expensive, we can remove it.
879 (save-window-excursion
880 (let ((debugger (lambda (&rest debugger-args
)
881 (ert--run-test-debugger info debugger-args
)))
884 ;; FIXME: Do we need to store the old binding of this
885 ;; and consider it in `ert--run-test-debugger'?
886 (debug-ignored-errors nil
)
888 (funcall (ert-test-body (ert--test-execution-info-test info
))))))
890 (setf (ert--test-execution-info-result info
) (make-ert-test-passed)))
893 (defun ert--force-message-log-buffer-truncation ()
894 "Immediately truncate *Messages* buffer according to `message-log-max'.
896 This can be useful after reducing the value of `message-log-max'."
897 (with-current-buffer (get-buffer-create "*Messages*")
898 ;; This is a reimplementation of this part of message_dolog() in xdisp.c:
899 ;; if (NATNUMP (Vmessage_log_max))
901 ;; scan_newline (Z, Z_BYTE, BEG, BEG_BYTE,
902 ;; -XFASTINT (Vmessage_log_max) - 1, 0);
903 ;; del_range_both (BEG, BEG_BYTE, PT, PT_BYTE, 0);
905 (when (and (integerp message-log-max
) (>= message-log-max
0))
906 (let ((begin (point-min))
908 (goto-char (point-max))
909 (forward-line (- message-log-max
))
911 (delete-region begin end
)))))
913 (defvar ert--running-tests nil
914 "List of tests that are currently in execution.
916 This list is empty while no test is running, has one element
917 while a test is running, two elements while a test run from
918 inside a test is running, etc. The list is in order of nesting,
919 innermost test first.
921 The elements are of type `ert-test'.")
923 (defun ert-run-test (ert-test)
926 Returns the result and stores it in ERT-TEST's `most-recent-result' slot."
927 (setf (ert-test-most-recent-result ert-test
) nil
)
929 (lexical-let ((begin-marker
930 (with-current-buffer (get-buffer-create "*Messages*")
931 (set-marker (make-marker) (point-max)))))
933 (lexical-let ((info (make-ert--test-execution-info
936 (make-ert-test-aborted-with-non-local-exit)
937 :exit-continuation
(lambda ()
938 (return-from error nil
))))
939 (should-form-accu (list)))
941 (let ((ert--should-execution-observer
942 (lambda (form-description)
943 (push form-description should-form-accu
)))
945 (ert--running-tests (cons ert-test ert--running-tests
)))
946 (ert--run-test-internal info
))
947 (let ((result (ert--test-execution-info-result info
)))
948 (setf (ert-test-result-messages result
)
949 (with-current-buffer (get-buffer-create "*Messages*")
950 (buffer-substring begin-marker
(point-max))))
951 (ert--force-message-log-buffer-truncation)
952 (setq should-form-accu
(nreverse should-form-accu
))
953 (setf (ert-test-result-should-forms result
)
955 (setf (ert-test-most-recent-result ert-test
) result
))))
956 (set-marker begin-marker nil
))))
957 (ert-test-most-recent-result ert-test
))
959 (defun ert-running-test ()
960 "Return the top-level test currently executing."
961 (car (last ert--running-tests
)))
966 (defun ert-test-result-type-p (result result-type
)
967 "Return non-nil if RESULT matches type RESULT-TYPE.
971 nil -- Never matches.
973 :failed, :passed -- Matches corresponding results.
974 \(and TYPES...\) -- Matches if all TYPES match.
975 \(or TYPES...\) -- Matches if some TYPES match.
976 \(not TYPE\) -- Matches if TYPE does not match.
977 \(satisfies PREDICATE\) -- Matches if PREDICATE returns true when called with
979 ;; It would be easy to add `member' and `eql' types etc., but I
980 ;; haven't bothered yet.
981 (etypecase result-type
984 ((member :failed
) (ert-test-failed-p result
))
985 ((member :passed
) (ert-test-passed-p result
))
987 (destructuring-bind (operator &rest operands
) result-type
990 (case (length operands
)
993 (and (ert-test-result-type-p result
(first operands
))
994 (ert-test-result-type-p result
`(and ,@(rest operands
)))))))
996 (case (length operands
)
999 (or (ert-test-result-type-p result
(first operands
))
1000 (ert-test-result-type-p result
`(or ,@(rest operands
)))))))
1002 (assert (eql (length operands
) 1))
1003 (not (ert-test-result-type-p result
(first operands
))))
1005 (assert (eql (length operands
) 1))
1006 (funcall (first operands
) result
)))))))
1008 (defun ert-test-result-expected-p (test result
)
1009 "Return non-nil if TEST's expected result type matches RESULT."
1010 (ert-test-result-type-p result
(ert-test-expected-result-type test
)))
1012 (defun ert-select-tests (selector universe
)
1013 "Return the tests that match SELECTOR.
1015 UNIVERSE specifies the set of tests to select from; it should be
1016 a list of tests, or t, which refers to all tests named by symbols
1019 Returns the set of tests as a list.
1023 nil -- Selects the empty set.
1024 t -- Selects UNIVERSE.
1025 :new -- Selects all tests that have not been run yet.
1026 :failed, :passed -- Select tests according to their most recent result.
1027 :expected, :unexpected -- Select tests according to their most recent result.
1028 a string -- Selects all tests that have a name that matches the string,
1030 a test -- Selects that test.
1031 a symbol -- Selects the test that the symbol names, errors if none.
1032 \(member TESTS...\) -- Selects TESTS, a list of tests or symbols naming tests.
1033 \(eql TEST\) -- Selects TEST, a test or a symbol naming a test.
1034 \(and SELECTORS...\) -- Selects the tests that match all SELECTORS.
1035 \(or SELECTORS...\) -- Selects the tests that match any SELECTOR.
1036 \(not SELECTOR\) -- Selects all tests that do not match SELECTOR.
1037 \(tag TAG) -- Selects all tests that have TAG on their tags list.
1038 \(satisfies PREDICATE\) -- Selects all tests that satisfy PREDICATE.
1040 Only selectors that require a superset of tests, such
1041 as (satisfies ...), strings, :new, etc. make use of UNIVERSE.
1042 Selectors that do not, such as \(member ...\), just return the
1043 set implied by them without checking whether it is really
1044 contained in UNIVERSE."
1045 ;; This code needs to match the etypecase in
1046 ;; `ert-insert-human-readable-selector'.
1049 ((member t
) (etypecase universe
1051 ((member t
) (ert-select-tests "" universe
))))
1052 ((member :new
) (ert-select-tests
1053 `(satisfies ,(lambda (test)
1054 (null (ert-test-most-recent-result test
))))
1056 ((member :failed
) (ert-select-tests
1057 `(satisfies ,(lambda (test)
1058 (ert-test-result-type-p
1059 (ert-test-most-recent-result test
)
1062 ((member :passed
) (ert-select-tests
1063 `(satisfies ,(lambda (test)
1064 (ert-test-result-type-p
1065 (ert-test-most-recent-result test
)
1068 ((member :expected
) (ert-select-tests
1071 (ert-test-result-expected-p
1073 (ert-test-most-recent-result test
))))
1075 ((member :unexpected
) (ert-select-tests `(not :expected
) universe
))
1078 ((member t
) (mapcar #'ert-get-test
1079 (apropos-internal selector
#'ert-test-boundp
)))
1080 (list (ert--remove-if-not (lambda (test)
1081 (and (ert-test-name test
)
1082 (string-match selector
1083 (ert-test-name test
))))
1085 (ert-test (list selector
))
1087 (assert (ert-test-boundp selector
))
1088 (list (ert-get-test selector
)))
1090 (destructuring-bind (operator &rest operands
) selector
1093 (mapcar (lambda (purported-test)
1094 (etypecase purported-test
1095 (symbol (assert (ert-test-boundp purported-test
))
1096 (ert-get-test purported-test
))
1097 (ert-test purported-test
)))
1100 (assert (eql (length operands
) 1))
1101 (ert-select-tests `(member ,@operands
) universe
))
1103 ;; Do these definitions of AND, NOT and OR satisfy de
1104 ;; Morgan's laws? Should they?
1105 (case (length operands
)
1106 (0 (ert-select-tests 't universe
))
1107 (t (ert-select-tests `(and ,@(rest operands
))
1108 (ert-select-tests (first operands
)
1111 (assert (eql (length operands
) 1))
1112 (let ((all-tests (ert-select-tests 't universe
)))
1113 (ert--set-difference all-tests
1114 (ert-select-tests (first operands
)
1117 (case (length operands
)
1118 (0 (ert-select-tests 'nil universe
))
1119 (t (ert--union (ert-select-tests (first operands
) universe
)
1120 (ert-select-tests `(or ,@(rest operands
))
1123 (assert (eql (length operands
) 1))
1124 (let ((tag (first operands
)))
1125 (ert-select-tests `(satisfies
1127 (member tag
(ert-test-tags test
))))
1130 (assert (eql (length operands
) 1))
1131 (ert--remove-if-not (first operands
)
1132 (ert-select-tests 't universe
))))))))
1134 (defun ert--insert-human-readable-selector (selector)
1135 "Insert a human-readable presentation of SELECTOR into the current buffer."
1136 ;; This is needed to avoid printing the (huge) contents of the
1137 ;; `backtrace' slot of the result objects in the
1138 ;; `most-recent-result' slots of test case objects in (eql ...) or
1139 ;; (member ...) selectors.
1140 (labels ((rec (selector)
1141 ;; This code needs to match the etypecase in `ert-select-tests'.
1144 :new
:failed
:passed
1145 :expected
:unexpected
)
1150 (if (ert-test-name selector
)
1151 (make-symbol (format "<%S>" (ert-test-name selector
)))
1152 (make-symbol "<unnamed test>")))
1154 (destructuring-bind (operator &rest operands
) selector
1156 ((member eql and not or
)
1157 `(,operator
,@(mapcar #'rec operands
)))
1158 ((member tag satisfies
)
1160 (insert (format "%S" (rec selector
)))))
1163 ;;; Facilities for running a whole set of tests.
1165 ;; The data structure that contains the set of tests being executed
1166 ;; during one particular test run, their results, the state of the
1167 ;; execution, and some statistics.
1169 ;; The data about results and expected results of tests may seem
1170 ;; redundant here, since the test objects also carry such information.
1171 ;; However, the information in the test objects may be more recent, it
1172 ;; may correspond to a different test run. We need the information
1173 ;; that corresponds to this run in order to be able to update the
1174 ;; statistics correctly when a test is re-run interactively and has a
1175 ;; different result than before.
1176 (defstruct ert--stats
1177 (selector (assert nil
))
1178 ;; The tests, in order.
1179 (tests (assert nil
) :type vector
)
1180 ;; A map of test names (or the test objects themselves for unnamed
1181 ;; tests) to indices into the `tests' vector.
1182 (test-map (assert nil
) :type hash-table
)
1183 ;; The results of the tests during this run, in order.
1184 (test-results (assert nil
) :type vector
)
1185 ;; The start times of the tests, in order, as reported by
1187 (test-start-times (assert nil
) :type vector
)
1188 ;; The end times of the tests, in order, as reported by
1190 (test-end-times (assert nil
) :type vector
)
1192 (passed-unexpected 0)
1194 (failed-unexpected 0)
1199 ;; The time at or after which the next redisplay should occur, as a
1201 (next-redisplay 0.0))
1203 (defun ert-stats-completed-expected (stats)
1204 "Return the number of tests in STATS that had expected results."
1205 (+ (ert--stats-passed-expected stats
)
1206 (ert--stats-failed-expected stats
)))
1208 (defun ert-stats-completed-unexpected (stats)
1209 "Return the number of tests in STATS that had unexpected results."
1210 (+ (ert--stats-passed-unexpected stats
)
1211 (ert--stats-failed-unexpected stats
)))
1213 (defun ert-stats-completed (stats)
1214 "Number of tests in STATS that have run so far."
1215 (+ (ert-stats-completed-expected stats
)
1216 (ert-stats-completed-unexpected stats
)))
1218 (defun ert-stats-total (stats)
1219 "Number of tests in STATS, regardless of whether they have run yet."
1220 (length (ert--stats-tests stats
)))
1222 ;; The stats object of the current run, dynamically bound. This is
1223 ;; used for the mode line progress indicator.
1224 (defvar ert--current-run-stats nil
)
1226 (defun ert--stats-test-key (test)
1227 "Return the key used for TEST in the test map of ert--stats objects.
1229 Returns the name of TEST if it has one, or TEST itself otherwise."
1230 (or (ert-test-name test
) test
))
1232 (defun ert--stats-set-test-and-result (stats pos test result
)
1233 "Change STATS by replacing the test at position POS with TEST and RESULT.
1235 Also changes the counters in STATS to match."
1236 (let* ((tests (ert--stats-tests stats
))
1237 (results (ert--stats-test-results stats
))
1238 (old-test (aref tests pos
))
1239 (map (ert--stats-test-map stats
)))
1241 (if (ert-test-result-expected-p (aref tests pos
)
1243 (etypecase (aref results pos
)
1244 (ert-test-passed (incf (ert--stats-passed-expected stats
) d
))
1245 (ert-test-failed (incf (ert--stats-failed-expected stats
) d
))
1247 (ert-test-aborted-with-non-local-exit))
1248 (etypecase (aref results pos
)
1249 (ert-test-passed (incf (ert--stats-passed-unexpected stats
) d
))
1250 (ert-test-failed (incf (ert--stats-failed-unexpected stats
) d
))
1252 (ert-test-aborted-with-non-local-exit)))))
1253 ;; Adjust counters to remove the result that is currently in stats.
1255 ;; Put new test and result into stats.
1256 (setf (aref tests pos
) test
1257 (aref results pos
) result
)
1258 (remhash (ert--stats-test-key old-test
) map
)
1259 (setf (gethash (ert--stats-test-key test
) map
) pos
)
1260 ;; Adjust counters to match new result.
1264 (defun ert--make-stats (tests selector
)
1265 "Create a new `ert--stats' object for running TESTS.
1267 SELECTOR is the selector that was used to select TESTS."
1268 (setq tests
(ert--coerce-to-vector tests
))
1269 (let ((map (make-hash-table :size
(length tests
))))
1271 for test across tests
1272 for key
= (ert--stats-test-key test
) do
1273 (assert (not (gethash key map
)))
1274 (setf (gethash key map
) i
))
1275 (make-ert--stats :selector selector
1278 :test-results
(make-vector (length tests
) nil
)
1279 :test-start-times
(make-vector (length tests
) nil
)
1280 :test-end-times
(make-vector (length tests
) nil
))))
1282 (defun ert-run-or-rerun-test (stats test listener
)
1283 ;; checkdoc-order: nil
1284 "Run the single test TEST and record the result using STATS and LISTENER."
1285 (let ((ert--current-run-stats stats
)
1286 (pos (ert--stats-test-pos stats test
)))
1287 (ert--stats-set-test-and-result stats pos test nil
)
1288 ;; Call listener after setting/before resetting
1289 ;; (ert--stats-current-test stats); the listener might refresh the
1290 ;; mode line display, and if the value is not set yet/any more
1291 ;; during this refresh, the mode line will flicker unnecessarily.
1292 (setf (ert--stats-current-test stats
) test
)
1293 (funcall listener
'test-started stats test
)
1294 (setf (ert-test-most-recent-result test
) nil
)
1295 (setf (aref (ert--stats-test-start-times stats
) pos
) (current-time))
1298 (setf (aref (ert--stats-test-end-times stats
) pos
) (current-time))
1299 (let ((result (ert-test-most-recent-result test
)))
1300 (ert--stats-set-test-and-result stats pos test result
)
1301 (funcall listener
'test-ended stats test result
))
1302 (setf (ert--stats-current-test stats
) nil
))))
1304 (defun ert-run-tests (selector listener
)
1305 "Run the tests specified by SELECTOR, sending progress updates to LISTENER."
1306 (let* ((tests (ert-select-tests selector t
))
1307 (stats (ert--make-stats tests selector
)))
1308 (setf (ert--stats-start-time stats
) (current-time))
1309 (funcall listener
'run-started stats
)
1312 (let ((ert--current-run-stats stats
))
1313 (force-mode-line-update)
1316 (loop for test in tests do
1317 (ert-run-or-rerun-test stats test listener
))
1318 (setq abortedp nil
))
1319 (setf (ert--stats-aborted-p stats
) abortedp
)
1320 (setf (ert--stats-end-time stats
) (current-time))
1321 (funcall listener
'run-ended stats abortedp
)))
1322 (force-mode-line-update))
1325 (defun ert--stats-test-pos (stats test
)
1326 ;; checkdoc-order: nil
1327 "Return the position (index) of TEST in the run represented by STATS."
1328 (gethash (ert--stats-test-key test
) (ert--stats-test-map stats
)))
1331 ;;; Formatting functions shared across UIs.
1333 (defun ert--format-time-iso8601 (time)
1334 "Format TIME in the variant of ISO 8601 used for timestamps in ERT."
1335 (format-time-string "%Y-%m-%d %T%z" time
))
1337 (defun ert-char-for-test-result (result expectedp
)
1338 "Return a character that represents the test result RESULT.
1340 EXPECTEDP specifies whether the result was expected."
1341 (let ((s (etypecase result
1342 (ert-test-passed ".P")
1343 (ert-test-failed "fF")
1345 (ert-test-aborted-with-non-local-exit "aA"))))
1346 (elt s
(if expectedp
0 1))))
1348 (defun ert-string-for-test-result (result expectedp
)
1349 "Return a string that represents the test result RESULT.
1351 EXPECTEDP specifies whether the result was expected."
1352 (let ((s (etypecase result
1353 (ert-test-passed '("passed" "PASSED"))
1354 (ert-test-failed '("failed" "FAILED"))
1355 (null '("unknown" "UNKNOWN"))
1356 (ert-test-aborted-with-non-local-exit '("aborted" "ABORTED")))))
1357 (elt s
(if expectedp
0 1))))
1359 (defun ert--pp-with-indentation-and-newline (object)
1360 "Pretty-print OBJECT, indenting it to the current column of point.
1361 Ensures a final newline is inserted."
1362 (let ((begin (point)))
1363 (pp object
(current-buffer))
1364 (unless (bolp) (insert "\n"))
1369 (defun ert--insert-infos (result)
1370 "Insert `ert-info' infos from RESULT into current buffer.
1372 RESULT must be an `ert-test-result-with-condition'."
1373 (check-type result ert-test-result-with-condition
)
1374 (dolist (info (ert-test-result-with-condition-infos result
))
1375 (destructuring-bind (prefix . message
) info
1376 (let ((begin (point))
1377 (indentation (make-string (+ (length prefix
) 4) ?\s
))
1381 (insert message
"\n")
1382 (setq end
(copy-marker (point)))
1386 (while (< (point) end
)
1387 (insert indentation
)
1389 (when end
(set-marker end nil
)))))))
1392 ;;; Running tests in batch mode.
1394 (defvar ert-batch-backtrace-right-margin
70
1395 "*The maximum line length for printing backtraces in `ert-run-tests-batch'.")
1398 (defun ert-run-tests-batch (&optional selector
)
1399 "Run the tests specified by SELECTOR, printing results to the terminal.
1401 SELECTOR works as described in `ert-select-tests', except if
1402 SELECTOR is nil, in which case all tests rather than none will be
1403 run; this makes the command line \"emacs -batch -l my-tests.el -f
1404 ert-run-tests-batch-and-exit\" useful.
1406 Returns the stats object."
1407 (unless selector
(setq selector
't
))
1410 (lambda (event-type &rest event-args
)
1413 (destructuring-bind (stats) event-args
1414 (message "Running %s tests (%s)"
1415 (length (ert--stats-tests stats
))
1416 (ert--format-time-iso8601 (ert--stats-start-time stats
)))))
1418 (destructuring-bind (stats abortedp
) event-args
1419 (let ((unexpected (ert-stats-completed-unexpected stats
))
1420 (expected-failures (ert--stats-failed-expected stats
)))
1421 (message "\n%sRan %s tests, %s results as expected%s (%s)%s\n"
1425 (ert-stats-total stats
)
1426 (ert-stats-completed-expected stats
)
1427 (if (zerop unexpected
)
1429 (format ", %s unexpected" unexpected
))
1430 (ert--format-time-iso8601 (ert--stats-end-time stats
))
1431 (if (zerop expected-failures
)
1433 (format "\n%s expected failures" expected-failures
)))
1434 (unless (zerop unexpected
)
1435 (message "%s unexpected results:" unexpected
)
1436 (loop for test across
(ert--stats-tests stats
)
1437 for result
= (ert-test-most-recent-result test
) do
1438 (when (not (ert-test-result-expected-p test result
))
1440 (ert-string-for-test-result result nil
)
1441 (ert-test-name test
))))
1442 (message "%s" "")))))
1446 (destructuring-bind (stats test result
) event-args
1447 (unless (ert-test-result-expected-p test result
)
1450 (message "Test %S passed unexpectedly" (ert-test-name test
)))
1451 (ert-test-result-with-condition
1452 (message "Test %S backtrace:" (ert-test-name test
))
1454 (ert--print-backtrace (ert-test-result-with-condition-backtrace
1456 (goto-char (point-min))
1458 (let ((start (point))
1459 (end (progn (end-of-line) (point))))
1461 (+ start ert-batch-backtrace-right-margin
)))
1462 (message "%s" (buffer-substring-no-properties
1466 (ert--insert-infos result
)
1468 (let ((print-escape-newlines t
)
1471 (let ((begin (point)))
1472 (ert--pp-with-indentation-and-newline
1473 (ert-test-result-with-condition-condition result
))))
1474 (goto-char (1- (point-max)))
1475 (assert (looking-at "\n"))
1477 (message "Test %S condition:" (ert-test-name test
))
1478 (message "%s" (buffer-string))))
1479 (ert-test-aborted-with-non-local-exit
1480 (message "Test %S aborted with non-local exit"
1481 (ert-test-name test
)))))
1482 (let* ((max (prin1-to-string (length (ert--stats-tests stats
))))
1483 (format-string (concat "%9s %"
1484 (prin1-to-string (length max
))
1486 (message format-string
1487 (ert-string-for-test-result result
1488 (ert-test-result-expected-p
1490 (1+ (ert--stats-test-pos stats test
))
1491 (ert-test-name test
)))))))))
1494 (defun ert-run-tests-batch-and-exit (&optional selector
)
1495 "Like `ert-run-tests-batch', but exits Emacs when done.
1497 The exit status will be 0 if all test results were as expected, 1
1498 on unexpected results, or 2 if the tool detected an error outside
1499 of the tests (e.g. invalid SELECTOR or bug in the code that runs
1502 (let ((stats (ert-run-tests-batch selector
)))
1503 (kill-emacs (if (zerop (ert-stats-completed-unexpected stats
)) 0 1)))
1506 (message "Error running tests")
1511 ;;; Utility functions for load/unload actions.
1513 (defun ert--activate-font-lock-keywords ()
1514 "Activate font-lock keywords for some of ERT's symbols."
1515 (font-lock-add-keywords
1517 '(("(\\(\\<ert-deftest\\)\\>\\s *\\(\\sw+\\)?"
1518 (1 font-lock-keyword-face nil t
)
1519 (2 font-lock-function-name-face nil t
)))))
1521 (defun* ert--remove-from-list
(list-var element
&key key test
)
1522 "Remove ELEMENT from the value of LIST-VAR if present.
1524 This can be used as an inverse of `add-to-list'."
1525 (unless key
(setq key
#'identity
))
1526 (unless test
(setq test
#'equal
))
1527 (setf (symbol-value list-var
)
1528 (ert--remove* element
1529 (symbol-value list-var
)
1534 ;;; Some basic interactive functions.
1536 (defun ert-read-test-name (prompt &optional default history
1537 add-default-to-prompt
)
1538 "Read the name of a test and return it as a symbol.
1540 Prompt with PROMPT. If DEFAULT is a valid test name, use it as a
1541 default. HISTORY is the history to use; see `completing-read'.
1542 If ADD-DEFAULT-TO-PROMPT is non-nil, PROMPT will be modified to
1543 include the default, if any.
1545 Signals an error if no test name was read."
1547 (string (let ((symbol (intern-soft default
)))
1548 (unless (and symbol
(ert-test-boundp symbol
))
1549 (setq default nil
))))
1550 (symbol (setq default
1551 (if (ert-test-boundp default
)
1552 (symbol-name default
)
1554 (ert-test (setq default
(ert-test-name default
))))
1555 (when add-default-to-prompt
1556 (setq prompt
(if (null default
)
1557 (format "%s: " prompt
)
1558 (format "%s (default %s): " prompt default
))))
1559 (let ((input (completing-read prompt obarray
#'ert-test-boundp
1560 t nil history default nil
)))
1561 ;; completing-read returns an empty string if default was nil and
1562 ;; the user just hit enter.
1563 (let ((sym (intern-soft input
)))
1564 (if (ert-test-boundp sym
)
1566 (error "Input does not name a test")))))
1568 (defun ert-read-test-name-at-point (prompt)
1569 "Read the name of a test and return it as a symbol.
1570 As a default, use the symbol at point, or the test at point if in
1571 the ERT results buffer. Prompt with PROMPT, augmented with the
1573 (ert-read-test-name prompt
(ert-test-at-point) nil t
))
1575 (defun ert-find-test-other-window (test-name)
1576 "Find, in another window, the definition of TEST-NAME."
1577 (interactive (list (ert-read-test-name-at-point "Find test definition: ")))
1578 (find-function-do-it test-name
'ert-deftest
'switch-to-buffer-other-window
))
1580 (defun ert-delete-test (test-name)
1581 "Make the test TEST-NAME unbound.
1583 Nothing more than an interactive interface to `ert-make-test-unbound'."
1584 (interactive (list (ert-read-test-name-at-point "Delete test")))
1585 (ert-make-test-unbound test-name
))
1587 (defun ert-delete-all-tests ()
1588 "Make all symbols in `obarray' name no test."
1590 (when (interactive-p)
1591 (unless (y-or-n-p "Delete all tests? ")
1593 ;; We can't use `ert-select-tests' here since that gives us only
1594 ;; test objects, and going from them back to the test name symbols
1595 ;; can fail if the `ert-test' defstruct has been redefined.
1596 (mapc #'ert-make-test-unbound
(apropos-internal "" #'ert-test-boundp
))
1600 ;;; Display of test progress and results.
1602 ;; An entry in the results buffer ewoc. There is one entry per test.
1603 (defstruct ert--ewoc-entry
1605 ;; If the result of this test was expected, its ewoc entry is hidden
1607 (hidden-p (assert nil
))
1608 ;; An ewoc entry may be collapsed to hide details such as the error
1611 ;; I'm not sure the ability to expand and collapse entries is still
1612 ;; a useful feature.
1614 ;; By default, the ewoc entry presents the error condition with
1615 ;; certain limits on how much to print (`print-level',
1616 ;; `print-length'). The user can interactively switch to a set of
1618 (extended-printer-limits-p nil
))
1620 ;; Variables local to the results buffer.
1623 (defvar ert--results-ewoc
)
1624 ;; The stats object.
1625 (defvar ert--results-stats
)
1626 ;; A string with one character per test. Each character represents
1627 ;; the result of the corresponding test. The string is displayed near
1628 ;; the top of the buffer and serves as a progress bar.
1629 (defvar ert--results-progress-bar-string
)
1630 ;; The position where the progress bar button begins.
1631 (defvar ert--results-progress-bar-button-begin
)
1632 ;; The test result listener that updates the buffer when tests are run.
1633 (defvar ert--results-listener
)
1635 (defun ert-insert-test-name-button (test-name)
1636 "Insert a button that links to TEST-NAME."
1637 (insert-text-button (format "%S" test-name
)
1638 :type
'ert--test-name-button
1639 'ert-test-name test-name
))
1641 (defun ert--results-format-expected-unexpected (expected unexpected
)
1642 "Return a string indicating EXPECTED expected results, UNEXPECTED unexpected."
1643 (if (zerop unexpected
)
1644 (format "%s" expected
)
1645 (format "%s (%s unexpected)" (+ expected unexpected
) unexpected
)))
1647 (defun ert--results-update-ewoc-hf (ewoc stats
)
1648 "Update the header and footer of EWOC to show certain information from STATS.
1650 Also sets `ert--results-progress-bar-button-begin'."
1651 (let ((run-count (ert-stats-completed stats
))
1652 (results-buffer (current-buffer))
1653 ;; Need to save buffer-local value.
1654 (font-lock font-lock-mode
))
1659 (insert "Selector: ")
1660 (ert--insert-human-readable-selector (ert--stats-selector stats
))
1663 (format (concat "Passed: %s\n"
1666 (ert--results-format-expected-unexpected
1667 (ert--stats-passed-expected stats
)
1668 (ert--stats-passed-unexpected stats
))
1669 (ert--results-format-expected-unexpected
1670 (ert--stats-failed-expected stats
)
1671 (ert--stats-failed-unexpected stats
))
1673 (ert-stats-total stats
)))
1675 (format "Started at: %s\n"
1676 (ert--format-time-iso8601 (ert--stats-start-time stats
))))
1677 ;; FIXME: This is ugly. Need to properly define invariants of
1678 ;; the `stats' data structure.
1679 (let ((state (cond ((ert--stats-aborted-p stats
) 'aborted
)
1680 ((ert--stats-current-test stats
) 'running
)
1681 ((ert--stats-end-time stats
) 'finished
)
1687 (cond ((ert--stats-current-test stats
)
1688 (insert "Aborted during test: ")
1689 (ert-insert-test-name-button
1690 (ert-test-name (ert--stats-current-test stats
))))
1692 (insert "Aborted."))))
1694 (assert (ert--stats-current-test stats
))
1695 (insert "Running test: ")
1696 (ert-insert-test-name-button (ert-test-name
1697 (ert--stats-current-test stats
))))
1699 (assert (not (ert--stats-current-test stats
)))
1700 (insert "Finished.")))
1702 (if (ert--stats-end-time stats
)
1705 (if (ert--stats-aborted-p stats
)
1708 (ert--format-time-iso8601 (ert--stats-end-time stats
))))
1711 (let ((progress-bar-string (with-current-buffer results-buffer
1712 ert--results-progress-bar-string
)))
1713 (let ((progress-bar-button-begin
1714 (insert-text-button progress-bar-string
1715 :type
'ert--results-progress-bar-button
1716 'face
(or (and font-lock
1717 (ert-face-for-stats stats
))
1719 ;; The header gets copied verbatim to the results buffer,
1720 ;; and all positions remain the same, so
1721 ;; `progress-bar-button-begin' will be the right position
1722 ;; even in the results buffer.
1723 (with-current-buffer results-buffer
1724 (set (make-local-variable 'ert--results-progress-bar-button-begin
)
1725 progress-bar-button-begin
))))
1730 ;; We actually want an empty footer, but that would trigger a bug
1731 ;; in ewoc, sometimes clearing the entire buffer. (It's possible
1732 ;; that this bug has been fixed since this has been tested; we
1733 ;; should test it again.)
1737 (defvar ert-test-run-redisplay-interval-secs
.1
1738 "How many seconds ERT should wait between redisplays while running tests.
1740 While running tests, ERT shows the current progress, and this variable
1741 determines how frequently the progress display is updated.")
1743 (defun ert--results-update-stats-display (ewoc stats
)
1744 "Update EWOC and the mode line to show data from STATS."
1745 ;; TODO(ohler): investigate using `make-progress-reporter'.
1746 (ert--results-update-ewoc-hf ewoc stats
)
1747 (force-mode-line-update)
1749 (setf (ert--stats-next-redisplay stats
)
1750 (+ (float-time) ert-test-run-redisplay-interval-secs
)))
1752 (defun ert--results-update-stats-display-maybe (ewoc stats
)
1753 "Call `ert--results-update-stats-display' if not called recently.
1755 EWOC and STATS are arguments for `ert--results-update-stats-display'."
1756 (when (>= (float-time) (ert--stats-next-redisplay stats
))
1757 (ert--results-update-stats-display ewoc stats
)))
1759 (defun ert--tests-running-mode-line-indicator ()
1760 "Return a string for the mode line that shows the test run progress."
1761 (let* ((stats ert--current-run-stats
)
1762 (tests-total (ert-stats-total stats
))
1763 (tests-completed (ert-stats-completed stats
)))
1764 (if (>= tests-completed tests-total
)
1765 (format " ERT(%s/%s,finished)" tests-completed tests-total
)
1766 (format " ERT(%s/%s):%s"
1767 (1+ tests-completed
)
1769 (if (null (ert--stats-current-test stats
))
1772 (ert-test-name (ert--stats-current-test stats
))))))))
1774 (defun ert--make-xrefs-region (begin end
)
1775 "Attach cross-references to function names between BEGIN and END.
1777 BEGIN and END specify a region in the current buffer."
1780 (narrow-to-region begin
(point))
1781 ;; Inhibit optimization in `debugger-make-xrefs' that would
1782 ;; sometimes insert unrelated backtrace info into our buffer.
1783 (let ((debugger-previous-backtrace nil
))
1784 (debugger-make-xrefs)))))
1786 (defun ert--string-first-line (s)
1787 "Return the first line of S, or S if it contains no newlines.
1789 The return value does not include the line terminator."
1790 (substring s
0 (ert--string-position ?
\n s
)))
1792 (defun ert-face-for-test-result (expectedp)
1793 "Return a face that shows whether a test result was expected or unexpected.
1795 If EXPECTEDP is nil, returns the face for unexpected results; if
1796 non-nil, returns the face for expected results.."
1797 (if expectedp
'ert-test-result-expected
'ert-test-result-unexpected
))
1799 (defun ert-face-for-stats (stats)
1800 "Return a face that represents STATS."
1801 (cond ((ert--stats-aborted-p stats
) 'nil
)
1802 ((plusp (ert-stats-completed-unexpected stats
))
1803 (ert-face-for-test-result nil
))
1804 ((eql (ert-stats-completed-expected stats
) (ert-stats-total stats
))
1805 (ert-face-for-test-result t
))
1808 (defun ert--print-test-for-ewoc (entry)
1809 "The ewoc print function for ewoc test entries. ENTRY is the entry to print."
1810 (let* ((test (ert--ewoc-entry-test entry
))
1811 (stats ert--results-stats
)
1812 (result (let ((pos (ert--stats-test-pos stats test
)))
1814 (aref (ert--stats-test-results stats
) pos
)))
1815 (hiddenp (ert--ewoc-entry-hidden-p entry
))
1816 (expandedp (ert--ewoc-entry-expanded-p entry
))
1817 (extended-printer-limits-p (ert--ewoc-entry-extended-printer-limits-p
1821 (let ((expectedp (ert-test-result-expected-p test result
)))
1822 (insert-text-button (format "%c" (ert-char-for-test-result
1824 :type
'ert--results-expand-collapse-button
1825 'face
(or (and font-lock-mode
1826 (ert-face-for-test-result
1830 (ert-insert-test-name-button (ert-test-name test
))
1832 (when (and expandedp
(not (eql result
'nil
)))
1833 (when (ert-test-documentation test
)
1836 (ert--string-first-line (ert-test-documentation test
))
1837 'font-lock-face
'font-lock-doc-face
)
1841 (if (ert-test-result-expected-p test result
)
1842 (insert " passed\n")
1843 (insert " passed unexpectedly\n"))
1845 (ert-test-result-with-condition
1846 (ert--insert-infos result
)
1847 (let ((print-escape-newlines t
)
1848 (print-level (if extended-printer-limits-p
12 6))
1849 (print-length (if extended-printer-limits-p
100 10)))
1851 (let ((begin (point)))
1852 (ert--pp-with-indentation-and-newline
1853 (ert-test-result-with-condition-condition result
))
1854 (ert--make-xrefs-region begin
(point)))))
1855 (ert-test-aborted-with-non-local-exit
1856 (insert " aborted\n")))
1860 (defun ert--results-font-lock-function (enabledp)
1861 "Redraw the ERT results buffer after font-lock-mode was switched on or off.
1863 ENABLEDP is true if font-lock-mode is switched on, false
1865 (ert--results-update-ewoc-hf ert--results-ewoc ert--results-stats
)
1866 (ewoc-refresh ert--results-ewoc
)
1867 (font-lock-default-function enabledp
))
1869 (defun ert--setup-results-buffer (stats listener buffer-name
)
1870 "Set up a test results buffer.
1872 STATS is the stats object; LISTENER is the results listener;
1873 BUFFER-NAME, if non-nil, is the buffer name to use."
1874 (unless buffer-name
(setq buffer-name
"*ert*"))
1875 (let ((buffer (get-buffer-create buffer-name
)))
1876 (with-current-buffer buffer
1877 (let ((inhibit-read-only t
))
1878 (buffer-disable-undo)
1881 ;; Erase buffer again in case switching out of the previous
1882 ;; mode inserted anything. (This happens e.g. when switching
1883 ;; from ert-results-mode to ert-results-mode when
1884 ;; font-lock-mode turns itself off in change-major-mode-hook.)
1886 (set (make-local-variable 'font-lock-function
)
1887 'ert--results-font-lock-function
)
1888 (let ((ewoc (ewoc-create 'ert--print-test-for-ewoc nil nil t
)))
1889 (set (make-local-variable 'ert--results-ewoc
) ewoc
)
1890 (set (make-local-variable 'ert--results-stats
) stats
)
1891 (set (make-local-variable 'ert--results-progress-bar-string
)
1892 (make-string (ert-stats-total stats
)
1893 (ert-char-for-test-result nil t
)))
1894 (set (make-local-variable 'ert--results-listener
) listener
)
1895 (loop for test across
(ert--stats-tests stats
) do
1896 (ewoc-enter-last ewoc
1897 (make-ert--ewoc-entry :test test
:hidden-p t
)))
1898 (ert--results-update-ewoc-hf ert--results-ewoc ert--results-stats
)
1899 (goto-char (1- (point-max)))
1903 (defvar ert--selector-history nil
1904 "List of recent test selectors read from terminal.")
1906 ;; Should OUTPUT-BUFFER-NAME and MESSAGE-FN really be arguments here?
1907 ;; They are needed only for our automated self-tests at the moment.
1908 ;; Or should there be some other mechanism?
1910 (defun ert-run-tests-interactively (selector
1911 &optional output-buffer-name message-fn
)
1912 "Run the tests specified by SELECTOR and display the results in a buffer.
1914 SELECTOR works as described in `ert-select-tests'.
1915 OUTPUT-BUFFER-NAME and MESSAGE-FN should normally be nil; they
1916 are used for automated self-tests and specify which buffer to use
1917 and how to display message."
1919 (list (let ((default (if ert--selector-history
1920 ;; Can't use `first' here as this form is
1921 ;; not compiled, and `first' is not
1922 ;; defined without cl.
1923 (car ert--selector-history
)
1925 (read-from-minibuffer (if (null default
)
1927 (format "Run tests (default %s): " default
))
1928 nil nil t
'ert--selector-history
1931 (unless message-fn
(setq message-fn
'message
))
1932 (lexical-let ((output-buffer-name output-buffer-name
)
1935 (message-fn message-fn
))
1937 (lambda (event-type &rest event-args
)
1940 (destructuring-bind (stats) event-args
1941 (setq buffer
(ert--setup-results-buffer stats
1943 output-buffer-name
))
1944 (pop-to-buffer buffer
)))
1946 (destructuring-bind (stats abortedp
) event-args
1948 "%sRan %s tests, %s results were as expected%s"
1952 (ert-stats-total stats
)
1953 (ert-stats-completed-expected stats
)
1955 (ert-stats-completed-unexpected stats
)))
1956 (if (zerop unexpected
)
1958 (format ", %s unexpected" unexpected
))))
1959 (ert--results-update-stats-display (with-current-buffer buffer
1963 (destructuring-bind (stats test
) event-args
1964 (with-current-buffer buffer
1965 (let* ((ewoc ert--results-ewoc
)
1966 (pos (ert--stats-test-pos stats test
))
1967 (node (ewoc-nth ewoc pos
)))
1969 (setf (ert--ewoc-entry-test (ewoc-data node
)) test
)
1970 (aset ert--results-progress-bar-string pos
1971 (ert-char-for-test-result nil t
))
1972 (ert--results-update-stats-display-maybe ewoc stats
)
1973 (ewoc-invalidate ewoc node
)))))
1975 (destructuring-bind (stats test result
) event-args
1976 (with-current-buffer buffer
1977 (let* ((ewoc ert--results-ewoc
)
1978 (pos (ert--stats-test-pos stats test
))
1979 (node (ewoc-nth ewoc pos
)))
1980 (when (ert--ewoc-entry-hidden-p (ewoc-data node
))
1981 (setf (ert--ewoc-entry-hidden-p (ewoc-data node
))
1982 (ert-test-result-expected-p test result
)))
1983 (aset ert--results-progress-bar-string pos
1984 (ert-char-for-test-result result
1985 (ert-test-result-expected-p
1987 (ert--results-update-stats-display-maybe ewoc stats
)
1988 (ewoc-invalidate ewoc node
))))))))
1993 (defalias 'ert
'ert-run-tests-interactively
)
1996 ;;; Simple view mode for auxiliary information like stack traces or
1997 ;;; messages. Mainly binds "q" for quit.
1999 (define-derived-mode ert-simple-view-mode special-mode
"ERT-View"
2000 "Major mode for viewing auxiliary information in ERT.")
2002 ;;; Commands and button actions for the results buffer.
2004 (define-derived-mode ert-results-mode special-mode
"ERT-Results"
2005 "Major mode for viewing results of ERT test runs.")
2007 (loop for
(key binding
) in
2008 '(;; Stuff that's not in the menu.
2009 ("\t" forward-button
)
2010 ([backtab] backward-button)
2011 ("j" ert-results-jump-between-summary-and-result)
2012 ("L" ert-results-toggle-printer-limits-for-test-at-point)
2013 ("n" ert-results-next-test)
2014 ("p" ert-results-previous-test)
2015 ;; Stuff that is in the menu.
2016 ("R" ert-results-rerun-all-tests)
2017 ("r" ert-results-rerun-test-at-point)
2018 ("d" ert-results-rerun-test-at-point-debugging-errors)
2019 ("." ert-results-find-test-at-point-other-window)
2020 ("b" ert-results-pop-to-backtrace-for-test-at-point)
2021 ("m" ert-results-pop-to-messages-for-test-at-point)
2022 ("l" ert-results-pop-to-should-forms-for-test-at-point)
2023 ("h" ert-results-describe-test-at-point)
2024 ("D" ert-delete-test)
2025 ("T" ert-results-pop-to-timings)
2028 (define-key ert-results-mode-map key binding))
2030 (easy-menu-define ert-results-mode-menu ert-results-mode-map
2031 "Menu for `ert-results-mode'."
2033 ["Re-run all tests" ert-results-rerun-all-tests]
2035 ["Re-run test" ert-results-rerun-test-at-point]
2036 ["Debug test" ert-results-rerun-test-at-point-debugging-errors]
2037 ["Show test definition" ert-results-find-test-at-point-other-window]
2039 ["Show backtrace" ert-results-pop-to-backtrace-for-test-at-point]
2040 ["Show messages" ert-results-pop-to-messages-for-test-at-point]
2041 ["Show `should' forms" ert-results-pop-to-should-forms-for-test-at-point]
2042 ["Describe test" ert-results-describe-test-at-point]
2044 ["Delete test" ert-delete-test]
2046 ["Show execution time of each test" ert-results-pop-to-timings]
2049 (define-button-type 'ert--results-progress-bar-button
2050 'action #'ert--results-progress-bar-button-action
2051 'help-echo "mouse-2, RET: Reveal test result")
2053 (define-button-type 'ert--test-name-button
2054 'action #'ert--test-name-button-action
2055 'help-echo "mouse-2, RET: Find test definition")
2057 (define-button-type 'ert--results-expand-collapse-button
2058 'action #'ert--results-expand-collapse-button-action
2059 'help-echo "mouse-2, RET: Expand/collapse test result")
2061 (defun ert--results-test-node-or-null-at-point ()
2062 "If point is on a valid ewoc node, return it; return nil otherwise.
2064 To be used in the ERT results buffer."
2065 (let* ((ewoc ert--results-ewoc)
2066 (node (ewoc-locate ewoc)))
2067 ;; `ewoc-locate' will return an arbitrary node when point is on
2068 ;; header or footer, or when all nodes are invisible. So we need
2069 ;; to validate its return value here.
2071 ;; Update: I'm seeing nil being returned in some cases now,
2072 ;; perhaps this has been changed?
2074 (>= (point) (ewoc-location node))
2075 (not (ert--ewoc-entry-hidden-p (ewoc-data node))))
2079 (defun ert--results-test-node-at-point ()
2080 "If point is on a valid ewoc node, return it; signal an error otherwise.
2082 To be used in the ERT results buffer."
2083 (or (ert--results-test-node-or-null-at-point)
2084 (error "No test at point")))
2086 (defun ert-results-next-test ()
2087 "Move point to the next test.
2089 To be used in the ERT results buffer."
2091 (ert--results-move (ewoc-locate ert--results-ewoc) 'ewoc-next
2094 (defun ert-results-previous-test ()
2095 "Move point to the previous test.
2097 To be used in the ERT results buffer."
2099 (ert--results-move (ewoc-locate ert--results-ewoc) 'ewoc-prev
2102 (defun ert--results-move (node ewoc-fn error-message)
2103 "Move point from NODE to the previous or next node.
2105 EWOC-FN specifies the direction and should be either `ewoc-prev'
2106 or `ewoc-next'. If there are no more nodes in that direction, an
2107 error is signalled with the message ERROR-MESSAGE."
2109 (setq node (funcall ewoc-fn ert--results-ewoc node))
2111 (error "%s" error-message))
2112 (unless (ert--ewoc-entry-hidden-p (ewoc-data node))
2113 (goto-char (ewoc-location node))
2116 (defun ert--results-expand-collapse-button-action (button)
2117 "Expand or collapse the test node BUTTON belongs to."
2118 (let* ((ewoc ert--results-ewoc)
2119 (node (save-excursion
2120 (goto-char (ert--button-action-position))
2121 (ert--results-test-node-at-point)))
2122 (entry (ewoc-data node)))
2123 (setf (ert--ewoc-entry-expanded-p entry)
2124 (not (ert--ewoc-entry-expanded-p entry)))
2125 (ewoc-invalidate ewoc node)))
2127 (defun ert-results-find-test-at-point-other-window ()
2128 "Find the definition of the test at point in another window.
2130 To be used in the ERT results buffer."
2132 (let ((name (ert-test-at-point)))
2134 (error "No test at point"))
2135 (ert-find-test-other-window name)))
2137 (defun ert--test-name-button-action (button)
2138 "Find the definition of the test BUTTON belongs to, in another window."
2139 (let ((name (button-get button 'ert-test-name)))
2140 (ert-find-test-other-window name)))
2142 (defun ert--ewoc-position (ewoc node)
2143 ;; checkdoc-order: nil
2144 "Return the position of NODE in EWOC, or nil if NODE is not in EWOC."
2146 for node-here = (ewoc-nth ewoc 0) then (ewoc-next ewoc node-here)
2147 do (when (eql node node-here)
2149 finally (return nil)))
2151 (defun ert-results-jump-between-summary-and-result ()
2152 "Jump back and forth between the test run summary and individual test results.
2154 From an ewoc node, jumps to the character that represents the
2155 same test in the progress bar, and vice versa.
2157 To be used in the ERT results buffer."
2158 ;; Maybe this command isn't actually needed much, but if it is, it
2159 ;; seems like an indication that the UI design is not optimal. If
2160 ;; jumping back and forth between a summary at the top of the buffer
2161 ;; and the error log in the remainder of the buffer is useful, then
2162 ;; the summary apparently needs to be easily accessible from the
2163 ;; error log, and perhaps it would be better to have it in a
2164 ;; separate buffer to keep it visible.
2166 (let ((ewoc ert--results-ewoc)
2167 (progress-bar-begin ert--results-progress-bar-button-begin))
2168 (cond ((ert--results-test-node-or-null-at-point)
2169 (let* ((node (ert--results-test-node-at-point))
2170 (pos (ert--ewoc-position ewoc node)))
2171 (goto-char (+ progress-bar-begin pos))))
2172 ((and (<= progress-bar-begin (point))
2173 (< (point) (button-end (button-at progress-bar-begin))))
2174 (let* ((node (ewoc-nth ewoc (- (point) progress-bar-begin)))
2175 (entry (ewoc-data node)))
2176 (when (ert--ewoc-entry-hidden-p entry)
2177 (setf (ert--ewoc-entry-hidden-p entry) nil)
2178 (ewoc-invalidate ewoc node))
2179 (ewoc-goto-node ewoc node)))
2181 (goto-char progress-bar-begin)))))
2183 (defun ert-test-at-point ()
2184 "Return the name of the test at point as a symbol, or nil if none."
2185 (or (and (eql major-mode 'ert-results-mode)
2186 (let ((test (ert--results-test-at-point-no-redefinition)))
2187 (and test (ert-test-name test))))
2188 (let* ((thing (thing-at-point 'symbol))
2189 (sym (intern-soft thing)))
2190 (and (ert-test-boundp sym)
2193 (defun ert--results-test-at-point-no-redefinition ()
2194 "Return the test at point, or nil.
2196 To be used in the ERT results buffer."
2197 (assert (eql major-mode 'ert-results-mode))
2198 (if (ert--results-test-node-or-null-at-point)
2199 (let* ((node (ert--results-test-node-at-point))
2200 (test (ert--ewoc-entry-test (ewoc-data node))))
2202 (let ((progress-bar-begin ert--results-progress-bar-button-begin))
2203 (when (and (<= progress-bar-begin (point))
2204 (< (point) (button-end (button-at progress-bar-begin))))
2205 (let* ((test-index (- (point) progress-bar-begin))
2206 (test (aref (ert--stats-tests ert--results-stats)
2210 (defun ert--results-test-at-point-allow-redefinition ()
2211 "Look up the test at point, and check whether it has been redefined.
2213 To be used in the ERT results buffer.
2215 Returns a list of two elements: the test (or nil) and a symbol
2216 specifying whether the test has been redefined.
2218 If a new test has been defined with the same name as the test at
2219 point, replaces the test at point with the new test, and returns
2220 the new test and the symbol `redefined'.
2222 If the test has been deleted, returns the old test and the symbol
2225 If the test is still current, returns the test and the symbol nil.
2227 If there is no test at point, returns a list with two nils."
2228 (let ((test (ert--results-test-at-point-no-redefinition)))
2231 ((null (ert-test-name test))
2234 (let* ((name (ert-test-name test))
2235 (new-test (and (ert-test-boundp name)
2236 (ert-get-test name))))
2237 (cond ((eql test new-test)
2242 (ert--results-update-after-test-redefinition
2243 (ert--stats-test-pos ert--results-stats test)
2245 `(,new-test redefined))))))))
2247 (defun ert--results-update-after-test-redefinition (pos new-test)
2248 "Update results buffer after the test at pos POS has been redefined.
2250 Also updates the stats object. NEW-TEST is the new test
2252 (let* ((stats ert--results-stats)
2253 (ewoc ert--results-ewoc)
2254 (node (ewoc-nth ewoc pos))
2255 (entry (ewoc-data node)))
2256 (ert--stats-set-test-and-result stats pos new-test nil)
2257 (setf (ert--ewoc-entry-test entry) new-test
2258 (aref ert--results-progress-bar-string pos) (ert-char-for-test-result
2260 (ewoc-invalidate ewoc node))
2263 (defun ert--button-action-position ()
2264 "The buffer position where the last button action was triggered."
2265 (cond ((integerp last-command-event)
2267 ((eventp last-command-event)
2268 (posn-point (event-start last-command-event)))
2271 (defun ert--results-progress-bar-button-action (button)
2272 "Jump to details for the test represented by the character clicked in BUTTON."
2273 (goto-char (ert--button-action-position))
2274 (ert-results-jump-between-summary-and-result))
2276 (defun ert-results-rerun-all-tests ()
2277 "Re-run all tests, using the same selector.
2279 To be used in the ERT results buffer."
2281 (assert (eql major-mode 'ert-results-mode))
2282 (let ((selector (ert--stats-selector ert--results-stats)))
2283 (ert-run-tests-interactively selector (buffer-name))))
2285 (defun ert-results-rerun-test-at-point ()
2286 "Re-run the test at point.
2288 To be used in the ERT results buffer."
2290 (destructuring-bind (test redefinition-state)
2291 (ert--results-test-at-point-allow-redefinition)
2293 (error "No test at point"))
2294 (let* ((stats ert--results-stats)
2295 (progress-message (format "Running %stest %S"
2296 (ecase redefinition-state
2298 (redefined "new definition of ")
2299 (deleted "deleted "))
2300 (ert-test-name test))))
2301 ;; Need to save and restore point manually here: When point is on
2302 ;; the first visible ewoc entry while the header is updated, point
2303 ;; moves to the top of the buffer. This is undesirable, and a
2304 ;; simple `save-excursion' doesn't prevent it.
2305 (let ((point (point)))
2309 (message "%s..." progress-message)
2310 (ert-run-or-rerun-test stats test
2311 ert--results-listener))
2312 (ert--results-update-stats-display ert--results-ewoc stats)
2315 (let ((result (ert-test-most-recent-result test)))
2316 (ert-string-for-test-result
2317 result (ert-test-result-expected-p test result)))))
2318 (goto-char point))))))
2320 (defun ert-results-rerun-test-at-point-debugging-errors ()
2321 "Re-run the test at point with `ert-debug-on-error' bound to t.
2323 To be used in the ERT results buffer."
2325 (let ((ert-debug-on-error t))
2326 (ert-results-rerun-test-at-point)))
2328 (defun ert-results-pop-to-backtrace-for-test-at-point ()
2329 "Display the backtrace for the test at point.
2331 To be used in the ERT results buffer."
2333 (let* ((test (ert--results-test-at-point-no-redefinition))
2334 (stats ert--results-stats)
2335 (pos (ert--stats-test-pos stats test))
2336 (result (aref (ert--stats-test-results stats) pos)))
2338 (ert-test-passed (error "Test passed, no backtrace available"))
2339 (ert-test-result-with-condition
2340 (let ((backtrace (ert-test-result-with-condition-backtrace result))
2341 (buffer (get-buffer-create "*ERT Backtrace*")))
2342 (pop-to-buffer buffer)
2343 (let ((inhibit-read-only t))
2344 (buffer-disable-undo)
2346 (ert-simple-view-mode)
2347 ;; Use unibyte because `debugger-setup-buffer' also does so.
2348 (set-buffer-multibyte nil)
2349 (setq truncate-lines t)
2350 (ert--print-backtrace backtrace)
2351 (debugger-make-xrefs)
2352 (goto-char (point-min))
2353 (insert "Backtrace for test `")
2354 (ert-insert-test-name-button (ert-test-name test))
2355 (insert "':\n")))))))
2357 (defun ert-results-pop-to-messages-for-test-at-point ()
2358 "Display the part of the *Messages* buffer generated during the test at point.
2360 To be used in the ERT results buffer."
2362 (let* ((test (ert--results-test-at-point-no-redefinition))
2363 (stats ert--results-stats)
2364 (pos (ert--stats-test-pos stats test))
2365 (result (aref (ert--stats-test-results stats) pos)))
2366 (let ((buffer (get-buffer-create "*ERT Messages*")))
2367 (pop-to-buffer buffer)
2368 (let ((inhibit-read-only t))
2369 (buffer-disable-undo)
2371 (ert-simple-view-mode)
2372 (insert (ert-test-result-messages result))
2373 (goto-char (point-min))
2374 (insert "Messages for test `")
2375 (ert-insert-test-name-button (ert-test-name test))
2378 (defun ert-results-pop-to-should-forms-for-test-at-point ()
2379 "Display the list of `should' forms executed during the test at point.
2381 To be used in the ERT results buffer."
2383 (let* ((test (ert--results-test-at-point-no-redefinition))
2384 (stats ert--results-stats)
2385 (pos (ert--stats-test-pos stats test))
2386 (result (aref (ert--stats-test-results stats) pos)))
2387 (let ((buffer (get-buffer-create "*ERT list of should forms*")))
2388 (pop-to-buffer buffer)
2389 (let ((inhibit-read-only t))
2390 (buffer-disable-undo)
2392 (ert-simple-view-mode)
2393 (if (null (ert-test-result-should-forms result))
2394 (insert "\n(No should forms during this test.)\n")
2395 (loop for form-description in (ert-test-result-should-forms result)
2398 (insert (format "%s: " i))
2399 (let ((begin (point)))
2400 (ert--pp-with-indentation-and-newline form-description)
2401 (ert--make-xrefs-region begin (point)))))
2402 (goto-char (point-min))
2403 (insert "`should' forms executed during test `")
2404 (ert-insert-test-name-button (ert-test-name test))
2407 (insert (concat "(Values are shallow copies and may have "
2408 "looked different during the test if they\n"
2409 "have been modified destructively.)\n"))
2410 (forward-line 1)))))
2412 (defun ert-results-toggle-printer-limits-for-test-at-point ()
2413 "Toggle how much of the condition to print for the test at point.
2415 To be used in the ERT results buffer."
2417 (let* ((ewoc ert--results-ewoc)
2418 (node (ert--results-test-node-at-point))
2419 (entry (ewoc-data node)))
2420 (setf (ert--ewoc-entry-extended-printer-limits-p entry)
2421 (not (ert--ewoc-entry-extended-printer-limits-p entry)))
2422 (ewoc-invalidate ewoc node)))
2424 (defun ert-results-pop-to-timings ()
2425 "Display test timings for the last run.
2427 To be used in the ERT results buffer."
2429 (let* ((stats ert--results-stats)
2430 (start-times (ert--stats-test-start-times stats))
2431 (end-times (ert--stats-test-end-times stats))
2432 (buffer (get-buffer-create "*ERT timings*"))
2433 (data (loop for test across (ert--stats-tests stats)
2434 for start-time across (ert--stats-test-start-times stats)
2435 for end-time across (ert--stats-test-end-times stats)
2437 (float-time (subtract-time end-time
2439 (setq data (sort data (lambda (a b)
2440 (> (second a) (second b)))))
2441 (pop-to-buffer buffer)
2442 (let ((inhibit-read-only t))
2443 (buffer-disable-undo)
2445 (ert-simple-view-mode)
2447 (insert "(No data)\n")
2448 (insert (format "%-3s %8s %8s\n" "" "time" "cumul"))
2449 (loop for (test time) in data
2450 for cumul-time = time then (+ cumul-time time)
2452 (let ((begin (point)))
2453 (insert (format "%3s: %8.3f %8.3f " i time cumul-time))
2454 (ert-insert-test-name-button (ert-test-name test))
2456 (goto-char (point-min))
2457 (insert "Tests by run time (seconds):\n\n")
2461 (defun ert-describe-test (test-or-test-name)
2462 "Display the documentation for TEST-OR-TEST-NAME (a symbol or ert-test)."
2463 (interactive (list (ert-read-test-name-at-point "Describe test")))
2464 (when (< emacs-major-version 24)
2465 (error "Requires Emacs 24"))
2468 (etypecase test-or-test-name
2469 (symbol (setq test-name test-or-test-name
2470 test-definition (ert-get-test test-or-test-name)))
2471 (ert-test (setq test-name (ert-test-name test-or-test-name)
2472 test-definition test-or-test-name)))
2473 (help-setup-xref (list #'ert-describe-test test-or-test-name)
2474 (called-interactively-p 'interactive))
2476 (with-help-window (help-buffer)
2477 (with-current-buffer (help-buffer)
2478 (insert (if test-name (format "%S" test-name) "<anonymous test>"))
2479 (insert " is a test")
2480 (let ((file-name (and test-name
2481 (symbol-file test-name 'ert-deftest))))
2483 (insert " defined in `" (file-name-nondirectory file-name) "'")
2485 (re-search-backward "`\\([^`']+\\)'" nil t)
2486 (help-xref-button 1 'help-function-def test-name file-name)))
2488 (fill-region-as-paragraph (point-min) (point))
2490 (unless (and (ert-test-boundp test-name)
2491 (eql (ert-get-test test-name) test-definition))
2492 (let ((begin (point)))
2493 (insert "Note: This test has been redefined or deleted, "
2494 "this documentation refers to an old definition.")
2495 (fill-region-as-paragraph begin (point)))
2497 (insert (or (ert-test-documentation test-definition)
2498 "It is not documented.")
2501 (defun ert-results-describe-test-at-point ()
2502 "Display the documentation of the test at point.
2504 To be used in the ERT results buffer."
2506 (ert-describe-test (ert--results-test-at-point-no-redefinition)))
2509 ;;; Actions on load/unload.
2511 (add-to-list 'find-function-regexp-alist '(ert-deftest . ert--find-test-regexp))
2512 (add-to-list 'minor-mode-alist '(ert--current-run-stats
2514 (ert--tests-running-mode-line-indicator))))
2515 (add-to-list 'emacs-lisp-mode-hook 'ert--activate-font-lock-keywords)
2517 (defun ert--unload-function ()
2518 "Unload function to undo the side-effects of loading ert.el."
2519 (ert--remove-from-list 'find-function-regexp-alist 'ert-deftest :key #'car)
2520 (ert--remove-from-list 'minor-mode-alist 'ert--current-run-stats :key #'car)
2521 (ert--remove-from-list 'emacs-lisp-mode-hook
2522 'ert--activate-font-lock-keywords)
2525 (defvar ert-unload-hook '())
2526 (add-hook 'ert-unload-hook 'ert--unload-function)
2531 ;;; ert.el ends here