Update copyright year to 2014 by running admin/update-copyright.
[emacs.git] / lisp / emacs-lisp / ert.el
blob4b118609d1eff556a10c915df2fab85da0296c89
1 ;;; ert.el --- Emacs Lisp Regression Testing -*- lexical-binding: t -*-
3 ;; Copyright (C) 2007-2008, 2010-2014 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', `should-error' and
38 ;; `skip-unless' are available. `should' is similar to cl's `assert',
39 ;; but signals a different error when its condition is violated that
40 ;; is caught and processed by ERT. In addition, it analyzes its
41 ;; argument form and records information that helps debugging
42 ;; (`assert' tries to do something similar when its second argument
43 ;; SHOW-ARGS is true, but `should' is more sophisticated). For
44 ;; information on `should-not' and `should-error', see their
45 ;; docstrings. `skip-unless' skips the test immediately without
46 ;; processing further, this is useful for checking the test
47 ;; environment (like availability of features, external binaries, etc).
49 ;; See ERT's info manual as well as the docstrings for more details.
50 ;; To compile the manual, run `makeinfo ert.texinfo' in the ERT
51 ;; directory, then C-u M-x info ert.info in Emacs to view it.
53 ;; To see some examples of tests written in ERT, see its self-tests in
54 ;; ert-tests.el. Some of these are tricky due to the bootstrapping
55 ;; problem of writing tests for a testing tool, others test simple
56 ;; functions and are straightforward.
58 ;;; Code:
60 (require 'cl-lib)
61 (require 'button)
62 (require 'debug)
63 (require 'easymenu)
64 (require 'ewoc)
65 (require 'find-func)
66 (require 'help)
69 ;;; UI customization options.
71 (defgroup ert ()
72 "ERT, the Emacs Lisp regression testing tool."
73 :prefix "ert-"
74 :group 'lisp)
76 (defface ert-test-result-expected '((((class color) (background light))
77 :background "green1")
78 (((class color) (background dark))
79 :background "green3"))
80 "Face used for expected results in the ERT results buffer."
81 :group 'ert)
83 (defface ert-test-result-unexpected '((((class color) (background light))
84 :background "red1")
85 (((class color) (background dark))
86 :background "red3"))
87 "Face used for unexpected results in the ERT results buffer."
88 :group 'ert)
91 ;;; Copies/reimplementations of cl functions.
93 (defun ert-equal-including-properties (a b)
94 "Return t if A and B have similar structure and contents.
96 This is like `equal-including-properties' except that it compares
97 the property values of text properties structurally (by
98 recursing) rather than with `eq'. Perhaps this is what
99 `equal-including-properties' should do in the first place; see
100 Emacs bug 6581 at URL `http://debbugs.gnu.org/cgi/bugreport.cgi?bug=6581'."
101 ;; This implementation is inefficient. Rather than making it
102 ;; efficient, let's hope bug 6581 gets fixed so that we can delete
103 ;; it altogether.
104 (not (ert--explain-equal-including-properties a b)))
107 ;;; Defining and locating tests.
109 ;; The data structure that represents a test case.
110 (cl-defstruct ert-test
111 (name nil)
112 (documentation nil)
113 (body (cl-assert nil))
114 (most-recent-result nil)
115 (expected-result-type ':passed)
116 (tags '()))
118 (defun ert-test-boundp (symbol)
119 "Return non-nil if SYMBOL names a test."
120 (and (get symbol 'ert--test) t))
122 (defun ert-get-test (symbol)
123 "If SYMBOL names a test, return that. Signal an error otherwise."
124 (unless (ert-test-boundp symbol) (error "No test named `%S'" symbol))
125 (get symbol 'ert--test))
127 (defun ert-set-test (symbol definition)
128 "Make SYMBOL name the test DEFINITION, and return DEFINITION."
129 (when (eq symbol 'nil)
130 ;; We disallow nil since `ert-test-at-point' and related functions
131 ;; want to return a test name, but also need an out-of-band value
132 ;; on failure. Nil is the most natural out-of-band value; using 0
133 ;; or "" or signaling an error would be too awkward.
135 ;; Note that nil is still a valid value for the `name' slot in
136 ;; ert-test objects. It designates an anonymous test.
137 (error "Attempt to define a test named nil"))
138 (put symbol 'ert--test definition)
139 definition)
141 (defun ert-make-test-unbound (symbol)
142 "Make SYMBOL name no test. Return SYMBOL."
143 (cl-remprop symbol 'ert--test)
144 symbol)
146 (defun ert--parse-keys-and-body (keys-and-body)
147 "Split KEYS-AND-BODY into keyword-and-value pairs and the remaining body.
149 KEYS-AND-BODY should have the form of a property list, with the
150 exception that only keywords are permitted as keys and that the
151 tail -- the body -- is a list of forms that does not start with a
152 keyword.
154 Returns a two-element list containing the keys-and-values plist
155 and the body."
156 (let ((extracted-key-accu '())
157 (remaining keys-and-body))
158 (while (keywordp (car-safe remaining))
159 (let ((keyword (pop remaining)))
160 (unless (consp remaining)
161 (error "Value expected after keyword %S in %S"
162 keyword keys-and-body))
163 (when (assoc keyword extracted-key-accu)
164 (warn "Keyword %S appears more than once in %S" keyword
165 keys-and-body))
166 (push (cons keyword (pop remaining)) extracted-key-accu)))
167 (setq extracted-key-accu (nreverse extracted-key-accu))
168 (list (cl-loop for (key . value) in extracted-key-accu
169 collect key
170 collect value)
171 remaining)))
173 ;;;###autoload
174 (cl-defmacro ert-deftest (name () &body docstring-keys-and-body)
175 "Define NAME (a symbol) as a test.
177 BODY is evaluated as a `progn' when the test is run. It should
178 signal a condition on failure or just return if the test passes.
180 `should', `should-not', `should-error' and `skip-unless' are
181 useful for assertions in BODY.
183 Use `ert' to run tests interactively.
185 Tests that are expected to fail can be marked as such
186 using :expected-result. See `ert-test-result-type-p' for a
187 description of valid values for RESULT-TYPE.
189 \(fn NAME () [DOCSTRING] [:expected-result RESULT-TYPE] \
190 \[:tags '(TAG...)] BODY...)"
191 (declare (debug (&define :name test
192 name sexp [&optional stringp]
193 [&rest keywordp sexp] def-body))
194 (doc-string 3)
195 (indent 2))
196 (let ((documentation nil)
197 (documentation-supplied-p nil))
198 (when (stringp (car docstring-keys-and-body))
199 (setq documentation (pop docstring-keys-and-body)
200 documentation-supplied-p t))
201 (cl-destructuring-bind
202 ((&key (expected-result nil expected-result-supplied-p)
203 (tags nil tags-supplied-p))
204 body)
205 (ert--parse-keys-and-body docstring-keys-and-body)
206 `(cl-macrolet ((skip-unless (form) `(ert--skip-unless ,form)))
207 (ert-set-test ',name
208 (make-ert-test
209 :name ',name
210 ,@(when documentation-supplied-p
211 `(:documentation ,documentation))
212 ,@(when expected-result-supplied-p
213 `(:expected-result-type ,expected-result))
214 ,@(when tags-supplied-p
215 `(:tags ,tags))
216 :body (lambda () ,@body)))
217 ;; This hack allows `symbol-file' to associate `ert-deftest'
218 ;; forms with files, and therefore enables `find-function' to
219 ;; work with tests. However, it leads to warnings in
220 ;; `unload-feature', which doesn't know how to undefine tests
221 ;; and has no mechanism for extension.
222 (push '(ert-deftest . ,name) current-load-list)
223 ',name))))
225 ;; We use these `put' forms in addition to the (declare (indent)) in
226 ;; the defmacro form since the `declare' alone does not lead to
227 ;; correct indentation before the .el/.elc file is loaded.
228 ;; Autoloading these `put' forms solves this.
229 ;;;###autoload
230 (progn
231 ;; TODO(ohler): Figure out what these mean and make sure they are correct.
232 (put 'ert-deftest 'lisp-indent-function 2)
233 (put 'ert-info 'lisp-indent-function 1))
235 (defvar ert--find-test-regexp
236 (concat "^\\s-*(ert-deftest"
237 find-function-space-re
238 "%s\\(\\s-\\|$\\)")
239 "The regexp the `find-function' mechanisms use for finding test definitions.")
242 (define-error 'ert-test-failed "Test failed")
243 (define-error 'ert-test-skipped "Test skipped")
245 (defun ert-pass ()
246 "Terminate the current test and mark it passed. Does not return."
247 (throw 'ert--pass nil))
249 (defun ert-fail (data)
250 "Terminate the current test and mark it failed. Does not return.
251 DATA is displayed to the user and should state the reason of the failure."
252 (signal 'ert-test-failed (list data)))
254 (defun ert-skip (data)
255 "Terminate the current test and mark it skipped. Does not return.
256 DATA is displayed to the user and should state the reason for skipping."
257 (signal 'ert-test-skipped (list data)))
260 ;;; The `should' macros.
262 (defvar ert--should-execution-observer nil)
264 (defun ert--signal-should-execution (form-description)
265 "Tell the current `should' form observer (if any) about FORM-DESCRIPTION."
266 (when ert--should-execution-observer
267 (funcall ert--should-execution-observer form-description)))
269 (defun ert--special-operator-p (thing)
270 "Return non-nil if THING is a symbol naming a special operator."
271 (and (symbolp thing)
272 (let ((definition (indirect-function thing t)))
273 (and (subrp definition)
274 (eql (cdr (subr-arity definition)) 'unevalled)))))
276 (defun ert--expand-should-1 (whole form inner-expander)
277 "Helper function for the `should' macro and its variants."
278 (let ((form
279 (macroexpand form (cond
280 ((boundp 'macroexpand-all-environment)
281 macroexpand-all-environment)
282 ((boundp 'cl-macro-environment)
283 cl-macro-environment)))))
284 (cond
285 ((or (atom form) (ert--special-operator-p (car form)))
286 (let ((value (cl-gensym "value-")))
287 `(let ((,value (cl-gensym "ert-form-evaluation-aborted-")))
288 ,(funcall inner-expander
289 `(setq ,value ,form)
290 `(list ',whole :form ',form :value ,value)
291 value)
292 ,value)))
294 (let ((fn-name (car form))
295 (arg-forms (cdr form)))
296 (cl-assert (or (symbolp fn-name)
297 (and (consp fn-name)
298 (eql (car fn-name) 'lambda)
299 (listp (cdr fn-name)))))
300 (let ((fn (cl-gensym "fn-"))
301 (args (cl-gensym "args-"))
302 (value (cl-gensym "value-"))
303 (default-value (cl-gensym "ert-form-evaluation-aborted-")))
304 `(let ((,fn (function ,fn-name))
305 (,args (list ,@arg-forms)))
306 (let ((,value ',default-value))
307 ,(funcall inner-expander
308 `(setq ,value (apply ,fn ,args))
309 `(nconc (list ',whole)
310 (list :form `(,,fn ,@,args))
311 (unless (eql ,value ',default-value)
312 (list :value ,value))
313 (let ((-explainer-
314 (and (symbolp ',fn-name)
315 (get ',fn-name 'ert-explainer))))
316 (when -explainer-
317 (list :explanation
318 (apply -explainer- ,args)))))
319 value)
320 ,value))))))))
322 (defun ert--expand-should (whole form inner-expander)
323 "Helper function for the `should' macro and its variants.
325 Analyzes FORM and returns an expression that has the same
326 semantics under evaluation but records additional debugging
327 information.
329 INNER-EXPANDER should be a function and is called with two
330 arguments: INNER-FORM and FORM-DESCRIPTION-FORM, where INNER-FORM
331 is an expression equivalent to FORM, and FORM-DESCRIPTION-FORM is
332 an expression that returns a description of FORM. INNER-EXPANDER
333 should return code that calls INNER-FORM and performs the checks
334 and error signaling specific to the particular variant of
335 `should'. The code that INNER-EXPANDER returns must not call
336 FORM-DESCRIPTION-FORM before it has called INNER-FORM."
337 (ert--expand-should-1
338 whole form
339 (lambda (inner-form form-description-form value-var)
340 (let ((form-description (cl-gensym "form-description-")))
341 `(let (,form-description)
342 ,(funcall inner-expander
343 `(unwind-protect
344 ,inner-form
345 (setq ,form-description ,form-description-form)
346 (ert--signal-should-execution ,form-description))
347 `,form-description
348 value-var))))))
350 (cl-defmacro should (form)
351 "Evaluate FORM. If it returns nil, abort the current test as failed.
353 Returns the value of FORM."
354 (declare (debug t))
355 (ert--expand-should `(should ,form) form
356 (lambda (inner-form form-description-form _value-var)
357 `(unless ,inner-form
358 (ert-fail ,form-description-form)))))
360 (cl-defmacro should-not (form)
361 "Evaluate FORM. If it returns non-nil, abort the current test as failed.
363 Returns nil."
364 (declare (debug t))
365 (ert--expand-should `(should-not ,form) form
366 (lambda (inner-form form-description-form _value-var)
367 `(unless (not ,inner-form)
368 (ert-fail ,form-description-form)))))
370 (defun ert--should-error-handle-error (form-description-fn
371 condition type exclude-subtypes)
372 "Helper function for `should-error'.
374 Determines whether CONDITION matches TYPE and EXCLUDE-SUBTYPES,
375 and aborts the current test as failed if it doesn't."
376 (let ((signaled-conditions (get (car condition) 'error-conditions))
377 (handled-conditions (cl-etypecase type
378 (list type)
379 (symbol (list type)))))
380 (cl-assert signaled-conditions)
381 (unless (cl-intersection signaled-conditions handled-conditions)
382 (ert-fail (append
383 (funcall form-description-fn)
384 (list
385 :condition condition
386 :fail-reason (concat "the error signaled did not"
387 " have the expected type")))))
388 (when exclude-subtypes
389 (unless (member (car condition) handled-conditions)
390 (ert-fail (append
391 (funcall form-description-fn)
392 (list
393 :condition condition
394 :fail-reason (concat "the error signaled was a subtype"
395 " of the expected type"))))))))
397 ;; FIXME: The expansion will evaluate the keyword args (if any) in
398 ;; nonstandard order.
399 (cl-defmacro should-error (form &rest keys &key type exclude-subtypes)
400 "Evaluate FORM and check that it signals an error.
402 The error signaled needs to match TYPE. TYPE should be a list
403 of condition names. (It can also be a non-nil symbol, which is
404 equivalent to a singleton list containing that symbol.) If
405 EXCLUDE-SUBTYPES is nil, the error matches TYPE if one of its
406 condition names is an element of TYPE. If EXCLUDE-SUBTYPES is
407 non-nil, the error matches TYPE if it is an element of TYPE.
409 If the error matches, returns (ERROR-SYMBOL . DATA) from the
410 error. If not, or if no error was signaled, abort the test as
411 failed."
412 (declare (debug t))
413 (unless type (setq type ''error))
414 (ert--expand-should
415 `(should-error ,form ,@keys)
416 form
417 (lambda (inner-form form-description-form value-var)
418 (let ((errorp (cl-gensym "errorp"))
419 (form-description-fn (cl-gensym "form-description-fn-")))
420 `(let ((,errorp nil)
421 (,form-description-fn (lambda () ,form-description-form)))
422 (condition-case -condition-
423 ,inner-form
424 ;; We can't use ,type here because we want to evaluate it.
425 (error
426 (setq ,errorp t)
427 (ert--should-error-handle-error ,form-description-fn
428 -condition-
429 ,type ,exclude-subtypes)
430 (setq ,value-var -condition-)))
431 (unless ,errorp
432 (ert-fail (append
433 (funcall ,form-description-fn)
434 (list
435 :fail-reason "did not signal an error")))))))))
437 (cl-defmacro ert--skip-unless (form)
438 "Evaluate FORM. If it returns nil, skip the current test.
439 Errors during evaluation are caught and handled like nil."
440 (declare (debug t))
441 (ert--expand-should `(skip-unless ,form) form
442 (lambda (inner-form form-description-form _value-var)
443 `(unless (ignore-errors ,inner-form)
444 (ert-skip ,form-description-form)))))
447 ;;; Explanation of `should' failures.
449 ;; TODO(ohler): Rework explanations so that they are displayed in a
450 ;; similar way to `ert-info' messages; in particular, allow text
451 ;; buttons in explanations that give more detail or open an ediff
452 ;; buffer. Perhaps explanations should be reported through `ert-info'
453 ;; rather than as part of the condition.
455 (defun ert--proper-list-p (x)
456 "Return non-nil if X is a proper list, nil otherwise."
457 (cl-loop
458 for firstp = t then nil
459 for fast = x then (cddr fast)
460 for slow = x then (cdr slow) do
461 (when (null fast) (cl-return t))
462 (when (not (consp fast)) (cl-return nil))
463 (when (null (cdr fast)) (cl-return t))
464 (when (not (consp (cdr fast))) (cl-return nil))
465 (when (and (not firstp) (eq fast slow)) (cl-return nil))))
467 (defun ert--explain-format-atom (x)
468 "Format the atom X for `ert--explain-equal'."
469 (cl-typecase x
470 (character (list x (format "#x%x" x) (format "?%c" x)))
471 (fixnum (list x (format "#x%x" x)))
472 (t x)))
474 (defun ert--explain-equal-rec (a b)
475 "Return a programmer-readable explanation of why A and B are not `equal'.
476 Returns nil if they are."
477 (if (not (equal (type-of a) (type-of b)))
478 `(different-types ,a ,b)
479 (cl-etypecase a
480 (cons
481 (let ((a-proper-p (ert--proper-list-p a))
482 (b-proper-p (ert--proper-list-p b)))
483 (if (not (eql (not a-proper-p) (not b-proper-p)))
484 `(one-list-proper-one-improper ,a ,b)
485 (if a-proper-p
486 (if (not (equal (length a) (length b)))
487 `(proper-lists-of-different-length ,(length a) ,(length b)
488 ,a ,b
489 first-mismatch-at
490 ,(cl-mismatch a b :test 'equal))
491 (cl-loop for i from 0
492 for ai in a
493 for bi in b
494 for xi = (ert--explain-equal-rec ai bi)
495 do (when xi (cl-return `(list-elt ,i ,xi)))
496 finally (cl-assert (equal a b) t)))
497 (let ((car-x (ert--explain-equal-rec (car a) (car b))))
498 (if car-x
499 `(car ,car-x)
500 (let ((cdr-x (ert--explain-equal-rec (cdr a) (cdr b))))
501 (if cdr-x
502 `(cdr ,cdr-x)
503 (cl-assert (equal a b) t)
504 nil))))))))
505 (array (if (not (equal (length a) (length b)))
506 `(arrays-of-different-length ,(length a) ,(length b)
507 ,a ,b
508 ,@(unless (char-table-p a)
509 `(first-mismatch-at
510 ,(cl-mismatch a b :test 'equal))))
511 (cl-loop for i from 0
512 for ai across a
513 for bi across b
514 for xi = (ert--explain-equal-rec ai bi)
515 do (when xi (cl-return `(array-elt ,i ,xi)))
516 finally (cl-assert (equal a b) t))))
517 (atom (if (not (equal a b))
518 (if (and (symbolp a) (symbolp b) (string= a b))
519 `(different-symbols-with-the-same-name ,a ,b)
520 `(different-atoms ,(ert--explain-format-atom a)
521 ,(ert--explain-format-atom b)))
522 nil)))))
524 (defun ert--explain-equal (a b)
525 "Explainer function for `equal'."
526 ;; Do a quick comparison in C to avoid running our expensive
527 ;; comparison when possible.
528 (if (equal a b)
530 (ert--explain-equal-rec a b)))
531 (put 'equal 'ert-explainer 'ert--explain-equal)
533 (defun ert--significant-plist-keys (plist)
534 "Return the keys of PLIST that have non-null values, in order."
535 (cl-assert (zerop (mod (length plist) 2)) t)
536 (cl-loop for (key value . rest) on plist by #'cddr
537 unless (or (null value) (memq key accu)) collect key into accu
538 finally (cl-return accu)))
540 (defun ert--plist-difference-explanation (a b)
541 "Return a programmer-readable explanation of why A and B are different plists.
543 Returns nil if they are equivalent, i.e., have the same value for
544 each key, where absent values are treated as nil. The order of
545 key/value pairs in each list does not matter."
546 (cl-assert (zerop (mod (length a) 2)) t)
547 (cl-assert (zerop (mod (length b) 2)) t)
548 ;; Normalizing the plists would be another way to do this but it
549 ;; requires a total ordering on all lisp objects (since any object
550 ;; is valid as a text property key). Perhaps defining such an
551 ;; ordering is useful in other contexts, too, but it's a lot of
552 ;; work, so let's punt on it for now.
553 (let* ((keys-a (ert--significant-plist-keys a))
554 (keys-b (ert--significant-plist-keys b))
555 (keys-in-a-not-in-b (cl-set-difference keys-a keys-b :test 'eq))
556 (keys-in-b-not-in-a (cl-set-difference keys-b keys-a :test 'eq)))
557 (cl-flet ((explain-with-key (key)
558 (let ((value-a (plist-get a key))
559 (value-b (plist-get b key)))
560 (cl-assert (not (equal value-a value-b)) t)
561 `(different-properties-for-key
562 ,key ,(ert--explain-equal-including-properties value-a
563 value-b)))))
564 (cond (keys-in-a-not-in-b
565 (explain-with-key (car keys-in-a-not-in-b)))
566 (keys-in-b-not-in-a
567 (explain-with-key (car keys-in-b-not-in-a)))
569 (cl-loop for key in keys-a
570 when (not (equal (plist-get a key) (plist-get b key)))
571 return (explain-with-key key)))))))
573 (defun ert--abbreviate-string (s len suffixp)
574 "Shorten string S to at most LEN chars.
576 If SUFFIXP is non-nil, returns a suffix of S, otherwise a prefix."
577 (let ((n (length s)))
578 (cond ((< n len)
580 (suffixp
581 (substring s (- n len)))
583 (substring s 0 len)))))
585 ;; TODO(ohler): Once bug 6581 is fixed, rename this to
586 ;; `ert--explain-equal-including-properties-rec' and add a fast-path
587 ;; wrapper like `ert--explain-equal'.
588 (defun ert--explain-equal-including-properties (a b)
589 "Explainer function for `ert-equal-including-properties'.
591 Returns a programmer-readable explanation of why A and B are not
592 `ert-equal-including-properties', or nil if they are."
593 (if (not (equal a b))
594 (ert--explain-equal a b)
595 (cl-assert (stringp a) t)
596 (cl-assert (stringp b) t)
597 (cl-assert (eql (length a) (length b)) t)
598 (cl-loop for i from 0 to (length a)
599 for props-a = (text-properties-at i a)
600 for props-b = (text-properties-at i b)
601 for difference = (ert--plist-difference-explanation
602 props-a props-b)
603 do (when difference
604 (cl-return `(char ,i ,(substring-no-properties a i (1+ i))
605 ,difference
606 context-before
607 ,(ert--abbreviate-string
608 (substring-no-properties a 0 i)
609 10 t)
610 context-after
611 ,(ert--abbreviate-string
612 (substring-no-properties a (1+ i))
613 10 nil))))
614 ;; TODO(ohler): Get `equal-including-properties' fixed in
615 ;; Emacs, delete `ert-equal-including-properties', and
616 ;; re-enable this assertion.
617 ;;finally (cl-assert (equal-including-properties a b) t)
619 (put 'ert-equal-including-properties
620 'ert-explainer
621 'ert--explain-equal-including-properties)
624 ;;; Implementation of `ert-info'.
626 ;; TODO(ohler): The name `info' clashes with
627 ;; `ert--test-execution-info'. One or both should be renamed.
628 (defvar ert--infos '()
629 "The stack of `ert-info' infos that currently apply.
631 Bound dynamically. This is a list of (PREFIX . MESSAGE) pairs.")
633 (cl-defmacro ert-info ((message-form &key ((:prefix prefix-form) "Info: "))
634 &body body)
635 "Evaluate MESSAGE-FORM and BODY, and report the message if BODY fails.
637 To be used within ERT tests. MESSAGE-FORM should evaluate to a
638 string that will be displayed together with the test result if
639 the test fails. PREFIX-FORM should evaluate to a string as well
640 and is displayed in front of the value of MESSAGE-FORM."
641 (declare (debug ((form &rest [sexp form]) body))
642 (indent 1))
643 `(let ((ert--infos (cons (cons ,prefix-form ,message-form) ert--infos)))
644 ,@body))
648 ;;; Facilities for running a single test.
650 (defvar ert-debug-on-error nil
651 "Non-nil means enter debugger when a test fails or terminates with an error.")
653 ;; The data structures that represent the result of running a test.
654 (cl-defstruct ert-test-result
655 (messages nil)
656 (should-forms nil)
658 (cl-defstruct (ert-test-passed (:include ert-test-result)))
659 (cl-defstruct (ert-test-result-with-condition (:include ert-test-result))
660 (condition (cl-assert nil))
661 (backtrace (cl-assert nil))
662 (infos (cl-assert nil)))
663 (cl-defstruct (ert-test-quit (:include ert-test-result-with-condition)))
664 (cl-defstruct (ert-test-failed (:include ert-test-result-with-condition)))
665 (cl-defstruct (ert-test-skipped (:include ert-test-result-with-condition)))
666 (cl-defstruct (ert-test-aborted-with-non-local-exit
667 (:include ert-test-result)))
670 (defun ert--record-backtrace ()
671 "Record the current backtrace (as a list) and return it."
672 ;; Since the backtrace is stored in the result object, result
673 ;; objects must only be printed with appropriate limits
674 ;; (`print-level' and `print-length') in place. For interactive
675 ;; use, the cost of ensuring this possibly outweighs the advantage
676 ;; of storing the backtrace for
677 ;; `ert-results-pop-to-backtrace-for-test-at-point' given that we
678 ;; already have `ert-results-rerun-test-debugging-errors-at-point'.
679 ;; For batch use, however, printing the backtrace may be useful.
680 (cl-loop
681 ;; 6 is the number of frames our own debugger adds (when
682 ;; compiled; more when interpreted). FIXME: Need to describe a
683 ;; procedure for determining this constant.
684 for i from 6
685 for frame = (backtrace-frame i)
686 while frame
687 collect frame))
689 (defun ert--print-backtrace (backtrace)
690 "Format the backtrace BACKTRACE to the current buffer."
691 ;; This is essentially a reimplementation of Fbacktrace
692 ;; (src/eval.c), but for a saved backtrace, not the current one.
693 (let ((print-escape-newlines t)
694 (print-level 8)
695 (print-length 50))
696 (dolist (frame backtrace)
697 (cl-ecase (car frame)
698 ((nil)
699 ;; Special operator.
700 (cl-destructuring-bind (special-operator &rest arg-forms)
701 (cdr frame)
702 (insert
703 (format " %S\n" (cons special-operator arg-forms)))))
704 ((t)
705 ;; Function call.
706 (cl-destructuring-bind (fn &rest args) (cdr frame)
707 (insert (format " %S(" fn))
708 (cl-loop for firstp = t then nil
709 for arg in args do
710 (unless firstp
711 (insert " "))
712 (insert (format "%S" arg)))
713 (insert ")\n")))))))
715 ;; A container for the state of the execution of a single test and
716 ;; environment data needed during its execution.
717 (cl-defstruct ert--test-execution-info
718 (test (cl-assert nil))
719 (result (cl-assert nil))
720 ;; A thunk that may be called when RESULT has been set to its final
721 ;; value and test execution should be terminated. Should not
722 ;; return.
723 (exit-continuation (cl-assert nil))
724 ;; The binding of `debugger' outside of the execution of the test.
725 next-debugger
726 ;; The binding of `ert-debug-on-error' that is in effect for the
727 ;; execution of the current test. We store it to avoid being
728 ;; affected by any new bindings the test itself may establish. (I
729 ;; don't remember whether this feature is important.)
730 ert-debug-on-error)
732 (defun ert--run-test-debugger (info args)
733 "During a test run, `debugger' is bound to a closure that calls this function.
735 This function records failures and errors and either terminates
736 the test silently or calls the interactive debugger, as
737 appropriate.
739 INFO is the ert--test-execution-info corresponding to this test
740 run. ARGS are the arguments to `debugger'."
741 (cl-destructuring-bind (first-debugger-arg &rest more-debugger-args)
742 args
743 (cl-ecase first-debugger-arg
744 ((lambda debug t exit nil)
745 (apply (ert--test-execution-info-next-debugger info) args))
746 (error
747 (let* ((condition (car more-debugger-args))
748 (type (cl-case (car condition)
749 ((quit) 'quit)
750 ((ert-test-skipped) 'skipped)
751 (otherwise 'failed)))
752 (backtrace (ert--record-backtrace))
753 (infos (reverse ert--infos)))
754 (setf (ert--test-execution-info-result info)
755 (cl-ecase type
756 (quit
757 (make-ert-test-quit :condition condition
758 :backtrace backtrace
759 :infos infos))
760 (skipped
761 (make-ert-test-skipped :condition condition
762 :backtrace backtrace
763 :infos infos))
764 (failed
765 (make-ert-test-failed :condition condition
766 :backtrace backtrace
767 :infos infos))))
768 ;; Work around Emacs's heuristic (in eval.c) for detecting
769 ;; errors in the debugger.
770 (cl-incf num-nonmacro-input-events)
771 ;; FIXME: We should probably implement more fine-grained
772 ;; control a la non-t `debug-on-error' here.
773 (cond
774 ((ert--test-execution-info-ert-debug-on-error info)
775 (apply (ert--test-execution-info-next-debugger info) args))
776 (t))
777 (funcall (ert--test-execution-info-exit-continuation info)))))))
779 (defun ert--run-test-internal (test-execution-info)
780 "Low-level function to run a test according to TEST-EXECUTION-INFO.
782 This mainly sets up debugger-related bindings."
783 (setf (ert--test-execution-info-next-debugger test-execution-info) debugger
784 (ert--test-execution-info-ert-debug-on-error test-execution-info)
785 ert-debug-on-error)
786 (catch 'ert--pass
787 ;; For now, each test gets its own temp buffer and its own
788 ;; window excursion, just to be safe. If this turns out to be
789 ;; too expensive, we can remove it.
790 (with-temp-buffer
791 (save-window-excursion
792 (let ((debugger (lambda (&rest args)
793 (ert--run-test-debugger test-execution-info
794 args)))
795 (debug-on-error t)
796 (debug-on-quit t)
797 ;; FIXME: Do we need to store the old binding of this
798 ;; and consider it in `ert--run-test-debugger'?
799 (debug-ignored-errors nil)
800 (ert--infos '()))
801 (funcall (ert-test-body (ert--test-execution-info-test
802 test-execution-info))))))
803 (ert-pass))
804 (setf (ert--test-execution-info-result test-execution-info)
805 (make-ert-test-passed))
806 nil)
808 (defun ert--force-message-log-buffer-truncation ()
809 "Immediately truncate *Messages* buffer according to `message-log-max'.
811 This can be useful after reducing the value of `message-log-max'."
812 (with-current-buffer (messages-buffer)
813 ;; This is a reimplementation of this part of message_dolog() in xdisp.c:
814 ;; if (NATNUMP (Vmessage_log_max))
815 ;; {
816 ;; scan_newline (Z, Z_BYTE, BEG, BEG_BYTE,
817 ;; -XFASTINT (Vmessage_log_max) - 1, 0);
818 ;; del_range_both (BEG, BEG_BYTE, PT, PT_BYTE, 0);
819 ;; }
820 (when (and (integerp message-log-max) (>= message-log-max 0))
821 (let ((begin (point-min))
822 (end (save-excursion
823 (goto-char (point-max))
824 (forward-line (- message-log-max))
825 (point)))
826 (inhibit-read-only t))
827 (delete-region begin end)))))
829 (defvar ert--running-tests nil
830 "List of tests that are currently in execution.
832 This list is empty while no test is running, has one element
833 while a test is running, two elements while a test run from
834 inside a test is running, etc. The list is in order of nesting,
835 innermost test first.
837 The elements are of type `ert-test'.")
839 (defun ert-run-test (ert-test)
840 "Run ERT-TEST.
842 Returns the result and stores it in ERT-TEST's `most-recent-result' slot."
843 (setf (ert-test-most-recent-result ert-test) nil)
844 (cl-block error
845 (let ((begin-marker
846 (with-current-buffer (messages-buffer)
847 (point-max-marker))))
848 (unwind-protect
849 (let ((info (make-ert--test-execution-info
850 :test ert-test
851 :result
852 (make-ert-test-aborted-with-non-local-exit)
853 :exit-continuation (lambda ()
854 (cl-return-from error nil))))
855 (should-form-accu (list)))
856 (unwind-protect
857 (let ((ert--should-execution-observer
858 (lambda (form-description)
859 (push form-description should-form-accu)))
860 (message-log-max t)
861 (ert--running-tests (cons ert-test ert--running-tests)))
862 (ert--run-test-internal info))
863 (let ((result (ert--test-execution-info-result info)))
864 (setf (ert-test-result-messages result)
865 (with-current-buffer (messages-buffer)
866 (buffer-substring begin-marker (point-max))))
867 (ert--force-message-log-buffer-truncation)
868 (setq should-form-accu (nreverse should-form-accu))
869 (setf (ert-test-result-should-forms result)
870 should-form-accu)
871 (setf (ert-test-most-recent-result ert-test) result))))
872 (set-marker begin-marker nil))))
873 (ert-test-most-recent-result ert-test))
875 (defun ert-running-test ()
876 "Return the top-level test currently executing."
877 (car (last ert--running-tests)))
880 ;;; Test selectors.
882 (defun ert-test-result-type-p (result result-type)
883 "Return non-nil if RESULT matches type RESULT-TYPE.
885 Valid result types:
887 nil -- Never matches.
888 t -- Always matches.
889 :failed, :passed, :skipped -- Matches corresponding results.
890 \(and TYPES...\) -- Matches if all TYPES match.
891 \(or TYPES...\) -- Matches if some TYPES match.
892 \(not TYPE\) -- Matches if TYPE does not match.
893 \(satisfies PREDICATE\) -- Matches if PREDICATE returns true when called with
894 RESULT."
895 ;; It would be easy to add `member' and `eql' types etc., but I
896 ;; haven't bothered yet.
897 (cl-etypecase result-type
898 ((member nil) nil)
899 ((member t) t)
900 ((member :failed) (ert-test-failed-p result))
901 ((member :passed) (ert-test-passed-p result))
902 ((member :skipped) (ert-test-skipped-p result))
903 (cons
904 (cl-destructuring-bind (operator &rest operands) result-type
905 (cl-ecase operator
906 (and
907 (cl-case (length operands)
908 (0 t)
910 (and (ert-test-result-type-p result (car operands))
911 (ert-test-result-type-p result `(and ,@(cdr operands)))))))
913 (cl-case (length operands)
914 (0 nil)
916 (or (ert-test-result-type-p result (car operands))
917 (ert-test-result-type-p result `(or ,@(cdr operands)))))))
918 (not
919 (cl-assert (eql (length operands) 1))
920 (not (ert-test-result-type-p result (car operands))))
921 (satisfies
922 (cl-assert (eql (length operands) 1))
923 (funcall (car operands) result)))))))
925 (defun ert-test-result-expected-p (test result)
926 "Return non-nil if TEST's expected result type matches RESULT."
928 (ert-test-result-type-p result :skipped)
929 (ert-test-result-type-p result (ert-test-expected-result-type test))))
931 (defun ert-select-tests (selector universe)
932 "Return a list of tests that match SELECTOR.
934 UNIVERSE specifies the set of tests to select from; it should be a list
935 of tests, or t, which refers to all tests named by symbols in `obarray'.
937 Valid SELECTORs:
939 nil -- Selects the empty set.
940 t -- Selects UNIVERSE.
941 :new -- Selects all tests that have not been run yet.
942 :failed, :passed -- Select tests according to their most recent result.
943 :expected, :unexpected -- Select tests according to their most recent result.
944 a string -- A regular expression selecting all tests with matching names.
945 a test -- (i.e., an object of the ert-test data-type) Selects that test.
946 a symbol -- Selects the test that the symbol names, errors if none.
947 \(member TESTS...) -- Selects the elements of TESTS, a list of tests
948 or symbols naming tests.
949 \(eql TEST\) -- Selects TEST, a test or a symbol naming a test.
950 \(and SELECTORS...) -- Selects the tests that match all SELECTORS.
951 \(or SELECTORS...) -- Selects the tests that match any of the SELECTORS.
952 \(not SELECTOR) -- Selects all tests that do not match SELECTOR.
953 \(tag TAG) -- Selects all tests that have TAG on their tags list.
954 A tag is an arbitrary label you can apply when you define a test.
955 \(satisfies PREDICATE) -- Selects all tests that satisfy PREDICATE.
956 PREDICATE is a function that takes an ert-test object as argument,
957 and returns non-nil if it is selected.
959 Only selectors that require a superset of tests, such
960 as (satisfies ...), strings, :new, etc. make use of UNIVERSE.
961 Selectors that do not, such as (member ...), just return the
962 set implied by them without checking whether it is really
963 contained in UNIVERSE."
964 ;; This code needs to match the etypecase in
965 ;; `ert-insert-human-readable-selector'.
966 (cl-etypecase selector
967 ((member nil) nil)
968 ((member t) (cl-etypecase universe
969 (list universe)
970 ((member t) (ert-select-tests "" universe))))
971 ((member :new) (ert-select-tests
972 `(satisfies ,(lambda (test)
973 (null (ert-test-most-recent-result test))))
974 universe))
975 ((member :failed) (ert-select-tests
976 `(satisfies ,(lambda (test)
977 (ert-test-result-type-p
978 (ert-test-most-recent-result test)
979 ':failed)))
980 universe))
981 ((member :passed) (ert-select-tests
982 `(satisfies ,(lambda (test)
983 (ert-test-result-type-p
984 (ert-test-most-recent-result test)
985 ':passed)))
986 universe))
987 ((member :expected) (ert-select-tests
988 `(satisfies
989 ,(lambda (test)
990 (ert-test-result-expected-p
991 test
992 (ert-test-most-recent-result test))))
993 universe))
994 ((member :unexpected) (ert-select-tests `(not :expected) universe))
995 (string
996 (cl-etypecase universe
997 ((member t) (mapcar #'ert-get-test
998 (apropos-internal selector #'ert-test-boundp)))
999 (list (cl-remove-if-not (lambda (test)
1000 (and (ert-test-name test)
1001 (string-match selector
1002 (symbol-name
1003 (ert-test-name test)))))
1004 universe))))
1005 (ert-test (list selector))
1006 (symbol
1007 (cl-assert (ert-test-boundp selector))
1008 (list (ert-get-test selector)))
1009 (cons
1010 (cl-destructuring-bind (operator &rest operands) selector
1011 (cl-ecase operator
1012 (member
1013 (mapcar (lambda (purported-test)
1014 (cl-etypecase purported-test
1015 (symbol (cl-assert (ert-test-boundp purported-test))
1016 (ert-get-test purported-test))
1017 (ert-test purported-test)))
1018 operands))
1019 (eql
1020 (cl-assert (eql (length operands) 1))
1021 (ert-select-tests `(member ,@operands) universe))
1022 (and
1023 ;; Do these definitions of AND, NOT and OR satisfy de
1024 ;; Morgan's laws? Should they?
1025 (cl-case (length operands)
1026 (0 (ert-select-tests 't universe))
1027 (t (ert-select-tests `(and ,@(cdr operands))
1028 (ert-select-tests (car operands)
1029 universe)))))
1030 (not
1031 (cl-assert (eql (length operands) 1))
1032 (let ((all-tests (ert-select-tests 't universe)))
1033 (cl-set-difference all-tests
1034 (ert-select-tests (car operands)
1035 all-tests))))
1037 (cl-case (length operands)
1038 (0 (ert-select-tests 'nil universe))
1039 (t (cl-union (ert-select-tests (car operands) universe)
1040 (ert-select-tests `(or ,@(cdr operands))
1041 universe)))))
1042 (tag
1043 (cl-assert (eql (length operands) 1))
1044 (let ((tag (car operands)))
1045 (ert-select-tests `(satisfies
1046 ,(lambda (test)
1047 (member tag (ert-test-tags test))))
1048 universe)))
1049 (satisfies
1050 (cl-assert (eql (length operands) 1))
1051 (cl-remove-if-not (car operands)
1052 (ert-select-tests 't universe))))))))
1054 (defun ert--insert-human-readable-selector (selector)
1055 "Insert a human-readable presentation of SELECTOR into the current buffer."
1056 ;; This is needed to avoid printing the (huge) contents of the
1057 ;; `backtrace' slot of the result objects in the
1058 ;; `most-recent-result' slots of test case objects in (eql ...) or
1059 ;; (member ...) selectors.
1060 (cl-labels ((rec (selector)
1061 ;; This code needs to match the etypecase in
1062 ;; `ert-select-tests'.
1063 (cl-etypecase selector
1064 ((or (member nil t
1065 :new :failed :passed
1066 :expected :unexpected)
1067 string
1068 symbol)
1069 selector)
1070 (ert-test
1071 (if (ert-test-name selector)
1072 (make-symbol (format "<%S>" (ert-test-name selector)))
1073 (make-symbol "<unnamed test>")))
1074 (cons
1075 (cl-destructuring-bind (operator &rest operands) selector
1076 (cl-ecase operator
1077 ((member eql and not or)
1078 `(,operator ,@(mapcar #'rec operands)))
1079 ((member tag satisfies)
1080 selector)))))))
1081 (insert (format "%S" (rec selector)))))
1084 ;;; Facilities for running a whole set of tests.
1086 ;; The data structure that contains the set of tests being executed
1087 ;; during one particular test run, their results, the state of the
1088 ;; execution, and some statistics.
1090 ;; The data about results and expected results of tests may seem
1091 ;; redundant here, since the test objects also carry such information.
1092 ;; However, the information in the test objects may be more recent, it
1093 ;; may correspond to a different test run. We need the information
1094 ;; that corresponds to this run in order to be able to update the
1095 ;; statistics correctly when a test is re-run interactively and has a
1096 ;; different result than before.
1097 (cl-defstruct ert--stats
1098 (selector (cl-assert nil))
1099 ;; The tests, in order.
1100 (tests (cl-assert nil) :type vector)
1101 ;; A map of test names (or the test objects themselves for unnamed
1102 ;; tests) to indices into the `tests' vector.
1103 (test-map (cl-assert nil) :type hash-table)
1104 ;; The results of the tests during this run, in order.
1105 (test-results (cl-assert nil) :type vector)
1106 ;; The start times of the tests, in order, as reported by
1107 ;; `current-time'.
1108 (test-start-times (cl-assert nil) :type vector)
1109 ;; The end times of the tests, in order, as reported by
1110 ;; `current-time'.
1111 (test-end-times (cl-assert nil) :type vector)
1112 (passed-expected 0)
1113 (passed-unexpected 0)
1114 (failed-expected 0)
1115 (failed-unexpected 0)
1116 (skipped 0)
1117 (start-time nil)
1118 (end-time nil)
1119 (aborted-p nil)
1120 (current-test nil)
1121 ;; The time at or after which the next redisplay should occur, as a
1122 ;; float.
1123 (next-redisplay 0.0))
1125 (defun ert-stats-completed-expected (stats)
1126 "Return the number of tests in STATS that had expected results."
1127 (+ (ert--stats-passed-expected stats)
1128 (ert--stats-failed-expected stats)))
1130 (defun ert-stats-completed-unexpected (stats)
1131 "Return the number of tests in STATS that had unexpected results."
1132 (+ (ert--stats-passed-unexpected stats)
1133 (ert--stats-failed-unexpected stats)))
1135 (defun ert-stats-skipped (stats)
1136 "Number of tests in STATS that have skipped."
1137 (ert--stats-skipped stats))
1139 (defun ert-stats-completed (stats)
1140 "Number of tests in STATS that have run so far."
1141 (+ (ert-stats-completed-expected stats)
1142 (ert-stats-completed-unexpected stats)
1143 (ert-stats-skipped stats)))
1145 (defun ert-stats-total (stats)
1146 "Number of tests in STATS, regardless of whether they have run yet."
1147 (length (ert--stats-tests stats)))
1149 ;; The stats object of the current run, dynamically bound. This is
1150 ;; used for the mode line progress indicator.
1151 (defvar ert--current-run-stats nil)
1153 (defun ert--stats-test-key (test)
1154 "Return the key used for TEST in the test map of ert--stats objects.
1156 Returns the name of TEST if it has one, or TEST itself otherwise."
1157 (or (ert-test-name test) test))
1159 (defun ert--stats-set-test-and-result (stats pos test result)
1160 "Change STATS by replacing the test at position POS with TEST and RESULT.
1162 Also changes the counters in STATS to match."
1163 (let* ((tests (ert--stats-tests stats))
1164 (results (ert--stats-test-results stats))
1165 (old-test (aref tests pos))
1166 (map (ert--stats-test-map stats)))
1167 (cl-flet ((update (d)
1168 (if (ert-test-result-expected-p (aref tests pos)
1169 (aref results pos))
1170 (cl-etypecase (aref results pos)
1171 (ert-test-passed
1172 (cl-incf (ert--stats-passed-expected stats) d))
1173 (ert-test-failed
1174 (cl-incf (ert--stats-failed-expected stats) d))
1175 (ert-test-skipped
1176 (cl-incf (ert--stats-skipped stats) d))
1177 (null)
1178 (ert-test-aborted-with-non-local-exit)
1179 (ert-test-quit))
1180 (cl-etypecase (aref results pos)
1181 (ert-test-passed
1182 (cl-incf (ert--stats-passed-unexpected stats) d))
1183 (ert-test-failed
1184 (cl-incf (ert--stats-failed-unexpected stats) d))
1185 (ert-test-skipped
1186 (cl-incf (ert--stats-skipped stats) d))
1187 (null)
1188 (ert-test-aborted-with-non-local-exit)
1189 (ert-test-quit)))))
1190 ;; Adjust counters to remove the result that is currently in stats.
1191 (update -1)
1192 ;; Put new test and result into stats.
1193 (setf (aref tests pos) test
1194 (aref results pos) result)
1195 (remhash (ert--stats-test-key old-test) map)
1196 (setf (gethash (ert--stats-test-key test) map) pos)
1197 ;; Adjust counters to match new result.
1198 (update +1)
1199 nil)))
1201 (defun ert--make-stats (tests selector)
1202 "Create a new `ert--stats' object for running TESTS.
1204 SELECTOR is the selector that was used to select TESTS."
1205 (setq tests (cl-coerce tests 'vector))
1206 (let ((map (make-hash-table :size (length tests))))
1207 (cl-loop for i from 0
1208 for test across tests
1209 for key = (ert--stats-test-key test) do
1210 (cl-assert (not (gethash key map)))
1211 (setf (gethash key map) i))
1212 (make-ert--stats :selector selector
1213 :tests tests
1214 :test-map map
1215 :test-results (make-vector (length tests) nil)
1216 :test-start-times (make-vector (length tests) nil)
1217 :test-end-times (make-vector (length tests) nil))))
1219 (defun ert-run-or-rerun-test (stats test listener)
1220 ;; checkdoc-order: nil
1221 "Run the single test TEST and record the result using STATS and LISTENER."
1222 (let ((ert--current-run-stats stats)
1223 (pos (ert--stats-test-pos stats test)))
1224 (ert--stats-set-test-and-result stats pos test nil)
1225 ;; Call listener after setting/before resetting
1226 ;; (ert--stats-current-test stats); the listener might refresh the
1227 ;; mode line display, and if the value is not set yet/any more
1228 ;; during this refresh, the mode line will flicker unnecessarily.
1229 (setf (ert--stats-current-test stats) test)
1230 (funcall listener 'test-started stats test)
1231 (setf (ert-test-most-recent-result test) nil)
1232 (setf (aref (ert--stats-test-start-times stats) pos) (current-time))
1233 (unwind-protect
1234 (ert-run-test test)
1235 (setf (aref (ert--stats-test-end-times stats) pos) (current-time))
1236 (let ((result (ert-test-most-recent-result test)))
1237 (ert--stats-set-test-and-result stats pos test result)
1238 (funcall listener 'test-ended stats test result))
1239 (setf (ert--stats-current-test stats) nil))))
1241 (defun ert-run-tests (selector listener)
1242 "Run the tests specified by SELECTOR, sending progress updates to LISTENER."
1243 (let* ((tests (ert-select-tests selector t))
1244 (stats (ert--make-stats tests selector)))
1245 (setf (ert--stats-start-time stats) (current-time))
1246 (funcall listener 'run-started stats)
1247 (let ((abortedp t))
1248 (unwind-protect
1249 (let ((ert--current-run-stats stats))
1250 (force-mode-line-update)
1251 (unwind-protect
1252 (progn
1253 (cl-loop for test in tests do
1254 (ert-run-or-rerun-test stats test listener))
1255 (setq abortedp nil))
1256 (setf (ert--stats-aborted-p stats) abortedp)
1257 (setf (ert--stats-end-time stats) (current-time))
1258 (funcall listener 'run-ended stats abortedp)))
1259 (force-mode-line-update))
1260 stats)))
1262 (defun ert--stats-test-pos (stats test)
1263 ;; checkdoc-order: nil
1264 "Return the position (index) of TEST in the run represented by STATS."
1265 (gethash (ert--stats-test-key test) (ert--stats-test-map stats)))
1268 ;;; Formatting functions shared across UIs.
1270 (defun ert--format-time-iso8601 (time)
1271 "Format TIME in the variant of ISO 8601 used for timestamps in ERT."
1272 (format-time-string "%Y-%m-%d %T%z" time))
1274 (defun ert-char-for-test-result (result expectedp)
1275 "Return a character that represents the test result RESULT.
1277 EXPECTEDP specifies whether the result was expected."
1278 (let ((s (cl-etypecase result
1279 (ert-test-passed ".P")
1280 (ert-test-failed "fF")
1281 (ert-test-skipped "sS")
1282 (null "--")
1283 (ert-test-aborted-with-non-local-exit "aA")
1284 (ert-test-quit "qQ"))))
1285 (elt s (if expectedp 0 1))))
1287 (defun ert-string-for-test-result (result expectedp)
1288 "Return a string that represents the test result RESULT.
1290 EXPECTEDP specifies whether the result was expected."
1291 (let ((s (cl-etypecase result
1292 (ert-test-passed '("passed" "PASSED"))
1293 (ert-test-failed '("failed" "FAILED"))
1294 (ert-test-skipped '("skipped" "SKIPPED"))
1295 (null '("unknown" "UNKNOWN"))
1296 (ert-test-aborted-with-non-local-exit '("aborted" "ABORTED"))
1297 (ert-test-quit '("quit" "QUIT")))))
1298 (elt s (if expectedp 0 1))))
1300 (defun ert--pp-with-indentation-and-newline (object)
1301 "Pretty-print OBJECT, indenting it to the current column of point.
1302 Ensures a final newline is inserted."
1303 (let ((begin (point)))
1304 (pp object (current-buffer))
1305 (unless (bolp) (insert "\n"))
1306 (save-excursion
1307 (goto-char begin)
1308 (indent-sexp))))
1310 (defun ert--insert-infos (result)
1311 "Insert `ert-info' infos from RESULT into current buffer.
1313 RESULT must be an `ert-test-result-with-condition'."
1314 (cl-check-type result ert-test-result-with-condition)
1315 (dolist (info (ert-test-result-with-condition-infos result))
1316 (cl-destructuring-bind (prefix . message) info
1317 (let ((begin (point))
1318 (indentation (make-string (+ (length prefix) 4) ?\s))
1319 (end nil))
1320 (unwind-protect
1321 (progn
1322 (insert message "\n")
1323 (setq end (copy-marker (point)))
1324 (goto-char begin)
1325 (insert " " prefix)
1326 (forward-line 1)
1327 (while (< (point) end)
1328 (insert indentation)
1329 (forward-line 1)))
1330 (when end (set-marker end nil)))))))
1333 ;;; Running tests in batch mode.
1335 (defvar ert-batch-backtrace-right-margin 70
1336 "The maximum line length for printing backtraces in `ert-run-tests-batch'.")
1338 ;;;###autoload
1339 (defun ert-run-tests-batch (&optional selector)
1340 "Run the tests specified by SELECTOR, printing results to the terminal.
1342 SELECTOR works as described in `ert-select-tests', except if
1343 SELECTOR is nil, in which case all tests rather than none will be
1344 run; this makes the command line \"emacs -batch -l my-tests.el -f
1345 ert-run-tests-batch-and-exit\" useful.
1347 Returns the stats object."
1348 (unless selector (setq selector 't))
1349 (ert-run-tests
1350 selector
1351 (lambda (event-type &rest event-args)
1352 (cl-ecase event-type
1353 (run-started
1354 (cl-destructuring-bind (stats) event-args
1355 (message "Running %s tests (%s)"
1356 (length (ert--stats-tests stats))
1357 (ert--format-time-iso8601 (ert--stats-start-time stats)))))
1358 (run-ended
1359 (cl-destructuring-bind (stats abortedp) event-args
1360 (let ((unexpected (ert-stats-completed-unexpected stats))
1361 (skipped (ert-stats-skipped stats))
1362 (expected-failures (ert--stats-failed-expected stats)))
1363 (message "\n%sRan %s tests, %s results as expected%s%s (%s)%s\n"
1364 (if (not abortedp)
1366 "Aborted: ")
1367 (ert-stats-total stats)
1368 (ert-stats-completed-expected stats)
1369 (if (zerop unexpected)
1371 (format ", %s unexpected" unexpected))
1372 (if (zerop skipped)
1374 (format ", %s skipped" skipped))
1375 (ert--format-time-iso8601 (ert--stats-end-time stats))
1376 (if (zerop expected-failures)
1378 (format "\n%s expected failures" expected-failures)))
1379 (unless (zerop unexpected)
1380 (message "%s unexpected results:" unexpected)
1381 (cl-loop for test across (ert--stats-tests stats)
1382 for result = (ert-test-most-recent-result test) do
1383 (when (not (ert-test-result-expected-p test result))
1384 (message "%9s %S"
1385 (ert-string-for-test-result result nil)
1386 (ert-test-name test))))
1387 (message "%s" ""))
1388 (unless (zerop skipped)
1389 (message "%s skipped results:" skipped)
1390 (cl-loop for test across (ert--stats-tests stats)
1391 for result = (ert-test-most-recent-result test) do
1392 (when (ert-test-result-type-p result :skipped)
1393 (message "%9s %S"
1394 (ert-string-for-test-result result nil)
1395 (ert-test-name test))))
1396 (message "%s" "")))))
1397 (test-started
1399 (test-ended
1400 (cl-destructuring-bind (stats test result) event-args
1401 (unless (ert-test-result-expected-p test result)
1402 (cl-etypecase result
1403 (ert-test-passed
1404 (message "Test %S passed unexpectedly" (ert-test-name test)))
1405 (ert-test-result-with-condition
1406 (message "Test %S backtrace:" (ert-test-name test))
1407 (with-temp-buffer
1408 (ert--print-backtrace (ert-test-result-with-condition-backtrace
1409 result))
1410 (goto-char (point-min))
1411 (while (not (eobp))
1412 (let ((start (point))
1413 (end (progn (end-of-line) (point))))
1414 (setq end (min end
1415 (+ start ert-batch-backtrace-right-margin)))
1416 (message "%s" (buffer-substring-no-properties
1417 start end)))
1418 (forward-line 1)))
1419 (with-temp-buffer
1420 (ert--insert-infos result)
1421 (insert " ")
1422 (let ((print-escape-newlines t)
1423 (print-level 5)
1424 (print-length 10))
1425 (ert--pp-with-indentation-and-newline
1426 (ert-test-result-with-condition-condition result)))
1427 (goto-char (1- (point-max)))
1428 (cl-assert (looking-at "\n"))
1429 (delete-char 1)
1430 (message "Test %S condition:" (ert-test-name test))
1431 (message "%s" (buffer-string))))
1432 (ert-test-aborted-with-non-local-exit
1433 (message "Test %S aborted with non-local exit"
1434 (ert-test-name test)))
1435 (ert-test-quit
1436 (message "Quit during %S" (ert-test-name test)))))
1437 (let* ((max (prin1-to-string (length (ert--stats-tests stats))))
1438 (format-string (concat "%9s %"
1439 (prin1-to-string (length max))
1440 "s/" max " %S")))
1441 (message format-string
1442 (ert-string-for-test-result result
1443 (ert-test-result-expected-p
1444 test result))
1445 (1+ (ert--stats-test-pos stats test))
1446 (ert-test-name test)))))))))
1448 ;;;###autoload
1449 (defun ert-run-tests-batch-and-exit (&optional selector)
1450 "Like `ert-run-tests-batch', but exits Emacs when done.
1452 The exit status will be 0 if all test results were as expected, 1
1453 on unexpected results, or 2 if the tool detected an error outside
1454 of the tests (e.g. invalid SELECTOR or bug in the code that runs
1455 the tests)."
1456 (unwind-protect
1457 (let ((stats (ert-run-tests-batch selector)))
1458 (kill-emacs (if (zerop (ert-stats-completed-unexpected stats)) 0 1)))
1459 (unwind-protect
1460 (progn
1461 (message "Error running tests")
1462 (backtrace))
1463 (kill-emacs 2))))
1466 ;;; Utility functions for load/unload actions.
1468 (defun ert--activate-font-lock-keywords ()
1469 "Activate font-lock keywords for some of ERT's symbols."
1470 (font-lock-add-keywords
1472 '(("(\\(\\<ert-deftest\\)\\>\\s *\\(\\sw+\\)?"
1473 (1 font-lock-keyword-face nil t)
1474 (2 font-lock-function-name-face nil t)))))
1476 (cl-defun ert--remove-from-list (list-var element &key key test)
1477 "Remove ELEMENT from the value of LIST-VAR if present.
1479 This can be used as an inverse of `add-to-list'."
1480 (unless key (setq key #'identity))
1481 (unless test (setq test #'equal))
1482 (setf (symbol-value list-var)
1483 (cl-remove element
1484 (symbol-value list-var)
1485 :key key
1486 :test test)))
1489 ;;; Some basic interactive functions.
1491 (defun ert-read-test-name (prompt &optional default history
1492 add-default-to-prompt)
1493 "Read the name of a test and return it as a symbol.
1495 Prompt with PROMPT. If DEFAULT is a valid test name, use it as a
1496 default. HISTORY is the history to use; see `completing-read'.
1497 If ADD-DEFAULT-TO-PROMPT is non-nil, PROMPT will be modified to
1498 include the default, if any.
1500 Signals an error if no test name was read."
1501 (cl-etypecase default
1502 (string (let ((symbol (intern-soft default)))
1503 (unless (and symbol (ert-test-boundp symbol))
1504 (setq default nil))))
1505 (symbol (setq default
1506 (if (ert-test-boundp default)
1507 (symbol-name default)
1508 nil)))
1509 (ert-test (setq default (ert-test-name default))))
1510 (when add-default-to-prompt
1511 (setq prompt (if (null default)
1512 (format "%s: " prompt)
1513 (format "%s (default %s): " prompt default))))
1514 (let ((input (completing-read prompt obarray #'ert-test-boundp
1515 t nil history default nil)))
1516 ;; completing-read returns an empty string if default was nil and
1517 ;; the user just hit enter.
1518 (let ((sym (intern-soft input)))
1519 (if (ert-test-boundp sym)
1521 (error "Input does not name a test")))))
1523 (defun ert-read-test-name-at-point (prompt)
1524 "Read the name of a test and return it as a symbol.
1525 As a default, use the symbol at point, or the test at point if in
1526 the ERT results buffer. Prompt with PROMPT, augmented with the
1527 default (if any)."
1528 (ert-read-test-name prompt (ert-test-at-point) nil t))
1530 (defun ert-find-test-other-window (test-name)
1531 "Find, in another window, the definition of TEST-NAME."
1532 (interactive (list (ert-read-test-name-at-point "Find test definition: ")))
1533 (find-function-do-it test-name 'ert-deftest 'switch-to-buffer-other-window))
1535 (defun ert-delete-test (test-name)
1536 "Make the test TEST-NAME unbound.
1538 Nothing more than an interactive interface to `ert-make-test-unbound'."
1539 (interactive (list (ert-read-test-name-at-point "Delete test")))
1540 (ert-make-test-unbound test-name))
1542 (defun ert-delete-all-tests ()
1543 "Make all symbols in `obarray' name no test."
1544 (interactive)
1545 (when (called-interactively-p 'any)
1546 (unless (y-or-n-p "Delete all tests? ")
1547 (error "Aborted")))
1548 ;; We can't use `ert-select-tests' here since that gives us only
1549 ;; test objects, and going from them back to the test name symbols
1550 ;; can fail if the `ert-test' defstruct has been redefined.
1551 (mapc #'ert-make-test-unbound (apropos-internal "" #'ert-test-boundp))
1555 ;;; Display of test progress and results.
1557 ;; An entry in the results buffer ewoc. There is one entry per test.
1558 (cl-defstruct ert--ewoc-entry
1559 (test (cl-assert nil))
1560 ;; If the result of this test was expected, its ewoc entry is hidden
1561 ;; initially.
1562 (hidden-p (cl-assert nil))
1563 ;; An ewoc entry may be collapsed to hide details such as the error
1564 ;; condition.
1566 ;; I'm not sure the ability to expand and collapse entries is still
1567 ;; a useful feature.
1568 (expanded-p t)
1569 ;; By default, the ewoc entry presents the error condition with
1570 ;; certain limits on how much to print (`print-level',
1571 ;; `print-length'). The user can interactively switch to a set of
1572 ;; higher limits.
1573 (extended-printer-limits-p nil))
1575 ;; Variables local to the results buffer.
1577 ;; The ewoc.
1578 (defvar ert--results-ewoc)
1579 ;; The stats object.
1580 (defvar ert--results-stats)
1581 ;; A string with one character per test. Each character represents
1582 ;; the result of the corresponding test. The string is displayed near
1583 ;; the top of the buffer and serves as a progress bar.
1584 (defvar ert--results-progress-bar-string)
1585 ;; The position where the progress bar button begins.
1586 (defvar ert--results-progress-bar-button-begin)
1587 ;; The test result listener that updates the buffer when tests are run.
1588 (defvar ert--results-listener)
1590 (defun ert-insert-test-name-button (test-name)
1591 "Insert a button that links to TEST-NAME."
1592 (insert-text-button (format "%S" test-name)
1593 :type 'ert--test-name-button
1594 'ert-test-name test-name))
1596 (defun ert--results-format-expected-unexpected (expected unexpected)
1597 "Return a string indicating EXPECTED expected results, UNEXPECTED unexpected."
1598 (if (zerop unexpected)
1599 (format "%s" expected)
1600 (format "%s (%s unexpected)" (+ expected unexpected) unexpected)))
1602 (defun ert--results-update-ewoc-hf (ewoc stats)
1603 "Update the header and footer of EWOC to show certain information from STATS.
1605 Also sets `ert--results-progress-bar-button-begin'."
1606 (let ((run-count (ert-stats-completed stats))
1607 (results-buffer (current-buffer))
1608 ;; Need to save buffer-local value.
1609 (font-lock font-lock-mode))
1610 (ewoc-set-hf
1611 ewoc
1612 ;; header
1613 (with-temp-buffer
1614 (insert "Selector: ")
1615 (ert--insert-human-readable-selector (ert--stats-selector stats))
1616 (insert "\n")
1617 (insert
1618 (format (concat "Passed: %s\n"
1619 "Failed: %s\n"
1620 "Skipped: %s\n"
1621 "Total: %s/%s\n\n")
1622 (ert--results-format-expected-unexpected
1623 (ert--stats-passed-expected stats)
1624 (ert--stats-passed-unexpected stats))
1625 (ert--results-format-expected-unexpected
1626 (ert--stats-failed-expected stats)
1627 (ert--stats-failed-unexpected stats))
1628 (ert-stats-skipped stats)
1629 run-count
1630 (ert-stats-total stats)))
1631 (insert
1632 (format "Started at: %s\n"
1633 (ert--format-time-iso8601 (ert--stats-start-time stats))))
1634 ;; FIXME: This is ugly. Need to properly define invariants of
1635 ;; the `stats' data structure.
1636 (let ((state (cond ((ert--stats-aborted-p stats) 'aborted)
1637 ((ert--stats-current-test stats) 'running)
1638 ((ert--stats-end-time stats) 'finished)
1639 (t 'preparing))))
1640 (cl-ecase state
1641 (preparing
1642 (insert ""))
1643 (aborted
1644 (cond ((ert--stats-current-test stats)
1645 (insert "Aborted during test: ")
1646 (ert-insert-test-name-button
1647 (ert-test-name (ert--stats-current-test stats))))
1649 (insert "Aborted."))))
1650 (running
1651 (cl-assert (ert--stats-current-test stats))
1652 (insert "Running test: ")
1653 (ert-insert-test-name-button (ert-test-name
1654 (ert--stats-current-test stats))))
1655 (finished
1656 (cl-assert (not (ert--stats-current-test stats)))
1657 (insert "Finished.")))
1658 (insert "\n")
1659 (if (ert--stats-end-time stats)
1660 (insert
1661 (format "%s%s\n"
1662 (if (ert--stats-aborted-p stats)
1663 "Aborted at: "
1664 "Finished at: ")
1665 (ert--format-time-iso8601 (ert--stats-end-time stats))))
1666 (insert "\n"))
1667 (insert "\n"))
1668 (let ((progress-bar-string (with-current-buffer results-buffer
1669 ert--results-progress-bar-string)))
1670 (let ((progress-bar-button-begin
1671 (insert-text-button progress-bar-string
1672 :type 'ert--results-progress-bar-button
1673 'face (or (and font-lock
1674 (ert-face-for-stats stats))
1675 'button))))
1676 ;; The header gets copied verbatim to the results buffer,
1677 ;; and all positions remain the same, so
1678 ;; `progress-bar-button-begin' will be the right position
1679 ;; even in the results buffer.
1680 (with-current-buffer results-buffer
1681 (set (make-local-variable 'ert--results-progress-bar-button-begin)
1682 progress-bar-button-begin))))
1683 (insert "\n\n")
1684 (buffer-string))
1685 ;; footer
1687 ;; We actually want an empty footer, but that would trigger a bug
1688 ;; in ewoc, sometimes clearing the entire buffer. (It's possible
1689 ;; that this bug has been fixed since this has been tested; we
1690 ;; should test it again.)
1691 "\n")))
1694 (defvar ert-test-run-redisplay-interval-secs .1
1695 "How many seconds ERT should wait between redisplays while running tests.
1697 While running tests, ERT shows the current progress, and this variable
1698 determines how frequently the progress display is updated.")
1700 (defun ert--results-update-stats-display (ewoc stats)
1701 "Update EWOC and the mode line to show data from STATS."
1702 ;; TODO(ohler): investigate using `make-progress-reporter'.
1703 (ert--results-update-ewoc-hf ewoc stats)
1704 (force-mode-line-update)
1705 (redisplay t)
1706 (setf (ert--stats-next-redisplay stats)
1707 (+ (float-time) ert-test-run-redisplay-interval-secs)))
1709 (defun ert--results-update-stats-display-maybe (ewoc stats)
1710 "Call `ert--results-update-stats-display' if not called recently.
1712 EWOC and STATS are arguments for `ert--results-update-stats-display'."
1713 (when (>= (float-time) (ert--stats-next-redisplay stats))
1714 (ert--results-update-stats-display ewoc stats)))
1716 (defun ert--tests-running-mode-line-indicator ()
1717 "Return a string for the mode line that shows the test run progress."
1718 (let* ((stats ert--current-run-stats)
1719 (tests-total (ert-stats-total stats))
1720 (tests-completed (ert-stats-completed stats)))
1721 (if (>= tests-completed tests-total)
1722 (format " ERT(%s/%s,finished)" tests-completed tests-total)
1723 (format " ERT(%s/%s):%s"
1724 (1+ tests-completed)
1725 tests-total
1726 (if (null (ert--stats-current-test stats))
1728 (format "%S"
1729 (ert-test-name (ert--stats-current-test stats))))))))
1731 (defun ert--make-xrefs-region (begin end)
1732 "Attach cross-references to function names between BEGIN and END.
1734 BEGIN and END specify a region in the current buffer."
1735 (save-excursion
1736 (save-restriction
1737 (narrow-to-region begin end)
1738 ;; Inhibit optimization in `debugger-make-xrefs' that would
1739 ;; sometimes insert unrelated backtrace info into our buffer.
1740 (let ((debugger-previous-backtrace nil))
1741 (debugger-make-xrefs)))))
1743 (defun ert--string-first-line (s)
1744 "Return the first line of S, or S if it contains no newlines.
1746 The return value does not include the line terminator."
1747 (substring s 0 (cl-position ?\n s)))
1749 (defun ert-face-for-test-result (expectedp)
1750 "Return a face that shows whether a test result was expected or unexpected.
1752 If EXPECTEDP is nil, returns the face for unexpected results; if
1753 non-nil, returns the face for expected results.."
1754 (if expectedp 'ert-test-result-expected 'ert-test-result-unexpected))
1756 (defun ert-face-for-stats (stats)
1757 "Return a face that represents STATS."
1758 (cond ((ert--stats-aborted-p stats) 'nil)
1759 ((cl-plusp (ert-stats-completed-unexpected stats))
1760 (ert-face-for-test-result nil))
1761 ((eql (ert-stats-completed-expected stats) (ert-stats-total stats))
1762 (ert-face-for-test-result t))
1763 (t 'nil)))
1765 (defun ert--print-test-for-ewoc (entry)
1766 "The ewoc print function for ewoc test entries. ENTRY is the entry to print."
1767 (let* ((test (ert--ewoc-entry-test entry))
1768 (stats ert--results-stats)
1769 (result (let ((pos (ert--stats-test-pos stats test)))
1770 (cl-assert pos)
1771 (aref (ert--stats-test-results stats) pos)))
1772 (hiddenp (ert--ewoc-entry-hidden-p entry))
1773 (expandedp (ert--ewoc-entry-expanded-p entry))
1774 (extended-printer-limits-p (ert--ewoc-entry-extended-printer-limits-p
1775 entry)))
1776 (cond (hiddenp)
1778 (let ((expectedp (ert-test-result-expected-p test result)))
1779 (insert-text-button (format "%c" (ert-char-for-test-result
1780 result expectedp))
1781 :type 'ert--results-expand-collapse-button
1782 'face (or (and font-lock-mode
1783 (ert-face-for-test-result
1784 expectedp))
1785 'button)))
1786 (insert " ")
1787 (ert-insert-test-name-button (ert-test-name test))
1788 (insert "\n")
1789 (when (and expandedp (not (eql result 'nil)))
1790 (when (ert-test-documentation test)
1791 (insert " "
1792 (propertize
1793 (ert--string-first-line (ert-test-documentation test))
1794 'font-lock-face 'font-lock-doc-face)
1795 "\n"))
1796 (cl-etypecase result
1797 (ert-test-passed
1798 (if (ert-test-result-expected-p test result)
1799 (insert " passed\n")
1800 (insert " passed unexpectedly\n"))
1801 (insert ""))
1802 (ert-test-result-with-condition
1803 (ert--insert-infos result)
1804 (let ((print-escape-newlines t)
1805 (print-level (if extended-printer-limits-p 12 6))
1806 (print-length (if extended-printer-limits-p 100 10)))
1807 (insert " ")
1808 (let ((begin (point)))
1809 (ert--pp-with-indentation-and-newline
1810 (ert-test-result-with-condition-condition result))
1811 (ert--make-xrefs-region begin (point)))))
1812 (ert-test-aborted-with-non-local-exit
1813 (insert " aborted\n"))
1814 (ert-test-quit
1815 (insert " quit\n")))
1816 (insert "\n")))))
1817 nil)
1819 (defun ert--results-font-lock-function (enabledp)
1820 "Redraw the ERT results buffer after font-lock-mode was switched on or off.
1822 ENABLEDP is true if font-lock-mode is switched on, false
1823 otherwise."
1824 (ert--results-update-ewoc-hf ert--results-ewoc ert--results-stats)
1825 (ewoc-refresh ert--results-ewoc)
1826 (font-lock-default-function enabledp))
1828 (defun ert--setup-results-buffer (stats listener buffer-name)
1829 "Set up a test results buffer.
1831 STATS is the stats object; LISTENER is the results listener;
1832 BUFFER-NAME, if non-nil, is the buffer name to use."
1833 (unless buffer-name (setq buffer-name "*ert*"))
1834 (let ((buffer (get-buffer-create buffer-name)))
1835 (with-current-buffer buffer
1836 (let ((inhibit-read-only t))
1837 (buffer-disable-undo)
1838 (erase-buffer)
1839 (ert-results-mode)
1840 ;; Erase buffer again in case switching out of the previous
1841 ;; mode inserted anything. (This happens e.g. when switching
1842 ;; from ert-results-mode to ert-results-mode when
1843 ;; font-lock-mode turns itself off in change-major-mode-hook.)
1844 (erase-buffer)
1845 (set (make-local-variable 'font-lock-function)
1846 'ert--results-font-lock-function)
1847 (let ((ewoc (ewoc-create 'ert--print-test-for-ewoc nil nil t)))
1848 (set (make-local-variable 'ert--results-ewoc) ewoc)
1849 (set (make-local-variable 'ert--results-stats) stats)
1850 (set (make-local-variable 'ert--results-progress-bar-string)
1851 (make-string (ert-stats-total stats)
1852 (ert-char-for-test-result nil t)))
1853 (set (make-local-variable 'ert--results-listener) listener)
1854 (cl-loop for test across (ert--stats-tests stats) do
1855 (ewoc-enter-last ewoc
1856 (make-ert--ewoc-entry :test test
1857 :hidden-p t)))
1858 (ert--results-update-ewoc-hf ert--results-ewoc ert--results-stats)
1859 (goto-char (1- (point-max)))
1860 buffer)))))
1863 (defvar ert--selector-history nil
1864 "List of recent test selectors read from terminal.")
1866 ;; Should OUTPUT-BUFFER-NAME and MESSAGE-FN really be arguments here?
1867 ;; They are needed only for our automated self-tests at the moment.
1868 ;; Or should there be some other mechanism?
1869 ;;;###autoload
1870 (defun ert-run-tests-interactively (selector
1871 &optional output-buffer-name message-fn)
1872 "Run the tests specified by SELECTOR and display the results in a buffer.
1874 SELECTOR works as described in `ert-select-tests'.
1875 OUTPUT-BUFFER-NAME and MESSAGE-FN should normally be nil; they
1876 are used for automated self-tests and specify which buffer to use
1877 and how to display message."
1878 (interactive
1879 (list (let ((default (if ert--selector-history
1880 ;; Can't use `first' here as this form is
1881 ;; not compiled, and `first' is not
1882 ;; defined without cl.
1883 (car ert--selector-history)
1884 "t")))
1885 (completing-read (if (null default)
1886 "Run tests: "
1887 (format "Run tests (default %s): " default))
1888 obarray #'ert-test-boundp nil nil
1889 'ert--selector-history default nil))
1890 nil))
1891 (unless message-fn (setq message-fn 'message))
1892 (let ((output-buffer-name output-buffer-name)
1893 buffer
1894 listener
1895 (message-fn message-fn))
1896 (setq listener
1897 (lambda (event-type &rest event-args)
1898 (cl-ecase event-type
1899 (run-started
1900 (cl-destructuring-bind (stats) event-args
1901 (setq buffer (ert--setup-results-buffer stats
1902 listener
1903 output-buffer-name))
1904 (pop-to-buffer buffer)))
1905 (run-ended
1906 (cl-destructuring-bind (stats abortedp) event-args
1907 (funcall message-fn
1908 "%sRan %s tests, %s results were as expected%s%s"
1909 (if (not abortedp)
1911 "Aborted: ")
1912 (ert-stats-total stats)
1913 (ert-stats-completed-expected stats)
1914 (let ((unexpected
1915 (ert-stats-completed-unexpected stats)))
1916 (if (zerop unexpected)
1918 (format ", %s unexpected" unexpected)))
1919 (let ((skipped
1920 (ert-stats-skipped stats)))
1921 (if (zerop skipped)
1923 (format ", %s skipped" skipped))))
1924 (ert--results-update-stats-display (with-current-buffer buffer
1925 ert--results-ewoc)
1926 stats)))
1927 (test-started
1928 (cl-destructuring-bind (stats test) event-args
1929 (with-current-buffer buffer
1930 (let* ((ewoc ert--results-ewoc)
1931 (pos (ert--stats-test-pos stats test))
1932 (node (ewoc-nth ewoc pos)))
1933 (cl-assert node)
1934 (setf (ert--ewoc-entry-test (ewoc-data node)) test)
1935 (aset ert--results-progress-bar-string pos
1936 (ert-char-for-test-result nil t))
1937 (ert--results-update-stats-display-maybe ewoc stats)
1938 (ewoc-invalidate ewoc node)))))
1939 (test-ended
1940 (cl-destructuring-bind (stats test result) event-args
1941 (with-current-buffer buffer
1942 (let* ((ewoc ert--results-ewoc)
1943 (pos (ert--stats-test-pos stats test))
1944 (node (ewoc-nth ewoc pos)))
1945 (when (ert--ewoc-entry-hidden-p (ewoc-data node))
1946 (setf (ert--ewoc-entry-hidden-p (ewoc-data node))
1947 (ert-test-result-expected-p test result)))
1948 (aset ert--results-progress-bar-string pos
1949 (ert-char-for-test-result result
1950 (ert-test-result-expected-p
1951 test result)))
1952 (ert--results-update-stats-display-maybe ewoc stats)
1953 (ewoc-invalidate ewoc node))))))))
1954 (ert-run-tests
1955 selector
1956 listener)))
1957 ;;;###autoload
1958 (defalias 'ert 'ert-run-tests-interactively)
1961 ;;; Simple view mode for auxiliary information like stack traces or
1962 ;;; messages. Mainly binds "q" for quit.
1964 (define-derived-mode ert-simple-view-mode special-mode "ERT-View"
1965 "Major mode for viewing auxiliary information in ERT.")
1967 ;;; Commands and button actions for the results buffer.
1969 (define-derived-mode ert-results-mode special-mode "ERT-Results"
1970 "Major mode for viewing results of ERT test runs.")
1972 (cl-loop for (key binding) in
1973 '( ;; Stuff that's not in the menu.
1974 ("\t" forward-button)
1975 ([backtab] backward-button)
1976 ("j" ert-results-jump-between-summary-and-result)
1977 ("L" ert-results-toggle-printer-limits-for-test-at-point)
1978 ("n" ert-results-next-test)
1979 ("p" ert-results-previous-test)
1980 ;; Stuff that is in the menu.
1981 ("R" ert-results-rerun-all-tests)
1982 ("r" ert-results-rerun-test-at-point)
1983 ("d" ert-results-rerun-test-at-point-debugging-errors)
1984 ("." ert-results-find-test-at-point-other-window)
1985 ("b" ert-results-pop-to-backtrace-for-test-at-point)
1986 ("m" ert-results-pop-to-messages-for-test-at-point)
1987 ("l" ert-results-pop-to-should-forms-for-test-at-point)
1988 ("h" ert-results-describe-test-at-point)
1989 ("D" ert-delete-test)
1990 ("T" ert-results-pop-to-timings)
1993 (define-key ert-results-mode-map key binding))
1995 (easy-menu-define ert-results-mode-menu ert-results-mode-map
1996 "Menu for `ert-results-mode'."
1997 '("ERT Results"
1998 ["Re-run all tests" ert-results-rerun-all-tests]
1999 "--"
2000 ["Re-run test" ert-results-rerun-test-at-point]
2001 ["Debug test" ert-results-rerun-test-at-point-debugging-errors]
2002 ["Show test definition" ert-results-find-test-at-point-other-window]
2003 "--"
2004 ["Show backtrace" ert-results-pop-to-backtrace-for-test-at-point]
2005 ["Show messages" ert-results-pop-to-messages-for-test-at-point]
2006 ["Show `should' forms" ert-results-pop-to-should-forms-for-test-at-point]
2007 ["Describe test" ert-results-describe-test-at-point]
2008 "--"
2009 ["Delete test" ert-delete-test]
2010 "--"
2011 ["Show execution time of each test" ert-results-pop-to-timings]
2014 (define-button-type 'ert--results-progress-bar-button
2015 'action #'ert--results-progress-bar-button-action
2016 'help-echo "mouse-2, RET: Reveal test result")
2018 (define-button-type 'ert--test-name-button
2019 'action #'ert--test-name-button-action
2020 'help-echo "mouse-2, RET: Find test definition")
2022 (define-button-type 'ert--results-expand-collapse-button
2023 'action #'ert--results-expand-collapse-button-action
2024 'help-echo "mouse-2, RET: Expand/collapse test result")
2026 (defun ert--results-test-node-or-null-at-point ()
2027 "If point is on a valid ewoc node, return it; return nil otherwise.
2029 To be used in the ERT results buffer."
2030 (let* ((ewoc ert--results-ewoc)
2031 (node (ewoc-locate ewoc)))
2032 ;; `ewoc-locate' will return an arbitrary node when point is on
2033 ;; header or footer, or when all nodes are invisible. So we need
2034 ;; to validate its return value here.
2036 ;; Update: I'm seeing nil being returned in some cases now,
2037 ;; perhaps this has been changed?
2038 (if (and node
2039 (>= (point) (ewoc-location node))
2040 (not (ert--ewoc-entry-hidden-p (ewoc-data node))))
2041 node
2042 nil)))
2044 (defun ert--results-test-node-at-point ()
2045 "If point is on a valid ewoc node, return it; signal an error otherwise.
2047 To be used in the ERT results buffer."
2048 (or (ert--results-test-node-or-null-at-point)
2049 (error "No test at point")))
2051 (defun ert-results-next-test ()
2052 "Move point to the next test.
2054 To be used in the ERT results buffer."
2055 (interactive)
2056 (ert--results-move (ewoc-locate ert--results-ewoc) 'ewoc-next
2057 "No tests below"))
2059 (defun ert-results-previous-test ()
2060 "Move point to the previous test.
2062 To be used in the ERT results buffer."
2063 (interactive)
2064 (ert--results-move (ewoc-locate ert--results-ewoc) 'ewoc-prev
2065 "No tests above"))
2067 (defun ert--results-move (node ewoc-fn error-message)
2068 "Move point from NODE to the previous or next node.
2070 EWOC-FN specifies the direction and should be either `ewoc-prev'
2071 or `ewoc-next'. If there are no more nodes in that direction, an
2072 error is signaled with the message ERROR-MESSAGE."
2073 (cl-loop
2074 (setq node (funcall ewoc-fn ert--results-ewoc node))
2075 (when (null node)
2076 (error "%s" error-message))
2077 (unless (ert--ewoc-entry-hidden-p (ewoc-data node))
2078 (goto-char (ewoc-location node))
2079 (cl-return))))
2081 (defun ert--results-expand-collapse-button-action (_button)
2082 "Expand or collapse the test node BUTTON belongs to."
2083 (let* ((ewoc ert--results-ewoc)
2084 (node (save-excursion
2085 (goto-char (ert--button-action-position))
2086 (ert--results-test-node-at-point)))
2087 (entry (ewoc-data node)))
2088 (setf (ert--ewoc-entry-expanded-p entry)
2089 (not (ert--ewoc-entry-expanded-p entry)))
2090 (ewoc-invalidate ewoc node)))
2092 (defun ert-results-find-test-at-point-other-window ()
2093 "Find the definition of the test at point in another window.
2095 To be used in the ERT results buffer."
2096 (interactive)
2097 (let ((name (ert-test-at-point)))
2098 (unless name
2099 (error "No test at point"))
2100 (ert-find-test-other-window name)))
2102 (defun ert--test-name-button-action (button)
2103 "Find the definition of the test BUTTON belongs to, in another window."
2104 (let ((name (button-get button 'ert-test-name)))
2105 (ert-find-test-other-window name)))
2107 (defun ert--ewoc-position (ewoc node)
2108 ;; checkdoc-order: nil
2109 "Return the position of NODE in EWOC, or nil if NODE is not in EWOC."
2110 (cl-loop for i from 0
2111 for node-here = (ewoc-nth ewoc 0) then (ewoc-next ewoc node-here)
2112 do (when (eql node node-here)
2113 (cl-return i))
2114 finally (cl-return nil)))
2116 (defun ert-results-jump-between-summary-and-result ()
2117 "Jump back and forth between the test run summary and individual test results.
2119 From an ewoc node, jumps to the character that represents the
2120 same test in the progress bar, and vice versa.
2122 To be used in the ERT results buffer."
2123 ;; Maybe this command isn't actually needed much, but if it is, it
2124 ;; seems like an indication that the UI design is not optimal. If
2125 ;; jumping back and forth between a summary at the top of the buffer
2126 ;; and the error log in the remainder of the buffer is useful, then
2127 ;; the summary apparently needs to be easily accessible from the
2128 ;; error log, and perhaps it would be better to have it in a
2129 ;; separate buffer to keep it visible.
2130 (interactive)
2131 (let ((ewoc ert--results-ewoc)
2132 (progress-bar-begin ert--results-progress-bar-button-begin))
2133 (cond ((ert--results-test-node-or-null-at-point)
2134 (let* ((node (ert--results-test-node-at-point))
2135 (pos (ert--ewoc-position ewoc node)))
2136 (goto-char (+ progress-bar-begin pos))))
2137 ((and (<= progress-bar-begin (point))
2138 (< (point) (button-end (button-at progress-bar-begin))))
2139 (let* ((node (ewoc-nth ewoc (- (point) progress-bar-begin)))
2140 (entry (ewoc-data node)))
2141 (when (ert--ewoc-entry-hidden-p entry)
2142 (setf (ert--ewoc-entry-hidden-p entry) nil)
2143 (ewoc-invalidate ewoc node))
2144 (ewoc-goto-node ewoc node)))
2146 (goto-char progress-bar-begin)))))
2148 (defun ert-test-at-point ()
2149 "Return the name of the test at point as a symbol, or nil if none."
2150 (or (and (eql major-mode 'ert-results-mode)
2151 (let ((test (ert--results-test-at-point-no-redefinition)))
2152 (and test (ert-test-name test))))
2153 (let* ((thing (thing-at-point 'symbol))
2154 (sym (intern-soft thing)))
2155 (and (ert-test-boundp sym)
2156 sym))))
2158 (defun ert--results-test-at-point-no-redefinition ()
2159 "Return the test at point, or nil.
2161 To be used in the ERT results buffer."
2162 (cl-assert (eql major-mode 'ert-results-mode))
2163 (if (ert--results-test-node-or-null-at-point)
2164 (let* ((node (ert--results-test-node-at-point))
2165 (test (ert--ewoc-entry-test (ewoc-data node))))
2166 test)
2167 (let ((progress-bar-begin ert--results-progress-bar-button-begin))
2168 (when (and (<= progress-bar-begin (point))
2169 (< (point) (button-end (button-at progress-bar-begin))))
2170 (let* ((test-index (- (point) progress-bar-begin))
2171 (test (aref (ert--stats-tests ert--results-stats)
2172 test-index)))
2173 test)))))
2175 (defun ert--results-test-at-point-allow-redefinition ()
2176 "Look up the test at point, and check whether it has been redefined.
2178 To be used in the ERT results buffer.
2180 Returns a list of two elements: the test (or nil) and a symbol
2181 specifying whether the test has been redefined.
2183 If a new test has been defined with the same name as the test at
2184 point, replaces the test at point with the new test, and returns
2185 the new test and the symbol `redefined'.
2187 If the test has been deleted, returns the old test and the symbol
2188 `deleted'.
2190 If the test is still current, returns the test and the symbol nil.
2192 If there is no test at point, returns a list with two nils."
2193 (let ((test (ert--results-test-at-point-no-redefinition)))
2194 (cond ((null test)
2195 `(nil nil))
2196 ((null (ert-test-name test))
2197 `(,test nil))
2199 (let* ((name (ert-test-name test))
2200 (new-test (and (ert-test-boundp name)
2201 (ert-get-test name))))
2202 (cond ((eql test new-test)
2203 `(,test nil))
2204 ((null new-test)
2205 `(,test deleted))
2207 (ert--results-update-after-test-redefinition
2208 (ert--stats-test-pos ert--results-stats test)
2209 new-test)
2210 `(,new-test redefined))))))))
2212 (defun ert--results-update-after-test-redefinition (pos new-test)
2213 "Update results buffer after the test at pos POS has been redefined.
2215 Also updates the stats object. NEW-TEST is the new test
2216 definition."
2217 (let* ((stats ert--results-stats)
2218 (ewoc ert--results-ewoc)
2219 (node (ewoc-nth ewoc pos))
2220 (entry (ewoc-data node)))
2221 (ert--stats-set-test-and-result stats pos new-test nil)
2222 (setf (ert--ewoc-entry-test entry) new-test
2223 (aref ert--results-progress-bar-string pos) (ert-char-for-test-result
2224 nil t))
2225 (ewoc-invalidate ewoc node))
2226 nil)
2228 (defun ert--button-action-position ()
2229 "The buffer position where the last button action was triggered."
2230 (cond ((integerp last-command-event)
2231 (point))
2232 ((eventp last-command-event)
2233 (posn-point (event-start last-command-event)))
2234 (t (cl-assert nil))))
2236 (defun ert--results-progress-bar-button-action (_button)
2237 "Jump to details for the test represented by the character clicked in BUTTON."
2238 (goto-char (ert--button-action-position))
2239 (ert-results-jump-between-summary-and-result))
2241 (defun ert-results-rerun-all-tests ()
2242 "Re-run all tests, using the same selector.
2244 To be used in the ERT results buffer."
2245 (interactive)
2246 (cl-assert (eql major-mode 'ert-results-mode))
2247 (let ((selector (ert--stats-selector ert--results-stats)))
2248 (ert-run-tests-interactively selector (buffer-name))))
2250 (defun ert-results-rerun-test-at-point ()
2251 "Re-run the test at point.
2253 To be used in the ERT results buffer."
2254 (interactive)
2255 (cl-destructuring-bind (test redefinition-state)
2256 (ert--results-test-at-point-allow-redefinition)
2257 (when (null test)
2258 (error "No test at point"))
2259 (let* ((stats ert--results-stats)
2260 (progress-message (format "Running %stest %S"
2261 (cl-ecase redefinition-state
2262 ((nil) "")
2263 (redefined "new definition of ")
2264 (deleted "deleted "))
2265 (ert-test-name test))))
2266 ;; Need to save and restore point manually here: When point is on
2267 ;; the first visible ewoc entry while the header is updated, point
2268 ;; moves to the top of the buffer. This is undesirable, and a
2269 ;; simple `save-excursion' doesn't prevent it.
2270 (let ((point (point)))
2271 (unwind-protect
2272 (unwind-protect
2273 (progn
2274 (message "%s..." progress-message)
2275 (ert-run-or-rerun-test stats test
2276 ert--results-listener))
2277 (ert--results-update-stats-display ert--results-ewoc stats)
2278 (message "%s...%s"
2279 progress-message
2280 (let ((result (ert-test-most-recent-result test)))
2281 (ert-string-for-test-result
2282 result (ert-test-result-expected-p test result)))))
2283 (goto-char point))))))
2285 (defun ert-results-rerun-test-at-point-debugging-errors ()
2286 "Re-run the test at point with `ert-debug-on-error' bound to t.
2288 To be used in the ERT results buffer."
2289 (interactive)
2290 (let ((ert-debug-on-error t))
2291 (ert-results-rerun-test-at-point)))
2293 (defun ert-results-pop-to-backtrace-for-test-at-point ()
2294 "Display the backtrace for the test at point.
2296 To be used in the ERT results buffer."
2297 (interactive)
2298 (let* ((test (ert--results-test-at-point-no-redefinition))
2299 (stats ert--results-stats)
2300 (pos (ert--stats-test-pos stats test))
2301 (result (aref (ert--stats-test-results stats) pos)))
2302 (cl-etypecase result
2303 (ert-test-passed (error "Test passed, no backtrace available"))
2304 (ert-test-result-with-condition
2305 (let ((backtrace (ert-test-result-with-condition-backtrace result))
2306 (buffer (get-buffer-create "*ERT Backtrace*")))
2307 (pop-to-buffer buffer)
2308 (let ((inhibit-read-only t))
2309 (buffer-disable-undo)
2310 (erase-buffer)
2311 (ert-simple-view-mode)
2312 ;; Use unibyte because `debugger-setup-buffer' also does so.
2313 (set-buffer-multibyte nil)
2314 (setq truncate-lines t)
2315 (ert--print-backtrace backtrace)
2316 (debugger-make-xrefs)
2317 (goto-char (point-min))
2318 (insert "Backtrace for test `")
2319 (ert-insert-test-name-button (ert-test-name test))
2320 (insert "':\n")))))))
2322 (defun ert-results-pop-to-messages-for-test-at-point ()
2323 "Display the part of the *Messages* buffer generated during the test at point.
2325 To be used in the ERT results buffer."
2326 (interactive)
2327 (let* ((test (ert--results-test-at-point-no-redefinition))
2328 (stats ert--results-stats)
2329 (pos (ert--stats-test-pos stats test))
2330 (result (aref (ert--stats-test-results stats) pos)))
2331 (let ((buffer (get-buffer-create "*ERT Messages*")))
2332 (pop-to-buffer buffer)
2333 (let ((inhibit-read-only t))
2334 (buffer-disable-undo)
2335 (erase-buffer)
2336 (ert-simple-view-mode)
2337 (insert (ert-test-result-messages result))
2338 (goto-char (point-min))
2339 (insert "Messages for test `")
2340 (ert-insert-test-name-button (ert-test-name test))
2341 (insert "':\n")))))
2343 (defun ert-results-pop-to-should-forms-for-test-at-point ()
2344 "Display the list of `should' forms executed during the test at point.
2346 To be used in the ERT results buffer."
2347 (interactive)
2348 (let* ((test (ert--results-test-at-point-no-redefinition))
2349 (stats ert--results-stats)
2350 (pos (ert--stats-test-pos stats test))
2351 (result (aref (ert--stats-test-results stats) pos)))
2352 (let ((buffer (get-buffer-create "*ERT list of should forms*")))
2353 (pop-to-buffer buffer)
2354 (let ((inhibit-read-only t))
2355 (buffer-disable-undo)
2356 (erase-buffer)
2357 (ert-simple-view-mode)
2358 (if (null (ert-test-result-should-forms result))
2359 (insert "\n(No should forms during this test.)\n")
2360 (cl-loop for form-description
2361 in (ert-test-result-should-forms result)
2362 for i from 1 do
2363 (insert "\n")
2364 (insert (format "%s: " i))
2365 (let ((begin (point)))
2366 (ert--pp-with-indentation-and-newline form-description)
2367 (ert--make-xrefs-region begin (point)))))
2368 (goto-char (point-min))
2369 (insert "`should' forms executed during test `")
2370 (ert-insert-test-name-button (ert-test-name test))
2371 (insert "':\n")
2372 (insert "\n")
2373 (insert (concat "(Values are shallow copies and may have "
2374 "looked different during the test if they\n"
2375 "have been modified destructively.)\n"))
2376 (forward-line 1)))))
2378 (defun ert-results-toggle-printer-limits-for-test-at-point ()
2379 "Toggle how much of the condition to print for the test at point.
2381 To be used in the ERT results buffer."
2382 (interactive)
2383 (let* ((ewoc ert--results-ewoc)
2384 (node (ert--results-test-node-at-point))
2385 (entry (ewoc-data node)))
2386 (setf (ert--ewoc-entry-extended-printer-limits-p entry)
2387 (not (ert--ewoc-entry-extended-printer-limits-p entry)))
2388 (ewoc-invalidate ewoc node)))
2390 (defun ert-results-pop-to-timings ()
2391 "Display test timings for the last run.
2393 To be used in the ERT results buffer."
2394 (interactive)
2395 (let* ((stats ert--results-stats)
2396 (buffer (get-buffer-create "*ERT timings*"))
2397 (data (cl-loop for test across (ert--stats-tests stats)
2398 for start-time across (ert--stats-test-start-times
2399 stats)
2400 for end-time across (ert--stats-test-end-times stats)
2401 collect (list test
2402 (float-time (subtract-time
2403 end-time start-time))))))
2404 (setq data (sort data (lambda (a b)
2405 (> (cl-second a) (cl-second b)))))
2406 (pop-to-buffer buffer)
2407 (let ((inhibit-read-only t))
2408 (buffer-disable-undo)
2409 (erase-buffer)
2410 (ert-simple-view-mode)
2411 (if (null data)
2412 (insert "(No data)\n")
2413 (insert (format "%-3s %8s %8s\n" "" "time" "cumul"))
2414 (cl-loop for (test time) in data
2415 for cumul-time = time then (+ cumul-time time)
2416 for i from 1 do
2417 (progn
2418 (insert (format "%3s: %8.3f %8.3f " i time cumul-time))
2419 (ert-insert-test-name-button (ert-test-name test))
2420 (insert "\n"))))
2421 (goto-char (point-min))
2422 (insert "Tests by run time (seconds):\n\n")
2423 (forward-line 1))))
2425 ;;;###autoload
2426 (defun ert-describe-test (test-or-test-name)
2427 "Display the documentation for TEST-OR-TEST-NAME (a symbol or ert-test)."
2428 (interactive (list (ert-read-test-name-at-point "Describe test")))
2429 (when (< emacs-major-version 24)
2430 (error "Requires Emacs 24"))
2431 (let (test-name
2432 test-definition)
2433 (cl-etypecase test-or-test-name
2434 (symbol (setq test-name test-or-test-name
2435 test-definition (ert-get-test test-or-test-name)))
2436 (ert-test (setq test-name (ert-test-name test-or-test-name)
2437 test-definition test-or-test-name)))
2438 (help-setup-xref (list #'ert-describe-test test-or-test-name)
2439 (called-interactively-p 'interactive))
2440 (save-excursion
2441 (with-help-window (help-buffer)
2442 (with-current-buffer (help-buffer)
2443 (insert (if test-name (format "%S" test-name) "<anonymous test>"))
2444 (insert " is a test")
2445 (let ((file-name (and test-name
2446 (symbol-file test-name 'ert-deftest))))
2447 (when file-name
2448 (insert " defined in `" (file-name-nondirectory file-name) "'")
2449 (save-excursion
2450 (re-search-backward "`\\([^`']+\\)'" nil t)
2451 (help-xref-button 1 'help-function-def test-name file-name)))
2452 (insert ".")
2453 (fill-region-as-paragraph (point-min) (point))
2454 (insert "\n\n")
2455 (unless (and (ert-test-boundp test-name)
2456 (eql (ert-get-test test-name) test-definition))
2457 (let ((begin (point)))
2458 (insert "Note: This test has been redefined or deleted, "
2459 "this documentation refers to an old definition.")
2460 (fill-region-as-paragraph begin (point)))
2461 (insert "\n\n"))
2462 (insert (or (ert-test-documentation test-definition)
2463 "It is not documented.")
2464 "\n")))))))
2466 (defun ert-results-describe-test-at-point ()
2467 "Display the documentation of the test at point.
2469 To be used in the ERT results buffer."
2470 (interactive)
2471 (ert-describe-test (ert--results-test-at-point-no-redefinition)))
2474 ;;; Actions on load/unload.
2476 (add-to-list 'find-function-regexp-alist '(ert-deftest . ert--find-test-regexp))
2477 (add-to-list 'minor-mode-alist '(ert--current-run-stats
2478 (:eval
2479 (ert--tests-running-mode-line-indicator))))
2480 (add-to-list 'emacs-lisp-mode-hook 'ert--activate-font-lock-keywords)
2482 (defun ert--unload-function ()
2483 "Unload function to undo the side-effects of loading ert.el."
2484 (ert--remove-from-list 'find-function-regexp-alist 'ert-deftest :key #'car)
2485 (ert--remove-from-list 'minor-mode-alist 'ert--current-run-stats :key #'car)
2486 (ert--remove-from-list 'emacs-lisp-mode-hook
2487 'ert--activate-font-lock-keywords)
2488 nil)
2490 (defvar ert-unload-hook '())
2491 (add-hook 'ert-unload-hook 'ert--unload-function)
2494 (provide 'ert)
2496 ;;; ert.el ends here