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