Document reserved keys
[emacs.git] / lisp / emacs-lisp / ert.el
blob15d488f7101e7d99bec357e03d37d408b8539424
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 ;;;###autoload
1337 (defun ert-run-tests-batch (&optional selector)
1338 "Run the tests specified by SELECTOR, printing results to the terminal.
1340 SELECTOR works as described in `ert-select-tests', except if
1341 SELECTOR is nil, in which case all tests rather than none will be
1342 run; this makes the command line \"emacs -batch -l my-tests.el -f
1343 ert-run-tests-batch-and-exit\" useful.
1345 Returns the stats object."
1346 (unless selector (setq selector 't))
1347 (ert-run-tests
1348 selector
1349 (lambda (event-type &rest event-args)
1350 (cl-ecase event-type
1351 (run-started
1352 (cl-destructuring-bind (stats) event-args
1353 (message "Running %s tests (%s)"
1354 (length (ert--stats-tests stats))
1355 (ert--format-time-iso8601 (ert--stats-start-time stats)))))
1356 (run-ended
1357 (cl-destructuring-bind (stats abortedp) event-args
1358 (let ((unexpected (ert-stats-completed-unexpected stats))
1359 (skipped (ert-stats-skipped stats))
1360 (expected-failures (ert--stats-failed-expected stats)))
1361 (message "\n%sRan %s tests, %s results as expected%s%s (%s)%s\n"
1362 (if (not abortedp)
1364 "Aborted: ")
1365 (ert-stats-total stats)
1366 (ert-stats-completed-expected stats)
1367 (if (zerop unexpected)
1369 (format ", %s unexpected" unexpected))
1370 (if (zerop skipped)
1372 (format ", %s skipped" skipped))
1373 (ert--format-time-iso8601 (ert--stats-end-time stats))
1374 (if (zerop expected-failures)
1376 (format "\n%s expected failures" expected-failures)))
1377 (unless (zerop unexpected)
1378 (message "%s unexpected results:" unexpected)
1379 (cl-loop for test across (ert--stats-tests stats)
1380 for result = (ert-test-most-recent-result test) do
1381 (when (not (ert-test-result-expected-p test result))
1382 (message "%9s %S"
1383 (ert-string-for-test-result result nil)
1384 (ert-test-name test))))
1385 (message "%s" ""))
1386 (unless (zerop skipped)
1387 (message "%s skipped results:" skipped)
1388 (cl-loop for test across (ert--stats-tests stats)
1389 for result = (ert-test-most-recent-result test) do
1390 (when (ert-test-result-type-p result :skipped)
1391 (message "%9s %S"
1392 (ert-string-for-test-result result nil)
1393 (ert-test-name test))))
1394 (message "%s" "")))))
1395 (test-started
1397 (test-ended
1398 (cl-destructuring-bind (stats test result) event-args
1399 (unless (ert-test-result-expected-p test result)
1400 (cl-etypecase result
1401 (ert-test-passed
1402 (message "Test %S passed unexpectedly" (ert-test-name test)))
1403 (ert-test-result-with-condition
1404 (message "Test %S backtrace:" (ert-test-name test))
1405 (with-temp-buffer
1406 (ert--print-backtrace
1407 (ert-test-result-with-condition-backtrace result)
1408 nil)
1409 (if (not ert-batch-backtrace-right-margin)
1410 (message "%s"
1411 (buffer-substring-no-properties (point-min)
1412 (point-max)))
1413 (goto-char (point-min))
1414 (while (not (eobp))
1415 (let ((start (point))
1416 (end (line-end-position)))
1417 (setq end (min end
1418 (+ start
1419 ert-batch-backtrace-right-margin)))
1420 (message "%s" (buffer-substring-no-properties
1421 start end)))
1422 (forward-line 1))))
1423 (with-temp-buffer
1424 (ert--insert-infos result)
1425 (insert " ")
1426 (let ((print-escape-newlines t)
1427 (print-level 5)
1428 (print-length 10))
1429 (ert--pp-with-indentation-and-newline
1430 (ert-test-result-with-condition-condition result)))
1431 (goto-char (1- (point-max)))
1432 (cl-assert (looking-at "\n"))
1433 (delete-char 1)
1434 (message "Test %S condition:" (ert-test-name test))
1435 (message "%s" (buffer-string))))
1436 (ert-test-aborted-with-non-local-exit
1437 (message "Test %S aborted with non-local exit"
1438 (ert-test-name test)))
1439 (ert-test-quit
1440 (message "Quit during %S" (ert-test-name test)))))
1441 (let* ((max (prin1-to-string (length (ert--stats-tests stats))))
1442 (format-string (concat "%9s %"
1443 (prin1-to-string (length max))
1444 "s/" max " %S")))
1445 (message format-string
1446 (ert-string-for-test-result result
1447 (ert-test-result-expected-p
1448 test result))
1449 (1+ (ert--stats-test-pos stats test))
1450 (ert-test-name test)))))))
1451 nil))
1453 ;;;###autoload
1454 (defun ert-run-tests-batch-and-exit (&optional selector)
1455 "Like `ert-run-tests-batch', but exits Emacs when done.
1457 The exit status will be 0 if all test results were as expected, 1
1458 on unexpected results, or 2 if the tool detected an error outside
1459 of the tests (e.g. invalid SELECTOR or bug in the code that runs
1460 the tests)."
1461 (or noninteractive
1462 (user-error "This function is only for use in batch mode"))
1463 ;; Better crash loudly than attempting to recover from undefined
1464 ;; behavior.
1465 (setq attempt-stack-overflow-recovery nil
1466 attempt-orderly-shutdown-on-fatal-signal nil)
1467 (unwind-protect
1468 (let ((stats (ert-run-tests-batch selector)))
1469 (kill-emacs (if (zerop (ert-stats-completed-unexpected stats)) 0 1)))
1470 (unwind-protect
1471 (progn
1472 (message "Error running tests")
1473 (backtrace))
1474 (kill-emacs 2))))
1477 (defun ert-summarize-tests-batch-and-exit ()
1478 "Summarize the results of testing.
1479 Expects to be called in batch mode, with logfiles as command-line arguments.
1480 The logfiles should have the `ert-run-tests-batch' format. When finished,
1481 this exits Emacs, with status as per `ert-run-tests-batch-and-exit'."
1482 (or noninteractive
1483 (user-error "This function is only for use in batch mode"))
1484 ;; Better crash loudly than attempting to recover from undefined
1485 ;; behavior.
1486 (setq attempt-stack-overflow-recovery nil
1487 attempt-orderly-shutdown-on-fatal-signal nil)
1488 (let ((nlogs (length command-line-args-left))
1489 (ntests 0) (nrun 0) (nexpected 0) (nunexpected 0) (nskipped 0)
1490 nnotrun logfile notests badtests unexpected skipped)
1491 (with-temp-buffer
1492 (while (setq logfile (pop command-line-args-left))
1493 (erase-buffer)
1494 (when (file-readable-p logfile) (insert-file-contents logfile))
1495 (if (not (re-search-forward "^Running \\([0-9]+\\) tests" nil t))
1496 (push logfile notests)
1497 (setq ntests (+ ntests (string-to-number (match-string 1))))
1498 (if (not (re-search-forward "^\\(Aborted: \\)?\
1499 Ran \\([0-9]+\\) tests, \\([0-9]+\\) results as expected\
1500 \\(?:, \\([0-9]+\\) unexpected\\)?\
1501 \\(?:, \\([0-9]+\\) skipped\\)?" nil t))
1502 (push logfile badtests)
1503 (if (match-string 1) (push logfile badtests))
1504 (setq nrun (+ nrun (string-to-number (match-string 2)))
1505 nexpected (+ nexpected (string-to-number (match-string 3))))
1506 (when (match-string 4)
1507 (push logfile unexpected)
1508 (setq nunexpected (+ nunexpected
1509 (string-to-number (match-string 4)))))
1510 (when (match-string 5)
1511 (push logfile skipped)
1512 (setq nskipped (+ nskipped
1513 (string-to-number (match-string 5)))))))))
1514 (setq nnotrun (- ntests nrun))
1515 (message "\nSUMMARY OF TEST RESULTS")
1516 (message "-----------------------")
1517 (message "Files examined: %d" nlogs)
1518 (message "Ran %d tests%s, %d results as expected%s%s"
1519 nrun
1520 (if (zerop nnotrun) "" (format ", %d failed to run" nnotrun))
1521 nexpected
1522 (if (zerop nunexpected)
1524 (format ", %d unexpected" nunexpected))
1525 (if (zerop nskipped)
1527 (format ", %d skipped" nskipped)))
1528 (when notests
1529 (message "%d files did not contain any tests:" (length notests))
1530 (mapc (lambda (l) (message " %s" l)) notests))
1531 (when badtests
1532 (message "%d files did not finish:" (length badtests))
1533 (mapc (lambda (l) (message " %s" l)) badtests))
1534 (when unexpected
1535 (message "%d files contained unexpected results:" (length unexpected))
1536 (mapc (lambda (l) (message " %s" l)) unexpected))
1537 ;; More details on hydra, where the logs are harder to get to.
1538 (when (and (getenv "EMACS_HYDRA_CI")
1539 (not (zerop (+ nunexpected nskipped))))
1540 (message "\nDETAILS")
1541 (message "-------")
1542 (with-temp-buffer
1543 (dolist (x (list (list skipped "skipped" "SKIPPED")
1544 (list unexpected "unexpected" "FAILED")))
1545 (mapc (lambda (l)
1546 (erase-buffer)
1547 (insert-file-contents l)
1548 (message "%s:" l)
1549 (when (re-search-forward (format "^[ \t]*[0-9]+ %s results:"
1550 (nth 1 x))
1551 nil t)
1552 (while (and (zerop (forward-line 1))
1553 (looking-at (format "^[ \t]*%s" (nth 2 x))))
1554 (message "%s" (buffer-substring (line-beginning-position)
1555 (line-end-position))))))
1556 (car x)))))
1557 (kill-emacs (cond ((or notests badtests (not (zerop nnotrun))) 2)
1558 (unexpected 1)
1559 (t 0)))))
1561 ;;; Utility functions for load/unload actions.
1563 (defun ert--activate-font-lock-keywords ()
1564 "Activate font-lock keywords for some of ERT's symbols."
1565 (font-lock-add-keywords
1567 '(("(\\(\\<ert-deftest\\)\\>\\s *\\(\\(?:\\sw\\|\\s_\\)+\\)?"
1568 (1 font-lock-keyword-face nil t)
1569 (2 font-lock-function-name-face nil t)))))
1571 (cl-defun ert--remove-from-list (list-var element &key key test)
1572 "Remove ELEMENT from the value of LIST-VAR if present.
1574 This can be used as an inverse of `add-to-list'."
1575 (unless key (setq key #'identity))
1576 (unless test (setq test #'equal))
1577 (setf (symbol-value list-var)
1578 (cl-remove element
1579 (symbol-value list-var)
1580 :key key
1581 :test test)))
1584 ;;; Some basic interactive functions.
1586 (defun ert-read-test-name (prompt &optional default history
1587 add-default-to-prompt)
1588 "Read the name of a test and return it as a symbol.
1590 Prompt with PROMPT. If DEFAULT is a valid test name, use it as a
1591 default. HISTORY is the history to use; see `completing-read'.
1592 If ADD-DEFAULT-TO-PROMPT is non-nil, PROMPT will be modified to
1593 include the default, if any.
1595 Signals an error if no test name was read."
1596 (cl-etypecase default
1597 (string (let ((symbol (intern-soft default)))
1598 (unless (and symbol (ert-test-boundp symbol))
1599 (setq default nil))))
1600 (symbol (setq default
1601 (if (ert-test-boundp default)
1602 (symbol-name default)
1603 nil)))
1604 (ert-test (setq default (ert-test-name default))))
1605 (when add-default-to-prompt
1606 (setq prompt (if (null default)
1607 (format "%s: " prompt)
1608 (format "%s (default %s): " prompt default))))
1609 (let ((input (completing-read prompt obarray #'ert-test-boundp
1610 t nil history default nil)))
1611 ;; completing-read returns an empty string if default was nil and
1612 ;; the user just hit enter.
1613 (let ((sym (intern-soft input)))
1614 (if (ert-test-boundp sym)
1616 (user-error "Input does not name a test")))))
1618 (defun ert-read-test-name-at-point (prompt)
1619 "Read the name of a test and return it as a symbol.
1620 As a default, use the symbol at point, or the test at point if in
1621 the ERT results buffer. Prompt with PROMPT, augmented with the
1622 default (if any)."
1623 (ert-read-test-name prompt (ert-test-at-point) nil t))
1625 (defun ert-find-test-other-window (test-name)
1626 "Find, in another window, the definition of TEST-NAME."
1627 (interactive (list (ert-read-test-name-at-point "Find test definition: ")))
1628 (find-function-do-it test-name 'ert--test 'switch-to-buffer-other-window))
1630 (defun ert-delete-test (test-name)
1631 "Make the test TEST-NAME unbound.
1633 Nothing more than an interactive interface to `ert-make-test-unbound'."
1634 (interactive (list (ert-read-test-name-at-point "Delete test")))
1635 (ert-make-test-unbound test-name))
1637 (defun ert-delete-all-tests ()
1638 "Make all symbols in `obarray' name no test."
1639 (interactive)
1640 (when (called-interactively-p 'any)
1641 (unless (y-or-n-p "Delete all tests? ")
1642 (user-error "Aborted")))
1643 ;; We can't use `ert-select-tests' here since that gives us only
1644 ;; test objects, and going from them back to the test name symbols
1645 ;; can fail if the `ert-test' defstruct has been redefined.
1646 (mapc #'ert-make-test-unbound (apropos-internal "" #'ert-test-boundp))
1650 ;;; Display of test progress and results.
1652 ;; An entry in the results buffer ewoc. There is one entry per test.
1653 (cl-defstruct ert--ewoc-entry
1654 (test (cl-assert nil))
1655 ;; If the result of this test was expected, its ewoc entry is hidden
1656 ;; initially.
1657 (hidden-p (cl-assert nil))
1658 ;; An ewoc entry may be collapsed to hide details such as the error
1659 ;; condition.
1661 ;; I'm not sure the ability to expand and collapse entries is still
1662 ;; a useful feature.
1663 (expanded-p t)
1664 ;; By default, the ewoc entry presents the error condition with
1665 ;; certain limits on how much to print (`print-level',
1666 ;; `print-length'). The user can interactively switch to a set of
1667 ;; higher limits.
1668 (extended-printer-limits-p nil))
1670 ;; Variables local to the results buffer.
1672 ;; The ewoc.
1673 (defvar ert--results-ewoc)
1674 ;; The stats object.
1675 (defvar ert--results-stats)
1676 ;; A string with one character per test. Each character represents
1677 ;; the result of the corresponding test. The string is displayed near
1678 ;; the top of the buffer and serves as a progress bar.
1679 (defvar ert--results-progress-bar-string)
1680 ;; The position where the progress bar button begins.
1681 (defvar ert--results-progress-bar-button-begin)
1682 ;; The test result listener that updates the buffer when tests are run.
1683 (defvar ert--results-listener)
1685 (defun ert-insert-test-name-button (test-name)
1686 "Insert a button that links to TEST-NAME."
1687 (insert-text-button (format "%S" test-name)
1688 :type 'ert--test-name-button
1689 'ert-test-name test-name))
1691 (defun ert--results-format-expected-unexpected (expected unexpected)
1692 "Return a string indicating EXPECTED expected results, UNEXPECTED unexpected."
1693 (if (zerop unexpected)
1694 (format "%s" expected)
1695 (format "%s (%s unexpected)" (+ expected unexpected) unexpected)))
1697 (defun ert--results-update-ewoc-hf (ewoc stats)
1698 "Update the header and footer of EWOC to show certain information from STATS.
1700 Also sets `ert--results-progress-bar-button-begin'."
1701 (let ((run-count (ert-stats-completed stats))
1702 (results-buffer (current-buffer))
1703 ;; Need to save buffer-local value.
1704 (font-lock font-lock-mode))
1705 (ewoc-set-hf
1706 ewoc
1707 ;; header
1708 (with-temp-buffer
1709 (insert "Selector: ")
1710 (ert--insert-human-readable-selector (ert--stats-selector stats))
1711 (insert "\n")
1712 (insert
1713 (format (concat "Passed: %s\n"
1714 "Failed: %s\n"
1715 "Skipped: %s\n"
1716 "Total: %s/%s\n\n")
1717 (ert--results-format-expected-unexpected
1718 (ert--stats-passed-expected stats)
1719 (ert--stats-passed-unexpected stats))
1720 (ert--results-format-expected-unexpected
1721 (ert--stats-failed-expected stats)
1722 (ert--stats-failed-unexpected stats))
1723 (ert-stats-skipped stats)
1724 run-count
1725 (ert-stats-total stats)))
1726 (insert
1727 (format "Started at: %s\n"
1728 (ert--format-time-iso8601 (ert--stats-start-time stats))))
1729 ;; FIXME: This is ugly. Need to properly define invariants of
1730 ;; the `stats' data structure.
1731 (let ((state (cond ((ert--stats-aborted-p stats) 'aborted)
1732 ((ert--stats-current-test stats) 'running)
1733 ((ert--stats-end-time stats) 'finished)
1734 (t 'preparing))))
1735 (cl-ecase state
1736 (preparing
1737 (insert ""))
1738 (aborted
1739 (cond ((ert--stats-current-test stats)
1740 (insert "Aborted during test: ")
1741 (ert-insert-test-name-button
1742 (ert-test-name (ert--stats-current-test stats))))
1744 (insert "Aborted."))))
1745 (running
1746 (cl-assert (ert--stats-current-test stats))
1747 (insert "Running test: ")
1748 (ert-insert-test-name-button (ert-test-name
1749 (ert--stats-current-test stats))))
1750 (finished
1751 (cl-assert (not (ert--stats-current-test stats)))
1752 (insert "Finished.")))
1753 (insert "\n")
1754 (if (ert--stats-end-time stats)
1755 (insert
1756 (format "%s%s\n"
1757 (if (ert--stats-aborted-p stats)
1758 "Aborted at: "
1759 "Finished at: ")
1760 (ert--format-time-iso8601 (ert--stats-end-time stats))))
1761 (insert "\n"))
1762 (insert "\n"))
1763 (let ((progress-bar-string (with-current-buffer results-buffer
1764 ert--results-progress-bar-string)))
1765 (let ((progress-bar-button-begin
1766 (insert-text-button progress-bar-string
1767 :type 'ert--results-progress-bar-button
1768 'face (or (and font-lock
1769 (ert-face-for-stats stats))
1770 'button))))
1771 ;; The header gets copied verbatim to the results buffer,
1772 ;; and all positions remain the same, so
1773 ;; `progress-bar-button-begin' will be the right position
1774 ;; even in the results buffer.
1775 (with-current-buffer results-buffer
1776 (set (make-local-variable 'ert--results-progress-bar-button-begin)
1777 progress-bar-button-begin))))
1778 (insert "\n\n")
1779 (buffer-string))
1780 ;; footer
1782 ;; We actually want an empty footer, but that would trigger a bug
1783 ;; in ewoc, sometimes clearing the entire buffer. (It's possible
1784 ;; that this bug has been fixed since this has been tested; we
1785 ;; should test it again.)
1786 "\n")))
1789 (defvar ert-test-run-redisplay-interval-secs .1
1790 "How many seconds ERT should wait between redisplays while running tests.
1792 While running tests, ERT shows the current progress, and this variable
1793 determines how frequently the progress display is updated.")
1795 (defun ert--results-update-stats-display (ewoc stats)
1796 "Update EWOC and the mode line to show data from STATS."
1797 ;; TODO(ohler): investigate using `make-progress-reporter'.
1798 (ert--results-update-ewoc-hf ewoc stats)
1799 (force-mode-line-update)
1800 (redisplay t)
1801 (setf (ert--stats-next-redisplay stats)
1802 (+ (float-time) ert-test-run-redisplay-interval-secs)))
1804 (defun ert--results-update-stats-display-maybe (ewoc stats)
1805 "Call `ert--results-update-stats-display' if not called recently.
1807 EWOC and STATS are arguments for `ert--results-update-stats-display'."
1808 (when (>= (float-time) (ert--stats-next-redisplay stats))
1809 (ert--results-update-stats-display ewoc stats)))
1811 (defun ert--tests-running-mode-line-indicator ()
1812 "Return a string for the mode line that shows the test run progress."
1813 (let* ((stats ert--current-run-stats)
1814 (tests-total (ert-stats-total stats))
1815 (tests-completed (ert-stats-completed stats)))
1816 (if (>= tests-completed tests-total)
1817 (format " ERT(%s/%s,finished)" tests-completed tests-total)
1818 (format " ERT(%s/%s):%s"
1819 (1+ tests-completed)
1820 tests-total
1821 (if (null (ert--stats-current-test stats))
1823 (format "%S"
1824 (ert-test-name (ert--stats-current-test stats))))))))
1826 (defun ert--make-xrefs-region (begin end)
1827 "Attach cross-references to function names between BEGIN and END.
1829 BEGIN and END specify a region in the current buffer."
1830 (save-excursion
1831 (goto-char begin)
1832 (while (progn
1833 (goto-char (+ (point) 2))
1834 (skip-syntax-forward "^w_")
1835 (< (point) end))
1836 (let* ((beg (point))
1837 (end (progn (skip-syntax-forward "w_") (point)))
1838 (sym (intern-soft (buffer-substring-no-properties
1839 beg end)))
1840 (file (and sym (symbol-file sym 'defun))))
1841 (when file
1842 (goto-char beg)
1843 ;; help-xref-button needs to operate on something matched
1844 ;; by a regexp, so set that up for it.
1845 (re-search-forward "\\(\\sw\\|\\s_\\)+")
1846 (help-xref-button 0 'help-function-def sym file)))
1847 (forward-line 1))))
1849 (defun ert--string-first-line (s)
1850 "Return the first line of S, or S if it contains no newlines.
1852 The return value does not include the line terminator."
1853 (substring s 0 (cl-position ?\n s)))
1855 (defun ert-face-for-test-result (expectedp)
1856 "Return a face that shows whether a test result was expected or unexpected.
1858 If EXPECTEDP is nil, returns the face for unexpected results; if
1859 non-nil, returns the face for expected results.."
1860 (if expectedp 'ert-test-result-expected 'ert-test-result-unexpected))
1862 (defun ert-face-for-stats (stats)
1863 "Return a face that represents STATS."
1864 (cond ((ert--stats-aborted-p stats) 'nil)
1865 ((cl-plusp (ert-stats-completed-unexpected stats))
1866 (ert-face-for-test-result nil))
1867 ((eql (ert-stats-completed-expected stats) (ert-stats-total stats))
1868 (ert-face-for-test-result t))
1869 (t 'nil)))
1871 (defun ert--print-test-for-ewoc (entry)
1872 "The ewoc print function for ewoc test entries. ENTRY is the entry to print."
1873 (let* ((test (ert--ewoc-entry-test entry))
1874 (stats ert--results-stats)
1875 (result (let ((pos (ert--stats-test-pos stats test)))
1876 (cl-assert pos)
1877 (aref (ert--stats-test-results stats) pos)))
1878 (hiddenp (ert--ewoc-entry-hidden-p entry))
1879 (expandedp (ert--ewoc-entry-expanded-p entry))
1880 (extended-printer-limits-p (ert--ewoc-entry-extended-printer-limits-p
1881 entry)))
1882 (cond (hiddenp)
1884 (let ((expectedp (ert-test-result-expected-p test result)))
1885 (insert-text-button (format "%c" (ert-char-for-test-result
1886 result expectedp))
1887 :type 'ert--results-expand-collapse-button
1888 'face (or (and font-lock-mode
1889 (ert-face-for-test-result
1890 expectedp))
1891 'button)))
1892 (insert " ")
1893 (ert-insert-test-name-button (ert-test-name test))
1894 (insert "\n")
1895 (when (and expandedp (not (eql result 'nil)))
1896 (when (ert-test-documentation test)
1897 (insert " "
1898 (propertize
1899 (ert--string-first-line
1900 (substitute-command-keys
1901 (ert-test-documentation test)))
1902 'font-lock-face 'font-lock-doc-face)
1903 "\n"))
1904 (cl-etypecase result
1905 (ert-test-passed
1906 (if (ert-test-result-expected-p test result)
1907 (insert " passed\n")
1908 (insert " passed unexpectedly\n"))
1909 (insert ""))
1910 (ert-test-result-with-condition
1911 (ert--insert-infos result)
1912 (let ((print-escape-newlines t)
1913 (print-level (if extended-printer-limits-p 12 6))
1914 (print-length (if extended-printer-limits-p 100 10)))
1915 (insert " ")
1916 (let ((begin (point)))
1917 (ert--pp-with-indentation-and-newline
1918 (ert-test-result-with-condition-condition result))
1919 (ert--make-xrefs-region begin (point)))))
1920 (ert-test-aborted-with-non-local-exit
1921 (insert " aborted\n"))
1922 (ert-test-quit
1923 (insert " quit\n")))
1924 (insert "\n")))))
1925 nil)
1927 (defun ert--results-font-lock-function (enabledp)
1928 "Redraw the ERT results buffer after font-lock-mode was switched on or off.
1930 ENABLEDP is true if font-lock-mode is switched on, false
1931 otherwise."
1932 (ert--results-update-ewoc-hf ert--results-ewoc ert--results-stats)
1933 (ewoc-refresh ert--results-ewoc)
1934 (font-lock-default-function enabledp))
1936 (defun ert--setup-results-buffer (stats listener buffer-name)
1937 "Set up a test results buffer.
1939 STATS is the stats object; LISTENER is the results listener;
1940 BUFFER-NAME, if non-nil, is the buffer name to use."
1941 (unless buffer-name (setq buffer-name "*ert*"))
1942 (let ((buffer (get-buffer-create buffer-name)))
1943 (with-current-buffer buffer
1944 (let ((inhibit-read-only t))
1945 (buffer-disable-undo)
1946 (erase-buffer)
1947 (ert-results-mode)
1948 ;; Erase buffer again in case switching out of the previous
1949 ;; mode inserted anything. (This happens e.g. when switching
1950 ;; from ert-results-mode to ert-results-mode when
1951 ;; font-lock-mode turns itself off in change-major-mode-hook.)
1952 (erase-buffer)
1953 (set (make-local-variable 'font-lock-function)
1954 'ert--results-font-lock-function)
1955 (let ((ewoc (ewoc-create 'ert--print-test-for-ewoc nil nil t)))
1956 (set (make-local-variable 'ert--results-ewoc) ewoc)
1957 (set (make-local-variable 'ert--results-stats) stats)
1958 (set (make-local-variable 'ert--results-progress-bar-string)
1959 (make-string (ert-stats-total stats)
1960 (ert-char-for-test-result nil t)))
1961 (set (make-local-variable 'ert--results-listener) listener)
1962 (cl-loop for test across (ert--stats-tests stats) do
1963 (ewoc-enter-last ewoc
1964 (make-ert--ewoc-entry :test test
1965 :hidden-p t)))
1966 (ert--results-update-ewoc-hf ert--results-ewoc ert--results-stats)
1967 (goto-char (1- (point-max)))
1968 buffer)))))
1971 (defvar ert--selector-history nil
1972 "List of recent test selectors read from terminal.")
1974 ;; Should OUTPUT-BUFFER-NAME and MESSAGE-FN really be arguments here?
1975 ;; They are needed only for our automated self-tests at the moment.
1976 ;; Or should there be some other mechanism?
1977 ;;;###autoload
1978 (defun ert-run-tests-interactively (selector
1979 &optional output-buffer-name message-fn)
1980 "Run the tests specified by SELECTOR and display the results in a buffer.
1982 SELECTOR works as described in `ert-select-tests'.
1983 OUTPUT-BUFFER-NAME and MESSAGE-FN should normally be nil; they
1984 are used for automated self-tests and specify which buffer to use
1985 and how to display message."
1986 (interactive
1987 (list (let ((default (if ert--selector-history
1988 ;; Can't use `first' here as this form is
1989 ;; not compiled, and `first' is not
1990 ;; defined without cl.
1991 (car ert--selector-history)
1992 "t")))
1993 (read
1994 (completing-read (if (null default)
1995 "Run tests: "
1996 (format "Run tests (default %s): " default))
1997 obarray #'ert-test-boundp nil nil
1998 'ert--selector-history default nil)))
1999 nil))
2000 (unless message-fn (setq message-fn 'message))
2001 (let ((output-buffer-name output-buffer-name)
2002 buffer
2003 listener
2004 (message-fn message-fn))
2005 (setq listener
2006 (lambda (event-type &rest event-args)
2007 (cl-ecase event-type
2008 (run-started
2009 (cl-destructuring-bind (stats) event-args
2010 (setq buffer (ert--setup-results-buffer stats
2011 listener
2012 output-buffer-name))
2013 (pop-to-buffer buffer)))
2014 (run-ended
2015 (cl-destructuring-bind (stats abortedp) event-args
2016 (funcall message-fn
2017 "%sRan %s tests, %s results were as expected%s%s"
2018 (if (not abortedp)
2020 "Aborted: ")
2021 (ert-stats-total stats)
2022 (ert-stats-completed-expected stats)
2023 (let ((unexpected
2024 (ert-stats-completed-unexpected stats)))
2025 (if (zerop unexpected)
2027 (format ", %s unexpected" unexpected)))
2028 (let ((skipped
2029 (ert-stats-skipped stats)))
2030 (if (zerop skipped)
2032 (format ", %s skipped" skipped))))
2033 (ert--results-update-stats-display (with-current-buffer buffer
2034 ert--results-ewoc)
2035 stats)))
2036 (test-started
2037 (cl-destructuring-bind (stats test) event-args
2038 (with-current-buffer buffer
2039 (let* ((ewoc ert--results-ewoc)
2040 (pos (ert--stats-test-pos stats test))
2041 (node (ewoc-nth ewoc pos)))
2042 (cl-assert node)
2043 (setf (ert--ewoc-entry-test (ewoc-data node)) test)
2044 (aset ert--results-progress-bar-string pos
2045 (ert-char-for-test-result nil t))
2046 (ert--results-update-stats-display-maybe ewoc stats)
2047 (ewoc-invalidate ewoc node)))))
2048 (test-ended
2049 (cl-destructuring-bind (stats test result) event-args
2050 (with-current-buffer buffer
2051 (let* ((ewoc ert--results-ewoc)
2052 (pos (ert--stats-test-pos stats test))
2053 (node (ewoc-nth ewoc pos)))
2054 (when (ert--ewoc-entry-hidden-p (ewoc-data node))
2055 (setf (ert--ewoc-entry-hidden-p (ewoc-data node))
2056 (ert-test-result-expected-p test result)))
2057 (aset ert--results-progress-bar-string pos
2058 (ert-char-for-test-result result
2059 (ert-test-result-expected-p
2060 test result)))
2061 (ert--results-update-stats-display-maybe ewoc stats)
2062 (ewoc-invalidate ewoc node))))))))
2063 (ert-run-tests selector listener t)))
2065 ;;;###autoload
2066 (defalias 'ert 'ert-run-tests-interactively)
2069 ;;; Simple view mode for auxiliary information like stack traces or
2070 ;;; messages. Mainly binds "q" for quit.
2072 (define-derived-mode ert-simple-view-mode special-mode "ERT-View"
2073 "Major mode for viewing auxiliary information in ERT.")
2075 ;;; Commands and button actions for the results buffer.
2077 (define-derived-mode ert-results-mode special-mode "ERT-Results"
2078 "Major mode for viewing results of ERT test runs.")
2080 (cl-loop for (key binding) in
2081 '( ;; Stuff that's not in the menu.
2082 ("\t" forward-button)
2083 ([backtab] backward-button)
2084 ("j" ert-results-jump-between-summary-and-result)
2085 ("L" ert-results-toggle-printer-limits-for-test-at-point)
2086 ("n" ert-results-next-test)
2087 ("p" ert-results-previous-test)
2088 ;; Stuff that is in the menu.
2089 ("R" ert-results-rerun-all-tests)
2090 ("r" ert-results-rerun-test-at-point)
2091 ("d" ert-results-rerun-test-at-point-debugging-errors)
2092 ("." ert-results-find-test-at-point-other-window)
2093 ("b" ert-results-pop-to-backtrace-for-test-at-point)
2094 ("m" ert-results-pop-to-messages-for-test-at-point)
2095 ("l" ert-results-pop-to-should-forms-for-test-at-point)
2096 ("h" ert-results-describe-test-at-point)
2097 ("D" ert-delete-test)
2098 ("T" ert-results-pop-to-timings)
2101 (define-key ert-results-mode-map key binding))
2103 (easy-menu-define ert-results-mode-menu ert-results-mode-map
2104 "Menu for `ert-results-mode'."
2105 '("ERT Results"
2106 ["Re-run all tests" ert-results-rerun-all-tests]
2107 "--"
2108 ;; FIXME? Why are there (at least) 3 different ways to decide if
2109 ;; there is a test at point?
2110 ["Re-run test" ert-results-rerun-test-at-point
2111 :active (car (ert--results-test-at-point-allow-redefinition))]
2112 ["Debug test" ert-results-rerun-test-at-point-debugging-errors
2113 :active (car (ert--results-test-at-point-allow-redefinition))]
2114 ["Show test definition" ert-results-find-test-at-point-other-window
2115 :active (ert-test-at-point)]
2116 "--"
2117 ["Show backtrace" ert-results-pop-to-backtrace-for-test-at-point
2118 :active (ert--results-test-at-point-no-redefinition)]
2119 ["Show messages" ert-results-pop-to-messages-for-test-at-point
2120 :active (ert--results-test-at-point-no-redefinition)]
2121 ["Show `should' forms" ert-results-pop-to-should-forms-for-test-at-point
2122 :active (ert--results-test-at-point-no-redefinition)]
2123 ["Describe test" ert-results-describe-test-at-point
2124 :active (ert--results-test-at-point-no-redefinition)]
2125 "--"
2126 ["Delete test" ert-delete-test]
2127 "--"
2128 ["Show execution time of each test" ert-results-pop-to-timings]
2131 (define-button-type 'ert--results-progress-bar-button
2132 'action #'ert--results-progress-bar-button-action
2133 'help-echo "mouse-2, RET: Reveal test result")
2135 (define-button-type 'ert--test-name-button
2136 'action #'ert--test-name-button-action
2137 'help-echo "mouse-2, RET: Find test definition")
2139 (define-button-type 'ert--results-expand-collapse-button
2140 'action #'ert--results-expand-collapse-button-action
2141 'help-echo "mouse-2, RET: Expand/collapse test result")
2143 (defun ert--results-test-node-or-null-at-point ()
2144 "If point is on a valid ewoc node, return it; return nil otherwise.
2146 To be used in the ERT results buffer."
2147 (let* ((ewoc ert--results-ewoc)
2148 (node (ewoc-locate ewoc)))
2149 ;; `ewoc-locate' will return an arbitrary node when point is on
2150 ;; header or footer, or when all nodes are invisible. So we need
2151 ;; to validate its return value here.
2153 ;; Update: I'm seeing nil being returned in some cases now,
2154 ;; perhaps this has been changed?
2155 (if (and node
2156 (>= (point) (ewoc-location node))
2157 (not (ert--ewoc-entry-hidden-p (ewoc-data node))))
2158 node
2159 nil)))
2161 (defun ert--results-test-node-at-point ()
2162 "If point is on a valid ewoc node, return it; signal an error otherwise.
2164 To be used in the ERT results buffer."
2165 (or (ert--results-test-node-or-null-at-point)
2166 (user-error "No test at point")))
2168 (defun ert-results-next-test ()
2169 "Move point to the next test.
2171 To be used in the ERT results buffer."
2172 (interactive)
2173 (ert--results-move (ewoc-locate ert--results-ewoc) 'ewoc-next
2174 "No tests below"))
2176 (defun ert-results-previous-test ()
2177 "Move point to the previous test.
2179 To be used in the ERT results buffer."
2180 (interactive)
2181 (ert--results-move (ewoc-locate ert--results-ewoc) 'ewoc-prev
2182 "No tests above"))
2184 (defun ert--results-move (node ewoc-fn error-message)
2185 "Move point from NODE to the previous or next node.
2187 EWOC-FN specifies the direction and should be either `ewoc-prev'
2188 or `ewoc-next'. If there are no more nodes in that direction, a
2189 user-error is signaled with the message ERROR-MESSAGE."
2190 (cl-loop
2191 (setq node (funcall ewoc-fn ert--results-ewoc node))
2192 (when (null node)
2193 (user-error "%s" error-message))
2194 (unless (ert--ewoc-entry-hidden-p (ewoc-data node))
2195 (goto-char (ewoc-location node))
2196 (cl-return))))
2198 (defun ert--results-expand-collapse-button-action (_button)
2199 "Expand or collapse the test node BUTTON belongs to."
2200 (let* ((ewoc ert--results-ewoc)
2201 (node (save-excursion
2202 (goto-char (ert--button-action-position))
2203 (ert--results-test-node-at-point)))
2204 (entry (ewoc-data node)))
2205 (setf (ert--ewoc-entry-expanded-p entry)
2206 (not (ert--ewoc-entry-expanded-p entry)))
2207 (ewoc-invalidate ewoc node)))
2209 (defun ert-results-find-test-at-point-other-window ()
2210 "Find the definition of the test at point in another window.
2212 To be used in the ERT results buffer."
2213 (interactive)
2214 (let ((name (ert-test-at-point)))
2215 (unless name
2216 (user-error "No test at point"))
2217 (ert-find-test-other-window name)))
2219 (defun ert--test-name-button-action (button)
2220 "Find the definition of the test BUTTON belongs to, in another window."
2221 (let ((name (button-get button 'ert-test-name)))
2222 (ert-find-test-other-window name)))
2224 (defun ert--ewoc-position (ewoc node)
2225 ;; checkdoc-order: nil
2226 "Return the position of NODE in EWOC, or nil if NODE is not in EWOC."
2227 (cl-loop for i from 0
2228 for node-here = (ewoc-nth ewoc 0) then (ewoc-next ewoc node-here)
2229 do (when (eql node node-here)
2230 (cl-return i))
2231 finally (cl-return nil)))
2233 (defun ert-results-jump-between-summary-and-result ()
2234 "Jump back and forth between the test run summary and individual test results.
2236 From an ewoc node, jumps to the character that represents the
2237 same test in the progress bar, and vice versa.
2239 To be used in the ERT results buffer."
2240 ;; Maybe this command isn't actually needed much, but if it is, it
2241 ;; seems like an indication that the UI design is not optimal. If
2242 ;; jumping back and forth between a summary at the top of the buffer
2243 ;; and the error log in the remainder of the buffer is useful, then
2244 ;; the summary apparently needs to be easily accessible from the
2245 ;; error log, and perhaps it would be better to have it in a
2246 ;; separate buffer to keep it visible.
2247 (interactive)
2248 (let ((ewoc ert--results-ewoc)
2249 (progress-bar-begin ert--results-progress-bar-button-begin))
2250 (cond ((ert--results-test-node-or-null-at-point)
2251 (let* ((node (ert--results-test-node-at-point))
2252 (pos (ert--ewoc-position ewoc node)))
2253 (goto-char (+ progress-bar-begin pos))))
2254 ((and (<= progress-bar-begin (point))
2255 (< (point) (button-end (button-at progress-bar-begin))))
2256 (let* ((node (ewoc-nth ewoc (- (point) progress-bar-begin)))
2257 (entry (ewoc-data node)))
2258 (when (ert--ewoc-entry-hidden-p entry)
2259 (setf (ert--ewoc-entry-hidden-p entry) nil)
2260 (ewoc-invalidate ewoc node))
2261 (ewoc-goto-node ewoc node)))
2263 (goto-char progress-bar-begin)))))
2265 (defun ert-test-at-point ()
2266 "Return the name of the test at point as a symbol, or nil if none."
2267 (or (and (eql major-mode 'ert-results-mode)
2268 (let ((test (ert--results-test-at-point-no-redefinition)))
2269 (and test (ert-test-name test))))
2270 (let* ((thing (thing-at-point 'symbol))
2271 (sym (intern-soft thing)))
2272 (and (ert-test-boundp sym)
2273 sym))))
2275 (defun ert--results-test-at-point-no-redefinition (&optional error)
2276 "Return the test at point, or nil.
2277 If optional argument ERROR is non-nil, signal an error rather than return nil.
2278 To be used in the ERT results buffer."
2279 (cl-assert (eql major-mode 'ert-results-mode))
2281 (if (ert--results-test-node-or-null-at-point)
2282 (let* ((node (ert--results-test-node-at-point))
2283 (test (ert--ewoc-entry-test (ewoc-data node))))
2284 test)
2285 (let ((progress-bar-begin ert--results-progress-bar-button-begin))
2286 (when (and (<= progress-bar-begin (point))
2287 (< (point) (button-end (button-at progress-bar-begin))))
2288 (let* ((test-index (- (point) progress-bar-begin))
2289 (test (aref (ert--stats-tests ert--results-stats)
2290 test-index)))
2291 test))))
2292 (if error (user-error "No test at point"))))
2294 (defun ert--results-test-at-point-allow-redefinition ()
2295 "Look up the test at point, and check whether it has been redefined.
2297 To be used in the ERT results buffer.
2299 Returns a list of two elements: the test (or nil) and a symbol
2300 specifying whether the test has been redefined.
2302 If a new test has been defined with the same name as the test at
2303 point, replaces the test at point with the new test, and returns
2304 the new test and the symbol `redefined'.
2306 If the test has been deleted, returns the old test and the symbol
2307 `deleted'.
2309 If the test is still current, returns the test and the symbol nil.
2311 If there is no test at point, returns a list with two nils."
2312 (let ((test (ert--results-test-at-point-no-redefinition)))
2313 (cond ((null test)
2314 `(nil nil))
2315 ((null (ert-test-name test))
2316 `(,test nil))
2318 (let* ((name (ert-test-name test))
2319 (new-test (and (ert-test-boundp name)
2320 (ert-get-test name))))
2321 (cond ((eql test new-test)
2322 `(,test nil))
2323 ((null new-test)
2324 `(,test deleted))
2326 (ert--results-update-after-test-redefinition
2327 (ert--stats-test-pos ert--results-stats test)
2328 new-test)
2329 `(,new-test redefined))))))))
2331 (defun ert--results-update-after-test-redefinition (pos new-test)
2332 "Update results buffer after the test at pos POS has been redefined.
2334 Also updates the stats object. NEW-TEST is the new test
2335 definition."
2336 (let* ((stats ert--results-stats)
2337 (ewoc ert--results-ewoc)
2338 (node (ewoc-nth ewoc pos))
2339 (entry (ewoc-data node)))
2340 (ert--stats-set-test-and-result stats pos new-test nil)
2341 (setf (ert--ewoc-entry-test entry) new-test
2342 (aref ert--results-progress-bar-string pos) (ert-char-for-test-result
2343 nil t))
2344 (ewoc-invalidate ewoc node))
2345 nil)
2347 (defun ert--button-action-position ()
2348 "The buffer position where the last button action was triggered."
2349 (cond ((integerp last-command-event)
2350 (point))
2351 ((eventp last-command-event)
2352 (posn-point (event-start last-command-event)))
2353 (t (cl-assert nil))))
2355 (defun ert--results-progress-bar-button-action (_button)
2356 "Jump to details for the test represented by the character clicked in BUTTON."
2357 (goto-char (ert--button-action-position))
2358 (ert-results-jump-between-summary-and-result))
2360 (defun ert-results-rerun-all-tests ()
2361 "Re-run all tests, using the same selector.
2363 To be used in the ERT results buffer."
2364 (interactive)
2365 (cl-assert (eql major-mode 'ert-results-mode))
2366 (let ((selector (ert--stats-selector ert--results-stats)))
2367 (ert-run-tests-interactively selector (buffer-name))))
2369 (defun ert-results-rerun-test-at-point ()
2370 "Re-run the test at point.
2372 To be used in the ERT results buffer."
2373 (interactive)
2374 (cl-destructuring-bind (test redefinition-state)
2375 (ert--results-test-at-point-allow-redefinition)
2376 (when (null test)
2377 (user-error "No test at point"))
2378 (let* ((stats ert--results-stats)
2379 (progress-message (format "Running %stest %S"
2380 (cl-ecase redefinition-state
2381 ((nil) "")
2382 (redefined "new definition of ")
2383 (deleted "deleted "))
2384 (ert-test-name test))))
2385 ;; Need to save and restore point manually here: When point is on
2386 ;; the first visible ewoc entry while the header is updated, point
2387 ;; moves to the top of the buffer. This is undesirable, and a
2388 ;; simple `save-excursion' doesn't prevent it.
2389 (let ((point (point)))
2390 (unwind-protect
2391 (unwind-protect
2392 (progn
2393 (message "%s..." progress-message)
2394 (ert-run-or-rerun-test stats test
2395 ert--results-listener))
2396 (ert--results-update-stats-display ert--results-ewoc stats)
2397 (message "%s...%s"
2398 progress-message
2399 (let ((result (ert-test-most-recent-result test)))
2400 (ert-string-for-test-result
2401 result (ert-test-result-expected-p test result)))))
2402 (goto-char point))))))
2404 (defun ert-results-rerun-test-at-point-debugging-errors ()
2405 "Re-run the test at point with `ert-debug-on-error' bound to t.
2407 To be used in the ERT results buffer."
2408 (interactive)
2409 (let ((ert-debug-on-error t))
2410 (ert-results-rerun-test-at-point)))
2412 (defun ert-results-pop-to-backtrace-for-test-at-point ()
2413 "Display the backtrace for the test at point.
2415 To be used in the ERT results buffer."
2416 (interactive)
2417 (let* ((test (ert--results-test-at-point-no-redefinition t))
2418 (stats ert--results-stats)
2419 (pos (ert--stats-test-pos stats test))
2420 (result (aref (ert--stats-test-results stats) pos)))
2421 (cl-etypecase result
2422 (ert-test-passed (error "Test passed, no backtrace available"))
2423 (ert-test-result-with-condition
2424 (let ((backtrace (ert-test-result-with-condition-backtrace result))
2425 (buffer (get-buffer-create "*ERT Backtrace*")))
2426 (pop-to-buffer buffer)
2427 (let ((inhibit-read-only t))
2428 (buffer-disable-undo)
2429 (erase-buffer)
2430 (ert-simple-view-mode)
2431 (set-buffer-multibyte t) ; mimic debugger-setup-buffer
2432 (setq truncate-lines t)
2433 (ert--print-backtrace backtrace t)
2434 (goto-char (point-min))
2435 (insert (substitute-command-keys "Backtrace for test `"))
2436 (ert-insert-test-name-button (ert-test-name test))
2437 (insert (substitute-command-keys "':\n"))))))))
2439 (defun ert-results-pop-to-messages-for-test-at-point ()
2440 "Display the part of the *Messages* buffer generated during the test at point.
2442 To be used in the ERT results buffer."
2443 (interactive)
2444 (let* ((test (ert--results-test-at-point-no-redefinition t))
2445 (stats ert--results-stats)
2446 (pos (ert--stats-test-pos stats test))
2447 (result (aref (ert--stats-test-results stats) pos)))
2448 (let ((buffer (get-buffer-create "*ERT Messages*")))
2449 (pop-to-buffer buffer)
2450 (let ((inhibit-read-only t))
2451 (buffer-disable-undo)
2452 (erase-buffer)
2453 (ert-simple-view-mode)
2454 (insert (ert-test-result-messages result))
2455 (goto-char (point-min))
2456 (insert (substitute-command-keys "Messages for test `"))
2457 (ert-insert-test-name-button (ert-test-name test))
2458 (insert (substitute-command-keys "':\n"))))))
2460 (defun ert-results-pop-to-should-forms-for-test-at-point ()
2461 "Display the list of `should' forms executed during the test at point.
2463 To be used in the ERT results buffer."
2464 (interactive)
2465 (let* ((test (ert--results-test-at-point-no-redefinition t))
2466 (stats ert--results-stats)
2467 (pos (ert--stats-test-pos stats test))
2468 (result (aref (ert--stats-test-results stats) pos)))
2469 (let ((buffer (get-buffer-create "*ERT list of should forms*")))
2470 (pop-to-buffer buffer)
2471 (let ((inhibit-read-only t))
2472 (buffer-disable-undo)
2473 (erase-buffer)
2474 (ert-simple-view-mode)
2475 (if (null (ert-test-result-should-forms result))
2476 (insert "\n(No should forms during this test.)\n")
2477 (cl-loop for form-description
2478 in (ert-test-result-should-forms result)
2479 for i from 1 do
2480 (insert "\n")
2481 (insert (format "%s: " i))
2482 (let ((begin (point)))
2483 (ert--pp-with-indentation-and-newline form-description)
2484 (ert--make-xrefs-region begin (point)))))
2485 (goto-char (point-min))
2486 (insert (substitute-command-keys
2487 "`should' forms executed during test `"))
2488 (ert-insert-test-name-button (ert-test-name test))
2489 (insert (substitute-command-keys "':\n"))
2490 (insert "\n")
2491 (insert (concat "(Values are shallow copies and may have "
2492 "looked different during the test if they\n"
2493 "have been modified destructively.)\n"))
2494 (forward-line 1)))))
2496 (defun ert-results-toggle-printer-limits-for-test-at-point ()
2497 "Toggle how much of the condition to print for the test at point.
2499 To be used in the ERT results buffer."
2500 (interactive)
2501 (let* ((ewoc ert--results-ewoc)
2502 (node (ert--results-test-node-at-point))
2503 (entry (ewoc-data node)))
2504 (setf (ert--ewoc-entry-extended-printer-limits-p entry)
2505 (not (ert--ewoc-entry-extended-printer-limits-p entry)))
2506 (ewoc-invalidate ewoc node)))
2508 (defun ert-results-pop-to-timings ()
2509 "Display test timings for the last run.
2511 To be used in the ERT results buffer."
2512 (interactive)
2513 (let* ((stats ert--results-stats)
2514 (buffer (get-buffer-create "*ERT timings*"))
2515 (data (cl-loop for test across (ert--stats-tests stats)
2516 for start-time across (ert--stats-test-start-times
2517 stats)
2518 for end-time across (ert--stats-test-end-times stats)
2519 collect (list test
2520 (float-time (time-subtract
2521 end-time start-time))))))
2522 (setq data (sort data (lambda (a b)
2523 (> (cl-second a) (cl-second b)))))
2524 (pop-to-buffer buffer)
2525 (let ((inhibit-read-only t))
2526 (buffer-disable-undo)
2527 (erase-buffer)
2528 (ert-simple-view-mode)
2529 (if (null data)
2530 (insert "(No data)\n")
2531 (insert (format "%-3s %8s %8s\n" "" "time" "cumul"))
2532 (cl-loop for (test time) in data
2533 for cumul-time = time then (+ cumul-time time)
2534 for i from 1 do
2535 (progn
2536 (insert (format "%3s: %8.3f %8.3f " i time cumul-time))
2537 (ert-insert-test-name-button (ert-test-name test))
2538 (insert "\n"))))
2539 (goto-char (point-min))
2540 (insert "Tests by run time (seconds):\n\n")
2541 (forward-line 1))))
2543 ;;;###autoload
2544 (defun ert-describe-test (test-or-test-name)
2545 "Display the documentation for TEST-OR-TEST-NAME (a symbol or ert-test)."
2546 (interactive (list (ert-read-test-name-at-point "Describe test")))
2547 (when (< emacs-major-version 24)
2548 (user-error "Requires Emacs 24 or later"))
2549 (let (test-name
2550 test-definition)
2551 (cl-etypecase test-or-test-name
2552 (symbol (setq test-name test-or-test-name
2553 test-definition (ert-get-test test-or-test-name)))
2554 (ert-test (setq test-name (ert-test-name test-or-test-name)
2555 test-definition test-or-test-name)))
2556 (help-setup-xref (list #'ert-describe-test test-or-test-name)
2557 (called-interactively-p 'interactive))
2558 (save-excursion
2559 (with-help-window (help-buffer)
2560 (with-current-buffer (help-buffer)
2561 (insert (if test-name (format "%S" test-name) "<anonymous test>"))
2562 (insert " is a test")
2563 (let ((file-name (and test-name
2564 (symbol-file test-name 'ert--test))))
2565 (when file-name
2566 (insert (format-message " defined in `%s'"
2567 (file-name-nondirectory file-name)))
2568 (save-excursion
2569 (re-search-backward (substitute-command-keys "`\\([^`']+\\)'")
2570 nil t)
2571 (help-xref-button 1 'help-function-def test-name file-name)))
2572 (insert ".")
2573 (fill-region-as-paragraph (point-min) (point))
2574 (insert "\n\n")
2575 (unless (and (ert-test-boundp test-name)
2576 (eql (ert-get-test test-name) test-definition))
2577 (let ((begin (point)))
2578 (insert "Note: This test has been redefined or deleted, "
2579 "this documentation refers to an old definition.")
2580 (fill-region-as-paragraph begin (point)))
2581 (insert "\n\n"))
2582 (insert (substitute-command-keys
2583 (or (ert-test-documentation test-definition)
2584 "It is not documented."))
2585 "\n")))))))
2587 (defun ert-results-describe-test-at-point ()
2588 "Display the documentation of the test at point.
2590 To be used in the ERT results buffer."
2591 (interactive)
2592 (ert-describe-test (ert--results-test-at-point-no-redefinition t)))
2595 ;;; Actions on load/unload.
2597 (add-to-list 'find-function-regexp-alist '(ert--test . ert--find-test-regexp))
2598 (add-to-list 'minor-mode-alist '(ert--current-run-stats
2599 (:eval
2600 (ert--tests-running-mode-line-indicator))))
2601 (add-hook 'emacs-lisp-mode-hook #'ert--activate-font-lock-keywords)
2603 (defun ert--unload-function ()
2604 "Unload function to undo the side-effects of loading ert.el."
2605 (ert--remove-from-list 'find-function-regexp-alist 'ert-deftest :key #'car)
2606 (ert--remove-from-list 'minor-mode-alist 'ert--current-run-stats :key #'car)
2607 (ert--remove-from-list 'emacs-lisp-mode-hook
2608 'ert--activate-font-lock-keywords)
2609 nil)
2611 (defvar ert-unload-hook '())
2612 (add-hook 'ert-unload-hook #'ert--unload-function)
2615 (provide 'ert)
2617 ;;; ert.el ends here