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