File: test_testresult.py

package info (click to toggle)
python-testtools 2.3.0-5
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,344 kB
  • sloc: python: 13,873; makefile: 126; sh: 2
file content (3078 lines) | stat: -rw-r--r-- 110,714 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
# Copyright (c) 2008-2016 testtools developers. See LICENSE for details.

"""Test TestResults and related things."""

__metaclass__ = type

import codecs
import datetime
import doctest
from itertools import chain, combinations
import os
import re
import shutil
import sys
import tempfile
import threading
from unittest import TestSuite
from extras import safe_hasattr, try_imports, try_import

Queue = try_imports(['Queue.Queue', 'queue.Queue'])

testresources = try_import('testresources')

from testtools import (
    CopyStreamResult,
    ExtendedToOriginalDecorator,
    ExtendedToStreamDecorator,
    MultiTestResult,
    PlaceHolder,
    ResourcedToStreamDecorator,
    StreamFailFast,
    StreamResult,
    StreamResultRouter,
    StreamSummary,
    StreamTagger,
    StreamToDict,
    StreamToExtendedDecorator,
    StreamToQueue,
    Tagger,
    TestCase,
    TestControl,
    TestResult,
    TestResultDecorator,
    TestByTestResult,
    TextTestResult,
    ThreadsafeForwardingResult,
    TimestampingStreamResult,
    testresult,
    )
from testtools.compat import (
    _b,
    _get_exception_encoding,
    _r,
    _u,
    advance_iterator,
    str_is_unicode,
    StringIO,
    )
from testtools.content import (
    Content,
    content_from_stream,
    text_content,
    TracebackContent,
    )
from testtools.content_type import ContentType, UTF8_TEXT
from testtools.matchers import (
    AllMatch,
    Contains,
    DocTestMatches,
    Equals,
    HasLength,
    MatchesAny,
    MatchesException,
    MatchesRegex,
    Raises,
    )
from testtools.tests.helpers import (
    an_exc_info,
    FullStackRunTest,
    LoggingResult,
    run_with_stack_hidden,
    )
from testtools.testresult.doubles import (
    Python26TestResult,
    Python27TestResult,
    ExtendedTestResult,
    StreamResult as LoggingStreamResult,
    TwistedTestResult,
    )
from testtools.testresult.real import (
    _details_to_str,
    _merge_tags,
    utc,
    )


def make_erroring_test():
    class Test(TestCase):
        def error(self):
            a = 1
            1/0
    return Test("error")


def make_failing_test():
    class Test(TestCase):
        def failed(self):
            self.fail("yo!")
    return Test("failed")


def make_mismatching_test():
    class Test(TestCase):
        def mismatch(self):
            self.assertEqual(1, 2)
    return Test("mismatch")


def make_unexpectedly_successful_test():
    class Test(TestCase):
        def succeeded(self):
            self.expectFailure("yo!", lambda: None)
    return Test("succeeded")


def make_test():
    class Test(TestCase):
        def test(self):
            pass
    return Test("test")


def make_exception_info(exceptionFactory, *args, **kwargs):
    try:
        raise exceptionFactory(*args, **kwargs)
    except:
        return sys.exc_info()


class TestControlContract(object):
    """Stopping test runs."""

    def test_initially_not_shouldStop(self):
        # A result is not set to stop initially.
        result = self.makeResult()
        self.assertFalse(result.shouldStop)

    def test_stop_sets_shouldStop(self):
        # Calling 'stop()' sets 'shouldStop' to True.
        result = self.makeResult()
        result.stop()
        self.assertTrue(result.shouldStop)


class Python26Contract(TestControlContract):

    def test_fresh_result_is_successful(self):
        # A result is considered successful before any tests are run.
        result = self.makeResult()
        self.assertTrue(result.wasSuccessful())

    def test_addError_is_failure(self):
        # addError fails the test run.
        result = self.makeResult()
        result.startTest(self)
        result.addError(self, an_exc_info)
        result.stopTest(self)
        self.assertFalse(result.wasSuccessful())

    def test_addFailure_is_failure(self):
        # addFailure fails the test run.
        result = self.makeResult()
        result.startTest(self)
        result.addFailure(self, an_exc_info)
        result.stopTest(self)
        self.assertFalse(result.wasSuccessful())

    def test_addSuccess_is_success(self):
        # addSuccess does not fail the test run.
        result = self.makeResult()
        result.startTest(self)
        result.addSuccess(self)
        result.stopTest(self)
        self.assertTrue(result.wasSuccessful())


class Python27Contract(Python26Contract):

    def test_addExpectedFailure(self):
        # Calling addExpectedFailure(test, exc_info) completes ok.
        result = self.makeResult()
        result.startTest(self)
        result.addExpectedFailure(self, an_exc_info)

    def test_addExpectedFailure_is_success(self):
        # addExpectedFailure does not fail the test run.
        result = self.makeResult()
        result.startTest(self)
        result.addExpectedFailure(self, an_exc_info)
        result.stopTest(self)
        self.assertTrue(result.wasSuccessful())

    def test_addSkipped(self):
        # Calling addSkip(test, reason) completes ok.
        result = self.makeResult()
        result.startTest(self)
        result.addSkip(self, _u("Skipped for some reason"))

    def test_addSkip_is_success(self):
        # addSkip does not fail the test run.
        result = self.makeResult()
        result.startTest(self)
        result.addSkip(self, _u("Skipped for some reason"))
        result.stopTest(self)
        self.assertTrue(result.wasSuccessful())

    def test_addUnexpectedSuccess(self):
        # Calling addUnexpectedSuccess(test) completes ok.
        result = self.makeResult()
        result.startTest(self)
        result.addUnexpectedSuccess(self)

    def test_addUnexpectedSuccess_was_successful(self):
        # addUnexpectedSuccess does not fail the test run in Python 2.7.
        result = self.makeResult()
        result.startTest(self)
        result.addUnexpectedSuccess(self)
        result.stopTest(self)
        self.assertTrue(result.wasSuccessful())

    def test_startStopTestRun(self):
        # Calling startTestRun completes ok.
        result = self.makeResult()
        result.startTestRun()
        result.stopTestRun()

    def test_failfast(self):
        result = self.makeResult()
        result.failfast = True
        class Failing(TestCase):
            def test_a(self):
                self.fail('a')
            def test_b(self):
                self.fail('b')
        TestSuite([Failing('test_a'), Failing('test_b')]).run(result)
        self.assertEqual(1, result.testsRun)


class TagsContract(Python27Contract):
    """Tests to ensure correct tagging behaviour.

    See the subunit docs for guidelines on how this is supposed to work.
    """

    def test_no_tags_by_default(self):
        # Results initially have no tags.
        result = self.makeResult()
        result.startTestRun()
        self.assertEqual(frozenset(), result.current_tags)

    def test_adding_tags(self):
        # Tags are added using 'tags' and thus become visible in
        # 'current_tags'.
        result = self.makeResult()
        result.startTestRun()
        result.tags(set(['foo']), set())
        self.assertEqual(set(['foo']), result.current_tags)

    def test_removing_tags(self):
        # Tags are removed using 'tags'.
        result = self.makeResult()
        result.startTestRun()
        result.tags(set(['foo']), set())
        result.tags(set(), set(['foo']))
        self.assertEqual(set(), result.current_tags)

    def test_startTestRun_resets_tags(self):
        # startTestRun makes a new test run, and thus clears all the tags.
        result = self.makeResult()
        result.startTestRun()
        result.tags(set(['foo']), set())
        result.startTestRun()
        self.assertEqual(set(), result.current_tags)

    def test_add_tags_within_test(self):
        # Tags can be added after a test has run.
        result = self.makeResult()
        result.startTestRun()
        result.tags(set(['foo']), set())
        result.startTest(self)
        result.tags(set(['bar']), set())
        self.assertEqual(set(['foo', 'bar']), result.current_tags)

    def test_tags_added_in_test_are_reverted(self):
        # Tags added during a test run are then reverted once that test has
        # finished.
        result = self.makeResult()
        result.startTestRun()
        result.tags(set(['foo']), set())
        result.startTest(self)
        result.tags(set(['bar']), set())
        result.addSuccess(self)
        result.stopTest(self)
        self.assertEqual(set(['foo']), result.current_tags)

    def test_tags_removed_in_test(self):
        # Tags can be removed during tests.
        result = self.makeResult()
        result.startTestRun()
        result.tags(set(['foo']), set())
        result.startTest(self)
        result.tags(set(), set(['foo']))
        self.assertEqual(set(), result.current_tags)

    def test_tags_removed_in_test_are_restored(self):
        # Tags removed during tests are restored once that test has finished.
        result = self.makeResult()
        result.startTestRun()
        result.tags(set(['foo']), set())
        result.startTest(self)
        result.tags(set(), set(['foo']))
        result.addSuccess(self)
        result.stopTest(self)
        self.assertEqual(set(['foo']), result.current_tags)


class DetailsContract(TagsContract):
    """Tests for the details API of TestResults."""

    def test_addExpectedFailure_details(self):
        # Calling addExpectedFailure(test, details=xxx) completes ok.
        result = self.makeResult()
        result.startTest(self)
        result.addExpectedFailure(self, details={})

    def test_addError_details(self):
        # Calling addError(test, details=xxx) completes ok.
        result = self.makeResult()
        result.startTest(self)
        result.addError(self, details={})

    def test_addFailure_details(self):
        # Calling addFailure(test, details=xxx) completes ok.
        result = self.makeResult()
        result.startTest(self)
        result.addFailure(self, details={})

    def test_addSkipped_details(self):
        # Calling addSkip(test, reason) completes ok.
        result = self.makeResult()
        result.startTest(self)
        result.addSkip(self, details={})

    def test_addUnexpectedSuccess_details(self):
        # Calling addUnexpectedSuccess(test) completes ok.
        result = self.makeResult()
        result.startTest(self)
        result.addUnexpectedSuccess(self, details={})

    def test_addSuccess_details(self):
        # Calling addSuccess(test) completes ok.
        result = self.makeResult()
        result.startTest(self)
        result.addSuccess(self, details={})


class FallbackContract(DetailsContract):
    """When we fallback we take our policy choice to map calls.

    For instance, we map unexpectedSuccess to an error code, not to success.
    """

    def test_addUnexpectedSuccess_was_successful(self):
        # addUnexpectedSuccess fails test run in testtools.
        result = self.makeResult()
        result.startTest(self)
        result.addUnexpectedSuccess(self)
        result.stopTest(self)
        self.assertFalse(result.wasSuccessful())


class StartTestRunContract(FallbackContract):
    """Defines the contract for testtools policy choices.

    That is things which are not simply extensions to unittest but choices we
    have made differently.
    """

    def test_startTestRun_resets_unexpected_success(self):
        result = self.makeResult()
        result.startTest(self)
        result.addUnexpectedSuccess(self)
        result.stopTest(self)
        result.startTestRun()
        self.assertTrue(result.wasSuccessful())

    def test_startTestRun_resets_failure(self):
        result = self.makeResult()
        result.startTest(self)
        result.addFailure(self, an_exc_info)
        result.stopTest(self)
        result.startTestRun()
        self.assertTrue(result.wasSuccessful())

    def test_startTestRun_resets_errors(self):
        result = self.makeResult()
        result.startTest(self)
        result.addError(self, an_exc_info)
        result.stopTest(self)
        result.startTestRun()
        self.assertTrue(result.wasSuccessful())


class TestTestResultContract(TestCase, StartTestRunContract):

    run_test_with = FullStackRunTest

    def makeResult(self):
        return TestResult()


class TestMultiTestResultContract(TestCase, StartTestRunContract):

    run_test_with = FullStackRunTest

    def makeResult(self):
        return MultiTestResult(TestResult(), TestResult())


class TestTextTestResultContract(TestCase, StartTestRunContract):

    run_test_with = FullStackRunTest

    def makeResult(self):
        return TextTestResult(StringIO())


class TestThreadSafeForwardingResultContract(TestCase, StartTestRunContract):

    run_test_with = FullStackRunTest

    def makeResult(self):
        result_semaphore = threading.Semaphore(1)
        target = TestResult()
        return ThreadsafeForwardingResult(target, result_semaphore)


class TestExtendedTestResultContract(TestCase, StartTestRunContract):

    def makeResult(self):
        return ExtendedTestResult()


class TestPython26TestResultContract(TestCase, Python26Contract):

    def makeResult(self):
        return Python26TestResult()


class TestAdaptedPython26TestResultContract(TestCase, FallbackContract):

    def makeResult(self):
        return ExtendedToOriginalDecorator(Python26TestResult())


class TestPython27TestResultContract(TestCase, Python27Contract):

    def makeResult(self):
        return Python27TestResult()


class TestAdaptedPython27TestResultContract(TestCase, DetailsContract):

    def makeResult(self):
        return ExtendedToOriginalDecorator(Python27TestResult())


class TestAdaptedTwistedTestResultContract(TestCase, DetailsContract):

    def makeResult(self):
        return ExtendedToOriginalDecorator(TwistedTestResult())


class TestAdaptedStreamResult(TestCase, DetailsContract):

    def makeResult(self):
        return ExtendedToStreamDecorator(StreamResult())


class TestTestResultDecoratorContract(TestCase, StartTestRunContract):

    run_test_with = FullStackRunTest

    def makeResult(self):
        return TestResultDecorator(TestResult())


# DetailsContract because ExtendedToStreamDecorator follows Python for
# uxsuccess handling.
class TestStreamToExtendedContract(TestCase, DetailsContract):

    def makeResult(self):
        return ExtendedToStreamDecorator(
            StreamToExtendedDecorator(ExtendedTestResult()))


class TestStreamResultContract(object):

    def _make_result(self):
        raise NotImplementedError(self._make_result)

    def test_startTestRun(self):
        result = self._make_result()
        result.startTestRun()
        result.stopTestRun()

    def test_files(self):
        # Test parameter combinations when files are being emitted.
        result = self._make_result()
        result.startTestRun()
        self.addCleanup(result.stopTestRun)
        now = datetime.datetime.now(utc)
        inputs = list(dict(
            eof=True,
            mime_type="text/plain",
            route_code=_u("1234"),
            test_id=_u("foo"),
            timestamp=now,
            ).items())
        param_dicts = self._power_set(inputs)
        for kwargs in param_dicts:
            result.status(file_name=_u("foo"), file_bytes=_b(""), **kwargs)
            result.status(file_name=_u("foo"), file_bytes=_b("bar"), **kwargs)

    def test_test_status(self):
        # Tests non-file attachment parameter combinations.
        result = self._make_result()
        result.startTestRun()
        self.addCleanup(result.stopTestRun)
        now = datetime.datetime.now(utc)
        args = [[_u("foo"), s] for s in [
            'exists',
            'inprogress',
            'xfail',
            'uxsuccess',
            'success',
            'fail',
            'skip',
        ]]
        inputs = list(dict(
            runnable=False,
            test_tags=set(['quux']),
            route_code=_u("1234"),
            timestamp=now,
            ).items())
        param_dicts = self._power_set(inputs)
        for kwargs in param_dicts:
            for arg in args:
                result.status(test_id=arg[0], test_status=arg[1], **kwargs)

    def _power_set(self, iterable):
        "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
        s = list(iterable)
        param_dicts = []
        combos = (combinations(s, r) for r in range(len(s) + 1))
        for ss in chain.from_iterable(combos):
            param_dicts.append(dict(ss))
        return param_dicts


class TestBaseStreamResultContract(TestCase, TestStreamResultContract):

    def _make_result(self):
        return StreamResult()


class TestCopyStreamResultContract(TestCase, TestStreamResultContract):

    def _make_result(self):
        return CopyStreamResult([StreamResult(), StreamResult()])


class TestDoubleStreamResultContract(TestCase, TestStreamResultContract):

    def _make_result(self):
        return LoggingStreamResult()


class TestExtendedToStreamDecoratorContract(TestCase, TestStreamResultContract):

    def _make_result(self):
        return ExtendedToStreamDecorator(StreamResult())


class TestResourcedToStreamDecoratorContract(TestCase, TestStreamResultContract):

    def _make_result(self):
        return ResourcedToStreamDecorator(StreamResult())


class TestStreamSummaryResultContract(TestCase, TestStreamResultContract):

    def _make_result(self):
        return StreamSummary()


class TestStreamTaggerContract(TestCase, TestStreamResultContract):

    def _make_result(self):
        return StreamTagger([StreamResult()], add=set(), discard=set())


class TestStreamToDictContract(TestCase, TestStreamResultContract):

    def _make_result(self):
        return StreamToDict(lambda x:None)


class TestStreamToExtendedDecoratorContract(TestCase, TestStreamResultContract):

    def _make_result(self):
        return StreamToExtendedDecorator(ExtendedTestResult())


class TestStreamToQueueContract(TestCase, TestStreamResultContract):

    def _make_result(self):
        queue = Queue()
        return StreamToQueue(queue, "foo")


class TestStreamFailFastContract(TestCase, TestStreamResultContract):

    def _make_result(self):
        return StreamFailFast(lambda:None)


class TestStreamResultRouterContract(TestCase, TestStreamResultContract):

    def _make_result(self):
        return StreamResultRouter(StreamResult())


class TestDoubleStreamResultEvents(TestCase):

    def test_startTestRun(self):
        result = LoggingStreamResult()
        result.startTestRun()
        self.assertEqual([('startTestRun',)], result._events)

    def test_stopTestRun(self):
        result = LoggingStreamResult()
        result.startTestRun()
        result.stopTestRun()
        self.assertEqual([('startTestRun',), ('stopTestRun',)], result._events)

    def test_file(self):
        result = LoggingStreamResult()
        result.startTestRun()
        now = datetime.datetime.now(utc)
        result.status(file_name="foo", file_bytes="bar", eof=True, mime_type="text/json",
            test_id="id", route_code='abc', timestamp=now)
        self.assertEqual(
            [('startTestRun',),
             ('status', 'id', None, None, True, 'foo', 'bar', True, 'text/json', 'abc', now)],
            result._events)

    def test_status(self):
        result = LoggingStreamResult()
        result.startTestRun()
        now = datetime.datetime.now(utc)
        result.status("foo", "success", test_tags=set(['tag']),
            runnable=False, route_code='abc', timestamp=now)
        self.assertEqual(
            [('startTestRun',),
             ('status', 'foo', 'success', set(['tag']), False, None, None, False, None, 'abc', now)],
            result._events)


class TestCopyStreamResultCopies(TestCase):

    def setUp(self):
        super(TestCopyStreamResultCopies, self).setUp()
        self.target1 = LoggingStreamResult()
        self.target2 = LoggingStreamResult()
        self.targets = [self.target1._events, self.target2._events]
        self.result = CopyStreamResult([self.target1, self.target2])

    def test_startTestRun(self):
        self.result.startTestRun()
        self.assertThat(self.targets, AllMatch(Equals([('startTestRun',)])))

    def test_stopTestRun(self):
        self.result.startTestRun()
        self.result.stopTestRun()
        self.assertThat(self.targets,
            AllMatch(Equals([('startTestRun',), ('stopTestRun',)])))

    def test_status(self):
        self.result.startTestRun()
        now = datetime.datetime.now(utc)
        self.result.status("foo", "success", test_tags=set(['tag']),
            runnable=False, file_name="foo", file_bytes=b'bar', eof=True,
            mime_type="text/json", route_code='abc', timestamp=now)
        self.assertThat(self.targets,
            AllMatch(Equals([('startTestRun',),
                ('status', 'foo', 'success', set(['tag']), False, "foo",
                 b'bar', True, "text/json", 'abc', now)
                ])))


class TestStreamTagger(TestCase):

    def test_adding(self):
        log = LoggingStreamResult()
        result = StreamTagger([log], add=['foo'])
        result.startTestRun()
        result.status()
        result.status(test_tags=set(['bar']))
        result.status(test_tags=None)
        result.stopTestRun()
        self.assertEqual([
            ('startTestRun',),
            ('status', None, None, set(['foo']), True, None, None, False, None, None, None),
            ('status', None, None, set(['foo', 'bar']), True, None, None, False, None, None, None),
            ('status', None, None, set(['foo']), True, None, None, False, None, None, None),
            ('stopTestRun',),
            ], log._events)

    def test_discarding(self):
        log = LoggingStreamResult()
        result = StreamTagger([log], discard=['foo'])
        result.startTestRun()
        result.status()
        result.status(test_tags=None)
        result.status(test_tags=set(['foo']))
        result.status(test_tags=set(['bar']))
        result.status(test_tags=set(['foo', 'bar']))
        result.stopTestRun()
        self.assertEqual([
            ('startTestRun',),
            ('status', None, None, None, True, None, None, False, None, None, None),
            ('status', None, None, None, True, None, None, False, None, None, None),
            ('status', None, None, None, True, None, None, False, None, None, None),
            ('status', None, None, set(['bar']), True, None, None, False, None, None, None),
            ('status', None, None, set(['bar']), True, None, None, False, None, None, None),
            ('stopTestRun',),
            ], log._events)


class TestStreamToDict(TestCase):

    def test_hung_test(self):
        tests = []
        result = StreamToDict(tests.append)
        result.startTestRun()
        result.status('foo', 'inprogress')
        self.assertEqual([], tests)
        result.stopTestRun()
        self.assertEqual([
            {'id': 'foo', 'tags': set(), 'details': {}, 'status': 'inprogress',
             'timestamps': [None, None]}
            ], tests)

    def test_all_terminal_states_reported(self):
        tests = []
        result = StreamToDict(tests.append)
        result.startTestRun()
        result.status('success', 'success')
        result.status('skip', 'skip')
        result.status('exists', 'exists')
        result.status('fail', 'fail')
        result.status('xfail', 'xfail')
        result.status('uxsuccess', 'uxsuccess')
        self.assertThat(tests, HasLength(6))
        self.assertEqual(
            ['success', 'skip', 'exists', 'fail', 'xfail', 'uxsuccess'],
            [test['id'] for test in tests])
        result.stopTestRun()
        self.assertThat(tests, HasLength(6))

    def test_files_reported(self):
        tests = []
        result = StreamToDict(tests.append)
        result.startTestRun()
        result.status(file_name="some log.txt",
            file_bytes=_b("1234 log message"), eof=True,
            mime_type="text/plain; charset=utf8", test_id="foo.bar")
        result.status(file_name="another file",
            file_bytes=_b("""Traceback..."""), test_id="foo.bar")
        result.stopTestRun()
        self.assertThat(tests, HasLength(1))
        test = tests[0]
        self.assertEqual("foo.bar", test['id'])
        self.assertEqual("unknown", test['status'])
        details = test['details']
        self.assertEqual(
            _u("1234 log message"), details['some log.txt'].as_text())
        self.assertEqual(
            _b("Traceback..."),
            _b('').join(details['another file'].iter_bytes()))
        self.assertEqual(
            "application/octet-stream", repr(details['another file'].content_type))

    def test_bad_mime(self):
        # Testtools was making bad mime types, this tests that the specific
        # corruption is catered for.
        return
        tests = []
        result = StreamToDict(tests.append)
        result.startTestRun()
        result.status(file_name="file", file_bytes=b'a',
            mime_type='text/plain; charset=utf8, language=python',
            test_id='id')
        result.stopTestRun()
        self.assertThat(tests, HasLength(1))
        test = tests[0]
        self.assertEqual("id", test['id'])
        details = test['details']
        self.assertEqual(_u("a"), details['file'].as_text())
        self.assertEqual(
            "text/plain; charset=\"utf8\"",
            repr(details['file'].content_type))

    def test_timestamps(self):
        tests = []
        result = StreamToDict(tests.append)
        result.startTestRun()
        result.status(test_id='foo', test_status='inprogress', timestamp="A")
        result.status(test_id='foo', test_status='success', timestamp="B")
        result.status(test_id='bar', test_status='inprogress', timestamp="C")
        result.stopTestRun()
        self.assertThat(tests, HasLength(2))
        self.assertEqual(["A", "B"], tests[0]['timestamps'])
        self.assertEqual(["C", None], tests[1]['timestamps'])

    def test_files_skipped(self):
        tests = []
        result = StreamToDict(tests.append)
        result.startTestRun()
        result.status(file_name="some log.txt",
            file_bytes="", eof=True,
            mime_type="text/plain; charset=utf8", test_id="foo.bar")
        result.stopTestRun()
        self.assertThat(tests, HasLength(1))
        details = tests[0]['details']
        self.assertNotIn("some log.txt", details)


class TestExtendedToStreamDecorator(TestCase):

    def test_explicit_time(self):
        log = LoggingStreamResult()
        result = ExtendedToStreamDecorator(log)
        result.startTestRun()
        now = datetime.datetime.now(utc)
        result.time(now)
        result.startTest(self)
        result.addSuccess(self)
        result.stopTest(self)
        result.stopTestRun()
        self.assertEqual([
            ('startTestRun',),
            ('status',
             'testtools.tests.test_testresult.TestExtendedToStreamDecorator.test_explicit_time',
             'inprogress',
             None,
             True,
             None,
             None,
             False,
             None,
             None,
             now),
            ('status',
             'testtools.tests.test_testresult.TestExtendedToStreamDecorator.test_explicit_time',
             'success',
              set(),
              True,
              None,
              None,
              False,
              None,
              None,
              now),
             ('stopTestRun',)], log._events)

    def test_wasSuccessful_after_stopTestRun(self):
        log = LoggingStreamResult()
        result = ExtendedToStreamDecorator(log)
        result.startTestRun()
        result.status(test_id='foo', test_status='fail')
        result.stopTestRun()
        self.assertEqual(False, result.wasSuccessful())

    def test_empty_detail_status_correct(self):
        log = LoggingStreamResult()
        result = ExtendedToStreamDecorator(log)
        result.startTestRun()
        now = datetime.datetime.now(utc)
        result.time(now)
        result.startTest(self)
        result.addError(self, details={'foo': text_content(_u(""))})
        result.stopTest(self)
        result.stopTestRun()
        self.assertEqual([
            ('startTestRun',),
            ('status',
             'testtools.tests.test_testresult.TestExtendedToStreamDecorator.test_empty_detail_status_correct',
             'inprogress',
             None,
             True,
             None,
             None,
             False,
             None,
             None,
             now),
            ('status',
             'testtools.tests.test_testresult.TestExtendedToStreamDecorator.test_empty_detail_status_correct',
              None,
              None,
              True,
              'foo',
              _b(''),
              True,
              'text/plain; charset="utf8"',
              None,
              now),
            ('status',
             'testtools.tests.test_testresult.TestExtendedToStreamDecorator.test_empty_detail_status_correct',
             'fail',
              set(),
              True,
              None,
              None,
              False,
              None,
              None,
              now),
             ('stopTestRun',)], log._events)


class TestResourcedToStreamDecorator(TestCase):

    def setUp(self):
        super(TestResourcedToStreamDecorator, self).setUp()
        if testresources is None:
            self.skipTest('Need testresources')

    def test_startMakeResource(self):
        log = LoggingStreamResult()
        result = ResourcedToStreamDecorator(log)
        timestamp = datetime.datetime.utcfromtimestamp(3.476)
        result.startTestRun()
        result.time(timestamp)
        resource = testresources.TestResourceManager()
        result.startMakeResource(resource)
        [_, event] = log._events
        self.assertEqual(
            'testresources.TestResourceManager.make', event.test_id)
        self.assertEqual('inprogress', event.test_status)
        self.assertFalse(event.runnable)
        self.assertEqual(timestamp, event.timestamp)

    def test_startMakeResource_with_custom_id_method(self):
        log = LoggingStreamResult()
        result = ResourcedToStreamDecorator(log)
        resource = testresources.TestResourceManager()
        resource.id = lambda: 'nice.resource'
        result.startTestRun()
        result.startMakeResource(resource)
        self.assertEqual('nice.resource.make', log._events[1].test_id)

    def test_stopMakeResource(self):
        log = LoggingStreamResult()
        result = ResourcedToStreamDecorator(log)
        resource = testresources.TestResourceManager()
        result.startTestRun()
        result.stopMakeResource(resource)
        [_, event] = log._events
        self.assertEqual(
            'testresources.TestResourceManager.make', event.test_id)
        self.assertEqual('success', event.test_status)

    def test_startCleanResource(self):
        log = LoggingStreamResult()
        result = ResourcedToStreamDecorator(log)
        resource = testresources.TestResourceManager()
        result.startTestRun()
        result.startCleanResource(resource)
        [_, event] = log._events
        self.assertEqual(
            'testresources.TestResourceManager.clean', event.test_id)
        self.assertEqual('inprogress', event.test_status)

    def test_stopCleanResource(self):
        log = LoggingStreamResult()
        result = ResourcedToStreamDecorator(log)
        resource = testresources.TestResourceManager()
        result.startTestRun()
        result.stopCleanResource(resource)
        [_, event] = log._events
        self.assertEqual(
            'testresources.TestResourceManager.clean', event.test_id)
        self.assertEqual('success', event.test_status)


class TestStreamFailFast(TestCase):

    def test_inprogress(self):
        result = StreamFailFast(self.fail)
        result.status('foo', 'inprogress')

    def test_exists(self):
        result = StreamFailFast(self.fail)
        result.status('foo', 'exists')

    def test_xfail(self):
        result = StreamFailFast(self.fail)
        result.status('foo', 'xfail')

    def test_uxsuccess(self):
        calls = []
        def hook():
            calls.append("called")
        result = StreamFailFast(hook)
        result.status('foo', 'uxsuccess')
        result.status('foo', 'uxsuccess')
        self.assertEqual(['called', 'called'], calls)

    def test_success(self):
        result = StreamFailFast(self.fail)
        result.status('foo', 'success')

    def test_fail(self):
        calls = []
        def hook():
            calls.append("called")
        result = StreamFailFast(hook)
        result.status('foo', 'fail')
        result.status('foo', 'fail')
        self.assertEqual(['called', 'called'], calls)

    def test_skip(self):
        result = StreamFailFast(self.fail)
        result.status('foo', 'skip')


class TestStreamSummary(TestCase):

    def test_attributes(self):
        result = StreamSummary()
        result.startTestRun()
        self.assertEqual([], result.failures)
        self.assertEqual([], result.errors)
        self.assertEqual([], result.skipped)
        self.assertEqual([], result.expectedFailures)
        self.assertEqual([], result.unexpectedSuccesses)
        self.assertEqual(0, result.testsRun)

    def test_startTestRun(self):
        result = StreamSummary()
        result.startTestRun()
        result.failures.append('x')
        result.errors.append('x')
        result.skipped.append('x')
        result.expectedFailures.append('x')
        result.unexpectedSuccesses.append('x')
        result.testsRun = 1
        result.startTestRun()
        self.assertEqual([], result.failures)
        self.assertEqual([], result.errors)
        self.assertEqual([], result.skipped)
        self.assertEqual([], result.expectedFailures)
        self.assertEqual([], result.unexpectedSuccesses)
        self.assertEqual(0, result.testsRun)

    def test_wasSuccessful(self):
        # wasSuccessful returns False if any of
        # failures/errors is non-empty.
        result = StreamSummary()
        result.startTestRun()
        self.assertEqual(True, result.wasSuccessful())
        result.failures.append('x')
        self.assertEqual(False, result.wasSuccessful())
        result.startTestRun()
        result.errors.append('x')
        self.assertEqual(False, result.wasSuccessful())
        result.startTestRun()
        result.skipped.append('x')
        self.assertEqual(True, result.wasSuccessful())
        result.startTestRun()
        result.expectedFailures.append('x')
        self.assertEqual(True, result.wasSuccessful())
        result.startTestRun()
        result.unexpectedSuccesses.append('x')
        self.assertEqual(True, result.wasSuccessful())

    def test_stopTestRun(self):
        result = StreamSummary()
        # terminal successful codes.
        result.startTestRun()
        result.status("foo", "inprogress")
        result.status("foo", "success")
        result.status("bar", "skip")
        result.status("baz", "exists")
        result.stopTestRun()
        self.assertEqual(True, result.wasSuccessful())
        # Existence is terminal but doesn't count as 'running' a test.
        self.assertEqual(2, result.testsRun)

    def test_stopTestRun_inprogress_test_fails(self):
        # Tests inprogress at stopTestRun trigger a failure.
        result = StreamSummary()
        result.startTestRun()
        result.status("foo", "inprogress")
        result.stopTestRun()
        self.assertEqual(False, result.wasSuccessful())
        self.assertThat(result.errors, HasLength(1))
        self.assertEqual("foo", result.errors[0][0].id())
        self.assertEqual("Test did not complete", result.errors[0][1])
        # interim state detection handles route codes - while duplicate ids in
        # one run is undesirable, it may happen (e.g. with repeated tests).
        result.startTestRun()
        result.status("foo", "inprogress")
        result.status("foo", "inprogress", route_code="A")
        result.status("foo", "success", route_code="A")
        result.stopTestRun()
        self.assertEqual(False, result.wasSuccessful())

    def test_status_skip(self):
        # when skip is seen, a synthetic test is reported with reason captured
        # from the 'reason' file attachment if any.
        result = StreamSummary()
        result.startTestRun()
        result.status(file_name="reason",
            file_bytes=_b("Missing dependency"), eof=True,
            mime_type="text/plain; charset=utf8", test_id="foo.bar")
        result.status("foo.bar", "skip")
        self.assertThat(result.skipped, HasLength(1))
        self.assertEqual("foo.bar", result.skipped[0][0].id())
        self.assertEqual(_u("Missing dependency"), result.skipped[0][1])

    def _report_files(self, result):
        result.status(file_name="some log.txt",
            file_bytes=_b("1234 log message"), eof=True,
            mime_type="text/plain; charset=utf8", test_id="foo.bar")
        result.status(file_name="traceback",
            file_bytes=_b("""Traceback (most recent call last):
  File "testtools/tests/test_testresult.py", line 607, in test_stopTestRun
      AllMatch(Equals([('startTestRun',), ('stopTestRun',)])))
testtools.matchers._impl.MismatchError: Differences: [
[('startTestRun',), ('stopTestRun',)] != []
[('startTestRun',), ('stopTestRun',)] != []
]
"""), eof=True, mime_type="text/plain; charset=utf8", test_id="foo.bar")

    files_message = Equals(_u("""some log.txt: {{{1234 log message}}}

Traceback (most recent call last):
  File "testtools/tests/test_testresult.py", line 607, in test_stopTestRun
      AllMatch(Equals([('startTestRun',), ('stopTestRun',)])))
testtools.matchers._impl.MismatchError: Differences: [
[('startTestRun',), ('stopTestRun',)] != []
[('startTestRun',), ('stopTestRun',)] != []
]
"""))

    def test_status_fail(self):
        # when fail is seen, a synthetic test is reported with all files
        # attached shown as the message.
        result = StreamSummary()
        result.startTestRun()
        self._report_files(result)
        result.status("foo.bar", "fail")
        self.assertThat(result.errors, HasLength(1))
        self.assertEqual("foo.bar", result.errors[0][0].id())
        self.assertThat(result.errors[0][1], self.files_message)

    def test_status_xfail(self):
        # when xfail is seen, a synthetic test is reported with all files
        # attached shown as the message.
        result = StreamSummary()
        result.startTestRun()
        self._report_files(result)
        result.status("foo.bar", "xfail")
        self.assertThat(result.expectedFailures, HasLength(1))
        self.assertEqual("foo.bar", result.expectedFailures[0][0].id())
        self.assertThat(result.expectedFailures[0][1], self.files_message)

    def test_status_uxsuccess(self):
        # when uxsuccess is seen, a synthetic test is reported.
        result = StreamSummary()
        result.startTestRun()
        result.status("foo.bar", "uxsuccess")
        self.assertThat(result.unexpectedSuccesses, HasLength(1))
        self.assertEqual("foo.bar", result.unexpectedSuccesses[0].id())


class TestTestControl(TestCase, TestControlContract):

    def makeResult(self):
        return TestControl()


class TestTestResult(TestCase):
    """Tests for 'TestResult'."""

    run_tests_with = FullStackRunTest

    def makeResult(self):
        """Make an arbitrary result for testing."""
        return TestResult()

    def test_addSkipped(self):
        # Calling addSkip on a TestResult records the test that was skipped in
        # its skip_reasons dict.
        result = self.makeResult()
        result.addSkip(self, _u("Skipped for some reason"))
        self.assertEqual({_u("Skipped for some reason"):[self]},
            result.skip_reasons)
        result.addSkip(self, _u("Skipped for some reason"))
        self.assertEqual({_u("Skipped for some reason"):[self, self]},
            result.skip_reasons)
        result.addSkip(self, _u("Skipped for another reason"))
        self.assertEqual({_u("Skipped for some reason"):[self, self],
            _u("Skipped for another reason"):[self]},
            result.skip_reasons)

    def test_now_datetime_now(self):
        result = self.makeResult()
        olddatetime = testresult.real.datetime
        def restore():
            testresult.real.datetime = olddatetime
        self.addCleanup(restore)
        class Module:
            pass
        now = datetime.datetime.now(utc)
        stubdatetime = Module()
        stubdatetime.datetime = Module()
        stubdatetime.datetime.now = lambda tz: now
        testresult.real.datetime = stubdatetime
        # Calling _now() looks up the time.
        self.assertEqual(now, result._now())
        then = now + datetime.timedelta(0, 1)
        # Set an explicit datetime, which gets returned from then on.
        result.time(then)
        self.assertNotEqual(now, result._now())
        self.assertEqual(then, result._now())
        # go back to looking it up.
        result.time(None)
        self.assertEqual(now, result._now())

    def test_now_datetime_time(self):
        result = self.makeResult()
        now = datetime.datetime.now(utc)
        result.time(now)
        self.assertEqual(now, result._now())

    def test_traceback_formatting_without_stack_hidden(self):
        # During the testtools test run, we show our levels of the stack,
        # because we want to be able to use our test suite to debug our own
        # code.
        result = self.makeResult()
        test = make_erroring_test()
        test.run(result)
        self.assertThat(
            result.errors[0][1],
            DocTestMatches(
                'Traceback (most recent call last):\n'
                '  File "...testtools...runtest.py", line ..., in _run_user\n'
                '    return fn(*args, **kwargs)\n'
                '  File "...testtools...testcase.py", line ..., in _run_test_method\n'
                '    return self._get_test_method()()\n'
                '  File "...testtools...tests...test_testresult.py", line ..., in error\n'
                '    1/0\n'
                'ZeroDivisionError: ...\n',
                doctest.ELLIPSIS | doctest.REPORT_UDIFF))

    def test_traceback_formatting_with_stack_hidden(self):
        result = self.makeResult()
        test = make_erroring_test()
        run_with_stack_hidden(True, test.run, result)
        self.assertThat(
            result.errors[0][1],
            DocTestMatches(
                'Traceback (most recent call last):\n'
                '  File "...testtools...tests...test_testresult.py", line ..., in error\n'
                '    1/0\n'
                'ZeroDivisionError: ...\n',
                doctest.ELLIPSIS))

    def test_traceback_formatting_with_stack_hidden_mismatch(self):
        result = self.makeResult()
        test = make_mismatching_test()
        run_with_stack_hidden(True, test.run, result)
        self.assertThat(
            result.failures[0][1],
            DocTestMatches(
                'Traceback (most recent call last):\n'
                '  File "...testtools...tests...test_testresult.py", line ..., in mismatch\n'
                '    self.assertEqual(1, 2)\n'
                '...MismatchError: 1 != 2\n',
                doctest.ELLIPSIS))

    def test_exc_info_to_unicode(self):
        # subunit upcalls to TestResult._exc_info_to_unicode, so we need to
        # make sure that it's there.
        #
        # See <https://bugs.launchpad.net/testtools/+bug/929063>.
        test = make_erroring_test()
        exc_info = make_exception_info(RuntimeError, "foo")
        result = self.makeResult()
        text_traceback = result._exc_info_to_unicode(exc_info, test)
        self.assertEqual(
            TracebackContent(exc_info, test).as_text(), text_traceback)

    def test_traceback_with_locals(self):
        result = self.makeResult()
        result.tb_locals = True
        test = make_erroring_test()
        test.run(result)
        self.assertThat(
            result.errors[0][1],
            DocTestMatches(
                'Traceback (most recent call last):\n'
                '  File "...testtools...runtest.py", line ..., in _run_user\n'
                '    return fn(*args, **kwargs)\n'
                '    args = ...\n'
                '    fn = ...\n'
                '    kwargs = ...\n'
                '    self = ...\n'
                '  File "...testtools...testcase.py", line ..., in _run_test_method\n'
                '    return self._get_test_method()()\n'
                '    result = ...\n'
                '    self = ...\n'
                '  File "...testtools...tests...test_testresult.py", line ..., in error\n'
                '    1/0\n'
                '    a = 1\n'
                '    self = ...\n'
                'ZeroDivisionError: ...\n',
                doctest.ELLIPSIS | doctest.REPORT_UDIFF))


class TestMultiTestResult(TestCase):
    """Tests for 'MultiTestResult'."""

    def setUp(self):
        super(TestMultiTestResult, self).setUp()
        self.result1 = LoggingResult([])
        self.result2 = LoggingResult([])
        self.multiResult = MultiTestResult(self.result1, self.result2)

    def assertResultLogsEqual(self, expectedEvents):
        """Assert that our test results have received the expected events."""
        self.assertEqual(expectedEvents, self.result1._events)
        self.assertEqual(expectedEvents, self.result2._events)

    def test_repr(self):
        self.assertEqual(
            '<MultiTestResult (%r, %r)>' % (
                ExtendedToOriginalDecorator(self.result1),
                ExtendedToOriginalDecorator(self.result2)),
            repr(self.multiResult))

    def test_empty(self):
        # Initializing a `MultiTestResult` doesn't do anything to its
        # `TestResult`s.
        self.assertResultLogsEqual([])

    def test_failfast_get(self):
        # Reading reads from the first one - arbitrary choice.
        self.assertEqual(False, self.multiResult.failfast)
        self.result1.failfast = True
        self.assertEqual(True, self.multiResult.failfast)

    def test_failfast_set(self):
        # Writing writes to all.
        self.multiResult.failfast = True
        self.assertEqual(True, self.result1.failfast)
        self.assertEqual(True, self.result2.failfast)

    def test_shouldStop(self):
        self.assertFalse(self.multiResult.shouldStop)
        self.result2.stop()
        # NB: result1 is not stopped: MultiTestResult has to combine the
        # values.
        self.assertTrue(self.multiResult.shouldStop)

    def test_startTest(self):
        # Calling `startTest` on a `MultiTestResult` calls `startTest` on all
        # its `TestResult`s.
        self.multiResult.startTest(self)
        self.assertResultLogsEqual([('startTest', self)])

    def test_stop(self):
        self.assertFalse(self.multiResult.shouldStop)
        self.multiResult.stop()
        self.assertResultLogsEqual(['stop'])

    def test_stopTest(self):
        # Calling `stopTest` on a `MultiTestResult` calls `stopTest` on all
        # its `TestResult`s.
        self.multiResult.stopTest(self)
        self.assertResultLogsEqual([('stopTest', self)])

    def test_addSkipped(self):
        # Calling `addSkip` on a `MultiTestResult` calls addSkip on its
        # results.
        reason = _u("Skipped for some reason")
        self.multiResult.addSkip(self, reason)
        self.assertResultLogsEqual([('addSkip', self, reason)])

    def test_addSuccess(self):
        # Calling `addSuccess` on a `MultiTestResult` calls `addSuccess` on
        # all its `TestResult`s.
        self.multiResult.addSuccess(self)
        self.assertResultLogsEqual([('addSuccess', self)])

    def test_done(self):
        # Calling `done` on a `MultiTestResult` calls `done` on all its
        # `TestResult`s.
        self.multiResult.done()
        self.assertResultLogsEqual([('done')])

    def test_addFailure(self):
        # Calling `addFailure` on a `MultiTestResult` calls `addFailure` on
        # all its `TestResult`s.
        exc_info = make_exception_info(AssertionError, 'failure')
        self.multiResult.addFailure(self, exc_info)
        self.assertResultLogsEqual([('addFailure', self, exc_info)])

    def test_addError(self):
        # Calling `addError` on a `MultiTestResult` calls `addError` on all
        # its `TestResult`s.
        exc_info = make_exception_info(RuntimeError, 'error')
        self.multiResult.addError(self, exc_info)
        self.assertResultLogsEqual([('addError', self, exc_info)])

    def test_startTestRun(self):
        # Calling `startTestRun` on a `MultiTestResult` forwards to all its
        # `TestResult`s.
        self.multiResult.startTestRun()
        self.assertResultLogsEqual([('startTestRun')])

    def test_stopTestRun(self):
        # Calling `stopTestRun` on a `MultiTestResult` forwards to all its
        # `TestResult`s.
        self.multiResult.stopTestRun()
        self.assertResultLogsEqual([('stopTestRun')])

    def test_stopTestRun_returns_results(self):
        # `MultiTestResult.stopTestRun` returns a tuple of all of the return
        # values the `stopTestRun`s that it forwards to.
        class Result(LoggingResult):
            def stopTestRun(self):
                super(Result, self).stopTestRun()
                return 'foo'
        multi_result = MultiTestResult(Result([]), Result([]))
        result = multi_result.stopTestRun()
        self.assertEqual(('foo', 'foo'), result)

    def test_tags(self):
        # Calling `tags` on a `MultiTestResult` calls `tags` on all its
        # `TestResult`s.
        added_tags = set(['foo', 'bar'])
        removed_tags = set(['eggs'])
        self.multiResult.tags(added_tags, removed_tags)
        self.assertResultLogsEqual([('tags', added_tags, removed_tags)])

    def test_time(self):
        # the time call is dispatched, not eaten by the base class
        self.multiResult.time('foo')
        self.assertResultLogsEqual([('time', 'foo')])


class TestTextTestResult(TestCase):
    """Tests for 'TextTestResult'."""

    def setUp(self):
        super(TestTextTestResult, self).setUp()
        self.result = TextTestResult(StringIO())

    def getvalue(self):
        return self.result.stream.getvalue()

    def test__init_sets_stream(self):
        result = TextTestResult("fp")
        self.assertEqual("fp", result.stream)

    def reset_output(self):
        self.result.stream = StringIO()

    def test_startTestRun(self):
        self.result.startTestRun()
        self.assertEqual("Tests running...\n", self.getvalue())

    def test_stopTestRun_count_many(self):
        test = make_test()
        self.result.startTestRun()
        self.result.startTest(test)
        self.result.stopTest(test)
        self.result.startTest(test)
        self.result.stopTest(test)
        self.result.stream = StringIO()
        self.result.stopTestRun()
        self.assertThat(self.getvalue(),
            DocTestMatches("\nRan 2 tests in ...s\n...", doctest.ELLIPSIS))

    def test_stopTestRun_count_single(self):
        test = make_test()
        self.result.startTestRun()
        self.result.startTest(test)
        self.result.stopTest(test)
        self.reset_output()
        self.result.stopTestRun()
        self.assertThat(self.getvalue(),
            DocTestMatches("\nRan 1 test in ...s\nOK\n", doctest.ELLIPSIS))

    def test_stopTestRun_count_zero(self):
        self.result.startTestRun()
        self.reset_output()
        self.result.stopTestRun()
        self.assertThat(self.getvalue(),
            DocTestMatches("\nRan 0 tests in ...s\nOK\n", doctest.ELLIPSIS))

    def test_stopTestRun_current_time(self):
        test = make_test()
        now = datetime.datetime.now(utc)
        self.result.time(now)
        self.result.startTestRun()
        self.result.startTest(test)
        now = now + datetime.timedelta(0, 0, 0, 1)
        self.result.time(now)
        self.result.stopTest(test)
        self.reset_output()
        self.result.stopTestRun()
        self.assertThat(self.getvalue(),
            DocTestMatches("... in 0.001s\n...", doctest.ELLIPSIS))

    def test_stopTestRun_successful(self):
        self.result.startTestRun()
        self.result.stopTestRun()
        self.assertThat(self.getvalue(),
            DocTestMatches("...\nOK\n", doctest.ELLIPSIS))

    def test_stopTestRun_not_successful_failure(self):
        test = make_failing_test()
        self.result.startTestRun()
        test.run(self.result)
        self.result.stopTestRun()
        self.assertThat(self.getvalue(),
            DocTestMatches("...\nFAILED (failures=1)\n", doctest.ELLIPSIS))

    def test_stopTestRun_not_successful_error(self):
        test = make_erroring_test()
        self.result.startTestRun()
        test.run(self.result)
        self.result.stopTestRun()
        self.assertThat(self.getvalue(),
            DocTestMatches("...\nFAILED (failures=1)\n", doctest.ELLIPSIS))

    def test_stopTestRun_not_successful_unexpected_success(self):
        test = make_unexpectedly_successful_test()
        self.result.startTestRun()
        test.run(self.result)
        self.result.stopTestRun()
        self.assertThat(self.getvalue(),
            DocTestMatches("...\nFAILED (failures=1)\n", doctest.ELLIPSIS))

    def test_stopTestRun_shows_details(self):
        self.skip("Disabled per bug 1188420")
        def run_tests():
            self.result.startTestRun()
            make_erroring_test().run(self.result)
            make_unexpectedly_successful_test().run(self.result)
            make_failing_test().run(self.result)
            self.reset_output()
            self.result.stopTestRun()
        run_with_stack_hidden(True, run_tests)
        self.assertThat(self.getvalue(),
            DocTestMatches("""...======================================================================
ERROR: testtools.tests.test_testresult.Test.error
----------------------------------------------------------------------
Traceback (most recent call last):
  File "...testtools...tests...test_testresult.py", line ..., in error
    1/0
ZeroDivisionError:... divi... by zero...
======================================================================
FAIL: testtools.tests.test_testresult.Test.failed
----------------------------------------------------------------------
Traceback (most recent call last):
  File "...testtools...tests...test_testresult.py", line ..., in failed
    self.fail("yo!")
AssertionError: yo!
======================================================================
UNEXPECTED SUCCESS: testtools.tests.test_testresult.Test.succeeded
----------------------------------------------------------------------
...""", doctest.ELLIPSIS | doctest.REPORT_NDIFF))


class TestThreadSafeForwardingResult(TestCase):
    """Tests for `TestThreadSafeForwardingResult`."""

    def make_results(self, n):
        events = []
        target = LoggingResult(events)
        semaphore = threading.Semaphore(1)
        return [
            ThreadsafeForwardingResult(target, semaphore)
            for i in range(n)], events

    def test_nonforwarding_methods(self):
        # startTest and stopTest are not forwarded because they need to be
        # batched.
        [result], events = self.make_results(1)
        result.startTest(self)
        result.stopTest(self)
        self.assertEqual([], events)

    def test_tags_not_forwarded(self):
        # Tags need to be batched for each test, so they aren't forwarded
        # until a test runs.
        [result], events = self.make_results(1)
        result.tags(set(['foo']), set(['bar']))
        self.assertEqual([], events)

    def test_global_tags_simple(self):
        # Tags specified outside of a test result are global. When a test's
        # results are finally forwarded, we send through these global tags
        # *as* test specific tags, because as a multiplexer there should be no
        # way for a global tag on an input stream to affect tests from other
        # streams - we can just always issue test local tags.
        [result], events = self.make_results(1)
        result.tags(set(['foo']), set())
        result.time(1)
        result.startTest(self)
        result.time(2)
        result.addSuccess(self)
        self.assertEqual(
            [('time', 1),
             ('startTest', self),
             ('time', 2),
             ('tags', set(['foo']), set()),
             ('addSuccess', self),
             ('stopTest', self),
             ], events)

    def test_global_tags_complex(self):
        # Multiple calls to tags() in a global context are buffered until the
        # next test completes and are issued as part of of the test context,
        # because they cannot be issued until the output result is locked.
        # The sample data shows them being merged together, this is, strictly
        # speaking incidental - they could be issued separately (in-order) and
        # still be legitimate.
        [result], events = self.make_results(1)
        result.tags(set(['foo', 'bar']), set(['baz', 'qux']))
        result.tags(set(['cat', 'qux']), set(['bar', 'dog']))
        result.time(1)
        result.startTest(self)
        result.time(2)
        result.addSuccess(self)
        self.assertEqual(
            [('time', 1),
             ('startTest', self),
             ('time', 2),
             ('tags', set(['cat', 'foo', 'qux']), set(['dog', 'bar', 'baz'])),
             ('addSuccess', self),
             ('stopTest', self),
             ], events)

    def test_local_tags(self):
        # Any tags set within a test context are forwarded in that test
        # context when the result is finally forwarded.  This means that the
        # tags for the test are part of the atomic message communicating
        # everything about that test.
        [result], events = self.make_results(1)
        result.time(1)
        result.startTest(self)
        result.tags(set(['foo']), set([]))
        result.tags(set(), set(['bar']))
        result.time(2)
        result.addSuccess(self)
        self.assertEqual(
            [('time', 1),
             ('startTest', self),
             ('time', 2),
             ('tags', set(['foo']), set(['bar'])),
             ('addSuccess', self),
             ('stopTest', self),
             ], events)

    def test_local_tags_dont_leak(self):
        # A tag set during a test is local to that test and is not set during
        # the tests that follow.
        [result], events = self.make_results(1)
        a, b = PlaceHolder('a'), PlaceHolder('b')
        result.time(1)
        result.startTest(a)
        result.tags(set(['foo']), set([]))
        result.time(2)
        result.addSuccess(a)
        result.stopTest(a)
        result.time(3)
        result.startTest(b)
        result.time(4)
        result.addSuccess(b)
        result.stopTest(b)
        self.assertEqual(
            [('time', 1),
             ('startTest', a),
             ('time', 2),
             ('tags', set(['foo']), set()),
             ('addSuccess', a),
             ('stopTest', a),
             ('time', 3),
             ('startTest', b),
             ('time', 4),
             ('addSuccess', b),
             ('stopTest', b),
             ], events)

    def test_startTestRun(self):
        # Calls to startTestRun are not batched, because we are only
        # interested in sending tests atomically, not the whole run.
        [result1, result2], events = self.make_results(2)
        result1.startTestRun()
        result2.startTestRun()
        self.assertEqual(["startTestRun", "startTestRun"], events)

    def test_stopTestRun(self):
        # Calls to stopTestRun are not batched, because we are only
        # interested in sending tests atomically, not the whole run.
        [result1, result2], events = self.make_results(2)
        result1.stopTestRun()
        result2.stopTestRun()
        self.assertEqual(["stopTestRun", "stopTestRun"], events)

    def test_forward_addError(self):
        # Once we receive an addError event, we forward all of the events for
        # that test, as we now know that test is complete.
        [result], events = self.make_results(1)
        exc_info = make_exception_info(RuntimeError, 'error')
        start_time = datetime.datetime.utcfromtimestamp(1.489)
        end_time = datetime.datetime.utcfromtimestamp(51.476)
        result.time(start_time)
        result.startTest(self)
        result.time(end_time)
        result.addError(self, exc_info)
        self.assertEqual([
            ('time', start_time),
            ('startTest', self),
            ('time', end_time),
            ('addError', self, exc_info),
            ('stopTest', self),
            ], events)

    def test_forward_addFailure(self):
        # Once we receive an addFailure event, we forward all of the events
        # for that test, as we now know that test is complete.
        [result], events = self.make_results(1)
        exc_info = make_exception_info(AssertionError, 'failure')
        start_time = datetime.datetime.utcfromtimestamp(2.489)
        end_time = datetime.datetime.utcfromtimestamp(3.476)
        result.time(start_time)
        result.startTest(self)
        result.time(end_time)
        result.addFailure(self, exc_info)
        self.assertEqual([
            ('time', start_time),
            ('startTest', self),
            ('time', end_time),
            ('addFailure', self, exc_info),
            ('stopTest', self),
            ], events)

    def test_forward_addSkip(self):
        # Once we receive an addSkip event, we forward all of the events for
        # that test, as we now know that test is complete.
        [result], events = self.make_results(1)
        reason = _u("Skipped for some reason")
        start_time = datetime.datetime.utcfromtimestamp(4.489)
        end_time = datetime.datetime.utcfromtimestamp(5.476)
        result.time(start_time)
        result.startTest(self)
        result.time(end_time)
        result.addSkip(self, reason)
        self.assertEqual([
            ('time', start_time),
            ('startTest', self),
            ('time', end_time),
            ('addSkip', self, reason),
            ('stopTest', self),
            ], events)

    def test_forward_addSuccess(self):
        # Once we receive an addSuccess event, we forward all of the events
        # for that test, as we now know that test is complete.
        [result], events = self.make_results(1)
        start_time = datetime.datetime.utcfromtimestamp(6.489)
        end_time = datetime.datetime.utcfromtimestamp(7.476)
        result.time(start_time)
        result.startTest(self)
        result.time(end_time)
        result.addSuccess(self)
        self.assertEqual([
            ('time', start_time),
            ('startTest', self),
            ('time', end_time),
            ('addSuccess', self),
            ('stopTest', self),
            ], events)

    def test_only_one_test_at_a_time(self):
        # Even if there are multiple ThreadsafeForwardingResults forwarding to
        # the same target result, the target result only receives the complete
        # events for one test at a time.
        [result1, result2], events = self.make_results(2)
        test1, test2 = self, make_test()
        start_time1 = datetime.datetime.utcfromtimestamp(1.489)
        end_time1 = datetime.datetime.utcfromtimestamp(2.476)
        start_time2 = datetime.datetime.utcfromtimestamp(3.489)
        end_time2 = datetime.datetime.utcfromtimestamp(4.489)
        result1.time(start_time1)
        result2.time(start_time2)
        result1.startTest(test1)
        result2.startTest(test2)
        result1.time(end_time1)
        result2.time(end_time2)
        result2.addSuccess(test2)
        result1.addSuccess(test1)
        self.assertEqual([
            # test2 finishes first, and so is flushed first.
            ('time', start_time2),
            ('startTest', test2),
            ('time', end_time2),
            ('addSuccess', test2),
            ('stopTest', test2),
            # test1 finishes next, and thus follows.
            ('time', start_time1),
            ('startTest', test1),
            ('time', end_time1),
            ('addSuccess', test1),
            ('stopTest', test1),
            ], events)


class TestMergeTags(TestCase):

    def test_merge_unseen_gone_tag(self):
        # If an incoming "gone" tag isn't currently tagged one way or the
        # other, add it to the "gone" tags.
        current_tags = set(['present']), set(['missing'])
        changing_tags = set(), set(['going'])
        expected = set(['present']), set(['missing', 'going'])
        self.assertEqual(
            expected, _merge_tags(current_tags, changing_tags))

    def test_merge_incoming_gone_tag_with_current_new_tag(self):
        # If one of the incoming "gone" tags is one of the existing "new"
        # tags, then it overrides the "new" tag, leaving it marked as "gone".
        current_tags = set(['present', 'going']), set(['missing'])
        changing_tags = set(), set(['going'])
        expected = set(['present']), set(['missing', 'going'])
        self.assertEqual(
            expected, _merge_tags(current_tags, changing_tags))

    def test_merge_unseen_new_tag(self):
        current_tags = set(['present']), set(['missing'])
        changing_tags = set(['coming']), set()
        expected = set(['coming', 'present']), set(['missing'])
        self.assertEqual(
            expected, _merge_tags(current_tags, changing_tags))

    def test_merge_incoming_new_tag_with_current_gone_tag(self):
        # If one of the incoming "new" tags is currently marked as "gone",
        # then it overrides the "gone" tag, leaving it marked as "new".
        current_tags = set(['present']), set(['coming', 'missing'])
        changing_tags = set(['coming']), set()
        expected = set(['coming', 'present']), set(['missing'])
        self.assertEqual(
            expected, _merge_tags(current_tags, changing_tags))


class TestStreamResultRouter(TestCase):

    def test_start_stop_test_run_no_fallback(self):
        result = StreamResultRouter()
        result.startTestRun()
        result.stopTestRun()

    def test_no_fallback_errors(self):
        self.assertRaises(Exception, StreamResultRouter().status, test_id='f')

    def test_fallback_calls(self):
        fallback = LoggingStreamResult()
        result = StreamResultRouter(fallback)
        result.startTestRun()
        result.status(test_id='foo')
        result.stopTestRun()
        self.assertEqual([
            ('startTestRun',),
            ('status', 'foo', None, None, True, None, None, False, None, None,
             None),
            ('stopTestRun',),
            ],
            fallback._events)

    def test_fallback_no_do_start_stop_run(self):
        fallback = LoggingStreamResult()
        result = StreamResultRouter(fallback, do_start_stop_run=False)
        result.startTestRun()
        result.status(test_id='foo')
        result.stopTestRun()
        self.assertEqual([
            ('status', 'foo', None, None, True, None, None, False, None, None,
             None)
            ],
            fallback._events)

    def test_add_rule_bad_policy(self):
        router = StreamResultRouter()
        target = LoggingStreamResult()
        self.assertRaises(ValueError, router.add_rule, target, 'route_code_prefixa',
            route_prefix='0')

    def test_add_rule_extra_policy_arg(self):
        router = StreamResultRouter()
        target = LoggingStreamResult()
        self.assertRaises(TypeError, router.add_rule, target, 'route_code_prefix',
            route_prefix='0', foo=1)

    def test_add_rule_missing_prefix(self):
        router = StreamResultRouter()
        target = LoggingStreamResult()
        self.assertRaises(TypeError, router.add_rule, target, 'route_code_prefix')

    def test_add_rule_slash_in_prefix(self):
        router = StreamResultRouter()
        target = LoggingStreamResult()
        self.assertRaises(TypeError, router.add_rule, target, 'route_code_prefix',
            route_prefix='0/')

    def test_add_rule_route_code_consume_False(self):
        fallback = LoggingStreamResult()
        target = LoggingStreamResult()
        router = StreamResultRouter(fallback)
        router.add_rule(target, 'route_code_prefix', route_prefix='0')
        router.status(test_id='foo', route_code='0')
        router.status(test_id='foo', route_code='0/1')
        router.status(test_id='foo')
        self.assertEqual([
            ('status', 'foo', None, None, True, None, None, False, None, '0',
             None),
            ('status', 'foo', None, None, True, None, None, False, None, '0/1',
             None),
            ],
            target._events)
        self.assertEqual([
            ('status', 'foo', None, None, True, None, None, False, None, None,
             None),
            ],
            fallback._events)

    def test_add_rule_route_code_consume_True(self):
        fallback = LoggingStreamResult()
        target = LoggingStreamResult()
        router = StreamResultRouter(fallback)
        router.add_rule(
            target, 'route_code_prefix', route_prefix='0', consume_route=True)
        router.status(test_id='foo', route_code='0') # -> None
        router.status(test_id='foo', route_code='0/1') # -> 1
        router.status(test_id='foo', route_code='1') # -> fallback as-is.
        self.assertEqual([
            ('status', 'foo', None, None, True, None, None, False, None, None,
             None),
            ('status', 'foo', None, None, True, None, None, False, None, '1',
             None),
            ],
            target._events)
        self.assertEqual([
            ('status', 'foo', None, None, True, None, None, False, None, '1',
             None),
            ],
            fallback._events)

    def test_add_rule_test_id(self):
        nontest = LoggingStreamResult()
        test = LoggingStreamResult()
        router = StreamResultRouter(test)
        router.add_rule(nontest, 'test_id', test_id=None)
        router.status(test_id='foo', file_name="bar", file_bytes=b'')
        router.status(file_name="bar", file_bytes=b'')
        self.assertEqual([
            ('status', 'foo', None, None, True, 'bar', b'', False, None, None,
             None),], test._events)
        self.assertEqual([
            ('status', None, None, None, True, 'bar', b'', False, None, None,
             None),], nontest._events)

    def test_add_rule_do_start_stop_run(self):
        nontest = LoggingStreamResult()
        router = StreamResultRouter()
        router.add_rule(nontest, 'test_id', test_id=None, do_start_stop_run=True)
        router.startTestRun()
        router.stopTestRun()
        self.assertEqual([
            ('startTestRun',),
            ('stopTestRun',),
            ], nontest._events)

    def test_add_rule_do_start_stop_run_after_startTestRun(self):
        nontest = LoggingStreamResult()
        router = StreamResultRouter()
        router.startTestRun()
        router.add_rule(nontest, 'test_id', test_id=None, do_start_stop_run=True)
        router.stopTestRun()
        self.assertEqual([
            ('startTestRun',),
            ('stopTestRun',),
            ], nontest._events)


class TestStreamToQueue(TestCase):

    def make_result(self):
        queue = Queue()
        return queue, StreamToQueue(queue, "foo")

    def test_status(self):
        def check_event(event_dict, route=None, time=None):
            self.assertEqual("status", event_dict['event'])
            self.assertEqual("test", event_dict['test_id'])
            self.assertEqual("fail", event_dict['test_status'])
            self.assertEqual(set(["quux"]), event_dict['test_tags'])
            self.assertEqual(False, event_dict['runnable'])
            self.assertEqual("file", event_dict['file_name'])
            self.assertEqual(_b("content"), event_dict['file_bytes'])
            self.assertEqual(True, event_dict['eof'])
            self.assertEqual("quux", event_dict['mime_type'])
            self.assertEqual("test", event_dict['test_id'])
            self.assertEqual(route, event_dict['route_code'])
            self.assertEqual(time, event_dict['timestamp'])
        queue, result = self.make_result()
        result.status("test", "fail", test_tags=set(["quux"]), runnable=False,
            file_name="file", file_bytes=_b("content"), eof=True,
            mime_type="quux", route_code=None, timestamp=None)
        self.assertEqual(1, queue.qsize())
        a_time = datetime.datetime.now(utc)
        result.status("test", "fail", test_tags=set(["quux"]), runnable=False,
            file_name="file", file_bytes=_b("content"), eof=True,
            mime_type="quux", route_code="bar", timestamp=a_time)
        self.assertEqual(2, queue.qsize())
        check_event(queue.get(False), route="foo", time=None)
        check_event(queue.get(False), route="foo/bar", time=a_time)

    def testStartTestRun(self):
        queue, result = self.make_result()
        result.startTestRun()
        self.assertEqual(
            {'event':'startTestRun', 'result':result}, queue.get(False))
        self.assertTrue(queue.empty())

    def testStopTestRun(self):
        queue, result = self.make_result()
        result.stopTestRun()
        self.assertEqual(
            {'event':'stopTestRun', 'result':result}, queue.get(False))
        self.assertTrue(queue.empty())


class TestExtendedToOriginalResultDecoratorBase(TestCase):

    def make_26_result(self):
        self.result = Python26TestResult()
        self.make_converter()

    def make_27_result(self):
        self.result = Python27TestResult()
        self.make_converter()

    def make_converter(self):
        self.converter = ExtendedToOriginalDecorator(self.result)

    def make_extended_result(self):
        self.result = ExtendedTestResult()
        self.make_converter()

    def check_outcome_details(self, outcome):
        """Call an outcome with a details dict to be passed through."""
        # This dict is /not/ convertible - thats deliberate, as it should
        # not hit the conversion code path.
        details = {'foo': 'bar'}
        getattr(self.converter, outcome)(self, details=details)
        self.assertEqual([(outcome, self, details)], self.result._events)

    def get_details_and_string(self):
        """Get a details dict and expected string."""
        text1 = lambda: [_b("1\n2\n")]
        text2 = lambda: [_b("3\n4\n")]
        bin1 = lambda: [_b("5\n")]
        details = {'text 1': Content(ContentType('text', 'plain'), text1),
            'text 2': Content(ContentType('text', 'strange'), text2),
            'bin 1': Content(ContentType('application', 'binary'), bin1)}
        return (details,
                ("Binary content:\n"
                 "  bin 1 (application/binary)\n"
                 "\n"
                 "text 1: {{{\n"
                 "1\n"
                 "2\n"
                 "}}}\n"
                 "\n"
                 "text 2: {{{\n"
                 "3\n"
                 "4\n"
                 "}}}\n"))

    def check_outcome_details_to_exec_info(self, outcome, expected=None):
        """Call an outcome with a details dict to be made into exc_info."""
        # The conversion is a done using RemoteError and the string contents
        # of the text types in the details dict.
        if not expected:
            expected = outcome
        details, err_str = self.get_details_and_string()
        getattr(self.converter, outcome)(self, details=details)
        err = self.converter._details_to_exc_info(details)
        self.assertEqual([(expected, self, err)], self.result._events)

    def check_outcome_details_to_nothing(self, outcome, expected=None):
        """Call an outcome with a details dict to be swallowed."""
        if not expected:
            expected = outcome
        details = {'foo': 'bar'}
        getattr(self.converter, outcome)(self, details=details)
        self.assertEqual([(expected, self)], self.result._events)

    def check_outcome_details_to_string(self, outcome):
        """Call an outcome with a details dict to be stringified."""
        details, err_str = self.get_details_and_string()
        getattr(self.converter, outcome)(self, details=details)
        self.assertEqual([(outcome, self, err_str)], self.result._events)

    def check_outcome_details_to_arg(self, outcome, arg, extra_detail=None):
        """Call an outcome with a details dict to have an arg extracted."""
        details, _ = self.get_details_and_string()
        if extra_detail:
            details.update(extra_detail)
        getattr(self.converter, outcome)(self, details=details)
        self.assertEqual([(outcome, self, arg)], self.result._events)

    def check_outcome_exc_info(self, outcome, expected=None):
        """Check that calling a legacy outcome still works."""
        # calling some outcome with the legacy exc_info style api (no keyword
        # parameters) gets passed through.
        if not expected:
            expected = outcome
        err = sys.exc_info()
        getattr(self.converter, outcome)(self, err)
        self.assertEqual([(expected, self, err)], self.result._events)

    def check_outcome_exc_info_to_nothing(self, outcome, expected=None):
        """Check that calling a legacy outcome on a fallback works."""
        # calling some outcome with the legacy exc_info style api (no keyword
        # parameters) gets passed through.
        if not expected:
            expected = outcome
        err = sys.exc_info()
        getattr(self.converter, outcome)(self, err)
        self.assertEqual([(expected, self)], self.result._events)

    def check_outcome_nothing(self, outcome, expected=None):
        """Check that calling a legacy outcome still works."""
        if not expected:
            expected = outcome
        getattr(self.converter, outcome)(self)
        self.assertEqual([(expected, self)], self.result._events)

    def check_outcome_string_nothing(self, outcome, expected):
        """Check that calling outcome with a string calls expected."""
        getattr(self.converter, outcome)(self, "foo")
        self.assertEqual([(expected, self)], self.result._events)

    def check_outcome_string(self, outcome):
        """Check that calling outcome with a string works."""
        getattr(self.converter, outcome)(self, "foo")
        self.assertEqual([(outcome, self, "foo")], self.result._events)


class TestExtendedToOriginalResultDecorator(
    TestExtendedToOriginalResultDecoratorBase):

    def test_failfast_py26(self):
        self.make_26_result()
        self.assertEqual(False, self.converter.failfast)
        self.converter.failfast = True
        self.assertFalse(safe_hasattr(self.converter.decorated, 'failfast'))

    def test_failfast_py27(self):
        self.make_27_result()
        self.assertEqual(False, self.converter.failfast)
        # setting it should write it to the backing result
        self.converter.failfast = True
        self.assertEqual(True, self.converter.decorated.failfast)

    def test_progress_py26(self):
        self.make_26_result()
        self.converter.progress(1, 2)

    def test_progress_py27(self):
        self.make_27_result()
        self.converter.progress(1, 2)

    def test_progress_pyextended(self):
        self.make_extended_result()
        self.converter.progress(1, 2)
        self.assertEqual([('progress', 1, 2)], self.result._events)

    def test_shouldStop(self):
        self.make_26_result()
        self.assertEqual(False, self.converter.shouldStop)
        self.converter.decorated.stop()
        self.assertEqual(True, self.converter.shouldStop)

    def test_startTest_py26(self):
        self.make_26_result()
        self.converter.startTest(self)
        self.assertEqual([('startTest', self)], self.result._events)

    def test_startTest_py27(self):
        self.make_27_result()
        self.converter.startTest(self)
        self.assertEqual([('startTest', self)], self.result._events)

    def test_startTest_pyextended(self):
        self.make_extended_result()
        self.converter.startTest(self)
        self.assertEqual([('startTest', self)], self.result._events)

    def test_startTestRun_py26(self):
        self.make_26_result()
        self.converter.startTestRun()
        self.assertEqual([], self.result._events)

    def test_startTestRun_py27(self):
        self.make_27_result()
        self.converter.startTestRun()
        self.assertEqual([('startTestRun',)], self.result._events)

    def test_startTestRun_pyextended(self):
        self.make_extended_result()
        self.converter.startTestRun()
        self.assertEqual([('startTestRun',)], self.result._events)

    def test_stopTest_py26(self):
        self.make_26_result()
        self.converter.stopTest(self)
        self.assertEqual([('stopTest', self)], self.result._events)

    def test_stopTest_py27(self):
        self.make_27_result()
        self.converter.stopTest(self)
        self.assertEqual([('stopTest', self)], self.result._events)

    def test_stopTest_pyextended(self):
        self.make_extended_result()
        self.converter.stopTest(self)
        self.assertEqual([('stopTest', self)], self.result._events)

    def test_stopTestRun_py26(self):
        self.make_26_result()
        self.converter.stopTestRun()
        self.assertEqual([], self.result._events)

    def test_stopTestRun_py27(self):
        self.make_27_result()
        self.converter.stopTestRun()
        self.assertEqual([('stopTestRun',)], self.result._events)

    def test_stopTestRun_pyextended(self):
        self.make_extended_result()
        self.converter.stopTestRun()
        self.assertEqual([('stopTestRun',)], self.result._events)

    def test_tags_py26(self):
        self.make_26_result()
        self.converter.tags(set([1]), set([2]))

    def test_tags_py27(self):
        self.make_27_result()
        self.converter.tags(set([1]), set([2]))

    def test_tags_pyextended(self):
        self.make_extended_result()
        self.converter.tags(set([1]), set([2]))
        self.assertEqual([('tags', set([1]), set([2]))], self.result._events)

    def test_time_py26(self):
        self.make_26_result()
        self.converter.time(1)

    def test_time_py27(self):
        self.make_27_result()
        self.converter.time(1)

    def test_time_pyextended(self):
        self.make_extended_result()
        self.converter.time(1)
        self.assertEqual([('time', 1)], self.result._events)


class TestExtendedToOriginalAddError(TestExtendedToOriginalResultDecoratorBase):

    outcome = 'addError'

    def test_outcome_Original_py26(self):
        self.make_26_result()
        self.check_outcome_exc_info(self.outcome)

    def test_outcome_Original_py27(self):
        self.make_27_result()
        self.check_outcome_exc_info(self.outcome)

    def test_outcome_Original_pyextended(self):
        self.make_extended_result()
        self.check_outcome_exc_info(self.outcome)

    def test_outcome_Extended_py26(self):
        self.make_26_result()
        self.check_outcome_details_to_exec_info(self.outcome)

    def test_outcome_Extended_py27(self):
        self.make_27_result()
        self.check_outcome_details_to_exec_info(self.outcome)

    def test_outcome_Extended_pyextended(self):
        self.make_extended_result()
        self.check_outcome_details(self.outcome)

    def test_outcome__no_details(self):
        self.make_extended_result()
        self.assertThat(
            lambda: getattr(self.converter, self.outcome)(self),
            Raises(MatchesException(ValueError)))


class TestExtendedToOriginalAddFailure(
    TestExtendedToOriginalAddError):

    outcome = 'addFailure'


class TestExtendedToOriginalAddExpectedFailure(
    TestExtendedToOriginalAddError):

    outcome = 'addExpectedFailure'

    def test_outcome_Original_py26(self):
        self.make_26_result()
        self.check_outcome_exc_info_to_nothing(self.outcome, 'addSuccess')

    def test_outcome_Extended_py26(self):
        self.make_26_result()
        self.check_outcome_details_to_nothing(self.outcome, 'addSuccess')



class TestExtendedToOriginalAddSkip(
    TestExtendedToOriginalResultDecoratorBase):

    outcome = 'addSkip'

    def test_outcome_Original_py26(self):
        self.make_26_result()
        self.check_outcome_string_nothing(self.outcome, 'addSuccess')

    def test_outcome_Original_py27(self):
        self.make_27_result()
        self.check_outcome_string(self.outcome)

    def test_outcome_Original_pyextended(self):
        self.make_extended_result()
        self.check_outcome_string(self.outcome)

    def test_outcome_Extended_py26(self):
        self.make_26_result()
        self.check_outcome_string_nothing(self.outcome, 'addSuccess')

    def test_outcome_Extended_py27_no_reason(self):
        self.make_27_result()
        self.check_outcome_details_to_string(self.outcome)

    def test_outcome_Extended_py27_reason(self):
        self.make_27_result()
        self.check_outcome_details_to_arg(self.outcome, 'foo',
            {'reason': Content(UTF8_TEXT, lambda:[_b('foo')])})

    def test_outcome_Extended_pyextended(self):
        self.make_extended_result()
        self.check_outcome_details(self.outcome)

    def test_outcome__no_details(self):
        self.make_extended_result()
        self.assertThat(
            lambda: getattr(self.converter, self.outcome)(self),
            Raises(MatchesException(ValueError)))


class TestExtendedToOriginalAddSuccess(
    TestExtendedToOriginalResultDecoratorBase):

    outcome = 'addSuccess'
    expected = 'addSuccess'

    def test_outcome_Original_py26(self):
        self.make_26_result()
        self.check_outcome_nothing(self.outcome, self.expected)

    def test_outcome_Original_py27(self):
        self.make_27_result()
        self.check_outcome_nothing(self.outcome)

    def test_outcome_Original_pyextended(self):
        self.make_extended_result()
        self.check_outcome_nothing(self.outcome)

    def test_outcome_Extended_py26(self):
        self.make_26_result()
        self.check_outcome_details_to_nothing(self.outcome, self.expected)

    def test_outcome_Extended_py27(self):
        self.make_27_result()
        self.check_outcome_details_to_nothing(self.outcome)

    def test_outcome_Extended_pyextended(self):
        self.make_extended_result()
        self.check_outcome_details(self.outcome)


class TestExtendedToOriginalAddUnexpectedSuccess(
    TestExtendedToOriginalResultDecoratorBase):

    outcome = 'addUnexpectedSuccess'
    expected = 'addFailure'

    def test_outcome_Original_py26(self):
        self.make_26_result()
        getattr(self.converter, self.outcome)(self)
        [event] = self.result._events
        self.assertEqual((self.expected, self), event[:2])

    def test_outcome_Original_py27(self):
        self.make_27_result()
        self.check_outcome_nothing(self.outcome)

    def test_outcome_Original_pyextended(self):
        self.make_extended_result()
        self.check_outcome_nothing(self.outcome)

    def test_outcome_Extended_py26(self):
        self.make_26_result()
        getattr(self.converter, self.outcome)(self)
        [event] = self.result._events
        self.assertEqual((self.expected, self), event[:2])

    def test_outcome_Extended_py27(self):
        self.make_27_result()
        self.check_outcome_details_to_nothing(self.outcome)

    def test_outcome_Extended_pyextended(self):
        self.make_extended_result()
        self.check_outcome_details(self.outcome)


class TestExtendedToOriginalResultOtherAttributes(
    TestExtendedToOriginalResultDecoratorBase):

    def test_other_attribute(self):
        class OtherExtendedResult:
            def foo(self):
                return 2
            bar = 1
        self.result = OtherExtendedResult()
        self.make_converter()
        self.assertEqual(1, self.converter.bar)
        self.assertEqual(2, self.converter.foo())


class TestNonAsciiResults(TestCase):
    """Test all kinds of tracebacks are cleanly interpreted as unicode

    Currently only uses weak "contains" assertions, would be good to be much
    stricter about the expected output. This would add a few failures for the
    current release of IronPython for instance, which gets some traceback
    lines muddled.
    """

    _sample_texts = (
        _u("pa\u026a\u03b8\u0259n"), # Unicode encodings only
        _u("\u5357\u7121"), # In ISO 2022 encodings
        _u("\xa7\xa7\xa7"), # In ISO 8859 encodings
        )

    _is_pypy = "__pypy__" in sys.builtin_module_names
    # Everything but Jython shows syntax errors on the current character
    _error_on_character = os.name != "java" and not _is_pypy

    def _run(self, stream, test):
        """Run the test, the same as in testtools.run but not to stdout"""
        result = TextTestResult(stream)
        result.startTestRun()
        try:
            return test.run(result)
        finally:
            result.stopTestRun()

    def _write_module(self, name, encoding, contents):
        """Create Python module on disk with contents in given encoding"""
        try:
            # Need to pre-check that the coding is valid or codecs.open drops
            # the file without closing it which breaks non-refcounted pythons
            codecs.lookup(encoding)
        except LookupError:
            self.skip("Encoding unsupported by implementation: %r" % encoding)
        f = codecs.open(os.path.join(self.dir, name + ".py"), "w", encoding)
        try:
            f.write(contents)
        finally:
            f.close()

    def _test_external_case(self, testline, coding="ascii", modulelevel="",
            suffix=""):
        """Create and run a test case in a seperate module"""
        self._setup_external_case(testline, coding, modulelevel, suffix)
        return self._run_external_case()

    def _setup_external_case(self, testline, coding="ascii", modulelevel="",
            suffix=""):
        """Create a test case in a seperate module"""
        _, prefix, self.modname = self.id().rsplit(".", 2)
        self.dir = tempfile.mkdtemp(prefix=prefix, suffix=suffix)
        self.addCleanup(shutil.rmtree, self.dir)
        self._write_module(self.modname, coding,
            # Older Python 2 versions don't see a coding declaration in a
            # docstring so it has to be in a comment, but then we can't
            # workaround bug: <http://ironpython.codeplex.com/workitem/26940>
            "# coding: %s\n"
            "import testtools\n"
            "%s\n"
            "class Test(testtools.TestCase):\n"
            "    def runTest(self):\n"
            "        %s\n" % (coding, modulelevel, testline))

    def _run_external_case(self):
        """Run the prepared test case in a seperate module"""
        sys.path.insert(0, self.dir)
        self.addCleanup(sys.path.remove, self.dir)
        module = __import__(self.modname)
        self.addCleanup(sys.modules.pop, self.modname)
        stream = StringIO()
        self._run(stream, module.Test())
        return stream.getvalue()

    def _get_sample_text(self, encoding="unicode_internal"):
        if encoding is None and str_is_unicode:
           encoding = "unicode_internal"
        for u in self._sample_texts:
            try:
                b = u.encode(encoding)
                if u == b.decode(encoding):
                   if str_is_unicode:
                       return u, u
                   return u, b
            except (LookupError, UnicodeError):
                pass
        self.skip("Could not find a sample text for encoding: %r" % encoding)

    def _as_output(self, text):
        return text

    def test_non_ascii_failure_string(self):
        """Assertion contents can be non-ascii and should get decoded"""
        text, raw = self._get_sample_text(_get_exception_encoding())
        textoutput = self._test_external_case("self.fail(%s)" % _r(raw))
        self.assertIn(self._as_output(text), textoutput)

    def test_non_ascii_failure_string_via_exec(self):
        """Assertion via exec can be non-ascii and still gets decoded"""
        text, raw = self._get_sample_text(_get_exception_encoding())
        textoutput = self._test_external_case(
            testline='exec ("self.fail(%s)")' % _r(raw))
        self.assertIn(self._as_output(text), textoutput)

    def test_control_characters_in_failure_string(self):
        """Control characters in assertions should be escaped"""
        textoutput = self._test_external_case("self.fail('\\a\\a\\a')")
        self.expectFailure("Defense against the beeping horror unimplemented",
            self.assertNotIn, self._as_output("\a\a\a"), textoutput)
        self.assertIn(self._as_output(_u("\uFFFD\uFFFD\uFFFD")), textoutput)

    def _local_os_error_matcher(self):
        if sys.version_info > (3, 3):
            return MatchesAny(Contains("FileExistsError: "),
                              Contains("PermissionError: "))
        elif os.name != "nt":
            return Contains(self._as_output("OSError: "))
        else:
            return Contains(self._as_output("WindowsError: "))

    def test_os_error(self):
        """Locale error messages from the OS shouldn't break anything"""
        textoutput = self._test_external_case(
            modulelevel="import os",
            testline="os.mkdir('/')")
        self.assertThat(textoutput, self._local_os_error_matcher())

    def test_assertion_text_shift_jis(self):
        """A terminal raw backslash in an encoded string is weird but fine"""
        example_text = _u("\u5341")
        textoutput = self._test_external_case(
            coding="shift_jis",
            testline="self.fail('%s')" % example_text)
        if str_is_unicode:
            output_text = example_text
        else:
            output_text = "b%r" % example_text.encode("shift_jis")
        self.assertIn(self._as_output("AssertionError: %s" % output_text),
            textoutput)

    def test_file_comment_iso2022_jp(self):
        """Control character escapes must be preserved if valid encoding"""
        example_text, _ = self._get_sample_text("iso2022_jp")
        textoutput = self._test_external_case(
            coding="iso2022_jp",
            testline="self.fail('Simple') # %s" % example_text)
        self.assertIn(self._as_output(example_text), textoutput)

    def test_unicode_exception(self):
        """Exceptions that can be formated losslessly as unicode should be"""
        example_text, _ = self._get_sample_text()
        exception_class = (
            "class FancyError(Exception):\n"
            # A __unicode__ method does nothing on py3k but the default works
            "    def __unicode__(self):\n"
            "        return self.args[0]\n")
        textoutput = self._test_external_case(
            modulelevel=exception_class,
            testline="raise FancyError(%s)" % _r(example_text))
        self.assertIn(self._as_output(example_text), textoutput)

    def test_unprintable_exception(self):
        """A totally useless exception instance still prints something"""
        exception_class = (
            "class UnprintableError(Exception):\n"
            "    def __str__(self):\n"
            "        raise RuntimeError\n"
            "    def __unicode__(self):\n"
            "        raise RuntimeError\n"
            "    def __repr__(self):\n"
            "        raise RuntimeError\n")
        textoutput = self._test_external_case(
            modulelevel=exception_class,
            testline="raise UnprintableError")
        self.assertIn(self._as_output(
            "UnprintableError: <unprintable UnprintableError object>\n"),
            textoutput)

    def test_non_ascii_dirname(self):
        """Script paths in the traceback can be non-ascii"""
        text, raw = self._get_sample_text(sys.getfilesystemencoding())
        textoutput = self._test_external_case(
            # Avoid bug in Python 3 by giving a unicode source encoding rather
            # than just ascii which raises a SyntaxError with no other details
            coding="utf-8",
            testline="self.fail('Simple')",
            suffix=raw)
        self.assertIn(self._as_output(text), textoutput)

    def test_syntax_error(self):
        """Syntax errors should still have fancy special-case formatting"""
        textoutput = self._test_external_case("exec ('f(a, b c)')")
        self.assertIn(self._as_output(
            '  File "<string>", line 1\n'
            '    f(a, b c)\n'
            + ' ' * self._error_on_character +
            '          ^\n'
            'SyntaxError: '
            ), textoutput)

    def test_syntax_error_malformed(self):
        """Syntax errors with bogus parameters should break anything"""
        textoutput = self._test_external_case("raise SyntaxError(3, 2, 1)")
        self.assertIn(self._as_output("\nSyntaxError: "), textoutput)

    def test_syntax_error_line_iso_8859_1(self):
        """Syntax error on a latin-1 line shows the line decoded"""
        text, raw = self._get_sample_text("iso-8859-1")
        textoutput = self._setup_external_case("import bad")
        self._write_module("bad", "iso-8859-1",
            "# coding: iso-8859-1\n! = 0 # %s\n" % text)
        textoutput = self._run_external_case()
        self.assertIn(self._as_output(_u(
            #'bad.py", line 2\n'
            '    ! = 0 # %s\n'
            '    ^\n'
            'SyntaxError: ') %
            (text,)), textoutput)

    def test_syntax_error_line_iso_8859_5(self):
        """Syntax error on a iso-8859-5 line shows the line decoded"""
        text, raw = self._get_sample_text("iso-8859-5")
        textoutput = self._setup_external_case("import bad")
        self._write_module("bad", "iso-8859-5",
            "# coding: iso-8859-5\n%% = 0 # %s\n" % text)
        textoutput = self._run_external_case()
        self.assertThat(
            textoutput,
            MatchesRegex(
                self._as_output(_u(
                #'bad.py", line 2\n'
                '.*%% = 0 # %s\n'
                + ' ' * self._error_on_character +
                '\\s*\\^\n'
                'SyntaxError:.*') %
                (text,)),
            re.MULTILINE | re.DOTALL)
        )

    def test_syntax_error_line_euc_jp(self):
        """Syntax error on a euc_jp line shows the line decoded"""
        text, raw = self._get_sample_text("euc_jp")
        textoutput = self._setup_external_case("import bad")
        self._write_module("bad", "euc_jp",
            "# coding: euc_jp\n$ = 0 # %s\n" % text)
        textoutput = self._run_external_case()
        # pypy uses cpython's multibyte codecs so has their behavior here
        if self._is_pypy:
            self._error_on_character = True
        self.assertIn(self._as_output(_u(
            #'bad.py", line 2\n'
            '    $ = 0 # %s\n'
            + ' ' * self._error_on_character +
            '   ^\n'
            'SyntaxError: ') %
            (text,)), textoutput)

    def test_syntax_error_line_utf_8(self):
        """Syntax error on a utf-8 line shows the line decoded"""
        text, raw = self._get_sample_text("utf-8")
        textoutput = self._setup_external_case("import bad")
        self._write_module("bad", "utf-8", _u("\ufeff^ = 0 # %s\n") % text)
        textoutput = self._run_external_case()
        self.assertThat(
            textoutput,
            MatchesRegex(
                self._as_output(_u(
                    '.*bad.py", line 1\n'
                    '\\s*\\^ = 0 # %s\n'
                    + ' ' * self._error_on_character +
                    '\\s*\\^\n'
                    'SyntaxError:.*') % text),
                re.M | re.S)
        )


class TestNonAsciiResultsWithUnittest(TestNonAsciiResults):
    """Test that running under unittest produces clean ascii strings"""

    def _run(self, stream, test):
        from unittest import TextTestRunner as _Runner
        return _Runner(stream).run(test)

    def _as_output(self, text):
        if str_is_unicode:
            return text
        return text.encode("utf-8")


class TestDetailsToStr(TestCase):

    def test_no_details(self):
        string = _details_to_str({})
        self.assertThat(string, Equals(''))

    def test_binary_content(self):
        content = content_from_stream(
            StringIO('foo'), content_type=ContentType('image', 'jpeg'))
        string = _details_to_str({'attachment': content})
        self.assertThat(
            string, Equals("""\
Binary content:
  attachment (image/jpeg)
"""))

    def test_single_line_content(self):
        content = text_content('foo')
        string = _details_to_str({'attachment': content})
        self.assertThat(string, Equals('attachment: {{{foo}}}\n'))

    def test_multi_line_text_content(self):
        content = text_content('foo\nbar\nbaz')
        string = _details_to_str({'attachment': content})
        self.assertThat(string, Equals('attachment: {{{\nfoo\nbar\nbaz\n}}}\n'))

    def test_special_text_content(self):
        content = text_content('foo')
        string = _details_to_str({'attachment': content}, special='attachment')
        self.assertThat(string, Equals('foo\n'))

    def test_multiple_text_content(self):
        string = _details_to_str(
            {'attachment': text_content('foo\nfoo'),
             'attachment-1': text_content('bar\nbar')})
        self.assertThat(
            string, Equals('attachment: {{{\n'
                           'foo\n'
                           'foo\n'
                           '}}}\n'
                           '\n'
                           'attachment-1: {{{\n'
                           'bar\n'
                           'bar\n'
                           '}}}\n'))

    def test_empty_attachment(self):
        string = _details_to_str({'attachment': text_content('')})
        self.assertThat(
            string, Equals("""\
Empty attachments:
  attachment
"""))

    def test_lots_of_different_attachments(self):
        jpg = lambda x: content_from_stream(
            StringIO(x), ContentType('image', 'jpeg'))
        attachments = {
            'attachment': text_content('foo'),
            'attachment-1': text_content('traceback'),
            'attachment-2': jpg('pic1'),
            'attachment-3': text_content('bar'),
            'attachment-4': text_content(''),
            'attachment-5': jpg('pic2'),
            }
        string = _details_to_str(attachments, special='attachment-1')
        self.assertThat(
            string, Equals("""\
Binary content:
  attachment-2 (image/jpeg)
  attachment-5 (image/jpeg)
Empty attachments:
  attachment-4

attachment: {{{foo}}}
attachment-3: {{{bar}}}

traceback
"""))


class TestByTestResultTests(TestCase):

    def setUp(self):
        super(TestByTestResultTests, self).setUp()
        self.log = []
        self.result = TestByTestResult(self.on_test)
        now = iter(range(5))
        self.result._now = lambda: advance_iterator(now)

    def assertCalled(self, **kwargs):
        defaults = {
            'test': self,
            'tags': set(),
            'details': None,
            'start_time': 0,
            'stop_time': 1,
            }
        defaults.update(kwargs)
        self.assertEqual([defaults], self.log)

    def on_test(self, **kwargs):
        self.log.append(kwargs)

    def test_no_tests_nothing_reported(self):
        self.result.startTestRun()
        self.result.stopTestRun()
        self.assertEqual([], self.log)

    def test_add_success(self):
        self.result.startTest(self)
        self.result.addSuccess(self)
        self.result.stopTest(self)
        self.assertCalled(status='success')

    def test_add_success_details(self):
        self.result.startTest(self)
        details = {'foo': 'bar'}
        self.result.addSuccess(self, details=details)
        self.result.stopTest(self)
        self.assertCalled(status='success', details=details)

    def test_global_tags(self):
        self.result.tags(['foo'], [])
        self.result.startTest(self)
        self.result.addSuccess(self)
        self.result.stopTest(self)
        self.assertCalled(status='success', tags=set(['foo']))

    def test_local_tags(self):
        self.result.tags(['foo'], [])
        self.result.startTest(self)
        self.result.tags(['bar'], [])
        self.result.addSuccess(self)
        self.result.stopTest(self)
        self.assertCalled(status='success', tags=set(['foo', 'bar']))

    def test_add_error(self):
        self.result.startTest(self)
        try:
            1/0
        except ZeroDivisionError:
            error = sys.exc_info()
        self.result.addError(self, error)
        self.result.stopTest(self)
        self.assertCalled(
            status='error',
            details={'traceback': TracebackContent(error, self)})

    def test_add_error_details(self):
        self.result.startTest(self)
        details = {"foo": text_content("bar")}
        self.result.addError(self, details=details)
        self.result.stopTest(self)
        self.assertCalled(status='error', details=details)

    def test_add_failure(self):
        self.result.startTest(self)
        try:
            self.fail("intentional failure")
        except self.failureException:
            failure = sys.exc_info()
        self.result.addFailure(self, failure)
        self.result.stopTest(self)
        self.assertCalled(
            status='failure',
            details={'traceback': TracebackContent(failure, self)})

    def test_add_failure_details(self):
        self.result.startTest(self)
        details = {"foo": text_content("bar")}
        self.result.addFailure(self, details=details)
        self.result.stopTest(self)
        self.assertCalled(status='failure', details=details)

    def test_add_xfail(self):
        self.result.startTest(self)
        try:
            1/0
        except ZeroDivisionError:
            error = sys.exc_info()
        self.result.addExpectedFailure(self, error)
        self.result.stopTest(self)
        self.assertCalled(
            status='xfail',
            details={'traceback': TracebackContent(error, self)})

    def test_add_xfail_details(self):
        self.result.startTest(self)
        details = {"foo": text_content("bar")}
        self.result.addExpectedFailure(self, details=details)
        self.result.stopTest(self)
        self.assertCalled(status='xfail', details=details)

    def test_add_unexpected_success(self):
        self.result.startTest(self)
        details = {'foo': 'bar'}
        self.result.addUnexpectedSuccess(self, details=details)
        self.result.stopTest(self)
        self.assertCalled(status='success', details=details)

    def test_add_skip_reason(self):
        self.result.startTest(self)
        reason = self.getUniqueString()
        self.result.addSkip(self, reason)
        self.result.stopTest(self)
        self.assertCalled(
            status='skip', details={'reason': text_content(reason)})

    def test_add_skip_details(self):
        self.result.startTest(self)
        details = {'foo': 'bar'}
        self.result.addSkip(self, details=details)
        self.result.stopTest(self)
        self.assertCalled(status='skip', details=details)

    def test_twice(self):
        self.result.startTest(self)
        self.result.addSuccess(self, details={'foo': 'bar'})
        self.result.stopTest(self)
        self.result.startTest(self)
        self.result.addSuccess(self)
        self.result.stopTest(self)
        self.assertEqual(
            [{'test': self,
              'status': 'success',
              'start_time': 0,
              'stop_time': 1,
              'tags': set(),
              'details': {'foo': 'bar'}},
             {'test': self,
              'status': 'success',
              'start_time': 2,
              'stop_time': 3,
              'tags': set(),
              'details': None},
             ],
            self.log)


class TestTagger(TestCase):

    def test_tags_tests(self):
        result = ExtendedTestResult()
        tagger = Tagger(result, set(['foo']), set(['bar']))
        test1, test2 = self, make_test()
        tagger.startTest(test1)
        tagger.addSuccess(test1)
        tagger.stopTest(test1)
        tagger.startTest(test2)
        tagger.addSuccess(test2)
        tagger.stopTest(test2)
        self.assertEqual(
            [('startTest', test1),
             ('tags', set(['foo']), set(['bar'])),
             ('addSuccess', test1),
             ('stopTest', test1),
             ('startTest', test2),
             ('tags', set(['foo']), set(['bar'])),
             ('addSuccess', test2),
             ('stopTest', test2),
             ], result._events)


class TestTimestampingStreamResult(TestCase):

    def test_startTestRun(self):
        result = TimestampingStreamResult(LoggingStreamResult())
        result.startTestRun()
        self.assertEqual([('startTestRun',)], result.targets[0]._events)

    def test_stopTestRun(self):
        result = TimestampingStreamResult(LoggingStreamResult())
        result.stopTestRun()
        self.assertEqual([('stopTestRun',)], result.targets[0]._events)

    def test_status_no_timestamp(self):
        result = TimestampingStreamResult(LoggingStreamResult())
        result.status(test_id="A", test_status="B", test_tags="C",
            runnable="D", file_name="E", file_bytes=b"F", eof=True,
            mime_type="G", route_code="H")
        events = result.targets[0]._events
        self.assertThat(events, HasLength(1))
        self.assertThat(events[0], HasLength(11))
        self.assertEqual(
            ("status", "A", "B", "C", "D", "E", b"F", True, "G", "H"),
            events[0][:10])
        self.assertNotEqual(None, events[0][10])
        self.assertIsInstance(events[0][10], datetime.datetime)

    def test_status_timestamp(self):
        result = TimestampingStreamResult(LoggingStreamResult())
        result.status(timestamp="F")
        self.assertEqual("F", result.targets[0]._events[0][10])


def test_suite():
    from unittest import TestLoader
    return TestLoader().loadTestsFromName(__name__)