* lisp/emacs-lisp/ert.el (describe-symbol-backends): Add ourselves
[emacs.git] / lisp / emacs-lisp / ert.el
bloba47108545d1a639a37dd582e53a633db9008d794
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)
680 (cl-defstruct (ert-test-passed (:include ert-test-result)))
681 (cl-defstruct (ert-test-result-with-condition (:include ert-test-result))
682 (condition (cl-assert nil))
683 (backtrace (cl-assert nil))
684 (infos (cl-assert nil)))
685 (cl-defstruct (ert-test-quit (:include ert-test-result-with-condition)))
686 (cl-defstruct (ert-test-failed (:include ert-test-result-with-condition)))
687 (cl-defstruct (ert-test-skipped (:include ert-test-result-with-condition)))
688 (cl-defstruct (ert-test-aborted-with-non-local-exit
689 (:include ert-test-result)))
691 (defun ert--print-backtrace (backtrace do-xrefs)
692 "Format the backtrace BACKTRACE to the current buffer."
693 (let ((print-escape-newlines t)
694 (print-level 8)
695 (print-length 50))
696 (debugger-insert-backtrace backtrace do-xrefs)))
698 ;; A container for the state of the execution of a single test and
699 ;; environment data needed during its execution.
700 (cl-defstruct ert--test-execution-info
701 (test (cl-assert nil))
702 (result (cl-assert nil))
703 ;; A thunk that may be called when RESULT has been set to its final
704 ;; value and test execution should be terminated. Should not
705 ;; return.
706 (exit-continuation (cl-assert nil))
707 ;; The binding of `debugger' outside of the execution of the test.
708 next-debugger
709 ;; The binding of `ert-debug-on-error' that is in effect for the
710 ;; execution of the current test. We store it to avoid being
711 ;; affected by any new bindings the test itself may establish. (I
712 ;; don't remember whether this feature is important.)
713 ert-debug-on-error)
715 (defun ert--run-test-debugger (info args)
716 "During a test run, `debugger' is bound to a closure that calls this function.
718 This function records failures and errors and either terminates
719 the test silently or calls the interactive debugger, as
720 appropriate.
722 INFO is the ert--test-execution-info corresponding to this test
723 run. ARGS are the arguments to `debugger'."
724 (cl-destructuring-bind (first-debugger-arg &rest more-debugger-args)
725 args
726 (cl-ecase first-debugger-arg
727 ((lambda debug t exit nil)
728 (apply (ert--test-execution-info-next-debugger info) args))
729 (error
730 (let* ((condition (car more-debugger-args))
731 (type (cl-case (car condition)
732 ((quit) 'quit)
733 ((ert-test-skipped) 'skipped)
734 (otherwise 'failed)))
735 ;; We store the backtrace in the result object for
736 ;; `ert-results-pop-to-backtrace-for-test-at-point'.
737 ;; This means we have to limit `print-level' and
738 ;; `print-length' when printing result objects. That
739 ;; might not be worth while when we can also use
740 ;; `ert-results-rerun-test-debugging-errors-at-point',
741 ;; (i.e., when running interactively) but having the
742 ;; backtrace ready for printing is important for batch
743 ;; use.
745 ;; Grab the frames above the debugger.
746 (backtrace (cdr (backtrace-frames debugger)))
747 (infos (reverse ert--infos)))
748 (setf (ert--test-execution-info-result info)
749 (cl-ecase type
750 (quit
751 (make-ert-test-quit :condition condition
752 :backtrace backtrace
753 :infos infos))
754 (skipped
755 (make-ert-test-skipped :condition condition
756 :backtrace backtrace
757 :infos infos))
758 (failed
759 (make-ert-test-failed :condition condition
760 :backtrace backtrace
761 :infos infos))))
762 ;; Work around Emacs's heuristic (in eval.c) for detecting
763 ;; errors in the debugger.
764 (cl-incf num-nonmacro-input-events)
765 ;; FIXME: We should probably implement more fine-grained
766 ;; control a la non-t `debug-on-error' here.
767 (cond
768 ((ert--test-execution-info-ert-debug-on-error info)
769 (apply (ert--test-execution-info-next-debugger info) args))
770 (t))
771 (funcall (ert--test-execution-info-exit-continuation info)))))))
773 (defun ert--run-test-internal (test-execution-info)
774 "Low-level function to run a test according to TEST-EXECUTION-INFO.
776 This mainly sets up debugger-related bindings."
777 (setf (ert--test-execution-info-next-debugger test-execution-info) debugger
778 (ert--test-execution-info-ert-debug-on-error test-execution-info)
779 ert-debug-on-error)
780 (catch 'ert--pass
781 ;; For now, each test gets its own temp buffer and its own
782 ;; window excursion, just to be safe. If this turns out to be
783 ;; too expensive, we can remove it.
784 (with-temp-buffer
785 (save-window-excursion
786 ;; FIXME: Use `signal-hook-function' instead of `debugger' to
787 ;; handle ert errors. Once that's done, remove
788 ;; `ert--should-signal-hook'. See Bug#24402 and Bug#11218 for
789 ;; details.
790 (let ((debugger (lambda (&rest args)
791 (ert--run-test-debugger test-execution-info
792 args)))
793 (debug-on-error t)
794 (debug-on-quit t)
795 ;; FIXME: Do we need to store the old binding of this
796 ;; and consider it in `ert--run-test-debugger'?
797 (debug-ignored-errors nil)
798 (ert--infos '()))
799 (funcall (ert-test-body (ert--test-execution-info-test
800 test-execution-info))))))
801 (ert-pass))
802 (setf (ert--test-execution-info-result test-execution-info)
803 (make-ert-test-passed))
804 nil)
806 (defun ert--force-message-log-buffer-truncation ()
807 "Immediately truncate *Messages* buffer according to `message-log-max'.
809 This can be useful after reducing the value of `message-log-max'."
810 (with-current-buffer (messages-buffer)
811 ;; This is a reimplementation of this part of message_dolog() in xdisp.c:
812 ;; if (NATNUMP (Vmessage_log_max))
813 ;; {
814 ;; scan_newline (Z, Z_BYTE, BEG, BEG_BYTE,
815 ;; -XFASTINT (Vmessage_log_max) - 1, 0);
816 ;; del_range_both (BEG, BEG_BYTE, PT, PT_BYTE, 0);
817 ;; }
818 (when (and (integerp message-log-max) (>= message-log-max 0))
819 (let ((begin (point-min))
820 (end (save-excursion
821 (goto-char (point-max))
822 (forward-line (- message-log-max))
823 (point)))
824 (inhibit-read-only t))
825 (delete-region begin end)))))
827 (defvar ert--running-tests nil
828 "List of tests that are currently in execution.
830 This list is empty while no test is running, has one element
831 while a test is running, two elements while a test run from
832 inside a test is running, etc. The list is in order of nesting,
833 innermost test first.
835 The elements are of type `ert-test'.")
837 (defun ert-run-test (ert-test)
838 "Run ERT-TEST.
840 Returns the result and stores it in ERT-TEST's `most-recent-result' slot."
841 (setf (ert-test-most-recent-result ert-test) nil)
842 (cl-block error
843 (let ((begin-marker
844 (with-current-buffer (messages-buffer)
845 (point-max-marker))))
846 (unwind-protect
847 (let ((info (make-ert--test-execution-info
848 :test ert-test
849 :result
850 (make-ert-test-aborted-with-non-local-exit)
851 :exit-continuation (lambda ()
852 (cl-return-from error nil))))
853 (should-form-accu (list)))
854 (unwind-protect
855 (let ((ert--should-execution-observer
856 (lambda (form-description)
857 (push form-description should-form-accu)))
858 (message-log-max t)
859 (ert--running-tests (cons ert-test ert--running-tests)))
860 (ert--run-test-internal info))
861 (let ((result (ert--test-execution-info-result info)))
862 (setf (ert-test-result-messages result)
863 (with-current-buffer (messages-buffer)
864 (buffer-substring begin-marker (point-max))))
865 (ert--force-message-log-buffer-truncation)
866 (setq should-form-accu (nreverse should-form-accu))
867 (setf (ert-test-result-should-forms result)
868 should-form-accu)
869 (setf (ert-test-most-recent-result ert-test) result))))
870 (set-marker begin-marker nil))))
871 (ert-test-most-recent-result ert-test))
873 (defun ert-running-test ()
874 "Return the top-level test currently executing."
875 (car (last ert--running-tests)))
878 ;;; Test selectors.
880 (defun ert-test-result-type-p (result result-type)
881 "Return non-nil if RESULT matches type RESULT-TYPE.
883 Valid result types:
885 nil -- Never matches.
886 t -- Always matches.
887 :failed, :passed, :skipped -- Matches corresponding results.
888 \(and TYPES...) -- Matches if all TYPES match.
889 \(or TYPES...) -- Matches if some TYPES match.
890 \(not TYPE) -- Matches if TYPE does not match.
891 \(satisfies PREDICATE) -- Matches if PREDICATE returns true when called with
892 RESULT."
893 ;; It would be easy to add `member' and `eql' types etc., but I
894 ;; haven't bothered yet.
895 (pcase-exhaustive result-type
896 ('nil nil)
897 ('t t)
898 (:failed (ert-test-failed-p result))
899 (:passed (ert-test-passed-p result))
900 (:skipped (ert-test-skipped-p result))
901 (`(,operator . ,operands)
902 (cl-ecase operator
903 (and
904 (cl-case (length operands)
905 (0 t)
907 (and (ert-test-result-type-p result (car operands))
908 (ert-test-result-type-p result `(and ,@(cdr operands)))))))
910 (cl-case (length operands)
911 (0 nil)
913 (or (ert-test-result-type-p result (car operands))
914 (ert-test-result-type-p result `(or ,@(cdr operands)))))))
915 (not
916 (cl-assert (eql (length operands) 1))
917 (not (ert-test-result-type-p result (car operands))))
918 (satisfies
919 (cl-assert (eql (length operands) 1))
920 (funcall (car operands) result))))))
922 (defun ert-test-result-expected-p (test result)
923 "Return non-nil if TEST's expected result type matches RESULT."
925 (ert-test-result-type-p result :skipped)
926 (ert-test-result-type-p result (ert-test-expected-result-type test))))
928 (defun ert-select-tests (selector universe)
929 "Return a list of tests that match SELECTOR.
931 UNIVERSE specifies the set of tests to select from; it should be a list
932 of tests, or t, which refers to all tests named by symbols in `obarray'.
934 Valid SELECTORs:
936 nil -- Selects the empty set.
937 t -- Selects UNIVERSE.
938 :new -- Selects all tests that have not been run yet.
939 :failed, :passed -- Select tests according to their most recent result.
940 :expected, :unexpected -- Select tests according to their most recent result.
941 a string -- A regular expression selecting all tests with matching names.
942 a test -- (i.e., an object of the ert-test data-type) Selects that test.
943 a symbol -- Selects the test that the symbol names, errors if none.
944 \(member TESTS...) -- Selects the elements of TESTS, a list of tests
945 or symbols naming tests.
946 \(eql TEST) -- Selects TEST, a test or a symbol naming a test.
947 \(and SELECTORS...) -- Selects the tests that match all SELECTORS.
948 \(or SELECTORS...) -- Selects the tests that match any of the SELECTORS.
949 \(not SELECTOR) -- Selects all tests that do not match SELECTOR.
950 \(tag TAG) -- Selects all tests that have TAG on their tags list.
951 A tag is an arbitrary label you can apply when you define a test.
952 \(satisfies PREDICATE) -- Selects all tests that satisfy PREDICATE.
953 PREDICATE is a function that takes an ert-test object as argument,
954 and returns non-nil if it is selected.
956 Only selectors that require a superset of tests, such
957 as (satisfies ...), strings, :new, etc. make use of UNIVERSE.
958 Selectors that do not, such as (member ...), just return the
959 set implied by them without checking whether it is really
960 contained in UNIVERSE."
961 ;; This code needs to match the cases in
962 ;; `ert-insert-human-readable-selector'.
963 (pcase-exhaustive selector
964 ('nil nil)
965 ('t (pcase-exhaustive universe
966 ((pred listp) universe)
967 (`t (ert-select-tests "" universe))))
968 (:new (ert-select-tests
969 `(satisfies ,(lambda (test)
970 (null (ert-test-most-recent-result test))))
971 universe))
972 (:failed (ert-select-tests
973 `(satisfies ,(lambda (test)
974 (ert-test-result-type-p
975 (ert-test-most-recent-result test)
976 ':failed)))
977 universe))
978 (:passed (ert-select-tests
979 `(satisfies ,(lambda (test)
980 (ert-test-result-type-p
981 (ert-test-most-recent-result test)
982 ':passed)))
983 universe))
984 (:expected (ert-select-tests
985 `(satisfies
986 ,(lambda (test)
987 (ert-test-result-expected-p
988 test
989 (ert-test-most-recent-result test))))
990 universe))
991 (:unexpected (ert-select-tests `(not :expected) universe))
992 ((pred stringp)
993 (pcase-exhaustive universe
994 (`t (mapcar #'ert-get-test
995 (apropos-internal selector #'ert-test-boundp)))
996 ((pred listp)
997 (cl-remove-if-not (lambda (test)
998 (and (ert-test-name test)
999 (string-match selector
1000 (symbol-name
1001 (ert-test-name test)))))
1002 universe))))
1003 ((pred ert-test-p) (list selector))
1004 ((pred symbolp)
1005 (cl-assert (ert-test-boundp selector))
1006 (list (ert-get-test selector)))
1007 (`(,operator . ,operands)
1008 (cl-ecase operator
1009 (member
1010 (mapcar (lambda (purported-test)
1011 (pcase-exhaustive purported-test
1012 ((pred symbolp)
1013 (cl-assert (ert-test-boundp purported-test))
1014 (ert-get-test purported-test))
1015 ((pred ert-test-p) purported-test)))
1016 operands))
1017 (eql
1018 (cl-assert (eql (length operands) 1))
1019 (ert-select-tests `(member ,@operands) universe))
1020 (and
1021 ;; Do these definitions of AND, NOT and OR satisfy de
1022 ;; Morgan's laws? Should they?
1023 (cl-case (length operands)
1024 (0 (ert-select-tests 't universe))
1025 (t (ert-select-tests `(and ,@(cdr operands))
1026 (ert-select-tests (car operands)
1027 universe)))))
1028 (not
1029 (cl-assert (eql (length operands) 1))
1030 (let ((all-tests (ert-select-tests 't universe)))
1031 (cl-set-difference all-tests
1032 (ert-select-tests (car operands)
1033 all-tests))))
1035 (cl-case (length operands)
1036 (0 (ert-select-tests 'nil universe))
1037 (t (cl-union (ert-select-tests (car operands) universe)
1038 (ert-select-tests `(or ,@(cdr operands))
1039 universe)))))
1040 (tag
1041 (cl-assert (eql (length operands) 1))
1042 (let ((tag (car operands)))
1043 (ert-select-tests `(satisfies
1044 ,(lambda (test)
1045 (member tag (ert-test-tags test))))
1046 universe)))
1047 (satisfies
1048 (cl-assert (eql (length operands) 1))
1049 (cl-remove-if-not (car operands)
1050 (ert-select-tests 't universe)))))))
1052 (defun ert--insert-human-readable-selector (selector)
1053 "Insert a human-readable presentation of SELECTOR into the current buffer."
1054 ;; This is needed to avoid printing the (huge) contents of the
1055 ;; `backtrace' slot of the result objects in the
1056 ;; `most-recent-result' slots of test case objects in (eql ...) or
1057 ;; (member ...) selectors.
1058 (cl-labels ((rec (selector)
1059 ;; This code needs to match the cases in
1060 ;; `ert-select-tests'.
1061 (pcase-exhaustive selector
1062 ((or
1063 ;; 'nil 't :new :failed :passed :expected :unexpected
1064 (pred stringp)
1065 (pred symbolp))
1066 selector)
1067 ((pred ert-test-p)
1068 (if (ert-test-name selector)
1069 (make-symbol (format "<%S>" (ert-test-name selector)))
1070 (make-symbol "<unnamed test>")))
1071 (`(,operator . ,operands)
1072 (pcase operator
1073 ((or 'member 'eql 'and 'not 'or)
1074 `(,operator ,@(mapcar #'rec operands)))
1075 ((or 'tag 'satisfies)
1076 selector))))))
1077 (insert (format "%S" (rec selector)))))
1080 ;;; Facilities for running a whole set of tests.
1082 ;; The data structure that contains the set of tests being executed
1083 ;; during one particular test run, their results, the state of the
1084 ;; execution, and some statistics.
1086 ;; The data about results and expected results of tests may seem
1087 ;; redundant here, since the test objects also carry such information.
1088 ;; However, the information in the test objects may be more recent, it
1089 ;; may correspond to a different test run. We need the information
1090 ;; that corresponds to this run in order to be able to update the
1091 ;; statistics correctly when a test is re-run interactively and has a
1092 ;; different result than before.
1093 (cl-defstruct ert--stats
1094 (selector (cl-assert nil))
1095 ;; The tests, in order.
1096 (tests (cl-assert nil) :type vector)
1097 ;; A map of test names (or the test objects themselves for unnamed
1098 ;; tests) to indices into the `tests' vector.
1099 (test-map (cl-assert nil) :type hash-table)
1100 ;; The results of the tests during this run, in order.
1101 (test-results (cl-assert nil) :type vector)
1102 ;; The start times of the tests, in order, as reported by
1103 ;; `current-time'.
1104 (test-start-times (cl-assert nil) :type vector)
1105 ;; The end times of the tests, in order, as reported by
1106 ;; `current-time'.
1107 (test-end-times (cl-assert nil) :type vector)
1108 (passed-expected 0)
1109 (passed-unexpected 0)
1110 (failed-expected 0)
1111 (failed-unexpected 0)
1112 (skipped 0)
1113 (start-time nil)
1114 (end-time nil)
1115 (aborted-p nil)
1116 (current-test nil)
1117 ;; The time at or after which the next redisplay should occur, as a
1118 ;; float.
1119 (next-redisplay 0.0))
1121 (defun ert-stats-completed-expected (stats)
1122 "Return the number of tests in STATS that had expected results."
1123 (+ (ert--stats-passed-expected stats)
1124 (ert--stats-failed-expected stats)))
1126 (defun ert-stats-completed-unexpected (stats)
1127 "Return the number of tests in STATS that had unexpected results."
1128 (+ (ert--stats-passed-unexpected stats)
1129 (ert--stats-failed-unexpected stats)))
1131 (defun ert-stats-skipped (stats)
1132 "Number of tests in STATS that have skipped."
1133 (ert--stats-skipped stats))
1135 (defun ert-stats-completed (stats)
1136 "Number of tests in STATS that have run so far."
1137 (+ (ert-stats-completed-expected stats)
1138 (ert-stats-completed-unexpected stats)
1139 (ert-stats-skipped stats)))
1141 (defun ert-stats-total (stats)
1142 "Number of tests in STATS, regardless of whether they have run yet."
1143 (length (ert--stats-tests stats)))
1145 ;; The stats object of the current run, dynamically bound. This is
1146 ;; used for the mode line progress indicator.
1147 (defvar ert--current-run-stats nil)
1149 (defun ert--stats-test-key (test)
1150 "Return the key used for TEST in the test map of ert--stats objects.
1152 Returns the name of TEST if it has one, or TEST itself otherwise."
1153 (or (ert-test-name test) test))
1155 (defun ert--stats-set-test-and-result (stats pos test result)
1156 "Change STATS by replacing the test at position POS with TEST and RESULT.
1158 Also changes the counters in STATS to match."
1159 (let* ((tests (ert--stats-tests stats))
1160 (results (ert--stats-test-results stats))
1161 (old-test (aref tests pos))
1162 (map (ert--stats-test-map stats)))
1163 (cl-flet ((update (d)
1164 (if (ert-test-result-expected-p (aref tests pos)
1165 (aref results pos))
1166 (cl-etypecase (aref results pos)
1167 (ert-test-passed
1168 (cl-incf (ert--stats-passed-expected stats) d))
1169 (ert-test-failed
1170 (cl-incf (ert--stats-failed-expected stats) d))
1171 (ert-test-skipped
1172 (cl-incf (ert--stats-skipped stats) d))
1173 (null)
1174 (ert-test-aborted-with-non-local-exit)
1175 (ert-test-quit))
1176 (cl-etypecase (aref results pos)
1177 (ert-test-passed
1178 (cl-incf (ert--stats-passed-unexpected stats) d))
1179 (ert-test-failed
1180 (cl-incf (ert--stats-failed-unexpected stats) d))
1181 (ert-test-skipped
1182 (cl-incf (ert--stats-skipped stats) d))
1183 (null)
1184 (ert-test-aborted-with-non-local-exit)
1185 (ert-test-quit)))))
1186 ;; Adjust counters to remove the result that is currently in stats.
1187 (update -1)
1188 ;; Put new test and result into stats.
1189 (setf (aref tests pos) test
1190 (aref results pos) result)
1191 (remhash (ert--stats-test-key old-test) map)
1192 (setf (gethash (ert--stats-test-key test) map) pos)
1193 ;; Adjust counters to match new result.
1194 (update +1)
1195 nil)))
1197 (defun ert--make-stats (tests selector)
1198 "Create a new `ert--stats' object for running TESTS.
1200 SELECTOR is the selector that was used to select TESTS."
1201 (setq tests (cl-coerce tests 'vector))
1202 (let ((map (make-hash-table :size (length tests))))
1203 (cl-loop for i from 0
1204 for test across tests
1205 for key = (ert--stats-test-key test) do
1206 (cl-assert (not (gethash key map)))
1207 (setf (gethash key map) i))
1208 (make-ert--stats :selector selector
1209 :tests tests
1210 :test-map map
1211 :test-results (make-vector (length tests) nil)
1212 :test-start-times (make-vector (length tests) nil)
1213 :test-end-times (make-vector (length tests) nil))))
1215 (defun ert-run-or-rerun-test (stats test listener)
1216 ;; checkdoc-order: nil
1217 "Run the single test TEST and record the result using STATS and LISTENER."
1218 (let ((ert--current-run-stats stats)
1219 (pos (ert--stats-test-pos stats test)))
1220 (ert--stats-set-test-and-result stats pos test nil)
1221 ;; Call listener after setting/before resetting
1222 ;; (ert--stats-current-test stats); the listener might refresh the
1223 ;; mode line display, and if the value is not set yet/any more
1224 ;; during this refresh, the mode line will flicker unnecessarily.
1225 (setf (ert--stats-current-test stats) test)
1226 (funcall listener 'test-started stats test)
1227 (setf (ert-test-most-recent-result test) nil)
1228 (setf (aref (ert--stats-test-start-times stats) pos) (current-time))
1229 (unwind-protect
1230 (ert-run-test test)
1231 (setf (aref (ert--stats-test-end-times stats) pos) (current-time))
1232 (let ((result (ert-test-most-recent-result test)))
1233 (ert--stats-set-test-and-result stats pos test result)
1234 (funcall listener 'test-ended stats test result))
1235 (setf (ert--stats-current-test stats) nil))))
1237 (defun ert-run-tests (selector listener &optional interactively)
1238 "Run the tests specified by SELECTOR, sending progress updates to LISTENER."
1239 (let* ((tests (ert-select-tests selector t))
1240 (stats (ert--make-stats tests selector)))
1241 (setf (ert--stats-start-time stats) (current-time))
1242 (funcall listener 'run-started stats)
1243 (let ((abortedp t))
1244 (unwind-protect
1245 (let ((ert--current-run-stats stats))
1246 (force-mode-line-update)
1247 (unwind-protect
1248 (cl-loop for test in tests do
1249 (ert-run-or-rerun-test stats test listener)
1250 (when (and interactively
1251 (ert-test-quit-p
1252 (ert-test-most-recent-result test))
1253 (y-or-n-p "Abort testing? "))
1254 (cl-return))
1255 finally (setq abortedp nil))
1256 (setf (ert--stats-aborted-p stats) abortedp)
1257 (setf (ert--stats-end-time stats) (current-time))
1258 (funcall listener 'run-ended stats abortedp)))
1259 (force-mode-line-update))
1260 stats)))
1262 (defun ert--stats-test-pos (stats test)
1263 ;; checkdoc-order: nil
1264 "Return the position (index) of TEST in the run represented by STATS."
1265 (gethash (ert--stats-test-key test) (ert--stats-test-map stats)))
1268 ;;; Formatting functions shared across UIs.
1270 (defun ert--format-time-iso8601 (time)
1271 "Format TIME in the variant of ISO 8601 used for timestamps in ERT."
1272 (format-time-string "%Y-%m-%d %T%z" time))
1274 (defun ert-char-for-test-result (result expectedp)
1275 "Return a character that represents the test result RESULT.
1277 EXPECTEDP specifies whether the result was expected."
1278 (let ((s (cl-etypecase result
1279 (ert-test-passed ".P")
1280 (ert-test-failed "fF")
1281 (ert-test-skipped "sS")
1282 (null "--")
1283 (ert-test-aborted-with-non-local-exit "aA")
1284 (ert-test-quit "qQ"))))
1285 (elt s (if expectedp 0 1))))
1287 (defun ert-string-for-test-result (result expectedp)
1288 "Return a string that represents the test result RESULT.
1290 EXPECTEDP specifies whether the result was expected."
1291 (let ((s (cl-etypecase result
1292 (ert-test-passed '("passed" "PASSED"))
1293 (ert-test-failed '("failed" "FAILED"))
1294 (ert-test-skipped '("skipped" "SKIPPED"))
1295 (null '("unknown" "UNKNOWN"))
1296 (ert-test-aborted-with-non-local-exit '("aborted" "ABORTED"))
1297 (ert-test-quit '("quit" "QUIT")))))
1298 (elt s (if expectedp 0 1))))
1300 (defun ert--pp-with-indentation-and-newline (object)
1301 "Pretty-print OBJECT, indenting it to the current column of point.
1302 Ensures a final newline is inserted."
1303 (let ((begin (point))
1304 (pp-escape-newlines nil))
1305 (pp object (current-buffer))
1306 (unless (bolp) (insert "\n"))
1307 (save-excursion
1308 (goto-char begin)
1309 (indent-sexp))))
1311 (defun ert--insert-infos (result)
1312 "Insert `ert-info' infos from RESULT into current buffer.
1314 RESULT must be an `ert-test-result-with-condition'."
1315 (cl-check-type result ert-test-result-with-condition)
1316 (dolist (info (ert-test-result-with-condition-infos result))
1317 (cl-destructuring-bind (prefix . message) info
1318 (let ((begin (point))
1319 (indentation (make-string (+ (length prefix) 4) ?\s))
1320 (end nil))
1321 (unwind-protect
1322 (progn
1323 (insert message "\n")
1324 (setq end (point-marker))
1325 (goto-char begin)
1326 (insert " " prefix)
1327 (forward-line 1)
1328 (while (< (point) end)
1329 (insert indentation)
1330 (forward-line 1)))
1331 (when end (set-marker end nil)))))))
1334 ;;; Running tests in batch mode.
1336 (defvar ert-quiet nil
1337 "Non-nil makes ERT only print important information in batch mode.")
1339 ;;;###autoload
1340 (defun ert-run-tests-batch (&optional selector)
1341 "Run the tests specified by SELECTOR, printing results to the terminal.
1343 SELECTOR works as described in `ert-select-tests', except if
1344 SELECTOR is nil, in which case all tests rather than none will be
1345 run; this makes the command line \"emacs -batch -l my-tests.el -f
1346 ert-run-tests-batch-and-exit\" useful.
1348 Returns the stats object."
1349 (unless selector (setq selector 't))
1350 (ert-run-tests
1351 selector
1352 (lambda (event-type &rest event-args)
1353 (cl-ecase event-type
1354 (run-started
1355 (unless ert-quiet
1356 (cl-destructuring-bind (stats) event-args
1357 (message "Running %s tests (%s)"
1358 (length (ert--stats-tests stats))
1359 (ert--format-time-iso8601 (ert--stats-start-time stats))))))
1360 (run-ended
1361 (cl-destructuring-bind (stats abortedp) event-args
1362 (let ((unexpected (ert-stats-completed-unexpected stats))
1363 (skipped (ert-stats-skipped stats))
1364 (expected-failures (ert--stats-failed-expected stats)))
1365 (message "\n%sRan %s tests, %s results as expected%s%s (%s)%s\n"
1366 (if (not abortedp)
1368 "Aborted: ")
1369 (ert-stats-total stats)
1370 (ert-stats-completed-expected stats)
1371 (if (zerop unexpected)
1373 (format ", %s unexpected" unexpected))
1374 (if (zerop skipped)
1376 (format ", %s skipped" skipped))
1377 (ert--format-time-iso8601 (ert--stats-end-time stats))
1378 (if (zerop expected-failures)
1380 (format "\n%s expected failures" expected-failures)))
1381 (unless (zerop unexpected)
1382 (message "%s unexpected results:" unexpected)
1383 (cl-loop for test across (ert--stats-tests stats)
1384 for result = (ert-test-most-recent-result test) do
1385 (when (not (ert-test-result-expected-p test result))
1386 (message "%9s %S"
1387 (ert-string-for-test-result result nil)
1388 (ert-test-name test))))
1389 (message "%s" ""))
1390 (unless (zerop skipped)
1391 (message "%s skipped results:" skipped)
1392 (cl-loop for test across (ert--stats-tests stats)
1393 for result = (ert-test-most-recent-result test) do
1394 (when (ert-test-result-type-p result :skipped)
1395 (message "%9s %S"
1396 (ert-string-for-test-result result nil)
1397 (ert-test-name test))))
1398 (message "%s" "")))))
1399 (test-started
1401 (test-ended
1402 (cl-destructuring-bind (stats test result) event-args
1403 (unless (ert-test-result-expected-p test result)
1404 (cl-etypecase result
1405 (ert-test-passed
1406 (message "Test %S passed unexpectedly" (ert-test-name test)))
1407 (ert-test-result-with-condition
1408 (message "Test %S backtrace:" (ert-test-name test))
1409 (with-temp-buffer
1410 (ert--print-backtrace
1411 (ert-test-result-with-condition-backtrace result)
1412 nil)
1413 (if (not ert-batch-backtrace-right-margin)
1414 (message "%s"
1415 (buffer-substring-no-properties (point-min)
1416 (point-max)))
1417 (goto-char (point-min))
1418 (while (not (eobp))
1419 (let ((start (point))
1420 (end (line-end-position)))
1421 (setq end (min end
1422 (+ start
1423 ert-batch-backtrace-right-margin)))
1424 (message "%s" (buffer-substring-no-properties
1425 start end)))
1426 (forward-line 1))))
1427 (with-temp-buffer
1428 (ert--insert-infos result)
1429 (insert " ")
1430 (let ((print-escape-newlines t)
1431 (print-level 5)
1432 (print-length 10))
1433 (ert--pp-with-indentation-and-newline
1434 (ert-test-result-with-condition-condition result)))
1435 (goto-char (1- (point-max)))
1436 (cl-assert (looking-at "\n"))
1437 (delete-char 1)
1438 (message "Test %S condition:" (ert-test-name test))
1439 (message "%s" (buffer-string))))
1440 (ert-test-aborted-with-non-local-exit
1441 (message "Test %S aborted with non-local exit"
1442 (ert-test-name test)))
1443 (ert-test-quit
1444 (message "Quit during %S" (ert-test-name test)))))
1445 (unless ert-quiet
1446 (let* ((max (prin1-to-string (length (ert--stats-tests stats))))
1447 (format-string (concat "%9s %"
1448 (prin1-to-string (length max))
1449 "s/" max " %S")))
1450 (message format-string
1451 (ert-string-for-test-result result
1452 (ert-test-result-expected-p
1453 test result))
1454 (1+ (ert--stats-test-pos stats test))
1455 (ert-test-name test))))))))
1456 nil))
1458 ;;;###autoload
1459 (defun ert-run-tests-batch-and-exit (&optional selector)
1460 "Like `ert-run-tests-batch', but exits Emacs when done.
1462 The exit status will be 0 if all test results were as expected, 1
1463 on unexpected results, or 2 if the tool detected an error outside
1464 of the tests (e.g. invalid SELECTOR or bug in the code that runs
1465 the tests)."
1466 (or noninteractive
1467 (user-error "This function is only for use in batch mode"))
1468 ;; Better crash loudly than attempting to recover from undefined
1469 ;; behavior.
1470 (setq attempt-stack-overflow-recovery nil
1471 attempt-orderly-shutdown-on-fatal-signal nil)
1472 (unwind-protect
1473 (let ((stats (ert-run-tests-batch selector)))
1474 (kill-emacs (if (zerop (ert-stats-completed-unexpected stats)) 0 1)))
1475 (unwind-protect
1476 (progn
1477 (message "Error running tests")
1478 (backtrace))
1479 (kill-emacs 2))))
1482 (defun ert-summarize-tests-batch-and-exit ()
1483 "Summarize the results of testing.
1484 Expects to be called in batch mode, with logfiles as command-line arguments.
1485 The logfiles should have the `ert-run-tests-batch' format. When finished,
1486 this exits Emacs, with status as per `ert-run-tests-batch-and-exit'."
1487 (or noninteractive
1488 (user-error "This function is only for use in batch mode"))
1489 ;; Better crash loudly than attempting to recover from undefined
1490 ;; behavior.
1491 (setq attempt-stack-overflow-recovery nil
1492 attempt-orderly-shutdown-on-fatal-signal nil)
1493 (let ((nlogs (length command-line-args-left))
1494 (ntests 0) (nrun 0) (nexpected 0) (nunexpected 0) (nskipped 0)
1495 nnotrun logfile notests badtests unexpected skipped)
1496 (with-temp-buffer
1497 (while (setq logfile (pop command-line-args-left))
1498 (erase-buffer)
1499 (when (file-readable-p logfile) (insert-file-contents logfile))
1500 (if (not (re-search-forward "^Running \\([0-9]+\\) tests" nil t))
1501 (push logfile notests)
1502 (setq ntests (+ ntests (string-to-number (match-string 1))))
1503 (if (not (re-search-forward "^\\(Aborted: \\)?\
1504 Ran \\([0-9]+\\) tests, \\([0-9]+\\) results as expected\
1505 \\(?:, \\([0-9]+\\) unexpected\\)?\
1506 \\(?:, \\([0-9]+\\) skipped\\)?" nil t))
1507 (push logfile badtests)
1508 (if (match-string 1) (push logfile badtests))
1509 (setq nrun (+ nrun (string-to-number (match-string 2)))
1510 nexpected (+ nexpected (string-to-number (match-string 3))))
1511 (when (match-string 4)
1512 (push logfile unexpected)
1513 (setq nunexpected (+ nunexpected
1514 (string-to-number (match-string 4)))))
1515 (when (match-string 5)
1516 (push logfile skipped)
1517 (setq nskipped (+ nskipped
1518 (string-to-number (match-string 5)))))))))
1519 (setq nnotrun (- ntests nrun))
1520 (message "\nSUMMARY OF TEST RESULTS")
1521 (message "-----------------------")
1522 (message "Files examined: %d" nlogs)
1523 (message "Ran %d tests%s, %d results as expected%s%s"
1524 nrun
1525 (if (zerop nnotrun) "" (format ", %d failed to run" nnotrun))
1526 nexpected
1527 (if (zerop nunexpected)
1529 (format ", %d unexpected" nunexpected))
1530 (if (zerop nskipped)
1532 (format ", %d skipped" nskipped)))
1533 (when notests
1534 (message "%d files did not contain any tests:" (length notests))
1535 (mapc (lambda (l) (message " %s" l)) notests))
1536 (when badtests
1537 (message "%d files did not finish:" (length badtests))
1538 (mapc (lambda (l) (message " %s" l)) badtests))
1539 (when unexpected
1540 (message "%d files contained unexpected results:" (length unexpected))
1541 (mapc (lambda (l) (message " %s" l)) unexpected))
1542 ;; More details on hydra, where the logs are harder to get to.
1543 (when (and (getenv "EMACS_HYDRA_CI")
1544 (not (zerop (+ nunexpected nskipped))))
1545 (message "\nDETAILS")
1546 (message "-------")
1547 (with-temp-buffer
1548 (dolist (x (list (list skipped "skipped" "SKIPPED")
1549 (list unexpected "unexpected" "FAILED")))
1550 (mapc (lambda (l)
1551 (erase-buffer)
1552 (insert-file-contents l)
1553 (message "%s:" l)
1554 (when (re-search-forward (format "^[ \t]*[0-9]+ %s results:"
1555 (nth 1 x))
1556 nil t)
1557 (while (and (zerop (forward-line 1))
1558 (looking-at (format "^[ \t]*%s" (nth 2 x))))
1559 (message "%s" (buffer-substring (line-beginning-position)
1560 (line-end-position))))))
1561 (car x)))))
1562 (kill-emacs (cond ((or notests badtests (not (zerop nnotrun))) 2)
1563 (unexpected 1)
1564 (t 0)))))
1566 ;;; Utility functions for load/unload actions.
1568 (defun ert--activate-font-lock-keywords ()
1569 "Activate font-lock keywords for some of ERT's symbols."
1570 (font-lock-add-keywords
1572 '(("(\\(\\<ert-deftest\\)\\>\\s *\\(\\(?:\\sw\\|\\s_\\)+\\)?"
1573 (1 font-lock-keyword-face nil t)
1574 (2 font-lock-function-name-face nil t)))))
1576 (cl-defun ert--remove-from-list (list-var element &key key test)
1577 "Remove ELEMENT from the value of LIST-VAR if present.
1579 This can be used as an inverse of `add-to-list'."
1580 (unless key (setq key #'identity))
1581 (unless test (setq test #'equal))
1582 (setf (symbol-value list-var)
1583 (cl-remove element
1584 (symbol-value list-var)
1585 :key key
1586 :test test)))
1589 ;;; Some basic interactive functions.
1591 (defun ert-read-test-name (prompt &optional default history
1592 add-default-to-prompt)
1593 "Read the name of a test and return it as a symbol.
1595 Prompt with PROMPT. If DEFAULT is a valid test name, use it as a
1596 default. HISTORY is the history to use; see `completing-read'.
1597 If ADD-DEFAULT-TO-PROMPT is non-nil, PROMPT will be modified to
1598 include the default, if any.
1600 Signals an error if no test name was read."
1601 (cl-etypecase default
1602 (string (let ((symbol (intern-soft default)))
1603 (unless (and symbol (ert-test-boundp symbol))
1604 (setq default nil))))
1605 (symbol (setq default
1606 (if (ert-test-boundp default)
1607 (symbol-name default)
1608 nil)))
1609 (ert-test (setq default (ert-test-name default))))
1610 (when add-default-to-prompt
1611 (setq prompt (if (null default)
1612 (format "%s: " prompt)
1613 (format "%s (default %s): " prompt default))))
1614 (let ((input (completing-read prompt obarray #'ert-test-boundp
1615 t nil history default nil)))
1616 ;; completing-read returns an empty string if default was nil and
1617 ;; the user just hit enter.
1618 (let ((sym (intern-soft input)))
1619 (if (ert-test-boundp sym)
1621 (user-error "Input does not name a test")))))
1623 (defun ert-read-test-name-at-point (prompt)
1624 "Read the name of a test and return it as a symbol.
1625 As a default, use the symbol at point, or the test at point if in
1626 the ERT results buffer. Prompt with PROMPT, augmented with the
1627 default (if any)."
1628 (ert-read-test-name prompt (ert-test-at-point) nil t))
1630 (defun ert-find-test-other-window (test-name)
1631 "Find, in another window, the definition of TEST-NAME."
1632 (interactive (list (ert-read-test-name-at-point "Find test definition: ")))
1633 (find-function-do-it test-name 'ert--test 'switch-to-buffer-other-window))
1635 (defun ert-delete-test (test-name)
1636 "Make the test TEST-NAME unbound.
1638 Nothing more than an interactive interface to `ert-make-test-unbound'."
1639 (interactive (list (ert-read-test-name-at-point "Delete test")))
1640 (ert-make-test-unbound test-name))
1642 (defun ert-delete-all-tests ()
1643 "Make all symbols in `obarray' name no test."
1644 (interactive)
1645 (when (called-interactively-p 'any)
1646 (unless (y-or-n-p "Delete all tests? ")
1647 (user-error "Aborted")))
1648 ;; We can't use `ert-select-tests' here since that gives us only
1649 ;; test objects, and going from them back to the test name symbols
1650 ;; can fail if the `ert-test' defstruct has been redefined.
1651 (mapc #'ert-make-test-unbound (apropos-internal "" #'ert-test-boundp))
1655 ;;; Display of test progress and results.
1657 ;; An entry in the results buffer ewoc. There is one entry per test.
1658 (cl-defstruct ert--ewoc-entry
1659 (test (cl-assert nil))
1660 ;; If the result of this test was expected, its ewoc entry is hidden
1661 ;; initially.
1662 (hidden-p (cl-assert nil))
1663 ;; An ewoc entry may be collapsed to hide details such as the error
1664 ;; condition.
1666 ;; I'm not sure the ability to expand and collapse entries is still
1667 ;; a useful feature.
1668 (expanded-p t)
1669 ;; By default, the ewoc entry presents the error condition with
1670 ;; certain limits on how much to print (`print-level',
1671 ;; `print-length'). The user can interactively switch to a set of
1672 ;; higher limits.
1673 (extended-printer-limits-p nil))
1675 ;; Variables local to the results buffer.
1677 ;; The ewoc.
1678 (defvar ert--results-ewoc)
1679 ;; The stats object.
1680 (defvar ert--results-stats)
1681 ;; A string with one character per test. Each character represents
1682 ;; the result of the corresponding test. The string is displayed near
1683 ;; the top of the buffer and serves as a progress bar.
1684 (defvar ert--results-progress-bar-string)
1685 ;; The position where the progress bar button begins.
1686 (defvar ert--results-progress-bar-button-begin)
1687 ;; The test result listener that updates the buffer when tests are run.
1688 (defvar ert--results-listener)
1690 (defun ert-insert-test-name-button (test-name)
1691 "Insert a button that links to TEST-NAME."
1692 (insert-text-button (format "%S" test-name)
1693 :type 'ert--test-name-button
1694 'ert-test-name test-name))
1696 (defun ert--results-format-expected-unexpected (expected unexpected)
1697 "Return a string indicating EXPECTED expected results, UNEXPECTED unexpected."
1698 (if (zerop unexpected)
1699 (format "%s" expected)
1700 (format "%s (%s unexpected)" (+ expected unexpected) unexpected)))
1702 (defun ert--results-update-ewoc-hf (ewoc stats)
1703 "Update the header and footer of EWOC to show certain information from STATS.
1705 Also sets `ert--results-progress-bar-button-begin'."
1706 (let ((run-count (ert-stats-completed stats))
1707 (results-buffer (current-buffer))
1708 ;; Need to save buffer-local value.
1709 (font-lock font-lock-mode))
1710 (ewoc-set-hf
1711 ewoc
1712 ;; header
1713 (with-temp-buffer
1714 (insert "Selector: ")
1715 (ert--insert-human-readable-selector (ert--stats-selector stats))
1716 (insert "\n")
1717 (insert
1718 (format (concat "Passed: %s\n"
1719 "Failed: %s\n"
1720 "Skipped: %s\n"
1721 "Total: %s/%s\n\n")
1722 (ert--results-format-expected-unexpected
1723 (ert--stats-passed-expected stats)
1724 (ert--stats-passed-unexpected stats))
1725 (ert--results-format-expected-unexpected
1726 (ert--stats-failed-expected stats)
1727 (ert--stats-failed-unexpected stats))
1728 (ert-stats-skipped stats)
1729 run-count
1730 (ert-stats-total stats)))
1731 (insert
1732 (format "Started at: %s\n"
1733 (ert--format-time-iso8601 (ert--stats-start-time stats))))
1734 ;; FIXME: This is ugly. Need to properly define invariants of
1735 ;; the `stats' data structure.
1736 (let ((state (cond ((ert--stats-aborted-p stats) 'aborted)
1737 ((ert--stats-current-test stats) 'running)
1738 ((ert--stats-end-time stats) 'finished)
1739 (t 'preparing))))
1740 (cl-ecase state
1741 (preparing
1742 (insert ""))
1743 (aborted
1744 (cond ((ert--stats-current-test stats)
1745 (insert "Aborted during test: ")
1746 (ert-insert-test-name-button
1747 (ert-test-name (ert--stats-current-test stats))))
1749 (insert "Aborted."))))
1750 (running
1751 (cl-assert (ert--stats-current-test stats))
1752 (insert "Running test: ")
1753 (ert-insert-test-name-button (ert-test-name
1754 (ert--stats-current-test stats))))
1755 (finished
1756 (cl-assert (not (ert--stats-current-test stats)))
1757 (insert "Finished.")))
1758 (insert "\n")
1759 (if (ert--stats-end-time stats)
1760 (insert
1761 (format "%s%s\n"
1762 (if (ert--stats-aborted-p stats)
1763 "Aborted at: "
1764 "Finished at: ")
1765 (ert--format-time-iso8601 (ert--stats-end-time stats))))
1766 (insert "\n"))
1767 (insert "\n"))
1768 (let ((progress-bar-string (with-current-buffer results-buffer
1769 ert--results-progress-bar-string)))
1770 (let ((progress-bar-button-begin
1771 (insert-text-button progress-bar-string
1772 :type 'ert--results-progress-bar-button
1773 'face (or (and font-lock
1774 (ert-face-for-stats stats))
1775 'button))))
1776 ;; The header gets copied verbatim to the results buffer,
1777 ;; and all positions remain the same, so
1778 ;; `progress-bar-button-begin' will be the right position
1779 ;; even in the results buffer.
1780 (with-current-buffer results-buffer
1781 (set (make-local-variable 'ert--results-progress-bar-button-begin)
1782 progress-bar-button-begin))))
1783 (insert "\n\n")
1784 (buffer-string))
1785 ;; footer
1787 ;; We actually want an empty footer, but that would trigger a bug
1788 ;; in ewoc, sometimes clearing the entire buffer. (It's possible
1789 ;; that this bug has been fixed since this has been tested; we
1790 ;; should test it again.)
1791 "\n")))
1794 (defvar ert-test-run-redisplay-interval-secs .1
1795 "How many seconds ERT should wait between redisplays while running tests.
1797 While running tests, ERT shows the current progress, and this variable
1798 determines how frequently the progress display is updated.")
1800 (defun ert--results-update-stats-display (ewoc stats)
1801 "Update EWOC and the mode line to show data from STATS."
1802 ;; TODO(ohler): investigate using `make-progress-reporter'.
1803 (ert--results-update-ewoc-hf ewoc stats)
1804 (force-mode-line-update)
1805 (redisplay t)
1806 (setf (ert--stats-next-redisplay stats)
1807 (+ (float-time) ert-test-run-redisplay-interval-secs)))
1809 (defun ert--results-update-stats-display-maybe (ewoc stats)
1810 "Call `ert--results-update-stats-display' if not called recently.
1812 EWOC and STATS are arguments for `ert--results-update-stats-display'."
1813 (when (>= (float-time) (ert--stats-next-redisplay stats))
1814 (ert--results-update-stats-display ewoc stats)))
1816 (defun ert--tests-running-mode-line-indicator ()
1817 "Return a string for the mode line that shows the test run progress."
1818 (let* ((stats ert--current-run-stats)
1819 (tests-total (ert-stats-total stats))
1820 (tests-completed (ert-stats-completed stats)))
1821 (if (>= tests-completed tests-total)
1822 (format " ERT(%s/%s,finished)" tests-completed tests-total)
1823 (format " ERT(%s/%s):%s"
1824 (1+ tests-completed)
1825 tests-total
1826 (if (null (ert--stats-current-test stats))
1828 (format "%S"
1829 (ert-test-name (ert--stats-current-test stats))))))))
1831 (defun ert--make-xrefs-region (begin end)
1832 "Attach cross-references to function names between BEGIN and END.
1834 BEGIN and END specify a region in the current buffer."
1835 (save-excursion
1836 (goto-char begin)
1837 (while (progn
1838 (goto-char (+ (point) 2))
1839 (skip-syntax-forward "^w_")
1840 (< (point) end))
1841 (let* ((beg (point))
1842 (end (progn (skip-syntax-forward "w_") (point)))
1843 (sym (intern-soft (buffer-substring-no-properties
1844 beg end)))
1845 (file (and sym (symbol-file sym 'defun))))
1846 (when file
1847 (goto-char beg)
1848 ;; help-xref-button needs to operate on something matched
1849 ;; by a regexp, so set that up for it.
1850 (re-search-forward "\\(\\sw\\|\\s_\\)+")
1851 (help-xref-button 0 'help-function-def sym file)))
1852 (forward-line 1))))
1854 (defun ert--string-first-line (s)
1855 "Return the first line of S, or S if it contains no newlines.
1857 The return value does not include the line terminator."
1858 (substring s 0 (cl-position ?\n s)))
1860 (defun ert-face-for-test-result (expectedp)
1861 "Return a face that shows whether a test result was expected or unexpected.
1863 If EXPECTEDP is nil, returns the face for unexpected results; if
1864 non-nil, returns the face for expected results.."
1865 (if expectedp 'ert-test-result-expected 'ert-test-result-unexpected))
1867 (defun ert-face-for-stats (stats)
1868 "Return a face that represents STATS."
1869 (cond ((ert--stats-aborted-p stats) 'nil)
1870 ((cl-plusp (ert-stats-completed-unexpected stats))
1871 (ert-face-for-test-result nil))
1872 ((eql (ert-stats-completed-expected stats) (ert-stats-total stats))
1873 (ert-face-for-test-result t))
1874 (t 'nil)))
1876 (defun ert--print-test-for-ewoc (entry)
1877 "The ewoc print function for ewoc test entries. ENTRY is the entry to print."
1878 (let* ((test (ert--ewoc-entry-test entry))
1879 (stats ert--results-stats)
1880 (result (let ((pos (ert--stats-test-pos stats test)))
1881 (cl-assert pos)
1882 (aref (ert--stats-test-results stats) pos)))
1883 (hiddenp (ert--ewoc-entry-hidden-p entry))
1884 (expandedp (ert--ewoc-entry-expanded-p entry))
1885 (extended-printer-limits-p (ert--ewoc-entry-extended-printer-limits-p
1886 entry)))
1887 (cond (hiddenp)
1889 (let ((expectedp (ert-test-result-expected-p test result)))
1890 (insert-text-button (format "%c" (ert-char-for-test-result
1891 result expectedp))
1892 :type 'ert--results-expand-collapse-button
1893 'face (or (and font-lock-mode
1894 (ert-face-for-test-result
1895 expectedp))
1896 'button)))
1897 (insert " ")
1898 (ert-insert-test-name-button (ert-test-name test))
1899 (insert "\n")
1900 (when (and expandedp (not (eql result 'nil)))
1901 (when (ert-test-documentation test)
1902 (insert " "
1903 (propertize
1904 (ert--string-first-line
1905 (substitute-command-keys
1906 (ert-test-documentation test)))
1907 'font-lock-face 'font-lock-doc-face)
1908 "\n"))
1909 (cl-etypecase result
1910 (ert-test-passed
1911 (if (ert-test-result-expected-p test result)
1912 (insert " passed\n")
1913 (insert " passed unexpectedly\n"))
1914 (insert ""))
1915 (ert-test-result-with-condition
1916 (ert--insert-infos result)
1917 (let ((print-escape-newlines t)
1918 (print-level (if extended-printer-limits-p 12 6))
1919 (print-length (if extended-printer-limits-p 100 10)))
1920 (insert " ")
1921 (let ((begin (point)))
1922 (ert--pp-with-indentation-and-newline
1923 (ert-test-result-with-condition-condition result))
1924 (ert--make-xrefs-region begin (point)))))
1925 (ert-test-aborted-with-non-local-exit
1926 (insert " aborted\n"))
1927 (ert-test-quit
1928 (insert " quit\n")))
1929 (insert "\n")))))
1930 nil)
1932 (defun ert--results-font-lock-function (enabledp)
1933 "Redraw the ERT results buffer after font-lock-mode was switched on or off.
1935 ENABLEDP is true if font-lock-mode is switched on, false
1936 otherwise."
1937 (ert--results-update-ewoc-hf ert--results-ewoc ert--results-stats)
1938 (ewoc-refresh ert--results-ewoc)
1939 (font-lock-default-function enabledp))
1941 (defun ert--setup-results-buffer (stats listener buffer-name)
1942 "Set up a test results buffer.
1944 STATS is the stats object; LISTENER is the results listener;
1945 BUFFER-NAME, if non-nil, is the buffer name to use."
1946 (unless buffer-name (setq buffer-name "*ert*"))
1947 (let ((buffer (get-buffer-create buffer-name)))
1948 (with-current-buffer buffer
1949 (let ((inhibit-read-only t))
1950 (buffer-disable-undo)
1951 (erase-buffer)
1952 (ert-results-mode)
1953 ;; Erase buffer again in case switching out of the previous
1954 ;; mode inserted anything. (This happens e.g. when switching
1955 ;; from ert-results-mode to ert-results-mode when
1956 ;; font-lock-mode turns itself off in change-major-mode-hook.)
1957 (erase-buffer)
1958 (set (make-local-variable 'font-lock-function)
1959 'ert--results-font-lock-function)
1960 (let ((ewoc (ewoc-create 'ert--print-test-for-ewoc nil nil t)))
1961 (set (make-local-variable 'ert--results-ewoc) ewoc)
1962 (set (make-local-variable 'ert--results-stats) stats)
1963 (set (make-local-variable 'ert--results-progress-bar-string)
1964 (make-string (ert-stats-total stats)
1965 (ert-char-for-test-result nil t)))
1966 (set (make-local-variable 'ert--results-listener) listener)
1967 (cl-loop for test across (ert--stats-tests stats) do
1968 (ewoc-enter-last ewoc
1969 (make-ert--ewoc-entry :test test
1970 :hidden-p t)))
1971 (ert--results-update-ewoc-hf ert--results-ewoc ert--results-stats)
1972 (goto-char (1- (point-max)))
1973 buffer)))))
1976 (defvar ert--selector-history nil
1977 "List of recent test selectors read from terminal.")
1979 ;; Should OUTPUT-BUFFER-NAME and MESSAGE-FN really be arguments here?
1980 ;; They are needed only for our automated self-tests at the moment.
1981 ;; Or should there be some other mechanism?
1982 ;;;###autoload
1983 (defun ert-run-tests-interactively (selector
1984 &optional output-buffer-name message-fn)
1985 "Run the tests specified by SELECTOR and display the results in a buffer.
1987 SELECTOR works as described in `ert-select-tests'.
1988 OUTPUT-BUFFER-NAME and MESSAGE-FN should normally be nil; they
1989 are used for automated self-tests and specify which buffer to use
1990 and how to display message."
1991 (interactive
1992 (list (let ((default (if ert--selector-history
1993 ;; Can't use `first' here as this form is
1994 ;; not compiled, and `first' is not
1995 ;; defined without cl.
1996 (car ert--selector-history)
1997 "t")))
1998 (read
1999 (completing-read (if (null default)
2000 "Run tests: "
2001 (format "Run tests (default %s): " default))
2002 obarray #'ert-test-boundp nil nil
2003 'ert--selector-history default nil)))
2004 nil))
2005 (unless message-fn (setq message-fn 'message))
2006 (let ((output-buffer-name output-buffer-name)
2007 buffer
2008 listener
2009 (message-fn message-fn))
2010 (setq listener
2011 (lambda (event-type &rest event-args)
2012 (cl-ecase event-type
2013 (run-started
2014 (cl-destructuring-bind (stats) event-args
2015 (setq buffer (ert--setup-results-buffer stats
2016 listener
2017 output-buffer-name))
2018 (pop-to-buffer buffer)))
2019 (run-ended
2020 (cl-destructuring-bind (stats abortedp) event-args
2021 (funcall message-fn
2022 "%sRan %s tests, %s results were as expected%s%s"
2023 (if (not abortedp)
2025 "Aborted: ")
2026 (ert-stats-total stats)
2027 (ert-stats-completed-expected stats)
2028 (let ((unexpected
2029 (ert-stats-completed-unexpected stats)))
2030 (if (zerop unexpected)
2032 (format ", %s unexpected" unexpected)))
2033 (let ((skipped
2034 (ert-stats-skipped stats)))
2035 (if (zerop skipped)
2037 (format ", %s skipped" skipped))))
2038 (ert--results-update-stats-display (with-current-buffer buffer
2039 ert--results-ewoc)
2040 stats)))
2041 (test-started
2042 (cl-destructuring-bind (stats test) event-args
2043 (with-current-buffer buffer
2044 (let* ((ewoc ert--results-ewoc)
2045 (pos (ert--stats-test-pos stats test))
2046 (node (ewoc-nth ewoc pos)))
2047 (cl-assert node)
2048 (setf (ert--ewoc-entry-test (ewoc-data node)) test)
2049 (aset ert--results-progress-bar-string pos
2050 (ert-char-for-test-result nil t))
2051 (ert--results-update-stats-display-maybe ewoc stats)
2052 (ewoc-invalidate ewoc node)))))
2053 (test-ended
2054 (cl-destructuring-bind (stats test result) event-args
2055 (with-current-buffer buffer
2056 (let* ((ewoc ert--results-ewoc)
2057 (pos (ert--stats-test-pos stats test))
2058 (node (ewoc-nth ewoc pos)))
2059 (when (ert--ewoc-entry-hidden-p (ewoc-data node))
2060 (setf (ert--ewoc-entry-hidden-p (ewoc-data node))
2061 (ert-test-result-expected-p test result)))
2062 (aset ert--results-progress-bar-string pos
2063 (ert-char-for-test-result result
2064 (ert-test-result-expected-p
2065 test result)))
2066 (ert--results-update-stats-display-maybe ewoc stats)
2067 (ewoc-invalidate ewoc node))))))))
2068 (ert-run-tests selector listener t)))
2070 ;;;###autoload
2071 (defalias 'ert 'ert-run-tests-interactively)
2074 ;;; Simple view mode for auxiliary information like stack traces or
2075 ;;; messages. Mainly binds "q" for quit.
2077 (define-derived-mode ert-simple-view-mode special-mode "ERT-View"
2078 "Major mode for viewing auxiliary information in ERT.")
2080 ;;; Commands and button actions for the results buffer.
2082 (define-derived-mode ert-results-mode special-mode "ERT-Results"
2083 "Major mode for viewing results of ERT test runs.")
2085 (cl-loop for (key binding) in
2086 '( ;; Stuff that's not in the menu.
2087 ("\t" forward-button)
2088 ([backtab] backward-button)
2089 ("j" ert-results-jump-between-summary-and-result)
2090 ("L" ert-results-toggle-printer-limits-for-test-at-point)
2091 ("n" ert-results-next-test)
2092 ("p" ert-results-previous-test)
2093 ;; Stuff that is in the menu.
2094 ("R" ert-results-rerun-all-tests)
2095 ("r" ert-results-rerun-test-at-point)
2096 ("d" ert-results-rerun-test-at-point-debugging-errors)
2097 ("." ert-results-find-test-at-point-other-window)
2098 ("b" ert-results-pop-to-backtrace-for-test-at-point)
2099 ("m" ert-results-pop-to-messages-for-test-at-point)
2100 ("l" ert-results-pop-to-should-forms-for-test-at-point)
2101 ("h" ert-results-describe-test-at-point)
2102 ("D" ert-delete-test)
2103 ("T" ert-results-pop-to-timings)
2106 (define-key ert-results-mode-map key binding))
2108 (easy-menu-define ert-results-mode-menu ert-results-mode-map
2109 "Menu for `ert-results-mode'."
2110 '("ERT Results"
2111 ["Re-run all tests" ert-results-rerun-all-tests]
2112 "--"
2113 ;; FIXME? Why are there (at least) 3 different ways to decide if
2114 ;; there is a test at point?
2115 ["Re-run test" ert-results-rerun-test-at-point
2116 :active (car (ert--results-test-at-point-allow-redefinition))]
2117 ["Debug test" ert-results-rerun-test-at-point-debugging-errors
2118 :active (car (ert--results-test-at-point-allow-redefinition))]
2119 ["Show test definition" ert-results-find-test-at-point-other-window
2120 :active (ert-test-at-point)]
2121 "--"
2122 ["Show backtrace" ert-results-pop-to-backtrace-for-test-at-point
2123 :active (ert--results-test-at-point-no-redefinition)]
2124 ["Show messages" ert-results-pop-to-messages-for-test-at-point
2125 :active (ert--results-test-at-point-no-redefinition)]
2126 ["Show `should' forms" ert-results-pop-to-should-forms-for-test-at-point
2127 :active (ert--results-test-at-point-no-redefinition)]
2128 ["Describe test" ert-results-describe-test-at-point
2129 :active (ert--results-test-at-point-no-redefinition)]
2130 "--"
2131 ["Delete test" ert-delete-test]
2132 "--"
2133 ["Show execution time of each test" ert-results-pop-to-timings]
2136 (define-button-type 'ert--results-progress-bar-button
2137 'action #'ert--results-progress-bar-button-action
2138 'help-echo "mouse-2, RET: Reveal test result")
2140 (define-button-type 'ert--test-name-button
2141 'action #'ert--test-name-button-action
2142 'help-echo "mouse-2, RET: Find test definition")
2144 (define-button-type 'ert--results-expand-collapse-button
2145 'action #'ert--results-expand-collapse-button-action
2146 'help-echo "mouse-2, RET: Expand/collapse test result")
2148 (defun ert--results-test-node-or-null-at-point ()
2149 "If point is on a valid ewoc node, return it; return nil otherwise.
2151 To be used in the ERT results buffer."
2152 (let* ((ewoc ert--results-ewoc)
2153 (node (ewoc-locate ewoc)))
2154 ;; `ewoc-locate' will return an arbitrary node when point is on
2155 ;; header or footer, or when all nodes are invisible. So we need
2156 ;; to validate its return value here.
2158 ;; Update: I'm seeing nil being returned in some cases now,
2159 ;; perhaps this has been changed?
2160 (if (and node
2161 (>= (point) (ewoc-location node))
2162 (not (ert--ewoc-entry-hidden-p (ewoc-data node))))
2163 node
2164 nil)))
2166 (defun ert--results-test-node-at-point ()
2167 "If point is on a valid ewoc node, return it; signal an error otherwise.
2169 To be used in the ERT results buffer."
2170 (or (ert--results-test-node-or-null-at-point)
2171 (user-error "No test at point")))
2173 (defun ert-results-next-test ()
2174 "Move point to the next test.
2176 To be used in the ERT results buffer."
2177 (interactive)
2178 (ert--results-move (ewoc-locate ert--results-ewoc) 'ewoc-next
2179 "No tests below"))
2181 (defun ert-results-previous-test ()
2182 "Move point to the previous test.
2184 To be used in the ERT results buffer."
2185 (interactive)
2186 (ert--results-move (ewoc-locate ert--results-ewoc) 'ewoc-prev
2187 "No tests above"))
2189 (defun ert--results-move (node ewoc-fn error-message)
2190 "Move point from NODE to the previous or next node.
2192 EWOC-FN specifies the direction and should be either `ewoc-prev'
2193 or `ewoc-next'. If there are no more nodes in that direction, a
2194 user-error is signaled with the message ERROR-MESSAGE."
2195 (cl-loop
2196 (setq node (funcall ewoc-fn ert--results-ewoc node))
2197 (when (null node)
2198 (user-error "%s" error-message))
2199 (unless (ert--ewoc-entry-hidden-p (ewoc-data node))
2200 (goto-char (ewoc-location node))
2201 (cl-return))))
2203 (defun ert--results-expand-collapse-button-action (_button)
2204 "Expand or collapse the test node BUTTON belongs to."
2205 (let* ((ewoc ert--results-ewoc)
2206 (node (save-excursion
2207 (goto-char (ert--button-action-position))
2208 (ert--results-test-node-at-point)))
2209 (entry (ewoc-data node)))
2210 (setf (ert--ewoc-entry-expanded-p entry)
2211 (not (ert--ewoc-entry-expanded-p entry)))
2212 (ewoc-invalidate ewoc node)))
2214 (defun ert-results-find-test-at-point-other-window ()
2215 "Find the definition of the test at point in another window.
2217 To be used in the ERT results buffer."
2218 (interactive)
2219 (let ((name (ert-test-at-point)))
2220 (unless name
2221 (user-error "No test at point"))
2222 (ert-find-test-other-window name)))
2224 (defun ert--test-name-button-action (button)
2225 "Find the definition of the test BUTTON belongs to, in another window."
2226 (let ((name (button-get button 'ert-test-name)))
2227 (ert-find-test-other-window name)))
2229 (defun ert--ewoc-position (ewoc node)
2230 ;; checkdoc-order: nil
2231 "Return the position of NODE in EWOC, or nil if NODE is not in EWOC."
2232 (cl-loop for i from 0
2233 for node-here = (ewoc-nth ewoc 0) then (ewoc-next ewoc node-here)
2234 do (when (eql node node-here)
2235 (cl-return i))
2236 finally (cl-return nil)))
2238 (defun ert-results-jump-between-summary-and-result ()
2239 "Jump back and forth between the test run summary and individual test results.
2241 From an ewoc node, jumps to the character that represents the
2242 same test in the progress bar, and vice versa.
2244 To be used in the ERT results buffer."
2245 ;; Maybe this command isn't actually needed much, but if it is, it
2246 ;; seems like an indication that the UI design is not optimal. If
2247 ;; jumping back and forth between a summary at the top of the buffer
2248 ;; and the error log in the remainder of the buffer is useful, then
2249 ;; the summary apparently needs to be easily accessible from the
2250 ;; error log, and perhaps it would be better to have it in a
2251 ;; separate buffer to keep it visible.
2252 (interactive)
2253 (let ((ewoc ert--results-ewoc)
2254 (progress-bar-begin ert--results-progress-bar-button-begin))
2255 (cond ((ert--results-test-node-or-null-at-point)
2256 (let* ((node (ert--results-test-node-at-point))
2257 (pos (ert--ewoc-position ewoc node)))
2258 (goto-char (+ progress-bar-begin pos))))
2259 ((and (<= progress-bar-begin (point))
2260 (< (point) (button-end (button-at progress-bar-begin))))
2261 (let* ((node (ewoc-nth ewoc (- (point) progress-bar-begin)))
2262 (entry (ewoc-data node)))
2263 (when (ert--ewoc-entry-hidden-p entry)
2264 (setf (ert--ewoc-entry-hidden-p entry) nil)
2265 (ewoc-invalidate ewoc node))
2266 (ewoc-goto-node ewoc node)))
2268 (goto-char progress-bar-begin)))))
2270 (defun ert-test-at-point ()
2271 "Return the name of the test at point as a symbol, or nil if none."
2272 (or (and (eql major-mode 'ert-results-mode)
2273 (let ((test (ert--results-test-at-point-no-redefinition)))
2274 (and test (ert-test-name test))))
2275 (let* ((thing (thing-at-point 'symbol))
2276 (sym (intern-soft thing)))
2277 (and (ert-test-boundp sym)
2278 sym))))
2280 (defun ert--results-test-at-point-no-redefinition (&optional error)
2281 "Return the test at point, or nil.
2282 If optional argument ERROR is non-nil, signal an error rather than return nil.
2283 To be used in the ERT results buffer."
2284 (cl-assert (eql major-mode 'ert-results-mode))
2286 (if (ert--results-test-node-or-null-at-point)
2287 (let* ((node (ert--results-test-node-at-point))
2288 (test (ert--ewoc-entry-test (ewoc-data node))))
2289 test)
2290 (let ((progress-bar-begin ert--results-progress-bar-button-begin))
2291 (when (and (<= progress-bar-begin (point))
2292 (< (point) (button-end (button-at progress-bar-begin))))
2293 (let* ((test-index (- (point) progress-bar-begin))
2294 (test (aref (ert--stats-tests ert--results-stats)
2295 test-index)))
2296 test))))
2297 (if error (user-error "No test at point"))))
2299 (defun ert--results-test-at-point-allow-redefinition ()
2300 "Look up the test at point, and check whether it has been redefined.
2302 To be used in the ERT results buffer.
2304 Returns a list of two elements: the test (or nil) and a symbol
2305 specifying whether the test has been redefined.
2307 If a new test has been defined with the same name as the test at
2308 point, replaces the test at point with the new test, and returns
2309 the new test and the symbol `redefined'.
2311 If the test has been deleted, returns the old test and the symbol
2312 `deleted'.
2314 If the test is still current, returns the test and the symbol nil.
2316 If there is no test at point, returns a list with two nils."
2317 (let ((test (ert--results-test-at-point-no-redefinition)))
2318 (cond ((null test)
2319 `(nil nil))
2320 ((null (ert-test-name test))
2321 `(,test nil))
2323 (let* ((name (ert-test-name test))
2324 (new-test (and (ert-test-boundp name)
2325 (ert-get-test name))))
2326 (cond ((eql test new-test)
2327 `(,test nil))
2328 ((null new-test)
2329 `(,test deleted))
2331 (ert--results-update-after-test-redefinition
2332 (ert--stats-test-pos ert--results-stats test)
2333 new-test)
2334 `(,new-test redefined))))))))
2336 (defun ert--results-update-after-test-redefinition (pos new-test)
2337 "Update results buffer after the test at pos POS has been redefined.
2339 Also updates the stats object. NEW-TEST is the new test
2340 definition."
2341 (let* ((stats ert--results-stats)
2342 (ewoc ert--results-ewoc)
2343 (node (ewoc-nth ewoc pos))
2344 (entry (ewoc-data node)))
2345 (ert--stats-set-test-and-result stats pos new-test nil)
2346 (setf (ert--ewoc-entry-test entry) new-test
2347 (aref ert--results-progress-bar-string pos) (ert-char-for-test-result
2348 nil t))
2349 (ewoc-invalidate ewoc node))
2350 nil)
2352 (defun ert--button-action-position ()
2353 "The buffer position where the last button action was triggered."
2354 (cond ((integerp last-command-event)
2355 (point))
2356 ((eventp last-command-event)
2357 (posn-point (event-start last-command-event)))
2358 (t (cl-assert nil))))
2360 (defun ert--results-progress-bar-button-action (_button)
2361 "Jump to details for the test represented by the character clicked in BUTTON."
2362 (goto-char (ert--button-action-position))
2363 (ert-results-jump-between-summary-and-result))
2365 (defun ert-results-rerun-all-tests ()
2366 "Re-run all tests, using the same selector.
2368 To be used in the ERT results buffer."
2369 (interactive)
2370 (cl-assert (eql major-mode 'ert-results-mode))
2371 (let ((selector (ert--stats-selector ert--results-stats)))
2372 (ert-run-tests-interactively selector (buffer-name))))
2374 (defun ert-results-rerun-test-at-point ()
2375 "Re-run the test at point.
2377 To be used in the ERT results buffer."
2378 (interactive)
2379 (cl-destructuring-bind (test redefinition-state)
2380 (ert--results-test-at-point-allow-redefinition)
2381 (when (null test)
2382 (user-error "No test at point"))
2383 (let* ((stats ert--results-stats)
2384 (progress-message (format "Running %stest %S"
2385 (cl-ecase redefinition-state
2386 ((nil) "")
2387 (redefined "new definition of ")
2388 (deleted "deleted "))
2389 (ert-test-name test))))
2390 ;; Need to save and restore point manually here: When point is on
2391 ;; the first visible ewoc entry while the header is updated, point
2392 ;; moves to the top of the buffer. This is undesirable, and a
2393 ;; simple `save-excursion' doesn't prevent it.
2394 (let ((point (point)))
2395 (unwind-protect
2396 (unwind-protect
2397 (progn
2398 (message "%s..." progress-message)
2399 (ert-run-or-rerun-test stats test
2400 ert--results-listener))
2401 (ert--results-update-stats-display ert--results-ewoc stats)
2402 (message "%s...%s"
2403 progress-message
2404 (let ((result (ert-test-most-recent-result test)))
2405 (ert-string-for-test-result
2406 result (ert-test-result-expected-p test result)))))
2407 (goto-char point))))))
2409 (defun ert-results-rerun-test-at-point-debugging-errors ()
2410 "Re-run the test at point with `ert-debug-on-error' bound to t.
2412 To be used in the ERT results buffer."
2413 (interactive)
2414 (let ((ert-debug-on-error t))
2415 (ert-results-rerun-test-at-point)))
2417 (defun ert-results-pop-to-backtrace-for-test-at-point ()
2418 "Display the backtrace for the test at point.
2420 To be used in the ERT results buffer."
2421 (interactive)
2422 (let* ((test (ert--results-test-at-point-no-redefinition t))
2423 (stats ert--results-stats)
2424 (pos (ert--stats-test-pos stats test))
2425 (result (aref (ert--stats-test-results stats) pos)))
2426 (cl-etypecase result
2427 (ert-test-passed (error "Test passed, no backtrace available"))
2428 (ert-test-result-with-condition
2429 (let ((backtrace (ert-test-result-with-condition-backtrace result))
2430 (buffer (get-buffer-create "*ERT Backtrace*")))
2431 (pop-to-buffer buffer)
2432 (let ((inhibit-read-only t))
2433 (buffer-disable-undo)
2434 (erase-buffer)
2435 (ert-simple-view-mode)
2436 (set-buffer-multibyte t) ; mimic debugger-setup-buffer
2437 (setq truncate-lines t)
2438 (ert--print-backtrace backtrace t)
2439 (goto-char (point-min))
2440 (insert (substitute-command-keys "Backtrace for test `"))
2441 (ert-insert-test-name-button (ert-test-name test))
2442 (insert (substitute-command-keys "':\n"))))))))
2444 (defun ert-results-pop-to-messages-for-test-at-point ()
2445 "Display the part of the *Messages* buffer generated during the test at point.
2447 To be used in the ERT results buffer."
2448 (interactive)
2449 (let* ((test (ert--results-test-at-point-no-redefinition t))
2450 (stats ert--results-stats)
2451 (pos (ert--stats-test-pos stats test))
2452 (result (aref (ert--stats-test-results stats) pos)))
2453 (let ((buffer (get-buffer-create "*ERT Messages*")))
2454 (pop-to-buffer buffer)
2455 (let ((inhibit-read-only t))
2456 (buffer-disable-undo)
2457 (erase-buffer)
2458 (ert-simple-view-mode)
2459 (insert (ert-test-result-messages result))
2460 (goto-char (point-min))
2461 (insert (substitute-command-keys "Messages for test `"))
2462 (ert-insert-test-name-button (ert-test-name test))
2463 (insert (substitute-command-keys "':\n"))))))
2465 (defun ert-results-pop-to-should-forms-for-test-at-point ()
2466 "Display the list of `should' forms executed during the test at point.
2468 To be used in the ERT results buffer."
2469 (interactive)
2470 (let* ((test (ert--results-test-at-point-no-redefinition t))
2471 (stats ert--results-stats)
2472 (pos (ert--stats-test-pos stats test))
2473 (result (aref (ert--stats-test-results stats) pos)))
2474 (let ((buffer (get-buffer-create "*ERT list of should forms*")))
2475 (pop-to-buffer buffer)
2476 (let ((inhibit-read-only t))
2477 (buffer-disable-undo)
2478 (erase-buffer)
2479 (ert-simple-view-mode)
2480 (if (null (ert-test-result-should-forms result))
2481 (insert "\n(No should forms during this test.)\n")
2482 (cl-loop for form-description
2483 in (ert-test-result-should-forms result)
2484 for i from 1 do
2485 (insert "\n")
2486 (insert (format "%s: " i))
2487 (let ((begin (point)))
2488 (ert--pp-with-indentation-and-newline form-description)
2489 (ert--make-xrefs-region begin (point)))))
2490 (goto-char (point-min))
2491 (insert (substitute-command-keys
2492 "`should' forms executed during test `"))
2493 (ert-insert-test-name-button (ert-test-name test))
2494 (insert (substitute-command-keys "':\n"))
2495 (insert "\n")
2496 (insert (concat "(Values are shallow copies and may have "
2497 "looked different during the test if they\n"
2498 "have been modified destructively.)\n"))
2499 (forward-line 1)))))
2501 (defun ert-results-toggle-printer-limits-for-test-at-point ()
2502 "Toggle how much of the condition to print for the test at point.
2504 To be used in the ERT results buffer."
2505 (interactive)
2506 (let* ((ewoc ert--results-ewoc)
2507 (node (ert--results-test-node-at-point))
2508 (entry (ewoc-data node)))
2509 (setf (ert--ewoc-entry-extended-printer-limits-p entry)
2510 (not (ert--ewoc-entry-extended-printer-limits-p entry)))
2511 (ewoc-invalidate ewoc node)))
2513 (defun ert-results-pop-to-timings ()
2514 "Display test timings for the last run.
2516 To be used in the ERT results buffer."
2517 (interactive)
2518 (let* ((stats ert--results-stats)
2519 (buffer (get-buffer-create "*ERT timings*"))
2520 (data (cl-loop for test across (ert--stats-tests stats)
2521 for start-time across (ert--stats-test-start-times
2522 stats)
2523 for end-time across (ert--stats-test-end-times stats)
2524 collect (list test
2525 (float-time (time-subtract
2526 end-time start-time))))))
2527 (setq data (sort data (lambda (a b)
2528 (> (cl-second a) (cl-second b)))))
2529 (pop-to-buffer buffer)
2530 (let ((inhibit-read-only t))
2531 (buffer-disable-undo)
2532 (erase-buffer)
2533 (ert-simple-view-mode)
2534 (if (null data)
2535 (insert "(No data)\n")
2536 (insert (format "%-3s %8s %8s\n" "" "time" "cumul"))
2537 (cl-loop for (test time) in data
2538 for cumul-time = time then (+ cumul-time time)
2539 for i from 1 do
2540 (progn
2541 (insert (format "%3s: %8.3f %8.3f " i time cumul-time))
2542 (ert-insert-test-name-button (ert-test-name test))
2543 (insert "\n"))))
2544 (goto-char (point-min))
2545 (insert "Tests by run time (seconds):\n\n")
2546 (forward-line 1))))
2548 ;;;###autoload
2549 (defun ert-describe-test (test-or-test-name)
2550 "Display the documentation for TEST-OR-TEST-NAME (a symbol or ert-test)."
2551 (interactive (list (ert-read-test-name-at-point "Describe test")))
2552 (let (test-name
2553 test-definition)
2554 (cl-etypecase test-or-test-name
2555 (symbol (setq test-name test-or-test-name
2556 test-definition (ert-get-test test-or-test-name)))
2557 (ert-test (setq test-name (ert-test-name test-or-test-name)
2558 test-definition test-or-test-name)))
2559 (help-setup-xref (list #'ert-describe-test test-or-test-name)
2560 (called-interactively-p 'interactive))
2561 (save-excursion
2562 (with-help-window (help-buffer)
2563 (with-current-buffer (help-buffer)
2564 (insert (if test-name (format "%S" test-name) "<anonymous test>"))
2565 (insert " is a test")
2566 (let ((file-name (and test-name
2567 (symbol-file test-name 'ert--test))))
2568 (when file-name
2569 (insert (format-message " defined in `%s'"
2570 (file-name-nondirectory file-name)))
2571 (save-excursion
2572 (re-search-backward (substitute-command-keys "`\\([^`']+\\)'")
2573 nil t)
2574 (help-xref-button 1 'help-function-def test-name file-name)))
2575 (insert ".")
2576 (fill-region-as-paragraph (point-min) (point))
2577 (insert "\n\n")
2578 (unless (and (ert-test-boundp test-name)
2579 (eql (ert-get-test test-name) test-definition))
2580 (let ((begin (point)))
2581 (insert "Note: This test has been redefined or deleted, "
2582 "this documentation refers to an old definition.")
2583 (fill-region-as-paragraph begin (point)))
2584 (insert "\n\n"))
2585 (insert (substitute-command-keys
2586 (or (ert-test-documentation test-definition)
2587 "It is not documented."))
2588 "\n")
2589 ;; For describe-symbol-backends.
2590 (buffer-string)))))))
2592 (defun ert-results-describe-test-at-point ()
2593 "Display the documentation of the test at point.
2595 To be used in the ERT results buffer."
2596 (interactive)
2597 (ert-describe-test (ert--results-test-at-point-no-redefinition t)))
2600 ;;; Actions on load/unload.
2602 (require 'help-mode)
2603 (add-to-list 'describe-symbol-backends
2604 `("ERT test" ,#'ert-test-boundp
2605 ,(lambda (s _b _f) (ert-describe-test s))))
2607 (add-to-list 'find-function-regexp-alist '(ert--test . ert--find-test-regexp))
2608 (add-to-list 'minor-mode-alist '(ert--current-run-stats
2609 (:eval
2610 (ert--tests-running-mode-line-indicator))))
2611 (add-hook 'emacs-lisp-mode-hook #'ert--activate-font-lock-keywords)
2613 (defun ert--unload-function ()
2614 "Unload function to undo the side-effects of loading ert.el."
2615 (ert--remove-from-list 'find-function-regexp-alist 'ert-deftest :key #'car)
2616 (ert--remove-from-list 'minor-mode-alist 'ert--current-run-stats :key #'car)
2617 (ert--remove-from-list 'emacs-lisp-mode-hook
2618 'ert--activate-font-lock-keywords)
2619 nil)
2621 (defvar ert-unload-hook ())
2622 (add-hook 'ert-unload-hook #'ert--unload-function)
2625 (provide 'ert)
2627 ;;; ert.el ends here