summaryrefslogtreecommitdiffstats
path: root/conf.d/controller/lua.d/luaunit.lua
blob: 02377c9f8432836d6ac34bc7a93899670a0ed561 (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
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
--[[
        luaunit.lua

Description: A unit testing framework
Homepage: https://github.com/bluebird75/luaunit
Development by Philippe Fremy <phil@freehackers.org>
Based on initial work of Ryu, Gwang (http://www.gpgstudy.com/gpgiki/LuaUnit)
License: BSD License, see LICENSE.txt
]]--

require("math")
local M={}

-- private exported functions (for testing)
M.private = {}

M.VERSION='3.3'
M._VERSION=M.VERSION -- For LuaUnit v2 compatibility

-- a version which distinguish between regular Lua and LuaJit
M._LUAVERSION = (jit and jit.version) or _VERSION

--[[ Some people like assertEquals( actual, expected ) and some people prefer
assertEquals( expected, actual ).
]]--
M.ORDER_ACTUAL_EXPECTED = true
M.PRINT_TABLE_REF_IN_ERROR_MSG = false
M.TABLE_EQUALS_KEYBYCONTENT = true
M.LINE_LENGTH = 80
M.TABLE_DIFF_ANALYSIS_THRESHOLD = 10    -- display deep analysis for more than 10 items
M.LIST_DIFF_ANALYSIS_THRESHOLD  = 10    -- display deep analysis for more than 10 items

--[[ EPS is meant to help with Lua's floating point math in simple corner
cases like almostEquals(1.1-0.1, 1), which may not work as-is (e.g. on numbers
with rational binary representation) if the user doesn't provide some explicit
error margin.

The default margin used by almostEquals() in such cases is EPS; and since
Lua may be compiled with different numeric precisions (single vs. double), we
try to select a useful default for it dynamically. Note: If the initial value
is not acceptable, it can be changed by the user to better suit specific needs.

See also: https://en.wikipedia.org/wiki/Machine_epsilon
]]
M.EPS = 2^-52 -- = machine epsilon for "double", ~2.22E-16
if math.abs(1.1 - 1 - 0.1) > M.EPS then
    -- rounding error is above EPS, assume single precision
    M.EPS = 2^-23 -- = machine epsilon for "float", ~1.19E-07
end

-- set this to false to debug luaunit
local STRIP_LUAUNIT_FROM_STACKTRACE = true

M.VERBOSITY_DEFAULT = 10
M.VERBOSITY_LOW     = 1
M.VERBOSITY_QUIET   = 0
M.VERBOSITY_VERBOSE = 20
M.DEFAULT_DEEP_ANALYSIS = nil
M.FORCE_DEEP_ANALYSIS   = true
M.DISABLE_DEEP_ANALYSIS = false

-- set EXPORT_ASSERT_TO_GLOBALS to have all asserts visible as global values
-- EXPORT_ASSERT_TO_GLOBALS = true

-- we need to keep a copy of the script args before it is overriden
local cmdline_argv = rawget(_G, "arg")

M.FAILURE_PREFIX = 'LuaUnit test FAILURE: ' -- prefix string for failed tests
M.SUCCESS_PREFIX = 'LuaUnit test SUCCESS: ' -- prefix string for successful tests finished early



M.USAGE=[[Usage: lua <your_test_suite.lua> [options] [testname1 [testname2] ... ]
Options:
  -h, --help:             Print this help
  --version:              Print version information
  -v, --verbose:          Increase verbosity
  -q, --quiet:            Set verbosity to minimum
  -e, --error:            Stop on first error
  -f, --failure:          Stop on first failure or error
  -s, --shuffle:          Shuffle tests before running them
  -o, --output OUTPUT:    Set output type to OUTPUT
                          Possible values: text, tap, junit, nil
  -n, --name NAME:        For junit only, mandatory name of xml file
  -r, --repeat NUM:       Execute all tests NUM times, e.g. to trig the JIT
  -p, --pattern PATTERN:  Execute all test names matching the Lua PATTERN
                          May be repeated to include several patterns
                          Make sure you escape magic chars like +? with %
  -x, --exclude PATTERN:  Exclude all test names matching the Lua PATTERN
                          May be repeated to exclude several patterns
                          Make sure you escape magic chars like +? with %
  testname1, testname2, ... : tests to run in the form of testFunction,
                              TestClass or TestClass.testMethod
]]

local is_equal -- defined here to allow calling from mismatchFormattingPureList

----------------------------------------------------------------
--
--                 general utility functions
--
----------------------------------------------------------------

local function pcall_or_abort(func, ...)
    -- unpack is a global function for Lua 5.1, otherwise use table.unpack
    local unpack = rawget(_G, "unpack") or table.unpack
    local result = {pcall(func, ...)}
    if not result[1] then
        -- an error occurred
        print(result[2]) -- error message
        print()
        print(M.USAGE)
        os.exit(-1)
    end
    return unpack(result, 2)
end

local crossTypeOrdering = {
    number = 1, boolean = 2, string = 3, table = 4, other = 5
}
local crossTypeComparison = {
    number = function(a, b) return a < b end,
    string = function(a, b) return a < b end,
    other = function(a, b) return tostring(a) < tostring(b) end,
}

local function crossTypeSort(a, b)
    local type_a, type_b = type(a), type(b)
    if type_a == type_b then
        local func = crossTypeComparison[type_a] or crossTypeComparison.other
        return func(a, b)
    end
    type_a = crossTypeOrdering[type_a] or crossTypeOrdering.other
    type_b = crossTypeOrdering[type_b] or crossTypeOrdering.other
    return type_a < type_b
end

local function __genSortedIndex( t )
    -- Returns a sequence consisting of t's keys, sorted.
    local sortedIndex = {}

    for key,_ in pairs(t) do
        table.insert(sortedIndex, key)
    end

    table.sort(sortedIndex, crossTypeSort)
    return sortedIndex
end
M.private.__genSortedIndex = __genSortedIndex

local function sortedNext(state, control)
    -- Equivalent of the next() function of table iteration, but returns the
    -- keys in sorted order (see __genSortedIndex and crossTypeSort).
    -- The state is a temporary variable during iteration and contains the
    -- sorted key table (state.sortedIdx). It also stores the last index (into
    -- the keys) used by the iteration, to find the next one quickly.
    local key

    --print("sortedNext: control = "..tostring(control) )
    if control == nil then
        -- start of iteration
        state.count = #state.sortedIdx
        state.lastIdx = 1
        key = state.sortedIdx[1]
        return key, state.t[key]
    end

    -- normally, we expect the control variable to match the last key used
    if control ~= state.sortedIdx[state.lastIdx] then
        -- strange, we have to find the next value by ourselves
        -- the key table is sorted in crossTypeSort() order! -> use bisection
        local lower, upper = 1, state.count
        repeat
            state.lastIdx = math.modf((lower + upper) / 2)
            key = state.sortedIdx[state.lastIdx]
            if key == control then
                break -- key found (and thus prev index)
            end
            if crossTypeSort(key, control) then
                -- key < control, continue search "right" (towards upper bound)
                lower = state.lastIdx + 1
            else
                -- key > control, continue search "left" (towards lower bound)
                upper = state.lastIdx - 1
            end
        until lower > upper
        if lower > upper then -- only true if the key wasn't found, ...
            state.lastIdx = state.count -- ... so ensure no match in code below
        end
    end

    -- proceed by retrieving the next value (or nil) from the sorted keys
    state.lastIdx = state.lastIdx + 1
    key = state.sortedIdx[state.lastIdx]
    if key then
        return key, state.t[key]
    end

    -- getting here means returning `nil`, which will end the iteration
end

local function sortedPairs(tbl)
    -- Equivalent of the pairs() function on tables. Allows to iterate in
    -- sorted order. As required by "generic for" loops, this will return the
    -- iterator (function), an "invariant state", and the initial control value.
    -- (see http://www.lua.org/pil/7.2.html)
    return sortedNext, {t = tbl, sortedIdx = __genSortedIndex(tbl)}, nil
end
M.private.sortedPairs = sortedPairs

-- seed the random with a strongly varying seed
math.randomseed(os.clock()*1E11)

local function randomizeTable( t )
    -- randomize the item orders of the table t
    for i = #t, 2, -1 do
        local j = math.random(i)
        if i ~= j then
            t[i], t[j] = t[j], t[i]
        end
    end
end
M.private.randomizeTable = randomizeTable

local function strsplit(delimiter, text)
-- Split text into a list consisting of the strings in text, separated
-- by strings matching delimiter (which may _NOT_ be a pattern).
-- Example: strsplit(", ", "Anna, Bob, Charlie, Dolores")
    if delimiter == "" then -- this would result in endless loops
        error("delimiter matches empty string!")
    end
    local list, pos, first, last = {}, 1
    while true do
        first, last = text:find(delimiter, pos, true)
        if first then -- found?
            table.insert(list, text:sub(pos, first - 1))
            pos = last + 1
        else
            table.insert(list, text:sub(pos))
            break
        end
    end
    return list
end
M.private.strsplit = strsplit

local function hasNewLine( s )
    -- return true if s has a newline
    return (string.find(s, '\n', 1, true) ~= nil)
end
M.private.hasNewLine = hasNewLine

local function prefixString( prefix, s )
    -- Prefix all the lines of s with prefix
    return prefix .. string.gsub(s, '\n', '\n' .. prefix)
end
M.private.prefixString = prefixString

local function strMatch(s, pattern, start, final )
    -- return true if s matches completely the pattern from index start to index end
    -- return false in every other cases
    -- if start is nil, matches from the beginning of the string
    -- if final is nil, matches to the end of the string
    start = start or 1
    final = final or string.len(s)

    local foundStart, foundEnd = string.find(s, pattern, start, false)
    return foundStart == start and foundEnd == final
end
M.private.strMatch = strMatch

local function patternFilter(patterns, expr)
    -- Run `expr` through the inclusion and exclusion rules defined in patterns
    -- and return true if expr shall be included, false for excluded.
    -- Inclusion pattern are defined as normal patterns, exclusions 
    -- patterns start with `!` and are followed by a normal pattern

    -- result: nil = UNKNOWN (not matched yet), true = ACCEPT, false = REJECT
    -- default: true if no explicit "include" is found, set to false otherwise
    local default, result = true, nil

    if patterns ~= nil then
        for _, pattern in ipairs(patterns) do
            local exclude = pattern:sub(1,1) == '!'
            if exclude then
                pattern = pattern:sub(2)
            else
                -- at least one include pattern specified, a match is required
                default = false
            end
            -- print('pattern: ',pattern)
            -- print('exclude: ',exclude)
            -- print('default: ',default)

            if string.find(expr, pattern) then
                -- set result to false when excluding, true otherwise
                result = not exclude
            end
        end
    end

    if result ~= nil then
        return result
    end
    return default
end
M.private.patternFilter = patternFilter

local function xmlEscape( s )
    -- Return s escaped for XML attributes
    -- escapes table:
    -- "   &quot;
    -- '   &apos;
    -- <   &lt;
    -- >   &gt;
    -- &   &amp;

    return string.gsub( s, '.', {
        ['&'] = "&amp;",
        ['"'] = "&quot;",
        ["'"] = "&apos;",
        ['<'] = "&lt;",
        ['>'] = "&gt;",
    } )
end
M.private.xmlEscape = xmlEscape

local function xmlCDataEscape( s )
    -- Return s escaped for CData section, escapes: "]]>"
    return string.gsub( s, ']]>', ']]&gt;' )
end
M.private.xmlCDataEscape = xmlCDataEscape

local function stripLuaunitTrace( stackTrace )
    --[[
    -- Example of  a traceback:
    <<stack traceback:
        example_with_luaunit.lua:130: in function 'test2_withFailure'
        ./luaunit.lua:1449: in function <./luaunit.lua:1449>
        [C]: in function 'xpcall'
        ./luaunit.lua:1449: in function 'protectedCall'
        ./luaunit.lua:1508: in function 'execOneFunction'
        ./luaunit.lua:1596: in function 'runSuiteByInstances'
        ./luaunit.lua:1660: in function 'runSuiteByNames'
        ./luaunit.lua:1736: in function 'runSuite'
        example_with_luaunit.lua:140: in main chunk
        [C]: in ?>>

        Other example:
    <<stack traceback:
        ./luaunit.lua:545: in function 'assertEquals'
        example_with_luaunit.lua:58: in function 'TestToto.test7'
        ./luaunit.lua:1517: in function <./luaunit.lua:1517>
        [C]: in function 'xpcall'
        ./luaunit.lua:1517: in function 'protectedCall'
        ./luaunit.lua:1578: in function 'execOneFunction'
        ./luaunit.lua:1677: in function 'runSuiteByInstances'
        ./luaunit.lua:1730: in function 'runSuiteByNames'
        ./luaunit.lua:1806: in function 'runSuite'
        example_with_luaunit.lua:140: in main chunk
        [C]: in ?>>

    <<stack traceback:
        luaunit2/example_with_luaunit.lua:124: in function 'test1_withFailure'
        luaunit2/luaunit.lua:1532: in function <luaunit2/luaunit.lua:1532>
        [C]: in function 'xpcall'
        luaunit2/luaunit.lua:1532: in function 'protectedCall'
        luaunit2/luaunit.lua:1591: in function 'execOneFunction'
        luaunit2/luaunit.lua:1679: in function 'runSuiteByInstances'
        luaunit2/luaunit.lua:1743: in function 'runSuiteByNames'
        luaunit2/luaunit.lua:1819: in function 'runSuite'
        luaunit2/example_with_luaunit.lua:140: in main chunk
        [C]: in ?>>


    -- first line is "stack traceback": KEEP
    -- next line may be luaunit line: REMOVE
    -- next lines are call in the program under testOk: REMOVE
    -- next lines are calls from luaunit to call the program under test: KEEP

    -- Strategy:
    -- keep first line
    -- remove lines that are part of luaunit
    -- kepp lines until we hit a luaunit line
    ]]

    local function isLuaunitInternalLine( s )
        -- return true if line of stack trace comes from inside luaunit
        return s:find('[/\\]luaunit%.lua:%d+: ') ~= nil
    end

    -- print( '<<'..stackTrace..'>>' )

    local t = strsplit( '\n', stackTrace )
    -- print( prettystr(t) )

    local idx = 2

    -- remove lines that are still part of luaunit
    while t[idx] and isLuaunitInternalLine( t[idx] ) do
        -- print('Removing : '..t[idx] )
        table.remove(t, idx)
    end

    -- keep lines until we hit luaunit again
    while t[idx] and (not isLuaunitInternalLine(t[idx])) do
        -- print('Keeping : '..t[idx] )
        idx = idx + 1
    end

    -- remove remaining luaunit lines
    while t[idx] do
        -- print('Removing : '..t[idx] )
        table.remove(t, idx)
    end

    -- print( prettystr(t) )
    return table.concat( t, '\n')

end
M.private.stripLuaunitTrace = stripLuaunitTrace


local function prettystr_sub(v, indentLevel, printTableRefs, recursionTable )
    local type_v = type(v)
    if "string" == type_v  then
        -- use clever delimiters according to content:
        -- enclose with single quotes if string contains ", but no '
        if v:find('"', 1, true) and not v:find("'", 1, true) then
            return "'" .. v .. "'"
        end
        -- use double quotes otherwise, escape embedded "
        return '"' .. v:gsub('"', '\\"') .. '"'

    elseif "table" == type_v then
        --if v.__class__ then
        --    return string.gsub( tostring(v), 'table', v.__class__ )
        --end
        return M.private._table_tostring(v, indentLevel, printTableRefs, recursionTable)

    elseif "number" == type_v then
        -- eliminate differences in formatting between various Lua versions
        if v ~= v then
            return "#NaN" -- "not a number"
        end
        if v == math.huge then
            return "#Inf" -- "infinite"
        end
        if v == -math.huge then
            return "-#Inf"
        end
        if _VERSION == "Lua 5.3" then
            local i = math.tointeger(v)
            if i then
                return tostring(i)
            end
        end
    end

    return tostring(v)
end

local function prettystr( v )
    --[[ Pretty string conversion, to display the full content of a variable of any type.

    * string are enclosed with " by default, or with ' if string contains a "
    * tables are expanded to show their full content, with indentation in case of nested tables
    ]]--
    local recursionTable = {}
    local s = prettystr_sub(v, 1, M.PRINT_TABLE_REF_IN_ERROR_MSG, recursionTable)
    if recursionTable.recursionDetected and not M.PRINT_TABLE_REF_IN_ERROR_MSG then
        -- some table contain recursive references,
        -- so we must recompute the value by including all table references
        -- else the result looks like crap
        recursionTable = {}
        s = prettystr_sub(v, 1, true, recursionTable)
    end
    return s
end
M.prettystr = prettystr

function M.adjust_err_msg_with_iter( err_msg, iter_msg )
    --[[ Adjust the error message err_msg: trim the FAILURE_PREFIX or SUCCESS_PREFIX information if needed, 
    add the iteration message if any and return the result.

    err_msg:  string, error message captured with pcall
    iter_msg: a string describing the current iteration ("iteration N") or nil
              if there is no iteration in this test.

    Returns: (new_err_msg, test_status)
        new_err_msg: string, adjusted error message, or nil in case of success
        test_status: M.NodeStatus.FAIL, SUCCESS or ERROR according to the information
                     contained in the error message.
    ]]
    if iter_msg then
        iter_msg = iter_msg..', '
    else
        iter_msg = ''
    end

    local RE_FILE_LINE = '.*:%d+: '

    if (err_msg:find( M.SUCCESS_PREFIX ) == 1) or err_msg:match( '('..RE_FILE_LINE..')' .. M.SUCCESS_PREFIX .. ".*" ) then
        -- test finished early with success()
        return nil, M.NodeStatus.PASS
    end

    if (err_msg:find( M.FAILURE_PREFIX ) == 1) or (err_msg:match( '('..RE_FILE_LINE..')' .. M.FAILURE_PREFIX .. ".*" ) ~= nil) then
        -- substitute prefix by iteration message
        err_msg = err_msg:gsub(M.FAILURE_PREFIX, iter_msg, 1)
        -- print("failure detected")
        return err_msg, M.NodeStatus.FAIL
    else
        -- print("error detected")
        -- regular error, not a failure
        if iter_msg then
            local match
            -- "./test\\test_luaunit.lua:2241: some error msg
            match = err_msg:match( '(.*:%d+: ).*' ) 
            if match then
                err_msg = err_msg:gsub( match, match .. iter_msg )
            else
                -- no file:line: infromation, just add the iteration info at the beginning of the line
                err_msg = iter_msg .. err_msg
            end
        end
        return err_msg, M.NodeStatus.ERROR
    end
end

local function tryMismatchFormatting( table_a, table_b, doDeepAnalysis )
    --[[
    Prepares a nice error message when comparing tables, performing a deeper 
    analysis.

    Arguments:
    * table_a, table_b: tables to be compared
    * doDeepAnalysis:
        M.DEFAULT_DEEP_ANALYSIS: (the default if not specified) perform deep analysis only for big lists and big dictionnaries
        M.FORCE_DEEP_ANALYSIS  : always perform deep analysis
        M.DISABLE_DEEP_ANALYSIS: never perform deep analysis

    Returns: {success, result}
    * success: false if deep analysis could not be performed 
               in this case, just use standard assertion message
    * result: if success is true, a multi-line string with deep analysis of the two lists
    ]]

    -- check if table_a & table_b are suitable for deep analysis
    if type(table_a) ~= 'table' or type(table_b) ~= 'table' then
        return false
    end

    if doDeepAnalysis == M.DISABLE_DEEP_ANALYSIS then
        return false
    end

    local len_a, len_b, isPureList = #table_a, #table_b, true

    for k1, v1 in pairs(table_a) do
        if type(k1) ~= 'number' or k1 > len_a then
            -- this table a mapping
            isPureList = false
            break
        end
    end

    if isPureList then
        for k2, v2 in pairs(table_b) do
            if type(k2) ~= 'number' or k2 > len_b then
                -- this table a mapping
                isPureList = false
                break
            end
        end
    end

    if isPureList and math.min(len_a, len_b) < M.LIST_DIFF_ANALYSIS_THRESHOLD then
        if not (doDeepAnalysis == M.FORCE_DEEP_ANALYSIS) then
            return false
        end
    end

    if isPureList then
        return M.private.mismatchFormattingPureList( table_a, table_b )
    else
        -- only work on mapping for the moment
        -- return M.private.mismatchFormattingMapping( table_a, table_b, doDeepAnalysis )
        return false
    end
end
M.private.tryMismatchFormatting = tryMismatchFormatting

local function getTaTbDescr()
    if not M.ORDER_ACTUAL_EXPECTED then
        return 'expected', 'actual'
    end
    return 'actual', 'expected'
end

local function extendWithStrFmt( res, ... )
    table.insert( res, string.format( ... ) )
end

local function mismatchFormattingMapping( table_a, table_b, doDeepAnalysis )
    --[[
    Prepares a nice error message when comparing tables which are not pure lists, performing a deeper 
    analysis.

    Returns: {success, result}
    * success: false if deep analysis could not be performed 
               in this case, just use standard assertion message
    * result: if success is true, a multi-line string with deep analysis of the two lists
    ]]

    -- disable for the moment
    --[[
    local result = {}
    local descrTa, descrTb = getTaTbDescr()

    local keysCommon = {}
    local keysOnlyTa = {}
    local keysOnlyTb = {}
    local keysDiffTaTb = {}

    local k, v

    for k,v in pairs( table_a ) do
        if is_equal( v, table_b[k] ) then
            table.insert( keysCommon, k )
        else 
            if table_b[k] == nil then
                table.insert( keysOnlyTa, k )
            else
                table.insert( keysDiffTaTb, k )
            end
        end
    end

    for k,v in pairs( table_b ) do
        if not is_equal( v, table_a[k] ) and table_a[k] == nil then
            table.insert( keysOnlyTb, k )
        end
    end

    local len_a = #keysCommon + #keysDiffTaTb + #keysOnlyTa
    local len_b = #keysCommon + #keysDiffTaTb + #keysOnlyTb
    local limited_display = (len_a < 5 or len_b < 5)

    if math.min(len_a, len_b) < M.TABLE_DIFF_ANALYSIS_THRESHOLD then
        return false
    end

    if not limited_display then
        if len_a == len_b then
            extendWithStrFmt( result, 'Table A (%s) and B (%s) both have %d items', descrTa, descrTb, len_a )
        else
            extendWithStrFmt( result, 'Table A (%s) has %d items and table B (%s) has %d items', descrTa, len_a, descrTb, len_b )
            end

        if #keysCommon == 0 and #keysDiffTaTb == 0 then
            table.insert( result, 'Table A and B have no keys in common, they are totally different')
        else
            local s_other = 'other '
            if #keysCommon then
                extendWithStrFmt( result, 'Table A and B have %d identical items', #keysCommon )
            else
                table.insert( result, 'Table A and B have no identical items' )
                s_other = ''
            end

            if #keysDiffTaTb ~= 0 then
                result[#result] = string.format( '%s and %d items differing present in both tables', result[#result], #keysDiffTaTb)
            else
                result[#result] = string.format( '%s and no %sitems differing present in both tables', result[#result], s_other, #keysDiffTaTb)
            end
        end

        extendWithStrFmt( result, 'Table A has %d keys not present in table B and table B has %d keys not present in table A', #keysOnlyTa, #keysOnlyTb ) 
    end

    local function keytostring(k)
        if "string" == type(k) and k:match("^[_%a][_%w]*$") then
            return k
        end
        return prettystr(k)
    end

    if #keysDiffTaTb ~= 0 then
        table.insert( result, 'Items differing in A and B:')
        for k,v in sortedPairs( keysDiffTaTb ) do
            extendWithStrFmt( result, '  - A[%s]: %s', keytostring(v), prettystr(table_a[v]) )
            extendWithStrFmt( result, '  + B[%s]: %s', keytostring(v), prettystr(table_b[v]) )
        end
    end    

    if #keysOnlyTa ~= 0 then
        table.insert( result, 'Items only in table A:' )
        for k,v in sortedPairs( keysOnlyTa ) do
            extendWithStrFmt( result, '  - A[%s]: %s', keytostring(v), prettystr(table_a[v]) )
        end
    end

    if #keysOnlyTb ~= 0 then
        table.insert( result, 'Items only in table B:' )
        for k,v in sortedPairs( keysOnlyTb ) do
            extendWithStrFmt( result, '  + B[%s]: %s', keytostring(v), prettystr(table_b[v]) )
        end
    end

    if #keysCommon ~= 0 then
        table.insert( result, 'Items common to A and B:')
        for k,v in sortedPairs( keysCommon ) do
            extendWithStrFmt( result, '  = A and B [%s]: %s', keytostring(v), prettystr(table_a[v]) )
        end
    end    

    return true, table.concat( result, '\n')
    ]]
end
M.private.mismatchFormattingMapping = mismatchFormattingMapping

local function mismatchFormattingPureList( table_a, table_b )
    --[[
    Prepares a nice error message when comparing tables which are lists, performing a deeper 
    analysis.

    Returns: {success, result}
    * success: false if deep analysis could not be performed 
               in this case, just use standard assertion message
    * result: if success is true, a multi-line string with deep analysis of the two lists
    ]]
    local result, descrTa, descrTb = {}, getTaTbDescr()

    local len_a, len_b, refa, refb = #table_a, #table_b, '', ''
    if M.PRINT_TABLE_REF_IN_ERROR_MSG then
        refa, refb = string.format( '<%s> ', tostring(table_a)), string.format('<%s> ', tostring(table_b) )
    end
    local longest, shortest = math.max(len_a, len_b), math.min(len_a, len_b)
    local deltalv  = longest - shortest

    local commonUntil = shortest
    for i = 1, shortest do
        if not is_equal(table_a[i], table_b[i]) then
            commonUntil = i - 1
            break
        end
    end

    local commonBackTo = shortest - 1
    for i = 0, shortest - 1 do
        if not is_equal(table_a[len_a-i], table_b[len_b-i]) then
            commonBackTo = i - 1
            break
        end
    end


    table.insert( result, 'List difference analysis:' )    
    if len_a == len_b then
        -- TODO: handle expected/actual naming
        extendWithStrFmt( result, '* lists %sA (%s) and %sB (%s) have the same size', refa, descrTa, refb, descrTb )
    else 
        extendWithStrFmt( result, '* list sizes differ: list %sA (%s) has %d items, list %sB (%s) has %d items', refa, descrTa, len_a, refb, descrTb, len_b )
    end

    extendWithStrFmt( result, '* lists A and B start differing at index %d', commonUntil+1 ) 
    if commonBackTo >= 0 then
        if deltalv > 0 then
            extendWithStrFmt( result, '* lists A and B are equal again from index %d for A, %d for B', len_a-commonBackTo, len_b-commonBackTo )
        else
            extendWithStrFmt( result, '* lists A and B are equal again from index %d', len_a-commonBackTo )
        end
    end

    local function insertABValue(ai, bi)
        bi = bi or ai
        if is_equal( table_a[ai], table_b[bi]) then
            return extendWithStrFmt( result, '  = A[%d], B[%d]: %s', ai, bi, prettystr(table_a[ai]) )
        else
            extendWithStrFmt( result, '  - A[%d]: %s', ai, prettystr(table_a[ai]))
            extendWithStrFmt( result, '  + B[%d]: %s', bi, prettystr(table_b[bi]))
        end
    end

    -- common parts to list A & B, at the beginning
    if commonUntil > 0 then
        table.insert( result, '* Common parts:' )
        for i = 1, commonUntil do
            insertABValue( i )
        end
    end

    -- diffing parts to list A & B
    if commonUntil < shortest - commonBackTo - 1 then
        table.insert( result, '* Differing parts:' )
        for i = commonUntil + 1, shortest - commonBackTo - 1 do
            insertABValue( i )
        end
    end

    -- display indexes of one list, with no match on other list
    if shortest - commonBackTo <= longest - commonBackTo - 1 then
        table.insert( result, '* Present only in one list:' )
        for i = shortest - commonBackTo, longest - commonBackTo - 1 do
            if len_a > len_b then
                extendWithStrFmt( result, '  - A[%d]: %s', i, prettystr(table_a[i]) )
                -- table.insert( result, '+ (no matching B index)')
            else
                -- table.insert( result, '- no matching A index')
                extendWithStrFmt( result, '  + B[%d]: %s', i, prettystr(table_b[i]) )
            end
        end
    end

    -- common parts to list A & B, at the end
    if commonBackTo >= 0 then
        table.insert( result, '* Common parts at the end of the lists' )
        for i = longest - commonBackTo, longest do
            if len_a > len_b then
                insertABValue( i, i-deltalv )
            else
                insertABValue( i-deltalv, i )
            end
        end
    end

    return true, table.concat( result, '\n')
end
M.private.mismatchFormattingPureList = mismatchFormattingPureList

local function prettystrPairs(value1, value2, suffix_a, suffix_b)
    --[[
    This function helps with the recurring task of constructing the "expected
    vs. actual" error messages. It takes two arbitrary values and formats
    corresponding strings with prettystr().

    To keep the (possibly complex) output more readable in case the resulting
    strings contain line breaks, they get automatically prefixed with additional
    newlines. Both suffixes are optional (default to empty strings), and get
    appended to the "value1" string. "suffix_a" is used if line breaks were
    encountered, "suffix_b" otherwise.

    Returns the two formatted strings (including padding/newlines).
    ]]
    local str1, str2 = prettystr(value1), prettystr(value2)
    if hasNewLine(str1) or hasNewLine(str2) then
        -- line break(s) detected, add padding
        return "\n" .. str1 .. (suffix_a or ""), "\n" .. str2
    end
    return str1 .. (suffix_b or ""), str2
end
M.private.prettystrPairs = prettystrPairs

local function _table_raw_tostring( t )
    -- return the default tostring() for tables, with the table ID, even if the table has a metatable
    -- with the __tostring converter
    local mt = getmetatable( t )
    if mt then setmetatable( t, nil ) end
    local ref = tostring(t)
    if mt then setmetatable( t, mt ) end
    return ref
end
M.private._table_raw_tostring = _table_raw_tostring

local TABLE_TOSTRING_SEP = ", "
local TABLE_TOSTRING_SEP_LEN = string.len(TABLE_TOSTRING_SEP)

local function _table_tostring( tbl, indentLevel, printTableRefs, recursionTable )
    printTableRefs = printTableRefs or M.PRINT_TABLE_REF_IN_ERROR_MSG
    recursionTable = recursionTable or {}
    recursionTable[tbl] = true

    local result, dispOnMultLines = {}, false

    -- like prettystr but do not enclose with "" if the string is just alphanumerical
    -- this is better for displaying table keys who are often simple strings
    local function keytostring(k)
        if "string" == type(k) and k:match("^[_%a][_%w]*$") then
            return k
        end
        return prettystr_sub(k, indentLevel+1, printTableRefs, recursionTable)
    end

    local mt = getmetatable( tbl )

    if mt and mt.__tostring then
        -- if table has a __tostring() function in its metatable, use it to display the table
        -- else, compute a regular table
        result = strsplit( '\n', tostring(tbl) )
        return M.private._table_tostring_format_multiline_string( result, indentLevel )

    else
        -- no metatable, compute the table representation

        local entry, count, seq_index = nil, 0, 1
        for k, v in sortedPairs( tbl ) do

            -- key part
            if k == seq_index then
                -- for the sequential part of tables, we'll skip the "<key>=" output
                entry = ''
                seq_index = seq_index + 1
            elseif recursionTable[k] then
                -- recursion in the key detected
                recursionTable.recursionDetected = true
                entry = "<".._table_raw_tostring(k)..">="
            else
                entry = keytostring(k) .. "="
            end

            -- value part 
            if recursionTable[v] then
                -- recursion in the value detected!
                recursionTable.recursionDetected = true
                entry = entry .. "<".._table_raw_tostring(v)..">"
            else
                entry = entry ..
                    prettystr_sub( v, indentLevel+1, printTableRefs, recursionTable )
            end
            count = count + 1
            result[count] = entry
        end
        return M.private._table_tostring_format_result( tbl, result, indentLevel, printTableRefs )
    end

end
M.private._table_tostring = _table_tostring -- prettystr_sub() needs it

local function _table_tostring_format_multiline_string( tbl_str, indentLevel )
    local indentString = '\n'..string.rep("    ", indentLevel - 1)
    return table.concat( tbl_str, indentString )

end
M.private._table_tostring_format_multiline_string = _table_tostring_format_multiline_string


local function _table_tostring_format_result( tbl, result, indentLevel, printTableRefs )
    -- final function called in _table_to_string() to format the resulting list of 
    -- string describing the table.

    local dispOnMultLines = false

    -- set dispOnMultLines to true if the maximum LINE_LENGTH would be exceeded with the values
    local totalLength = 0
    for k, v in ipairs( result ) do
        totalLength = totalLength + string.len( v )
        if totalLength >= M.LINE_LENGTH then
            dispOnMultLines = true
            break
        end
    end

    -- set dispOnMultLines to true if the max LINE_LENGTH would be exceeded
    -- with the values and the separators.
    if not dispOnMultLines then
        -- adjust with length of separator(s):
        -- two items need 1 sep, three items two seps, ... plus len of '{}'
        if #result > 0 then
            totalLength = totalLength + TABLE_TOSTRING_SEP_LEN * (#result - 1)
        end
        dispOnMultLines = (totalLength + 2 >= M.LINE_LENGTH)
    end

    -- now reformat the result table (currently holding element strings)
    if dispOnMultLines then
        local indentString = string.rep("    ", indentLevel - 1)
        result = {  
                    "{\n    ", 
                    indentString,
                    table.concat(result, ",\n    " .. indentString), 
                    "\n",
                    indentString, 
                    "}"
                }
    else
        result = {"{", table.concat(result, TABLE_TOSTRING_SEP), "}"}
    end
    if printTableRefs then
        table.insert(result, 1, "<".._table_raw_tostring(tbl).."> ") -- prepend table ref
    end
    return table.concat(result)
end
M.private._table_tostring_format_result = _table_tostring_format_result -- prettystr_sub() needs it

local function _table_contains(t, element)
    if type(t) == "table" then
        local type_e = type(element)
        for _, value in pairs(t) do
            if type(value) == type_e then
                if value == element then
                    return true
                end
                if type_e == 'table' then
                    -- if we wanted recursive items content comparison, we could use
                    -- _is_table_items_equals(v, expected) but one level of just comparing
                    -- items is sufficient
                    if M.private._is_table_equals( value, element ) then
                        return true
                    end
                end
            end
        end
    end
    return false
end

local function _is_table_items_equals(actual, expected )
    local type_a, type_e = type(actual), type(expected)

    if (type_a == 'table') and (type_e == 'table') then
        for k, v in pairs(actual) do
            if not _table_contains(expected, v) then
                return false
            end
        end
        for k, v in pairs(expected) do
            if not _table_contains(actual, v) then
                return false
            end
        end
        return true

    elseif type_a ~= type_e then
        return false

    elseif actual ~= expected then
        return false
    end

    return true
end

--[[
This is a specialized metatable to help with the bookkeeping of recursions
in _is_table_equals(). It provides an __index table that implements utility
functions for easier management of the table. The "cached" method queries
the state of a specific (actual,expected) pair; and the "store" method sets
this state to the given value. The state of pairs not "seen" / visited is
assumed to be `nil`.
]]
local _recursion_cache_MT = {
    __index = {
        -- Return the cached value for an (actual,expected) pair (or `nil`)
        cached = function(t, actual, expected)
            local subtable = t[actual] or {}
            return subtable[expected]
        end,

        -- Store cached value for a specific (actual,expected) pair.
        -- Returns the value, so it's easy to use for a "tailcall" (return ...).
        store = function(t, actual, expected, value, asymmetric)
            local subtable = t[actual]
            if not subtable then
                subtable = {}
                t[actual] = subtable
            end
            subtable[expected] = value

            -- Unless explicitly marked "asymmetric": Consider the recursion
            -- on (expected,actual) to be equivalent to (actual,expected) by
            -- default, and thus cache the value for both.
            if not asymmetric then
                t:store(expected, actual, value, true)
            end

            return value
        end
    }
}

local function _is_table_equals(actual, expected, recursions)
    local type_a, type_e = type(actual), type(expected)
    recursions = recursions or setmetatable({}, _recursion_cache_MT)

    if type_a ~= type_e then
        return false -- different types won't match
    end

    if (type_a == 'table') --[[ and (type_e == 'table') ]] then
        if actual == expected then
            -- Both reference the same table, so they are actually identical
            return recursions:store(actual, expected, true)
        end

        -- If we've tested this (actual,expected) pair before: return cached value
        local previous = recursions:cached(actual, expected)
        if previous ~= nil then
            return previous
        end

        -- Mark this (actual,expected) pair, so we won't recurse it again. For
        -- now, assume a "false" result, which we might adjust later if needed.
        recursions:store(actual, expected, false)

        -- Tables must have identical element count, or they can't match.
        if (#actual ~= #expected) then
            return false
        end

        local actualKeysMatched, actualTableKeys = {}, {}

        for k, v in pairs(actual) do
            if M.TABLE_EQUALS_KEYBYCONTENT and type(k) == "table" then
                -- If the keys are tables, things get a bit tricky here as we
                -- can have _is_table_equals(t[k1], t[k2]) despite k1 ~= k2. So
                -- we first collect table keys from "actual", and then later try
                -- to match each table key from "expected" to actualTableKeys.
                table.insert(actualTableKeys, k)
            else
                if not _is_table_equals(v, expected[k], recursions) then
                    return false -- Mismatch on value, tables can't be equal
                end
                actualKeysMatched[k] = true -- Keep track of matched keys
            end
        end

        for k, v in pairs(expected) do
            if M.TABLE_EQUALS_KEYBYCONTENT and type(k) == "table" then
                local found = false
                -- Note: DON'T use ipairs() here, table may be non-sequential!
                for i, candidate in pairs(actualTableKeys) do
                    if _is_table_equals(candidate, k, recursions) then
                        if _is_table_equals(actual[candidate], v, recursions) then
                            found = true
                            -- Remove the candidate we matched against from the list
                            -- of table keys, so each key in actual can only match
                            -- one key in expected.
                            actualTableKeys[i] = nil
                            break
                        end
                        -- keys match but values don't, keep searching
                    end
                end
                if not found then
                    return false -- no matching (key,value) pair
                end
            else
                if not actualKeysMatched[k] then
                    -- Found a key that we did not see in "actual" -> mismatch
                    return false
                end
                -- Otherwise actual[k] was already matched against v = expected[k].
            end
        end

        if next(actualTableKeys) then
            -- If there is any key left in actualTableKeys, then that is
            -- a table-type key in actual with no matching counterpart
            -- (in expected), and so the tables aren't equal.
            return false
        end

        -- The tables are actually considered equal, update cache and return result
        return recursions:store(actual, expected, true)

    elseif actual ~= expected then
        return false
    end

    return true
end
M.private._is_table_equals = _is_table_equals
is_equal = _is_table_equals

local function failure(main_msg, extra_msg_or_nil, level)
    -- raise an error indicating a test failure
    -- for error() compatibility we adjust "level" here (by +1), to report the
    -- calling context
    local msg
    if type(extra_msg_or_nil) == 'string' and extra_msg_or_nil:len() > 0 then
        msg = extra_msg_or_nil .. '\n' .. main_msg
    else
        msg = main_msg
    end
    error(M.FAILURE_PREFIX .. msg, (level or 1) + 1)
end

local function fail_fmt(level, extra_msg_or_nil, ...)
     -- failure with printf-style formatted message and given error level
    failure(string.format(...), extra_msg_or_nil, (level or 1) + 1)
end
M.private.fail_fmt = fail_fmt

local function error_fmt(level, ...)
     -- printf-style error()
    error(string.format(...), (level or 1) + 1)
end

----------------------------------------------------------------
--
--                     assertions
--
----------------------------------------------------------------

local function errorMsgEquality(actual, expected, doDeepAnalysis)

    if not M.ORDER_ACTUAL_EXPECTED then
        expected, actual = actual, expected
    end
    if type(expected) == 'string' or type(expected) == 'table' then
        local strExpected, strActual = prettystrPairs(expected, actual)
        local result = string.format("expected: %s\nactual: %s", strExpected, strActual)

        -- extend with mismatch analysis if possible:
        local success, mismatchResult
        success, mismatchResult = tryMismatchFormatting( actual, expected, doDeepAnalysis )
        if success then 
            result = table.concat( { result, mismatchResult }, '\n' )
        end
        return result
    end
    return string.format("expected: %s, actual: %s",
                         prettystr(expected), prettystr(actual))
end

function M.assertError(f, ...)
    -- assert that calling f with the arguments will raise an error
    -- example: assertError( f, 1, 2 ) => f(1,2) should generate an error
    if pcall( f, ... ) then
        failure( "Expected an error when calling function but no error generated", nil, 2 )
    end
end

function M.fail( msg )
    -- stops a test due to a failure
    failure( msg, nil, 2 )
end

function M.failIf( cond, msg )
    -- Fails a test with "msg" if condition is true
    if cond then
        failure( msg, nil, 2 )
    end
end

function M.success()
    -- stops a test with a success
    error(M.SUCCESS_PREFIX, 2)
end

function M.successIf( cond )
    -- stops a test with a success if condition is met
    if cond then
        error(M.SUCCESS_PREFIX, 2)
    end
end


------------------------------------------------------------------
--                  Equality assertions
------------------------------------------------------------------

function M.assertEquals(actual, expected, extra_msg_or_nil, doDeepAnalysis)
    if type(actual) == 'table' and type(expected) == 'table' then
        if not _is_table_equals(actual, expected) then
            failure( errorMsgEquality(actual, expected, doDeepAnalysis), extra_msg_or_nil, 2 )
        end
    elseif type(actual) ~= type(expected) then
        failure( errorMsgEquality(actual, expected), extra_msg_or_nil, 2 )
    elseif actual ~= expected then
        failure( errorMsgEquality(actual, expected), extra_msg_or_nil, 2 )
    end
end

function M.almostEquals( actual, expected, margin )
    if type(actual) ~= 'number' or type(expected) ~= 'number' or type(margin) ~= 'number' then
        error_fmt(3, 'almostEquals: must supply only number arguments.\nArguments supplied: %s, %s, %s',
            prettystr(actual), prettystr(expected), prettystr(margin))
    end
    if margin < 0 then
        error('almostEquals: margin must not be negative, current value is ' .. margin, 3)
    end
    return math.abs(expected - actual) <= margin
end

function M.assertAlmostEquals( actual, expected, margin, extra_msg_or_nil )
    -- check that two floats are close by margin
    margin = margin or M.EPS
    if not M.almostEquals(actual, expected, margin) then
        if not M.ORDER_ACTUAL_EXPECTED then
            expected, actual = actual, expected
        end
        local delta = math.abs(actual - expected) 
        fail_fmt(2, extra_msg_or_nil, 'Values are not almost equal\n' ..
                    'Actual: %s, expected: %s, delta %s above margin of %s',
                    actual, expected, delta, margin)
    end
end

function M.assertNotEquals(actual, expected, extra_msg_or_nil)
    if type(actual) ~= type(expected) then
        return
    end

    if type(actual) == 'table' and type(expected) == 'table' then
        if not _is_table_equals(actual, expected) then
            return
        end
    elseif actual ~= expected then
        return
    end
    fail_fmt(2, extra_msg_or_nil, 'Received the not expected value: %s', prettystr(actual))
end

function M.assertNotAlmostEquals( actual, expected, margin, extra_msg_or_nil )
    -- check that two floats are not close by margin
    margin = margin or M.EPS
    if M.almostEquals(actual, expected, margin) then
        if not M.ORDER_ACTUAL_EXPECTED then
            expected, actual = actual, expected
        end
        local delta = math.abs(actual - expected)
        fail_fmt(2, extra_msg_or_nil, 'Values are almost equal\nActual: %s, expected: %s' ..
                    ', delta %s below margin of %s',
                    actual, expected, delta, margin)
    end
end

function M.assertItemsEquals(actual, expected, extra_msg_or_nil)
    -- checks that the items of table expected
    -- are contained in table actual. Warning, this function
    -- is at least O(n^2)
    if not _is_table_items_equals(actual, expected ) then
        expected, actual = prettystrPairs(expected, actual)
        fail_fmt(2, extra_msg_or_nil, 'Content of the tables are not identical:\nExpected: %s\nActual: %s',
                 expected, actual)
    end
end

------------------------------------------------------------------
--                  String assertion
------------------------------------------------------------------

function M.assertStrContains( str, sub, isPattern, extra_msg_or_nil )
    -- this relies on lua string.find function
    -- a string always contains the empty string
    if not string.find(str, sub, 1, not isPattern) then
        sub, str = prettystrPairs(sub, str, '\n')
        fail_fmt(2, extra_msg_or_nil, 'Could not find %s %s in string %s',
                 isPattern and 'pattern' or 'substring', sub, str)
    end
end

function M.assertStrIContains( str, sub, extra_msg_or_nil )
    -- this relies on lua string.find function
    -- a string always contains the empty string
    if not string.find(str:lower(), sub:lower(), 1, true) then
        sub, str = prettystrPairs(sub, str, '\n')
        fail_fmt(2, extra_msg_or_nil, 'Could not find (case insensitively) substring %s in string %s',
                 sub, str)
    end
end

function M.assertNotStrContains( str, sub, isPattern, extra_msg_or_nil )
    -- this relies on lua string.find function
    -- a string always contains the empty string
    if string.find(str, sub, 1, not isPattern) then
        sub, str = prettystrPairs(sub, str, '\n')
        fail_fmt(2, extra_msg_or_nil, 'Found the not expected %s %s in string %s',
                 isPattern and 'pattern' or 'substring', sub, str)
    end
end

function M.assertNotStrIContains( str, sub, extra_msg_or_nil )
    -- this relies on lua string.find function
    -- a string always contains the empty string
    if string.find(str:lower(), sub:lower(), 1, true) then
        sub, str = prettystrPairs(sub, str, '\n')
        fail_fmt(2, extra_msg_or_nil, 'Found (case insensitively) the not expected substring %s in string %s',
                 sub, str)
    end
end

function M.assertStrMatches( str, pattern, start, final, extra_msg_or_nil )
    -- Verify a full match for the string
    if not strMatch( str, pattern, start, final ) then
        pattern, str = prettystrPairs(pattern, str, '\n')
        fail_fmt(2, extra_msg_or_nil, 'Could not match pattern %s with string %s',
                 pattern, str)
    end
end

function M.assertErrorMsgEquals( expectedMsg, func, ... )
    -- assert that calling f with the arguments will raise an error
    -- example: assertError( f, 1, 2 ) => f(1,2) should generate an error
    local no_error, error_msg = pcall( func, ... )
    if no_error then
        failure( 'No error generated when calling function but expected error: '..M.prettystr(expectedMsg), nil, 2 )
    end
    if type(expectedMsg) == "string" and type(error_msg) ~= "string" then
        -- table are converted to string automatically
        error_msg = tostring(error_msg)
    end
    local differ = false
    if error_msg ~= expectedMsg then
        local tr = type(error_msg)
        local te = type(expectedMsg)
        if te == 'table' then
            if tr ~= 'table' then
                differ = true
            else
                 local ok = pcall(M.assertItemsEquals, error_msg, expectedMsg)
                 if not ok then
                     differ = true
                 end
            end
        else
           differ = true
        end
    end

    if differ then
        error_msg, expectedMsg = prettystrPairs(error_msg, expectedMsg)
        fail_fmt(2, nil, 'Error message expected: %s\nError message received: %s\n',
                 expectedMsg, error_msg)
    end
end

function M.assertErrorMsgContains( partialMsg, func, ... )
    -- assert that calling f with the arguments will raise an error
    -- example: assertError( f, 1, 2 ) => f(1,2) should generate an error
    local no_error, error_msg = pcall( func, ... )
    if no_error then
        failure( 'No error generated when calling function but expected error containing: '..prettystr(partialMsg), nil, 2 )
    end
    if type(error_msg) ~= "string" then
        error_msg = tostring(error_msg)
    end
    if not string.find( error_msg, partialMsg, nil, true ) then
        error_msg, partialMsg = prettystrPairs(error_msg, partialMsg)
        fail_fmt(2, nil, 'Error message does not contain: %s\nError message received: %s\n',
                 partialMsg, error_msg)
    end
end

function M.assertErrorMsgMatches( expectedMsg, func, ... )
    -- assert that calling f with the arguments will raise an error
    -- example: assertError( f, 1, 2 ) => f(1,2) should generate an error
    local no_error, error_msg = pcall( func, ... )
    if no_error then
        failure( 'No error generated when calling function but expected error matching: "'..expectedMsg..'"', nil, 2 )
    end
    if type(error_msg) ~= "string" then
        error_msg = tostring(error_msg)
    end
    if not strMatch( error_msg, expectedMsg ) then
        expectedMsg, error_msg = prettystrPairs(expectedMsg, error_msg)
        fail_fmt(2, nil, 'Error message does not match pattern: %s\nError message received: %s\n',
                 expectedMsg, error_msg)
    end
end

------------------------------------------------------------------
--              Type assertions
------------------------------------------------------------------

function M.assertEvalToTrue(value, extra_msg_or_nil)
    if not value then
        failure("expected: a value evaluating to true, actual: " ..prettystr(value), extra_msg_or_nil, 2)
    end
end

function M.assertEvalToFalse(value, extra_msg_or_nil)
    if value then
        failure("expected: false or nil, actual: " ..prettystr(value), extra_msg_or_nil, 2)
    end
end

function M.assertIsTrue(value, extra_msg_or_nil)
    if value ~= true then
        failure("expected: true, actual: " ..prettystr(value), extra_msg_or_nil, 2)
    end
end

function M.assertNotIsTrue(value, extra_msg_or_nil)
    if value == true then
        failure("expected: not true, actual: " ..prettystr(value), extra_msg_or_nil, 2)
    end
end

function M.assertIsFalse(value, extra_msg_or_nil)
    if value ~= false then
        failure("expected: false, actual: " ..prettystr(value), extra_msg_or_nil, 2)
    end
end

function M.assertNotIsFalse(value, extra_msg_or_nil)
    if value == false then
        failure("expected: not false, actual: " ..prettystr(value), extra_msg_or_nil, 2)
    end
end

function M.assertIsNil(value, extra_msg_or_nil)
    if value ~= nil then
        failure("expected: nil, actual: " ..prettystr(value), extra_msg_or_nil, 2)
    end
end

function M.assertNotIsNil(value, extra_msg_or_nil)
    if value == nil then
        failure("expected: not nil, actual: nil", extra_msg_or_nil, 2)
    end
end

--[[
Add type assertion functions to the module table M. Each of these functions
takes a single parameter "value", and checks that its Lua type matches the
expected string (derived from the function name):

M.assertIsXxx(value) -> ensure that type(value) conforms to "xxx"
]]
for _, funcName in ipairs(
    {'assertIsNumber', 'assertIsString', 'assertIsTable', 'assertIsBoolean',
     'assertIsFunction', 'assertIsUserdata', 'assertIsThread'}
) do
    local typeExpected = funcName:match("^assertIs([A-Z]%a*)$")
    -- Lua type() always returns lowercase, also make sure the match() succeeded
    typeExpected = typeExpected and typeExpected:lower()
                   or error("bad function name '"..funcName.."' for type assertion")

    M[funcName] = function(value, extra_msg_or_nil)
        if type(value) ~= typeExpected then
            if type(value) == 'nil' then
                fail_fmt(2, extra_msg_or_nil, 'expected: a %s value, actual: nil',
                         typeExpected, type(value), prettystrPairs(value))
            else
                fail_fmt(2, extra_msg_or_nil, 'expected: a %s value, actual: type %s, value %s',
                         typeExpected, type(value), prettystrPairs(value))
            end
        end
    end
end

--[[
Add shortcuts for verifying type of a variable, without failure (luaunit v2 compatibility)
M.isXxx(value) -> returns true if type(value) conforms to "xxx"
]]
for _, typeExpected in ipairs(
    {'Number', 'String', 'Table', 'Boolean',
     'Function', 'Userdata', 'Thread', 'Nil' }
) do
    local typeExpectedLower = typeExpected:lower()
    local isType = function(value)
        return (type(value) == typeExpectedLower)
    end
    M['is'..typeExpected] = isType
    M['is_'..typeExpectedLower] = isType
end

--[[
Add non-type assertion functions to the module table M. Each of these functions
takes a single parameter "value", and checks that its Lua type differs from the
expected string (derived from the function name):

M.assertNotIsXxx(value) -> ensure that type(value) is not "xxx"
]]
for _, funcName in ipairs(
    {'assertNotIsNumber', 'assertNotIsString', 'assertNotIsTable', 'assertNotIsBoolean',
     'assertNotIsFunction', 'assertNotIsUserdata', 'assertNotIsThread'}
) do
    local typeUnexpected = funcName:match("^assertNotIs([A-Z]%a*)$")
    -- Lua type() always returns lowercase, also make sure the match() succeeded
    typeUnexpected = typeUnexpected and typeUnexpected:lower()
                   or error("bad function name '"..funcName.."' for type assertion")

    M[funcName] = function(value, extra_msg_or_nil)
        if type(value) == typeUnexpected then
            fail_fmt(2, extra_msg_or_nil, 'expected: not a %s type, actual: value %s',
                     typeUnexpected, prettystrPairs(value))
        end
    end
end

function M.assertIs(actual, expected, extra_msg_or_nil)
    if actual ~= expected then
        if not M.ORDER_ACTUAL_EXPECTED then
            actual, expected = expected, actual
        end
        expected, actual = prettystrPairs(expected, actual, '\n', '')
        fail_fmt(2, extra_msg_or_nil, 'expected and actual object should not be different\nExpected: %s\nReceived: %s',
                 expected, actual)
    end
end

function M.assertNotIs(actual, expected, extra_msg_or_nil)
    if actual == expected then
        if not M.ORDER_ACTUAL_EXPECTED then
            expected = actual
        end
        fail_fmt(2, extra_msg_or_nil, 'expected and actual object should be different: %s',
                 prettystrPairs(expected))
    end
end


------------------------------------------------------------------
--              Scientific assertions
------------------------------------------------------------------


function M.assertIsNaN(value, extra_msg_or_nil)
    if type(value) ~= "number" or value == value then
        failure("expected: NaN, actual: " ..prettystr(value), extra_msg_or_nil, 2)
    end
end

function M.assertNotIsNaN(value, extra_msg_or_nil)
    if type(value) == "number" and value ~= value then
        failure("expected: not NaN, actual: NaN", extra_msg_or_nil, 2)
    end
end

function M.assertIsInf(value, extra_msg_or_nil)
    if type(value) ~= "number" or math.abs(value) ~= math.huge then
        failure("expected: #Inf, actual: " ..prettystr(value), extra_msg_or_nil, 2)
    end
end

function M.assertIsPlusInf(value, extra_msg_or_nil)
    if type(value) ~= "number" or value ~= math.huge then
        failure("expected: #Inf, actual: " ..prettystr(value), extra_msg_or_nil, 2)
    end
end

function M.assertIsMinusInf(value, extra_msg_or_nil)
    if type(value) ~= "number" or value ~= -math.huge then
        failure("expected: -#Inf, actual: " ..prettystr(value), extra_msg_or_nil, 2)
    end
end

function M.assertNotIsPlusInf(value, extra_msg_or_nil)
    if type(value) == "number" and value == math.huge then
        failure("expected: not #Inf, actual: #Inf", extra_msg_or_nil, 2)
    end
end

function M.assertNotIsMinusInf(value, extra_msg_or_nil)
    if type(value) == "number" and value == -math.huge then
        failure("expected: not -#Inf, actual: -#Inf", extra_msg_or_nil, 2)
    end
end

function M.assertNotIsInf(value, extra_msg_or_nil)
    if type(value) == "number" and math.abs(value) == math.huge then
        failure("expected: not infinity, actual: " .. prettystr(value), extra_msg_or_nil, 2)
    end
end

function M.assertIsPlusZero(value, extra_msg_or_nil)
    if type(value) ~= 'number' or value ~= 0 then
        failure("expected: +0.0, actual: " ..prettystr(value), extra_msg_or_nil, 2)
    else if (1/value == -math.huge) then
            -- more precise error diagnosis
            failure("expected: +0.0, actual: -0.0", extra_msg_or_nil, 2)
        else if (1/value ~= math.huge) then
                -- strange, case should have already been covered
                failure("expected: +0.0, actual: " ..prettystr(value), extra_msg_or_nil, 2)
            end
        end
    end
end

function M.assertIsMinusZero(value, extra_msg_or_nil)
    if type(value) ~= 'number' or value ~= 0 then
        failure("expected: -0.0, actual: " ..prettystr(value), extra_msg_or_nil, 2)
    else if (1/value == math.huge) then
            -- more precise error diagnosis
            failure("expected: -0.0, actual: +0.0", extra_msg_or_nil, 2)
        else if (1/value ~= -math.huge) then
                -- strange, case should have already been covered
                failure("expected: -0.0, actual: " ..prettystr(value), extra_msg_or_nil, 2)
            end
        end
    end
end

function M.assertNotIsPlusZero(value, extra_msg_or_nil)
    if type(value) == 'number' and (1/value == math.huge) then
        failure("expected: not +0.0, actual: +0.0", extra_msg_or_nil, 2)
    end
end

function M.assertNotIsMinusZero(value, extra_msg_or_nil)
    if type(value) == 'number' and (1/value == -math.huge) then
        failure("expected: not -0.0, actual: -0.0", extra_msg_or_nil, 2)
    end
end

----------------------------------------------------------------
--                     Compatibility layer
----------------------------------------------------------------

-- for compatibility with LuaUnit v2.x
function M.wrapFunctions()
    -- In LuaUnit version <= 2.1 , this function was necessary to include
    -- a test function inside the global test suite. Nowadays, the functions
    -- are simply run directly as part of the test discovery process.
    -- so just do nothing !
    io.stderr:write[[Use of WrapFunctions() is no longer needed.
Just prefix your test function names with "test" or "Test" and they
will be picked up and run by LuaUnit.
]]
end

local list_of_funcs = {
    -- { official function name , alias }

    -- general assertions
    { 'assertEquals'            , 'assert_equals' },
    { 'assertItemsEquals'       , 'assert_items_equals' },
    { 'assertNotEquals'         , 'assert_not_equals' },
    { 'assertAlmostEquals'      , 'assert_almost_equals' },
    { 'assertNotAlmostEquals'   , 'assert_not_almost_equals' },
    { 'assertEvalToTrue'        , 'assert_eval_to_true' },
    { 'assertEvalToFalse'       , 'assert_eval_to_false' },
    { 'assertStrContains'       , 'assert_str_contains' },
    { 'assertStrIContains'      , 'assert_str_icontains' },
    { 'assertNotStrContains'    , 'assert_not_str_contains' },
    { 'assertNotStrIContains'   , 'assert_not_str_icontains' },
    { 'assertStrMatches'        , 'assert_str_matches' },
    { 'assertError'             , 'assert_error' },
    { 'assertErrorMsgEquals'    , 'assert_error_msg_equals' },
    { 'assertErrorMsgContains'  , 'assert_error_msg_contains' },
    { 'assertErrorMsgMatches'   , 'assert_error_msg_matches' },
    { 'assertIs'                , 'assert_is' },
    { 'assertNotIs'             , 'assert_not_is' },
    { 'wrapFunctions'           , 'WrapFunctions' },
    { 'wrapFunctions'           , 'wrap_functions' },

    -- type assertions: assertIsXXX -> assert_is_xxx
    { 'assertIsNumber'          , 'assert_is_number' },
    { 'assertIsString'          , 'assert_is_string' },
    { 'assertIsTable'           , 'assert_is_table' },
    { 'assertIsBoolean'         , 'assert_is_boolean' },
    { 'assertIsNil'             , 'assert_is_nil' },
    { 'assertIsTrue'            , 'assert_is_true' },
    { 'assertIsFalse'           , 'assert_is_false' },
    { 'assertIsNaN'             , 'assert_is_nan' },
    { 'assertIsInf'             , 'assert_is_inf' },
    { 'assertIsPlusInf'         , 'assert_is_plus_inf' },
    { 'assertIsMinusInf'        , 'assert_is_minus_inf' },
    { 'assertIsPlusZero'        , 'assert_is_plus_zero' },
    { 'assertIsMinusZero'       , 'assert_is_minus_zero' },
    { 'assertIsFunction'        , 'assert_is_function' },
    { 'assertIsThread'          , 'assert_is_thread' },
    { 'assertIsUserdata'        , 'assert_is_userdata' },

    -- type assertions: assertIsXXX -> assertXxx
    { 'assertIsNumber'          , 'assertNumber' },
    { 'assertIsString'          , 'assertString' },
    { 'assertIsTable'           , 'assertTable' },
    { 'assertIsBoolean'         , 'assertBoolean' },
    { 'assertIsNil'             , 'assertNil' },
    { 'assertIsTrue'            , 'assertTrue' },
    { 'assertIsFalse'           , 'assertFalse' },
    { 'assertIsNaN'             , 'assertNaN' },
    { 'assertIsInf'             , 'assertInf' },
    { 'assertIsPlusInf'         , 'assertPlusInf' },
    { 'assertIsMinusInf'        , 'assertMinusInf' },
    { 'assertIsPlusZero'        , 'assertPlusZero' },
    { 'assertIsMinusZero'       , 'assertMinusZero'},
    { 'assertIsFunction'        , 'assertFunction' },
    { 'assertIsThread'          , 'assertThread' },
    { 'assertIsUserdata'        , 'assertUserdata' },

    -- type assertions: assertIsXXX -> assert_xxx (luaunit v2 compat)
    { 'assertIsNumber'          , 'assert_number' },
    { 'assertIsString'          , 'assert_string' },
    { 'assertIsTable'           , 'assert_table' },
    { 'assertIsBoolean'         , 'assert_boolean' },
    { 'assertIsNil'             , 'assert_nil' },
    { 'assertIsTrue'            , 'assert_true' },
    { 'assertIsFalse'           , 'assert_false' },
    { 'assertIsNaN'             , 'assert_nan' },
    { 'assertIsInf'             , 'assert_inf' },
    { 'assertIsPlusInf'         , 'assert_plus_inf' },
    { 'assertIsMinusInf'        , 'assert_minus_inf' },
    { 'assertIsPlusZero'        , 'assert_plus_zero' },
    { 'assertIsMinusZero'       , 'assert_minus_zero' },
    { 'assertIsFunction'        , 'assert_function' },
    { 'assertIsThread'          , 'assert_thread' },
    { 'assertIsUserdata'        , 'assert_userdata' },

    -- type assertions: assertNotIsXXX -> assert_not_is_xxx
    { 'assertNotIsNumber'       , 'assert_not_is_number' },
    { 'assertNotIsString'       , 'assert_not_is_string' },
    { 'assertNotIsTable'        , 'assert_not_is_table' },
    { 'assertNotIsBoolean'      , 'assert_not_is_boolean' },
    { 'assertNotIsNil'          , 'assert_not_is_nil' },
    { 'assertNotIsTrue'         , 'assert_not_is_true' },
    { 'assertNotIsFalse'        , 'assert_not_is_false' },
    { 'assertNotIsNaN'          , 'assert_not_is_nan' },
    { 'assertNotIsInf'          , 'assert_not_is_inf' },
    { 'assertNotIsPlusInf'      , 'assert_not_plus_inf' },
    { 'assertNotIsMinusInf'     , 'assert_not_minus_inf' },
    { 'assertNotIsPlusZero'     , 'assert_not_plus_zero' },
    { 'assertNotIsMinusZero'    , 'assert_not_minus_zero' },
    { 'assertNotIsFunction'     , 'assert_not_is_function' },
    { 'assertNotIsThread'       , 'assert_not_is_thread' },
    { 'assertNotIsUserdata'     , 'assert_not_is_userdata' },

    -- type assertions: assertNotIsXXX -> assertNotXxx (luaunit v2 compat)
    { 'assertNotIsNumber'       , 'assertNotNumber' },
    { 'assertNotIsString'       , 'assertNotString' },
    { 'assertNotIsTable'        , 'assertNotTable' },
    { 'assertNotIsBoolean'      , 'assertNotBoolean' },
    { 'assertNotIsNil'          , 'assertNotNil' },
    { 'assertNotIsTrue'         , 'assertNotTrue' },
    { 'assertNotIsFalse'        , 'assertNotFalse' },
    { 'assertNotIsNaN'          , 'assertNotNaN' },
    { 'assertNotIsInf'          , 'assertNotInf' },
    { 'assertNotIsPlusInf'      , 'assertNotPlusInf' },
    { 'assertNotIsMinusInf'     , 'assertNotMinusInf' },
    { 'assertNotIsPlusZero'     , 'assertNotPlusZero' },
    { 'assertNotIsMinusZero'    , 'assertNotMinusZero' },
    { 'assertNotIsFunction'     , 'assertNotFunction' },
    { 'assertNotIsThread'       , 'assertNotThread' },
    { 'assertNotIsUserdata'     , 'assertNotUserdata' },

    -- type assertions: assertNotIsXXX -> assert_not_xxx
    { 'assertNotIsNumber'       , 'assert_not_number' },
    { 'assertNotIsString'       , 'assert_not_string' },
    { 'assertNotIsTable'        , 'assert_not_table' },
    { 'assertNotIsBoolean'      , 'assert_not_boolean' },
    { 'assertNotIsNil'          , 'assert_not_nil' },
    { 'assertNotIsTrue'         , 'assert_not_true' },
    { 'assertNotIsFalse'        , 'assert_not_false' },
    { 'assertNotIsNaN'          , 'assert_not_nan' },
    { 'assertNotIsInf'          , 'assert_not_inf' },
    { 'assertNotIsPlusInf'      , 'assert_not_plus_inf' },
    { 'assertNotIsMinusInf'     , 'assert_not_minus_inf' },
    { 'assertNotIsPlusZero'     , 'assert_not_plus_zero' },
    { 'assertNotIsMinusZero'    , 'assert_not_minus_zero' },
    { 'assertNotIsFunction'     , 'assert_not_function' },
    { 'assertNotIsThread'       , 'assert_not_thread' },
    { 'assertNotIsUserdata'     , 'assert_not_userdata' },

    -- all assertions with Coroutine duplicate Thread assertions
    { 'assertIsThread'          , 'assertIsCoroutine' },
    { 'assertIsThread'          , 'assertCoroutine' },
    { 'assertIsThread'          , 'assert_is_coroutine' },
    { 'assertIsThread'          , 'assert_coroutine' },
    { 'assertNotIsThread'       , 'assertNotIsCoroutine' },
    { 'assertNotIsThread'       , 'assertNotCoroutine' },
    { 'assertNotIsThread'       , 'assert_not_is_coroutine' },
    { 'assertNotIsThread'       , 'assert_not_coroutine' },
}

-- Create all aliases in M
for _,v in ipairs( list_of_funcs ) do
    local funcname, alias = v[1], v[2]
    M[alias] = M[funcname]

    if EXPORT_ASSERT_TO_GLOBALS then
        _G[funcname] = M[funcname]
        _G[alias] = M[funcname]
    end
end

----------------------------------------------------------------
--
--                     Outputters
--
----------------------------------------------------------------

-- A common "base" class for outputters
-- For concepts involved (class inheritance) see http://www.lua.org/pil/16.2.html

local genericOutput = { __class__ = 'genericOutput' } -- class
local genericOutput_MT = { __index = genericOutput } -- metatable
M.genericOutput = genericOutput -- publish, so that custom classes may derive from it

function genericOutput.new(runner, default_verbosity)
    -- runner is the "parent" object controlling the output, usually a LuaUnit instance
    local t = { runner = runner }
    if runner then
        t.result = runner.result
        t.verbosity = runner.verbosity or default_verbosity
        t.fname = runner.fname
    else
        t.verbosity = default_verbosity
    end
    return setmetatable( t, genericOutput_MT)
end

-- abstract ("empty") methods
function genericOutput:startSuite() end
function genericOutput:startClass(className) end
function genericOutput:startTest(testName) end
function genericOutput:addStatus(node) end
function genericOutput:endTest(node) end
function genericOutput:endClass() end
function genericOutput:endSuite() end


----------------------------------------------------------------
--                     class TapOutput
----------------------------------------------------------------

local TapOutput = genericOutput.new() -- derived class
local TapOutput_MT = { __index = TapOutput } -- metatable
TapOutput.__class__ = 'TapOutput'

    -- For a good reference for TAP format, check: http://testanything.org/tap-specification.html

    function TapOutput.new(runner)
        local t = genericOutput.new(runner, M.VERBOSITY_LOW)
        return setmetatable( t, TapOutput_MT)
    end
    function TapOutput:startSuite()
        print("1.."..self.result.testCount)
        print('# Started on '..self.result.startDate)
    end
    function TapOutput:startClass(className)
        if className ~= '[TestFunctions]' then
            print('# Starting class: '..className)
        end
    end

    function TapOutput:addStatus( node )
        io.stdout:write("not ok ", self.result.currentTestNumber, "\t", node.testName, "\n")
        if self.verbosity > M.VERBOSITY_LOW then
           print( prefixString( '#   ', node.msg ) )
        end
        if self.verbosity > M.VERBOSITY_DEFAULT then
           print( prefixString( '#   ', node.stackTrace ) )
        end
    end

    function TapOutput:endTest( node )
        if node:isPassed() then
            io.stdout:write("ok     ", self.result.currentTestNumber, "\t", node.testName, "\n")
        end
    end

    function TapOutput:endSuite()
        print( '# '..M.LuaUnit.statusLine( self.result ) )
        return self.result.notPassedCount
    end


-- class TapOutput end

----------------------------------------------------------------
--                     class JUnitOutput
----------------------------------------------------------------

-- See directory junitxml for more information about the junit format
local JUnitOutput = genericOutput.new() -- derived class
local JUnitOutput_MT = { __index = JUnitOutput } -- metatable
JUnitOutput.__class__ = 'JUnitOutput'

    function JUnitOutput.new(runner)
        local t = genericOutput.new(runner, M.VERBOSITY_LOW)
        t.testList = {}
        return setmetatable( t, JUnitOutput_MT )
    end

    function JUnitOutput:startSuite()
        -- open xml file early to deal with errors
        if self.fname == nil then
            error('With Junit, an output filename must be supplied with --name!')
        end
        if string.sub(self.fname,-4) ~= '.xml' then
            self.fname = self.fname..'.xml'
        end
        self.fd = io.open(self.fname, "w")
        if self.fd == nil then
            error("Could not open file for writing: "..self.fname)
        end

        print('# XML output to '..self.fname)
        print('# Started on '..self.result.startDate)
    end
    function JUnitOutput:startClass(className)
        if className ~= '[TestFunctions]' then
            print('# Starting class: '..className)
        end
    end
    function JUnitOutput:startTest(testName)
        print('# Starting test: '..testName)
    end

    function JUnitOutput:addStatus( node )
        if node:isFailure() then
            print( '#   Failure: ' .. prefixString( '#   ', node.msg ):sub(4, nil) )
            -- print('# ' .. node.stackTrace)
        elseif node:isError() then
            print( '#   Error: ' .. prefixString( '#   '  , node.msg ):sub(4, nil) )
            -- print('# ' .. node.stackTrace)
        end
    end

    function JUnitOutput:endSuite()
        print( '# '..M.LuaUnit.statusLine(self.result))

        -- XML file writing
        self.fd:write('<?xml version="1.0" encoding="UTF-8" ?>\n')
        self.fd:write('<testsuites>\n')
        self.fd:write(string.format(
            '    <testsuite name="LuaUnit" id="00001" package="" hostname="localhost" tests="%d" timestamp="%s" time="%0.3f" errors="%d" failures="%d">\n',
            self.result.runCount, self.result.startIsodate, self.result.duration, self.result.errorCount, self.result.failureCount ))
        self.fd:write("        <properties>\n")
        self.fd:write(string.format('            <property name="Lua Version" value="%s"/>\n', _VERSION ) )
        self.fd:write(string.format('            <property name="LuaUnit Version" value="%s"/>\n', M.VERSION) )
        -- XXX please include system name and version if possible
        self.fd:write("        </properties>\n")

        for i,node in ipairs(self.result.tests) do
            self.fd:write(string.format('        <testcase classname="%s" name="%s" time="%0.3f">\n',
                node.className, node.testName, node.duration ) )
            if node:isNotPassed() then
                self.fd:write(node:statusXML())
            end
            self.fd:write('        </testcase>\n')
        end

        -- Next two lines are needed to validate junit ANT xsd, but really not useful in general:
        self.fd:write('    <system-out/>\n')
        self.fd:write('    <system-err/>\n')

        self.fd:write('    </testsuite>\n')
        self.fd:write('</testsuites>\n')
        self.fd:close()
        return self.result.notPassedCount
    end


-- class TapOutput end

----------------------------------------------------------------
--                     class TextOutput
----------------------------------------------------------------

--[[

-- Python Non verbose:

For each test: . or F or E

If some failed tests:
    ==============
    ERROR / FAILURE: TestName (testfile.testclass)
    ---------
    Stack trace


then --------------
then "Ran x tests in 0.000s"
then OK or FAILED (failures=1, error=1)

-- Python Verbose:
testname (filename.classname) ... ok
testname (filename.classname) ... FAIL
testname (filename.classname) ... ERROR

then --------------
then "Ran x tests in 0.000s"
then OK or FAILED (failures=1, error=1)

-- Ruby:
Started
 .
 Finished in 0.002695 seconds.

 1 tests, 2 assertions, 0 failures, 0 errors

-- Ruby:
>> ruby tc_simple_number2.rb
Loaded suite tc_simple_number2
Started
F..
Finished in 0.038617 seconds.

  1) Failure:
test_failure(TestSimpleNumber) [tc_simple_number2.rb:16]:
Adding doesn't work.
<3> expected but was
<4>.

3 tests, 4 assertions, 1 failures, 0 errors

-- Java Junit
.......F.
Time: 0,003
There was 1 failure:
1) testCapacity(junit.samples.VectorTest)junit.framework.AssertionFailedError
    at junit.samples.VectorTest.testCapacity(VectorTest.java:87)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

FAILURES!!!
Tests run: 8,  Failures: 1,  Errors: 0


-- Maven

# mvn test
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running math.AdditionTest
Tests run: 2, Failures: 1, Errors: 0, Skipped: 0, Time elapsed:
0.03 sec <<< FAILURE!

Results :

Failed tests:
  testLireSymbole(math.AdditionTest)

Tests run: 2, Failures: 1, Errors: 0, Skipped: 0


-- LuaUnit
---- non verbose
* display . or F or E when running tests
---- verbose
* display test name + ok/fail
----
* blank line
* number) ERROR or FAILURE: TestName
   Stack trace
* blank line
* number) ERROR or FAILURE: TestName
   Stack trace

then --------------
then "Ran x tests in 0.000s (%d not selected, %d skipped)"
then OK or FAILED (failures=1, error=1)


]]

local TextOutput = genericOutput.new() -- derived class
local TextOutput_MT = { __index = TextOutput } -- metatable
TextOutput.__class__ = 'TextOutput'

    function TextOutput.new(runner)
        local t = genericOutput.new(runner, M.VERBOSITY_DEFAULT)
        t.errorList = {}
        return setmetatable( t, TextOutput_MT )
    end

    function TextOutput:startSuite()
        if self.verbosity > M.VERBOSITY_DEFAULT then
            print( 'Started on '.. self.result.startDate )
        end
    end

    function TextOutput:startTest(testName)
        if self.verbosity > M.VERBOSITY_DEFAULT then
            io.stdout:write( "    ", self.result.currentNode.testName, " ... " )
        end
    end

    function TextOutput:endTest( node )
        if node:isPassed() then
            if self.verbosity > M.VERBOSITY_DEFAULT then
                io.stdout:write("Ok\n")
            else
                io.stdout:write(".")
            end
        else
            if self.verbosity > M.VERBOSITY_DEFAULT then
                print( node.status )
                print( node.msg )
                --[[
                -- find out when to do this:
                if self.verbosity > M.VERBOSITY_DEFAULT then
                    print( node.stackTrace )
                end
                ]]
            else
                -- write only the first character of status
                io.stdout:write(string.sub(node.status, 1, 1))
            end
        end
    end

    function TextOutput:displayOneFailedTest( index, fail )
        print(index..") "..fail.testName )
        print( fail.msg )
        print( fail.stackTrace )
        print()
    end

    function TextOutput:displayFailedTests()
        if self.result.notPassedCount ~= 0 then
            print("Failed tests:")
            print("-------------")
            for i, v in ipairs(self.result.notPassed) do
                self:displayOneFailedTest(i, v)
            end
        end
    end

    function TextOutput:endSuite()
        if self.verbosity > M.VERBOSITY_DEFAULT then
            print("=========================================================")
        else
            print()
        end
        self:displayFailedTests()
        print( M.LuaUnit.statusLine( self.result ) )
        if self.result.notPassedCount == 0 then
            print('OK')
        end
    end

-- class TextOutput end


----------------------------------------------------------------
--                     class NilOutput
----------------------------------------------------------------

local function nopCallable()
    --print(42)
    return nopCallable
end

local NilOutput = { __class__ = 'NilOuptut' } -- class
local NilOutput_MT = { __index = nopCallable } -- metatable

function NilOutput.new(runner)
    return setmetatable( { __class__ = 'NilOutput' }, NilOutput_MT )
end

----------------------------------------------------------------
--
--                     class LuaUnit
--
----------------------------------------------------------------

M.LuaUnit = {
    outputType = TextOutput,
    verbosity = M.VERBOSITY_DEFAULT,
    __class__ = 'LuaUnit'
}
local LuaUnit_MT = { __index = M.LuaUnit }

if EXPORT_ASSERT_TO_GLOBALS then
    LuaUnit = M.LuaUnit
end

    function M.LuaUnit.new()
        return setmetatable( {}, LuaUnit_MT )
    end

    -----------------[[ Utility methods ]]---------------------

    function M.LuaUnit.asFunction(aObject)
        -- return "aObject" if it is a function, and nil otherwise
        if 'function' == type(aObject) then
            return aObject
        end
    end

    function M.LuaUnit.splitClassMethod(someName)
        --[[
        Return a pair of className, methodName strings for a name in the form
        "class.method". If no class part (or separator) is found, will return
        nil, someName instead (the latter being unchanged).

        This convention thus also replaces the older isClassMethod() test:
        You just have to check for a non-nil className (return) value.
        ]]
        local separator = string.find(someName, '.', 1, true)
        if separator then
            return someName:sub(1, separator - 1), someName:sub(separator + 1)
        end
        return nil, someName
    end

    function M.LuaUnit.isMethodTestName( s )
        -- return true is the name matches the name of a test method
        -- default rule is that is starts with 'Test' or with 'test'
        return string.sub(s, 1, 4):lower() == 'test'
    end

    function M.LuaUnit.isTestName( s )
        -- return true is the name matches the name of a test
        -- default rule is that is starts with 'Test' or with 'test'
        return string.sub(s, 1, 4):lower() == 'test'
    end

    function M.LuaUnit.collectTests()
        -- return a list of all test names in the global namespace
        -- that match LuaUnit.isTestName

        local testNames = {}
        for k, _ in pairs(_G) do
            if type(k) == "string" and M.LuaUnit.isTestName( k ) then
                table.insert( testNames , k )
            end
        end
        table.sort( testNames )
        return testNames
    end

    function M.LuaUnit.parseCmdLine( cmdLine )
        -- parse the command line
        -- Supported command line parameters:
        -- --verbose, -v: increase verbosity
        -- --quiet, -q: silence output
        -- --error, -e: treat errors as fatal (quit program)
        -- --output, -o, + name: select output type
        -- --pattern, -p, + pattern: run test matching pattern, may be repeated
        -- --exclude, -x, + pattern: run test not matching pattern, may be repeated
        -- --shuffle, -s, : shuffle tests before reunning them
        -- --name, -n, + fname: name of output file for junit, default to stdout
        -- --repeat, -r, + num: number of times to execute each test
        -- [testnames, ...]: run selected test names
        --
        -- Returns a table with the following fields:
        -- verbosity: nil, M.VERBOSITY_DEFAULT, M.VERBOSITY_QUIET, M.VERBOSITY_VERBOSE
        -- output: nil, 'tap', 'junit', 'text', 'nil'
        -- testNames: nil or a list of test names to run
        -- exeRepeat: num or 1
        -- pattern: nil or a list of patterns
        -- exclude: nil or a list of patterns

        local result, state = {}, nil
        local SET_OUTPUT = 1
        local SET_PATTERN = 2
        local SET_EXCLUDE = 3
        local SET_FNAME = 4
        local SET_REPEAT = 5

        if cmdLine == nil then
            return result
        end

        local function parseOption( option )
            if option == '--help' or option == '-h' then
                result['help'] = true
                return
            elseif option == '--version' then
                result['version'] = true
                return
            elseif option == '--verbose' or option == '-v' then
                result['verbosity'] = M.VERBOSITY_VERBOSE
                return
            elseif option == '--quiet' or option == '-q' then
                result['verbosity'] = M.VERBOSITY_QUIET
                return
            elseif option == '--error' or option == '-e' then
                result['quitOnError'] = true
                return
            elseif option == '--failure' or option == '-f' then
                result['quitOnFailure'] = true
                return
            elseif option == '--shuffle' or option == '-s' then
                result['shuffle'] = true
                return
            elseif option == '--output' or option == '-o' then
                state = SET_OUTPUT
                return state
            elseif option == '--name' or option == '-n' then
                state = SET_FNAME
                return state
            elseif option == '--repeat' or option == '-r' then
                state = SET_REPEAT
                return state
            elseif option == '--pattern' or option == '-p' then
                state = SET_PATTERN
                return state
            elseif option == '--exclude' or option == '-x' then
                state = SET_EXCLUDE
                return state
            end
            error('Unknown option: '..option,3)
        end

        local function setArg( cmdArg, state )
            if state == SET_OUTPUT then
                result['output'] = cmdArg
                return
            elseif state == SET_FNAME then
                result['fname'] = cmdArg
                return
            elseif state == SET_REPEAT then
                result['exeRepeat'] = tonumber(cmdArg)
                                     or error('Malformed -r argument: '..cmdArg)
                return
            elseif state == SET_PATTERN then
                if result['pattern'] then
                    table.insert( result['pattern'], cmdArg )
                else
                    result['pattern'] = { cmdArg }
                end
                return
            elseif state == SET_EXCLUDE then
                local notArg = '!'..cmdArg
                if result['pattern'] then
                    table.insert( result['pattern'],  notArg )
                else
                    result['pattern'] = { notArg }
                end
                return
            end
            error('Unknown parse state: '.. state)
        end


        for i, cmdArg in ipairs(cmdLine) do
            if state ~= nil then
                setArg( cmdArg, state, result )
                state = nil
            else
                if cmdArg:sub(1,1) == '-' then
                    state = parseOption( cmdArg )
                else
                    if result['testNames'] then
                        table.insert( result['testNames'], cmdArg )
                    else
                        result['testNames'] = { cmdArg }
                    end
                end
            end
        end

        if result['help'] then
            M.LuaUnit.help()
        end

        if result['version'] then
            M.LuaUnit.version()
        end

        if state ~= nil then
            error('Missing argument after '..cmdLine[ #cmdLine ],2 )
        end

        return result
    end

    function M.LuaUnit.help()
        print(M.USAGE)
        os.exit(0)
    end

    function M.LuaUnit.version()
        print('LuaUnit v'..M.VERSION..' by Philippe Fremy <phil@freehackers.org>')
        os.exit(0)
    end

----------------------------------------------------------------
--                     class NodeStatus
----------------------------------------------------------------

    local NodeStatus = { __class__ = 'NodeStatus' } -- class
    local NodeStatus_MT = { __index = NodeStatus } -- metatable
    M.NodeStatus = NodeStatus

    -- values of status
    NodeStatus.PASS  = 'PASS'
    NodeStatus.FAIL  = 'FAIL'
    NodeStatus.ERROR = 'ERROR'

    function NodeStatus.new( number, testName, className )
        local t = { number = number, testName = testName, className = className }
        setmetatable( t, NodeStatus_MT )
        t:pass()
        return t
    end

    function NodeStatus:pass()
        self.status = self.PASS
        -- useless but we know it's the field we want to use
        self.msg = nil
        self.stackTrace = nil
    end

    function NodeStatus:fail(msg, stackTrace)
        self.status = self.FAIL
        self.msg = msg
        self.stackTrace = stackTrace
    end

    function NodeStatus:error(msg, stackTrace)
        self.status = self.ERROR
        self.msg = msg
        self.stackTrace = stackTrace
    end

    function NodeStatus:isPassed()
        return self.status == NodeStatus.PASS
    end

    function NodeStatus:isNotPassed()
        -- print('hasFailure: '..prettystr(self))
        return self.status ~= NodeStatus.PASS
    end

    function NodeStatus:isFailure()
        return self.status == NodeStatus.FAIL
    end

    function NodeStatus:isError()
        return self.status == NodeStatus.ERROR
    end

    function NodeStatus:statusXML()
        if self:isError() then
            return table.concat(
                {'            <error type="', xmlEscape(self.msg), '">\n',
                 '                <![CDATA[', xmlCDataEscape(self.stackTrace),
                 ']]></error>\n'})
        elseif self:isFailure() then
            return table.concat(
                {'            <failure type="', xmlEscape(self.msg), '">\n',
                 '                <![CDATA[', xmlCDataEscape(self.stackTrace),
                 ']]></failure>\n'})
        end
        return '            <passed/>\n' -- (not XSD-compliant! normally shouldn't get here)
    end

    --------------[[ Output methods ]]-------------------------

    local function conditional_plural(number, singular)
        -- returns a grammatically well-formed string "%d <singular/plural>"
        local suffix = ''
        if number ~= 1 then -- use plural
            suffix = (singular:sub(-2) == 'ss') and 'es' or 's'
        end
        return string.format('%d %s%s', number, singular, suffix)
    end

    function M.LuaUnit.statusLine(result)
        -- return status line string according to results
        local s = {
            string.format('Ran %d tests in %0.3f seconds',
                          result.runCount, result.duration),
            conditional_plural(result.passedCount, 'success'),
        }
        if result.notPassedCount > 0 then
            if result.failureCount > 0 then
                table.insert(s, conditional_plural(result.failureCount, 'failure'))
            end
            if result.errorCount > 0 then
                table.insert(s, conditional_plural(result.errorCount, 'error'))
            end
        else
            table.insert(s, '0 failures')
        end
        if result.nonSelectedCount > 0 then
            table.insert(s, string.format("%d non-selected", result.nonSelectedCount))
        end
        return table.concat(s, ', ')
    end

    function M.LuaUnit:startSuite(testCount, nonSelectedCount)
        self.result = {
            testCount = testCount,
            nonSelectedCount = nonSelectedCount,
            passedCount = 0,
            runCount = 0,
            currentTestNumber = 0,
            currentClassName = "",
            currentNode = nil,
            suiteStarted = true,
            startTime = os.clock(),
            startDate = os.date(os.getenv('LUAUNIT_DATEFMT')),
            startIsodate = os.date('%Y-%m-%dT%H:%M:%S'),
            patternIncludeFilter = self.patternIncludeFilter,
            tests = {},
            failures = {},
            errors = {},
            notPassed = {},
        }

        self.outputType = self.outputType or TextOutput
        self.output = self.outputType.new(self)
        self.output:startSuite()
    end

    function M.LuaUnit:startClass( className )
        self.result.currentClassName = className
        self.output:startClass( className )
    end

    function M.LuaUnit:startTest( testName  )
        self.result.currentTestNumber = self.result.currentTestNumber + 1
        self.result.runCount = self.result.runCount + 1
        self.result.currentNode = NodeStatus.new(
            self.result.currentTestNumber,
            testName,
            self.result.currentClassName
        )
        self.result.currentNode.startTime = os.clock()
        table.insert( self.result.tests, self.result.currentNode )
        self.output:startTest( testName )
    end

    function M.LuaUnit:addStatus( err )
        -- "err" is expected to be a table / result from protectedCall()
        if err.status == NodeStatus.PASS then
            return
        end

        local node = self.result.currentNode

        --[[ As a first approach, we will report only one error or one failure for one test.

        However, we can have the case where the test is in failure, and the teardown is in error.
        In such case, it's a good idea to report both a failure and an error in the test suite. This is
        what Python unittest does for example. However, it mixes up counts so need to be handled carefully: for
        example, there could be more (failures + errors) count that tests. What happens to the current node ?

        We will do this more intelligent version later.
        ]]

        -- if the node is already in failure/error, just don't report the new error (see above)
        if node.status ~= NodeStatus.PASS then
            return
        end

        if err.status == NodeStatus.FAIL then
            node:fail( err.msg, err.trace )
            table.insert( self.result.failures, node )
        elseif err.status == NodeStatus.ERROR then
            node:error( err.msg, err.trace )
            table.insert( self.result.errors, node )
        end

        if node:isFailure() or node:isError() then
            -- add to the list of failed tests (gets printed separately)
            table.insert( self.result.notPassed, node )
        end
        self.output:addStatus( node )
    end

    function M.LuaUnit:endTest()
        local node = self.result.currentNode
        -- print( 'endTest() '..prettystr(node))
        -- print( 'endTest() '..prettystr(node:isNotPassed()))
        node.duration = os.clock() - node.startTime
        node.startTime = nil
        self.output:endTest( node )

        if node:isPassed() then
            self.result.passedCount = self.result.passedCount + 1
        elseif node:isError() then
            if self.quitOnError or self.quitOnFailure then
                -- Runtime error - abort test execution as requested by
                -- "--error" option. This is done by setting a special
                -- flag that gets handled in runSuiteByInstances().
                print("\nERROR during LuaUnit test execution:\n" .. node.msg)
                self.result.aborted = true
            end
        elseif node:isFailure() then
            if self.quitOnFailure then
                -- Failure - abort test execution as requested by
                -- "--failure" option. This is done by setting a special
                -- flag that gets handled in runSuiteByInstances().
                print("\nFailure during LuaUnit test execution:\n" .. node.msg)
                self.result.aborted = true
            end
        end
        self.result.currentNode = nil
    end

    function M.LuaUnit:endClass()
        self.output:endClass()
    end

    function M.LuaUnit:endSuite()
        if self.result.suiteStarted == false then
            error('LuaUnit:endSuite() -- suite was already ended' )
        end
        self.result.duration = os.clock()-self.result.startTime
        self.result.suiteStarted = false

        -- Expose test counts for outputter's endSuite(). This could be managed
        -- internally instead, but unit tests (and existing use cases) might
        -- rely on these fields being present.
        self.result.notPassedCount = #self.result.notPassed
        self.result.failureCount = #self.result.failures
        self.result.errorCount = #self.result.errors

        self.output:endSuite()
    end

    function M.LuaUnit:setOutputType(outputType)
        -- default to text
        -- tap produces results according to TAP format
        if outputType:upper() == "NIL" then
            self.outputType = NilOutput
            return
        end
        if outputType:upper() == "TAP" then
            self.outputType = TapOutput
            return
        end
        if outputType:upper() == "JUNIT" then
            self.outputType = JUnitOutput
            return
        end
        if outputType:upper() == "TEXT" then
            self.outputType = TextOutput
            return
        end
        error( 'No such format: '..outputType,2)
    end

    --------------[[ Runner ]]-----------------

    function M.LuaUnit:protectedCall(classInstance, methodInstance, prettyFuncName)
        -- if classInstance is nil, this is just a function call
        -- else, it's method of a class being called.

        local function err_handler(e)
            -- transform error into a table, adding the traceback information
            return {
                status = NodeStatus.ERROR,
                msg = e,
                trace = string.sub(debug.traceback("", 3), 2)
            }
        end

        local ok, err
        if classInstance then
            -- stupid Lua < 5.2 does not allow xpcall with arguments so let's use a workaround
            ok, err = xpcall( function () methodInstance(classInstance) end, err_handler )
        else
            ok, err = xpcall( function () methodInstance() end, err_handler )
        end
        if ok then
            return {status = NodeStatus.PASS}
        end

        local iter_msg
        iter_msg = self.exeRepeat and 'iteration '..self.currentCount

        err.msg, err.status = M.adjust_err_msg_with_iter( err.msg, iter_msg )

        if err.status == NodeStatus.PASS then
            err.trace = nil
            return err
        end

        -- reformat / improve the stack trace
        if prettyFuncName then -- we do have the real method name
            err.trace = err.trace:gsub("in (%a+) 'methodInstance'", "in %1 '"..prettyFuncName.."'")
        end
        if STRIP_LUAUNIT_FROM_STACKTRACE then
            err.trace = stripLuaunitTrace(err.trace)
        end

        return err -- return the error "object" (table)
    end


    function M.LuaUnit:execOneFunction(className, methodName, classInstance, methodInstance)
        -- When executing a test function, className and classInstance must be nil
        -- When executing a class method, all parameters must be set

        if type(methodInstance) ~= 'function' then
            error( tostring(methodName)..' must be a function, not '..type(methodInstance))
        end

        local prettyFuncName
        if className == nil then
            className = '[TestFunctions]'
            prettyFuncName = methodName
        else
            prettyFuncName = className..'.'..methodName
        end

        if self.lastClassName ~= className then
            if self.lastClassName ~= nil then
                self:endClass()
            end
            self:startClass( className )
            self.lastClassName = className
        end

        self:startTest(prettyFuncName)

        local node = self.result.currentNode
        for iter_n = 1, self.exeRepeat or 1 do
            if node:isNotPassed() then
                break
            end
            self.currentCount = iter_n

            -- run setUp first (if any)
            if classInstance then
                local func = self.asFunction( classInstance.setUp ) or
                             self.asFunction( classInstance.Setup ) or
                             self.asFunction( classInstance.setup ) or
                             self.asFunction( classInstance.SetUp )
                if func then
                    self:addStatus(self:protectedCall(classInstance, func, className..'.setUp'))
                end
            end

            -- run testMethod()
            if node:isPassed() then
                self:addStatus(self:protectedCall(classInstance, methodInstance, prettyFuncName))
            end

            -- lastly, run tearDown (if any)
            if classInstance then
                local func = self.asFunction( classInstance.tearDown ) or
                             self.asFunction( classInstance.TearDown ) or
                             self.asFunction( classInstance.teardown ) or
                             self.asFunction( classInstance.Teardown )
                if func then
                    self:addStatus(self:protectedCall(classInstance, func, className..'.tearDown'))
                end
            end
        end

        self:endTest()
    end

    function M.LuaUnit.expandOneClass( result, className, classInstance )
        --[[
        Input: a list of { name, instance }, a class name, a class instance
        Ouptut: modify result to add all test method instance in the form:
        { className.methodName, classInstance }
        ]]
        for methodName, methodInstance in sortedPairs(classInstance) do
            if M.LuaUnit.asFunction(methodInstance) and M.LuaUnit.isMethodTestName( methodName ) then
                table.insert( result, { className..'.'..methodName, classInstance } )
            end
        end
    end

    function M.LuaUnit.expandClasses( listOfNameAndInst )
        --[[
        -- expand all classes (provided as {className, classInstance}) to a list of {className.methodName, classInstance}
        -- functions and methods remain untouched

        Input: a list of { name, instance }

        Output:
        * { function name, function instance } : do nothing
        * { class.method name, class instance }: do nothing
        * { class name, class instance } : add all method names in the form of (className.methodName, classInstance)
        ]]
        local result = {}

        for i,v in ipairs( listOfNameAndInst ) do
            local name, instance = v[1], v[2]
            if M.LuaUnit.asFunction(instance) then
                table.insert( result, { name, instance } )
            else
                if type(instance) ~= 'table' then
                    error( 'Instance must be a table or a function, not a '..type(instance)..' with value '..prettystr(instance))
                end
                local className, methodName = M.LuaUnit.splitClassMethod( name )
                if className then
                    local methodInstance = instance[methodName]
                    if methodInstance == nil then
                        error( "Could not find method in class "..tostring(className).." for method "..tostring(methodName) )
                    end
                    table.insert( result, { name, instance } )
                else
                    M.LuaUnit.expandOneClass( result, name, instance )
                end
            end
        end

        return result
    end

    function M.LuaUnit.applyPatternFilter( patternIncFilter, listOfNameAndInst )
        local included, excluded = {}, {}
        for i, v in ipairs( listOfNameAndInst ) do
            -- local name, instance = v[1], v[2]
            if  patternFilter( patternIncFilter, v[1] ) then
                table.insert( included, v )
            else
                table.insert( excluded, v )
            end
        end
        return included, excluded
    end

    function M.LuaUnit:runSuiteByInstances( listOfNameAndInst )
        --[[ Run an explicit list of tests. Each item of the list must be one of:
        * { function name, function instance }
        * { class name, class instance }
        * { class.method name, class instance }
        ]]

        local expandedList = self.expandClasses( listOfNameAndInst )
        if self.shuffle then
            randomizeTable( expandedList )
        end
        local filteredList, filteredOutList = self.applyPatternFilter(
            self.patternIncludeFilter, expandedList )

        self:startSuite( #filteredList, #filteredOutList )

        for i,v in ipairs( filteredList ) do
            local name, instance = v[1], v[2]
            if M.LuaUnit.asFunction(instance) then
                self:execOneFunction( nil, name, nil, instance )
            else
                -- expandClasses() should have already taken care of sanitizing the input
                assert( type(instance) == 'table' )
                local className, methodName = M.LuaUnit.splitClassMethod( name )
                assert( className ~= nil )
                local methodInstance = instance[methodName]
                assert(methodInstance ~= nil)
                self:execOneFunction( className, methodName, instance, methodInstance )
            end
            if self.result.aborted then
                break -- "--error" or "--failure" option triggered
            end
        end

        if self.lastClassName ~= nil then
            self:endClass()
        end

        self:endSuite()

        if self.result.aborted then
            print("LuaUnit ABORTED (as requested by --error or --failure option)")
            os.exit(-2)
        end
    end

    function M.LuaUnit:runSuiteByNames( listOfName )
        --[[ Run LuaUnit with a list of generic names, coming either from command-line or from global
            namespace analysis. Convert the list into a list of (name, valid instances (table or function))
            and calls runSuiteByInstances.
        ]]

        local instanceName, instance
        local listOfNameAndInst = {}

        for i,name in ipairs( listOfName ) do
            local className, methodName = M.LuaUnit.splitClassMethod( name )
            if className then
                instanceName = className
                instance = _G[instanceName]

                if instance == nil then
                    error( "No such name in global space: "..instanceName )
                end

                if type(instance) ~= 'table' then
                    error( 'Instance of '..instanceName..' must be a table, not '..type(instance))
                end

                local methodInstance = instance[methodName]
                if methodInstance == nil then
                    error( "Could not find method in class "..tostring(className).." for method "..tostring(methodName) )
                end

            else
                -- for functions and classes
                instanceName = name
                instance = _G[instanceName]
            end

            if instance == nil then
                error( "No such name in global space: "..instanceName )
            end

            if (type(instance) ~= 'table' and type(instance) ~= 'function') then
                error( 'Name must match a function or a table: '..instanceName )
            end

            table.insert( listOfNameAndInst, { name, instance } )
        end

        self:runSuiteByInstances( listOfNameAndInst )
    end

    function M.LuaUnit.run(...)
        -- Run some specific test classes.
        -- If no arguments are passed, run the class names specified on the
        -- command line. If no class name is specified on the command line
        -- run all classes whose name starts with 'Test'
        --
        -- If arguments are passed, they must be strings of the class names
        -- that you want to run or generic command line arguments (-o, -p, -v, ...)

        local runner = M.LuaUnit.new()
        return runner:runSuite(...)
    end

    function M.LuaUnit:runSuite( ... )

        local args = {...}
        if type(args[1]) == 'table' and args[1].__class__ == 'LuaUnit' then
            -- run was called with the syntax M.LuaUnit:runSuite()
            -- we support both M.LuaUnit.run() and M.LuaUnit:run()
            -- strip out the first argument
            table.remove(args,1)
        end

        if #args == 0 then
            args = cmdline_argv
        end

        local options = pcall_or_abort( M.LuaUnit.parseCmdLine, args )

        -- We expect these option fields to be either `nil` or contain
        -- valid values, so it's safe to always copy them directly.
        self.verbosity     = options.verbosity
        self.quitOnError   = options.quitOnError
        self.quitOnFailure = options.quitOnFailure
        self.fname         = options.fname

        self.exeRepeat            = options.exeRepeat
        self.patternIncludeFilter = options.pattern
        self.shuffle              = options.shuffle

        if options.output then
            if options.output:lower() == 'junit' and options.fname == nil then
                print('With junit output, a filename must be supplied with -n or --name')
                os.exit(-1)
            end
            pcall_or_abort(self.setOutputType, self, options.output)
        end

        self:runSuiteByNames( options.testNames or M.LuaUnit.collectTests() )

        return self.result.notPassedCount
    end
-- class LuaUnit

-- For compatbility with LuaUnit v2
M.run = M.LuaUnit.run
M.Run = M.LuaUnit.run

function M:setVerbosity( verbosity )
    M.LuaUnit.verbosity = verbosity
end
M.set_verbosity = M.setVerbosity
M.SetVerbosity = M.setVerbosity


return M