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