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