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