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