summaryrefslogtreecommitdiff
path: root/lisp/emacs-lisp/ert.el
blob: fdbf95319ff50951843724c794c2378914d63f08 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
;;; ert.el --- Emacs Lisp Regression Testing  -*- lexical-binding: t -*-

;; Copyright (C) 2007-2008, 2010-2021 Free Software Foundation, Inc.

;; Author: Christian Ohler <ohler@gnu.org>
;; Keywords: lisp, tools

;; This file is part of GNU Emacs.

;; GNU Emacs 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.

;; GNU Emacs 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 GNU Emacs.  If not, see <https://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', `should-error' and
;; `skip-unless' 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.  `skip-unless' skips the test immediately without
;; processing further, this is useful for checking the test
;; environment (like availability of features, external binaries, etc).
;;
;; 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:

(require 'cl-lib)
(require 'debug)
(require 'backtrace)
(require 'easymenu)
(require 'ewoc)
(require 'find-func)
(require 'pp)

;;; UI customization options.

(defgroup ert ()
  "ERT, the Emacs Lisp regression testing tool."
  :prefix "ert-"
  :group 'lisp)

(defcustom ert-batch-backtrace-right-margin 70
  "Maximum length of lines in ERT backtraces in batch mode.
Use nil for no limit (caution: backtrace lines can be very long)."
  :type '(choice (const :tag "No truncation" nil) integer))

(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-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 `https://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-equal-including-properties a b)))


;;; Defining and locating tests.

;; The data structure that represents a test case.
(cl-defstruct ert-test
  (name nil)
  (documentation nil)
  (body (cl-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 signaling 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"))
  (define-symbol-prop symbol 'ert--test definition)
  definition)

(defun ert-make-test-unbound (symbol)
  "Make SYMBOL name no test.  Return SYMBOL."
  (cl-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 (keywordp (car-safe 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 (cl-loop for (key . value) in extracted-key-accu
                   collect key
                   collect value)
          remaining)))

;;;###autoload
(cl-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', `should-error' and `skip-unless' 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.

Macros in BODY are expanded when the test is defined, not when it
is run.  If a macro (possibly with side effects) is to be tested,
it has to be wrapped in `(eval (quote ...))'.

\(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 (car docstring-keys-and-body))
      (setq documentation (pop docstring-keys-and-body)
            documentation-supplied-p t))
    (cl-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)
      `(cl-macrolet ((skip-unless (form) `(ert--skip-unless ,form)))
         (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)))
         ',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.")


(define-error 'ert-test-failed "Test failed")
(define-error 'ert-test-skipped "Test skipped")

(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)))

(defun ert-skip (data)
  "Terminate the current test and mark it skipped.  Does not return.
DATA is displayed to the user and should state the reason for skipping."
  (signal 'ert-test-skipped (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)))

;; See Bug#24402 for why this exists
(defun ert--should-signal-hook (error-symbol data)
  "Stupid hack to stop `condition-case' from catching ert signals.
It should only be stopped when ran from inside ert--run-test-internal."
  (when (and (not (symbolp debugger))   ; only run on anonymous debugger
             (memq error-symbol '(ert-test-failed ert-test-skipped)))
    (funcall debugger 'error (list error-symbol data))))

(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)))
         (and (subrp definition)
              (eql (cdr (subr-arity definition)) 'unevalled)))))

;; FIXME: Code inside of here should probably be evaluated like it is
;; outside of tests, with the sole exception of error handling
(defun ert--expand-should-1 (whole form inner-expander)
  "Helper function for the `should' macro and its variants."
  (let ((form
         ;; catch macroexpansion errors
         (condition-case err
             (macroexpand-all form
                              (append (bound-and-true-p
                                       byte-compile-macro-environment)
                                      (cond
                                       ((boundp 'macroexpand-all-environment)
                                        macroexpand-all-environment)
                                       ((boundp 'cl-macro-environment)
                                        cl-macro-environment))))
           (error `(signal ',(car err) ',(cdr err))))))
    (cond
     ((or (atom form) (ert--special-operator-p (car form)))
      (let ((value (gensym "value-")))
        `(let ((,value (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)))
        (cl-assert (or (symbolp fn-name)
                       (and (consp fn-name)
                            (eql (car fn-name) 'lambda)
                            (listp (cdr fn-name)))))
        (let ((fn (gensym "fn-"))
              (args (gensym "args-"))
              (value (gensym "value-"))
              (default-value (gensym "ert-form-evaluation-aborted-")))
          `(let* ((,fn (function ,fn-name))
                  (,args (condition-case err
                             (let ((signal-hook-function #'ert--should-signal-hook))
                               (list ,@arg-forms))
                           (error (progn (setq ,fn #'signal)
                                         (list (car err)
                                               (cdr err)))))))
             (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 signaling 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."
  (ert--expand-should-1
   whole form
   (lambda (inner-form form-description-form value-var)
     (let ((form-description (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))))))

(cl-defmacro should (form)
  "Evaluate FORM.  If it returns nil, abort the current test as failed.

Returns the value of FORM."
  (declare (debug t))
  (ert--expand-should `(should ,form) form
                      (lambda (inner-form form-description-form _value-var)
                        `(unless ,inner-form
                           (ert-fail ,form-description-form)))))

(cl-defmacro should-not (form)
  "Evaluate FORM.  If it returns non-nil, abort the current test as failed.

Returns nil."
  (declare (debug t))
  (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 ((signaled-conditions (get (car condition) 'error-conditions))
        (handled-conditions (pcase-exhaustive type
                              ((pred listp) type)
                              ((pred symbolp) (list type)))))
    (cl-assert signaled-conditions)
    (unless (cl-intersection signaled-conditions handled-conditions)
      (ert-fail (append
                 (funcall form-description-fn)
                 (list
                  :condition condition
                  :fail-reason (concat "the error signaled 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 signaled was a subtype"
                                         " of the expected type"))))))))

;; FIXME: The expansion will evaluate the keyword args (if any) in
;; nonstandard order.
(cl-defmacro should-error (form &rest keys &key type exclude-subtypes)
  "Evaluate FORM and check that it signals an error.

The error signaled 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 signaled, abort the test as
failed."
  (declare (debug t))
  (unless type (setq type ''error))
  (ert--expand-should
   `(should-error ,form ,@keys)
   form
   (lambda (inner-form form-description-form value-var)
     (let ((errorp (gensym "errorp"))
           (form-description-fn (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")))))))))

(cl-defmacro ert--skip-unless (form)
  "Evaluate FORM.  If it returns nil, skip the current test.
Errors during evaluation are caught and handled like nil."
  (declare (debug t))
  (ert--expand-should `(skip-unless ,form) form
                      (lambda (inner-form form-description-form _value-var)
                        `(unless (ignore-errors ,inner-form)
                           (ert-skip ,form-description-form)))))


;;; 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--explain-format-atom (x)
  "Format the atom X for `ert--explain-equal'."
  (pcase x
    ((pred characterp) (list x (format "#x%x" x) (format "?%c" x)))
    ((pred integerp) (list x (format "#x%x" x)))
    (_ x)))

(defun ert--explain-equal-rec (a b)
  "Return a programmer-readable explanation of why A and B are not `equal'.
Returns nil if they are."
  (if (not (eq (type-of a) (type-of b)))
      `(different-types ,a ,b)
    (pcase a
      ((pred consp)
       (let ((a-length (proper-list-p a))
             (b-length (proper-list-p b)))
         (if (not (eq (not a-length) (not b-length)))
             `(one-list-proper-one-improper ,a ,b)
           (if a-length
               (if (/= a-length b-length)
                   `(proper-lists-of-different-length ,a-length ,b-length
                                                      ,a ,b
                                                      first-mismatch-at
                                                      ,(cl-mismatch a b :test 'equal))
                 (cl-loop for i from 0
                          for ai in a
                          for bi in b
                          for xi = (ert--explain-equal-rec ai bi)
                          do (when xi (cl-return `(list-elt ,i ,xi)))
                          finally (cl-assert (equal a b) t)))
             (let ((car-x (ert--explain-equal-rec (car a) (car b))))
               (if car-x
                   `(car ,car-x)
                 (let ((cdr-x (ert--explain-equal-rec (cdr a) (cdr b))))
                   (if cdr-x
                       `(cdr ,cdr-x)
                     (cl-assert (equal a b) t)
                     nil))))))))
      ((pred cl-struct-p)
       (cl-loop for slot in (cl-struct-slot-info (type-of a))
                for ai across a
                for bi across b
                for xf = (ert--explain-equal-rec ai bi)
                do (when xf (cl-return `(struct-field ,(car slot) ,xf)))
                finally (cl-assert (equal a b) t)))
      ((or (pred arrayp) (pred recordp))
       ;; For mixed unibyte/multibyte string comparisons, make both multibyte.
       (when (and (stringp a)
                  (xor (multibyte-string-p a) (multibyte-string-p b)))
         (setq a (string-to-multibyte a))
         (setq b (string-to-multibyte b)))
       (if (/= (length a) (length b))
           `(arrays-of-different-length ,(length a) ,(length b)
                                        ,a ,b
                                        ,@(unless (char-table-p a)
                                            `(first-mismatch-at
                                              ,(cl-mismatch a b :test 'equal))))
         (cl-loop for i from 0
                  for ai across a
                  for bi across b
                  for xi = (ert--explain-equal-rec ai bi)
                  do (when xi (cl-return `(array-elt ,i ,xi)))
                  finally (cl-assert (equal a b) t))))
      (_
       (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)))))

(defun ert--explain-equal (a b)
  "Explainer function for `equal'."
  ;; Do a quick comparison in C to avoid running our expensive
  ;; comparison when possible.
  (if (equal a b)
      nil
    (ert--explain-equal-rec a b)))
(put 'equal 'ert-explainer 'ert--explain-equal)

(defun ert--significant-plist-keys (plist)
  "Return the keys of PLIST that have non-null values, in order."
  (cl-assert (zerop (mod (length plist) 2)) t)
  (cl-loop for (key value . rest) on plist by #'cddr
           unless (or (null value) (memq key accu)) collect key into accu
           finally (cl-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."
  (cl-assert (zerop (mod (length a) 2)) t)
  (cl-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 (cl-set-difference keys-a keys-b :test 'eq))
         (keys-in-b-not-in-a (cl-set-difference keys-b keys-a :test 'eq)))
    (cl-flet ((explain-with-key (key)
                (let ((value-a (plist-get a key))
                      (value-b (plist-get b key)))
                  (cl-assert (not (equal value-a value-b)) t)
                  `(different-properties-for-key
                    ,key ,(ert--explain-equal-including-properties value-a
                                                                   value-b)))))
      (cond (keys-in-a-not-in-b
             (explain-with-key (car keys-in-a-not-in-b)))
            (keys-in-b-not-in-a
             (explain-with-key (car keys-in-b-not-in-a)))
            (t
             (cl-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)))))

;; TODO(ohler): Once bug 6581 is fixed, rename this to
;; `ert--explain-equal-including-properties-rec' and add a fast-path
;; wrapper like `ert--explain-equal'.
(defun ert--explain-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-equal a b)
    (cl-assert (stringp a) t)
    (cl-assert (stringp b) t)
    (cl-assert (eql (length a) (length b)) t)
    (cl-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
                  (cl-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 (cl-assert (equal-including-properties a b) t)
             )))
(put 'ert-equal-including-properties
     'ert-explainer
     'ert--explain-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.")

(cl-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.
(cl-defstruct ert-test-result
  (messages nil)
  (should-forms nil)
  (duration 0)
  )
(cl-defstruct (ert-test-passed (:include ert-test-result)))
(cl-defstruct (ert-test-result-with-condition (:include ert-test-result))
  (condition (cl-assert nil))
  (backtrace (cl-assert nil))
  (infos (cl-assert nil)))
(cl-defstruct (ert-test-quit (:include ert-test-result-with-condition)))
(cl-defstruct (ert-test-failed (:include ert-test-result-with-condition)))
(cl-defstruct (ert-test-skipped (:include ert-test-result-with-condition)))
(cl-defstruct (ert-test-aborted-with-non-local-exit
               (:include ert-test-result)))

;; A container for the state of the execution of a single test and
;; environment data needed during its execution.
(cl-defstruct ert--test-execution-info
  (test (cl-assert nil))
  (result (cl-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 (cl-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 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.  ARGS are the arguments to `debugger'."
  (cl-destructuring-bind (first-debugger-arg &rest more-debugger-args)
      args
    (cl-ecase first-debugger-arg
      ((lambda debug t exit nil)
       (apply (ert--test-execution-info-next-debugger info) args))
      (error
       (let* ((condition (car more-debugger-args))
              (type (cl-case (car condition)
                      ((quit) 'quit)
		      ((ert-test-skipped) 'skipped)
                      (otherwise 'failed)))
              ;; We store the backtrace in the result object for
              ;; `ert-results-pop-to-backtrace-for-test-at-point'.
              ;; This means we have to limit `print-level' and
              ;; `print-length' when printing result objects.  That
              ;; might not be worth while when we can also use
              ;; `ert-results-rerun-test-at-point-debugging-errors',
              ;; (i.e., when running interactively) but having the
              ;; backtrace ready for printing is important for batch
              ;; use.
              ;;
              ;; Grab the frames above the debugger.
              (backtrace (cdr (backtrace-get-frames debugger)))
              (infos (reverse ert--infos)))
         (setf (ert--test-execution-info-result info)
               (cl-ecase type
                 (quit
                  (make-ert-test-quit :condition condition
                                      :backtrace backtrace
                                      :infos infos))
                 (skipped
                  (make-ert-test-skipped :condition condition
                                        :backtrace backtrace
                                        :infos infos))
                 (failed
                  (make-ert-test-failed :condition condition
                                        :backtrace backtrace
                                        :infos infos))))
         ;; Work around Emacs's heuristic (in eval.c) for detecting
         ;; errors in the debugger.
         (cl-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) args))
          (t))
         (funcall (ert--test-execution-info-exit-continuation info)))))))

(defun ert--run-test-internal (test-execution-info)
  "Low-level function to run a test according to TEST-EXECUTION-INFO.

This mainly sets up debugger-related bindings."
  (setf (ert--test-execution-info-next-debugger test-execution-info) debugger
        (ert--test-execution-info-ert-debug-on-error test-execution-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
        ;; FIXME: Use `signal-hook-function' instead of `debugger' to
        ;; handle ert errors. Once that's done, remove
        ;; `ert--should-signal-hook'.  See Bug#24402 and Bug#11218 for
        ;; details.
        (let ((debugger (lambda (&rest args)
                          (ert--run-test-debugger test-execution-info
                                                  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
                                   test-execution-info))))))
    (ert-pass))
  (setf (ert--test-execution-info-result test-execution-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 (messages-buffer)
    ;; This is a reimplementation of this part of message_dolog() in xdisp.c:
    ;; if (FIXNATP (Vmessage_log_max))
    ;;   {
    ;;     scan_newline (Z, Z_BYTE, BEG, BEG_BYTE,
    ;;                   -XFIXNAT (Vmessage_log_max) - 1, false);
    ;;     del_range_both (BEG, BEG_BYTE, PT, PT_BYTE, false);
    ;;   }
    (when (natnump message-log-max)
      (let ((begin (point-min))
            (end (save-excursion
                   (goto-char (point-max))
                   (forward-line (- message-log-max))
                   (point)))
            (inhibit-read-only t))
        (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)
  (cl-block error
    (let ((begin-marker
           (with-current-buffer (messages-buffer)
             (point-max-marker))))
      (unwind-protect
          (let ((info (make-ert--test-execution-info
                       :test ert-test
                       :result
                       (make-ert-test-aborted-with-non-local-exit)
                       :exit-continuation (lambda ()
                                            (cl-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 (messages-buffer)
                        (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, :skipped -- 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.
  (pcase-exhaustive result-type
    ('nil nil)
    ('t t)
    (:failed (ert-test-failed-p result))
    (:passed (ert-test-passed-p result))
    (:skipped (ert-test-skipped-p result))
    (`(,operator . ,operands)
     (cl-ecase operator
       (and
        (cl-case (length operands)
          (0 t)
          (t
           (and (ert-test-result-type-p result (car operands))
                (ert-test-result-type-p result `(and ,@(cdr operands)))))))
       (or
        (cl-case (length operands)
          (0 nil)
          (t
           (or (ert-test-result-type-p result (car operands))
               (ert-test-result-type-p result `(or ,@(cdr operands)))))))
       (not
        (cl-assert (eql (length operands) 1))
        (not (ert-test-result-type-p result (car operands))))
       (satisfies
        (cl-assert (eql (length operands) 1))
        (funcall (car operands) result))))))

(defun ert-test-result-expected-p (test result)
  "Return non-nil if TEST's expected result type matches RESULT."
  (or
   (ert-test-result-type-p result :skipped)
   (ert-test-result-type-p result (ert-test-expected-result-type test))))

(defun ert-select-tests (selector universe)
  "Return a list of tests that match SELECTOR.

UNIVERSE specifies the set of tests to select from; it should be a list
of tests, or t, which refers to all tests named by symbols in `obarray'.

Valid SELECTORs:

nil  -- Selects the empty set.
t    -- Selects UNIVERSE.
:new -- Selects all tests that have not been run yet.
:failed, :passed       -- Select tests according to their most recent result.
:expected, :unexpected -- Select tests according to their most recent result.
a string -- A regular expression selecting all tests with matching names.
a test   -- (i.e., an object of the ert-test data-type) Selects that test.
a symbol -- Selects the test that the symbol names, errors if none.
\(member TESTS...) -- Selects the elements of TESTS, a list of tests
    or symbols naming tests.
\(eql TEST) -- Selects TEST, a test or a symbol naming a test.
\(and SELECTORS...) -- Selects the tests that match all SELECTORS.
\(or SELECTORS...)  -- Selects the tests that match any of the SELECTORS.
\(not SELECTOR)     -- Selects all tests that do not match SELECTOR.
\(tag TAG) -- Selects all tests that have TAG on their tags list.
    A tag is an arbitrary label you can apply when you define a test.
\(satisfies PREDICATE) -- Selects all tests that satisfy PREDICATE.
    PREDICATE is a function that takes an ert-test object as argument,
    and returns non-nil if it is selected.

Only selectors that require a superset of tests, such
as (satisfies ...), strings, :new, etc. make use of UNIVERSE.
Selectors that do not, such as (member ...), just return the
set implied by them without checking whether it is really
contained in UNIVERSE."
  ;; This code needs to match the cases in
  ;; `ert--insert-human-readable-selector'.
  (pcase-exhaustive selector
    ('nil nil)
    ('t (pcase-exhaustive universe
          ((pred listp) universe)
          (`t (ert-select-tests "" universe))))
    (:new (ert-select-tests
           `(satisfies ,(lambda (test)
                          (null (ert-test-most-recent-result test))))
           universe))
    (:failed (ert-select-tests
              `(satisfies ,(lambda (test)
                             (ert-test-result-type-p
                              (ert-test-most-recent-result test)
                              ':failed)))
              universe))
    (:passed (ert-select-tests
              `(satisfies ,(lambda (test)
                             (ert-test-result-type-p
                              (ert-test-most-recent-result test)
                              ':passed)))
              universe))
    (:expected (ert-select-tests
                `(satisfies
                  ,(lambda (test)
                     (ert-test-result-expected-p
                      test
                      (ert-test-most-recent-result test))))
                universe))
    (:unexpected (ert-select-tests '(not :expected) universe))
    ((pred stringp)
     (pcase-exhaustive universe
       (`t (mapcar #'ert-get-test
                   (apropos-internal selector #'ert-test-boundp)))
       ((pred listp)
        (cl-remove-if-not (lambda (test)
                            (and (ert-test-name test)
                                 (string-match selector
                                               (symbol-name
                                                (ert-test-name test)))))
                          universe))))
    ((pred ert-test-p) (list selector))
    ((pred symbolp)
     (cl-assert (ert-test-boundp selector))
     (list (ert-get-test selector)))
    (`(,operator . ,operands)
     (cl-ecase operator
       (member
        (mapcar (lambda (purported-test)
                  (pcase-exhaustive purported-test
                    ((pred symbolp)
                     (cl-assert (ert-test-boundp purported-test))
                     (ert-get-test purported-test))
                    ((pred ert-test-p) purported-test)))
                operands))
       (eql
        (cl-assert (eql (length operands) 1))
        (ert-select-tests `(member ,@operands) universe))
       (and
        ;; Do these definitions of AND, NOT and OR satisfy de
        ;; Morgan's laws?  Should they?
        (cl-case (length operands)
          (0 (ert-select-tests 't universe))
          (t (ert-select-tests `(and ,@(cdr operands))
                               (ert-select-tests (car operands)
                                                 universe)))))
       (not
        (cl-assert (eql (length operands) 1))
        (let ((all-tests (ert-select-tests 't universe)))
          (cl-set-difference all-tests
                             (ert-select-tests (car operands)
                                               all-tests))))
       (or
        (cl-case (length operands)
          (0 (ert-select-tests 'nil universe))
          (t (cl-union (ert-select-tests (car operands) universe)
                       (ert-select-tests `(or ,@(cdr operands))
                                         universe)))))
       (tag
        (cl-assert (eql (length operands) 1))
        (let ((tag (car operands)))
          (ert-select-tests `(satisfies
                              ,(lambda (test)
                                 (member tag (ert-test-tags test))))
                            universe)))
       (satisfies
        (cl-assert (eql (length operands) 1))
        (cl-remove-if-not (car operands)
                          (ert-select-tests 't universe)))))))

(defun ert--insert-human-readable-selector (selector)
  "Insert a human-readable presentation of SELECTOR into the current buffer."
  ;; This is needed to avoid printing the (huge) contents of the
  ;; `backtrace' slot of the result objects in the
  ;; `most-recent-result' slots of test case objects in (eql ...) or
  ;; (member ...) selectors.
  (cl-labels ((rec (selector)
                ;; This code needs to match the cases in
                ;; `ert-select-tests'.
                (pcase-exhaustive selector
                  ((or
                    ;; 'nil 't :new :failed :passed :expected :unexpected
                    (pred stringp)
                    (pred symbolp))
                   selector)
                  ((pred ert-test-p)
                   (if (ert-test-name selector)
                       (make-symbol (format "<%S>" (ert-test-name selector)))
                     (make-symbol "<unnamed test>")))
                  (`(,operator . ,operands)
                   (pcase operator
                     ((or 'member 'eql 'and 'not 'or)
                      `(,operator ,@(mapcar #'rec operands)))
                     ((or 'tag 'satisfies)
                      selector))))))
    (insert (format "%S" (rec selector)))))


;;; Facilities for running a whole set of tests.

;; The data structure that contains the set of tests being executed
;; during one particular test run, their results, the state of the
;; execution, and some statistics.
;;
;; The data about results and expected results of tests may seem
;; redundant here, since the test objects also carry such information.
;; However, the information in the test objects may be more recent, it
;; may correspond to a different test run.  We need the information
;; that corresponds to this run in order to be able to update the
;; statistics correctly when a test is re-run interactively and has a
;; different result than before.
(cl-defstruct ert--stats
  (selector (cl-assert nil))
  ;; The tests, in order.
  (tests (cl-assert nil) :type vector)
  ;; A map of test names (or the test objects themselves for unnamed
  ;; tests) to indices into the `tests' vector.
  (test-map (cl-assert nil) :type hash-table)
  ;; The results of the tests during this run, in order.
  (test-results (cl-assert nil) :type vector)
  ;; The start times of the tests, in order, as reported by
  ;; `current-time'.
  (test-start-times (cl-assert nil) :type vector)
  ;; The end times of the tests, in order, as reported by
  ;; `current-time'.
  (test-end-times (cl-assert nil) :type vector)
  (passed-expected 0)
  (passed-unexpected 0)
  (failed-expected 0)
  (failed-unexpected 0)
  (skipped 0)
  (start-time nil)
  (end-time nil)
  (aborted-p nil)
  (current-test nil)
  ;; The time at or after which the next redisplay should occur, as a
  ;; float.
  (next-redisplay 0.0))

(defun ert-stats-completed-expected (stats)
  "Return the number of tests in STATS that had expected results."
  (+ (ert--stats-passed-expected stats)
     (ert--stats-failed-expected stats)))

(defun ert-stats-completed-unexpected (stats)
  "Return the number of tests in STATS that had unexpected results."
  (+ (ert--stats-passed-unexpected stats)
     (ert--stats-failed-unexpected stats)))

(defun ert-stats-skipped (stats)
  "Number of tests in STATS that have skipped."
  (ert--stats-skipped stats))

(defun ert-stats-completed (stats)
  "Number of tests in STATS that have run so far."
  (+ (ert-stats-completed-expected stats)
     (ert-stats-completed-unexpected stats)
     (ert-stats-skipped stats)))

(defun ert-stats-total (stats)
  "Number of tests in STATS, regardless of whether they have run yet."
  (length (ert--stats-tests stats)))

;; The stats object of the current run, dynamically bound.  This is
;; used for the mode line progress indicator.
(defvar ert--current-run-stats nil)

(defun ert--stats-test-key (test)
  "Return the key used for TEST in the test map of ert--stats objects.

Returns the name of TEST if it has one, or TEST itself otherwise."
  (or (ert-test-name test) test))

(defun ert--stats-set-test-and-result (stats pos test result)
  "Change STATS by replacing the test at position POS with TEST and RESULT.

Also changes the counters in STATS to match."
  (let* ((tests (ert--stats-tests stats))
         (results (ert--stats-test-results stats))
         (old-test (aref tests pos))
         (map (ert--stats-test-map stats)))
    (cl-flet ((update (d)
                (if (ert-test-result-expected-p (aref tests pos)
                                                (aref results pos))
                    (cl-etypecase (aref results pos)
                      (ert-test-passed
                       (cl-incf (ert--stats-passed-expected stats) d))
                      (ert-test-failed
                       (cl-incf (ert--stats-failed-expected stats) d))
		      (ert-test-skipped
                       (cl-incf (ert--stats-skipped stats) d))
                      (null)
                      (ert-test-aborted-with-non-local-exit)
                      (ert-test-quit))
                  (cl-etypecase (aref results pos)
                    (ert-test-passed
                     (cl-incf (ert--stats-passed-unexpected stats) d))
                    (ert-test-failed
                     (cl-incf (ert--stats-failed-unexpected stats) d))
                    (ert-test-skipped
                     (cl-incf (ert--stats-skipped stats) d))
                    (null)
                    (ert-test-aborted-with-non-local-exit)
                    (ert-test-quit)))))
      ;; Adjust counters to remove the result that is currently in stats.
      (update -1)
      ;; Put new test and result into stats.
      (setf (aref tests pos) test
            (aref results pos) result)
      (remhash (ert--stats-test-key old-test) map)
      (setf (gethash (ert--stats-test-key test) map) pos)
      ;; Adjust counters to match new result.
      (update +1)
      nil)))

(defun ert--make-stats (tests selector)
  "Create a new `ert--stats' object for running TESTS.

SELECTOR is the selector that was used to select TESTS."
  (setq tests (cl-coerce tests 'vector))
  (let ((map (make-hash-table :size (length tests))))
    (cl-loop for i from 0
             for test across tests
             for key = (ert--stats-test-key test) do
             (cl-assert (not (gethash key map)))
             (setf (gethash key map) i))
    (make-ert--stats :selector selector
                     :tests tests
                     :test-map map
                     :test-results (make-vector (length tests) nil)
                     :test-start-times (make-vector (length tests) nil)
                     :test-end-times (make-vector (length tests) nil))))

(defun ert-run-or-rerun-test (stats test listener)
  ;; checkdoc-order: nil
  "Run the single test TEST and record the result using STATS and LISTENER."
  (let ((ert--current-run-stats stats)
        (pos (ert--stats-test-pos stats test)))
    (ert--stats-set-test-and-result stats pos test nil)
    ;; Call listener after setting/before resetting
    ;; (ert--stats-current-test stats); the listener might refresh the
    ;; mode line display, and if the value is not set yet/any more
    ;; during this refresh, the mode line will flicker unnecessarily.
    (setf (ert--stats-current-test stats) test)
    (funcall listener 'test-started stats test)
    (setf (ert-test-most-recent-result test) nil)
    (setf (aref (ert--stats-test-start-times stats) pos) (current-time))
    (unwind-protect
        (ert-run-test test)
      (setf (aref (ert--stats-test-end-times stats) pos) (current-time))
      (let ((result (ert-test-most-recent-result test)))
        (setf (ert-test-result-duration result)
              (float-time
               (time-subtract
                (aref (ert--stats-test-end-times stats) pos)
                (aref (ert--stats-test-start-times stats) pos))))
        (ert--stats-set-test-and-result stats pos test result)
        (funcall listener 'test-ended stats test result))
      (setf (ert--stats-current-test stats) nil))))

(defun ert-run-tests (selector listener &optional interactively)
  "Run the tests specified by SELECTOR, sending progress updates to LISTENER."
  (let* ((tests (ert-select-tests selector t))
         (stats (ert--make-stats tests selector)))
    (setf (ert--stats-start-time stats) (current-time))
    (funcall listener 'run-started stats)
    (let ((abortedp t))
      (unwind-protect
          (let ((ert--current-run-stats stats))
            (force-mode-line-update)
            (unwind-protect
		(cl-loop for test in tests do
			 (ert-run-or-rerun-test stats test listener)
			 (when (and interactively
				    (ert-test-quit-p
				     (ert-test-most-recent-result test))
				    (y-or-n-p "Abort testing? "))
			   (cl-return))
			 finally (setq abortedp nil))
              (setf (ert--stats-aborted-p stats) abortedp)
              (setf (ert--stats-end-time stats) (current-time))
              (funcall listener 'run-ended stats abortedp)))
        (force-mode-line-update))
      stats)))

(defun ert--stats-test-pos (stats test)
  ;; checkdoc-order: nil
  "Return the position (index) of TEST in the run represented by STATS."
  (gethash (ert--stats-test-key test) (ert--stats-test-map stats)))


;;; Formatting functions shared across UIs.

(defun ert--format-time-iso8601 (time)
  "Format TIME in the variant of ISO 8601 used for timestamps in ERT."
  (format-time-string "%Y-%m-%d %T%z" time))

(defun ert-char-for-test-result (result expectedp)
  "Return a character that represents the test result RESULT.

EXPECTEDP specifies whether the result was expected."
  (let ((s (cl-etypecase result
             (ert-test-passed ".P")
             (ert-test-failed "fF")
             (ert-test-skipped "sS")
             (null "--")
             (ert-test-aborted-with-non-local-exit "aA")
             (ert-test-quit "qQ"))))
    (elt s (if expectedp 0 1))))

(defun ert-string-for-test-result (result expectedp)
  "Return a string that represents the test result RESULT.

EXPECTEDP specifies whether the result was expected."
  (let ((s (cl-etypecase result
             (ert-test-passed '("passed" "PASSED"))
             (ert-test-failed '("failed" "FAILED"))
             (ert-test-skipped '("skipped" "SKIPPED"))
             (null '("unknown" "UNKNOWN"))
             (ert-test-aborted-with-non-local-exit '("aborted" "ABORTED"))
             (ert-test-quit '("quit" "QUIT")))))
    (elt s (if expectedp 0 1))))

(defun ert--pp-with-indentation-and-newline (object)
  "Pretty-print OBJECT, indenting it to the current column of point.
Ensures a final newline is inserted."
  (let ((begin (point))
        (pp-escape-newlines nil)
        (print-escape-control-characters t))
    (pp object (current-buffer))
    (unless (bolp) (insert "\n"))
    (save-excursion
      (goto-char begin)
      (indent-sexp))))

(defun ert--insert-infos (result)
  "Insert `ert-info' infos from RESULT into current buffer.

RESULT must be an `ert-test-result-with-condition'."
  (cl-check-type result ert-test-result-with-condition)
  (dolist (info (ert-test-result-with-condition-infos result))
    (cl-destructuring-bind (prefix . message) info
      (let ((begin (point))
            (indentation (make-string (+ (length prefix) 4) ?\s))
            (end nil))
        (unwind-protect
            (progn
              (insert message "\n")
              (setq end (point-marker))
              (goto-char begin)
              (insert "    " prefix)
              (forward-line 1)
              (while (< (point) end)
                (insert indentation)
                (forward-line 1)))
          (when end (set-marker end nil)))))))


;;; Running tests in batch mode.

(defvar ert-quiet nil
  "Non-nil makes ERT only print important information in batch mode.")

;;;###autoload
(defun ert-run-tests-batch (&optional selector)
  "Run the tests specified by SELECTOR, printing results to the terminal.

SELECTOR works as described in `ert-select-tests', except if
SELECTOR is nil, in which case all tests rather than none will be
run; this makes the command line \"emacs -batch -l my-tests.el -f
ert-run-tests-batch-and-exit\" useful.

Returns the stats object."
  (unless selector (setq selector 't))
  (ert-run-tests
   selector
   (lambda (event-type &rest event-args)
     (cl-ecase event-type
       (run-started
        (unless ert-quiet
          (cl-destructuring-bind (stats) event-args
            (message "Running %s tests (%s, selector `%S')"
                     (length (ert--stats-tests stats))
                     (ert--format-time-iso8601 (ert--stats-start-time stats))
                     selector))))
       (run-ended
        (cl-destructuring-bind (stats abortedp) event-args
          (let ((unexpected (ert-stats-completed-unexpected stats))
                (skipped (ert-stats-skipped stats))
		(expected-failures (ert--stats-failed-expected stats)))
            (message "\n%sRan %s tests, %s results as expected, %s unexpected%s (%s, %f sec)%s\n"
                     (if (not abortedp)
                         ""
                       "Aborted: ")
                     (ert-stats-total stats)
                     (ert-stats-completed-expected stats)
                     unexpected
                     (if (zerop skipped)
                         ""
                       (format ", %s skipped" skipped))
                     (ert--format-time-iso8601 (ert--stats-end-time stats))
                     (float-time
                      (time-subtract
                       (ert--stats-end-time stats)
                       (ert--stats-start-time stats)))
                     (if (zerop expected-failures)
                         ""
                       (format "\n%s expected failures" expected-failures)))
            (unless (zerop unexpected)
              (message "%s unexpected results:" unexpected)
              (cl-loop for test across (ert--stats-tests stats)
                       for result = (ert-test-most-recent-result test) do
                       (when (not (ert-test-result-expected-p test result))
                         (message "%9s  %S"
                                  (ert-string-for-test-result result nil)
                                  (ert-test-name test))))
              (message "%s" ""))
            (unless (zerop skipped)
              (message "%s skipped results:" skipped)
              (cl-loop for test across (ert--stats-tests stats)
                       for result = (ert-test-most-recent-result test) do
                       (when (ert-test-result-type-p result :skipped)
                         (message "%9s  %S"
                                  (ert-string-for-test-result result nil)
                                  (ert-test-name test))))
              (message "%s" "")))))
       (test-started
        )
       (test-ended
        (cl-destructuring-bind (stats test result) event-args
          (unless (ert-test-result-expected-p test result)
            (cl-etypecase result
              (ert-test-passed
               (message "Test %S passed unexpectedly" (ert-test-name test)))
              (ert-test-result-with-condition
               (message "Test %S backtrace:" (ert-test-name test))
               (with-temp-buffer
                 (insert (backtrace-to-string
                          (ert-test-result-with-condition-backtrace result)))
                 (if (not ert-batch-backtrace-right-margin)
                     (message "%s"
                              (buffer-substring-no-properties (point-min)
                                                              (point-max)))
                   (goto-char (point-min))
                   (while (not (eobp))
                     (let ((start (point))
                           (end (line-end-position)))
                       (setq end (min end
                                      (+ start
                                         ert-batch-backtrace-right-margin)))
                       (message "%s" (buffer-substring-no-properties
                                      start end)))
                     (forward-line 1))))
               (with-temp-buffer
                 (ert--insert-infos result)
                 (insert "    ")
                 (let ((print-escape-newlines t)
                       (print-level 5)
                       (print-length 10))
                   (ert--pp-with-indentation-and-newline
                    (ert-test-result-with-condition-condition result)))
                 (goto-char (1- (point-max)))
                 (cl-assert (looking-at "\n"))
                 (delete-char 1)
                 (message "Test %S condition:" (ert-test-name test))
                 (message "%s" (buffer-string))))
              (ert-test-aborted-with-non-local-exit
               (message "Test %S aborted with non-local exit"
                        (ert-test-name test)))
              (ert-test-quit
               (message "Quit during %S" (ert-test-name test)))))
          (unless ert-quiet
            (let* ((max (prin1-to-string (length (ert--stats-tests stats))))
                   (format-string (concat "%9s  %"
                                          (prin1-to-string (length max))
                                          "s/" max "  %S (%f sec)")))
              (message format-string
                       (ert-string-for-test-result result
                                                   (ert-test-result-expected-p
                                                    test result))
                       (1+ (ert--stats-test-pos stats test))
                       (ert-test-name test)
                       (ert-test-result-duration result))))))))
   nil))

;;;###autoload
(defun ert-run-tests-batch-and-exit (&optional selector)
  "Like `ert-run-tests-batch', but exits Emacs when done.

The exit status will be 0 if all test results were as expected, 1
on unexpected results, or 2 if the tool detected an error outside
of the tests (e.g. invalid SELECTOR or bug in the code that runs
the tests)."
  (or noninteractive
      (user-error "This function is only for use in batch mode"))
  ;; Better crash loudly than attempting to recover from undefined
  ;; behavior.
  (setq attempt-stack-overflow-recovery nil
        attempt-orderly-shutdown-on-fatal-signal nil)
  (unwind-protect
      (let ((stats (ert-run-tests-batch selector)))
        (kill-emacs (if (zerop (ert-stats-completed-unexpected stats)) 0 1)))
    (unwind-protect
        (progn
          (message "Error running tests")
          (backtrace))
      (kill-emacs 2))))


(defun ert-summarize-tests-batch-and-exit (&optional high)
  "Summarize the results of testing.
Expects to be called in batch mode, with logfiles as command-line arguments.
The logfiles should have the `ert-run-tests-batch' format.  When finished,
this exits Emacs, with status as per `ert-run-tests-batch-and-exit'.

If HIGH is a natural number, the HIGH long lasting tests are summarized."
  (or noninteractive
      (user-error "This function is only for use in batch mode"))
  (or (natnump high) (setq high 0))
  ;; Better crash loudly than attempting to recover from undefined
  ;; behavior.
  (setq attempt-stack-overflow-recovery nil
        attempt-orderly-shutdown-on-fatal-signal nil)
  (let ((nlogs (length command-line-args-left))
        (ntests 0) (nrun 0) (nexpected 0) (nunexpected 0) (nskipped 0)
        nnotrun logfile notests badtests unexpected skipped tests)
    (with-temp-buffer
      (while (setq logfile (pop command-line-args-left))
        (erase-buffer)
        (when (file-readable-p logfile) (insert-file-contents logfile))
        (if (not (re-search-forward "^Running \\([0-9]+\\) tests" nil t))
            (push logfile notests)
          (setq ntests (+ ntests (string-to-number (match-string 1))))
          (if (not (re-search-forward "^\\(Aborted: \\)?\
Ran \\([0-9]+\\) tests, \\([0-9]+\\) results as expected\
\\(?:, \\([0-9]+\\) unexpected\\)?\
\\(?:, \\([0-9]+\\) skipped\\)?" nil t))
              (push logfile badtests)
            (if (match-string 1) (push logfile badtests))
            (setq nrun (+ nrun (string-to-number (match-string 2)))
                  nexpected (+ nexpected (string-to-number (match-string 3))))
            (when (match-string 4)
	      (let ((n (string-to-number (match-string 4))))
		(unless (zerop n)
		  (push logfile unexpected)
		  (setq nunexpected (+ nunexpected n)))))
            (when (match-string 5)
              (push logfile skipped)
              (setq nskipped (+ nskipped
                                (string-to-number (match-string 5)))))
            (unless (zerop high)
              (goto-char (point-min))
              (while (< (point) (point-max))
                (if (looking-at "^\\s-+\\w+\\s-+[[:digit:]]+/[[:digit:]]+\\s-+\\S-+\\s-+(\\([.[:digit:]]+\\)\\s-+sec)$")
                    (push (cons (string-to-number (match-string 1))
                                (match-string 0))
                          tests))
                (forward-line)))))))
    (setq nnotrun (- ntests nrun))
    (message "\nSUMMARY OF TEST RESULTS")
    (message "-----------------------")
    (message "Files examined: %d" nlogs)
    (message "Ran %d tests%s, %d results as expected, %d unexpected, %d skipped"
             nrun
             (if (zerop nnotrun) "" (format ", %d failed to run" nnotrun))
             nexpected nunexpected nskipped)
    (when notests
      (message "%d files did not contain any tests:" (length notests))
      (mapc (lambda (l) (message "  %s" l)) notests))
    (when badtests
      (message "%d files did not finish:" (length badtests))
      (mapc (lambda (l) (message "  %s" l)) badtests)
      (if (getenv "EMACS_HYDRA_CI")
          (with-temp-buffer
            (dolist (f badtests)
              (erase-buffer)
              (insert-file-contents f)
              (message "Contents of unfinished file %s:" f)
              (message "-----\n%s\n-----" (buffer-string))))))
    (when unexpected
      (message "%d files contained unexpected results:" (length unexpected))
      (mapc (lambda (l) (message "  %s" l)) unexpected))
    (unless (or (null tests) (zerop high))
      (message "\nLONG-RUNNING TESTS")
      (message "------------------")
      (setq tests (sort tests (lambda (x y) (> (car x) (car y)))))
      (when (< high (length tests)) (setcdr (nthcdr (1- high) tests) nil))
      (message "%s" (mapconcat 'cdr tests "\n")))
    ;; More details on hydra, where the logs are harder to get to.
    (when (and (getenv "EMACS_HYDRA_CI")
               (not (zerop (+ nunexpected nskipped))))
      (message "\nDETAILS")
      (message "-------")
      (with-temp-buffer
        (dolist (x (list (list skipped "skipped" "SKIPPED")
                         (list unexpected "unexpected"
                               "\\(?:FAILED\\|PASSED\\)")))
          (mapc (lambda (l)
                  (erase-buffer)
                  (insert-file-contents l)
                  (message "%s:" l)
                  (when (re-search-forward (format "^[ \t]*[0-9]+ %s results:"
                                                   (nth 1 x))
                                           nil t)
                    (while (and (zerop (forward-line 1))
                                (looking-at (format "^[ \t]*%s" (nth 2 x))))
                      (message "%s" (buffer-substring (line-beginning-position)
                                                      (line-end-position))))))
                (car x)))))
    (kill-emacs (cond ((or notests badtests (not (zerop nnotrun))) 2)
                      (unexpected 1)
                      (t 0)))))

;;; Utility functions for load/unload actions.

(defun ert--activate-font-lock-keywords ()
  "Activate font-lock keywords for some of ERT's symbols."
  (font-lock-add-keywords
   nil
   '(("(\\(\\<ert-deftest\\)\\>\\s *\\(\\(?:\\sw\\|\\s_\\)+\\)?"
      (1 font-lock-keyword-face nil t)
      (2 font-lock-function-name-face nil t)))))

(cl-defun ert--remove-from-list (list-var element &key key test)
  "Remove ELEMENT from the value of LIST-VAR if present.

This can be used as an inverse of `add-to-list'."
  (unless key (setq key #'identity))
  (unless test (setq test #'equal))
  (setf (symbol-value list-var)
        (cl-remove element
                   (symbol-value list-var)
                   :key key
                   :test test)))


;;; Some basic interactive functions.

(defun ert-read-test-name (prompt &optional default history
                                  add-default-to-prompt)
  "Read the name of a test and return it as a symbol.

Prompt with PROMPT.  If DEFAULT is a valid test name, use it as a
default.  HISTORY is the history to use; see `completing-read'.
If ADD-DEFAULT-TO-PROMPT is non-nil, PROMPT will be modified to
include the default, if any.

Signals an error if no test name was read."
  (cl-etypecase default
    (string (let ((symbol (intern-soft default)))
              (unless (and symbol (ert-test-boundp symbol))
                (setq default nil))))
    (symbol (setq default
                  (if (ert-test-boundp default)
                      (symbol-name default)
                    nil)))
    (ert-test (setq default (ert-test-name default))))
  (when add-default-to-prompt
    (setq prompt (format-prompt prompt default)))
  (let ((input (completing-read prompt obarray #'ert-test-boundp
                                t nil history default nil)))
    ;; completing-read returns an empty string if default was nil and
    ;; the user just hit enter.
    (let ((sym (intern-soft input)))
      (if (ert-test-boundp sym)
          sym
        (user-error "Input does not name a test")))))

(defun ert-read-test-name-at-point (prompt)
  "Read the name of a test and return it as a symbol.
As a default, use the symbol at point, or the test at point if in
the ERT results buffer.  Prompt with PROMPT, augmented with the
default (if any)."
  (ert-read-test-name prompt (ert-test-at-point) nil t))

(defun ert-find-test-other-window (test-name)
  "Find, in another window, the definition of TEST-NAME."
  (interactive (list (ert-read-test-name-at-point "Find test definition: ")))
  (find-function-do-it test-name 'ert--test 'switch-to-buffer-other-window))

(defun ert-delete-test (test-name)
  "Make the test TEST-NAME unbound.

Nothing more than an interactive interface to `ert-make-test-unbound'."
  (interactive (list (ert-read-test-name-at-point "Delete test")))
  (ert-make-test-unbound test-name))

(defun ert-delete-all-tests ()
  "Make all symbols in `obarray' name no test."
  (interactive)
  (when (called-interactively-p 'any)
    (unless (y-or-n-p "Delete all tests? ")
      (user-error "Aborted")))
  ;; We can't use `ert-select-tests' here since that gives us only
  ;; test objects, and going from them back to the test name symbols
  ;; can fail if the `ert-test' defstruct has been redefined.
  (mapc #'ert-make-test-unbound (apropos-internal "" #'ert-test-boundp))
  t)


;;; Display of test progress and results.

;; An entry in the results buffer ewoc.  There is one entry per test.
(cl-defstruct ert--ewoc-entry
  (test (cl-assert nil))
  ;; If the result of this test was expected, its ewoc entry is hidden
  ;; initially.
  (hidden-p (cl-assert nil))
  ;; An ewoc entry may be collapsed to hide details such as the error
  ;; condition.
  ;;
  ;; I'm not sure the ability to expand and collapse entries is still
  ;; a useful feature.
  (expanded-p t)
  ;; By default, the ewoc entry presents the error condition with
  ;; certain limits on how much to print (`print-level',
  ;; `print-length').  The user can interactively switch to a set of
  ;; higher limits.
  (extended-printer-limits-p nil))

;; Variables local to the results buffer.

;; The ewoc.
(defvar ert--results-ewoc)
;; The stats object.
(defvar ert--results-stats)
;; A string with one character per test.  Each character represents
;; the result of the corresponding test.  The string is displayed near
;; the top of the buffer and serves as a progress bar.
(defvar ert--results-progress-bar-string)
;; The position where the progress bar button begins.
(defvar ert--results-progress-bar-button-begin)
;; The test result listener that updates the buffer when tests are run.
(defvar ert--results-listener)

(defun ert-insert-test-name-button (test-name)
  "Insert a button that links to TEST-NAME."
  (insert-text-button (format "%S" test-name)
                      :type 'ert--test-name-button
                      'ert-test-name test-name))

(defun ert--results-format-expected-unexpected (expected unexpected)
  "Return a string indicating EXPECTED expected results, UNEXPECTED unexpected."
  (if (zerop unexpected)
      (format "%s" expected)
    (format "%s (%s unexpected)" (+ expected unexpected) unexpected)))

(defun ert--results-update-ewoc-hf (ewoc stats)
  "Update the header and footer of EWOC to show certain information from STATS.

Also sets `ert--results-progress-bar-button-begin'."
  (let ((run-count (ert-stats-completed stats))
        (results-buffer (current-buffer))
        ;; Need to save buffer-local value.
        (font-lock font-lock-mode))
    (ewoc-set-hf
     ewoc
     ;; header
     (with-temp-buffer
       (insert "Selector: ")
       (ert--insert-human-readable-selector (ert--stats-selector stats))
       (insert "\n")
       (insert
        (format (concat "Passed:  %s\n"
                        "Failed:  %s\n"
                        "Skipped: %s\n"
                        "Total:   %s/%s\n\n")
                (ert--results-format-expected-unexpected
                 (ert--stats-passed-expected stats)
                 (ert--stats-passed-unexpected stats))
                (ert--results-format-expected-unexpected
                 (ert--stats-failed-expected stats)
                 (ert--stats-failed-unexpected stats))
                (ert-stats-skipped stats)
                run-count
                (ert-stats-total stats)))
       (insert
        (format "Started at:   %s\n"
                (ert--format-time-iso8601 (ert--stats-start-time stats))))
       ;; FIXME: This is ugly.  Need to properly define invariants of
       ;; the `stats' data structure.
       (let ((state (cond ((ert--stats-aborted-p stats) 'aborted)
                          ((ert--stats-current-test stats) 'running)
                          ((ert--stats-end-time stats) 'finished)
                          (t 'preparing))))
         (cl-ecase state
           (preparing
            (insert ""))
           (aborted
            (cond ((ert--stats-current-test stats)
                   (insert "Aborted during test: ")
                   (ert-insert-test-name-button
                    (ert-test-name (ert--stats-current-test stats))))
                  (t
                   (insert "Aborted."))))
           (running
            (cl-assert (ert--stats-current-test stats))
            (insert "Running test: ")
            (ert-insert-test-name-button (ert-test-name
                                          (ert--stats-current-test stats))))
           (finished
            (cl-assert (not (ert--stats-current-test stats)))
            (insert "Finished.")))
         (insert "\n")
         (if (ert--stats-end-time stats)
             (insert
              (format "%s%s\n"
                      (if (ert--stats-aborted-p stats)
                          "Aborted at:   "
                        "Finished at:  ")
                      (ert--format-time-iso8601 (ert--stats-end-time stats))))
           (insert "\n"))
         (insert "\n"))
       (let ((progress-bar-string (with-current-buffer results-buffer
                                    ert--results-progress-bar-string)))
         (let ((progress-bar-button-begin
                (insert-text-button progress-bar-string
                                    :type 'ert--results-progress-bar-button
                                    'face (or (and font-lock
                                                   (ert-face-for-stats stats))
                                              'button))))
           ;; The header gets copied verbatim to the results buffer,
           ;; and all positions remain the same, so
           ;; `progress-bar-button-begin' will be the right position
           ;; even in the results buffer.
           (with-current-buffer results-buffer
             (setq-local ert--results-progress-bar-button-begin
                         progress-bar-button-begin))))
       (insert "\n\n")
       (buffer-string))
     ;; footer
     ;;
     ;; We actually want an empty footer, but that would trigger a bug
     ;; in ewoc, sometimes clearing the entire buffer.  (It's possible
     ;; that this bug has been fixed since this has been tested; we
     ;; should test it again.)
     "\n")))


(defvar ert-test-run-redisplay-interval-secs .1
  "How many seconds ERT should wait between redisplays while running tests.

While running tests, ERT shows the current progress, and this variable
determines how frequently the progress display is updated.")

(defun ert--results-update-stats-display (ewoc stats)
  "Update EWOC and the mode line to show data from STATS."
  ;; TODO(ohler): investigate using `make-progress-reporter'.
  (ert--results-update-ewoc-hf ewoc stats)
  (force-mode-line-update)
  (redisplay t)
  (setf (ert--stats-next-redisplay stats)
	(float-time (time-add nil ert-test-run-redisplay-interval-secs))))

(defun ert--results-update-stats-display-maybe (ewoc stats)
  "Call `ert--results-update-stats-display' if not called recently.

EWOC and STATS are arguments for `ert--results-update-stats-display'."
  (unless (time-less-p nil (ert--stats-next-redisplay stats))
    (ert--results-update-stats-display ewoc stats)))

(defun ert--tests-running-mode-line-indicator ()
  "Return a string for the mode line that shows the test run progress."
  (let* ((stats ert--current-run-stats)
         (tests-total (ert-stats-total stats))
         (tests-completed (ert-stats-completed stats)))
    (if (>= tests-completed tests-total)
        (format " ERT(%s/%s,finished)" tests-completed tests-total)
      (format " ERT(%s/%s):%s"
              (1+ tests-completed)
              tests-total
              (if (null (ert--stats-current-test stats))
                  "?"
                (format "%S"
                        (ert-test-name (ert--stats-current-test stats))))))))

(defun ert--make-xrefs-region (begin end)
  "Attach cross-references to function names between BEGIN and END.

BEGIN and END specify a region in the current buffer."
  (save-excursion
    (goto-char begin)
    (while (progn
             (goto-char (+ (point) 2))
             (skip-syntax-forward "^w_")
             (< (point) end))
      (let* ((beg (point))
             (end (progn (skip-syntax-forward "w_") (point)))
             (sym (intern-soft (buffer-substring-no-properties
                                beg end)))
             (file (and sym (symbol-file sym 'defun))))
        (when file
          (goto-char beg)
          ;; help-xref-button needs to operate on something matched
          ;; by a regexp, so set that up for it.
          (re-search-forward "\\(\\sw\\|\\s_\\)+")
          (help-xref-button 0 'help-function-def sym file)))
      (forward-line 1))))

(defun ert--string-first-line (s)
  "Return the first line of S, or S if it contains no newlines.

The return value does not include the line terminator."
  (substring s 0 (cl-position ?\n s)))

(defun ert-face-for-test-result (expectedp)
  "Return a face that shows whether a test result was expected or unexpected.

If EXPECTEDP is nil, returns the face for unexpected results; if
non-nil, returns the face for expected results.."
  (if expectedp 'ert-test-result-expected 'ert-test-result-unexpected))

(defun ert-face-for-stats (stats)
  "Return a face that represents STATS."
  (cond ((ert--stats-aborted-p stats) 'nil)
        ((cl-plusp (ert-stats-completed-unexpected stats))
         (ert-face-for-test-result nil))
        ((eql (ert-stats-completed-expected stats) (ert-stats-total stats))
         (ert-face-for-test-result t))
        (t 'nil)))

(defun ert--print-test-for-ewoc (entry)
  "The ewoc print function for ewoc test entries.  ENTRY is the entry to print."
  (let* ((test (ert--ewoc-entry-test entry))
         (stats ert--results-stats)
         (result (let ((pos (ert--stats-test-pos stats test)))
                   (cl-assert pos)
                   (aref (ert--stats-test-results stats) pos)))
         (hiddenp (ert--ewoc-entry-hidden-p entry))
         (expandedp (ert--ewoc-entry-expanded-p entry))
         (extended-printer-limits-p (ert--ewoc-entry-extended-printer-limits-p
                                     entry)))
    (cond (hiddenp)
          (t
           (let ((expectedp (ert-test-result-expected-p test result)))
             (insert-text-button (format "%c" (ert-char-for-test-result
                                               result expectedp))
                                 :type 'ert--results-expand-collapse-button
                                 'face (or (and font-lock-mode
                                                (ert-face-for-test-result
                                                 expectedp))
                                           'button)))
           (insert " ")
           (ert-insert-test-name-button (ert-test-name test))
           (insert "\n")
           (when (and expandedp (not (eql result 'nil)))
             (when (ert-test-documentation test)
               (insert "    "
                       (propertize
                        (ert--string-first-line
                         (substitute-command-keys
                          (ert-test-documentation test)))
                        'font-lock-face 'font-lock-doc-face)
                       "\n"))
             (cl-etypecase result
               (ert-test-passed
                (if (ert-test-result-expected-p test result)
                    (insert "    passed\n")
                  (insert "    passed unexpectedly\n"))
                (insert ""))
               (ert-test-result-with-condition
                (ert--insert-infos result)
                (let ((print-escape-newlines t)
                      (print-level (if extended-printer-limits-p 12 6))
                      (print-length (if extended-printer-limits-p 100 10)))
                  (insert "    ")
                  (let ((begin (point)))
                    (ert--pp-with-indentation-and-newline
                     (ert-test-result-with-condition-condition result))
                    (ert--make-xrefs-region begin (point)))))
               (ert-test-aborted-with-non-local-exit
                (insert "    aborted\n"))
               (ert-test-quit
                (insert "    quit\n")))
             (insert "\n")))))
  nil)

(defun ert--results-font-lock-function (enabledp)
  "Redraw the ERT results buffer after font-lock-mode was switched on or off.

ENABLEDP is true if font-lock-mode is switched on, false
otherwise."
  (ert--results-update-ewoc-hf ert--results-ewoc ert--results-stats)
  (ewoc-refresh ert--results-ewoc)
  (font-lock-default-function enabledp))

(defun ert--setup-results-buffer (stats listener buffer-name)
  "Set up a test results buffer.

STATS is the stats object; LISTENER is the results listener;
BUFFER-NAME, if non-nil, is the buffer name to use."
  (unless buffer-name (setq buffer-name "*ert*"))
  (let ((buffer (get-buffer-create buffer-name)))
    (with-current-buffer buffer
      (let ((inhibit-read-only t))
        (buffer-disable-undo)
        (erase-buffer)
        (ert-results-mode)
        ;; Erase buffer again in case switching out of the previous
        ;; mode inserted anything.  (This happens e.g. when switching
        ;; from ert-results-mode to ert-results-mode when
        ;; font-lock-mode turns itself off in change-major-mode-hook.)
        (erase-buffer)
        (setq-local font-lock-function
                    'ert--results-font-lock-function)
        (let ((ewoc (ewoc-create 'ert--print-test-for-ewoc nil nil t)))
          (setq-local ert--results-ewoc ewoc)
          (setq-local ert--results-stats stats)
          (setq-local ert--results-progress-bar-string
                      (make-string (ert-stats-total stats)
                                   (ert-char-for-test-result nil t)))
          (setq-local ert--results-listener listener)
          (cl-loop for test across (ert--stats-tests stats) do
                   (ewoc-enter-last ewoc
                                    (make-ert--ewoc-entry :test test
                                                          :hidden-p t)))
          (ert--results-update-ewoc-hf ert--results-ewoc ert--results-stats)
          (goto-char (1- (point-max)))
          buffer)))))


(defvar ert--selector-history nil
  "List of recent test selectors read from terminal.")

;; Should OUTPUT-BUFFER-NAME and MESSAGE-FN really be arguments here?
;; They are needed only for our automated self-tests at the moment.
;; Or should there be some other mechanism?
;;;###autoload
(defun ert-run-tests-interactively (selector
                                    &optional output-buffer-name message-fn)
  "Run the tests specified by SELECTOR and display the results in a buffer.

SELECTOR works as described in `ert-select-tests'.
OUTPUT-BUFFER-NAME and MESSAGE-FN should normally be nil; they
are used for automated self-tests and specify which buffer to use
and how to display message."
  (interactive
   (list (let ((default (if ert--selector-history
                            ;; Can't use `first' here as this form is
                            ;; not compiled, and `first' is not
                            ;; defined without cl.
                            (car ert--selector-history)
                          "t")))
           (read
            (completing-read (format-prompt "Run tests" default)
                             obarray #'ert-test-boundp nil nil
                             'ert--selector-history default nil)))
         nil))
  (unless message-fn (setq message-fn 'message))
  (let ((output-buffer-name output-buffer-name)
        buffer
        listener
        (message-fn message-fn))
    (setq listener
          (lambda (event-type &rest event-args)
            (cl-ecase event-type
              (run-started
               (cl-destructuring-bind (stats) event-args
                 (setq buffer (ert--setup-results-buffer stats
                                                         listener
                                                         output-buffer-name))
                 (pop-to-buffer buffer)))
              (run-ended
               (cl-destructuring-bind (stats abortedp) event-args
                 (funcall message-fn
                          "%sRan %s tests, %s results were as expected%s%s"
                          (if (not abortedp)
                              ""
                            "Aborted: ")
                          (ert-stats-total stats)
                          (ert-stats-completed-expected stats)
                          (let ((unexpected
                                 (ert-stats-completed-unexpected stats)))
                            (if (zerop unexpected)
                                ""
                              (format ", %s unexpected" unexpected)))
                          (let ((skipped
                                 (ert-stats-skipped stats)))
                            (if (zerop skipped)
                                ""
                              (format ", %s skipped" skipped))))
                 (ert--results-update-stats-display (with-current-buffer buffer
                                                      ert--results-ewoc)
                                                    stats)))
              (test-started
               (cl-destructuring-bind (stats test) event-args
                 (with-current-buffer buffer
                   (let* ((ewoc ert--results-ewoc)
                          (pos (ert--stats-test-pos stats test))
                          (node (ewoc-nth ewoc pos)))
                     (cl-assert node)
                     (setf (ert--ewoc-entry-test (ewoc-data node)) test)
                     (aset ert--results-progress-bar-string pos
                           (ert-char-for-test-result nil t))
                     (ert--results-update-stats-display-maybe ewoc stats)
                     (ewoc-invalidate ewoc node)))))
              (test-ended
               (cl-destructuring-bind (stats test result) event-args
                 (with-current-buffer buffer
                   (let* ((ewoc ert--results-ewoc)
                          (pos (ert--stats-test-pos stats test))
                          (node (ewoc-nth ewoc pos)))
                     (when (ert--ewoc-entry-hidden-p (ewoc-data node))
                       (setf (ert--ewoc-entry-hidden-p (ewoc-data node))
                             (ert-test-result-expected-p test result)))
                     (aset ert--results-progress-bar-string pos
                           (ert-char-for-test-result result
                                                     (ert-test-result-expected-p
                                                      test result)))
                     (ert--results-update-stats-display-maybe ewoc stats)
                     (ewoc-invalidate ewoc node))))))))
    (ert-run-tests selector listener t)))

;;;###autoload
(defalias 'ert 'ert-run-tests-interactively)


;;; Simple view mode for auxiliary information like stack traces or
;;; messages.  Mainly binds "q" for quit.

(define-derived-mode ert-simple-view-mode special-mode "ERT-View"
  "Major mode for viewing auxiliary information in ERT.")

;;; Commands and button actions for the results buffer.

(define-derived-mode ert-results-mode special-mode "ERT-Results"
  "Major mode for viewing results of ERT test runs."
  (setq-local revert-buffer-function
              (lambda (&rest _) (ert-results-rerun-all-tests))))

(cl-loop for (key binding) in
         '( ;; Stuff that's not in the menu.
           ("\t" forward-button)
           ([backtab] backward-button)
           ("j" ert-results-jump-between-summary-and-result)
           ("L" ert-results-toggle-printer-limits-for-test-at-point)
           ("n" ert-results-next-test)
           ("p" ert-results-previous-test)
           ;; Stuff that is in the menu.
           ("R" ert-results-rerun-all-tests)
           ("r" ert-results-rerun-test-at-point)
           ("d" ert-results-rerun-test-at-point-debugging-errors)
           ("." ert-results-find-test-at-point-other-window)
           ("b" ert-results-pop-to-backtrace-for-test-at-point)
           ("m" ert-results-pop-to-messages-for-test-at-point)
           ("l" ert-results-pop-to-should-forms-for-test-at-point)
           ("h" ert-results-describe-test-at-point)
           ("D" ert-delete-test)
           ("T" ert-results-pop-to-timings)
           )
         do
         (define-key ert-results-mode-map key binding))

(easy-menu-define ert-results-mode-menu ert-results-mode-map
  "Menu for `ert-results-mode'."
  '("ERT Results"
    ["Re-run all tests" ert-results-rerun-all-tests]
    "--"
    ;; FIXME?  Why are there (at least) 3 different ways to decide if
    ;; there is a test at point?
    ["Re-run test" ert-results-rerun-test-at-point
     :active (car (ert--results-test-at-point-allow-redefinition))]
    ["Debug test" ert-results-rerun-test-at-point-debugging-errors
     :active (car (ert--results-test-at-point-allow-redefinition))]
    ["Show test definition" ert-results-find-test-at-point-other-window
     :active (ert-test-at-point)]
    "--"
    ["Show backtrace" ert-results-pop-to-backtrace-for-test-at-point
     :active (ert--results-test-at-point-no-redefinition)]
    ["Show messages" ert-results-pop-to-messages-for-test-at-point
     :active (ert--results-test-at-point-no-redefinition)]
    ["Show `should' forms" ert-results-pop-to-should-forms-for-test-at-point
     :active (ert--results-test-at-point-no-redefinition)]
    ["Describe test" ert-results-describe-test-at-point
     :active (ert--results-test-at-point-no-redefinition)]
    "--"
    ["Delete test" ert-delete-test]
    "--"
    ["Show execution time of each test" ert-results-pop-to-timings]
    ))

(define-button-type 'ert--results-progress-bar-button
  'action #'ert--results-progress-bar-button-action
  'help-echo "mouse-2, RET: Reveal test result")

(define-button-type 'ert--test-name-button
  'action #'ert--test-name-button-action
  'help-echo "mouse-2, RET: Find test definition")

(define-button-type 'ert--results-expand-collapse-button
  'action #'ert--results-expand-collapse-button-action
  'help-echo "mouse-2, RET: Expand/collapse test result")

(defun ert--results-test-node-or-null-at-point ()
  "If point is on a valid ewoc node, return it; return nil otherwise.

To be used in the ERT results buffer."
  (let* ((ewoc ert--results-ewoc)
         (node (ewoc-locate ewoc)))
    ;; `ewoc-locate' will return an arbitrary node when point is on
    ;; header or footer, or when all nodes are invisible.  So we need
    ;; to validate its return value here.
    ;;
    ;; Update: I'm seeing nil being returned in some cases now,
    ;; perhaps this has been changed?
    (if (and node
             (>= (point) (ewoc-location node))
             (not (ert--ewoc-entry-hidden-p (ewoc-data node))))
        node
      nil)))

(defun ert--results-test-node-at-point ()
  "If point is on a valid ewoc node, return it; signal an error otherwise.

To be used in the ERT results buffer."
  (or (ert--results-test-node-or-null-at-point)
      (user-error "No test at point")))

(defun ert-results-next-test ()
  "Move point to the next test.

To be used in the ERT results buffer."
  (interactive)
  (ert--results-move (ewoc-locate ert--results-ewoc) 'ewoc-next
                     "No tests below"))

(defun ert-results-previous-test ()
  "Move point to the previous test.

To be used in the ERT results buffer."
  (interactive)
  (ert--results-move (ewoc-locate ert--results-ewoc) 'ewoc-prev
                     "No tests above"))

(defun ert--results-move (node ewoc-fn error-message)
  "Move point from NODE to the previous or next node.

EWOC-FN specifies the direction and should be either `ewoc-prev'
or `ewoc-next'.  If there are no more nodes in that direction, a
user-error is signaled with the message ERROR-MESSAGE."
  (cl-loop
   (setq node (funcall ewoc-fn ert--results-ewoc node))
   (when (null node)
     (user-error "%s" error-message))
   (unless (ert--ewoc-entry-hidden-p (ewoc-data node))
     (goto-char (ewoc-location node))
     (cl-return))))

(defun ert--results-expand-collapse-button-action (_button)
  "Expand or collapse the test node BUTTON belongs to."
  (let* ((ewoc ert--results-ewoc)
         (node (save-excursion
                 (goto-char (ert--button-action-position))
                 (ert--results-test-node-at-point)))
         (entry (ewoc-data node)))
    (setf (ert--ewoc-entry-expanded-p entry)
          (not (ert--ewoc-entry-expanded-p entry)))
    (ewoc-invalidate ewoc node)))

(defun ert-results-find-test-at-point-other-window ()
  "Find the definition of the test at point in another window.

To be used in the ERT results buffer."
  (interactive)
  (let ((name (ert-test-at-point)))
    (unless name
      (user-error "No test at point"))
    (ert-find-test-other-window name)))

(defun ert--test-name-button-action (button)
  "Find the definition of the test BUTTON belongs to, in another window."
  (let ((name (button-get button 'ert-test-name)))
    (ert-find-test-other-window name)))

(defun ert--ewoc-position (ewoc node)
  ;; checkdoc-order: nil
  "Return the position of NODE in EWOC, or nil if NODE is not in EWOC."
  (cl-loop for i from 0
           for node-here = (ewoc-nth ewoc 0) then (ewoc-next ewoc node-here)
           do (when (eql node node-here)
                (cl-return i))
           finally (cl-return nil)))

(defun ert-results-jump-between-summary-and-result ()
  "Jump back and forth between the test run summary and individual test results.

From an ewoc node, jumps to the character that represents the
same test in the progress bar, and vice versa.

To be used in the ERT results buffer."
  ;; Maybe this command isn't actually needed much, but if it is, it
  ;; seems like an indication that the UI design is not optimal.  If
  ;; jumping back and forth between a summary at the top of the buffer
  ;; and the error log in the remainder of the buffer is useful, then
  ;; the summary apparently needs to be easily accessible from the
  ;; error log, and perhaps it would be better to have it in a
  ;; separate buffer to keep it visible.
  (interactive)
  (let ((ewoc ert--results-ewoc)
        (progress-bar-begin ert--results-progress-bar-button-begin))
    (cond ((ert--results-test-node-or-null-at-point)
           (let* ((node (ert--results-test-node-at-point))
                  (pos (ert--ewoc-position ewoc node)))
             (goto-char (+ progress-bar-begin pos))))
          ((and (<= progress-bar-begin (point))
                (< (point) (button-end (button-at progress-bar-begin))))
           (let* ((node (ewoc-nth ewoc (- (point) progress-bar-begin)))
                  (entry (ewoc-data node)))
             (when (ert--ewoc-entry-hidden-p entry)
               (setf (ert--ewoc-entry-hidden-p entry) nil)
               (ewoc-invalidate ewoc node))
             (ewoc-goto-node ewoc node)))
          (t
           (goto-char progress-bar-begin)))))

(defun ert-test-at-point ()
  "Return the name of the test at point as a symbol, or nil if none."
  (or (and (eql major-mode 'ert-results-mode)
           (let ((test (ert--results-test-at-point-no-redefinition)))
             (and test (ert-test-name test))))
      (let* ((thing (thing-at-point 'symbol))
             (sym (intern-soft thing)))
        (and (ert-test-boundp sym)
             sym))))

(defun ert--results-test-at-point-no-redefinition (&optional error)
  "Return the test at point, or nil.
If optional argument ERROR is non-nil, signal an error rather than return nil.
To be used in the ERT results buffer."
  (cl-assert (eql major-mode 'ert-results-mode))
  (or
   (if (ert--results-test-node-or-null-at-point)
       (let* ((node (ert--results-test-node-at-point))
              (test (ert--ewoc-entry-test (ewoc-data node))))
         test)
     (let ((progress-bar-begin ert--results-progress-bar-button-begin))
       (when (and (<= progress-bar-begin (point))
                  (< (point) (button-end (button-at progress-bar-begin))))
         (let* ((test-index (- (point) progress-bar-begin))
                (test (aref (ert--stats-tests ert--results-stats)
                           test-index)))
           test))))
   (if error (user-error "No test at point"))))

(defun ert--results-test-at-point-allow-redefinition ()
  "Look up the test at point, and check whether it has been redefined.

To be used in the ERT results buffer.

Returns a list of two elements: the test (or nil) and a symbol
specifying whether the test has been redefined.

If a new test has been defined with the same name as the test at
point, replaces the test at point with the new test, and returns
the new test and the symbol `redefined'.

If the test has been deleted, returns the old test and the symbol
`deleted'.

If the test is still current, returns the test and the symbol nil.

If there is no test at point, returns a list with two nils."
  (let ((test (ert--results-test-at-point-no-redefinition)))
    (cond ((null test)
           `(nil nil))
          ((null (ert-test-name test))
           `(,test nil))
          (t
           (let* ((name (ert-test-name test))
                  (new-test (and (ert-test-boundp name)
                                 (ert-get-test name))))
             (cond ((eql test new-test)
                    `(,test nil))
                   ((null new-test)
                    `(,test deleted))
                   (t
                    (ert--results-update-after-test-redefinition
                     (ert--stats-test-pos ert--results-stats test)
                     new-test)
                    `(,new-test redefined))))))))

(defun ert--results-update-after-test-redefinition (pos new-test)
  "Update results buffer after the test at pos POS has been redefined.

Also updates the stats object.  NEW-TEST is the new test
definition."
  (let* ((stats ert--results-stats)
         (ewoc ert--results-ewoc)
         (node (ewoc-nth ewoc pos))
         (entry (ewoc-data node)))
    (ert--stats-set-test-and-result stats pos new-test nil)
    (setf (ert--ewoc-entry-test entry) new-test
          (aref ert--results-progress-bar-string pos) (ert-char-for-test-result
                                                       nil t))
    (ewoc-invalidate ewoc node))
  nil)

(defun ert--button-action-position ()
  "The buffer position where the last button action was triggered."
  (cond ((integerp last-command-event)
         (point))
        ((eventp last-command-event)
         (posn-point (event-start last-command-event)))
        (t (cl-assert nil))))

(defun ert--results-progress-bar-button-action (_button)
  "Jump to details for the test represented by the character clicked in BUTTON."
  (goto-char (ert--button-action-position))
  (ert-results-jump-between-summary-and-result))

(defun ert-results-rerun-all-tests ()
  "Re-run all tests, using the same selector.

To be used in the ERT results buffer."
  (interactive)
  (cl-assert (eql major-mode 'ert-results-mode))
  (let ((selector (ert--stats-selector ert--results-stats)))
    (ert-run-tests-interactively selector (buffer-name))))

(defun ert-results-rerun-test-at-point ()
  "Re-run the test at point.

To be used in the ERT results buffer."
  (interactive)
  (cl-destructuring-bind (test redefinition-state)
      (ert--results-test-at-point-allow-redefinition)
    (when (null test)
      (user-error "No test at point"))
    (let* ((stats ert--results-stats)
           (progress-message (format "Running %stest %S"
                                     (cl-ecase redefinition-state
                                       ((nil) "")
                                       (redefined "new definition of ")
                                       (deleted "deleted "))
                                     (ert-test-name test))))
      ;; Need to save and restore point manually here: When point is on
      ;; the first visible ewoc entry while the header is updated, point
      ;; moves to the top of the buffer.  This is undesirable, and a
      ;; simple `save-excursion' doesn't prevent it.
      (let ((point (point)))
        (unwind-protect
            (unwind-protect
                (progn
                  (message "%s..." progress-message)
                  (ert-run-or-rerun-test stats test
                                         ert--results-listener))
              (ert--results-update-stats-display ert--results-ewoc stats)
              (message "%s...%s"
                       progress-message
                       (let ((result (ert-test-most-recent-result test)))
                         (ert-string-for-test-result
                          result (ert-test-result-expected-p test result)))))
          (goto-char point))))))

(defun ert-results-rerun-test-at-point-debugging-errors ()
  "Re-run the test at point with `ert-debug-on-error' bound to t.

To be used in the ERT results buffer."
  (interactive)
  (let ((ert-debug-on-error t))
    (ert-results-rerun-test-at-point)))

(defun ert-results-pop-to-backtrace-for-test-at-point ()
  "Display the backtrace for the test at point.

To be used in the ERT results buffer."
  (interactive)
  (let* ((test (ert--results-test-at-point-no-redefinition t))
         (stats ert--results-stats)
         (pos (ert--stats-test-pos stats test))
         (result (aref (ert--stats-test-results stats) pos)))
    (cl-etypecase result
      (ert-test-passed (error "Test passed, no backtrace available"))
      (ert-test-result-with-condition
       (let ((buffer (get-buffer-create "*ERT Backtrace*")))
         (pop-to-buffer buffer)
         (unless (derived-mode-p 'backtrace-mode)
           (backtrace-mode))
         (setq backtrace-insert-header-function
               (lambda () (ert--insert-backtrace-header (ert-test-name test)))
               backtrace-frames (ert-test-result-with-condition-backtrace result))
         (backtrace-print)
         (goto-char (point-min)))))))

(defun ert--insert-backtrace-header (name)
  (insert (substitute-command-keys "Backtrace for test `"))
  (ert-insert-test-name-button name)
  (insert (substitute-command-keys "':\n")))

(defun ert-results-pop-to-messages-for-test-at-point ()
  "Display the part of the *Messages* buffer generated during the test at point.

To be used in the ERT results buffer."
  (interactive)
  (let* ((test (ert--results-test-at-point-no-redefinition t))
         (stats ert--results-stats)
         (pos (ert--stats-test-pos stats test))
         (result (aref (ert--stats-test-results stats) pos)))
    (let ((buffer (get-buffer-create "*ERT Messages*")))
      (pop-to-buffer buffer)
      (let ((inhibit-read-only t))
        (buffer-disable-undo)
        (erase-buffer)
        (ert-simple-view-mode)
        (insert (ert-test-result-messages result))
        (goto-char (point-min))
        (insert (substitute-command-keys "Messages for test `"))
        (ert-insert-test-name-button (ert-test-name test))
        (insert (substitute-command-keys "':\n"))))))

(defun ert-results-pop-to-should-forms-for-test-at-point ()
  "Display the list of `should' forms executed during the test at point.

To be used in the ERT results buffer."
  (interactive)
  (let* ((test (ert--results-test-at-point-no-redefinition t))
         (stats ert--results-stats)
         (pos (ert--stats-test-pos stats test))
         (result (aref (ert--stats-test-results stats) pos)))
    (let ((buffer (get-buffer-create "*ERT list of should forms*")))
      (pop-to-buffer buffer)
      (let ((inhibit-read-only t))
        (buffer-disable-undo)
        (erase-buffer)
        (ert-simple-view-mode)
        (if (null (ert-test-result-should-forms result))
            (insert "\n(No should forms during this test.)\n")
          (cl-loop for form-description
                   in (ert-test-result-should-forms result)
                   for i from 1 do
                   (insert "\n")
                   (insert (format "%s: " i))
                   (let ((begin (point)))
                     (ert--pp-with-indentation-and-newline form-description)
                     (ert--make-xrefs-region begin (point)))))
        (goto-char (point-min))
        (insert (substitute-command-keys
                 "`should' forms executed during test `"))
        (ert-insert-test-name-button (ert-test-name test))
        (insert (substitute-command-keys "':\n"))
        (insert "\n")
        (insert (concat "(Values are shallow copies and may have "
                        "looked different during the test if they\n"
                        "have been modified destructively.)\n"))
        (forward-line 1)))))

(defun ert-results-toggle-printer-limits-for-test-at-point ()
  "Toggle how much of the condition to print for the test at point.

To be used in the ERT results buffer."
  (interactive)
  (let* ((ewoc ert--results-ewoc)
         (node (ert--results-test-node-at-point))
         (entry (ewoc-data node)))
    (setf (ert--ewoc-entry-extended-printer-limits-p entry)
          (not (ert--ewoc-entry-extended-printer-limits-p entry)))
    (ewoc-invalidate ewoc node)))

(defun ert-results-pop-to-timings ()
  "Display test timings for the last run.

To be used in the ERT results buffer."
  (interactive)
  (let* ((stats ert--results-stats)
         (buffer (get-buffer-create "*ERT timings*"))
         (data (cl-loop for test across (ert--stats-tests stats)
                        for start-time across (ert--stats-test-start-times
                                               stats)
                        for end-time across (ert--stats-test-end-times stats)
                        collect (list test
                                      (float-time (time-subtract
                                                   end-time start-time))))))
    (setq data (sort data (lambda (a b)
                            (> (cl-second a) (cl-second b)))))
    (pop-to-buffer buffer)
    (let ((inhibit-read-only t))
      (buffer-disable-undo)
      (erase-buffer)
      (ert-simple-view-mode)
      (if (null data)
          (insert "(No data)\n")
        (insert (format "%-3s  %8s %8s\n" "" "time" "cumul"))
        (cl-loop for (test time) in data
                 for cumul-time = time then (+ cumul-time time)
                 for i from 1 do
                 (progn
                   (insert (format "%3s: %8.3f %8.3f " i time cumul-time))
                   (ert-insert-test-name-button (ert-test-name test))
                   (insert "\n"))))
      (goto-char (point-min))
      (insert "Tests by run time (seconds):\n\n")
      (forward-line 1))))

;;;###autoload
(defun ert-describe-test (test-or-test-name)
  "Display the documentation for TEST-OR-TEST-NAME (a symbol or ert-test)."
  (interactive (list (ert-read-test-name-at-point "Describe test")))
  (let (test-name
        test-definition)
    (cl-etypecase test-or-test-name
      (symbol (setq test-name test-or-test-name
                    test-definition (ert-get-test test-or-test-name)))
      (ert-test (setq test-name (ert-test-name test-or-test-name)
                      test-definition test-or-test-name)))
    (help-setup-xref (list #'ert-describe-test test-or-test-name)
                     (called-interactively-p 'interactive))
    (save-excursion
      (with-help-window (help-buffer)
        (with-current-buffer (help-buffer)
          (insert (if test-name (format "%S" test-name) "<anonymous test>"))
          (insert " is a test")
          (let ((file-name (and test-name
                                (symbol-file test-name 'ert--test))))
            (when file-name
              (insert (format-message " defined in `%s'"
                                      (file-name-nondirectory file-name)))
              (save-excursion
                (re-search-backward (substitute-command-keys "`\\([^`']+\\)'")
                                    nil t)
                (help-xref-button 1 'help-function-def test-name file-name)))
            (insert ".")
            (fill-region-as-paragraph (point-min) (point))
            (insert "\n\n")
            (unless (and (ert-test-boundp test-name)
                         (eql (ert-get-test test-name) test-definition))
              (let ((begin (point)))
                (insert "Note: This test has been redefined or deleted, "
                        "this documentation refers to an old definition.")
                (fill-region-as-paragraph begin (point)))
              (insert "\n\n"))
            (insert (substitute-command-keys
                     (or (ert-test-documentation test-definition)
                         "It is not documented."))
                    "\n")
            ;; For describe-symbol-backends.
            (buffer-string)))))))

(defun ert-results-describe-test-at-point ()
  "Display the documentation of the test at point.

To be used in the ERT results buffer."
  (interactive)
  (ert-describe-test (ert--results-test-at-point-no-redefinition t)))


;;; Actions on load/unload.

(require 'help-mode)
(add-to-list 'describe-symbol-backends
             `("ERT test" ,#'ert-test-boundp
               ,(lambda (s _b _f) (ert-describe-test s))))

(add-to-list 'find-function-regexp-alist '(ert--test . ert--find-test-regexp))
(add-to-list 'minor-mode-alist '(ert--current-run-stats
                                 (:eval
                                  (ert--tests-running-mode-line-indicator))))
(add-hook 'emacs-lisp-mode-hook #'ert--activate-font-lock-keywords)

(defun ert--unload-function ()
  "Unload function to undo the side-effects of loading ert.el."
  (ert--remove-from-list 'find-function-regexp-alist 'ert-deftest :key #'car)
  (ert--remove-from-list 'minor-mode-alist 'ert--current-run-stats :key #'car)
  (ert--remove-from-list 'emacs-lisp-mode-hook
                         'ert--activate-font-lock-keywords)
  nil)

(defvar ert-unload-hook ())
(add-hook 'ert-unload-hook #'ert--unload-function)


(provide 'ert)

;;; ert.el ends here