forked from rejeep/ert-runner.el
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ert-compat.el
2544 lines (2259 loc) · 103 KB
/
ert-compat.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; ert.el --- Emacs Lisp Regression Testing
;; Copyright (C) 2007, 2008, 2010 Free Software Foundation, Inc.
;; Author: Christian M. Ohler
;; Keywords: lisp, tools
;; This file is NOT part of GNU Emacs.
;; This program is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; This program is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see `http://www.gnu.org/licenses/'.
;;; Commentary:
;; ERT is a tool for automated testing in Emacs Lisp. Its main
;; features are facilities for defining and running test cases and
;; reporting the results as well as for debugging test failures
;; interactively.
;;
;; The main entry points are `ert-deftest', which is similar to
;; `defun' but defines a test, and `ert-run-tests-interactively',
;; which runs tests and offers an interactive interface for inspecting
;; results and debugging. There is also
;; `ert-run-tests-batch-and-exit' for non-interactive use.
;;
;; The body of `ert-deftest' forms resembles a function body, but the
;; additional operators `should', `should-not' and `should-error' are
;; available. `should' is similar to cl's `assert', but signals a
;; different error when its condition is violated that is caught and
;; processed by ERT. In addition, it analyzes its argument form and
;; records information that helps debugging (`assert' tries to do
;; something similar when its second argument SHOW-ARGS is true, but
;; `should' is more sophisticated). For information on `should-not'
;; and `should-error', see their docstrings.
;;
;; See ERT's info manual as well as the docstrings for more details.
;; To compile the manual, run `makeinfo ert.texinfo' in the ERT
;; directory, then C-u M-x info ert.info in Emacs to view it.
;;
;; To see some examples of tests written in ERT, see its self-tests in
;; ert-tests.el. Some of these are tricky due to the bootstrapping
;; problem of writing tests for a testing tool, others test simple
;; functions and are straightforward.
;;; Code:
(eval-when-compile
(require 'cl))
(require 'button)
(require 'debug)
(require 'easymenu)
(require 'ewoc)
(require 'find-func)
(require 'help)
;;; UI customization options.
(defgroup ert ()
"ERT, the Emacs Lisp regression testing tool."
:prefix "ert-"
:group 'lisp)
(defface ert-test-result-expected '((((class color) (background light))
:background "green1")
(((class color) (background dark))
:background "green3"))
"Face used for expected results in the ERT results buffer."
:group 'ert)
(defface ert-test-result-unexpected '((((class color) (background light))
:background "red1")
(((class color) (background dark))
:background "red3"))
"Face used for unexpected results in the ERT results buffer."
:group 'ert)
;;; Copies/reimplementations of cl functions.
(defun ert--cl-do-remf (plist tag)
"Copy of `cl-do-remf'. Modify PLIST by removing TAG."
(let ((p (cdr plist)))
(while (and (cdr p) (not (eq (car (cdr p)) tag))) (setq p (cdr (cdr p))))
(and (cdr p) (progn (setcdr p (cdr (cdr (cdr p)))) t))))
(defun ert--remprop (sym tag)
"Copy of `cl-remprop'. Modify SYM's plist by removing TAG."
(let ((plist (symbol-plist sym)))
(if (and plist (eq tag (car plist)))
(progn (setplist sym (cdr (cdr plist))) t)
(ert--cl-do-remf plist tag))))
(defun ert--remove-if-not (ert-pred ert-list)
"A reimplementation of `remove-if-not'.
ERT-PRED is a predicate, ERT-LIST is the input list."
(loop for ert-x in ert-list
if (funcall ert-pred ert-x)
collect ert-x))
(defun ert--intersection (a b)
"A reimplementation of `intersection'. Intersect the sets A and B.
Elements are compared using `eql'."
(loop for x in a
if (memql x b)
collect x))
(defun ert--set-difference (a b)
"A reimplementation of `set-difference'. Subtract the set B from the set A.
Elements are compared using `eql'."
(loop for x in a
unless (memql x b)
collect x))
(defun ert--set-difference-eq (a b)
"A reimplementation of `set-difference'. Subtract the set B from the set A.
Elements are compared using `eq'."
(loop for x in a
unless (memq x b)
collect x))
(defun ert--union (a b)
"A reimplementation of `union'. Compute the union of the sets A and B.
Elements are compared using `eql'."
(append a (ert--set-difference b a)))
(eval-and-compile
(defvar ert--gensym-counter 0))
(eval-and-compile
(defun ert--gensym (&optional prefix)
"Only allows string PREFIX, not compatible with CL."
(unless prefix (setq prefix "G"))
(make-symbol (format "%s%s"
prefix
(prog1 ert--gensym-counter
(incf ert--gensym-counter))))))
(defun ert--coerce-to-vector (x)
"Coerce X to a vector."
(when (char-table-p x) (error "Not supported"))
(if (vectorp x)
x
(vconcat x)))
(defun* ert--remove* (x list &key key test)
"Does not support all the keywords of remove*."
(unless key (setq key #'identity))
(unless test (setq test #'eql))
(loop for y in list
unless (funcall test x (funcall key y))
collect y))
(defun ert--string-position (c s)
"Return the position of the first occurrence of C in S, or nil if none."
(loop for i from 0
for x across s
when (eql x c) return i))
(defun ert--mismatch (a b)
"Return index of first element that differs between A and B.
Like `mismatch'. Uses `equal' for comparison."
(cond ((or (listp a) (listp b))
(ert--mismatch (ert--coerce-to-vector a)
(ert--coerce-to-vector b)))
((> (length a) (length b))
(ert--mismatch b a))
(t
(let ((la (length a))
(lb (length b)))
(assert (arrayp a) t)
(assert (arrayp b) t)
(assert (<= la lb) t)
(loop for i below la
when (not (equal (aref a i) (aref b i))) return i
finally (return (if (/= la lb)
la
(assert (equal a b) t)
nil)))))))
(defun ert--subseq (seq start &optional end)
"Return a subsequence of SEQ from START to END."
(when (char-table-p seq) (error "Not supported"))
(let ((vector (substring (ert--coerce-to-vector seq) start end)))
(etypecase seq
(vector vector)
(string (concat vector))
(list (append vector nil))
(bool-vector (loop with result = (make-bool-vector (length vector) nil)
for i below (length vector) do
(setf (aref result i) (aref vector i))
finally (return result)))
(char-table (assert nil)))))
(defun ert-equal-including-properties (a b)
"Return t if A and B have similar structure and contents.
This is like `equal-including-properties' except that it compares
the property values of text properties structurally (by
recursing) rather than with `eq'. Perhaps this is what
`equal-including-properties' should do in the first place; see
Emacs bug 6581 at URL `http://debbugs.gnu.org/cgi/bugreport.cgi?bug=6581'."
;; This implementation is inefficient. Rather than making it
;; efficient, let's hope bug 6581 gets fixed so that we can delete
;; it altogether.
(not (ert--explain-not-equal-including-properties a b)))
;;; Defining and locating tests.
;; The data structure that represents a test case.
(defstruct ert-test
(name nil)
(documentation nil)
(body (assert nil))
(most-recent-result nil)
(expected-result-type ':passed)
(tags '()))
(defun ert-test-boundp (symbol)
"Return non-nil if SYMBOL names a test."
(and (get symbol 'ert--test) t))
(defun ert-get-test (symbol)
"If SYMBOL names a test, return that. Signal an error otherwise."
(unless (ert-test-boundp symbol) (error "No test named `%S'" symbol))
(get symbol 'ert--test))
(defun ert-set-test (symbol definition)
"Make SYMBOL name the test DEFINITION, and return DEFINITION."
(when (eq symbol 'nil)
;; We disallow nil since `ert-test-at-point' and related functions
;; want to return a test name, but also need an out-of-band value
;; on failure. Nil is the most natural out-of-band value; using 0
;; or "" or signalling an error would be too awkward.
;;
;; Note that nil is still a valid value for the `name' slot in
;; ert-test objects. It designates an anonymous test.
(error "Attempt to define a test named nil"))
(put symbol 'ert--test definition)
definition)
(defun ert-make-test-unbound (symbol)
"Make SYMBOL name no test. Return SYMBOL."
(ert--remprop symbol 'ert--test)
symbol)
(defun ert--parse-keys-and-body (keys-and-body)
"Split KEYS-AND-BODY into keyword-and-value pairs and the remaining body.
KEYS-AND-BODY should have the form of a property list, with the
exception that only keywords are permitted as keys and that the
tail -- the body -- is a list of forms that does not start with a
keyword.
Returns a two-element list containing the keys-and-values plist
and the body."
(let ((extracted-key-accu '())
(remaining keys-and-body))
(while (and (consp remaining) (keywordp (first remaining)))
(let ((keyword (pop remaining)))
(unless (consp remaining)
(error "Value expected after keyword %S in %S"
keyword keys-and-body))
(when (assoc keyword extracted-key-accu)
(warn "Keyword %S appears more than once in %S" keyword
keys-and-body))
(push (cons keyword (pop remaining)) extracted-key-accu)))
(setq extracted-key-accu (nreverse extracted-key-accu))
(list (loop for (key . value) in extracted-key-accu
collect key
collect value)
remaining)))
;;;###autoload
(defmacro* ert-deftest (name () &body docstring-keys-and-body)
"Define NAME (a symbol) as a test.
BODY is evaluated as a `progn' when the test is run. It should
signal a condition on failure or just return if the test passes.
`should', `should-not' and `should-error' are useful for
assertions in BODY.
Use `ert' to run tests interactively.
Tests that are expected to fail can be marked as such
using :expected-result. See `ert-test-result-type-p' for a
description of valid values for RESULT-TYPE.
\(fn NAME () [DOCSTRING] [:expected-result RESULT-TYPE] \
\[:tags '(TAG...)] BODY...)"
(declare (debug (&define :name test
name sexp [&optional stringp]
[&rest keywordp sexp] def-body))
(doc-string 3)
(indent 2))
(let ((documentation nil)
(documentation-supplied-p nil))
(when (stringp (first docstring-keys-and-body))
(setq documentation (pop docstring-keys-and-body)
documentation-supplied-p t))
(destructuring-bind ((&key (expected-result nil expected-result-supplied-p)
(tags nil tags-supplied-p))
body)
(ert--parse-keys-and-body docstring-keys-and-body)
`(progn
(ert-set-test ',name
(make-ert-test
:name ',name
,@(when documentation-supplied-p
`(:documentation ,documentation))
,@(when expected-result-supplied-p
`(:expected-result-type ,expected-result))
,@(when tags-supplied-p
`(:tags ,tags))
:body (lambda () ,@body)))
;; This hack allows `symbol-file' to associate `ert-deftest'
;; forms with files, and therefore enables `find-function' to
;; work with tests. However, it leads to warnings in
;; `unload-feature', which doesn't know how to undefine tests
;; and has no mechanism for extension.
(push '(ert-deftest . ,name) current-load-list)
',name))))
;; We use these `put' forms in addition to the (declare (indent)) in
;; the defmacro form since the `declare' alone does not lead to
;; correct indentation before the .el/.elc file is loaded.
;; Autoloading these `put' forms solves this.
;;;###autoload
(progn
;; TODO(ohler): Figure out what these mean and make sure they are correct.
(put 'ert-deftest 'lisp-indent-function 2)
(put 'ert-info 'lisp-indent-function 1))
(defvar ert--find-test-regexp
(concat "^\\s-*(ert-deftest"
find-function-space-re
"%s\\(\\s-\\|$\\)")
"The regexp the `find-function' mechanisms use for finding test definitions.")
(put 'ert-test-failed 'error-conditions '(error ert-test-failed))
(put 'ert-test-failed 'error-message "Test failed")
(defun ert-pass ()
"Terminate the current test and mark it passed. Does not return."
(throw 'ert--pass nil))
(defun ert-fail (data)
"Terminate the current test and mark it failed. Does not return.
DATA is displayed to the user and should state the reason of the failure."
(signal 'ert-test-failed (list data)))
;;; The `should' macros.
(defvar ert--should-execution-observer nil)
(defun ert--signal-should-execution (form-description)
"Tell the current `should' form observer (if any) about FORM-DESCRIPTION."
(when ert--should-execution-observer
(funcall ert--should-execution-observer form-description)))
(defun ert--special-operator-p (thing)
"Return non-nil if THING is a symbol naming a special operator."
(and (symbolp thing)
(let ((definition (indirect-function thing t)))
(and (subrp definition)
(eql (cdr (subr-arity definition)) 'unevalled)))))
(defun ert--expand-should-1 (whole form inner-expander)
"Helper function for the `should' macro and its variants."
(let ((form
;; If `cl-macroexpand' isn't bound, the code that we're
;; compiling doesn't depend on cl and thus doesn't need an
;; environment arg for `macroexpand'.
(if (fboundp 'cl-macroexpand)
;; Suppress warning about run-time call to cl funtion: we
;; only call it if it's fboundp.
(with-no-warnings
(cl-macroexpand form (and (boundp 'cl-macro-environment)
cl-macro-environment)))
(macroexpand form))))
(cond
((or (atom form) (ert--special-operator-p (car form)))
(let ((value (ert--gensym "value-")))
`(let ((,value (ert--gensym "ert-form-evaluation-aborted-")))
,(funcall inner-expander
`(setq ,value ,form)
`(list ',whole :form ',form :value ,value)
value)
,value)))
(t
(let ((fn-name (car form))
(arg-forms (cdr form)))
(assert (or (symbolp fn-name)
(and (consp fn-name)
(eql (car fn-name) 'lambda)
(listp (cdr fn-name)))))
(let ((fn (ert--gensym "fn-"))
(args (ert--gensym "args-"))
(value (ert--gensym "value-"))
(default-value (ert--gensym "ert-form-evaluation-aborted-")))
`(let ((,fn (function ,fn-name))
(,args (list ,@arg-forms)))
(let ((,value ',default-value))
,(funcall inner-expander
`(setq ,value (apply ,fn ,args))
`(nconc (list ',whole)
(list :form `(,,fn ,@,args))
(unless (eql ,value ',default-value)
(list :value ,value))
(let ((-explainer-
(and (symbolp ',fn-name)
(get ',fn-name 'ert-explainer))))
(when -explainer-
(list :explanation
(apply -explainer- ,args)))))
value)
,value))))))))
(defun ert--expand-should (whole form inner-expander)
"Helper function for the `should' macro and its variants.
Analyzes FORM and returns an expression that has the same
semantics under evaluation but records additional debugging
information.
INNER-EXPANDER should be a function and is called with two
arguments: INNER-FORM and FORM-DESCRIPTION-FORM, where INNER-FORM
is an expression equivalent to FORM, and FORM-DESCRIPTION-FORM is
an expression that returns a description of FORM. INNER-EXPANDER
should return code that calls INNER-FORM and performs the checks
and error signalling specific to the particular variant of
`should'. The code that INNER-EXPANDER returns must not call
FORM-DESCRIPTION-FORM before it has called INNER-FORM."
(lexical-let ((inner-expander inner-expander))
(ert--expand-should-1
whole form
(lambda (inner-form form-description-form value-var)
(let ((form-description (ert--gensym "form-description-")))
`(let (,form-description)
,(funcall inner-expander
`(unwind-protect
,inner-form
(setq ,form-description ,form-description-form)
(ert--signal-should-execution ,form-description))
`,form-description
value-var)))))))
(defmacro* should (form)
"Evaluate FORM. If it returns nil, abort the current test as failed.
Returns the value of FORM."
(ert--expand-should `(should ,form) form
(lambda (inner-form form-description-form value-var)
`(unless ,inner-form
(ert-fail ,form-description-form)))))
(defmacro* should-not (form)
"Evaluate FORM. If it returns non-nil, abort the current test as failed.
Returns nil."
(ert--expand-should `(should-not ,form) form
(lambda (inner-form form-description-form value-var)
`(unless (not ,inner-form)
(ert-fail ,form-description-form)))))
(defun ert--should-error-handle-error (form-description-fn
condition type exclude-subtypes)
"Helper function for `should-error'.
Determines whether CONDITION matches TYPE and EXCLUDE-SUBTYPES,
and aborts the current test as failed if it doesn't."
(let ((signalled-conditions (get (car condition) 'error-conditions))
(handled-conditions (etypecase type
(list type)
(symbol (list type)))))
(assert signalled-conditions)
(unless (ert--intersection signalled-conditions handled-conditions)
(ert-fail (append
(funcall form-description-fn)
(list
:condition condition
:fail-reason (concat "the error signalled did not"
" have the expected type")))))
(when exclude-subtypes
(unless (member (car condition) handled-conditions)
(ert-fail (append
(funcall form-description-fn)
(list
:condition condition
:fail-reason (concat "the error signalled was a subtype"
" of the expected type"))))))))
;; FIXME: The expansion will evaluate the keyword args (if any) in
;; nonstandard order.
(defmacro* should-error (form &rest keys &key type exclude-subtypes)
"Evaluate FORM and check that it signals an error.
The error signalled needs to match TYPE. TYPE should be a list
of condition names. (It can also be a non-nil symbol, which is
equivalent to a singleton list containing that symbol.) If
EXCLUDE-SUBTYPES is nil, the error matches TYPE if one of its
condition names is an element of TYPE. If EXCLUDE-SUBTYPES is
non-nil, the error matches TYPE if it is an element of TYPE.
If the error matches, returns (ERROR-SYMBOL . DATA) from the
error. If not, or if no error was signalled, abort the test as
failed."
(unless type (setq type ''error))
(ert--expand-should
`(should-error ,form ,@keys)
form
(lambda (inner-form form-description-form value-var)
(let ((errorp (ert--gensym "errorp"))
(form-description-fn (ert--gensym "form-description-fn-")))
`(let ((,errorp nil)
(,form-description-fn (lambda () ,form-description-form)))
(condition-case -condition-
,inner-form
;; We can't use ,type here because we want to evaluate it.
(error
(setq ,errorp t)
(ert--should-error-handle-error ,form-description-fn
-condition-
,type ,exclude-subtypes)
(setq ,value-var -condition-)))
(unless ,errorp
(ert-fail (append
(funcall ,form-description-fn)
(list
:fail-reason "did not signal an error")))))))))
;;; Explanation of `should' failures.
;; TODO(ohler): Rework explanations so that they are displayed in a
;; similar way to `ert-info' messages; in particular, allow text
;; buttons in explanations that give more detail or open an ediff
;; buffer. Perhaps explanations should be reported through `ert-info'
;; rather than as part of the condition.
(defun ert--proper-list-p (x)
"Return non-nil if X is a proper list, nil otherwise."
(loop
for firstp = t then nil
for fast = x then (cddr fast)
for slow = x then (cdr slow) do
(when (null fast) (return t))
(when (not (consp fast)) (return nil))
(when (null (cdr fast)) (return t))
(when (not (consp (cdr fast))) (return nil))
(when (and (not firstp) (eq fast slow)) (return nil))))
(defun ert--explain-format-atom (x)
"Format the atom X for `ert--explain-not-equal'."
(typecase x
(fixnum (list x (format "#x%x" x) (format "?%c" x)))
(t x)))
(defun ert--explain-not-equal (a b)
"Explainer function for `equal'.
Returns a programmer-readable explanation of why A and B are not
`equal', or nil if they are."
(if (not (equal (type-of a) (type-of b)))
`(different-types ,a ,b)
(etypecase a
(cons
(let ((a-proper-p (ert--proper-list-p a))
(b-proper-p (ert--proper-list-p b)))
(if (not (eql (not a-proper-p) (not b-proper-p)))
`(one-list-proper-one-improper ,a ,b)
(if a-proper-p
(if (not (equal (length a) (length b)))
`(proper-lists-of-different-length ,(length a) ,(length b)
,a ,b
first-mismatch-at
,(ert--mismatch a b))
(loop for i from 0
for ai in a
for bi in b
for xi = (ert--explain-not-equal ai bi)
do (when xi (return `(list-elt ,i ,xi)))
finally (assert (equal a b) t)))
(let ((car-x (ert--explain-not-equal (car a) (car b))))
(if car-x
`(car ,car-x)
(let ((cdr-x (ert--explain-not-equal (cdr a) (cdr b))))
(if cdr-x
`(cdr ,cdr-x)
(assert (equal a b) t)
nil))))))))
(array (if (not (equal (length a) (length b)))
`(arrays-of-different-length ,(length a) ,(length b)
,a ,b
,@(unless (char-table-p a)
`(first-mismatch-at
,(ert--mismatch a b))))
(loop for i from 0
for ai across a
for bi across b
for xi = (ert--explain-not-equal ai bi)
do (when xi (return `(array-elt ,i ,xi)))
finally (assert (equal a b) t))))
(atom (if (not (equal a b))
(if (and (symbolp a) (symbolp b) (string= a b))
`(different-symbols-with-the-same-name ,a ,b)
`(different-atoms ,(ert--explain-format-atom a)
,(ert--explain-format-atom b)))
nil)))))
(put 'equal 'ert-explainer 'ert--explain-not-equal)
(defun ert--significant-plist-keys (plist)
"Return the keys of PLIST that have non-null values, in order."
(assert (zerop (mod (length plist) 2)) t)
(loop for (key value . rest) on plist by #'cddr
unless (or (null value) (memq key accu)) collect key into accu
finally (return accu)))
(defun ert--plist-difference-explanation (a b)
"Return a programmer-readable explanation of why A and B are different plists.
Returns nil if they are equivalent, i.e., have the same value for
each key, where absent values are treated as nil. The order of
key/value pairs in each list does not matter."
(assert (zerop (mod (length a) 2)) t)
(assert (zerop (mod (length b) 2)) t)
;; Normalizing the plists would be another way to do this but it
;; requires a total ordering on all lisp objects (since any object
;; is valid as a text property key). Perhaps defining such an
;; ordering is useful in other contexts, too, but it's a lot of
;; work, so let's punt on it for now.
(let* ((keys-a (ert--significant-plist-keys a))
(keys-b (ert--significant-plist-keys b))
(keys-in-a-not-in-b (ert--set-difference-eq keys-a keys-b))
(keys-in-b-not-in-a (ert--set-difference-eq keys-b keys-a)))
(flet ((explain-with-key (key)
(let ((value-a (plist-get a key))
(value-b (plist-get b key)))
(assert (not (equal value-a value-b)) t)
`(different-properties-for-key
,key ,(ert--explain-not-equal-including-properties value-a
value-b)))))
(cond (keys-in-a-not-in-b
(explain-with-key (first keys-in-a-not-in-b)))
(keys-in-b-not-in-a
(explain-with-key (first keys-in-b-not-in-a)))
(t
(loop for key in keys-a
when (not (equal (plist-get a key) (plist-get b key)))
return (explain-with-key key)))))))
(defun ert--abbreviate-string (s len suffixp)
"Shorten string S to at most LEN chars.
If SUFFIXP is non-nil, returns a suffix of S, otherwise a prefix."
(let ((n (length s)))
(cond ((< n len)
s)
(suffixp
(substring s (- n len)))
(t
(substring s 0 len)))))
(defun ert--explain-not-equal-including-properties (a b)
"Explainer function for `ert-equal-including-properties'.
Returns a programmer-readable explanation of why A and B are not
`ert-equal-including-properties', or nil if they are."
(if (not (equal a b))
(ert--explain-not-equal a b)
(assert (stringp a) t)
(assert (stringp b) t)
(assert (eql (length a) (length b)) t)
(loop for i from 0 to (length a)
for props-a = (text-properties-at i a)
for props-b = (text-properties-at i b)
for difference = (ert--plist-difference-explanation props-a props-b)
do (when difference
(return `(char ,i ,(substring-no-properties a i (1+ i))
,difference
context-before
,(ert--abbreviate-string
(substring-no-properties a 0 i)
10 t)
context-after
,(ert--abbreviate-string
(substring-no-properties a (1+ i))
10 nil))))
;; TODO(ohler): Get `equal-including-properties' fixed in
;; Emacs, delete `ert-equal-including-properties', and
;; re-enable this assertion.
;;finally (assert (equal-including-properties a b) t)
)))
(put 'ert-equal-including-properties
'ert-explainer
'ert--explain-not-equal-including-properties)
;;; Implementation of `ert-info'.
;; TODO(ohler): The name `info' clashes with
;; `ert--test-execution-info'. One or both should be renamed.
(defvar ert--infos '()
"The stack of `ert-info' infos that currently apply.
Bound dynamically. This is a list of (PREFIX . MESSAGE) pairs.")
(defmacro* ert-info ((message-form &key ((:prefix prefix-form) "Info: "))
&body body)
"Evaluate MESSAGE-FORM and BODY, and report the message if BODY fails.
To be used within ERT tests. MESSAGE-FORM should evaluate to a
string that will be displayed together with the test result if
the test fails. PREFIX-FORM should evaluate to a string as well
and is displayed in front of the value of MESSAGE-FORM."
(declare (debug ((form &rest [sexp form]) body))
(indent 1))
`(let ((ert--infos (cons (cons ,prefix-form ,message-form) ert--infos)))
,@body))
;;; Facilities for running a single test.
(defvar ert-debug-on-error nil
"Non-nil means enter debugger when a test fails or terminates with an error.")
;; The data structures that represent the result of running a test.
(defstruct ert-test-result
(messages nil)
(should-forms nil)
)
(defstruct (ert-test-passed (:include ert-test-result)))
(defstruct (ert-test-result-with-condition (:include ert-test-result))
(condition (assert nil))
(backtrace (assert nil))
(infos (assert nil)))
(defstruct (ert-test-quit (:include ert-test-result-with-condition)))
(defstruct (ert-test-failed (:include ert-test-result-with-condition)))
(defstruct (ert-test-aborted-with-non-local-exit (:include ert-test-result)))
(defun ert--record-backtrace ()
"Record the current backtrace (as a list) and return it."
;; Since the backtrace is stored in the result object, result
;; objects must only be printed with appropriate limits
;; (`print-level' and `print-length') in place. For interactive
;; use, the cost of ensuring this possibly outweighs the advantage
;; of storing the backtrace for
;; `ert-results-pop-to-backtrace-for-test-at-point' given that we
;; already have `ert-results-rerun-test-debugging-errors-at-point'.
;; For batch use, however, printing the backtrace may be useful.
(loop
;; 6 is the number of frames our own debugger adds (when
;; compiled; more when interpreted). FIXME: Need to describe a
;; procedure for determining this constant.
for i from 6
for frame = (backtrace-frame i)
while frame
collect frame))
(defun ert--print-backtrace (backtrace)
"Format the backtrace BACKTRACE to the current buffer."
;; This is essentially a reimplementation of Fbacktrace
;; (src/eval.c), but for a saved backtrace, not the current one.
(let ((print-escape-newlines t)
(print-level 8)
(print-length 50))
(dolist (frame backtrace)
(ecase (first frame)
((nil)
;; Special operator.
(destructuring-bind (special-operator &rest arg-forms)
(cdr frame)
(insert
(format " %S\n" (list* special-operator arg-forms)))))
((t)
;; Function call.
(destructuring-bind (fn &rest args) (cdr frame)
(insert (format " %S(" fn))
(loop for firstp = t then nil
for arg in args do
(unless firstp
(insert " "))
(insert (format "%S" arg)))
(insert ")\n")))))))
;; A container for the state of the execution of a single test and
;; environment data needed during its execution.
(defstruct ert--test-execution-info
(test (assert nil))
(result (assert nil))
;; A thunk that may be called when RESULT has been set to its final
;; value and test execution should be terminated. Should not
;; return.
(exit-continuation (assert nil))
;; The binding of `debugger' outside of the execution of the test.
next-debugger
;; The binding of `ert-debug-on-error' that is in effect for the
;; execution of the current test. We store it to avoid being
;; affected by any new bindings the test itself may establish. (I
;; don't remember whether this feature is important.)
ert-debug-on-error)
(defun ert--run-test-debugger (info debugger-args)
"During a test run, `debugger' is bound to a closure that calls this function.
This function records failures and errors and either terminates
the test silently or calls the interactive debugger, as
appropriate.
INFO is the ert--test-execution-info corresponding to this test
run. DEBUGGER-ARGS are the arguments to `debugger'."
(destructuring-bind (first-debugger-arg &rest more-debugger-args)
debugger-args
(ecase first-debugger-arg
((lambda debug t exit nil)
(apply (ert--test-execution-info-next-debugger info) debugger-args))
(error
(let* ((condition (first more-debugger-args))
(type (case (car condition)
((quit) 'quit)
(otherwise 'failed)))
(backtrace (ert--record-backtrace))
(infos (reverse ert--infos)))
(setf (ert--test-execution-info-result info)
(ecase type
(quit
(make-ert-test-quit :condition condition
:backtrace backtrace
:infos infos))
(failed
(make-ert-test-failed :condition condition
:backtrace backtrace
:infos infos))))
;; Work around Emacs' heuristic (in eval.c) for detecting
;; errors in the debugger.
(incf num-nonmacro-input-events)
;; FIXME: We should probably implement more fine-grained
;; control a la non-t `debug-on-error' here.
(cond
((ert--test-execution-info-ert-debug-on-error info)
(apply (ert--test-execution-info-next-debugger info) debugger-args))
(t))
(funcall (ert--test-execution-info-exit-continuation info)))))))
(defun ert--run-test-internal (ert-test-execution-info)
"Low-level function to run a test according to ERT-TEST-EXECUTION-INFO.
This mainly sets up debugger-related bindings."
(lexical-let ((info ert-test-execution-info))
(setf (ert--test-execution-info-next-debugger info) debugger
(ert--test-execution-info-ert-debug-on-error info) ert-debug-on-error)
(catch 'ert--pass
;; For now, each test gets its own temp buffer and its own
;; window excursion, just to be safe. If this turns out to be
;; too expensive, we can remove it.
(with-temp-buffer
(save-window-excursion
(let ((debugger (lambda (&rest debugger-args)
(ert--run-test-debugger info debugger-args)))
(debug-on-error t)
(debug-on-quit t)
;; FIXME: Do we need to store the old binding of this
;; and consider it in `ert--run-test-debugger'?
(debug-ignored-errors nil)
(ert--infos '()))
(funcall (ert-test-body (ert--test-execution-info-test info))))))
(ert-pass))
(setf (ert--test-execution-info-result info) (make-ert-test-passed)))
nil)
(defun ert--force-message-log-buffer-truncation ()
"Immediately truncate *Messages* buffer according to `message-log-max'.
This can be useful after reducing the value of `message-log-max'."
(with-current-buffer (get-buffer-create "*Messages*")
;; This is a reimplementation of this part of message_dolog() in xdisp.c:
;; if (NATNUMP (Vmessage_log_max))
;; {
;; scan_newline (Z, Z_BYTE, BEG, BEG_BYTE,
;; -XFASTINT (Vmessage_log_max) - 1, 0);
;; del_range_both (BEG, BEG_BYTE, PT, PT_BYTE, 0);
;; }
(when (and (integerp message-log-max) (>= message-log-max 0))
(let ((begin (point-min))
(end (save-excursion
(goto-char (point-max))
(forward-line (- message-log-max))
(point))))
(delete-region begin end)))))
(defvar ert--running-tests nil
"List of tests that are currently in execution.
This list is empty while no test is running, has one element
while a test is running, two elements while a test run from
inside a test is running, etc. The list is in order of nesting,
innermost test first.
The elements are of type `ert-test'.")
(defun ert-run-test (ert-test)
"Run ERT-TEST.
Returns the result and stores it in ERT-TEST's `most-recent-result' slot."
(setf (ert-test-most-recent-result ert-test) nil)
(block error
(lexical-let ((begin-marker
(with-current-buffer (get-buffer-create "*Messages*")
(set-marker (make-marker) (point-max)))))
(unwind-protect
(lexical-let ((info (make-ert--test-execution-info
:test ert-test
:result
(make-ert-test-aborted-with-non-local-exit)
:exit-continuation (lambda ()
(return-from error nil))))
(should-form-accu (list)))
(unwind-protect
(let ((ert--should-execution-observer
(lambda (form-description)
(push form-description should-form-accu)))
(message-log-max t)
(ert--running-tests (cons ert-test ert--running-tests)))
(ert--run-test-internal info))
(let ((result (ert--test-execution-info-result info)))
(setf (ert-test-result-messages result)
(with-current-buffer (get-buffer-create "*Messages*")
(buffer-substring begin-marker (point-max))))
(ert--force-message-log-buffer-truncation)
(setq should-form-accu (nreverse should-form-accu))
(setf (ert-test-result-should-forms result)
should-form-accu)
(setf (ert-test-most-recent-result ert-test) result))))
(set-marker begin-marker nil))))
(ert-test-most-recent-result ert-test))
(defun ert-running-test ()
"Return the top-level test currently executing."
(car (last ert--running-tests)))
;;; Test selectors.
(defun ert-test-result-type-p (result result-type)
"Return non-nil if RESULT matches type RESULT-TYPE.
Valid result types:
nil -- Never matches.
t -- Always matches.
:failed, :passed -- Matches corresponding results.
\(and TYPES...\) -- Matches if all TYPES match.
\(or TYPES...\) -- Matches if some TYPES match.
\(not TYPE\) -- Matches if TYPE does not match.
\(satisfies PREDICATE\) -- Matches if PREDICATE returns true when called with
RESULT."
;; It would be easy to add `member' and `eql' types etc., but I
;; haven't bothered yet.
(etypecase result-type
((member nil) nil)
((member t) t)
((member :failed) (ert-test-failed-p result))
((member :passed) (ert-test-passed-p result))
(cons
(destructuring-bind (operator &rest operands) result-type
(ecase operator
(and
(case (length operands)
(0 t)
(t
(and (ert-test-result-type-p result (first operands))
(ert-test-result-type-p result `(and ,@(rest operands)))))))
(or
(case (length operands)
(0 nil)
(t
(or (ert-test-result-type-p result (first operands))
(ert-test-result-type-p result `(or ,@(rest operands)))))))