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