]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/ert.el
* simple.el (shell-command-to-string): Use `process-file'.
[gnu-emacs] / lisp / emacs-lisp / ert.el
1 ;;; ert.el --- Emacs Lisp Regression Testing
2
3 ;; Copyright (C) 2007-2008, 2010-2011 Free Software Foundation, Inc.
4
5 ;; Author: Christian Ohler <ohler@gnu.org>
6 ;; Keywords: lisp, tools
7
8 ;; This file is part of GNU Emacs.
9
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.
14 ;;
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.
19 ;;
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/'.
22
23 ;;; Commentary:
24
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.
29 ;;
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.
35 ;;
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.
45 ;;
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.
49 ;;
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.
54
55 ;;; Code:
56
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)
65
66
67 ;;; UI customization options.
68
69 (defgroup ert ()
70 "ERT, the Emacs Lisp regression testing tool."
71 :prefix "ert-"
72 :group 'lisp)
73
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)
80
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)
87
88
89 ;;; Copies/reimplementations of cl functions.
90
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))))
96
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))))
103
104 (defun ert--remove-if-not (ert-pred ert-list)
105 "A reimplementation of `remove-if-not'.
106
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))
111
112 (defun ert--intersection (a b)
113 "A reimplementation of `intersection'. Intersect the sets A and B.
114
115 Elements are compared using `eql'."
116 (loop for x in a
117 if (memql x b)
118 collect x))
119
120 (defun ert--set-difference (a b)
121 "A reimplementation of `set-difference'. Subtract the set B from the set A.
122
123 Elements are compared using `eql'."
124 (loop for x in a
125 unless (memql x b)
126 collect x))
127
128 (defun ert--set-difference-eq (a b)
129 "A reimplementation of `set-difference'. Subtract the set B from the set A.
130
131 Elements are compared using `eq'."
132 (loop for x in a
133 unless (memq x b)
134 collect x))
135
136 (defun ert--union (a b)
137 "A reimplementation of `union'. Compute the union of the sets A and B.
138
139 Elements are compared using `eql'."
140 (append a (ert--set-difference b a)))
141
142 (eval-and-compile
143 (defvar ert--gensym-counter 0))
144
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))))))
153
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)
158 x
159 (vconcat x)))
160
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))
168
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))
174
175 (defun ert--mismatch (a b)
176 "Return index of first element that differs between A and B.
177
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))
184 (t
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)
193 la
194 (assert (equal a b) t)
195 nil)))))))
196
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)))))
210
211 (defun ert-equal-including-properties (a b)
212 "Return t if A and B have similar structure and contents.
213
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)))
223
224
225 ;;; Defining and locating tests.
226
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 '()))
235
236 (defun ert-test-boundp (symbol)
237 "Return non-nil if SYMBOL names a test."
238 (and (get symbol 'ert--test) t))
239
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))
244
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.
252 ;;
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)
258
259 (defun ert-make-test-unbound (symbol)
260 "Make SYMBOL name no test. Return SYMBOL."
261 (ert--remprop symbol 'ert--test)
262 symbol)
263
264 (defun ert--parse-keys-and-body (keys-and-body)
265 "Split KEYS-AND-BODY into keyword-and-value pairs and the remaining body.
266
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.
271
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)))
290
291 ;;;###autoload
292 (defmacro* ert-deftest (name () &body docstring-keys-and-body)
293 "Define NAME (a symbol) as a test.
294
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.
297
298 `should', `should-not' and `should-error' are useful for
299 assertions in BODY.
300
301 Use `ert' to run tests interactively.
302
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.
306
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))))
341
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))
351
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.")
357
358
359 (put 'ert-test-failed 'error-conditions '(error ert-test-failed))
360 (put 'ert-test-failed 'error-message "Test failed")
361
362 (defun ert-pass ()
363 "Terminate the current test and mark it passed. Does not return."
364 (throw 'ert--pass nil))
365
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)))
370
371
372 ;;; The `should' macros.
373
374 (defvar ert--should-execution-observer nil)
375
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)))
380
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)))))
387
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)))
410 (t
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))))))))
438
439 (defun ert--expand-should (whole form inner-expander)
440 "Helper function for the `should' macro and its variants.
441
442 Analyzes FORM and returns an expression that has the same
443 semantics under evaluation but records additional debugging
444 information.
445
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)))))))
467
468 (defmacro* should (form)
469 "Evaluate FORM. If it returns nil, abort the current test as failed.
470
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)))))
476
477 (defmacro* should-not (form)
478 "Evaluate FORM. If it returns non-nil, abort the current test as failed.
479
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)))))
485
486 (defun ert--should-error-handle-error (form-description-fn
487 condition type exclude-subtypes)
488 "Helper function for `should-error'.
489
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"))))))))
512
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.
517
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.
524
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")))))))))
551
552
553 ;;; Explanation of `should' failures.
554
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.
560
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))))
572
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)))
578
579 (defun ert--explain-equal-rec (a b)
580 "Returns a programmer-readable explanation of why A and B are not `equal'.
581
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)))))
629
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)
635 nil
636 (ert--explain-equal-rec a b)))
637 (put 'equal 'ert-explainer 'ert--explain-equal)
638
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)))
645
646 (defun ert--plist-difference-explanation (a b)
647 "Return a programmer-readable explanation of why A and B are different plists.
648
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)))
674 (t
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)))))))
678
679 (defun ert--abbreviate-string (s len suffixp)
680 "Shorten string S to at most LEN chars.
681
682 If SUFFIXP is non-nil, returns a suffix of S, otherwise a prefix."
683 (let ((n (length s)))
684 (cond ((< n len)
685 s)
686 (suffixp
687 (substring s (- n len)))
688 (t
689 (substring s 0 len)))))
690
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'.
696
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)
723 )))
724 (put 'ert-equal-including-properties
725 'ert-explainer
726 'ert--explain-equal-including-properties)
727
728
729 ;;; Implementation of `ert-info'.
730
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.
735
736 Bound dynamically. This is a list of (PREFIX . MESSAGE) pairs.")
737
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.
741
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))
750
751
752
753 ;;; Facilities for running a single test.
754
755 (defvar ert-debug-on-error nil
756 "Non-nil means enter debugger when a test fails or terminates with an error.")
757
758 ;; The data structures that represent the result of running a test.
759 (defstruct ert-test-result
760 (messages nil)
761 (should-forms nil)
762 )
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)))
771
772
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))
791
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")))))))
817
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)
834
835 (defun ert--run-test-debugger (info debugger-args)
836 "During a test run, `debugger' is bound to a closure that calls this function.
837
838 This function records failures and errors and either terminates
839 the test silently or calls the interactive debugger, as
840 appropriate.
841
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)))))))
876
877 (defun ert--run-test-internal (ert-test-execution-info)
878 "Low-level function to run a test according to ERT-TEST-EXECUTION-INFO.
879
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)
902
903 (defun ert--force-message-log-buffer-truncation ()
904 "Immediately truncate *Messages* buffer according to `message-log-max'.
905
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)))))
922
923 (defvar ert--running-tests nil
924 "List of tests that are currently in execution.
925
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.
930
931 The elements are of type `ert-test'.")
932
933 (defun ert-run-test (ert-test)
934 "Run ERT-TEST.
935
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))
968
969 (defun ert-running-test ()
970 "Return the top-level test currently executing."
971 (car (last ert--running-tests)))
972
973
974 ;;; Test selectors.
975
976 (defun ert-test-result-type-p (result result-type)
977 "Return non-nil if RESULT matches type RESULT-TYPE.
978
979 Valid result types:
980
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)
1002 (t
1003 (and (ert-test-result-type-p result (first operands))
1004 (ert-test-result-type-p result `(and ,@(rest operands)))))))
1005 (or
1006 (case (length operands)
1007 (0 nil)
1008 (t
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)))))))
1017
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)))
1021
1022 (defun ert-select-tests (selector universe)
1023 "Return the tests that match SELECTOR.
1024
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'.
1028
1029 Returns the set of tests as a list.
1030
1031 Valid selectors:
1032
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.
1049
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))))
1126 (or
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))))))))
1143
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)))))
1171
1172
1173 ;;; Facilities for running a whole set of tests.
1174
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.
1178 ;;
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))
1212
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)))
1217
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)))
1222
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)))
1227
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)))
1231
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)
1235
1236 (defun ert--stats-test-key (test)
1237 "Return the key used for TEST in the test map of ert--stats objects.
1238
1239 Returns the name of TEST if it has one, or TEST itself otherwise."
1240 (or (ert-test-name test) test))
1241
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.
1244
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)))
1275
1276 (defun ert--make-stats (tests selector)
1277 "Create a new `ert--stats' object for running TESTS.
1278
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))))
1293
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))))
1315
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)))
1336
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)))
1341
1342
1343 ;;; Formatting functions shared across UIs.
1344
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))
1348
1349 (defun ert-char-for-test-result (result expectedp)
1350 "Return a character that represents the test result RESULT.
1351
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))))
1360
1361 (defun ert-string-for-test-result (result expectedp)
1362 "Return a string that represents the test result RESULT.
1363
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))))
1372
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))))
1382
1383 (defun ert--insert-infos (result)
1384 "Insert `ert-info' infos from RESULT into current buffer.
1385
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)))))))
1404
1405
1406 ;;; Running tests in batch mode.
1407
1408 (defvar ert-batch-backtrace-right-margin 70
1409 "*The maximum line length for printing backtraces in `ert-run-tests-batch'.")
1410
1411 ;;;###autoload
1412 (defun ert-run-tests-batch (&optional selector)
1413 "Run the tests specified by SELECTOR, printing results to the terminal.
1414
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.
1419
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)
1437 ""
1438 "Aborted: ")
1439 (ert-stats-total stats)
1440 (ert-stats-completed-expected stats)
1441 (if (zerop unexpected)
1442 ""
1443 (format ", %s unexpected" unexpected))
1444 (ert--format-time-iso8601 (ert--stats-end-time stats))
1445 (if (zerop expected-failures)
1446 ""
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
1458 )
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 (let ((begin (point)))
1486 (ert--pp-with-indentation-and-newline
1487 (ert-test-result-with-condition-condition result))))
1488 (goto-char (1- (point-max)))
1489 (assert (looking-at "\n"))
1490 (delete-char 1)
1491 (message "Test %S condition:" (ert-test-name test))
1492 (message "%s" (buffer-string))))
1493 (ert-test-aborted-with-non-local-exit
1494 (message "Test %S aborted with non-local exit"
1495 (ert-test-name test)))
1496 (ert-test-quit
1497 (message "Quit during %S" (ert-test-name test)))))
1498 (let* ((max (prin1-to-string (length (ert--stats-tests stats))))
1499 (format-string (concat "%9s %"
1500 (prin1-to-string (length max))
1501 "s/" max " %S")))
1502 (message format-string
1503 (ert-string-for-test-result result
1504 (ert-test-result-expected-p
1505 test result))
1506 (1+ (ert--stats-test-pos stats test))
1507 (ert-test-name test)))))))))
1508
1509 ;;;###autoload
1510 (defun ert-run-tests-batch-and-exit (&optional selector)
1511 "Like `ert-run-tests-batch', but exits Emacs when done.
1512
1513 The exit status will be 0 if all test results were as expected, 1
1514 on unexpected results, or 2 if the tool detected an error outside
1515 of the tests (e.g. invalid SELECTOR or bug in the code that runs
1516 the tests)."
1517 (unwind-protect
1518 (let ((stats (ert-run-tests-batch selector)))
1519 (kill-emacs (if (zerop (ert-stats-completed-unexpected stats)) 0 1)))
1520 (unwind-protect
1521 (progn
1522 (message "Error running tests")
1523 (backtrace))
1524 (kill-emacs 2))))
1525
1526
1527 ;;; Utility functions for load/unload actions.
1528
1529 (defun ert--activate-font-lock-keywords ()
1530 "Activate font-lock keywords for some of ERT's symbols."
1531 (font-lock-add-keywords
1532 nil
1533 '(("(\\(\\<ert-deftest\\)\\>\\s *\\(\\sw+\\)?"
1534 (1 font-lock-keyword-face nil t)
1535 (2 font-lock-function-name-face nil t)))))
1536
1537 (defun* ert--remove-from-list (list-var element &key key test)
1538 "Remove ELEMENT from the value of LIST-VAR if present.
1539
1540 This can be used as an inverse of `add-to-list'."
1541 (unless key (setq key #'identity))
1542 (unless test (setq test #'equal))
1543 (setf (symbol-value list-var)
1544 (ert--remove* element
1545 (symbol-value list-var)
1546 :key key
1547 :test test)))
1548
1549
1550 ;;; Some basic interactive functions.
1551
1552 (defun ert-read-test-name (prompt &optional default history
1553 add-default-to-prompt)
1554 "Read the name of a test and return it as a symbol.
1555
1556 Prompt with PROMPT. If DEFAULT is a valid test name, use it as a
1557 default. HISTORY is the history to use; see `completing-read'.
1558 If ADD-DEFAULT-TO-PROMPT is non-nil, PROMPT will be modified to
1559 include the default, if any.
1560
1561 Signals an error if no test name was read."
1562 (etypecase default
1563 (string (let ((symbol (intern-soft default)))
1564 (unless (and symbol (ert-test-boundp symbol))
1565 (setq default nil))))
1566 (symbol (setq default
1567 (if (ert-test-boundp default)
1568 (symbol-name default)
1569 nil)))
1570 (ert-test (setq default (ert-test-name default))))
1571 (when add-default-to-prompt
1572 (setq prompt (if (null default)
1573 (format "%s: " prompt)
1574 (format "%s (default %s): " prompt default))))
1575 (let ((input (completing-read prompt obarray #'ert-test-boundp
1576 t nil history default nil)))
1577 ;; completing-read returns an empty string if default was nil and
1578 ;; the user just hit enter.
1579 (let ((sym (intern-soft input)))
1580 (if (ert-test-boundp sym)
1581 sym
1582 (error "Input does not name a test")))))
1583
1584 (defun ert-read-test-name-at-point (prompt)
1585 "Read the name of a test and return it as a symbol.
1586 As a default, use the symbol at point, or the test at point if in
1587 the ERT results buffer. Prompt with PROMPT, augmented with the
1588 default (if any)."
1589 (ert-read-test-name prompt (ert-test-at-point) nil t))
1590
1591 (defun ert-find-test-other-window (test-name)
1592 "Find, in another window, the definition of TEST-NAME."
1593 (interactive (list (ert-read-test-name-at-point "Find test definition: ")))
1594 (find-function-do-it test-name 'ert-deftest 'switch-to-buffer-other-window))
1595
1596 (defun ert-delete-test (test-name)
1597 "Make the test TEST-NAME unbound.
1598
1599 Nothing more than an interactive interface to `ert-make-test-unbound'."
1600 (interactive (list (ert-read-test-name-at-point "Delete test")))
1601 (ert-make-test-unbound test-name))
1602
1603 (defun ert-delete-all-tests ()
1604 "Make all symbols in `obarray' name no test."
1605 (interactive)
1606 (when (interactive-p)
1607 (unless (y-or-n-p "Delete all tests? ")
1608 (error "Aborted")))
1609 ;; We can't use `ert-select-tests' here since that gives us only
1610 ;; test objects, and going from them back to the test name symbols
1611 ;; can fail if the `ert-test' defstruct has been redefined.
1612 (mapc #'ert-make-test-unbound (apropos-internal "" #'ert-test-boundp))
1613 t)
1614
1615
1616 ;;; Display of test progress and results.
1617
1618 ;; An entry in the results buffer ewoc. There is one entry per test.
1619 (defstruct ert--ewoc-entry
1620 (test (assert nil))
1621 ;; If the result of this test was expected, its ewoc entry is hidden
1622 ;; initially.
1623 (hidden-p (assert nil))
1624 ;; An ewoc entry may be collapsed to hide details such as the error
1625 ;; condition.
1626 ;;
1627 ;; I'm not sure the ability to expand and collapse entries is still
1628 ;; a useful feature.
1629 (expanded-p t)
1630 ;; By default, the ewoc entry presents the error condition with
1631 ;; certain limits on how much to print (`print-level',
1632 ;; `print-length'). The user can interactively switch to a set of
1633 ;; higher limits.
1634 (extended-printer-limits-p nil))
1635
1636 ;; Variables local to the results buffer.
1637
1638 ;; The ewoc.
1639 (defvar ert--results-ewoc)
1640 ;; The stats object.
1641 (defvar ert--results-stats)
1642 ;; A string with one character per test. Each character represents
1643 ;; the result of the corresponding test. The string is displayed near
1644 ;; the top of the buffer and serves as a progress bar.
1645 (defvar ert--results-progress-bar-string)
1646 ;; The position where the progress bar button begins.
1647 (defvar ert--results-progress-bar-button-begin)
1648 ;; The test result listener that updates the buffer when tests are run.
1649 (defvar ert--results-listener)
1650
1651 (defun ert-insert-test-name-button (test-name)
1652 "Insert a button that links to TEST-NAME."
1653 (insert-text-button (format "%S" test-name)
1654 :type 'ert--test-name-button
1655 'ert-test-name test-name))
1656
1657 (defun ert--results-format-expected-unexpected (expected unexpected)
1658 "Return a string indicating EXPECTED expected results, UNEXPECTED unexpected."
1659 (if (zerop unexpected)
1660 (format "%s" expected)
1661 (format "%s (%s unexpected)" (+ expected unexpected) unexpected)))
1662
1663 (defun ert--results-update-ewoc-hf (ewoc stats)
1664 "Update the header and footer of EWOC to show certain information from STATS.
1665
1666 Also sets `ert--results-progress-bar-button-begin'."
1667 (let ((run-count (ert-stats-completed stats))
1668 (results-buffer (current-buffer))
1669 ;; Need to save buffer-local value.
1670 (font-lock font-lock-mode))
1671 (ewoc-set-hf
1672 ewoc
1673 ;; header
1674 (with-temp-buffer
1675 (insert "Selector: ")
1676 (ert--insert-human-readable-selector (ert--stats-selector stats))
1677 (insert "\n")
1678 (insert
1679 (format (concat "Passed: %s\n"
1680 "Failed: %s\n"
1681 "Total: %s/%s\n\n")
1682 (ert--results-format-expected-unexpected
1683 (ert--stats-passed-expected stats)
1684 (ert--stats-passed-unexpected stats))
1685 (ert--results-format-expected-unexpected
1686 (ert--stats-failed-expected stats)
1687 (ert--stats-failed-unexpected stats))
1688 run-count
1689 (ert-stats-total stats)))
1690 (insert
1691 (format "Started at: %s\n"
1692 (ert--format-time-iso8601 (ert--stats-start-time stats))))
1693 ;; FIXME: This is ugly. Need to properly define invariants of
1694 ;; the `stats' data structure.
1695 (let ((state (cond ((ert--stats-aborted-p stats) 'aborted)
1696 ((ert--stats-current-test stats) 'running)
1697 ((ert--stats-end-time stats) 'finished)
1698 (t 'preparing))))
1699 (ecase state
1700 (preparing
1701 (insert ""))
1702 (aborted
1703 (cond ((ert--stats-current-test stats)
1704 (insert "Aborted during test: ")
1705 (ert-insert-test-name-button
1706 (ert-test-name (ert--stats-current-test stats))))
1707 (t
1708 (insert "Aborted."))))
1709 (running
1710 (assert (ert--stats-current-test stats))
1711 (insert "Running test: ")
1712 (ert-insert-test-name-button (ert-test-name
1713 (ert--stats-current-test stats))))
1714 (finished
1715 (assert (not (ert--stats-current-test stats)))
1716 (insert "Finished.")))
1717 (insert "\n")
1718 (if (ert--stats-end-time stats)
1719 (insert
1720 (format "%s%s\n"
1721 (if (ert--stats-aborted-p stats)
1722 "Aborted at: "
1723 "Finished at: ")
1724 (ert--format-time-iso8601 (ert--stats-end-time stats))))
1725 (insert "\n"))
1726 (insert "\n"))
1727 (let ((progress-bar-string (with-current-buffer results-buffer
1728 ert--results-progress-bar-string)))
1729 (let ((progress-bar-button-begin
1730 (insert-text-button progress-bar-string
1731 :type 'ert--results-progress-bar-button
1732 'face (or (and font-lock
1733 (ert-face-for-stats stats))
1734 'button))))
1735 ;; The header gets copied verbatim to the results buffer,
1736 ;; and all positions remain the same, so
1737 ;; `progress-bar-button-begin' will be the right position
1738 ;; even in the results buffer.
1739 (with-current-buffer results-buffer
1740 (set (make-local-variable 'ert--results-progress-bar-button-begin)
1741 progress-bar-button-begin))))
1742 (insert "\n\n")
1743 (buffer-string))
1744 ;; footer
1745 ;;
1746 ;; We actually want an empty footer, but that would trigger a bug
1747 ;; in ewoc, sometimes clearing the entire buffer. (It's possible
1748 ;; that this bug has been fixed since this has been tested; we
1749 ;; should test it again.)
1750 "\n")))
1751
1752
1753 (defvar ert-test-run-redisplay-interval-secs .1
1754 "How many seconds ERT should wait between redisplays while running tests.
1755
1756 While running tests, ERT shows the current progress, and this variable
1757 determines how frequently the progress display is updated.")
1758
1759 (defun ert--results-update-stats-display (ewoc stats)
1760 "Update EWOC and the mode line to show data from STATS."
1761 ;; TODO(ohler): investigate using `make-progress-reporter'.
1762 (ert--results-update-ewoc-hf ewoc stats)
1763 (force-mode-line-update)
1764 (redisplay t)
1765 (setf (ert--stats-next-redisplay stats)
1766 (+ (float-time) ert-test-run-redisplay-interval-secs)))
1767
1768 (defun ert--results-update-stats-display-maybe (ewoc stats)
1769 "Call `ert--results-update-stats-display' if not called recently.
1770
1771 EWOC and STATS are arguments for `ert--results-update-stats-display'."
1772 (when (>= (float-time) (ert--stats-next-redisplay stats))
1773 (ert--results-update-stats-display ewoc stats)))
1774
1775 (defun ert--tests-running-mode-line-indicator ()
1776 "Return a string for the mode line that shows the test run progress."
1777 (let* ((stats ert--current-run-stats)
1778 (tests-total (ert-stats-total stats))
1779 (tests-completed (ert-stats-completed stats)))
1780 (if (>= tests-completed tests-total)
1781 (format " ERT(%s/%s,finished)" tests-completed tests-total)
1782 (format " ERT(%s/%s):%s"
1783 (1+ tests-completed)
1784 tests-total
1785 (if (null (ert--stats-current-test stats))
1786 "?"
1787 (format "%S"
1788 (ert-test-name (ert--stats-current-test stats))))))))
1789
1790 (defun ert--make-xrefs-region (begin end)
1791 "Attach cross-references to function names between BEGIN and END.
1792
1793 BEGIN and END specify a region in the current buffer."
1794 (save-excursion
1795 (save-restriction
1796 (narrow-to-region begin (point))
1797 ;; Inhibit optimization in `debugger-make-xrefs' that would
1798 ;; sometimes insert unrelated backtrace info into our buffer.
1799 (let ((debugger-previous-backtrace nil))
1800 (debugger-make-xrefs)))))
1801
1802 (defun ert--string-first-line (s)
1803 "Return the first line of S, or S if it contains no newlines.
1804
1805 The return value does not include the line terminator."
1806 (substring s 0 (ert--string-position ?\n s)))
1807
1808 (defun ert-face-for-test-result (expectedp)
1809 "Return a face that shows whether a test result was expected or unexpected.
1810
1811 If EXPECTEDP is nil, returns the face for unexpected results; if
1812 non-nil, returns the face for expected results.."
1813 (if expectedp 'ert-test-result-expected 'ert-test-result-unexpected))
1814
1815 (defun ert-face-for-stats (stats)
1816 "Return a face that represents STATS."
1817 (cond ((ert--stats-aborted-p stats) 'nil)
1818 ((plusp (ert-stats-completed-unexpected stats))
1819 (ert-face-for-test-result nil))
1820 ((eql (ert-stats-completed-expected stats) (ert-stats-total stats))
1821 (ert-face-for-test-result t))
1822 (t 'nil)))
1823
1824 (defun ert--print-test-for-ewoc (entry)
1825 "The ewoc print function for ewoc test entries. ENTRY is the entry to print."
1826 (let* ((test (ert--ewoc-entry-test entry))
1827 (stats ert--results-stats)
1828 (result (let ((pos (ert--stats-test-pos stats test)))
1829 (assert pos)
1830 (aref (ert--stats-test-results stats) pos)))
1831 (hiddenp (ert--ewoc-entry-hidden-p entry))
1832 (expandedp (ert--ewoc-entry-expanded-p entry))
1833 (extended-printer-limits-p (ert--ewoc-entry-extended-printer-limits-p
1834 entry)))
1835 (cond (hiddenp)
1836 (t
1837 (let ((expectedp (ert-test-result-expected-p test result)))
1838 (insert-text-button (format "%c" (ert-char-for-test-result
1839 result expectedp))
1840 :type 'ert--results-expand-collapse-button
1841 'face (or (and font-lock-mode
1842 (ert-face-for-test-result
1843 expectedp))
1844 'button)))
1845 (insert " ")
1846 (ert-insert-test-name-button (ert-test-name test))
1847 (insert "\n")
1848 (when (and expandedp (not (eql result 'nil)))
1849 (when (ert-test-documentation test)
1850 (insert " "
1851 (propertize
1852 (ert--string-first-line (ert-test-documentation test))
1853 'font-lock-face 'font-lock-doc-face)
1854 "\n"))
1855 (etypecase result
1856 (ert-test-passed
1857 (if (ert-test-result-expected-p test result)
1858 (insert " passed\n")
1859 (insert " passed unexpectedly\n"))
1860 (insert ""))
1861 (ert-test-result-with-condition
1862 (ert--insert-infos result)
1863 (let ((print-escape-newlines t)
1864 (print-level (if extended-printer-limits-p 12 6))
1865 (print-length (if extended-printer-limits-p 100 10)))
1866 (insert " ")
1867 (let ((begin (point)))
1868 (ert--pp-with-indentation-and-newline
1869 (ert-test-result-with-condition-condition result))
1870 (ert--make-xrefs-region begin (point)))))
1871 (ert-test-aborted-with-non-local-exit
1872 (insert " aborted\n"))
1873 (ert-test-quit
1874 (insert " quit\n")))
1875 (insert "\n")))))
1876 nil)
1877
1878 (defun ert--results-font-lock-function (enabledp)
1879 "Redraw the ERT results buffer after font-lock-mode was switched on or off.
1880
1881 ENABLEDP is true if font-lock-mode is switched on, false
1882 otherwise."
1883 (ert--results-update-ewoc-hf ert--results-ewoc ert--results-stats)
1884 (ewoc-refresh ert--results-ewoc)
1885 (font-lock-default-function enabledp))
1886
1887 (defun ert--setup-results-buffer (stats listener buffer-name)
1888 "Set up a test results buffer.
1889
1890 STATS is the stats object; LISTENER is the results listener;
1891 BUFFER-NAME, if non-nil, is the buffer name to use."
1892 (unless buffer-name (setq buffer-name "*ert*"))
1893 (let ((buffer (get-buffer-create buffer-name)))
1894 (with-current-buffer buffer
1895 (let ((inhibit-read-only t))
1896 (buffer-disable-undo)
1897 (erase-buffer)
1898 (ert-results-mode)
1899 ;; Erase buffer again in case switching out of the previous
1900 ;; mode inserted anything. (This happens e.g. when switching
1901 ;; from ert-results-mode to ert-results-mode when
1902 ;; font-lock-mode turns itself off in change-major-mode-hook.)
1903 (erase-buffer)
1904 (set (make-local-variable 'font-lock-function)
1905 'ert--results-font-lock-function)
1906 (let ((ewoc (ewoc-create 'ert--print-test-for-ewoc nil nil t)))
1907 (set (make-local-variable 'ert--results-ewoc) ewoc)
1908 (set (make-local-variable 'ert--results-stats) stats)
1909 (set (make-local-variable 'ert--results-progress-bar-string)
1910 (make-string (ert-stats-total stats)
1911 (ert-char-for-test-result nil t)))
1912 (set (make-local-variable 'ert--results-listener) listener)
1913 (loop for test across (ert--stats-tests stats) do
1914 (ewoc-enter-last ewoc
1915 (make-ert--ewoc-entry :test test :hidden-p t)))
1916 (ert--results-update-ewoc-hf ert--results-ewoc ert--results-stats)
1917 (goto-char (1- (point-max)))
1918 buffer)))))
1919
1920
1921 (defvar ert--selector-history nil
1922 "List of recent test selectors read from terminal.")
1923
1924 ;; Should OUTPUT-BUFFER-NAME and MESSAGE-FN really be arguments here?
1925 ;; They are needed only for our automated self-tests at the moment.
1926 ;; Or should there be some other mechanism?
1927 ;;;###autoload
1928 (defun ert-run-tests-interactively (selector
1929 &optional output-buffer-name message-fn)
1930 "Run the tests specified by SELECTOR and display the results in a buffer.
1931
1932 SELECTOR works as described in `ert-select-tests'.
1933 OUTPUT-BUFFER-NAME and MESSAGE-FN should normally be nil; they
1934 are used for automated self-tests and specify which buffer to use
1935 and how to display message."
1936 (interactive
1937 (list (let ((default (if ert--selector-history
1938 ;; Can't use `first' here as this form is
1939 ;; not compiled, and `first' is not
1940 ;; defined without cl.
1941 (car ert--selector-history)
1942 "t")))
1943 (read-from-minibuffer (if (null default)
1944 "Run tests: "
1945 (format "Run tests (default %s): " default))
1946 nil nil t 'ert--selector-history
1947 default nil))
1948 nil))
1949 (unless message-fn (setq message-fn 'message))
1950 (lexical-let ((output-buffer-name output-buffer-name)
1951 buffer
1952 listener
1953 (message-fn message-fn))
1954 (setq listener
1955 (lambda (event-type &rest event-args)
1956 (ecase event-type
1957 (run-started
1958 (destructuring-bind (stats) event-args
1959 (setq buffer (ert--setup-results-buffer stats
1960 listener
1961 output-buffer-name))
1962 (pop-to-buffer buffer)))
1963 (run-ended
1964 (destructuring-bind (stats abortedp) event-args
1965 (funcall message-fn
1966 "%sRan %s tests, %s results were as expected%s"
1967 (if (not abortedp)
1968 ""
1969 "Aborted: ")
1970 (ert-stats-total stats)
1971 (ert-stats-completed-expected stats)
1972 (let ((unexpected
1973 (ert-stats-completed-unexpected stats)))
1974 (if (zerop unexpected)
1975 ""
1976 (format ", %s unexpected" unexpected))))
1977 (ert--results-update-stats-display (with-current-buffer buffer
1978 ert--results-ewoc)
1979 stats)))
1980 (test-started
1981 (destructuring-bind (stats test) event-args
1982 (with-current-buffer buffer
1983 (let* ((ewoc ert--results-ewoc)
1984 (pos (ert--stats-test-pos stats test))
1985 (node (ewoc-nth ewoc pos)))
1986 (assert node)
1987 (setf (ert--ewoc-entry-test (ewoc-data node)) test)
1988 (aset ert--results-progress-bar-string pos
1989 (ert-char-for-test-result nil t))
1990 (ert--results-update-stats-display-maybe ewoc stats)
1991 (ewoc-invalidate ewoc node)))))
1992 (test-ended
1993 (destructuring-bind (stats test result) event-args
1994 (with-current-buffer buffer
1995 (let* ((ewoc ert--results-ewoc)
1996 (pos (ert--stats-test-pos stats test))
1997 (node (ewoc-nth ewoc pos)))
1998 (when (ert--ewoc-entry-hidden-p (ewoc-data node))
1999 (setf (ert--ewoc-entry-hidden-p (ewoc-data node))
2000 (ert-test-result-expected-p test result)))
2001 (aset ert--results-progress-bar-string pos
2002 (ert-char-for-test-result result
2003 (ert-test-result-expected-p
2004 test result)))
2005 (ert--results-update-stats-display-maybe ewoc stats)
2006 (ewoc-invalidate ewoc node))))))))
2007 (ert-run-tests
2008 selector
2009 listener)))
2010 ;;;###autoload
2011 (defalias 'ert 'ert-run-tests-interactively)
2012
2013
2014 ;;; Simple view mode for auxiliary information like stack traces or
2015 ;;; messages. Mainly binds "q" for quit.
2016
2017 (define-derived-mode ert-simple-view-mode special-mode "ERT-View"
2018 "Major mode for viewing auxiliary information in ERT.")
2019
2020 ;;; Commands and button actions for the results buffer.
2021
2022 (define-derived-mode ert-results-mode special-mode "ERT-Results"
2023 "Major mode for viewing results of ERT test runs.")
2024
2025 (loop for (key binding) in
2026 '(;; Stuff that's not in the menu.
2027 ("\t" forward-button)
2028 ([backtab] backward-button)
2029 ("j" ert-results-jump-between-summary-and-result)
2030 ("L" ert-results-toggle-printer-limits-for-test-at-point)
2031 ("n" ert-results-next-test)
2032 ("p" ert-results-previous-test)
2033 ;; Stuff that is in the menu.
2034 ("R" ert-results-rerun-all-tests)
2035 ("r" ert-results-rerun-test-at-point)
2036 ("d" ert-results-rerun-test-at-point-debugging-errors)
2037 ("." ert-results-find-test-at-point-other-window)
2038 ("b" ert-results-pop-to-backtrace-for-test-at-point)
2039 ("m" ert-results-pop-to-messages-for-test-at-point)
2040 ("l" ert-results-pop-to-should-forms-for-test-at-point)
2041 ("h" ert-results-describe-test-at-point)
2042 ("D" ert-delete-test)
2043 ("T" ert-results-pop-to-timings)
2044 )
2045 do
2046 (define-key ert-results-mode-map key binding))
2047
2048 (easy-menu-define ert-results-mode-menu ert-results-mode-map
2049 "Menu for `ert-results-mode'."
2050 '("ERT Results"
2051 ["Re-run all tests" ert-results-rerun-all-tests]
2052 "--"
2053 ["Re-run test" ert-results-rerun-test-at-point]
2054 ["Debug test" ert-results-rerun-test-at-point-debugging-errors]
2055 ["Show test definition" ert-results-find-test-at-point-other-window]
2056 "--"
2057 ["Show backtrace" ert-results-pop-to-backtrace-for-test-at-point]
2058 ["Show messages" ert-results-pop-to-messages-for-test-at-point]
2059 ["Show `should' forms" ert-results-pop-to-should-forms-for-test-at-point]
2060 ["Describe test" ert-results-describe-test-at-point]
2061 "--"
2062 ["Delete test" ert-delete-test]
2063 "--"
2064 ["Show execution time of each test" ert-results-pop-to-timings]
2065 ))
2066
2067 (define-button-type 'ert--results-progress-bar-button
2068 'action #'ert--results-progress-bar-button-action
2069 'help-echo "mouse-2, RET: Reveal test result")
2070
2071 (define-button-type 'ert--test-name-button
2072 'action #'ert--test-name-button-action
2073 'help-echo "mouse-2, RET: Find test definition")
2074
2075 (define-button-type 'ert--results-expand-collapse-button
2076 'action #'ert--results-expand-collapse-button-action
2077 'help-echo "mouse-2, RET: Expand/collapse test result")
2078
2079 (defun ert--results-test-node-or-null-at-point ()
2080 "If point is on a valid ewoc node, return it; return nil otherwise.
2081
2082 To be used in the ERT results buffer."
2083 (let* ((ewoc ert--results-ewoc)
2084 (node (ewoc-locate ewoc)))
2085 ;; `ewoc-locate' will return an arbitrary node when point is on
2086 ;; header or footer, or when all nodes are invisible. So we need
2087 ;; to validate its return value here.
2088 ;;
2089 ;; Update: I'm seeing nil being returned in some cases now,
2090 ;; perhaps this has been changed?
2091 (if (and node
2092 (>= (point) (ewoc-location node))
2093 (not (ert--ewoc-entry-hidden-p (ewoc-data node))))
2094 node
2095 nil)))
2096
2097 (defun ert--results-test-node-at-point ()
2098 "If point is on a valid ewoc node, return it; signal an error otherwise.
2099
2100 To be used in the ERT results buffer."
2101 (or (ert--results-test-node-or-null-at-point)
2102 (error "No test at point")))
2103
2104 (defun ert-results-next-test ()
2105 "Move point to the next test.
2106
2107 To be used in the ERT results buffer."
2108 (interactive)
2109 (ert--results-move (ewoc-locate ert--results-ewoc) 'ewoc-next
2110 "No tests below"))
2111
2112 (defun ert-results-previous-test ()
2113 "Move point to the previous test.
2114
2115 To be used in the ERT results buffer."
2116 (interactive)
2117 (ert--results-move (ewoc-locate ert--results-ewoc) 'ewoc-prev
2118 "No tests above"))
2119
2120 (defun ert--results-move (node ewoc-fn error-message)
2121 "Move point from NODE to the previous or next node.
2122
2123 EWOC-FN specifies the direction and should be either `ewoc-prev'
2124 or `ewoc-next'. If there are no more nodes in that direction, an
2125 error is signalled with the message ERROR-MESSAGE."
2126 (loop
2127 (setq node (funcall ewoc-fn ert--results-ewoc node))
2128 (when (null node)
2129 (error "%s" error-message))
2130 (unless (ert--ewoc-entry-hidden-p (ewoc-data node))
2131 (goto-char (ewoc-location node))
2132 (return))))
2133
2134 (defun ert--results-expand-collapse-button-action (button)
2135 "Expand or collapse the test node BUTTON belongs to."
2136 (let* ((ewoc ert--results-ewoc)
2137 (node (save-excursion
2138 (goto-char (ert--button-action-position))
2139 (ert--results-test-node-at-point)))
2140 (entry (ewoc-data node)))
2141 (setf (ert--ewoc-entry-expanded-p entry)
2142 (not (ert--ewoc-entry-expanded-p entry)))
2143 (ewoc-invalidate ewoc node)))
2144
2145 (defun ert-results-find-test-at-point-other-window ()
2146 "Find the definition of the test at point in another window.
2147
2148 To be used in the ERT results buffer."
2149 (interactive)
2150 (let ((name (ert-test-at-point)))
2151 (unless name
2152 (error "No test at point"))
2153 (ert-find-test-other-window name)))
2154
2155 (defun ert--test-name-button-action (button)
2156 "Find the definition of the test BUTTON belongs to, in another window."
2157 (let ((name (button-get button 'ert-test-name)))
2158 (ert-find-test-other-window name)))
2159
2160 (defun ert--ewoc-position (ewoc node)
2161 ;; checkdoc-order: nil
2162 "Return the position of NODE in EWOC, or nil if NODE is not in EWOC."
2163 (loop for i from 0
2164 for node-here = (ewoc-nth ewoc 0) then (ewoc-next ewoc node-here)
2165 do (when (eql node node-here)
2166 (return i))
2167 finally (return nil)))
2168
2169 (defun ert-results-jump-between-summary-and-result ()
2170 "Jump back and forth between the test run summary and individual test results.
2171
2172 From an ewoc node, jumps to the character that represents the
2173 same test in the progress bar, and vice versa.
2174
2175 To be used in the ERT results buffer."
2176 ;; Maybe this command isn't actually needed much, but if it is, it
2177 ;; seems like an indication that the UI design is not optimal. If
2178 ;; jumping back and forth between a summary at the top of the buffer
2179 ;; and the error log in the remainder of the buffer is useful, then
2180 ;; the summary apparently needs to be easily accessible from the
2181 ;; error log, and perhaps it would be better to have it in a
2182 ;; separate buffer to keep it visible.
2183 (interactive)
2184 (let ((ewoc ert--results-ewoc)
2185 (progress-bar-begin ert--results-progress-bar-button-begin))
2186 (cond ((ert--results-test-node-or-null-at-point)
2187 (let* ((node (ert--results-test-node-at-point))
2188 (pos (ert--ewoc-position ewoc node)))
2189 (goto-char (+ progress-bar-begin pos))))
2190 ((and (<= progress-bar-begin (point))
2191 (< (point) (button-end (button-at progress-bar-begin))))
2192 (let* ((node (ewoc-nth ewoc (- (point) progress-bar-begin)))
2193 (entry (ewoc-data node)))
2194 (when (ert--ewoc-entry-hidden-p entry)
2195 (setf (ert--ewoc-entry-hidden-p entry) nil)
2196 (ewoc-invalidate ewoc node))
2197 (ewoc-goto-node ewoc node)))
2198 (t
2199 (goto-char progress-bar-begin)))))
2200
2201 (defun ert-test-at-point ()
2202 "Return the name of the test at point as a symbol, or nil if none."
2203 (or (and (eql major-mode 'ert-results-mode)
2204 (let ((test (ert--results-test-at-point-no-redefinition)))
2205 (and test (ert-test-name test))))
2206 (let* ((thing (thing-at-point 'symbol))
2207 (sym (intern-soft thing)))
2208 (and (ert-test-boundp sym)
2209 sym))))
2210
2211 (defun ert--results-test-at-point-no-redefinition ()
2212 "Return the test at point, or nil.
2213
2214 To be used in the ERT results buffer."
2215 (assert (eql major-mode 'ert-results-mode))
2216 (if (ert--results-test-node-or-null-at-point)
2217 (let* ((node (ert--results-test-node-at-point))
2218 (test (ert--ewoc-entry-test (ewoc-data node))))
2219 test)
2220 (let ((progress-bar-begin ert--results-progress-bar-button-begin))
2221 (when (and (<= progress-bar-begin (point))
2222 (< (point) (button-end (button-at progress-bar-begin))))
2223 (let* ((test-index (- (point) progress-bar-begin))
2224 (test (aref (ert--stats-tests ert--results-stats)
2225 test-index)))
2226 test)))))
2227
2228 (defun ert--results-test-at-point-allow-redefinition ()
2229 "Look up the test at point, and check whether it has been redefined.
2230
2231 To be used in the ERT results buffer.
2232
2233 Returns a list of two elements: the test (or nil) and a symbol
2234 specifying whether the test has been redefined.
2235
2236 If a new test has been defined with the same name as the test at
2237 point, replaces the test at point with the new test, and returns
2238 the new test and the symbol `redefined'.
2239
2240 If the test has been deleted, returns the old test and the symbol
2241 `deleted'.
2242
2243 If the test is still current, returns the test and the symbol nil.
2244
2245 If there is no test at point, returns a list with two nils."
2246 (let ((test (ert--results-test-at-point-no-redefinition)))
2247 (cond ((null test)
2248 `(nil nil))
2249 ((null (ert-test-name test))
2250 `(,test nil))
2251 (t
2252 (let* ((name (ert-test-name test))
2253 (new-test (and (ert-test-boundp name)
2254 (ert-get-test name))))
2255 (cond ((eql test new-test)
2256 `(,test nil))
2257 ((null new-test)
2258 `(,test deleted))
2259 (t
2260 (ert--results-update-after-test-redefinition
2261 (ert--stats-test-pos ert--results-stats test)
2262 new-test)
2263 `(,new-test redefined))))))))
2264
2265 (defun ert--results-update-after-test-redefinition (pos new-test)
2266 "Update results buffer after the test at pos POS has been redefined.
2267
2268 Also updates the stats object. NEW-TEST is the new test
2269 definition."
2270 (let* ((stats ert--results-stats)
2271 (ewoc ert--results-ewoc)
2272 (node (ewoc-nth ewoc pos))
2273 (entry (ewoc-data node)))
2274 (ert--stats-set-test-and-result stats pos new-test nil)
2275 (setf (ert--ewoc-entry-test entry) new-test
2276 (aref ert--results-progress-bar-string pos) (ert-char-for-test-result
2277 nil t))
2278 (ewoc-invalidate ewoc node))
2279 nil)
2280
2281 (defun ert--button-action-position ()
2282 "The buffer position where the last button action was triggered."
2283 (cond ((integerp last-command-event)
2284 (point))
2285 ((eventp last-command-event)
2286 (posn-point (event-start last-command-event)))
2287 (t (assert nil))))
2288
2289 (defun ert--results-progress-bar-button-action (button)
2290 "Jump to details for the test represented by the character clicked in BUTTON."
2291 (goto-char (ert--button-action-position))
2292 (ert-results-jump-between-summary-and-result))
2293
2294 (defun ert-results-rerun-all-tests ()
2295 "Re-run all tests, using the same selector.
2296
2297 To be used in the ERT results buffer."
2298 (interactive)
2299 (assert (eql major-mode 'ert-results-mode))
2300 (let ((selector (ert--stats-selector ert--results-stats)))
2301 (ert-run-tests-interactively selector (buffer-name))))
2302
2303 (defun ert-results-rerun-test-at-point ()
2304 "Re-run the test at point.
2305
2306 To be used in the ERT results buffer."
2307 (interactive)
2308 (destructuring-bind (test redefinition-state)
2309 (ert--results-test-at-point-allow-redefinition)
2310 (when (null test)
2311 (error "No test at point"))
2312 (let* ((stats ert--results-stats)
2313 (progress-message (format "Running %stest %S"
2314 (ecase redefinition-state
2315 ((nil) "")
2316 (redefined "new definition of ")
2317 (deleted "deleted "))
2318 (ert-test-name test))))
2319 ;; Need to save and restore point manually here: When point is on
2320 ;; the first visible ewoc entry while the header is updated, point
2321 ;; moves to the top of the buffer. This is undesirable, and a
2322 ;; simple `save-excursion' doesn't prevent it.
2323 (let ((point (point)))
2324 (unwind-protect
2325 (unwind-protect
2326 (progn
2327 (message "%s..." progress-message)
2328 (ert-run-or-rerun-test stats test
2329 ert--results-listener))
2330 (ert--results-update-stats-display ert--results-ewoc stats)
2331 (message "%s...%s"
2332 progress-message
2333 (let ((result (ert-test-most-recent-result test)))
2334 (ert-string-for-test-result
2335 result (ert-test-result-expected-p test result)))))
2336 (goto-char point))))))
2337
2338 (defun ert-results-rerun-test-at-point-debugging-errors ()
2339 "Re-run the test at point with `ert-debug-on-error' bound to t.
2340
2341 To be used in the ERT results buffer."
2342 (interactive)
2343 (let ((ert-debug-on-error t))
2344 (ert-results-rerun-test-at-point)))
2345
2346 (defun ert-results-pop-to-backtrace-for-test-at-point ()
2347 "Display the backtrace for the test at point.
2348
2349 To be used in the ERT results buffer."
2350 (interactive)
2351 (let* ((test (ert--results-test-at-point-no-redefinition))
2352 (stats ert--results-stats)
2353 (pos (ert--stats-test-pos stats test))
2354 (result (aref (ert--stats-test-results stats) pos)))
2355 (etypecase result
2356 (ert-test-passed (error "Test passed, no backtrace available"))
2357 (ert-test-result-with-condition
2358 (let ((backtrace (ert-test-result-with-condition-backtrace result))
2359 (buffer (get-buffer-create "*ERT Backtrace*")))
2360 (pop-to-buffer buffer)
2361 (let ((inhibit-read-only t))
2362 (buffer-disable-undo)
2363 (erase-buffer)
2364 (ert-simple-view-mode)
2365 ;; Use unibyte because `debugger-setup-buffer' also does so.
2366 (set-buffer-multibyte nil)
2367 (setq truncate-lines t)
2368 (ert--print-backtrace backtrace)
2369 (debugger-make-xrefs)
2370 (goto-char (point-min))
2371 (insert "Backtrace for test `")
2372 (ert-insert-test-name-button (ert-test-name test))
2373 (insert "':\n")))))))
2374
2375 (defun ert-results-pop-to-messages-for-test-at-point ()
2376 "Display the part of the *Messages* buffer generated during the test at point.
2377
2378 To be used in the ERT results buffer."
2379 (interactive)
2380 (let* ((test (ert--results-test-at-point-no-redefinition))
2381 (stats ert--results-stats)
2382 (pos (ert--stats-test-pos stats test))
2383 (result (aref (ert--stats-test-results stats) pos)))
2384 (let ((buffer (get-buffer-create "*ERT Messages*")))
2385 (pop-to-buffer buffer)
2386 (let ((inhibit-read-only t))
2387 (buffer-disable-undo)
2388 (erase-buffer)
2389 (ert-simple-view-mode)
2390 (insert (ert-test-result-messages result))
2391 (goto-char (point-min))
2392 (insert "Messages for test `")
2393 (ert-insert-test-name-button (ert-test-name test))
2394 (insert "':\n")))))
2395
2396 (defun ert-results-pop-to-should-forms-for-test-at-point ()
2397 "Display the list of `should' forms executed during the test at point.
2398
2399 To be used in the ERT results buffer."
2400 (interactive)
2401 (let* ((test (ert--results-test-at-point-no-redefinition))
2402 (stats ert--results-stats)
2403 (pos (ert--stats-test-pos stats test))
2404 (result (aref (ert--stats-test-results stats) pos)))
2405 (let ((buffer (get-buffer-create "*ERT list of should forms*")))
2406 (pop-to-buffer buffer)
2407 (let ((inhibit-read-only t))
2408 (buffer-disable-undo)
2409 (erase-buffer)
2410 (ert-simple-view-mode)
2411 (if (null (ert-test-result-should-forms result))
2412 (insert "\n(No should forms during this test.)\n")
2413 (loop for form-description in (ert-test-result-should-forms result)
2414 for i from 1 do
2415 (insert "\n")
2416 (insert (format "%s: " i))
2417 (let ((begin (point)))
2418 (ert--pp-with-indentation-and-newline form-description)
2419 (ert--make-xrefs-region begin (point)))))
2420 (goto-char (point-min))
2421 (insert "`should' forms executed during test `")
2422 (ert-insert-test-name-button (ert-test-name test))
2423 (insert "':\n")
2424 (insert "\n")
2425 (insert (concat "(Values are shallow copies and may have "
2426 "looked different during the test if they\n"
2427 "have been modified destructively.)\n"))
2428 (forward-line 1)))))
2429
2430 (defun ert-results-toggle-printer-limits-for-test-at-point ()
2431 "Toggle how much of the condition to print for the test at point.
2432
2433 To be used in the ERT results buffer."
2434 (interactive)
2435 (let* ((ewoc ert--results-ewoc)
2436 (node (ert--results-test-node-at-point))
2437 (entry (ewoc-data node)))
2438 (setf (ert--ewoc-entry-extended-printer-limits-p entry)
2439 (not (ert--ewoc-entry-extended-printer-limits-p entry)))
2440 (ewoc-invalidate ewoc node)))
2441
2442 (defun ert-results-pop-to-timings ()
2443 "Display test timings for the last run.
2444
2445 To be used in the ERT results buffer."
2446 (interactive)
2447 (let* ((stats ert--results-stats)
2448 (start-times (ert--stats-test-start-times stats))
2449 (end-times (ert--stats-test-end-times stats))
2450 (buffer (get-buffer-create "*ERT timings*"))
2451 (data (loop for test across (ert--stats-tests stats)
2452 for start-time across (ert--stats-test-start-times stats)
2453 for end-time across (ert--stats-test-end-times stats)
2454 collect (list test
2455 (float-time (subtract-time end-time
2456 start-time))))))
2457 (setq data (sort data (lambda (a b)
2458 (> (second a) (second b)))))
2459 (pop-to-buffer buffer)
2460 (let ((inhibit-read-only t))
2461 (buffer-disable-undo)
2462 (erase-buffer)
2463 (ert-simple-view-mode)
2464 (if (null data)
2465 (insert "(No data)\n")
2466 (insert (format "%-3s %8s %8s\n" "" "time" "cumul"))
2467 (loop for (test time) in data
2468 for cumul-time = time then (+ cumul-time time)
2469 for i from 1 do
2470 (let ((begin (point)))
2471 (insert (format "%3s: %8.3f %8.3f " i time cumul-time))
2472 (ert-insert-test-name-button (ert-test-name test))
2473 (insert "\n"))))
2474 (goto-char (point-min))
2475 (insert "Tests by run time (seconds):\n\n")
2476 (forward-line 1))))
2477
2478 ;;;###autoload
2479 (defun ert-describe-test (test-or-test-name)
2480 "Display the documentation for TEST-OR-TEST-NAME (a symbol or ert-test)."
2481 (interactive (list (ert-read-test-name-at-point "Describe test")))
2482 (when (< emacs-major-version 24)
2483 (error "Requires Emacs 24"))
2484 (let (test-name
2485 test-definition)
2486 (etypecase test-or-test-name
2487 (symbol (setq test-name test-or-test-name
2488 test-definition (ert-get-test test-or-test-name)))
2489 (ert-test (setq test-name (ert-test-name test-or-test-name)
2490 test-definition test-or-test-name)))
2491 (help-setup-xref (list #'ert-describe-test test-or-test-name)
2492 (called-interactively-p 'interactive))
2493 (save-excursion
2494 (with-help-window (help-buffer)
2495 (with-current-buffer (help-buffer)
2496 (insert (if test-name (format "%S" test-name) "<anonymous test>"))
2497 (insert " is a test")
2498 (let ((file-name (and test-name
2499 (symbol-file test-name 'ert-deftest))))
2500 (when file-name
2501 (insert " defined in `" (file-name-nondirectory file-name) "'")
2502 (save-excursion
2503 (re-search-backward "`\\([^`']+\\)'" nil t)
2504 (help-xref-button 1 'help-function-def test-name file-name)))
2505 (insert ".")
2506 (fill-region-as-paragraph (point-min) (point))
2507 (insert "\n\n")
2508 (unless (and (ert-test-boundp test-name)
2509 (eql (ert-get-test test-name) test-definition))
2510 (let ((begin (point)))
2511 (insert "Note: This test has been redefined or deleted, "
2512 "this documentation refers to an old definition.")
2513 (fill-region-as-paragraph begin (point)))
2514 (insert "\n\n"))
2515 (insert (or (ert-test-documentation test-definition)
2516 "It is not documented.")
2517 "\n")))))))
2518
2519 (defun ert-results-describe-test-at-point ()
2520 "Display the documentation of the test at point.
2521
2522 To be used in the ERT results buffer."
2523 (interactive)
2524 (ert-describe-test (ert--results-test-at-point-no-redefinition)))
2525
2526
2527 ;;; Actions on load/unload.
2528
2529 (add-to-list 'find-function-regexp-alist '(ert-deftest . ert--find-test-regexp))
2530 (add-to-list 'minor-mode-alist '(ert--current-run-stats
2531 (:eval
2532 (ert--tests-running-mode-line-indicator))))
2533 (add-to-list 'emacs-lisp-mode-hook 'ert--activate-font-lock-keywords)
2534
2535 (defun ert--unload-function ()
2536 "Unload function to undo the side-effects of loading ert.el."
2537 (ert--remove-from-list 'find-function-regexp-alist 'ert-deftest :key #'car)
2538 (ert--remove-from-list 'minor-mode-alist 'ert--current-run-stats :key #'car)
2539 (ert--remove-from-list 'emacs-lisp-mode-hook
2540 'ert--activate-font-lock-keywords)
2541 nil)
2542
2543 (defvar ert-unload-hook '())
2544 (add-hook 'ert-unload-hook 'ert--unload-function)
2545
2546
2547 (provide 'ert)
2548
2549 ;;; ert.el ends here