| 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 |
9
9
12
9
9
9
4
9
9
9
9
9
9
9
9
9
27
654
654
152
152
502
502
99
99
99
403
403
403
237
6
6
6
6
6
6
6
6
6
6
6
6
9633
18
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
18
6
6
6
6
92
54
6
6
6
6
6
6
6
6
336
264
240
336
729
60
46
14
6
6
6
6
6
6
6
6
6
6
6
6
6
6
6
51
51
51
51
6
6
6
6
6
6
6
6
6
6
28470
86805
86805
86805
86805
563
563
86242
25182
28470
6
6
6
6
3432
3432
6
6
6
6
6
6
6
6
6
6
6
6
6
3466
3466
7914
7914
7914
7880
7880
7880
34
32
32
32
32
32
126
32
32
32
126
126
32
6
6
6
6
6
46
46
92
92
92
92
92
207
207
207
191
207
207
2928
2928
2928
2928
46
35
35
218
5
35
30
46
23
46
46
46
46
46
202
202
202
202
2846
2846
2827
2827
2827
19
19
19
202
202
6228
6228
6228
202
1
46
310
310
310
46
8
46
46
46
24
24
24
2304
2304
5000
5000
24
2384
2384
24
10264
10264
46
46
46
46
3094
49
46
46
202
202
2846
46
46
9
37
193
193
193
2729
2729
2729
8
8
8
8
8
8
8
117
117
157
20
20
157
40
40
40
40
117
117
117
117
8
8
8
35
8
4
4
4
3
4
4
4
4
4
4
4
117
117
117
117
20
20
20
97
20
50
50
24
6
6
6
6
6
3036
3036
3036
15976
15976
6
6
6
6
6
6
3036
3036
435
435
2946
3036
3036
3501
3501
3036
465
465
435
3036
19
19
19
19
9
9
9
9
9
5
4
4
4
4
4
8
8
8
4
8
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
12
8
8
4
4
4
4
4
12
8
8
16
16
16
9
5
5
5
5
5
5
45
5
10
10
5
5
5
5
5
5
5
5
5
5
5
486
486
5
32
22
22
22
29
22
22
8
5
5
5
5
4
1
4
5
5
5
5
5
5
135
5
5
5
10
10
230
230
230
44
230
118
112
22
112
112
10
54
54
54
54
10
10
22
22
8
22
22
176
176
176
176
354
176
22
34
34
22
22
22
54
54
54
10
66
34
10
10
10
20
20
4
2
10
30
30
30
4
2
2
2
2
2
12
12
12
2
2
2
4
4
4
4
4
4
5
2
3
3
3
3
4
4
4
4
4
4
4
2
4
2
5
2
3
3
3
3
3
48
2
3
32
32
32
157
157
32
32
32
4
32
32
32
32
32
32
32
32
32
32
32
32
32
32
31
31
31
31
31
31
31
2
2
29
29
31
31
31
31
31
31
31
31
2
2
2
29
32
12
12
34
72
46
24
24
24
142
48
48
2
2
2
2
2
2
2
4
4
4
12
12
4
4
4
4
4
4
4
4
2
2
6
4
2
4
4
4
4
4
4
2
2
8
8
8
4
4
4
4
4
2
2
2
2
2
2
2
2
2
2
2
2
2
3
1
2
1
1
1
1
1
1
1
4
4
4
4
4
4
4
4
4
2
2
4
4
4
2
2
2
2
2
2
48
48
48
144
144
48
48
48
48
48
48
48
48
48
48
48
48
48
44
48
48
48
48
48
48
48
48
28
28
28
28
28
8
8
4
4
4
8
8
4
4
4
4
4
4
4
4
4
4
2
2
2
40
40
42
42
42
42
42
6
6
6
6
6
6
6
6
2
2
2
6
35
35
35
79
35
1
1
1
7
7
1
7
7
7
1
1
1
1
1
1
1
1
1
1
1
7
7
1
4
1
4
4
4
4
25
25
7
7
18
4
4
1
1
1
1
1
7
7
7
21
21
7
7
7
7
7
7
44
7
7
7
7
7
7
7
7
7
7
2
2
2
16
16
2
2
2
2
2
2
2
2
3
3
3
3
3
1
1
1
2
2
2
2
2
2
2
2
2
2
2
2
2
2
5
| /*jslint
bitwise: true, browser: true,
indent: 2,
maxerr: 8,
node: true, nomen: true,
regexp: true,
stupid: true,
todo: true
*/
// declare module vars
var exports, required, state, stateRestore, stateRestore2;
stateRestore = function (state2) {
/*
this function is used by testMock to restore the local state var
*/
'use strict';
state = state2;
};
(function submoduleUtility2Shared() {
/*
this shared submodule exports useful utilities
*/
'use strict';
var local = {
_name: 'utility2.submoduleUtility2Shared',
_init: function () {
/*
this function inits the submodule
*/
// export global object
if (typeof window === 'object') {
window.global = window;
}
// init module object
global.module = global.module || {};
// init exports object
exports = global.__exports__ = module.exports = {};
// init _debug_print
exports[['debug', 'Print'].join('')] = global[['debug', 'Print'].join('')] =
local._debug_print;
// init state object
state = exports.state = exports.state || {};
// init flag indicating whether we are in either browser or nodejs environment
state.modeNodejs = global.process && process.versions && process.versions.node;
local.setDefault(state, {
// default error
errorDefault: new Error('default error'),
// cached dict of files
fileDict: {},
// mime-type lookup for given file extensions
mimeLookupDict: {
'.css': 'text/css',
'.html': 'text/html',
'.js': 'application/javascript',
'.json': 'application/json',
'.txt': 'text/plain'
},
// dict of cli commands
modeCliDict: {},
// state to export to browser
stateBrowser: { fileDict: {} },
// dict of server-side callbacks used to create test-reports from browser tests
testCallbackDict: {},
// main test-report object used to accumulate test-reports from this and other platforms
testReport: {
// global code coverage object if it exists
coverage: global.__coverage__,
// list of javascript test platforms - e.g. browser / nodejs
testPlatformList: [{
// javascript platform name
name: state.modeNodejs ? 'nodejs - ' + process.platform + ' ' + process.version
: 'browser - ' + (navigator && navigator.userAgent),
// list of test cases and their results
testCaseList: []
}]
},
// default timeout for ajax requests and other async io
timeoutDefault: 30000
});
// init test platform object
state.testPlatform = state.testReport.testPlatformList[0];
// init this submodule
local.initSubmodule(local);
// init state.testReport
exports.testReportCreate(state.testReport, {});
},
initSubmodule: function (local) {
/*
this function inits a submodule's local object
*/
Object.keys(local).forEach(function (key) {
var match;
// add test case to state.testReport
if (key.slice(-5) === '_test') {
state.testPlatform.testCaseList.push({
callback: local[key],
name: local._name + '.' + key
});
return;
}
// set dict items to state object
match = (/(.+Dict)_(.*)/).exec(key);
if (match) {
state[match[1]] = state[match[1]] || {};
state[match[1]][match[2]] = local[key];
return;
}
match = (/(^ngApp_\w+)_(\w+)_(\w+)$/).exec(key);
Iif (match) {
// init angularjs app
state[match[1]] = state[match[1]] || global.angular.module(match[1], []);
// init angularjs app's sub-component
state[match[1]][match[2]](match[3], local[key]);
return;
}
// export items that don't start with an underscore _
if (key[0] !== '_') {
exports[key] = local[key];
}
});
},
_initSubmodule_default_test: function (onEventError) {
/*
this function tests initSubmodule's default handling behavior
*/
var data;
exports.testMock(onEventError, stateRestore, [
], function (onEventError) {
state = {};
// test default handling behavior
exports.initSubmodule({
// test dict handling behavior
_aaDict_bb: true,
_name: '_initSubmodule_default_test'
});
// validate state
data = exports.jsonStringifyOrdered(state);
exports.assert(data === '{"_aaDict":{"bb":true}}', data);
onEventError();
});
},
_ajax_default_test: function (onEventError) {
/*
this function tests ajax's default handling behavior
*/
exports.ajax({
url: '/test/hello.json'
}, function (error, data) {
exports.testTryCatch(function () {
// validate no error occurred
exports.assert(!error, error);
// validate data
exports.assert(data === '"hello"', data);
onEventError();
}, onEventError);
});
},
assert: function (passed, message) {
/*
this function throws an error if the assertion fails
*/
if (!passed) {
throw new Error('assertion error - ' + (
// if message is a string, then leave it as is
typeof message === 'string' ? message
// if message is an Error object, then get its stack trace
: message instanceof Error ? exports.errorStack(message)
// else JSON.stringify message
: JSON.stringify(message)
));
}
},
_assert_default_test: function (onEventError) {
/*
this function tests assert's default handling behavior
*/
// test assertion passed
exports.assert(true, true);
// test assertion failed
exports.testTryCatch(function () {
exports.assert(false);
}, function (error) {
// validate error occurred
exports.assert(error instanceof Error, error);
// validate error message
exports.assert(error.message === 'assertion error - undefined', error.message);
});
// test assertion failed with text message
exports.testTryCatch(function () {
exports.assert(false, '_assert_default_test');
}, function (error) {
// validate error occurred
exports.assert(error instanceof Error, error);
// validate error message
exports.assert(
error.message === 'assertion error - _assert_default_test',
error.message
);
});
// test assertion failed with error object
exports.testTryCatch(function () {
exports.assert(false, state.errorDefault);
}, function (error) {
// validate error occurred
exports.assert(error instanceof Error, error);
// validate error message
exports.assert(error.message.indexOf('assertion error - ') === 0, error.message);
});
onEventError();
},
callArg0: function (callback) {
/*
this function calls the callback in arg position 0
*/
callback();
},
callArg1: function (_, callback) {
/*
this function calls the callback in arg position 1
*/
// nop hack to pass jslint
exports.nop(_);
callback();
},
callArg2: function (_, __, callback) {
/*
this function calls the callback in arg position 2
*/
// nop hack to pass jslint
exports.nop(_, __);
callback();
},
callError0: function (onEventError) {
/*
this function calls the onEventError callback in arg position 0 with an error object
*/
onEventError(state.errorDefault);
},
callError1: function (_, onEventError) {
/*
this function calls the onEventError callback in arg position 1 with an error object
*/
// nop hack to pass jslint
exports.nop(_);
onEventError(state.errorDefault);
},
callError2: function (_, __, onEventError) {
/*
this function calls the onEventError callback in arg position 2 with an error object
*/
// nop hack to pass jslint
exports.nop(_, __);
onEventError(state.errorDefault);
},
_callX_default_test: function (onEventError) {
/*
this function tests callX's default handling behavior
*/
exports.callArg0(function (error) {
// validate no error occurred
exports.assert(!error, error);
});
exports.callArg1(null, function (error) {
// validate no error occurred
exports.assert(!error, error);
});
exports.callArg2(null, null, function (error) {
// validate no error occurred
exports.assert(!error, error);
});
exports.callError0(function (error) {
// validate error occurred
exports.assert(error instanceof Error, error);
});
exports.callError1(null, function (error) {
// validate error occurred
exports.assert(error instanceof Error, error);
});
exports.callError2(null, null, function (error) {
// validate error occurred
exports.assert(error instanceof Error, error);
});
onEventError();
},
_debug_print: function (arg) {
/*
this internal function is used for tmp debugging,
and jslint will nag you to remove it if used
*/
console.error('\n\n\ndebug' + 'Print');
console.error.apply(console, arguments);
console.error();
// return arg for inspection
return arg;
},
__debug_print_default_test: function (onEventError) {
/*
this function tests _debug_print's default handling behavior
*/
var message;
exports.testMock(onEventError, stateRestore, [
[console, { error: function (_) {
message += (_ || '') + '\n';
} }]
], function (onEventError) {
message = '';
local._debug_print('_debug_print_default_test');
exports.assert(
message === '\n\n\ndebug' + 'Print\n_debug_print_default_test\n\n',
message
);
onEventError();
});
},
errorStack: function (error) {
/*
this function returns the error's stack or message attribute if possible
*/
return error.stack || error.message;
},
jsonStringifyOrdered: function (value, replacer, space) {
/*
this function JSON.stringify's the value with dictionaries in sorted order,
allowing reliable / reproducible string comparisons and tests
*/
return JSON.stringify(value && (typeof value === 'object' || Array.isArray(value)) ?
JSON.parse(local._jsonStringifyOrderedRecurse(value))
: value, replacer, space);
},
_jsonStringifyOrdered_default_test: function (onEventError) {
/*
this function tests jsonStringifyOrdered's default handling behavior
*/
var data;
// test undefined handling behavior
data = exports.jsonStringifyOrdered(undefined);
exports.assert(data === undefined, data);
// test function handling behavior
data = exports.jsonStringifyOrdered(exports.nop);
exports.assert(data === undefined, data);
// test default handling behavior
data = exports.jsonStringifyOrdered({
ee: {},
dd: [undefined],
cc: exports.nop,
bb: 2,
aa: 1
});
exports.assert(data === '{"aa":1,"bb":2,"dd":[null],"ee":{}}', data);
onEventError();
},
_jsonStringifyOrderedRecurse: function (value) {
/*
this function recurses the value looking for dictionaries to sort
*/
value = Array.isArray(value) ?
'[' + value.map(local._jsonStringifyOrderedRecurse).join(',') + ']'
: typeof value !== 'object' || !value ?
JSON.stringify(value)
// sort list of keys
: '{' + Object.keys(value).filter(function (key) {
return JSON.stringify(value[key]) !== undefined;
}).sort().map(function (key) {
return JSON.stringify(key) + ':' +
local._jsonStringifyOrderedRecurse(value[key]);
}).join(',') + '}';
return value === undefined ? 'null' : value;
},
nop: function () {
/*
this function performs no operation (nop)
*/
return;
},
onEventErrorDefault: function (error, data) {
/*
this function provides a default, error / data handling callback.
if an error is given, it will print the error's message and stack,
else it will print the data
*/
if (error) {
// print error
console.error('\nonEventErrorDefault - error\n' + exports.errorStack(error) + '\n');
// print data if it's defined and not an empty string
} else if (data !== undefined && data !== '') {
// debug data
console.log('\nonEventErrorDefault - data\n' + JSON.stringify(data, null, 2) + '\n');
}
},
_onEventErrorDefault_default_test: function (onEventError) {
/*
this function tests onEventErrorDefault's default handling behavior
*/
var message;
exports.testMock(onEventError, stateRestore, [
[console, {
error: function (_) {
message = _;
},
log: function (_) {
message = _;
}
}]
], function (onEventError) {
// test default handling behavior
message = null;
exports.onEventErrorDefault(null, '_onEventErrorDefault_default_test');
// validate data message
exports.assert(message ===
'\nonEventErrorDefault - data\n"_onEventErrorDefault_default_test"\n', message);
// test no data handling behavior
message = null;
exports.onEventErrorDefault(null, '');
// validate no message was printed
exports.assert(message === null, message);
// test error handling behavior
message = '';
exports.onEventErrorDefault(new Error('_onEventErrorDefault_default_test'));
// validate error message
exports.assert((/\nonEventErrorDefault - error\n.*_onEventErrorDefault_default_test/)
.test(message.split('\n').slice(0, 3).join('\n')), JSON.stringify(message));
onEventError();
});
},
onEventTimeout: function (onEventError, timeout, message) {
/*
this function sets a timer to throw and handle a timeout error
*/
var error;
error = new Error('onEventTimeout - timeout error - ' + timeout + ' ms - ' + message);
error.code = 'ETIMEDOUT';
return setTimeout(function () {
onEventError(error);
}, timeout);
},
_onEventTimeout_timeout_test: function (onEventError) {
/*
this function tests onEventTimeout's timeout handling behavior
*/
var timeElapsed;
timeElapsed = Date.now();
exports.onEventTimeout(function (error) {
exports.testTryCatch(function () {
// validate error occurred
exports.assert(error instanceof Error);
// validate error is timeout error
exports.assert(error.code === 'ETIMEDOUT');
timeElapsed = Date.now() - timeElapsed;
// validate timeElapsed passed is greater than timeout
// bug - ie might timeout slightly earlier so increase timeElapsed by a small amount
exports.assert(timeElapsed + 100 >= 2000, timeElapsed);
onEventError();
}, onEventError);
}, 2000, '_onEventTimeout_timeoutError_test');
},
setDefault: function (options, defaults) {
/*
this function recursively sets default values for unset leaf nodes in the options object
*/
Object.keys(defaults).forEach(function (key) {
var defaults2, options2;
defaults2 = defaults[key];
options2 = options[key];
// set default value
if (options2 === undefined) {
options[key] = defaults2;
return;
}
// recurse defaults2 if options2 and defaults2 are both objects
if (defaults2 && typeof defaults2 === 'object' &&
options2 && typeof options2 === 'object' &&
!Array.isArray(options2)) {
local.setDefault(options2, defaults2);
}
});
return options;
},
_setDefault_default_test: function (onEventError) {
/*
this function tests setDefault's default handling behavior
*/
var options;
options = exports.setDefault(
{ aa: 1, bb: {}, cc: [] },
{ aa: 2, bb: { cc: 2 }, cc: [1, 2] }
);
// validate options
exports.assert(
exports.jsonStringifyOrdered(options) === '{"aa":1,"bb":{"cc":2},"cc":[]}',
options
);
onEventError();
},
setOverride: function (options, override, backup, depth) {
/*
this function recursively overrides the options object with the override object,
and optionally saves the original options object to the backup object,
and optionally accepts the depth recursion limit
*/
local._setOverrideRecurse(options, override, backup || {}, depth || Infinity);
return options;
},
_setOverride_default_test: function (onEventError) {
/*
this function tests setOverride's default handling behavior
*/
var backup, data, options;
backup = {};
// test override handling behavior
options = exports.setOverride(
{ aa: 1, bb: { cc: 2 }, dd: [3, 4], ee: { ff: { gg: 5, hh: 6 } } },
{ aa: 2, bb: { dd: 3 }, dd: [4, 5], ee: { ff: { gg: 6 } } },
backup,
2
);
// validate backup
data = exports.jsonStringifyOrdered(backup);
exports.assert(data === '{"aa":1,"bb":{},"dd":[3,4],"ee":{"ff":{"gg":5,"hh":6}}}', data);
// validate options
data = exports.jsonStringifyOrdered(options);
exports.assert(data ===
'{"aa":2,"bb":{"cc":2,"dd":3},"dd":[4,5],"ee":{"ff":{"gg":6}}}', data);
// test restore handling behavior
exports.setOverride(options, backup);
// validate backup
data = exports.jsonStringifyOrdered(backup);
exports.assert(data === '{"aa":1,"bb":{"dd":3},"dd":[3,4],"ee":{"ff":{"gg":6}}}', data);
// validate options
data = exports.jsonStringifyOrdered(options);
exports.assert(data ===
'{"aa":1,"bb":{"cc":2},"dd":[3,4],"ee":{"ff":{"gg":5,"hh":6}}}', data);
onEventError();
},
_setOverrideRecurse: function (options, override, backup, depth) {
/*
this function
1. save the options item to the backup object
2. set the override item to the options object
3. recurse the override object
*/
var options2, override2;
Object.keys(override).forEach(function (key) {
options2 = options[key];
override2 = backup[key] = override[key];
if (depth <= 1 ||
// override2 is not a plain object
!(override2 && typeof override2 === 'object' && !Array.isArray(override2)) ||
// options2 is not a plain object
!(options2 && typeof options2 === 'object' && !Array.isArray(options2))) {
// 1. save the options item to the backup object
backup[key] = options2;
// 2. set the override item to the options object
options[key] = override2;
return;
}
// 3. recurse the override object
local._setOverrideRecurse(options2, override2, override2, depth - 1);
});
},
testMock: function (onEventError, stateRestore, mockList, test) {
/*
this function mocks the state given in the mockList while running the test callback
*/
var onEventError2;
// prepend mandatory mocks for async / unsafe functions
mockList = [
// suppress console.log
[console, { log: exports.nop }],
// enforce synchonicity by mocking timers as exports.callArg0
[global, { setInterval: exports.callArg0, setTimeout: exports.callArg0 }],
[global.process || {}, { exit: exports.nop }]
].concat(mockList);
onEventError2 = function (error) {
// restore state
stateRestore(exports.state);
mockList.reverse().forEach(function (mock) {
exports.setOverride(mock[0], mock[2], null, 1);
});
onEventError(error);
};
// run onEventError callback in mocked state in a try-catch block
try {
// mock state
mockList.forEach(function (mock) {
mock[2] = {};
exports.setOverride(mock[0], mock[1], mock[2], 1);
});
// run test
test(onEventError2);
} catch (error) {
onEventError2(error);
}
},
_testMock_error_test: function (onEventError) {
/*
this function tests testMock's error handling behavior
*/
exports.testMock(function (error) {
// validate error occurred
exports.assert(error instanceof Error, error);
onEventError();
}, stateRestore, [
], function () {
throw state.errorDefault;
});
},
testReportCreate: function (testReport1, testReport2) {
/*
this function
1. merges testReport2 into testReport1
2. merges testReport2.coverage into testReport1.coverage
3. returns testReport1 in html format
*/
var errorMessageList,
env,
file1,
file2,
testCaseNumber,
testPlatform1,
testReport,
text,
timeElapsedParse;
// part 1 - merge testReport2 into testReport1
[testReport1, testReport2].forEach(function (testReport, ii) {
ii += 1;
exports.setDefault(testReport, {
date: new Date().toISOString(),
errorMessageList: [],
testPlatformList: [],
timeElapsed: 0
});
// security - handle malformed testReport
exports.assert(
testReport && typeof testReport === 'object',
ii + ' invalid testReport ' + typeof testReport
);
exports.assert(
typeof testReport.timeElapsed === 'number',
ii + ' invalid testReport.timeElapsed ' + typeof testReport.timeElapsed
);
// security - handle malformed testReport.testPlatformList
testReport.testPlatformList.forEach(function (testPlatform) {
exports.setDefault(testPlatform, {
name: 'undefined',
testCaseList: [],
timeElapsed: 0
});
exports.assert(
typeof testPlatform.name === 'string',
ii + ' invalid testPlatform.name ' + typeof testPlatform.name
);
if (state.modeNodejs) {
testPlatform.name = testPlatform.name.replace(
(/^(browser|nodejs)/),
process.env.MODE_CI_BUILD + ' - $1'
);
}
exports.assert(
typeof testPlatform.timeElapsed === 'number',
ii + ' invalid testPlatform.timeElapsed ' + typeof testPlatform.timeElapsed
);
// security - handle malformed testReport.testPlatformList.testCaseList
testPlatform.testCaseList.forEach(function (testCase) {
exports.setDefault(testCase, {
errorMessage: '',
name: 'undefined',
timeElapsed: 0
});
exports.assert(
typeof testCase.errorMessage === 'string',
ii + ' invalid testCase.errorMessage ' + typeof testCase.errorMessage
);
exports.assert(
typeof testCase.name === 'string',
ii + ' invalid testCase.name ' + typeof testCase.name
);
exports.assert(
typeof testCase.timeElapsed === 'number',
ii + ' invalid testCase.timeElapsed ' + typeof testCase.timeElapsed
);
});
});
});
// merge testPlatformList
testReport2.testPlatformList.forEach(function (testPlatform2) {
testPlatform1 = null;
testReport1.testPlatformList.forEach(function (_, ii) {
// replace existing testPlatform1 with testPlatform2
if (_.name === testPlatform2.name) {
testPlatform1 = testReport1.testPlatformList[ii] = testPlatform2;
}
});
// push new testPlatform2
if (!testPlatform1) {
testReport1.testPlatformList.push(testPlatform2);
}
});
// update testReport1.timeElapsed
if (testReport1.timeElapsed < 0xffffffff) {
testReport1.timeElapsed += testReport2.timeElapsed;
}
testReport = testReport1;
testReport.testsFailed = 0;
testReport.testsPassed = 0;
testReport.testsPending = 0;
testReport.testPlatformList.forEach(function (testPlatform) {
testPlatform.testsFailed = 0;
testPlatform.testsPassed = 0;
testPlatform.testsPending = 0;
testPlatform.testCaseList.forEach(function (testCase) {
// update failed tests
Iif (testCase.errorMessage) {
testCase.status = 'failed';
testPlatform.testsFailed += 1;
testReport.testsFailed += 1;
// update passed tests
} else if (testCase.timeElapsed < 0xffffffff) {
testCase.status = 'passed';
testPlatform.testsPassed += 1;
testReport.testsPassed += 1;
// update pending tests
} else {
testCase.status = 'pending';
testPlatform.testsPending += 1;
testReport.testsPending += 1;
}
});
// update testPlatform.status
testPlatform.status = testPlatform.testsFailed ? 'failed' :
testPlatform.testsPending ? 'pending' :
'passed';
// sort testCaseList by status and name
testPlatform.testCaseList.sort(function (arg1, arg2) {
arg1 = arg1.status.replace('passed', 'z') + arg1.name.toLowerCase();
arg2 = arg2.status.replace('passed', 'z') + arg2.name.toLowerCase();
return arg1 <= arg2 ? -1 : 1;
});
// update testReport.timeElapsed
if (testPlatform.timeElapsed < 0xffffffff &&
testPlatform.timeElapsed > testReport.timeElapsed) {
testReport.timeElapsed = testPlatform.timeElapsed;
}
});
// sort testPlatformList by status and name
testReport.testPlatformList.sort(function (arg1, arg2) {
arg1 = arg1.status.replace('passed', 'z') + arg1.name.toLowerCase();
arg2 = arg2.status.replace('passed', 'z') + arg2.name.toLowerCase();
return arg1 <= arg2 ? -1 : 1;
});
// stop testReport timer
if (testReport.testsPending === 0 && testReport.timeElapsed > 0xffffffff) {
testReport.timeElapsed = Date.now() - testReport.timeElapsed;
}
// part 2 - merge testReport2.coverage into testReport1.coverage
testReport1.coverage = testReport1.coverage || {};
testReport2.coverage = testReport2.coverage || {};
Object.keys(testReport2.coverage).forEach(function (file) {
// if it doesn't exist, then create a coverage object for the given file
file1 = testReport1.coverage[file] = testReport1.coverage[file] ||
{ b: {}, f: {}, s: {} };
file2 = testReport2.coverage[file];
// merge branching statements
Object.keys(file2.b).forEach(function (lineno) {
file1.b[lineno] = file1.b[lineno] || [];
file2.b[lineno].forEach(function (count, ii) {
file1.b[lineno][ii] = file1.b[lineno][ii] || 0;
file1.b[lineno][ii] += count;
});
});
// merge function definitions
Object.keys(file2.f).forEach(function (lineno) {
file1.f[lineno] = file1.f[lineno] || 0;
file1.f[lineno] += file2.f[lineno];
});
// merge non-branching statements
Object.keys(file2.s).forEach(function (lineno) {
file1.s[lineno] = file1.s[lineno] || 0;
file1.s[lineno] += file2.s[lineno];
});
});
// merge remaining items from testReport2 into testReport1
exports.setDefault(testReport1, testReport2);
// part 3 - create and return html test-report
// json-copy testReport, which will be modified for html templating
testReport = JSON.parse(JSON.stringify(testReport));
// init env
env = (global.process && process.env) || {};
timeElapsedParse = function (obj) {
/*
this function parses test timeElapsed
*/
if (obj.timeElapsed > 0xffffffff) {
obj.timeElapsed = Date.now() - obj.timeElapsed;
}
};
// parse timeElapsed
timeElapsedParse(testReport);
testReport.testPlatformList.forEach(function (testPlatform) {
timeElapsedParse(testPlatform);
testPlatform.testCaseList.forEach(function (testCase) {
timeElapsedParse(testCase);
});
});
// create html test-report
testCaseNumber = 0;
if (!state.fileDict['/public/test-report.html.template']) {
return;
}
return exports.textFormat(
state.fileDict['/public/test-report.html.template'].data,
exports.setOverride(testReport, {
CI_BUILD_NUMBER: env.CI_BUILD_NUMBER,
// security - sanitize '<' in text
CI_COMMIT_INFO: String(env.CI_COMMIT_INFO).replace((/</g), '<'),
name: state.name,
// map testPlatformList
testPlatformList: testReport.testPlatformList.map(function (testPlatform, ii) {
errorMessageList = [];
testPlatform.screenshotImg = testPlatform.screenshotImg || (state.modeNodejs && (
(/PhantomJS/).test(testPlatform.name) ?
'test-report.screenshot.phantomjs.png'
: (/SlimerJS/).test(testPlatform.name) ?
'test-report.screenshot.slimerjs.png'
: required.fs.existsSync('.build/test-report.screenshot.travis.png') ?
'test-report.screenshot.travis.png'
: ''
));
return exports.setOverride(testPlatform, {
errorMessageList: errorMessageList,
// security - sanitize '<' in text
name: String(testPlatform.name).replace((/</g), '<'),
screenshot: testPlatform.screenshotImg ?
'<a class="testReportPlatformScreenshotA" href="' +
testPlatform.screenshotImg + '">' +
'<img class="testReportPlatformScreenshotImg" src="' +
testPlatform.screenshotImg + '">' +
'</a>'
: '',
// map testCaseList
testCaseList: testPlatform.testCaseList.map(function (testCase) {
testCaseNumber += 1;
Iif (testCase.errorMessage) {
// word wrap error message to 96 characters in html <pre> tag
errorMessageList.push({ errorMessage:
(testCaseNumber + '. ' + testCase.name + '\n' + testCase.errorMessage)
.split('\n')
.map(function (line) {
for (text = [line]; line.length > 96; line = text[text.length - 1]) {
line = [line.slice(0, 95) + '\\', ' ' + line.slice(95)];
text.splice(text.length - 1, 1, line[0], line[1]);
}
return text.join('\n');
})
.join('\n')
// security - sanitize '<' in text
.replace((/</g), '<') });
}
return exports.setOverride(testCase, {
testCaseNumber: testCaseNumber,
testReportTestStatusClass: 'testReportTest' +
testCase.status[0].toUpperCase() + testCase.status.slice(1)
});
}),
testReportPlatformPreClass: 'testReportPlatformPre' +
(errorMessageList.length ? '' : 'Hidden'),
testPlatformNumber: ii + 1
});
}),
testsFailedClass: testReport.testsFailed ? 'testReportTestFailed'
: 'testReportTestPassed'
})
);
},
testRun: function () {
/*
this function runs the tests
*/
var remaining, testPlatform, testReport, testReportHtml;
testReport = state.testReport;
// start testReport timer
testReport.timeElapsed = Date.now();
// init testPlatform
testPlatform = state.testPlatform;
// start testPlatform timer
testPlatform.timeElapsed = Date.now();
remaining = testPlatform.testCaseList.length;
testPlatform.testCaseList.forEach(function (testCase) {
var errorFinished, finished, onEventError;
onEventError = function (error) {
if (error) {
console.error('\ntestCase ' + testCase.name + ' failed\n' +
exports.errorStack(error));
// save test error
testCase.errorMessage = testCase.errorMessage || exports.errorStack(error) || '';
}
// error - multiple callbacks in test case
if (finished) {
errorFinished = new Error('testCase ' + testCase.name + ' called multiple times');
exports.onEventErrorDefault(errorFinished);
// save test error
testCase.errorMessage = testCase.errorMessage || exports.errorStack(errorFinished);
return;
}
finished = true;
// stop testCase timer
testCase.timeElapsed = Date.now() - testCase.timeElapsed;
// decrement test counter
remaining -= 1;
// create test-report when all tests have finished
if (remaining === 0) {
// stop testPlatform timer
testPlatform.timeElapsed = Date.now() - testPlatform.timeElapsed;
testReportHtml = exports.testReportCreate(testReport, {});
// print test-report summary
console.log(testReport.testPlatformList.map(function (testPlatform) {
return '\ntest-report - ' + testPlatform.name + '\n' +
(' ' + testPlatform.timeElapsed).slice(-8) + ' ms | ' +
(' ' + testPlatform.testsFailed).slice(-2) + ' failed | ' +
(' ' + testPlatform.testsPassed).slice(-3) + ' passed';
}).join('\n') + '\n');
// nodejs code
if (state.modeNodejs) {
// create html test-report
console.log('\ncreating test-report file://' + process.cwd() +
'/.build/test-report.html');
required.fs.writeFileSync('.build/test-report.html', testReportHtml);
// create html coverage report
if (state.modeCoverage) {
console.log('creating coverage report file://' + process.cwd() +
'/.build/coverage-report.html/' + state.name + '/index.html');
}
// create build badge
required.fs.writeFileSync(
'.build/build.badge.svg',
state.fileDict['.build/build.badge.svg'].data
// edit branch name
.replace(
(/0000 00 00 00 00 00/g),
new Date().toISOString().slice(0, 19).replace('T', ' ')
)
// edit branch name
.replace((/- master -/g), '| ' + process.env.CI_BRANCH + ' |')
// edit commit id
.replace(
(/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/g),
process.env.CI_COMMIT_ID
)
);
// create test-report badge
required.fs.writeFileSync(
'.build/test-report.badge.svg',
state.fileDict['.build/test-report.badge.svg'].data
// edit number of tests failed
.replace((/999/g), testReport.testsFailed)
// edit badge color
.replace((/d00/g), testReport.testsFailed ? 'd00' : '0d0')
);
// non-zero exit if tests failed
setTimeout(function () {
process.exit(testReport.testsFailed);
}, 1000);
// browser code
} else {
// notify saucelabs of test results
global.global_test_results = {
testReport: state.testReport,
testCallbackId: state.testCallbackId,
// extra stuff to keep saucelabs happy - https://saucelabs.com/docs/rest#jsunit
failed: state.testReport.testsFailed
};
Eif ((/\bmodeTestReportUpload=1\b/).test(location.search)) {
exports.ajax({
data: JSON.stringify(global.global_test_results),
method: 'POST',
url: '/test/test-report-upload'
}, exports.onEventErrorDefault);
}
}
}
};
// run test case in try-catch block
try {
// start testCase timer
testCase.timeElapsed = Date.now();
// ignore utility2 tests in fast mode
Iif (state.modeNodejs && state.modeFast && testCase.name.indexOf('utility2.') === 0) {
onEventError();
return;
}
// create dummy failed test for code coverage
if (state.modeTestFail) {
onEventError();
// code coverage for multiple callback error
onEventError();
// code coverage for thrown error
throw state.errorDefault;
}
testCase.callback(onEventError);
} catch (error) {
onEventError(error);
}
});
},
testTryCatch: function (callback, onEventError) {
/*
this function calls the callback in a try-catch block,
and falls back to onEventError if an error is thrown
*/
try {
callback();
} catch (error) {
onEventError(error);
}
},
_testTryCatch_default_test: function (onEventError) {
/*
this function tests testTryCatch's default handling behavior
*/
// test default handling behavior
exports.testTryCatch(exports.nop, onEventError);
// test error handling behavior
exports.testTryCatch(function () {
throw state.errorDefault;
}, function (error) {
// validate error occurred
exports.assert(error instanceof Error, error);
});
onEventError();
},
// ascii character reference
textExampleAscii: '\x00\x01\x02\x03\x04\x05\x06\x07\b\t\n\x0b\f\r\x0e\x0f' +
'\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f' +
' !"#$%&\'()*+,-./0123456789:;<=>?' +
'@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_' +
'`abcdefghijklmnopqrstuvwxyz{|}~\x7f',
textFormat: function (template, dict) {
/*
this function replaces the keys in given text template
with the key / value pairs provided by the dict
*/
var value;
dict = dict || {};
// search for keys in the template
return local._textFormatList(template, dict).replace((/\{\{[^{}]+\}\}/g), function (key) {
// lookup key's value in the dict
value = key.slice(2, -2);
return dict.hasOwnProperty(value) ? dict[value] : key;
});
},
_textFormat_default_test: function (onEventError) {
/*
this function tests textFormat's default handling behavior
*/
var data;
data = exports.textFormat('{{aa}}{{aa}}{{bb}}{{bb}}{{cc}}{{cc}}', {
// test string handling behavior
aa: 'aa',
// test non-string handling behavior
bb: undefined
});
exports.assert(data === 'aaaaundefinedundefined{{cc}}{{cc}}', data);
// test list handling behavior
data = exports.textFormat('[{{@list1}}[{{@list2}}{{aa}},{{/@list2}}],{{/@list1}}]', {
list1: [
// test null handling behavior
null,
// test recursive list handling behavior
{ list2: [{ aa: 'bb' }, { aa: 'cc' }] }
]
});
exports.assert(data === '[[{{@list2}}{{aa}},{{/@list2}}],[bb,cc,],]', data);
onEventError();
},
_textFormatList: function (template, dict) {
/*
this function replaces the keys in given text template
with the key / value pairs provided by the dict
*/
var rgx, match, onEventReplace;
onEventReplace = function (_, fragment) {
// nop hack to pass jslint
exports.nop(_);
return dict[match].map(function (dict) {
return exports.textFormat(fragment, dict);
}).join('');
};
rgx = (/\{\{@[^{]+\}\}/g);
while (true) {
// search for array keys in the template
match = rgx.exec(template);
if (!match) {
break;
}
// lookup key's value in the dict
match = match[0].slice(3, -2);
if (Array.isArray(dict[match])) {
template = template.replace(
new RegExp('\\{\\{@' + match + '\\}\\}([\\S\\s]*?)\\{\\{\\/@' + match + '\\}\\}'),
onEventReplace
);
}
}
return template;
},
tryCatchHandler: function (onEventError) {
/*
this function returns a callback that will call onEventError in a try-catch block
*/
return function (error, data) {
Iif (error) {
onEventError(error);
return;
}
try {
onEventError(null, data);
} catch (error2) {
onEventError(error2);
}
};
}
};
local._init();
}());
(function submoduleUtility2Browser() {
/*
this browser submodule exports useful utilities
*/
'use strict';
var local = {
_name: 'utility2.submoduleUtility2Browser',
_init: function () {
/*
this function inits the submodule
*/
var tmp;
if (state.modeNodejs) {
return;
}
// init this submodule
exports.initSubmodule(local);
// init state.timeoutDefault
tmp = (/\btimeoutDefault=(\d+)\b/).exec(location.search);
state.timeoutDefault = tmp ? Number(tmp[1]) : state.timeoutDefault;
// init ajax
local._initAjax();
// init test
local._initTest();
},
_initAjax: function () {
/*
this function inits the ajax api
*/
// init ajaxProgressDiv element
local._ajaxProgressDiv = document.getElementsByClassName('ajaxProgressDiv')[0] ||
document.createElement('div');
// init ajaxProgressBarDiv element
local._ajaxProgressBarDiv = document.getElementsByClassName('ajaxProgressBarDiv')[0] ||
document.createElement('div');
// check ajax progress status every second,
// and hide the ajax progress bar if necessary
local._ajaxProgressHide();
},
__initAjax_noAjaxProgressBar_test: function (onEventError) {
/*
this function tests _initAjax's no ajax progress bar handling behavior
*/
exports.testMock(onEventError, stateRestore, [
[document, {
createElement: exports.nop,
// disable finding ajax progress bar
getElementsByClassName: function () {
return [];
}
}],
[local, {
_ajaxProgressBarDiv: null,
_ajaxProgressDiv: null,
_ajaxProgressHide: exports.nop
}]
], function (onEventError) {
local._initAjax();
// validate #ajaxProgressBarDiv was not found
exports.assert(local._ajaxProgressBarDiv === undefined, local._ajaxProgressBarDiv);
// validate #ajaxProgressDiv was not found
exports.assert(local._ajaxProgressDiv === undefined, local._ajaxProgressDiv);
onEventError();
});
},
_initTest: function () {
/*
this function inits the test api
*/
var timerInterval;
// run tests in test mode
Iif (!(/\bmodeTest=1\b/).test(location.search)) {
return;
}
// save server-side testCallbackId
state.testCallbackId = (/\btestCallbackId=([^&]+)/).exec(location.search);
state.testCallbackId = state.testCallbackId && state.testCallbackId[1];
// run test after all external resources have been loaded
window.addEventListener('load', function () {
// init testReportDiv element
state.testReportDiv = document.createElement('div');
document.body.appendChild(state.testReportDiv);
// run tests
exports.testRun();
// create initial blank test page
state.testReportDiv.innerHTML = exports.testReportCreate(state.testReport, {});
// update test-report status every 1000 ms until finished
timerInterval = setInterval(function () {
// update state.testReportDiv in browser
state.testReportDiv.innerHTML = exports.testReportCreate(state.testReport, {});
Iif (state.testReport.testsPending === 0) {
// cleanup timerInterval
clearInterval(timerInterval);
}
}, 1000);
});
},
ajax: function (options, onEventError) {
/*
this function implements the the ajax function for the browser
*/
var data, error, ii, onEventEvent, onEventError2, timerTimeout, xhr;
// error handling
onEventError2 = function (error, data) {
Iif (error) {
// add http method / statusCode / url debug info to error.message
error.message = options.method + ' ' + xhr.status + ' - ' +
options.url + '\n' +
JSON.stringify((xhr.responseText || '').slice(0, 256) + '...') + '\n' +
// trim potentially very long html response
error.message.slice(0, 4096);
}
onEventError(error, data, xhr);
};
// event handling
onEventEvent = function (event) {
switch (event.type) {
case 'abort':
case 'error':
case 'load':
// cleanup timerTimeout
clearTimeout(timerTimeout);
// remove xhr from ajax progress list
ii = local._ajaxProgressList.indexOf(xhr);
Eif (ii >= 0) {
local._ajaxProgressList.splice(ii, 1);
}
Eif (!error) {
// handle abort or error event
Iif (event.type === 'abort' || event.type === 'error' || xhr.status >= 400) {
error = new Error(event.type);
// handle text data
} else {
data = xhr.responseText;
}
}
onEventError2(error, data);
break;
}
// increment ajax progress bar
Iif (local._ajaxProgressList.length !== 0) {
local._ajaxProgressIncrement();
return;
}
// finish ajax progress bar
switch (event.type) {
case 'load':
local._ajaxProgressUpdate('100%', 'ajaxProgressBarDivSuccess', 'loaded');
break;
default:
local._ajaxProgressUpdate('100%', 'ajaxProgressBarDivError', event.type);
}
};
// init xhr object
xhr = new XMLHttpRequest();
// debug xhr
state.debugXhr = xhr;
// xhr event handling
xhr.addEventListener('abort', onEventEvent);
xhr.addEventListener('error', onEventEvent);
xhr.addEventListener('load', onEventEvent);
xhr.addEventListener('loadstart', local._ajaxProgressIncrement);
xhr.addEventListener('progress', local._ajaxProgressIncrement);
xhr.upload.addEventListener('progress', local._ajaxProgressIncrement);
// set timerTimeout
timerTimeout = exports.onEventTimeout(function (timerTimeout) {
error = timerTimeout;
xhr.abort();
}, state.timeoutDefault, 'ajax');
// display ajax progress bar if hidden
Eif (local._ajaxProgressList.length === 0) {
local._ajaxProgressDiv.style.display = 'block';
}
local._ajaxProgressList.push(xhr);
// open url in xhr
xhr.open(options.method || 'GET', options.url);
// init xhr headers
Object.keys(options.headers || {}).forEach(function (key) {
xhr.setRequestHeader(key, options.headers[key]);
});
// send data through xhr
xhr.send(options.data);
},
_ajaxProgressHide: function () {
// keep track of how many consecutive cycles ajax progress is complete
if (local._ajaxProgressList.length === 0 &&
local._ajaxProgressDiv.style.display !== 'none') {
local._ajaxProgressHideMode += 1;
// if ajax progress is complete for 2 consecutive cycles,
// then hide ajax progress bar and reset ajax progress
if (local._ajaxProgressHideMode === 2) {
local._ajaxProgressHideMode = 0;
// hide ajax progress bar
local._ajaxProgressDiv.style.display = 'none';
// reset ajax progress
local._ajaxProgressState = 0;
local._ajaxProgressUpdate('0%', 'ajaxProgressBarDivLoading', 'loading');
}
} else {
local._ajaxProgressHideMode = 0;
}
// check ajax progress status every second
setTimeout(local._ajaxProgressHide, 1000);
},
_ajaxProgressHideMode: 0,
_ajaxProgressIncrement: function () {
/*
this function increments the ajax progress bar
*/
// this algorithm can indefinitely increment the ajax progress bar
// with successively smaller increments without ever reaching 100%
local._ajaxProgressState += 1;
local._ajaxProgressUpdate(
100 - 75 * Math.exp(-0.125 * local._ajaxProgressState) + '%',
'ajaxProgressBarDivLoading',
'loading'
);
},
_ajaxProgressList: [],
_ajaxProgressState: 0,
_ajaxProgressUpdate: function (width, type, label) {
/*
this function visually updates the ajax progress bar
*/
local._ajaxProgressBarDiv.style.width = width;
local._ajaxProgressBarDiv.className = local._ajaxProgressBarDiv.className
.replace((/ajaxProgressBarDiv\w+/), type);
local._ajaxProgressBarDiv.innerHTML = label;
}
};
local._init();
}());
(function submoduleUtility2Nodejs() {
/*
this nodejs submodule exports useful utilities
*/
'use strict';
var local = {
_name: 'utility2.submoduleUtility2Nodejs',
_init: function () {
/*
this function inits the submodule
*/
Iif (!state.modeNodejs) {
return;
}
// init this submodule
exports.initSubmodule(local);
// init required object
required = exports.required = exports.required || {};
// require builtin modules
[
'child_process', 'crypto',
'fs',
'http', 'https',
'module',
'path',
'url',
'vm'
].forEach(function (module) {
required[module] = required[module] || require(module);
});
// require external modules
[
'istanbul',
'jslint-lite'
].forEach(function (module) {
try {
required[module.replace((/-/g), '_')] = require(module);
} catch (ignore) {
}
});
// override state with package.json object
exports.setOverride(state, require(__dirname + '/package.json'));
// init and watch package files
local._initFile();
// run the following code only if this module is in the root directory
Iif (__dirname !== process.cwd()) {
return;
}
// init cli
local._initCli();
// init coverage
local._initCoverage();
// re-init and re-watch package files
local._initFile();
// init repl
local._initRepl();
// init server
local._initServer();
},
_initCli: function () {
/*
this function inits the cli
*/
var argv, tmp;
// json-copy process.argv before modifying it
argv = JSON.parse(JSON.stringify(process.argv));
// append process.env.npm_config_mode_* to argv
Object.keys(process.env).sort().forEach(function (key) {
tmp = (/^npm_config_(mode_.+)/).exec(key);
Iif (tmp) {
argv.push('--' + tmp[1] + '=' + (process.env[key] || 'false'));
}
});
// parse cli argv and integrate it into the state dict
argv.forEach(function (arg, ii) {
if (arg.indexOf('--') === 0) {
arg = arg.split('=');
// --foo=1 -> state.foo = 1
tmp = arg.length > 1 ? arg.slice(1).join('=')
// --foo bar -> state.foo = 'bar'
: argv[ii + 1] && argv[ii + 1].indexOf('--') !== 0 ? argv[ii + 1]
// --foo -> state.foo = true
: true;
// convert arg to camel case
arg = arg[0].slice(2).replace((/[\-_][a-z]/g), function (match) {
return match[1].toUpperCase();
});
// try to parse arg as json object
try {
state[arg] = JSON.parse(tmp);
// else keep arg as is
} catch (error) {
state[arg] = tmp;
}
}
});
Eif (state.modeTestReportMerge || process.env.MODE_TEST_REPORT_MERGE) {
// if it exists, then merge the previous test-report into state.testReport
Eif (required.fs.existsSync('.build/test-report.json')) {
exports.testReportCreate(state.testReport, require('./.build/test-report.json'));
}
// on exit, write state.testReport to .build/test-report.json
process.on('exit', function () {
// remove dummy failed tests used for code coverage
if (state.modeTestFail) {
state.testReport = { coverage: state.testReport.coverage };
}
required.fs.writeFileSync(
'.build/test-report.json',
JSON.stringify(state.testReport)
);
});
}
// init cli after all modules have been synchronously loaded
setTimeout(function () {
tmp = state.modeCliDict[state.modeCli];
Eif (tmp) {
tmp(argv, exports.onEventErrorDefault);
}
});
},
_initCoverage: function () {
/*
this function inits the coverage api
*/
var coverage;
// init testReport.coverage object
Object.keys(global).forEach(function (key) {
if (key.indexOf('$$cov_') === 0) {
coverage = state.testReport.coverage;
// reference state.testReport.coverage to global coverage object
state.testReport.coverage = global[key];
// merge old coverage object to the global coverage object
exports.testReportCreate(state.testReport, { coverage: coverage });
}
});
},
_initFile: function () {
/*
this function inits and watches package files.
it parses the file data, and saves it to state.fileDict
*/
var cacheFile, parseFile, removeSubmodule;
cacheFile = function (options) {
/*
this function creates a unique cache url for the file data
*/
var file, fileCache;
file = options.file;
// cache only package files or /public/* files
if ((/^(?:main.data|main.js|utility2.data|utility2.js)$/).test(file)) {
file = '/public/' + file;
}
if (file.indexOf('/public/') !== 0) {
return;
}
// add .js extension for main.data and utility2.data
if ((/^\/public\/(?:main\.data|utility2\.data)$/).test(file)) {
file += '.js';
}
// create unique cache url for the file data using its sha256 hash
fileCache = state[file] = state[file] || file + '.' +
required.crypto.createHash('sha256').update(options.data).digest('hex') +
required.path.extname(file);
state.fileDict[fileCache] = options;
};
parseFile = function (file) {
/*
this function parses the file data and saves it to state.fileDict
*/
var data;
// init state.fileDict[file]
state.fileDict[file] = {
dataRaw: required.fs.readFileSync(__dirname + '/' + file, 'utf8'),
file: file
};
data = state.fileDict[file].dataRaw
// comment out shebang
.replace((/^#!/), '//#!');
switch (file) {
case 'example.js':
state.stateBrowser.fileDict[file] = { data: data, file: file };
break;
case 'main.js':
case 'utility2.js':
// remove nodejs submodules from script
data = removeSubmodule(data, 'Nodejs');
// if state.modeCoverage flag is enabled, then instrument the script
if (state.modeCoverage) {
data = (new required.istanbul.Instrumenter())
.instrumentSync(data, __dirname + '/' + file);
}
break;
case 'main.data':
case 'utility2.data':
data.replace(
(/^\/\* FILE_BEGIN ([\S\s]+?) \*\/$([\S\s]+?)^\/\* FILE_END \*\/$/gm),
function (_, options, data2, ii) {
// nop hack to pass jslint
exports.nop(_);
options = JSON.parse(options);
// save options to state.fileDict
state.fileDict[options.file] = exports.setOverride(options, {
// preserve lineno
data: data.slice(0, ii).replace((/.*/g), '') + data2,
dataRaw: data2,
fileParent: file
});
// run each action in options.actionList
options.actionList.forEach(function (action) {
(state.fileActionDict[action] || exports.nop)(options);
});
// create unique cache url for the file data
cacheFile(options);
}
);
// cull file to only have submodules
data = ('}());\n\n\n\n' + data + '\n(function submoduleFooBrowser() {').replace((
/(^\}\(\)\);\n\n\n\n)([\S\s]+?)(^\(function submodule\w+(?:Browser|Nodejs|Shared)\(\) \{$)/gm
), function (_, header, body, footer) {
// nop hack to pass jslint
exports.nop(_);
// preserve lineno
return header + body.replace((/.*/g), '') + footer;
}).replace('}());\n\n\n\n', '').replace((/.*$/), '').trimRight();
// eval embedded nodejs script in data file
// remove browser submodules from script
required.vm.runInNewContext(removeSubmodule(data, 'Browser'), {
console: console,
__exports__: exports,
__require__: require
}, file);
// remove nodejs submodules from data file
data = removeSubmodule(data, 'Nodejs');
break;
}
// save file data to state.fileDict
state.fileDict[file].data = data.trimRight();
// create unique cache url for the file data
cacheFile(state.fileDict[file]);
// update state.stateBrowserJson
state.stateBrowserJson = JSON.stringify(state.stateBrowser);
};
removeSubmodule = function (script, mode) {
/*
this function removes submodules with the specified mode from the script
*/
return (script + '\n\n\n\n').replace(new RegExp(
'^\\(function submodule\\w+' + mode + '\\(\\) \\{[\\S\\s]+?^\\}\\(\\)\\);\n\n\n\n',
'gm'
), function (match) {
// preserve lineno
return match.replace((/.*/g), '');
}).trimRight();
};
// init data files
['utility2.data', 'main.data'].forEach(parseFile);
// run the following code only if this module is in the root directory
Iif (__dirname !== process.cwd()) {
return;
}
// watch and auto-init data files
['main.data', 'utility2.data'].forEach(function (file) {
// cleanup any existing watchers on the file
required.fs.unwatchFile(file);
// watch the file using 1000 ms polling
required.fs.watchFile(file, {
interval: 1000,
persistent: false
}, function (stat2, stat1) {
if (stat2.mtime >= stat1.mtime) {
// save file data to state.fileDict
parseFile(file);
}
});
});
// watch and auto-jslint js files
['example.js', 'main.js', 'utility2.js'].forEach(function (file) {
// save file data to state.fileDict
parseFile(file);
// cleanup any existing watchers on the file
required.fs.unwatchFile(file);
// watch the file using 1000 ms polling
required.fs.watchFile(file, {
interval: 1000,
persistent: false
}, function (stat2, stat1) {
if (stat2.mtime >= stat1.mtime) {
// if modified, auto-jslint the file
Eif (required.jslint_lite) {
required.jslint_lite.jslintPrint(
required.fs.readFileSync(file, 'utf8'),
file
);
}
// if modified, re-save file data to state.fileDict
parseFile(file);
}
});
});
},
_initFile_watchFile_test: function (onEventError) {
/*
this function tests _initFile's watchFile handling behavior
*/
var onEventRemaining, remaining, remainingError;
onEventRemaining = function (error) {
remaining -= 1;
remainingError = remainingError || error;
if (remaining === 0) {
onEventError(remainingError);
}
};
remaining = 0;
['utility2.data', 'utility2.js'].forEach(function (file) {
remaining += 3;
required.fs.stat(file, function (error, stat) {
onEventRemaining(error);
// test default watchFile handling behavior
required.fs.utimes(file, stat.atime, new Date(), onEventRemaining);
// test nop watchFile handling behavior
setTimeout(function () {
required.fs.utimes(file, stat.atime, stat.mtime, onEventRemaining);
}, 2000);
});
});
},
_initRepl: function () {
/*
this function inits the ropl debugger
*/
if (!state.modeRepl) {
return;
}
// export exports
global.exports = exports;
// export required
global.required = required;
// export state
global.state = state;
// start repl
require('repl').start({
eval: local._initReplEval,
useGlobal: true
});
},
_initReplEval: function (script, __, file, onEventError) {
/*
this function custom evals the repl stdin
*/
var match;
try {
// nop hack to pass jslint
exports.nop(__);
match = (/^\(([^ ]+)(.*)\n\)/).exec(script);
Eif (match && state.replParseDict[match[1]]) {
script = state.replParseDict[match[1]](match[2]);
}
onEventError(null, required.vm.runInThisContext(script, file));
} catch (error) {
onEventError(error);
}
},
__initReplEval_default_test: function (onEventError) {
/*
this function tests _initReplEval's default handling behavior
*/
[
'($\n)',
'(print\n)'
].forEach(function (script) {
local._initReplEval(script, null, 'repl', exports.nop);
});
onEventError();
},
_initServer: function () {
/*
this function inits the server
*/
if (!state.serverPort || state.serverPort === true) {
return;
}
state.serverPort = Math.floor(
// create random port in the inclusive range 0x8000 - 0xffff
state.serverPort === 'random' ? (Math.random() * 0xffff) | 0x8000
: state.serverPort
);
// validate state.serverPort
exports.assert(
0 < state.serverPort && state.serverPort <= 0xffff,
'invalid state.serverPort ' + state.serverPort
);
// init state.localhost
state.localhost = 'http://localhost:' + state.serverPort;
console.log('\nserver starting on port ' + state.serverPort + ' ...');
// init server with exports.serverMiddleware
required.http.createServer(function (request, response) {
exports.serverMiddleware(request, response, function (error) {
exports.serverRespondDefault(response, error ? 500 : 404, error);
});
})
// set server to listen on state.serverPort
.listen(state.serverPort, function () {
console.log('... server started on port ' + state.serverPort);
});
},
ajax: function (options, onEventError) {
/*
this functions performs an asynchronous http(s) request with error handling and timeout,
and passes the responseText to onEventError
*/
var finished,
modeIo,
onEventIo,
request,
response,
responseText,
timerTimeout,
urlParsed;
modeIo = 0;
onEventIo = function (error, data) {
modeIo = error instanceof Error ? -1 : modeIo + 1;
switch (modeIo) {
case 1:
// clear old timerTimeout
clearTimeout(timerTimeout);
// set timerTimeout
timerTimeout = exports.onEventTimeout(
onEventIo,
options.timerTimeout || state.timeoutDefault,
'ajax ' + options.url
);
// handle implicit localhost
if (options.url[0] === '/') {
options.url = state.localhost + options.url;
}
// parse options.url
urlParsed = required.url.parse(options.url);
// disable socket pooling
options.agent = options.agent || false;
// hostname needed for http(s).request
options.hostname = urlParsed.hostname;
// path needed for http(s).request
options.path = urlParsed.path;
// port needed for http(s).request
options.port = urlParsed.port;
// protocol needed for http(s).request
options.protocol = urlParsed.protocol;
// init headers
options.headers = options.headers || {};
// init content-length header
options.headers['content-length'] =
typeof options.data === 'string' ? Buffer.byteLength(options.data)
: Buffer.isBuffer(options.data) ? options.data.length
: 0;
onEventIo();
break;
case 2:
// make http(s) request
request = (options.protocol === 'https:' ? required.https : required.http)
.request(options, onEventIo)
// handle error event
.on('error', onEventIo);
// debug ajax request
state.debugAjaxRequest = request;
// send request and/or data
request.end(options.data);
break;
case 3:
response = error;
// debug ajax response
state.debugAjaxResponse = response;
// follow redirects
switch (response.statusCode) {
case 301:
case 302:
case 303:
case 304:
case 305:
case 306:
case 307:
// cleanup request
request.end();
// cleanup response
response.destroy();
// limit max redirects
options.redirected = options.redirected || 0;
options.redirected += 1;
if (options.redirected >= 4) {
onEventIo(new Error('ajax - too many http redirects to ' +
response.headers.location));
return;
}
// parse options.url
try {
urlParsed = required.url.parse(response.headers.location);
} catch (error2) {
onEventIo(error2);
return;
}
options.hostname = urlParsed.hostname || options.hostname;
options.path = urlParsed.path;
options.port = urlParsed.port || options.port;
options.protocol = urlParsed.protocol || options.protocol;
modeIo -= 2;
onEventIo();
return;
}
// concat response stream into responseText
exports.streamReadAll(response, onEventIo);
break;
case 4:
// init responseText
responseText = options.resultType === 'binary' ? data : data.toString();
// error handling for http status code >= 400
if (response.statusCode >= 400) {
onEventIo(new Error(responseText));
return;
}
// successful response
onEventIo(null, responseText);
break;
default:
// ignore error / data if already finished
Iif (finished) {
return;
}
finished = true;
// cleanup timerTimeout
clearTimeout(timerTimeout);
// cleanup request socket
Eif (request) {
request.destroy();
}
// cleanup response socket
Eif (response) {
response.destroy();
}
if (error) {
// add http method / statusCode / url debug info to error.message
error.message = options.method + ' ' + (response && response.statusCode) + ' - ' +
options.url + '\n' +
JSON.stringify((responseText || '').slice(0, 256) + '...') + '\n' +
// trim potentially very long html response
error.message.slice(0, 4096);
onEventError(error, responseText);
return;
}
onEventError(null, responseText);
}
};
onEventIo();
},
fileActionDict_exportFile: function (options) {
/*
this function exports the file to stateBrowser
*/
state.stateBrowser.fileDict[options.file] = options;
exports.setOverride(state.stateBrowser, {
description: state.description,
name: state.name
});
},
fileActionDict_format: function (options) {
/*
this function formats the file with the state dict
*/
options.data = exports.textFormat(options.data, state);
},
fileActionDict_install: function (options) {
/*
this function installs the file
*/
// run the following code only if this module is in the root directory
Iif (state.modeCli === 'npmInstall' && __dirname === process.cwd()) {
required.fs.writeFileSync(options.file, options.data);
}
},
fileActionDict_lint: function (options) {
/*
this function lints the file
*/
switch (required.path.extname(options.file)) {
case '.js':
case '.json':
Eif (required.jslint_lite && required.jslint_lite.jslintPrint) {
required.jslint_lite.jslintPrint(options.data, options.file);
}
break;
}
},
fileActionDict_trim: function (options) {
/*
this function trims the file data
*/
options.data = options.data.trim();
},
fileActionDict_updateExternal: function (options) {
/*
this function updates external sources embedded in the data file
*/
// do not update external resources unless specified in cli
Eif (state.modeCli !== 'updateExternal') {
return;
}
console.log('updateExternal - updating ' + options.externalUrl);
exports.ajax({ url: options.externalUrl }, function (error, data) {
if (error) {
exports.onEventErrorDefault(error);
return;
}
state.fileDict[options.fileParent].dataRaw =
state.fileDict[options.fileParent].dataRaw.replace(options.dataRaw, '\n' +
data.trim() + '\n');
});
},
modeCliDict_coverageReportBadgeCreate: function () {
/*
this function creates a coverage badge
*/
var percent;
percent = (/Statements: <span class="metric">([.\d]+)/)
.exec(required.fs.readFileSync('.build/coverage-report.html/index.html', 'utf8'))[1];
required.fs.writeFileSync(
'.build/coverage-report.badge.svg',
state.fileDict['.build/coverage-report.badge.svg']
.data
// edit coverage badge percent
.replace((/100.0/g), percent)
// edit coverage badge color
.replace(
(/0d0/g),
('0' + Math.round((100 - Number(percent)) * 2.21).toString(16))
.slice(-2) +
('0' + Math.round(Number(percent) * 2.21).toString(16)).slice(-2) +
'00'
)
);
},
_modeCliDict_coverageReportBadgeCreate_default_test: function (onEventError) {
/*
this function tests modeCliDict_coverageReportBadgeCreate's default handling behavior
*/
exports.testMock(onEventError, stateRestore, [
[required, { fs: {
readFileSync: function () {
return 'Statements: <span class="metric">50.0%';
},
writeFileSync: exports.nop
} }]
], function (onEventError) {
local.modeCliDict_coverageReportBadgeCreate();
onEventError();
});
},
modeCliDict_githubContentsFilePush: function (argv, onEventError) {
/*
this function pushes the local file1 to the remote github file2
*/
var blob, file1, file2, modeIo, onEventIo, sha;
modeIo = 0;
onEventIo = function (error, data) {
modeIo += 1;
switch (modeIo) {
case 1:
file1 = argv[3];
file2 = file1.replace(argv[4], argv[5]);
console.log('pushing file https://' +
process.env.GITHUB_REPO.replace('/', '.github.io/') + '/' + file2);
exports.ajax({
headers: {
// github oauth authentication
authorization: 'token ' + process.env.GITHUB_TOKEN,
// bug - github api requires user-agent header
'user-agent': 'unknown'
},
url: 'https://api.github.com/repos/' + process.env.GITHUB_REPO +
'/contents/' + required.path.dirname(file2) + '?ref=gh-pages'
}, onEventIo);
break;
case 2:
blob = required.fs.readFileSync(file1);
data = data && JSON.parse(data);
if (Array.isArray(data)) {
// calculate git blob sha
sha = required.crypto.createHash('sha1')
.update('blob ' + blob.length + '\x00')
.update(blob)
.digest('hex');
data.forEach(function (dict) {
if (dict.path === file2) {
// no need to update if local and remote git blob sha matches
if (dict.sha === sha) {
process.exit();
}
sha = dict.sha;
}
});
}
exports.ajax({
data: JSON.stringify({
branch: 'gh-pages',
content: blob.toString('base64'),
message: '[skip ci] update file ' + file2,
sha: sha
}),
headers: {
// github oauth authentication
authorization: 'token ' + process.env.GITHUB_TOKEN,
// bug - github api requires user-agent header
'user-agent': 'unknown'
},
method: 'PUT',
url: 'https://api.github.com/repos/' + process.env.GITHUB_REPO + '/contents/' + file2
}, onEventIo);
break;
default:
onEventError(error);
process.exit(!!error);
}
};
onEventIo();
},
_modeCliDict_githubContentsFilePush_default_test: function (onEventError) {
/*
this function tests modeCliDict_githubContentsFilePush's default handling behavior
*/
var ajax1, mode;
exports.testMock(onEventError, stateRestore, [
[console, { error: exports.nop }],
[exports, { ajax: function (_, onEventError) {
// nop hack to pass jslint
exports.nop(_);
mode += 1;
switch (mode) {
case 1:
ajax1(onEventError);
break;
case 2:
onEventError();
break;
}
} }],
[required, {
fs: { readFileSync: function () {
return new Buffer(0);
} }
}],
[process, { argv: [null, null, null, 'aa/cc', 'aa', 'bb'] }]
], function (onEventError) {
// test file create handling behavior
mode = 0;
ajax1 = function (onEventError) {
// test file create handling behavior
onEventError(null, '{}');
};
local.modeCliDict_githubContentsFilePush(process.argv, function (error) {
exports.testTryCatch(function () {
// validate no error occurred
exports.assert(!error, error);
}, onEventError);
});
// test file update handling behavior
mode = 0;
ajax1 = function (onEventError) {
onEventError(null, JSON.stringify([
// test blob path mismatch handling behavior
{},
// test blob sha match handling behavior
// test file update handling behavior
{ path: 'bb/cc', sha: 'e69de29bb2d1d6434b8b29ae775ad8c2e48c5391' },
// test blob sha mismatch handling behavior
{ path: 'bb/cc' }
]));
};
local.modeCliDict_githubContentsFilePush(process.argv, function (error) {
exports.testTryCatch(function () {
// validate no error occurred
exports.assert(!error, error);
}, onEventError);
});
onEventError();
});
},
modeCliDict_npmTest: function () {
/*
this function runs npm test
*/
exports.testRun();
},
modeCliDict_saucelabsScreenshot: function () {
/*
this function grabs screenshots using saucelabs
*/
[
{
file: 'test-report.screenshot.heroku.png',
url: process.env.HEROKU_URL + '/?modeTest=1'
},
{
file: 'test-report.screenshot.travis.png',
url: 'https://travis-ci.org/' + process.env.GITHUB_REPO
}
].forEach(function (options) {
local._saucelabsScreenshot(options, exports.onEventErrorDefault);
});
},
modeCliDict_saucelabsTest: function () {
/*
this function runs saucelabs tests with the given json options piped from stdin
*/
var options;
options = JSON.parse(required.fs.readFileSync('.install/saucelabs-config.json'));
// init state
exports.setOverride(state, options.stateOverride);
// remove stateOverride param
options.stateOverride = undefined;
state.testPlatform.testCaseList = [{
callback: function (onEventError) {
local._saucelabsTest(options, onEventError);
},
name: local._name + '.__saucelabsTest_default_test'
}];
exports.testRun();
},
modeCliDict_updateExternal: function () {
/*
this function updates external resources in main.data and utility2.data
*/
// the updating code is done elsewhere.
// all we have to do is to save the updated file data on exit
process.on('exit', function () {
['main.data', 'utility2.data'].forEach(function (file) {
required.fs.writeFileSync(file, state.fileDict[file].dataRaw);
});
});
},
_phantomjsTest: function (file, onEventError) {
/*
this function spawns a phantomjs / slimerjs process from the given file
to test a webpage
*/
var onEventError2, testCallbackId, timerTimeout;
onEventError2 = function (error) {
// cleanup timerTimeout
clearTimeout(timerTimeout);
// garbage collect testCallbackId
delete state.testCallbackDict[testCallbackId];
onEventError(error);
};
// set timerTimeout
timerTimeout = exports.onEventTimeout(
onEventError2,
state.timeoutDefault,
file
);
// init testCallbackId
testCallbackId = Math.random().toString('36').slice(2);
state.testCallbackDict[testCallbackId] = onEventError2;
// spawn a phantomjs / slimerjs process from the given file to test a webpage
exports.shell({ argv: [
file,
'.install/phantomjs-test.js',
new Buffer(JSON.stringify({ argv0: required.path.basename(file), url: state.localhost +
'/?modeTest=1' +
'&modeTestReportUpload=1' +
'&testCallbackId=' + testCallbackId +
'&timeoutDefault=' + state.timeoutDefault })).toString('base64')
], modeDebug: false });
},
__phantomjsTest_default_test: function (onEventError) {
/*
this function tests _phantomjsTest's default handling behavior
*/
var onEventRemaining, remaining, remainingError;
onEventRemaining = function (error) {
remainingError = remainingError || error;
remaining -= 1;
if (remaining === 0) {
onEventError(remainingError);
}
};
remaining = 2;
// run browser test in phantomjs
local._phantomjsTest(require('phantomjs').path, onEventRemaining);
// run browser test in slimerjs
local._phantomjsTest(require('slimerjs').path, onEventRemaining);
},
replParseDict_$: function (arg2) {
/*
this function runs shell commands from the repl interpreter
*/
exports.shell({
argv: ['/bin/bash', '-c', exports.textFormat(arg2, state)],
modeDebug: false
});
},
replParseDict_print: function (arg2) {
/*
this function prints arg2 in stringified form from the repl interpreter
*/
return '(console.log(String(' + arg2 + '))\n)';
},
serverMiddleware: function (request, response, next) {
var modeIo, onEventIo, path;
modeIo = 0;
onEventIo = function () {
modeIo += 1;
switch (modeIo) {
case 1:
// debug server request
state.debugServerRequest = request;
// debug server response
state.debugServerResponse = response;
// security - validate request url path
path = request.url;
// security - enforce max url length
Eif (path.length <= 4096) {
// get base path without search params
path = (/[^#&?]*/).exec(path)[0];
Eif (path &&
// security - enforce max path length
path.length <= 256 &&
// security - disallow relative path
!(/\.\/|\.$/).test(path)) {
// dyanamic path handler
request.urlPathNormalized = required.path.resolve(path);
onEventIo();
return;
}
}
next(new Error('serverMiddleware - invalid url ' + path));
break;
case 2:
path = request.urlPathNormalized;
// security - if state.modeTest is falsey, then disallow /test/* path
Iif (path.indexOf('/test/') === 0 && !state.modeTest) {
next();
return;
}
// notify browser to cache /public/cache/* path
Iif (path.indexOf('/public/cache/') === 0) {
exports.serverRespondWriteHead(response, null, {
'cache-control': 'max-age=86400'
});
}
// walk up parent path, all the while looking for a matching handler for the path
while (!(state.serverPathHandlerDict[path] || path === '/')) {
path = required.path.dirname(path);
}
// found a handler matching request path
Eif (state.serverPathHandlerDict[path]) {
// debug server request handler
state.debugServerHandler = state.serverPathHandlerDict[path];
// process request with error handling
try {
onEventIo();
} catch (error) {
next(error);
}
// else goto next middleware
} else {
next();
}
break;
case 3:
state.serverPathHandlerDict[path](request, response, next);
break;
}
};
onEventIo();
},
'serverPathHandlerDict_/': function (request, response, next) {
// serve main page
if (request.urlPathNormalized === '/') {
exports.serverRespondData(response, 200, 'text/html', exports.textFormat(
state.fileDict['/public/main.html'].data,
{ stateBrowserJson: state.stateBrowserJson }
));
return;
}
// else fallback to next middleware
next();
},
'serverPathHandlerDict_/public': function (request, response, next) {
/*
this function responds with public cached data if it exists
*/
var options;
options = state.fileDict[request.urlPathNormalized];
// cached data exists - respond with cached data
Eif (options) {
exports.serverRespondData(
response,
200,
state.mimeLookupDict[
required.path.extname(request.urlPathNormalized)
] || 'application/octet-stream',
options.data
);
return;
}
// cached data does not exist - goto next middleware
next();
},
'serverPathHandlerDict_/test/hello.json': function (_, response) {
// nop hack to pass jslint
exports.nop(_);
exports.serverRespondData(response, 200, 'application/json', '"hello"');
},
'serverPathHandlerDict_/test/test-report-upload': function (request, response, next) {
/*
this function receives and parses uploaded test-reports
*/
var modeIo, onEventIo;
modeIo = 0;
onEventIo = function (error, data) {
modeIo = error instanceof Error ? -1 : modeIo + 1;
switch (modeIo) {
case 1:
// if report uploads are not allowed, then goto next middleware
Iif (!state.modeTestReportUpload) {
next();
return;
}
// stream test-report data into buffer
exports.streamReadAll(
request,
// security - use try-catch block to parse potential malformed data
exports.tryCatchHandler(onEventIo)
);
break;
case 2:
data = JSON.parse(data);
// debug data
state.debugTestReportUpload = data;
// merge data.testReport into state.testReport
exports.testReportCreate(state.testReport, data.testReport);
// call testCallbackId callback if it exists
(state.testCallbackDict[data.testCallbackId] || exports.onEventErrorDefault)(
data.testReport.testsFailed ? new Error('tests failed') : null
);
response.end();
break;
default:
next(error);
}
};
onEventIo();
},
serverRespondDefault: function (response, statusCode, error) {
/*
this function responds with a default message or error stack for the given statusCode
*/
// set response / statusCode / contentType
exports.serverRespondWriteHead(response, statusCode, { 'content-type': 'text/plain' });
// end response with error stack
Iif (error) {
exports.onEventErrorDefault(error);
response.end(exports.errorStack(error));
return;
}
// end response with default statusCode message
response.end(statusCode + ' ' +
(required.http.STATUS_CODES[statusCode] || 'Unknown Status Code'));
},
serverRespondData: function (response, statusCode, contentType, data) {
/*
this function responds with the given data
*/
// set response / statusCode / contentType
exports.serverRespondWriteHead(response, statusCode, { 'content-type': contentType });
// end response with data
response.end(data);
},
serverRespondWriteHead: function (response, statusCode, headers) {
/*
this function sets the response object's statusCode / headers
*/
Eif (!response.headersSent) {
// set response.statusCode
response.statusCode = statusCode || response.statusCode;
Object.keys(headers).forEach(function (key) {
// set only truthy headers
Eif (headers[key]) {
response.setHeader(key, headers[key]);
}
});
}
},
shell: function (options) {
/*
this function executes shell scripts with timeout handling
*/
var child, timerTimeoutPid;
// init options.stdio
options.stdio = options.stdio || ['ignore', 1, 2];
// debug shell options
Iif (options.modeDebug !== false) {
console.log('shell - options ' + JSON.stringify(options));
}
// spawn shell in child process
child = required.child_process.spawn(options.argv[0], options.argv.slice(1), options);
// set timerTimeoutPid
timerTimeoutPid = required.child_process.spawn('/bin/sh', ['-c', 'sleep ' +
((options.timeout || state.timeoutDefault) / 1000) + '; kill ' + child.pid +
' 2>/dev/null'], { stdio: 'ignore' });
// unref timerTimout process so it can continue tracking the original shell
// after nodejs exits
timerTimeoutPid.unref();
timerTimeoutPid = timerTimeoutPid.pid;
// debug shell exit code
child
// handle error event
.on('error', exports.onEventErrorDefault)
// handle exit event
.on('exit', function (exitCode) {
try {
// cleanup timerTimeoutPid
process.kill(timerTimeoutPid);
} catch (ignore) {
}
console.log('shell - process ' + child.pid + ' exited with code ' + exitCode);
});
return child;
},
streamReadAll: function (readableStream, onEventError) {
/*
this function concats data from readable stream and passes it to callback when done
*/
var chunks;
chunks = [];
// read data from readable stream
readableStream.on('data', function (chunk) {
chunks.push(chunk);
// call callback when finished reading
}).on('end', function () {
onEventError(null, Buffer.concat(chunks));
// pass any errors to the callback
}).on('error', onEventError);
},
_saucelabsTest: function (options, onEventError) {
/*
this function requests saucelabs to test a webpage
*/
var completed,
modeIo,
onEventIo,
onEventRemaining,
remaining,
remainingDict,
remainingError,
timerInterval,
timerTimeout;
modeIo = 0;
onEventIo = function (error, data) {
modeIo = error instanceof Error ? -1 : modeIo + 1;
switch (modeIo) {
case 1:
onEventRemaining = function (error) {
remainingError = remainingError || error;
remaining -= 1;
if (remaining === 0) {
modeIo = -2;
onEventIo(remainingError);
}
};
options = {
data: JSON.stringify(exports.setOverride(options, {
build: process.env.CI_BUILD_NUMBER_SAUCELABS,
// specify custom test framework in saucelabs
framework: 'custom',
// reduce timeoutDefault to account for saucelabs startup time
// bug - saucelabs only accepts integers for max-duration
'max-duration': Math.ceil(Math.max(0.00075 * state.timeoutDefault, 60)),
url: exports.textFormat(options.url, {
host: process.env.HEROKU_URL || state.localhost,
// reduce timeoutDefault to account for max-duration
timeoutDefault: 0.5 * state.timeoutDefault
})
})),
headers: {
authorization: 'Basic ' + new Buffer(process.env.SAUCE_USERNAME + ':' +
process.env.SAUCE_ACCESS_KEY).toString('base64'),
'content-type': 'application/json'
},
method: 'POST',
// platforms needed for later debugging
platforms: options.platforms,
url: 'https://saucelabs.com/rest/v1/' + process.env.SAUCE_USERNAME + '/js-tests',
url0: options.url
};
remaining = 0;
remainingDict = {};
// set timeout for _saucelabsTest
timerTimeout = exports.onEventTimeout(
onEventIo,
state.timeoutDefault,
'_saucelabsTest ' + options.url0
);
exports.ajax(options, exports.tryCatchHandler(onEventIo));
break;
case 2:
// JSON.parse data
data = JSON.parse(data);
// parse initial saucelabs response
console.log('\nsaucelabs - tests started - ' + JSON.stringify({
request: JSON.parse(options.data),
response: data
}));
// create remainingDict of test id's
data['js tests'].forEach(function (id, ii) {
remaining += 1;
remainingDict[id] = { id: id, platform: options.platforms[ii] };
});
// set timerInterval to poll saucelabs for test status
timerInterval = setInterval(function () {
// request test status
exports.ajax(exports.setOverride(options, {
data: JSON.stringify({ 'js tests': Object.keys(remainingDict) }),
url: 'https://saucelabs.com/rest/v1/' + process.env.SAUCE_USERNAME +
'/js-tests/status'
}), exports.tryCatchHandler(onEventIo));
}, 30000);
break;
case 3:
// check status of polled tests from saucelabs response
// decrement modeIo to repeat io loop
modeIo -= 1;
// JSON.parse data
data = JSON.parse(data);
completed = completed || data.completed || (/error/).test(data.status);
data['js tests'].forEach(function (data) {
Eif (remainingDict[data.id]) {
// test finished - remove from remainingDict
if (completed || data.result || (/error/).test(data.status)) {
// remove test from remainingDict
delete remainingDict[data.id];
// merge browser test-report
local._saucelabsMerge(data, onEventRemaining);
// test pending - update test status
} else {
remainingDict[data.id] = {
id: data.id,
job_id: data.job_id,
platform: data.platform,
status: data.status
};
}
}
});
console.log('\nsaucelabs - tests remaining - ' + JSON.stringify(remainingDict));
break;
default:
remaining = -2;
// cleanup timerInterval
clearInterval(timerInterval);
// cleanup timerTimeout
clearTimeout(timerTimeout);
onEventError(error);
}
};
onEventIo();
},
_saucelabsMerge: function (testReport, onEventError) {
/*
this function merges the saucelabs test-report into state.testReport
*/
var errorDefault, jobId, modeIo, onEventIo;
modeIo = 0;
onEventIo = function (error, data) {
modeIo = error instanceof Error ? -1 : modeIo + 1;
switch (modeIo) {
case 1:
// init errorDefault
errorDefault = new Error(JSON.stringify(testReport));
// init jobId
jobId = testReport.job_id;
// fetch saucelabs logs for the given jobId
exports.ajax({
url: 'https://saucelabs.com/jobs/' + jobId + '/log.json'
}, exports.tryCatchHandler(onEventIo));
break;
case 2:
// JSON.parse data
data = JSON.parse(data);
// fetch testReport from saucelabs logs
data.forEach(function (data) {
testReport = (data && data.result && data.result.testReport) || testReport;
});
// testReport recovery succeeded case
Eif (testReport.testPlatformList) {
// clear errorDefault
errorDefault = null;
// capture saucelabs screenshot
testReport.testPlatformList[0].screenshotImg =
'https://assets.saucelabs.com/jobs/' + jobId + '/0003screenshot.png';
}
onEventIo();
break;
default:
// notify saucelabs of pass / fail test statue
exports.ajax({
data: '{"passed":' + !errorDefault + '}',
headers: {
authorization: 'Basic ' + new Buffer(process.env.SAUCE_USERNAME +
':' + process.env.SAUCE_ACCESS_KEY).toString('base64'),
'content-type': 'application/json'
},
method: 'PUT',
url: 'https://saucelabs.com/rest/v1/' + process.env.SAUCE_USERNAME + '/jobs/' +
jobId
}, exports.nop);
// testReport recovery failed case
Iif (errorDefault) {
// create a minimal testReport reporting saucelabs internal error
testReport = { testPlatformList: [{
name: 'browser - saucelabs ' +
(testReport.platform || ['unknown user agent']).join(' '),
testCaseList: [{
errorMessage: exports.errorStack(errorDefault),
name: '__saucelabsTest_default_test',
timeElapsed: testReport.timeElapsed
}],
timeElapsed: testReport.timeElapsed
}] };
}
// merge recovered testReport into state.testReport
exports.testReportCreate(state.testReport, testReport);
onEventError(errorDefault);
}
};
onEventIo();
},
_saucelabsScreenshot: function (options, onEventError) {
/*
this function returns a url for the screenshot captured by saucelabs
*/
var jobId,
modeIo,
onEventIo,
remaining,
screenshotImg,
timerTimeout;
modeIo = 0;
onEventIo = function (error, data) {
modeIo = error instanceof Error ? -1 : modeIo + 1;
switch (modeIo) {
case 1:
// set timeout for screenshot to capture in seconds
exports.setOverride(options, {
data: JSON.stringify(exports.setOverride(JSON.parse(JSON.stringify(options)), {
// specify custom test framework in saucelabs
framework: 'custom',
// set max-duration timeout in seconds
// bug - saucelabs only accepts integers for max-duration
'max-duration': Math.ceil(0.00025 * state.timeoutDefault),
platforms: [["linux", "googlechrome", ""]],
// disable video recording for faster performance
'record-video': false
})),
headers: {
authorization: 'Basic ' + new Buffer(process.env.SAUCE_USERNAME + ':' +
process.env.SAUCE_ACCESS_KEY).toString('base64'),
'content-type': 'application/json'
},
method: 'POST',
url: 'https://saucelabs.com/rest/v1/' + process.env.SAUCE_USERNAME + '/js-tests',
url0: options.url
});
remaining = 1;
// set timeout for _saucelabsScreenshot
timerTimeout = exports.onEventTimeout(
onEventIo,
state.timeoutDefault,
'_saucelabsScreenshot ' + options.url0
);
exports.ajax(options, onEventIo);
break;
case 2:
exports.setOverride(options, {
data: data,
url: 'https://saucelabs.com/rest/v1/' + process.env.SAUCE_USERNAME +
'/js-tests/status'
});
onEventIo();
break;
case 3:
setTimeout(function () {
exports.ajax(options, exports.tryCatchHandler(onEventIo));
}, 5000);
break;
case 4:
jobId = JSON.parse(data)['js tests'][0].job_id;
if (jobId === 'job not ready') {
modeIo -= 2;
onEventIo();
return;
}
remaining -= 1;
Eif (remaining === 0) {
screenshotImg = 'https://assets.saucelabs.com/jobs/' + jobId +
'/0003screenshot.png';
setTimeout(onEventIo, 0.25 * state.timeoutDefault);
}
break;
case 5:
// fetch screenshotImg
exports.ajax({
resultType: 'binary',
url: screenshotImg
}, onEventIo);
break;
case 6:
// save screenshotImg
console.log('_saucelabsScreenshot - saving screenshot of ' + options.url0 +
' to ' + '.build/' + options.file);
required.fs.writeFile('.build/' + options.file, data, onEventIo);
break;
default:
remaining = -2;
// cleanup timerTimeout
clearTimeout(timerTimeout);
onEventError(error);
}
};
onEventIo();
}
};
local._init();
}());
|