* lisp/simple.el: Use lexical-binding.
[emacs.git] / lisp / emacs-lisp / ert.el
blob70d6a6a4a5fdb78a59545009bcee2d860f22e597
1 ;;; ert.el --- Emacs Lisp Regression Testing -*- lexical-binding: t -*-
3 ;; Copyright (C) 2007-2008, 2010-2013 Free Software Foundation, Inc.
5 ;; Author: Christian Ohler <ohler@gnu.org>
6 ;; Keywords: lisp, tools
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;; Commentary:
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
28 ;; interactively.
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.
55 ;;; Code:
57 (eval-when-compile (require 'cl-lib))
58 (require 'button)
59 (require 'debug)
60 (require 'easymenu)
61 (require 'ewoc)
62 (require 'find-func)
63 (require 'help)
66 ;;; UI customization options.
68 (defgroup ert ()
69 "ERT, the Emacs Lisp regression testing tool."
70 :prefix "ert-"
71 :group 'lisp)
73 (defface ert-test-result-expected '((((class color) (background light))
74 :background "green1")
75 (((class color) (background dark))
76 :background "green3"))
77 "Face used for expected results in the ERT results buffer."
78 :group 'ert)
80 (defface ert-test-result-unexpected '((((class color) (background light))
81 :background "red1")
82 (((class color) (background dark))
83 :background "red3"))
84 "Face used for unexpected results in the ERT results buffer."
85 :group 'ert)
88 ;;; Copies/reimplementations of cl functions.
90 (defun ert--cl-do-remf (plist tag)
91 "Copy of `cl-do-remf'. Modify PLIST by removing TAG."
92 (let ((p (cdr plist)))
93 (while (and (cdr p) (not (eq (car (cdr p)) tag))) (setq p (cdr (cdr p))))
94 (and (cdr p) (progn (setcdr p (cdr (cdr (cdr p)))) t))))
96 (defun ert--remprop (sym tag)
97 "Copy of `cl-remprop'. Modify SYM's plist by removing TAG."
98 (let ((plist (symbol-plist sym)))
99 (if (and plist (eq tag (car plist)))
100 (progn (setplist sym (cdr (cdr plist))) t)
101 (ert--cl-do-remf plist tag))))
103 (defun ert--remove-if-not (ert-pred ert-list)
104 "A reimplementation of `remove-if-not'.
106 ERT-PRED is a predicate, ERT-LIST is the input list."
107 (cl-loop for ert-x in ert-list
108 if (funcall ert-pred ert-x)
109 collect ert-x))
111 (defun ert--intersection (a b)
112 "A reimplementation of `intersection'. Intersect the sets A and B.
114 Elements are compared using `eql'."
115 (cl-loop for x in a
116 if (memql x b)
117 collect x))
119 (defun ert--set-difference (a b)
120 "A reimplementation of `set-difference'. Subtract the set B from the set A.
122 Elements are compared using `eql'."
123 (cl-loop for x in a
124 unless (memql x b)
125 collect x))
127 (defun ert--set-difference-eq (a b)
128 "A reimplementation of `set-difference'. Subtract the set B from the set A.
130 Elements are compared using `eq'."
131 (cl-loop for x in a
132 unless (memq x b)
133 collect x))
135 (defun ert--union (a b)
136 "A reimplementation of `union'. Compute the union of the sets A and B.
138 Elements are compared using `eql'."
139 (append a (ert--set-difference b a)))
141 (eval-and-compile
142 (defvar ert--gensym-counter 0))
144 (eval-and-compile
145 (defun ert--gensym (&optional prefix)
146 "Only allows string PREFIX, not compatible with CL."
147 (unless prefix (setq prefix "G"))
148 (make-symbol (format "%s%s"
149 prefix
150 (prog1 ert--gensym-counter
151 (cl-incf ert--gensym-counter))))))
153 (defun ert--coerce-to-vector (x)
154 "Coerce X to a vector."
155 (when (char-table-p x) (error "Not supported"))
156 (if (vectorp x)
158 (vconcat x)))
160 (cl-defun ert--remove* (x list &key key test)
161 "Does not support all the keywords of remove*."
162 (unless key (setq key #'identity))
163 (unless test (setq test #'eql))
164 (cl-loop for y in list
165 unless (funcall test x (funcall key y))
166 collect y))
168 (defun ert--string-position (c s)
169 "Return the position of the first occurrence of C in S, or nil if none."
170 (cl-loop for i from 0
171 for x across s
172 when (eql x c) return i))
174 (defun ert--mismatch (a b)
175 "Return index of first element that differs between A and B.
177 Like `mismatch'. Uses `equal' for comparison."
178 (cond ((or (listp a) (listp b))
179 (ert--mismatch (ert--coerce-to-vector a)
180 (ert--coerce-to-vector b)))
181 ((> (length a) (length b))
182 (ert--mismatch b a))
184 (let ((la (length a))
185 (lb (length b)))
186 (cl-assert (arrayp a) t)
187 (cl-assert (arrayp b) t)
188 (cl-assert (<= la lb) t)
189 (cl-loop for i below la
190 when (not (equal (aref a i) (aref b i))) return i
191 finally (cl-return (if (/= la lb)
193 (cl-assert (equal a b) t)
194 nil)))))))
196 (defun ert--subseq (seq start &optional end)
197 "Return a subsequence of SEQ from START to END."
198 (when (char-table-p seq) (error "Not supported"))
199 (let ((vector (substring (ert--coerce-to-vector seq) start end)))
200 (cl-etypecase seq
201 (vector vector)
202 (string (concat vector))
203 (list (append vector nil))
204 (bool-vector (cl-loop with result
205 = (make-bool-vector (length vector) nil)
206 for i below (length vector) do
207 (setf (aref result i) (aref vector i))
208 finally (cl-return result)))
209 (char-table (cl-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
221 ;; it altogether.
222 (not (ert--explain-equal-including-properties a b)))
225 ;;; Defining and locating tests.
227 ;; The data structure that represents a test case.
228 (cl-defstruct ert-test
229 (name nil)
230 (documentation nil)
231 (body (cl-assert nil))
232 (most-recent-result nil)
233 (expected-result-type ':passed)
234 (tags '()))
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)
257 definition)
259 (defun ert-make-test-unbound (symbol)
260 "Make SYMBOL name no test. Return SYMBOL."
261 (ert--remprop symbol 'ert--test)
262 symbol)
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
270 keyword.
272 Returns a two-element list containing the keys-and-values plist
273 and the body."
274 (let ((extracted-key-accu '())
275 (remaining keys-and-body))
276 (while (keywordp (car-safe 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
283 keys-and-body))
284 (push (cons keyword (pop remaining)) extracted-key-accu)))
285 (setq extracted-key-accu (nreverse extracted-key-accu))
286 (list (cl-loop for (key . value) in extracted-key-accu
287 collect key
288 collect value)
289 remaining)))
291 ;;;###autoload
292 (cl-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
299 assertions in BODY.
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))
312 (doc-string 3)
313 (indent 2))
314 (let ((documentation nil)
315 (documentation-supplied-p nil))
316 (when (stringp (car docstring-keys-and-body))
317 (setq documentation (pop docstring-keys-and-body)
318 documentation-supplied-p t))
319 (cl-destructuring-bind
320 ((&key (expected-result nil expected-result-supplied-p)
321 (tags nil tags-supplied-p))
322 body)
323 (ert--parse-keys-and-body docstring-keys-and-body)
324 `(progn
325 (ert-set-test ',name
326 (make-ert-test
327 :name ',name
328 ,@(when documentation-supplied-p
329 `(:documentation ,documentation))
330 ,@(when expected-result-supplied-p
331 `(:expected-result-type ,expected-result))
332 ,@(when tags-supplied-p
333 `(:tags ,tags))
334 :body (lambda () ,@body)))
335 ;; This hack allows `symbol-file' to associate `ert-deftest'
336 ;; forms with files, and therefore enables `find-function' to
337 ;; work with tests. However, it leads to warnings in
338 ;; `unload-feature', which doesn't know how to undefine tests
339 ;; and has no mechanism for extension.
340 (push '(ert-deftest . ,name) current-load-list)
341 ',name))))
343 ;; We use these `put' forms in addition to the (declare (indent)) in
344 ;; the defmacro form since the `declare' alone does not lead to
345 ;; correct indentation before the .el/.elc file is loaded.
346 ;; Autoloading these `put' forms solves this.
347 ;;;###autoload
348 (progn
349 ;; TODO(ohler): Figure out what these mean and make sure they are correct.
350 (put 'ert-deftest 'lisp-indent-function 2)
351 (put 'ert-info 'lisp-indent-function 1))
353 (defvar ert--find-test-regexp
354 (concat "^\\s-*(ert-deftest"
355 find-function-space-re
356 "%s\\(\\s-\\|$\\)")
357 "The regexp the `find-function' mechanisms use for finding test definitions.")
360 (put 'ert-test-failed 'error-conditions '(error ert-test-failed))
361 (put 'ert-test-failed 'error-message "Test failed")
363 (defun ert-pass ()
364 "Terminate the current test and mark it passed. Does not return."
365 (throw 'ert--pass nil))
367 (defun ert-fail (data)
368 "Terminate the current test and mark it failed. Does not return.
369 DATA is displayed to the user and should state the reason of the failure."
370 (signal 'ert-test-failed (list data)))
373 ;;; The `should' macros.
375 (defvar ert--should-execution-observer nil)
377 (defun ert--signal-should-execution (form-description)
378 "Tell the current `should' form observer (if any) about FORM-DESCRIPTION."
379 (when ert--should-execution-observer
380 (funcall ert--should-execution-observer form-description)))
382 (defun ert--special-operator-p (thing)
383 "Return non-nil if THING is a symbol naming a special operator."
384 (and (symbolp thing)
385 (let ((definition (indirect-function thing t)))
386 (and (subrp definition)
387 (eql (cdr (subr-arity definition)) 'unevalled)))))
389 (defun ert--expand-should-1 (whole form inner-expander)
390 "Helper function for the `should' macro and its variants."
391 (let ((form
392 (macroexpand form (cond
393 ((boundp 'macroexpand-all-environment)
394 macroexpand-all-environment)
395 ((boundp 'cl-macro-environment)
396 cl-macro-environment)))))
397 (cond
398 ((or (atom form) (ert--special-operator-p (car form)))
399 (let ((value (ert--gensym "value-")))
400 `(let ((,value (ert--gensym "ert-form-evaluation-aborted-")))
401 ,(funcall inner-expander
402 `(setq ,value ,form)
403 `(list ',whole :form ',form :value ,value)
404 value)
405 ,value)))
407 (let ((fn-name (car form))
408 (arg-forms (cdr form)))
409 (cl-assert (or (symbolp fn-name)
410 (and (consp fn-name)
411 (eql (car fn-name) 'lambda)
412 (listp (cdr fn-name)))))
413 (let ((fn (ert--gensym "fn-"))
414 (args (ert--gensym "args-"))
415 (value (ert--gensym "value-"))
416 (default-value (ert--gensym "ert-form-evaluation-aborted-")))
417 `(let ((,fn (function ,fn-name))
418 (,args (list ,@arg-forms)))
419 (let ((,value ',default-value))
420 ,(funcall inner-expander
421 `(setq ,value (apply ,fn ,args))
422 `(nconc (list ',whole)
423 (list :form `(,,fn ,@,args))
424 (unless (eql ,value ',default-value)
425 (list :value ,value))
426 (let ((-explainer-
427 (and (symbolp ',fn-name)
428 (get ',fn-name 'ert-explainer))))
429 (when -explainer-
430 (list :explanation
431 (apply -explainer- ,args)))))
432 value)
433 ,value))))))))
435 (defun ert--expand-should (whole form inner-expander)
436 "Helper function for the `should' macro and its variants.
438 Analyzes FORM and returns an expression that has the same
439 semantics under evaluation but records additional debugging
440 information.
442 INNER-EXPANDER should be a function and is called with two
443 arguments: INNER-FORM and FORM-DESCRIPTION-FORM, where INNER-FORM
444 is an expression equivalent to FORM, and FORM-DESCRIPTION-FORM is
445 an expression that returns a description of FORM. INNER-EXPANDER
446 should return code that calls INNER-FORM and performs the checks
447 and error signaling specific to the particular variant of
448 `should'. The code that INNER-EXPANDER returns must not call
449 FORM-DESCRIPTION-FORM before it has called INNER-FORM."
450 (ert--expand-should-1
451 whole form
452 (lambda (inner-form form-description-form value-var)
453 (let ((form-description (ert--gensym "form-description-")))
454 `(let (,form-description)
455 ,(funcall inner-expander
456 `(unwind-protect
457 ,inner-form
458 (setq ,form-description ,form-description-form)
459 (ert--signal-should-execution ,form-description))
460 `,form-description
461 value-var))))))
463 (cl-defmacro should (form)
464 "Evaluate FORM. If it returns nil, abort the current test as failed.
466 Returns the value of FORM."
467 (ert--expand-should `(should ,form) form
468 (lambda (inner-form form-description-form _value-var)
469 `(unless ,inner-form
470 (ert-fail ,form-description-form)))))
472 (cl-defmacro should-not (form)
473 "Evaluate FORM. If it returns non-nil, abort the current test as failed.
475 Returns nil."
476 (ert--expand-should `(should-not ,form) form
477 (lambda (inner-form form-description-form _value-var)
478 `(unless (not ,inner-form)
479 (ert-fail ,form-description-form)))))
481 (defun ert--should-error-handle-error (form-description-fn
482 condition type exclude-subtypes)
483 "Helper function for `should-error'.
485 Determines whether CONDITION matches TYPE and EXCLUDE-SUBTYPES,
486 and aborts the current test as failed if it doesn't."
487 (let ((signaled-conditions (get (car condition) 'error-conditions))
488 (handled-conditions (cl-etypecase type
489 (list type)
490 (symbol (list type)))))
491 (cl-assert signaled-conditions)
492 (unless (ert--intersection signaled-conditions handled-conditions)
493 (ert-fail (append
494 (funcall form-description-fn)
495 (list
496 :condition condition
497 :fail-reason (concat "the error signaled did not"
498 " have the expected type")))))
499 (when exclude-subtypes
500 (unless (member (car condition) handled-conditions)
501 (ert-fail (append
502 (funcall form-description-fn)
503 (list
504 :condition condition
505 :fail-reason (concat "the error signaled was a subtype"
506 " of the expected type"))))))))
508 ;; FIXME: The expansion will evaluate the keyword args (if any) in
509 ;; nonstandard order.
510 (cl-defmacro should-error (form &rest keys &key type exclude-subtypes)
511 "Evaluate FORM and check that it signals an error.
513 The error signaled needs to match TYPE. TYPE should be a list
514 of condition names. (It can also be a non-nil symbol, which is
515 equivalent to a singleton list containing that symbol.) If
516 EXCLUDE-SUBTYPES is nil, the error matches TYPE if one of its
517 condition names is an element of TYPE. If EXCLUDE-SUBTYPES is
518 non-nil, the error matches TYPE if it is an element of TYPE.
520 If the error matches, returns (ERROR-SYMBOL . DATA) from the
521 error. If not, or if no error was signaled, abort the test as
522 failed."
523 (unless type (setq type ''error))
524 (ert--expand-should
525 `(should-error ,form ,@keys)
526 form
527 (lambda (inner-form form-description-form value-var)
528 (let ((errorp (ert--gensym "errorp"))
529 (form-description-fn (ert--gensym "form-description-fn-")))
530 `(let ((,errorp nil)
531 (,form-description-fn (lambda () ,form-description-form)))
532 (condition-case -condition-
533 ,inner-form
534 ;; We can't use ,type here because we want to evaluate it.
535 (error
536 (setq ,errorp t)
537 (ert--should-error-handle-error ,form-description-fn
538 -condition-
539 ,type ,exclude-subtypes)
540 (setq ,value-var -condition-)))
541 (unless ,errorp
542 (ert-fail (append
543 (funcall ,form-description-fn)
544 (list
545 :fail-reason "did not signal an error")))))))))
548 ;;; Explanation of `should' failures.
550 ;; TODO(ohler): Rework explanations so that they are displayed in a
551 ;; similar way to `ert-info' messages; in particular, allow text
552 ;; buttons in explanations that give more detail or open an ediff
553 ;; buffer. Perhaps explanations should be reported through `ert-info'
554 ;; rather than as part of the condition.
556 (defun ert--proper-list-p (x)
557 "Return non-nil if X is a proper list, nil otherwise."
558 (cl-loop
559 for firstp = t then nil
560 for fast = x then (cddr fast)
561 for slow = x then (cdr slow) do
562 (when (null fast) (cl-return t))
563 (when (not (consp fast)) (cl-return nil))
564 (when (null (cdr fast)) (cl-return t))
565 (when (not (consp (cdr fast))) (cl-return nil))
566 (when (and (not firstp) (eq fast slow)) (cl-return nil))))
568 (defun ert--explain-format-atom (x)
569 "Format the atom X for `ert--explain-equal'."
570 (cl-typecase x
571 (fixnum (list x (format "#x%x" x) (format "?%c" x)))
572 (t x)))
574 (defun ert--explain-equal-rec (a b)
575 "Return a programmer-readable explanation of why A and B are not `equal'.
576 Returns nil if they are."
577 (if (not (equal (type-of a) (type-of b)))
578 `(different-types ,a ,b)
579 (cl-etypecase a
580 (cons
581 (let ((a-proper-p (ert--proper-list-p a))
582 (b-proper-p (ert--proper-list-p b)))
583 (if (not (eql (not a-proper-p) (not b-proper-p)))
584 `(one-list-proper-one-improper ,a ,b)
585 (if a-proper-p
586 (if (not (equal (length a) (length b)))
587 `(proper-lists-of-different-length ,(length a) ,(length b)
588 ,a ,b
589 first-mismatch-at
590 ,(ert--mismatch a b))
591 (cl-loop for i from 0
592 for ai in a
593 for bi in b
594 for xi = (ert--explain-equal-rec ai bi)
595 do (when xi (cl-return `(list-elt ,i ,xi)))
596 finally (cl-assert (equal a b) t)))
597 (let ((car-x (ert--explain-equal-rec (car a) (car b))))
598 (if car-x
599 `(car ,car-x)
600 (let ((cdr-x (ert--explain-equal-rec (cdr a) (cdr b))))
601 (if cdr-x
602 `(cdr ,cdr-x)
603 (cl-assert (equal a b) t)
604 nil))))))))
605 (array (if (not (equal (length a) (length b)))
606 `(arrays-of-different-length ,(length a) ,(length b)
607 ,a ,b
608 ,@(unless (char-table-p a)
609 `(first-mismatch-at
610 ,(ert--mismatch a b))))
611 (cl-loop for i from 0
612 for ai across a
613 for bi across b
614 for xi = (ert--explain-equal-rec ai bi)
615 do (when xi (cl-return `(array-elt ,i ,xi)))
616 finally (cl-assert (equal a b) t))))
617 (atom (if (not (equal a b))
618 (if (and (symbolp a) (symbolp b) (string= a b))
619 `(different-symbols-with-the-same-name ,a ,b)
620 `(different-atoms ,(ert--explain-format-atom a)
621 ,(ert--explain-format-atom b)))
622 nil)))))
624 (defun ert--explain-equal (a b)
625 "Explainer function for `equal'."
626 ;; Do a quick comparison in C to avoid running our expensive
627 ;; comparison when possible.
628 (if (equal a b)
630 (ert--explain-equal-rec a b)))
631 (put 'equal 'ert-explainer 'ert--explain-equal)
633 (defun ert--significant-plist-keys (plist)
634 "Return the keys of PLIST that have non-null values, in order."
635 (cl-assert (zerop (mod (length plist) 2)) t)
636 (cl-loop for (key value . rest) on plist by #'cddr
637 unless (or (null value) (memq key accu)) collect key into accu
638 finally (cl-return accu)))
640 (defun ert--plist-difference-explanation (a b)
641 "Return a programmer-readable explanation of why A and B are different plists.
643 Returns nil if they are equivalent, i.e., have the same value for
644 each key, where absent values are treated as nil. The order of
645 key/value pairs in each list does not matter."
646 (cl-assert (zerop (mod (length a) 2)) t)
647 (cl-assert (zerop (mod (length b) 2)) t)
648 ;; Normalizing the plists would be another way to do this but it
649 ;; requires a total ordering on all lisp objects (since any object
650 ;; is valid as a text property key). Perhaps defining such an
651 ;; ordering is useful in other contexts, too, but it's a lot of
652 ;; work, so let's punt on it for now.
653 (let* ((keys-a (ert--significant-plist-keys a))
654 (keys-b (ert--significant-plist-keys b))
655 (keys-in-a-not-in-b (ert--set-difference-eq keys-a keys-b))
656 (keys-in-b-not-in-a (ert--set-difference-eq keys-b keys-a)))
657 (cl-flet ((explain-with-key (key)
658 (let ((value-a (plist-get a key))
659 (value-b (plist-get b key)))
660 (cl-assert (not (equal value-a value-b)) t)
661 `(different-properties-for-key
662 ,key ,(ert--explain-equal-including-properties value-a
663 value-b)))))
664 (cond (keys-in-a-not-in-b
665 (explain-with-key (car keys-in-a-not-in-b)))
666 (keys-in-b-not-in-a
667 (explain-with-key (car keys-in-b-not-in-a)))
669 (cl-loop for key in keys-a
670 when (not (equal (plist-get a key) (plist-get b key)))
671 return (explain-with-key key)))))))
673 (defun ert--abbreviate-string (s len suffixp)
674 "Shorten string S to at most LEN chars.
676 If SUFFIXP is non-nil, returns a suffix of S, otherwise a prefix."
677 (let ((n (length s)))
678 (cond ((< n len)
680 (suffixp
681 (substring s (- n len)))
683 (substring s 0 len)))))
685 ;; TODO(ohler): Once bug 6581 is fixed, rename this to
686 ;; `ert--explain-equal-including-properties-rec' and add a fast-path
687 ;; wrapper like `ert--explain-equal'.
688 (defun ert--explain-equal-including-properties (a b)
689 "Explainer function for `ert-equal-including-properties'.
691 Returns a programmer-readable explanation of why A and B are not
692 `ert-equal-including-properties', or nil if they are."
693 (if (not (equal a b))
694 (ert--explain-equal a b)
695 (cl-assert (stringp a) t)
696 (cl-assert (stringp b) t)
697 (cl-assert (eql (length a) (length b)) t)
698 (cl-loop for i from 0 to (length a)
699 for props-a = (text-properties-at i a)
700 for props-b = (text-properties-at i b)
701 for difference = (ert--plist-difference-explanation
702 props-a props-b)
703 do (when difference
704 (cl-return `(char ,i ,(substring-no-properties a i (1+ i))
705 ,difference
706 context-before
707 ,(ert--abbreviate-string
708 (substring-no-properties a 0 i)
709 10 t)
710 context-after
711 ,(ert--abbreviate-string
712 (substring-no-properties a (1+ i))
713 10 nil))))
714 ;; TODO(ohler): Get `equal-including-properties' fixed in
715 ;; Emacs, delete `ert-equal-including-properties', and
716 ;; re-enable this assertion.
717 ;;finally (cl-assert (equal-including-properties a b) t)
719 (put 'ert-equal-including-properties
720 'ert-explainer
721 'ert--explain-equal-including-properties)
724 ;;; Implementation of `ert-info'.
726 ;; TODO(ohler): The name `info' clashes with
727 ;; `ert--test-execution-info'. One or both should be renamed.
728 (defvar ert--infos '()
729 "The stack of `ert-info' infos that currently apply.
731 Bound dynamically. This is a list of (PREFIX . MESSAGE) pairs.")
733 (cl-defmacro ert-info ((message-form &key ((:prefix prefix-form) "Info: "))
734 &body body)
735 "Evaluate MESSAGE-FORM and BODY, and report the message if BODY fails.
737 To be used within ERT tests. MESSAGE-FORM should evaluate to a
738 string that will be displayed together with the test result if
739 the test fails. PREFIX-FORM should evaluate to a string as well
740 and is displayed in front of the value of MESSAGE-FORM."
741 (declare (debug ((form &rest [sexp form]) body))
742 (indent 1))
743 `(let ((ert--infos (cons (cons ,prefix-form ,message-form) ert--infos)))
744 ,@body))
748 ;;; Facilities for running a single test.
750 (defvar ert-debug-on-error nil
751 "Non-nil means enter debugger when a test fails or terminates with an error.")
753 ;; The data structures that represent the result of running a test.
754 (cl-defstruct ert-test-result
755 (messages nil)
756 (should-forms nil)
758 (cl-defstruct (ert-test-passed (:include ert-test-result)))
759 (cl-defstruct (ert-test-result-with-condition (:include ert-test-result))
760 (condition (cl-assert nil))
761 (backtrace (cl-assert nil))
762 (infos (cl-assert nil)))
763 (cl-defstruct (ert-test-quit (:include ert-test-result-with-condition)))
764 (cl-defstruct (ert-test-failed (:include ert-test-result-with-condition)))
765 (cl-defstruct (ert-test-aborted-with-non-local-exit
766 (:include ert-test-result)))
769 (defun ert--record-backtrace ()
770 "Record the current backtrace (as a list) and return it."
771 ;; Since the backtrace is stored in the result object, result
772 ;; objects must only be printed with appropriate limits
773 ;; (`print-level' and `print-length') in place. For interactive
774 ;; use, the cost of ensuring this possibly outweighs the advantage
775 ;; of storing the backtrace for
776 ;; `ert-results-pop-to-backtrace-for-test-at-point' given that we
777 ;; already have `ert-results-rerun-test-debugging-errors-at-point'.
778 ;; For batch use, however, printing the backtrace may be useful.
779 (cl-loop
780 ;; 6 is the number of frames our own debugger adds (when
781 ;; compiled; more when interpreted). FIXME: Need to describe a
782 ;; procedure for determining this constant.
783 for i from 6
784 for frame = (backtrace-frame i)
785 while frame
786 collect frame))
788 (defun ert--print-backtrace (backtrace)
789 "Format the backtrace BACKTRACE to the current buffer."
790 ;; This is essentially a reimplementation of Fbacktrace
791 ;; (src/eval.c), but for a saved backtrace, not the current one.
792 (let ((print-escape-newlines t)
793 (print-level 8)
794 (print-length 50))
795 (dolist (frame backtrace)
796 (cl-ecase (car frame)
797 ((nil)
798 ;; Special operator.
799 (cl-destructuring-bind (special-operator &rest arg-forms)
800 (cdr frame)
801 (insert
802 (format " %S\n" (cons special-operator arg-forms)))))
803 ((t)
804 ;; Function call.
805 (cl-destructuring-bind (fn &rest args) (cdr frame)
806 (insert (format " %S(" fn))
807 (cl-loop for firstp = t then nil
808 for arg in args do
809 (unless firstp
810 (insert " "))
811 (insert (format "%S" arg)))
812 (insert ")\n")))))))
814 ;; A container for the state of the execution of a single test and
815 ;; environment data needed during its execution.
816 (cl-defstruct ert--test-execution-info
817 (test (cl-assert nil))
818 (result (cl-assert nil))
819 ;; A thunk that may be called when RESULT has been set to its final
820 ;; value and test execution should be terminated. Should not
821 ;; return.
822 (exit-continuation (cl-assert nil))
823 ;; The binding of `debugger' outside of the execution of the test.
824 next-debugger
825 ;; The binding of `ert-debug-on-error' that is in effect for the
826 ;; execution of the current test. We store it to avoid being
827 ;; affected by any new bindings the test itself may establish. (I
828 ;; don't remember whether this feature is important.)
829 ert-debug-on-error)
831 (defun ert--run-test-debugger (info args)
832 "During a test run, `debugger' is bound to a closure that calls this function.
834 This function records failures and errors and either terminates
835 the test silently or calls the interactive debugger, as
836 appropriate.
838 INFO is the ert--test-execution-info corresponding to this test
839 run. ARGS are the arguments to `debugger'."
840 (cl-destructuring-bind (first-debugger-arg &rest more-debugger-args)
841 args
842 (cl-ecase first-debugger-arg
843 ((lambda debug t exit nil)
844 (apply (ert--test-execution-info-next-debugger info) args))
845 (error
846 (let* ((condition (car more-debugger-args))
847 (type (cl-case (car condition)
848 ((quit) 'quit)
849 (otherwise 'failed)))
850 (backtrace (ert--record-backtrace))
851 (infos (reverse ert--infos)))
852 (setf (ert--test-execution-info-result info)
853 (cl-ecase type
854 (quit
855 (make-ert-test-quit :condition condition
856 :backtrace backtrace
857 :infos infos))
858 (failed
859 (make-ert-test-failed :condition condition
860 :backtrace backtrace
861 :infos infos))))
862 ;; Work around Emacs's heuristic (in eval.c) for detecting
863 ;; errors in the debugger.
864 (cl-incf num-nonmacro-input-events)
865 ;; FIXME: We should probably implement more fine-grained
866 ;; control a la non-t `debug-on-error' here.
867 (cond
868 ((ert--test-execution-info-ert-debug-on-error info)
869 (apply (ert--test-execution-info-next-debugger info) args))
870 (t))
871 (funcall (ert--test-execution-info-exit-continuation info)))))))
873 (defun ert--run-test-internal (test-execution-info)
874 "Low-level function to run a test according to TEST-EXECUTION-INFO.
876 This mainly sets up debugger-related bindings."
877 (setf (ert--test-execution-info-next-debugger test-execution-info) debugger
878 (ert--test-execution-info-ert-debug-on-error test-execution-info)
879 ert-debug-on-error)
880 (catch 'ert--pass
881 ;; For now, each test gets its own temp buffer and its own
882 ;; window excursion, just to be safe. If this turns out to be
883 ;; too expensive, we can remove it.
884 (with-temp-buffer
885 (save-window-excursion
886 (let ((debugger (lambda (&rest args)
887 (ert--run-test-debugger test-execution-info
888 args)))
889 (debug-on-error t)
890 (debug-on-quit t)
891 ;; FIXME: Do we need to store the old binding of this
892 ;; and consider it in `ert--run-test-debugger'?
893 (debug-ignored-errors nil)
894 (ert--infos '()))
895 (funcall (ert-test-body (ert--test-execution-info-test
896 test-execution-info))))))
897 (ert-pass))
898 (setf (ert--test-execution-info-result test-execution-info)
899 (make-ert-test-passed))
900 nil)
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))
909 ;; {
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);
913 ;; }
914 (when (and (integerp message-log-max) (>= message-log-max 0))
915 (let ((begin (point-min))
916 (end (save-excursion
917 (goto-char (point-max))
918 (forward-line (- message-log-max))
919 (point))))
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)
933 "Run 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)
937 (cl-block error
938 (let ((begin-marker
939 (with-current-buffer (get-buffer-create "*Messages*")
940 (set-marker (make-marker) (point-max)))))
941 (unwind-protect
942 (let ((info (make-ert--test-execution-info
943 :test ert-test
944 :result
945 (make-ert-test-aborted-with-non-local-exit)
946 :exit-continuation (lambda ()
947 (cl-return-from error nil))))
948 (should-form-accu (list)))
949 (unwind-protect
950 (let ((ert--should-execution-observer
951 (lambda (form-description)
952 (push form-description should-form-accu)))
953 (message-log-max t)
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)
963 should-form-accu)
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)))
973 ;;; Test selectors.
975 (defun ert-test-result-type-p (result result-type)
976 "Return non-nil if RESULT matches type RESULT-TYPE.
978 Valid result types:
980 nil -- Never matches.
981 t -- Always 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
987 RESULT."
988 ;; It would be easy to add `member' and `eql' types etc., but I
989 ;; haven't bothered yet.
990 (cl-etypecase result-type
991 ((member nil) nil)
992 ((member t) t)
993 ((member :failed) (ert-test-failed-p result))
994 ((member :passed) (ert-test-passed-p result))
995 (cons
996 (cl-destructuring-bind (operator &rest operands) result-type
997 (cl-ecase operator
998 (and
999 (cl-case (length operands)
1000 (0 t)
1002 (and (ert-test-result-type-p result (car operands))
1003 (ert-test-result-type-p result `(and ,@(cdr operands)))))))
1005 (cl-case (length operands)
1006 (0 nil)
1008 (or (ert-test-result-type-p result (car operands))
1009 (ert-test-result-type-p result `(or ,@(cdr operands)))))))
1010 (not
1011 (cl-assert (eql (length operands) 1))
1012 (not (ert-test-result-type-p result (car operands))))
1013 (satisfies
1014 (cl-assert (eql (length operands) 1))
1015 (funcall (car 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'.
1027 Valid SELECTORs:
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'.
1056 (cl-etypecase selector
1057 ((member nil) nil)
1058 ((member t) (cl-etypecase universe
1059 (list 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))))
1064 universe))
1065 ((member :failed) (ert-select-tests
1066 `(satisfies ,(lambda (test)
1067 (ert-test-result-type-p
1068 (ert-test-most-recent-result test)
1069 ':failed)))
1070 universe))
1071 ((member :passed) (ert-select-tests
1072 `(satisfies ,(lambda (test)
1073 (ert-test-result-type-p
1074 (ert-test-most-recent-result test)
1075 ':passed)))
1076 universe))
1077 ((member :expected) (ert-select-tests
1078 `(satisfies
1079 ,(lambda (test)
1080 (ert-test-result-expected-p
1081 test
1082 (ert-test-most-recent-result test))))
1083 universe))
1084 ((member :unexpected) (ert-select-tests `(not :expected) universe))
1085 (string
1086 (cl-etypecase 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))))
1093 universe))))
1094 (ert-test (list selector))
1095 (symbol
1096 (cl-assert (ert-test-boundp selector))
1097 (list (ert-get-test selector)))
1098 (cons
1099 (cl-destructuring-bind (operator &rest operands) selector
1100 (cl-ecase operator
1101 (member
1102 (mapcar (lambda (purported-test)
1103 (cl-etypecase purported-test
1104 (symbol (cl-assert (ert-test-boundp purported-test))
1105 (ert-get-test purported-test))
1106 (ert-test purported-test)))
1107 operands))
1108 (eql
1109 (cl-assert (eql (length operands) 1))
1110 (ert-select-tests `(member ,@operands) universe))
1111 (and
1112 ;; Do these definitions of AND, NOT and OR satisfy de
1113 ;; Morgan's laws? Should they?
1114 (cl-case (length operands)
1115 (0 (ert-select-tests 't universe))
1116 (t (ert-select-tests `(and ,@(cdr operands))
1117 (ert-select-tests (car operands)
1118 universe)))))
1119 (not
1120 (cl-assert (eql (length operands) 1))
1121 (let ((all-tests (ert-select-tests 't universe)))
1122 (ert--set-difference all-tests
1123 (ert-select-tests (car operands)
1124 all-tests))))
1126 (cl-case (length operands)
1127 (0 (ert-select-tests 'nil universe))
1128 (t (ert--union (ert-select-tests (car operands) universe)
1129 (ert-select-tests `(or ,@(cdr operands))
1130 universe)))))
1131 (tag
1132 (cl-assert (eql (length operands) 1))
1133 (let ((tag (car operands)))
1134 (ert-select-tests `(satisfies
1135 ,(lambda (test)
1136 (member tag (ert-test-tags test))))
1137 universe)))
1138 (satisfies
1139 (cl-assert (eql (length operands) 1))
1140 (ert--remove-if-not (car 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 (cl-labels ((rec (selector)
1150 ;; This code needs to match the etypecase in
1151 ;; `ert-select-tests'.
1152 (cl-etypecase selector
1153 ((or (member nil t
1154 :new :failed :passed
1155 :expected :unexpected)
1156 string
1157 symbol)
1158 selector)
1159 (ert-test
1160 (if (ert-test-name selector)
1161 (make-symbol (format "<%S>" (ert-test-name selector)))
1162 (make-symbol "<unnamed test>")))
1163 (cons
1164 (cl-destructuring-bind (operator &rest operands) selector
1165 (cl-ecase operator
1166 ((member eql and not or)
1167 `(,operator ,@(mapcar #'rec operands)))
1168 ((member tag satisfies)
1169 selector)))))))
1170 (insert (format "%S" (rec selector)))))
1173 ;;; Facilities for running a whole set of tests.
1175 ;; The data structure that contains the set of tests being executed
1176 ;; during one particular test run, their results, the state of the
1177 ;; execution, and some statistics.
1179 ;; The data about results and expected results of tests may seem
1180 ;; redundant here, since the test objects also carry such information.
1181 ;; However, the information in the test objects may be more recent, it
1182 ;; may correspond to a different test run. We need the information
1183 ;; that corresponds to this run in order to be able to update the
1184 ;; statistics correctly when a test is re-run interactively and has a
1185 ;; different result than before.
1186 (cl-defstruct ert--stats
1187 (selector (cl-assert nil))
1188 ;; The tests, in order.
1189 (tests (cl-assert nil) :type vector)
1190 ;; A map of test names (or the test objects themselves for unnamed
1191 ;; tests) to indices into the `tests' vector.
1192 (test-map (cl-assert nil) :type hash-table)
1193 ;; The results of the tests during this run, in order.
1194 (test-results (cl-assert nil) :type vector)
1195 ;; The start times of the tests, in order, as reported by
1196 ;; `current-time'.
1197 (test-start-times (cl-assert nil) :type vector)
1198 ;; The end times of the tests, in order, as reported by
1199 ;; `current-time'.
1200 (test-end-times (cl-assert nil) :type vector)
1201 (passed-expected 0)
1202 (passed-unexpected 0)
1203 (failed-expected 0)
1204 (failed-unexpected 0)
1205 (start-time nil)
1206 (end-time nil)
1207 (aborted-p nil)
1208 (current-test nil)
1209 ;; The time at or after which the next redisplay should occur, as a
1210 ;; float.
1211 (next-redisplay 0.0))
1213 (defun ert-stats-completed-expected (stats)
1214 "Return the number of tests in STATS that had expected results."
1215 (+ (ert--stats-passed-expected stats)
1216 (ert--stats-failed-expected stats)))
1218 (defun ert-stats-completed-unexpected (stats)
1219 "Return the number of tests in STATS that had unexpected results."
1220 (+ (ert--stats-passed-unexpected stats)
1221 (ert--stats-failed-unexpected stats)))
1223 (defun ert-stats-completed (stats)
1224 "Number of tests in STATS that have run so far."
1225 (+ (ert-stats-completed-expected stats)
1226 (ert-stats-completed-unexpected stats)))
1228 (defun ert-stats-total (stats)
1229 "Number of tests in STATS, regardless of whether they have run yet."
1230 (length (ert--stats-tests stats)))
1232 ;; The stats object of the current run, dynamically bound. This is
1233 ;; used for the mode line progress indicator.
1234 (defvar ert--current-run-stats nil)
1236 (defun ert--stats-test-key (test)
1237 "Return the key used for TEST in the test map of ert--stats objects.
1239 Returns the name of TEST if it has one, or TEST itself otherwise."
1240 (or (ert-test-name test) test))
1242 (defun ert--stats-set-test-and-result (stats pos test result)
1243 "Change STATS by replacing the test at position POS with TEST and RESULT.
1245 Also changes the counters in STATS to match."
1246 (let* ((tests (ert--stats-tests stats))
1247 (results (ert--stats-test-results stats))
1248 (old-test (aref tests pos))
1249 (map (ert--stats-test-map stats)))
1250 (cl-flet ((update (d)
1251 (if (ert-test-result-expected-p (aref tests pos)
1252 (aref results pos))
1253 (cl-etypecase (aref results pos)
1254 (ert-test-passed
1255 (cl-incf (ert--stats-passed-expected stats) d))
1256 (ert-test-failed
1257 (cl-incf (ert--stats-failed-expected stats) d))
1258 (null)
1259 (ert-test-aborted-with-non-local-exit)
1260 (ert-test-quit))
1261 (cl-etypecase (aref results pos)
1262 (ert-test-passed
1263 (cl-incf (ert--stats-passed-unexpected stats) d))
1264 (ert-test-failed
1265 (cl-incf (ert--stats-failed-unexpected stats) d))
1266 (null)
1267 (ert-test-aborted-with-non-local-exit)
1268 (ert-test-quit)))))
1269 ;; Adjust counters to remove the result that is currently in stats.
1270 (update -1)
1271 ;; Put new test and result into stats.
1272 (setf (aref tests pos) test
1273 (aref results pos) result)
1274 (remhash (ert--stats-test-key old-test) map)
1275 (setf (gethash (ert--stats-test-key test) map) pos)
1276 ;; Adjust counters to match new result.
1277 (update +1)
1278 nil)))
1280 (defun ert--make-stats (tests selector)
1281 "Create a new `ert--stats' object for running TESTS.
1283 SELECTOR is the selector that was used to select TESTS."
1284 (setq tests (ert--coerce-to-vector tests))
1285 (let ((map (make-hash-table :size (length tests))))
1286 (cl-loop for i from 0
1287 for test across tests
1288 for key = (ert--stats-test-key test) do
1289 (cl-assert (not (gethash key map)))
1290 (setf (gethash key map) i))
1291 (make-ert--stats :selector selector
1292 :tests tests
1293 :test-map map
1294 :test-results (make-vector (length tests) nil)
1295 :test-start-times (make-vector (length tests) nil)
1296 :test-end-times (make-vector (length tests) nil))))
1298 (defun ert-run-or-rerun-test (stats test listener)
1299 ;; checkdoc-order: nil
1300 "Run the single test TEST and record the result using STATS and LISTENER."
1301 (let ((ert--current-run-stats stats)
1302 (pos (ert--stats-test-pos stats test)))
1303 (ert--stats-set-test-and-result stats pos test nil)
1304 ;; Call listener after setting/before resetting
1305 ;; (ert--stats-current-test stats); the listener might refresh the
1306 ;; mode line display, and if the value is not set yet/any more
1307 ;; during this refresh, the mode line will flicker unnecessarily.
1308 (setf (ert--stats-current-test stats) test)
1309 (funcall listener 'test-started stats test)
1310 (setf (ert-test-most-recent-result test) nil)
1311 (setf (aref (ert--stats-test-start-times stats) pos) (current-time))
1312 (unwind-protect
1313 (ert-run-test test)
1314 (setf (aref (ert--stats-test-end-times stats) pos) (current-time))
1315 (let ((result (ert-test-most-recent-result test)))
1316 (ert--stats-set-test-and-result stats pos test result)
1317 (funcall listener 'test-ended stats test result))
1318 (setf (ert--stats-current-test stats) nil))))
1320 (defun ert-run-tests (selector listener)
1321 "Run the tests specified by SELECTOR, sending progress updates to LISTENER."
1322 (let* ((tests (ert-select-tests selector t))
1323 (stats (ert--make-stats tests selector)))
1324 (setf (ert--stats-start-time stats) (current-time))
1325 (funcall listener 'run-started stats)
1326 (let ((abortedp t))
1327 (unwind-protect
1328 (let ((ert--current-run-stats stats))
1329 (force-mode-line-update)
1330 (unwind-protect
1331 (progn
1332 (cl-loop for test in tests do
1333 (ert-run-or-rerun-test stats test listener))
1334 (setq abortedp nil))
1335 (setf (ert--stats-aborted-p stats) abortedp)
1336 (setf (ert--stats-end-time stats) (current-time))
1337 (funcall listener 'run-ended stats abortedp)))
1338 (force-mode-line-update))
1339 stats)))
1341 (defun ert--stats-test-pos (stats test)
1342 ;; checkdoc-order: nil
1343 "Return the position (index) of TEST in the run represented by STATS."
1344 (gethash (ert--stats-test-key test) (ert--stats-test-map stats)))
1347 ;;; Formatting functions shared across UIs.
1349 (defun ert--format-time-iso8601 (time)
1350 "Format TIME in the variant of ISO 8601 used for timestamps in ERT."
1351 (format-time-string "%Y-%m-%d %T%z" time))
1353 (defun ert-char-for-test-result (result expectedp)
1354 "Return a character that represents the test result RESULT.
1356 EXPECTEDP specifies whether the result was expected."
1357 (let ((s (cl-etypecase result
1358 (ert-test-passed ".P")
1359 (ert-test-failed "fF")
1360 (null "--")
1361 (ert-test-aborted-with-non-local-exit "aA")
1362 (ert-test-quit "qQ"))))
1363 (elt s (if expectedp 0 1))))
1365 (defun ert-string-for-test-result (result expectedp)
1366 "Return a string that represents the test result RESULT.
1368 EXPECTEDP specifies whether the result was expected."
1369 (let ((s (cl-etypecase result
1370 (ert-test-passed '("passed" "PASSED"))
1371 (ert-test-failed '("failed" "FAILED"))
1372 (null '("unknown" "UNKNOWN"))
1373 (ert-test-aborted-with-non-local-exit '("aborted" "ABORTED"))
1374 (ert-test-quit '("quit" "QUIT")))))
1375 (elt s (if expectedp 0 1))))
1377 (defun ert--pp-with-indentation-and-newline (object)
1378 "Pretty-print OBJECT, indenting it to the current column of point.
1379 Ensures a final newline is inserted."
1380 (let ((begin (point)))
1381 (pp object (current-buffer))
1382 (unless (bolp) (insert "\n"))
1383 (save-excursion
1384 (goto-char begin)
1385 (indent-sexp))))
1387 (defun ert--insert-infos (result)
1388 "Insert `ert-info' infos from RESULT into current buffer.
1390 RESULT must be an `ert-test-result-with-condition'."
1391 (cl-check-type result ert-test-result-with-condition)
1392 (dolist (info (ert-test-result-with-condition-infos result))
1393 (cl-destructuring-bind (prefix . message) info
1394 (let ((begin (point))
1395 (indentation (make-string (+ (length prefix) 4) ?\s))
1396 (end nil))
1397 (unwind-protect
1398 (progn
1399 (insert message "\n")
1400 (setq end (copy-marker (point)))
1401 (goto-char begin)
1402 (insert " " prefix)
1403 (forward-line 1)
1404 (while (< (point) end)
1405 (insert indentation)
1406 (forward-line 1)))
1407 (when end (set-marker end nil)))))))
1410 ;;; Running tests in batch mode.
1412 (defvar ert-batch-backtrace-right-margin 70
1413 "The maximum line length for printing backtraces in `ert-run-tests-batch'.")
1415 ;;;###autoload
1416 (defun ert-run-tests-batch (&optional selector)
1417 "Run the tests specified by SELECTOR, printing results to the terminal.
1419 SELECTOR works as described in `ert-select-tests', except if
1420 SELECTOR is nil, in which case all tests rather than none will be
1421 run; this makes the command line \"emacs -batch -l my-tests.el -f
1422 ert-run-tests-batch-and-exit\" useful.
1424 Returns the stats object."
1425 (unless selector (setq selector 't))
1426 (ert-run-tests
1427 selector
1428 (lambda (event-type &rest event-args)
1429 (cl-ecase event-type
1430 (run-started
1431 (cl-destructuring-bind (stats) event-args
1432 (message "Running %s tests (%s)"
1433 (length (ert--stats-tests stats))
1434 (ert--format-time-iso8601 (ert--stats-start-time stats)))))
1435 (run-ended
1436 (cl-destructuring-bind (stats abortedp) event-args
1437 (let ((unexpected (ert-stats-completed-unexpected stats))
1438 (expected-failures (ert--stats-failed-expected stats)))
1439 (message "\n%sRan %s tests, %s results as expected%s (%s)%s\n"
1440 (if (not abortedp)
1442 "Aborted: ")
1443 (ert-stats-total stats)
1444 (ert-stats-completed-expected stats)
1445 (if (zerop unexpected)
1447 (format ", %s unexpected" unexpected))
1448 (ert--format-time-iso8601 (ert--stats-end-time stats))
1449 (if (zerop expected-failures)
1451 (format "\n%s expected failures" expected-failures)))
1452 (unless (zerop unexpected)
1453 (message "%s unexpected results:" unexpected)
1454 (cl-loop for test across (ert--stats-tests stats)
1455 for result = (ert-test-most-recent-result test) do
1456 (when (not (ert-test-result-expected-p test result))
1457 (message "%9s %S"
1458 (ert-string-for-test-result result nil)
1459 (ert-test-name test))))
1460 (message "%s" "")))))
1461 (test-started
1463 (test-ended
1464 (cl-destructuring-bind (stats test result) event-args
1465 (unless (ert-test-result-expected-p test result)
1466 (cl-etypecase result
1467 (ert-test-passed
1468 (message "Test %S passed unexpectedly" (ert-test-name test)))
1469 (ert-test-result-with-condition
1470 (message "Test %S backtrace:" (ert-test-name test))
1471 (with-temp-buffer
1472 (ert--print-backtrace (ert-test-result-with-condition-backtrace
1473 result))
1474 (goto-char (point-min))
1475 (while (not (eobp))
1476 (let ((start (point))
1477 (end (progn (end-of-line) (point))))
1478 (setq end (min end
1479 (+ start ert-batch-backtrace-right-margin)))
1480 (message "%s" (buffer-substring-no-properties
1481 start end)))
1482 (forward-line 1)))
1483 (with-temp-buffer
1484 (ert--insert-infos result)
1485 (insert " ")
1486 (let ((print-escape-newlines t)
1487 (print-level 5)
1488 (print-length 10))
1489 (ert--pp-with-indentation-and-newline
1490 (ert-test-result-with-condition-condition result)))
1491 (goto-char (1- (point-max)))
1492 (cl-assert (looking-at "\n"))
1493 (delete-char 1)
1494 (message "Test %S condition:" (ert-test-name test))
1495 (message "%s" (buffer-string))))
1496 (ert-test-aborted-with-non-local-exit
1497 (message "Test %S aborted with non-local exit"
1498 (ert-test-name test)))
1499 (ert-test-quit
1500 (message "Quit during %S" (ert-test-name test)))))
1501 (let* ((max (prin1-to-string (length (ert--stats-tests stats))))
1502 (format-string (concat "%9s %"
1503 (prin1-to-string (length max))
1504 "s/" max " %S")))
1505 (message format-string
1506 (ert-string-for-test-result result
1507 (ert-test-result-expected-p
1508 test result))
1509 (1+ (ert--stats-test-pos stats test))
1510 (ert-test-name test)))))))))
1512 ;;;###autoload
1513 (defun ert-run-tests-batch-and-exit (&optional selector)
1514 "Like `ert-run-tests-batch', but exits Emacs when done.
1516 The exit status will be 0 if all test results were as expected, 1
1517 on unexpected results, or 2 if the tool detected an error outside
1518 of the tests (e.g. invalid SELECTOR or bug in the code that runs
1519 the tests)."
1520 (unwind-protect
1521 (let ((stats (ert-run-tests-batch selector)))
1522 (kill-emacs (if (zerop (ert-stats-completed-unexpected stats)) 0 1)))
1523 (unwind-protect
1524 (progn
1525 (message "Error running tests")
1526 (backtrace))
1527 (kill-emacs 2))))
1530 ;;; Utility functions for load/unload actions.
1532 (defun ert--activate-font-lock-keywords ()
1533 "Activate font-lock keywords for some of ERT's symbols."
1534 (font-lock-add-keywords
1536 '(("(\\(\\<ert-deftest\\)\\>\\s *\\(\\sw+\\)?"
1537 (1 font-lock-keyword-face nil t)
1538 (2 font-lock-function-name-face nil t)))))
1540 (cl-defun ert--remove-from-list (list-var element &key key test)
1541 "Remove ELEMENT from the value of LIST-VAR if present.
1543 This can be used as an inverse of `add-to-list'."
1544 (unless key (setq key #'identity))
1545 (unless test (setq test #'equal))
1546 (setf (symbol-value list-var)
1547 (ert--remove* element
1548 (symbol-value list-var)
1549 :key key
1550 :test test)))
1553 ;;; Some basic interactive functions.
1555 (defun ert-read-test-name (prompt &optional default history
1556 add-default-to-prompt)
1557 "Read the name of a test and return it as a symbol.
1559 Prompt with PROMPT. If DEFAULT is a valid test name, use it as a
1560 default. HISTORY is the history to use; see `completing-read'.
1561 If ADD-DEFAULT-TO-PROMPT is non-nil, PROMPT will be modified to
1562 include the default, if any.
1564 Signals an error if no test name was read."
1565 (cl-etypecase default
1566 (string (let ((symbol (intern-soft default)))
1567 (unless (and symbol (ert-test-boundp symbol))
1568 (setq default nil))))
1569 (symbol (setq default
1570 (if (ert-test-boundp default)
1571 (symbol-name default)
1572 nil)))
1573 (ert-test (setq default (ert-test-name default))))
1574 (when add-default-to-prompt
1575 (setq prompt (if (null default)
1576 (format "%s: " prompt)
1577 (format "%s (default %s): " prompt default))))
1578 (let ((input (completing-read prompt obarray #'ert-test-boundp
1579 t nil history default nil)))
1580 ;; completing-read returns an empty string if default was nil and
1581 ;; the user just hit enter.
1582 (let ((sym (intern-soft input)))
1583 (if (ert-test-boundp sym)
1585 (error "Input does not name a test")))))
1587 (defun ert-read-test-name-at-point (prompt)
1588 "Read the name of a test and return it as a symbol.
1589 As a default, use the symbol at point, or the test at point if in
1590 the ERT results buffer. Prompt with PROMPT, augmented with the
1591 default (if any)."
1592 (ert-read-test-name prompt (ert-test-at-point) nil t))
1594 (defun ert-find-test-other-window (test-name)
1595 "Find, in another window, the definition of TEST-NAME."
1596 (interactive (list (ert-read-test-name-at-point "Find test definition: ")))
1597 (find-function-do-it test-name 'ert-deftest 'switch-to-buffer-other-window))
1599 (defun ert-delete-test (test-name)
1600 "Make the test TEST-NAME unbound.
1602 Nothing more than an interactive interface to `ert-make-test-unbound'."
1603 (interactive (list (ert-read-test-name-at-point "Delete test")))
1604 (ert-make-test-unbound test-name))
1606 (defun ert-delete-all-tests ()
1607 "Make all symbols in `obarray' name no test."
1608 (interactive)
1609 (when (called-interactively-p 'any)
1610 (unless (y-or-n-p "Delete all tests? ")
1611 (error "Aborted")))
1612 ;; We can't use `ert-select-tests' here since that gives us only
1613 ;; test objects, and going from them back to the test name symbols
1614 ;; can fail if the `ert-test' defstruct has been redefined.
1615 (mapc #'ert-make-test-unbound (apropos-internal "" #'ert-test-boundp))
1619 ;;; Display of test progress and results.
1621 ;; An entry in the results buffer ewoc. There is one entry per test.
1622 (cl-defstruct ert--ewoc-entry
1623 (test (cl-assert nil))
1624 ;; If the result of this test was expected, its ewoc entry is hidden
1625 ;; initially.
1626 (hidden-p (cl-assert nil))
1627 ;; An ewoc entry may be collapsed to hide details such as the error
1628 ;; condition.
1630 ;; I'm not sure the ability to expand and collapse entries is still
1631 ;; a useful feature.
1632 (expanded-p t)
1633 ;; By default, the ewoc entry presents the error condition with
1634 ;; certain limits on how much to print (`print-level',
1635 ;; `print-length'). The user can interactively switch to a set of
1636 ;; higher limits.
1637 (extended-printer-limits-p nil))
1639 ;; Variables local to the results buffer.
1641 ;; The ewoc.
1642 (defvar ert--results-ewoc)
1643 ;; The stats object.
1644 (defvar ert--results-stats)
1645 ;; A string with one character per test. Each character represents
1646 ;; the result of the corresponding test. The string is displayed near
1647 ;; the top of the buffer and serves as a progress bar.
1648 (defvar ert--results-progress-bar-string)
1649 ;; The position where the progress bar button begins.
1650 (defvar ert--results-progress-bar-button-begin)
1651 ;; The test result listener that updates the buffer when tests are run.
1652 (defvar ert--results-listener)
1654 (defun ert-insert-test-name-button (test-name)
1655 "Insert a button that links to TEST-NAME."
1656 (insert-text-button (format "%S" test-name)
1657 :type 'ert--test-name-button
1658 'ert-test-name test-name))
1660 (defun ert--results-format-expected-unexpected (expected unexpected)
1661 "Return a string indicating EXPECTED expected results, UNEXPECTED unexpected."
1662 (if (zerop unexpected)
1663 (format "%s" expected)
1664 (format "%s (%s unexpected)" (+ expected unexpected) unexpected)))
1666 (defun ert--results-update-ewoc-hf (ewoc stats)
1667 "Update the header and footer of EWOC to show certain information from STATS.
1669 Also sets `ert--results-progress-bar-button-begin'."
1670 (let ((run-count (ert-stats-completed stats))
1671 (results-buffer (current-buffer))
1672 ;; Need to save buffer-local value.
1673 (font-lock font-lock-mode))
1674 (ewoc-set-hf
1675 ewoc
1676 ;; header
1677 (with-temp-buffer
1678 (insert "Selector: ")
1679 (ert--insert-human-readable-selector (ert--stats-selector stats))
1680 (insert "\n")
1681 (insert
1682 (format (concat "Passed: %s\n"
1683 "Failed: %s\n"
1684 "Total: %s/%s\n\n")
1685 (ert--results-format-expected-unexpected
1686 (ert--stats-passed-expected stats)
1687 (ert--stats-passed-unexpected stats))
1688 (ert--results-format-expected-unexpected
1689 (ert--stats-failed-expected stats)
1690 (ert--stats-failed-unexpected stats))
1691 run-count
1692 (ert-stats-total stats)))
1693 (insert
1694 (format "Started at: %s\n"
1695 (ert--format-time-iso8601 (ert--stats-start-time stats))))
1696 ;; FIXME: This is ugly. Need to properly define invariants of
1697 ;; the `stats' data structure.
1698 (let ((state (cond ((ert--stats-aborted-p stats) 'aborted)
1699 ((ert--stats-current-test stats) 'running)
1700 ((ert--stats-end-time stats) 'finished)
1701 (t 'preparing))))
1702 (cl-ecase state
1703 (preparing
1704 (insert ""))
1705 (aborted
1706 (cond ((ert--stats-current-test stats)
1707 (insert "Aborted during test: ")
1708 (ert-insert-test-name-button
1709 (ert-test-name (ert--stats-current-test stats))))
1711 (insert "Aborted."))))
1712 (running
1713 (cl-assert (ert--stats-current-test stats))
1714 (insert "Running test: ")
1715 (ert-insert-test-name-button (ert-test-name
1716 (ert--stats-current-test stats))))
1717 (finished
1718 (cl-assert (not (ert--stats-current-test stats)))
1719 (insert "Finished.")))
1720 (insert "\n")
1721 (if (ert--stats-end-time stats)
1722 (insert
1723 (format "%s%s\n"
1724 (if (ert--stats-aborted-p stats)
1725 "Aborted at: "
1726 "Finished at: ")
1727 (ert--format-time-iso8601 (ert--stats-end-time stats))))
1728 (insert "\n"))
1729 (insert "\n"))
1730 (let ((progress-bar-string (with-current-buffer results-buffer
1731 ert--results-progress-bar-string)))
1732 (let ((progress-bar-button-begin
1733 (insert-text-button progress-bar-string
1734 :type 'ert--results-progress-bar-button
1735 'face (or (and font-lock
1736 (ert-face-for-stats stats))
1737 'button))))
1738 ;; The header gets copied verbatim to the results buffer,
1739 ;; and all positions remain the same, so
1740 ;; `progress-bar-button-begin' will be the right position
1741 ;; even in the results buffer.
1742 (with-current-buffer results-buffer
1743 (set (make-local-variable 'ert--results-progress-bar-button-begin)
1744 progress-bar-button-begin))))
1745 (insert "\n\n")
1746 (buffer-string))
1747 ;; footer
1749 ;; We actually want an empty footer, but that would trigger a bug
1750 ;; in ewoc, sometimes clearing the entire buffer. (It's possible
1751 ;; that this bug has been fixed since this has been tested; we
1752 ;; should test it again.)
1753 "\n")))
1756 (defvar ert-test-run-redisplay-interval-secs .1
1757 "How many seconds ERT should wait between redisplays while running tests.
1759 While running tests, ERT shows the current progress, and this variable
1760 determines how frequently the progress display is updated.")
1762 (defun ert--results-update-stats-display (ewoc stats)
1763 "Update EWOC and the mode line to show data from STATS."
1764 ;; TODO(ohler): investigate using `make-progress-reporter'.
1765 (ert--results-update-ewoc-hf ewoc stats)
1766 (force-mode-line-update)
1767 (redisplay t)
1768 (setf (ert--stats-next-redisplay stats)
1769 (+ (float-time) ert-test-run-redisplay-interval-secs)))
1771 (defun ert--results-update-stats-display-maybe (ewoc stats)
1772 "Call `ert--results-update-stats-display' if not called recently.
1774 EWOC and STATS are arguments for `ert--results-update-stats-display'."
1775 (when (>= (float-time) (ert--stats-next-redisplay stats))
1776 (ert--results-update-stats-display ewoc stats)))
1778 (defun ert--tests-running-mode-line-indicator ()
1779 "Return a string for the mode line that shows the test run progress."
1780 (let* ((stats ert--current-run-stats)
1781 (tests-total (ert-stats-total stats))
1782 (tests-completed (ert-stats-completed stats)))
1783 (if (>= tests-completed tests-total)
1784 (format " ERT(%s/%s,finished)" tests-completed tests-total)
1785 (format " ERT(%s/%s):%s"
1786 (1+ tests-completed)
1787 tests-total
1788 (if (null (ert--stats-current-test stats))
1790 (format "%S"
1791 (ert-test-name (ert--stats-current-test stats))))))))
1793 (defun ert--make-xrefs-region (begin end)
1794 "Attach cross-references to function names between BEGIN and END.
1796 BEGIN and END specify a region in the current buffer."
1797 (save-excursion
1798 (save-restriction
1799 (narrow-to-region begin end)
1800 ;; Inhibit optimization in `debugger-make-xrefs' that would
1801 ;; sometimes insert unrelated backtrace info into our buffer.
1802 (let ((debugger-previous-backtrace nil))
1803 (debugger-make-xrefs)))))
1805 (defun ert--string-first-line (s)
1806 "Return the first line of S, or S if it contains no newlines.
1808 The return value does not include the line terminator."
1809 (substring s 0 (ert--string-position ?\n s)))
1811 (defun ert-face-for-test-result (expectedp)
1812 "Return a face that shows whether a test result was expected or unexpected.
1814 If EXPECTEDP is nil, returns the face for unexpected results; if
1815 non-nil, returns the face for expected results.."
1816 (if expectedp 'ert-test-result-expected 'ert-test-result-unexpected))
1818 (defun ert-face-for-stats (stats)
1819 "Return a face that represents STATS."
1820 (cond ((ert--stats-aborted-p stats) 'nil)
1821 ((cl-plusp (ert-stats-completed-unexpected stats))
1822 (ert-face-for-test-result nil))
1823 ((eql (ert-stats-completed-expected stats) (ert-stats-total stats))
1824 (ert-face-for-test-result t))
1825 (t 'nil)))
1827 (defun ert--print-test-for-ewoc (entry)
1828 "The ewoc print function for ewoc test entries. ENTRY is the entry to print."
1829 (let* ((test (ert--ewoc-entry-test entry))
1830 (stats ert--results-stats)
1831 (result (let ((pos (ert--stats-test-pos stats test)))
1832 (cl-assert pos)
1833 (aref (ert--stats-test-results stats) pos)))
1834 (hiddenp (ert--ewoc-entry-hidden-p entry))
1835 (expandedp (ert--ewoc-entry-expanded-p entry))
1836 (extended-printer-limits-p (ert--ewoc-entry-extended-printer-limits-p
1837 entry)))
1838 (cond (hiddenp)
1840 (let ((expectedp (ert-test-result-expected-p test result)))
1841 (insert-text-button (format "%c" (ert-char-for-test-result
1842 result expectedp))
1843 :type 'ert--results-expand-collapse-button
1844 'face (or (and font-lock-mode
1845 (ert-face-for-test-result
1846 expectedp))
1847 'button)))
1848 (insert " ")
1849 (ert-insert-test-name-button (ert-test-name test))
1850 (insert "\n")
1851 (when (and expandedp (not (eql result 'nil)))
1852 (when (ert-test-documentation test)
1853 (insert " "
1854 (propertize
1855 (ert--string-first-line (ert-test-documentation test))
1856 'font-lock-face 'font-lock-doc-face)
1857 "\n"))
1858 (cl-etypecase result
1859 (ert-test-passed
1860 (if (ert-test-result-expected-p test result)
1861 (insert " passed\n")
1862 (insert " passed unexpectedly\n"))
1863 (insert ""))
1864 (ert-test-result-with-condition
1865 (ert--insert-infos result)
1866 (let ((print-escape-newlines t)
1867 (print-level (if extended-printer-limits-p 12 6))
1868 (print-length (if extended-printer-limits-p 100 10)))
1869 (insert " ")
1870 (let ((begin (point)))
1871 (ert--pp-with-indentation-and-newline
1872 (ert-test-result-with-condition-condition result))
1873 (ert--make-xrefs-region begin (point)))))
1874 (ert-test-aborted-with-non-local-exit
1875 (insert " aborted\n"))
1876 (ert-test-quit
1877 (insert " quit\n")))
1878 (insert "\n")))))
1879 nil)
1881 (defun ert--results-font-lock-function (enabledp)
1882 "Redraw the ERT results buffer after font-lock-mode was switched on or off.
1884 ENABLEDP is true if font-lock-mode is switched on, false
1885 otherwise."
1886 (ert--results-update-ewoc-hf ert--results-ewoc ert--results-stats)
1887 (ewoc-refresh ert--results-ewoc)
1888 (font-lock-default-function enabledp))
1890 (defun ert--setup-results-buffer (stats listener buffer-name)
1891 "Set up a test results buffer.
1893 STATS is the stats object; LISTENER is the results listener;
1894 BUFFER-NAME, if non-nil, is the buffer name to use."
1895 (unless buffer-name (setq buffer-name "*ert*"))
1896 (let ((buffer (get-buffer-create buffer-name)))
1897 (with-current-buffer buffer
1898 (let ((inhibit-read-only t))
1899 (buffer-disable-undo)
1900 (erase-buffer)
1901 (ert-results-mode)
1902 ;; Erase buffer again in case switching out of the previous
1903 ;; mode inserted anything. (This happens e.g. when switching
1904 ;; from ert-results-mode to ert-results-mode when
1905 ;; font-lock-mode turns itself off in change-major-mode-hook.)
1906 (erase-buffer)
1907 (set (make-local-variable 'font-lock-function)
1908 'ert--results-font-lock-function)
1909 (let ((ewoc (ewoc-create 'ert--print-test-for-ewoc nil nil t)))
1910 (set (make-local-variable 'ert--results-ewoc) ewoc)
1911 (set (make-local-variable 'ert--results-stats) stats)
1912 (set (make-local-variable 'ert--results-progress-bar-string)
1913 (make-string (ert-stats-total stats)
1914 (ert-char-for-test-result nil t)))
1915 (set (make-local-variable 'ert--results-listener) listener)
1916 (cl-loop for test across (ert--stats-tests stats) do
1917 (ewoc-enter-last ewoc
1918 (make-ert--ewoc-entry :test test
1919 :hidden-p t)))
1920 (ert--results-update-ewoc-hf ert--results-ewoc ert--results-stats)
1921 (goto-char (1- (point-max)))
1922 buffer)))))
1925 (defvar ert--selector-history nil
1926 "List of recent test selectors read from terminal.")
1928 ;; Should OUTPUT-BUFFER-NAME and MESSAGE-FN really be arguments here?
1929 ;; They are needed only for our automated self-tests at the moment.
1930 ;; Or should there be some other mechanism?
1931 ;;;###autoload
1932 (defun ert-run-tests-interactively (selector
1933 &optional output-buffer-name message-fn)
1934 "Run the tests specified by SELECTOR and display the results in a buffer.
1936 SELECTOR works as described in `ert-select-tests'.
1937 OUTPUT-BUFFER-NAME and MESSAGE-FN should normally be nil; they
1938 are used for automated self-tests and specify which buffer to use
1939 and how to display message."
1940 (interactive
1941 (list (let ((default (if ert--selector-history
1942 ;; Can't use `first' here as this form is
1943 ;; not compiled, and `first' is not
1944 ;; defined without cl.
1945 (car ert--selector-history)
1946 "t")))
1947 (read-from-minibuffer (if (null default)
1948 "Run tests: "
1949 (format "Run tests (default %s): " default))
1950 nil nil t 'ert--selector-history
1951 default nil))
1952 nil))
1953 (unless message-fn (setq message-fn 'message))
1954 (let ((output-buffer-name output-buffer-name)
1955 buffer
1956 listener
1957 (message-fn message-fn))
1958 (setq listener
1959 (lambda (event-type &rest event-args)
1960 (cl-ecase event-type
1961 (run-started
1962 (cl-destructuring-bind (stats) event-args
1963 (setq buffer (ert--setup-results-buffer stats
1964 listener
1965 output-buffer-name))
1966 (pop-to-buffer buffer)))
1967 (run-ended
1968 (cl-destructuring-bind (stats abortedp) event-args
1969 (funcall message-fn
1970 "%sRan %s tests, %s results were as expected%s"
1971 (if (not abortedp)
1973 "Aborted: ")
1974 (ert-stats-total stats)
1975 (ert-stats-completed-expected stats)
1976 (let ((unexpected
1977 (ert-stats-completed-unexpected stats)))
1978 (if (zerop unexpected)
1980 (format ", %s unexpected" unexpected))))
1981 (ert--results-update-stats-display (with-current-buffer buffer
1982 ert--results-ewoc)
1983 stats)))
1984 (test-started
1985 (cl-destructuring-bind (stats test) event-args
1986 (with-current-buffer buffer
1987 (let* ((ewoc ert--results-ewoc)
1988 (pos (ert--stats-test-pos stats test))
1989 (node (ewoc-nth ewoc pos)))
1990 (cl-assert node)
1991 (setf (ert--ewoc-entry-test (ewoc-data node)) test)
1992 (aset ert--results-progress-bar-string pos
1993 (ert-char-for-test-result nil t))
1994 (ert--results-update-stats-display-maybe ewoc stats)
1995 (ewoc-invalidate ewoc node)))))
1996 (test-ended
1997 (cl-destructuring-bind (stats test result) event-args
1998 (with-current-buffer buffer
1999 (let* ((ewoc ert--results-ewoc)
2000 (pos (ert--stats-test-pos stats test))
2001 (node (ewoc-nth ewoc pos)))
2002 (when (ert--ewoc-entry-hidden-p (ewoc-data node))
2003 (setf (ert--ewoc-entry-hidden-p (ewoc-data node))
2004 (ert-test-result-expected-p test result)))
2005 (aset ert--results-progress-bar-string pos
2006 (ert-char-for-test-result result
2007 (ert-test-result-expected-p
2008 test result)))
2009 (ert--results-update-stats-display-maybe ewoc stats)
2010 (ewoc-invalidate ewoc node))))))))
2011 (ert-run-tests
2012 selector
2013 listener)))
2014 ;;;###autoload
2015 (defalias 'ert 'ert-run-tests-interactively)
2018 ;;; Simple view mode for auxiliary information like stack traces or
2019 ;;; messages. Mainly binds "q" for quit.
2021 (define-derived-mode ert-simple-view-mode special-mode "ERT-View"
2022 "Major mode for viewing auxiliary information in ERT.")
2024 ;;; Commands and button actions for the results buffer.
2026 (define-derived-mode ert-results-mode special-mode "ERT-Results"
2027 "Major mode for viewing results of ERT test runs.")
2029 (cl-loop for (key binding) in
2030 '( ;; Stuff that's not in the menu.
2031 ("\t" forward-button)
2032 ([backtab] backward-button)
2033 ("j" ert-results-jump-between-summary-and-result)
2034 ("L" ert-results-toggle-printer-limits-for-test-at-point)
2035 ("n" ert-results-next-test)
2036 ("p" ert-results-previous-test)
2037 ;; Stuff that is in the menu.
2038 ("R" ert-results-rerun-all-tests)
2039 ("r" ert-results-rerun-test-at-point)
2040 ("d" ert-results-rerun-test-at-point-debugging-errors)
2041 ("." ert-results-find-test-at-point-other-window)
2042 ("b" ert-results-pop-to-backtrace-for-test-at-point)
2043 ("m" ert-results-pop-to-messages-for-test-at-point)
2044 ("l" ert-results-pop-to-should-forms-for-test-at-point)
2045 ("h" ert-results-describe-test-at-point)
2046 ("D" ert-delete-test)
2047 ("T" ert-results-pop-to-timings)
2050 (define-key ert-results-mode-map key binding))
2052 (easy-menu-define ert-results-mode-menu ert-results-mode-map
2053 "Menu for `ert-results-mode'."
2054 '("ERT Results"
2055 ["Re-run all tests" ert-results-rerun-all-tests]
2056 "--"
2057 ["Re-run test" ert-results-rerun-test-at-point]
2058 ["Debug test" ert-results-rerun-test-at-point-debugging-errors]
2059 ["Show test definition" ert-results-find-test-at-point-other-window]
2060 "--"
2061 ["Show backtrace" ert-results-pop-to-backtrace-for-test-at-point]
2062 ["Show messages" ert-results-pop-to-messages-for-test-at-point]
2063 ["Show `should' forms" ert-results-pop-to-should-forms-for-test-at-point]
2064 ["Describe test" ert-results-describe-test-at-point]
2065 "--"
2066 ["Delete test" ert-delete-test]
2067 "--"
2068 ["Show execution time of each test" ert-results-pop-to-timings]
2071 (define-button-type 'ert--results-progress-bar-button
2072 'action #'ert--results-progress-bar-button-action
2073 'help-echo "mouse-2, RET: Reveal test result")
2075 (define-button-type 'ert--test-name-button
2076 'action #'ert--test-name-button-action
2077 'help-echo "mouse-2, RET: Find test definition")
2079 (define-button-type 'ert--results-expand-collapse-button
2080 'action #'ert--results-expand-collapse-button-action
2081 'help-echo "mouse-2, RET: Expand/collapse test result")
2083 (defun ert--results-test-node-or-null-at-point ()
2084 "If point is on a valid ewoc node, return it; return nil otherwise.
2086 To be used in the ERT results buffer."
2087 (let* ((ewoc ert--results-ewoc)
2088 (node (ewoc-locate ewoc)))
2089 ;; `ewoc-locate' will return an arbitrary node when point is on
2090 ;; header or footer, or when all nodes are invisible. So we need
2091 ;; to validate its return value here.
2093 ;; Update: I'm seeing nil being returned in some cases now,
2094 ;; perhaps this has been changed?
2095 (if (and node
2096 (>= (point) (ewoc-location node))
2097 (not (ert--ewoc-entry-hidden-p (ewoc-data node))))
2098 node
2099 nil)))
2101 (defun ert--results-test-node-at-point ()
2102 "If point is on a valid ewoc node, return it; signal an error otherwise.
2104 To be used in the ERT results buffer."
2105 (or (ert--results-test-node-or-null-at-point)
2106 (error "No test at point")))
2108 (defun ert-results-next-test ()
2109 "Move point to the next test.
2111 To be used in the ERT results buffer."
2112 (interactive)
2113 (ert--results-move (ewoc-locate ert--results-ewoc) 'ewoc-next
2114 "No tests below"))
2116 (defun ert-results-previous-test ()
2117 "Move point to the previous test.
2119 To be used in the ERT results buffer."
2120 (interactive)
2121 (ert--results-move (ewoc-locate ert--results-ewoc) 'ewoc-prev
2122 "No tests above"))
2124 (defun ert--results-move (node ewoc-fn error-message)
2125 "Move point from NODE to the previous or next node.
2127 EWOC-FN specifies the direction and should be either `ewoc-prev'
2128 or `ewoc-next'. If there are no more nodes in that direction, an
2129 error is signaled with the message ERROR-MESSAGE."
2130 (cl-loop
2131 (setq node (funcall ewoc-fn ert--results-ewoc node))
2132 (when (null node)
2133 (error "%s" error-message))
2134 (unless (ert--ewoc-entry-hidden-p (ewoc-data node))
2135 (goto-char (ewoc-location node))
2136 (cl-return))))
2138 (defun ert--results-expand-collapse-button-action (_button)
2139 "Expand or collapse the test node BUTTON belongs to."
2140 (let* ((ewoc ert--results-ewoc)
2141 (node (save-excursion
2142 (goto-char (ert--button-action-position))
2143 (ert--results-test-node-at-point)))
2144 (entry (ewoc-data node)))
2145 (setf (ert--ewoc-entry-expanded-p entry)
2146 (not (ert--ewoc-entry-expanded-p entry)))
2147 (ewoc-invalidate ewoc node)))
2149 (defun ert-results-find-test-at-point-other-window ()
2150 "Find the definition of the test at point in another window.
2152 To be used in the ERT results buffer."
2153 (interactive)
2154 (let ((name (ert-test-at-point)))
2155 (unless name
2156 (error "No test at point"))
2157 (ert-find-test-other-window name)))
2159 (defun ert--test-name-button-action (button)
2160 "Find the definition of the test BUTTON belongs to, in another window."
2161 (let ((name (button-get button 'ert-test-name)))
2162 (ert-find-test-other-window name)))
2164 (defun ert--ewoc-position (ewoc node)
2165 ;; checkdoc-order: nil
2166 "Return the position of NODE in EWOC, or nil if NODE is not in EWOC."
2167 (cl-loop for i from 0
2168 for node-here = (ewoc-nth ewoc 0) then (ewoc-next ewoc node-here)
2169 do (when (eql node node-here)
2170 (cl-return i))
2171 finally (cl-return nil)))
2173 (defun ert-results-jump-between-summary-and-result ()
2174 "Jump back and forth between the test run summary and individual test results.
2176 From an ewoc node, jumps to the character that represents the
2177 same test in the progress bar, and vice versa.
2179 To be used in the ERT results buffer."
2180 ;; Maybe this command isn't actually needed much, but if it is, it
2181 ;; seems like an indication that the UI design is not optimal. If
2182 ;; jumping back and forth between a summary at the top of the buffer
2183 ;; and the error log in the remainder of the buffer is useful, then
2184 ;; the summary apparently needs to be easily accessible from the
2185 ;; error log, and perhaps it would be better to have it in a
2186 ;; separate buffer to keep it visible.
2187 (interactive)
2188 (let ((ewoc ert--results-ewoc)
2189 (progress-bar-begin ert--results-progress-bar-button-begin))
2190 (cond ((ert--results-test-node-or-null-at-point)
2191 (let* ((node (ert--results-test-node-at-point))
2192 (pos (ert--ewoc-position ewoc node)))
2193 (goto-char (+ progress-bar-begin pos))))
2194 ((and (<= progress-bar-begin (point))
2195 (< (point) (button-end (button-at progress-bar-begin))))
2196 (let* ((node (ewoc-nth ewoc (- (point) progress-bar-begin)))
2197 (entry (ewoc-data node)))
2198 (when (ert--ewoc-entry-hidden-p entry)
2199 (setf (ert--ewoc-entry-hidden-p entry) nil)
2200 (ewoc-invalidate ewoc node))
2201 (ewoc-goto-node ewoc node)))
2203 (goto-char progress-bar-begin)))))
2205 (defun ert-test-at-point ()
2206 "Return the name of the test at point as a symbol, or nil if none."
2207 (or (and (eql major-mode 'ert-results-mode)
2208 (let ((test (ert--results-test-at-point-no-redefinition)))
2209 (and test (ert-test-name test))))
2210 (let* ((thing (thing-at-point 'symbol))
2211 (sym (intern-soft thing)))
2212 (and (ert-test-boundp sym)
2213 sym))))
2215 (defun ert--results-test-at-point-no-redefinition ()
2216 "Return the test at point, or nil.
2218 To be used in the ERT results buffer."
2219 (cl-assert (eql major-mode 'ert-results-mode))
2220 (if (ert--results-test-node-or-null-at-point)
2221 (let* ((node (ert--results-test-node-at-point))
2222 (test (ert--ewoc-entry-test (ewoc-data node))))
2223 test)
2224 (let ((progress-bar-begin ert--results-progress-bar-button-begin))
2225 (when (and (<= progress-bar-begin (point))
2226 (< (point) (button-end (button-at progress-bar-begin))))
2227 (let* ((test-index (- (point) progress-bar-begin))
2228 (test (aref (ert--stats-tests ert--results-stats)
2229 test-index)))
2230 test)))))
2232 (defun ert--results-test-at-point-allow-redefinition ()
2233 "Look up the test at point, and check whether it has been redefined.
2235 To be used in the ERT results buffer.
2237 Returns a list of two elements: the test (or nil) and a symbol
2238 specifying whether the test has been redefined.
2240 If a new test has been defined with the same name as the test at
2241 point, replaces the test at point with the new test, and returns
2242 the new test and the symbol `redefined'.
2244 If the test has been deleted, returns the old test and the symbol
2245 `deleted'.
2247 If the test is still current, returns the test and the symbol nil.
2249 If there is no test at point, returns a list with two nils."
2250 (let ((test (ert--results-test-at-point-no-redefinition)))
2251 (cond ((null test)
2252 `(nil nil))
2253 ((null (ert-test-name test))
2254 `(,test nil))
2256 (let* ((name (ert-test-name test))
2257 (new-test (and (ert-test-boundp name)
2258 (ert-get-test name))))
2259 (cond ((eql test new-test)
2260 `(,test nil))
2261 ((null new-test)
2262 `(,test deleted))
2264 (ert--results-update-after-test-redefinition
2265 (ert--stats-test-pos ert--results-stats test)
2266 new-test)
2267 `(,new-test redefined))))))))
2269 (defun ert--results-update-after-test-redefinition (pos new-test)
2270 "Update results buffer after the test at pos POS has been redefined.
2272 Also updates the stats object. NEW-TEST is the new test
2273 definition."
2274 (let* ((stats ert--results-stats)
2275 (ewoc ert--results-ewoc)
2276 (node (ewoc-nth ewoc pos))
2277 (entry (ewoc-data node)))
2278 (ert--stats-set-test-and-result stats pos new-test nil)
2279 (setf (ert--ewoc-entry-test entry) new-test
2280 (aref ert--results-progress-bar-string pos) (ert-char-for-test-result
2281 nil t))
2282 (ewoc-invalidate ewoc node))
2283 nil)
2285 (defun ert--button-action-position ()
2286 "The buffer position where the last button action was triggered."
2287 (cond ((integerp last-command-event)
2288 (point))
2289 ((eventp last-command-event)
2290 (posn-point (event-start last-command-event)))
2291 (t (cl-assert nil))))
2293 (defun ert--results-progress-bar-button-action (_button)
2294 "Jump to details for the test represented by the character clicked in BUTTON."
2295 (goto-char (ert--button-action-position))
2296 (ert-results-jump-between-summary-and-result))
2298 (defun ert-results-rerun-all-tests ()
2299 "Re-run all tests, using the same selector.
2301 To be used in the ERT results buffer."
2302 (interactive)
2303 (cl-assert (eql major-mode 'ert-results-mode))
2304 (let ((selector (ert--stats-selector ert--results-stats)))
2305 (ert-run-tests-interactively selector (buffer-name))))
2307 (defun ert-results-rerun-test-at-point ()
2308 "Re-run the test at point.
2310 To be used in the ERT results buffer."
2311 (interactive)
2312 (cl-destructuring-bind (test redefinition-state)
2313 (ert--results-test-at-point-allow-redefinition)
2314 (when (null test)
2315 (error "No test at point"))
2316 (let* ((stats ert--results-stats)
2317 (progress-message (format "Running %stest %S"
2318 (cl-ecase redefinition-state
2319 ((nil) "")
2320 (redefined "new definition of ")
2321 (deleted "deleted "))
2322 (ert-test-name test))))
2323 ;; Need to save and restore point manually here: When point is on
2324 ;; the first visible ewoc entry while the header is updated, point
2325 ;; moves to the top of the buffer. This is undesirable, and a
2326 ;; simple `save-excursion' doesn't prevent it.
2327 (let ((point (point)))
2328 (unwind-protect
2329 (unwind-protect
2330 (progn
2331 (message "%s..." progress-message)
2332 (ert-run-or-rerun-test stats test
2333 ert--results-listener))
2334 (ert--results-update-stats-display ert--results-ewoc stats)
2335 (message "%s...%s"
2336 progress-message
2337 (let ((result (ert-test-most-recent-result test)))
2338 (ert-string-for-test-result
2339 result (ert-test-result-expected-p test result)))))
2340 (goto-char point))))))
2342 (defun ert-results-rerun-test-at-point-debugging-errors ()
2343 "Re-run the test at point with `ert-debug-on-error' bound to t.
2345 To be used in the ERT results buffer."
2346 (interactive)
2347 (let ((ert-debug-on-error t))
2348 (ert-results-rerun-test-at-point)))
2350 (defun ert-results-pop-to-backtrace-for-test-at-point ()
2351 "Display the backtrace for the test at point.
2353 To be used in the ERT results buffer."
2354 (interactive)
2355 (let* ((test (ert--results-test-at-point-no-redefinition))
2356 (stats ert--results-stats)
2357 (pos (ert--stats-test-pos stats test))
2358 (result (aref (ert--stats-test-results stats) pos)))
2359 (cl-etypecase result
2360 (ert-test-passed (error "Test passed, no backtrace available"))
2361 (ert-test-result-with-condition
2362 (let ((backtrace (ert-test-result-with-condition-backtrace result))
2363 (buffer (get-buffer-create "*ERT Backtrace*")))
2364 (pop-to-buffer buffer)
2365 (let ((inhibit-read-only t))
2366 (buffer-disable-undo)
2367 (erase-buffer)
2368 (ert-simple-view-mode)
2369 ;; Use unibyte because `debugger-setup-buffer' also does so.
2370 (set-buffer-multibyte nil)
2371 (setq truncate-lines t)
2372 (ert--print-backtrace backtrace)
2373 (debugger-make-xrefs)
2374 (goto-char (point-min))
2375 (insert "Backtrace for test `")
2376 (ert-insert-test-name-button (ert-test-name test))
2377 (insert "':\n")))))))
2379 (defun ert-results-pop-to-messages-for-test-at-point ()
2380 "Display the part of the *Messages* buffer generated during the test at point.
2382 To be used in the ERT results buffer."
2383 (interactive)
2384 (let* ((test (ert--results-test-at-point-no-redefinition))
2385 (stats ert--results-stats)
2386 (pos (ert--stats-test-pos stats test))
2387 (result (aref (ert--stats-test-results stats) pos)))
2388 (let ((buffer (get-buffer-create "*ERT Messages*")))
2389 (pop-to-buffer buffer)
2390 (let ((inhibit-read-only t))
2391 (buffer-disable-undo)
2392 (erase-buffer)
2393 (ert-simple-view-mode)
2394 (insert (ert-test-result-messages result))
2395 (goto-char (point-min))
2396 (insert "Messages for test `")
2397 (ert-insert-test-name-button (ert-test-name test))
2398 (insert "':\n")))))
2400 (defun ert-results-pop-to-should-forms-for-test-at-point ()
2401 "Display the list of `should' forms executed during the test at point.
2403 To be used in the ERT results buffer."
2404 (interactive)
2405 (let* ((test (ert--results-test-at-point-no-redefinition))
2406 (stats ert--results-stats)
2407 (pos (ert--stats-test-pos stats test))
2408 (result (aref (ert--stats-test-results stats) pos)))
2409 (let ((buffer (get-buffer-create "*ERT list of should forms*")))
2410 (pop-to-buffer buffer)
2411 (let ((inhibit-read-only t))
2412 (buffer-disable-undo)
2413 (erase-buffer)
2414 (ert-simple-view-mode)
2415 (if (null (ert-test-result-should-forms result))
2416 (insert "\n(No should forms during this test.)\n")
2417 (cl-loop for form-description
2418 in (ert-test-result-should-forms result)
2419 for i from 1 do
2420 (insert "\n")
2421 (insert (format "%s: " i))
2422 (let ((begin (point)))
2423 (ert--pp-with-indentation-and-newline form-description)
2424 (ert--make-xrefs-region begin (point)))))
2425 (goto-char (point-min))
2426 (insert "`should' forms executed during test `")
2427 (ert-insert-test-name-button (ert-test-name test))
2428 (insert "':\n")
2429 (insert "\n")
2430 (insert (concat "(Values are shallow copies and may have "
2431 "looked different during the test if they\n"
2432 "have been modified destructively.)\n"))
2433 (forward-line 1)))))
2435 (defun ert-results-toggle-printer-limits-for-test-at-point ()
2436 "Toggle how much of the condition to print for the test at point.
2438 To be used in the ERT results buffer."
2439 (interactive)
2440 (let* ((ewoc ert--results-ewoc)
2441 (node (ert--results-test-node-at-point))
2442 (entry (ewoc-data node)))
2443 (setf (ert--ewoc-entry-extended-printer-limits-p entry)
2444 (not (ert--ewoc-entry-extended-printer-limits-p entry)))
2445 (ewoc-invalidate ewoc node)))
2447 (defun ert-results-pop-to-timings ()
2448 "Display test timings for the last run.
2450 To be used in the ERT results buffer."
2451 (interactive)
2452 (let* ((stats ert--results-stats)
2453 (buffer (get-buffer-create "*ERT timings*"))
2454 (data (cl-loop for test across (ert--stats-tests stats)
2455 for start-time across (ert--stats-test-start-times
2456 stats)
2457 for end-time across (ert--stats-test-end-times stats)
2458 collect (list test
2459 (float-time (subtract-time
2460 end-time start-time))))))
2461 (setq data (sort data (lambda (a b)
2462 (> (cl-second a) (cl-second b)))))
2463 (pop-to-buffer buffer)
2464 (let ((inhibit-read-only t))
2465 (buffer-disable-undo)
2466 (erase-buffer)
2467 (ert-simple-view-mode)
2468 (if (null data)
2469 (insert "(No data)\n")
2470 (insert (format "%-3s %8s %8s\n" "" "time" "cumul"))
2471 (cl-loop for (test time) in data
2472 for cumul-time = time then (+ cumul-time time)
2473 for i from 1 do
2474 (progn
2475 (insert (format "%3s: %8.3f %8.3f " i time cumul-time))
2476 (ert-insert-test-name-button (ert-test-name test))
2477 (insert "\n"))))
2478 (goto-char (point-min))
2479 (insert "Tests by run time (seconds):\n\n")
2480 (forward-line 1))))
2482 ;;;###autoload
2483 (defun ert-describe-test (test-or-test-name)
2484 "Display the documentation for TEST-OR-TEST-NAME (a symbol or ert-test)."
2485 (interactive (list (ert-read-test-name-at-point "Describe test")))
2486 (when (< emacs-major-version 24)
2487 (error "Requires Emacs 24"))
2488 (let (test-name
2489 test-definition)
2490 (cl-etypecase test-or-test-name
2491 (symbol (setq test-name test-or-test-name
2492 test-definition (ert-get-test test-or-test-name)))
2493 (ert-test (setq test-name (ert-test-name test-or-test-name)
2494 test-definition test-or-test-name)))
2495 (help-setup-xref (list #'ert-describe-test test-or-test-name)
2496 (called-interactively-p 'interactive))
2497 (save-excursion
2498 (with-help-window (help-buffer)
2499 (with-current-buffer (help-buffer)
2500 (insert (if test-name (format "%S" test-name) "<anonymous test>"))
2501 (insert " is a test")
2502 (let ((file-name (and test-name
2503 (symbol-file test-name 'ert-deftest))))
2504 (when file-name
2505 (insert " defined in `" (file-name-nondirectory file-name) "'")
2506 (save-excursion
2507 (re-search-backward "`\\([^`']+\\)'" nil t)
2508 (help-xref-button 1 'help-function-def test-name file-name)))
2509 (insert ".")
2510 (fill-region-as-paragraph (point-min) (point))
2511 (insert "\n\n")
2512 (unless (and (ert-test-boundp test-name)
2513 (eql (ert-get-test test-name) test-definition))
2514 (let ((begin (point)))
2515 (insert "Note: This test has been redefined or deleted, "
2516 "this documentation refers to an old definition.")
2517 (fill-region-as-paragraph begin (point)))
2518 (insert "\n\n"))
2519 (insert (or (ert-test-documentation test-definition)
2520 "It is not documented.")
2521 "\n")))))))
2523 (defun ert-results-describe-test-at-point ()
2524 "Display the documentation of the test at point.
2526 To be used in the ERT results buffer."
2527 (interactive)
2528 (ert-describe-test (ert--results-test-at-point-no-redefinition)))
2531 ;;; Actions on load/unload.
2533 (add-to-list 'find-function-regexp-alist '(ert-deftest . ert--find-test-regexp))
2534 (add-to-list 'minor-mode-alist '(ert--current-run-stats
2535 (:eval
2536 (ert--tests-running-mode-line-indicator))))
2537 (add-to-list 'emacs-lisp-mode-hook 'ert--activate-font-lock-keywords)
2539 (defun ert--unload-function ()
2540 "Unload function to undo the side-effects of loading ert.el."
2541 (ert--remove-from-list 'find-function-regexp-alist 'ert-deftest :key #'car)
2542 (ert--remove-from-list 'minor-mode-alist 'ert--current-run-stats :key #'car)
2543 (ert--remove-from-list 'emacs-lisp-mode-hook
2544 'ert--activate-font-lock-keywords)
2545 nil)
2547 (defvar ert-unload-hook '())
2548 (add-hook 'ert-unload-hook 'ert--unload-function)
2551 (provide 'ert)
2553 ;;; ert.el ends here