aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/python/traitlets/py3/tests/test_traitlets.py
blob: f9f623b4ae6b0e6cbe705639db8b82ea05dbc73c (plain) (blame)
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
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
"""Tests for traitlets.traitlets."""

# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
#
# Adapted from enthought.traits, Copyright (c) Enthought, Inc.,
# also under the terms of the Modified BSD License.
from __future__ import annotations

import pickle
import re
import typing as t
from unittest import TestCase

import pytest

from traitlets import (
    All,
    Any,
    BaseDescriptor,
    Bool,
    Bytes,
    Callable,
    CBytes,
    CFloat,
    CInt,
    CLong,
    Complex,
    CRegExp,
    CUnicode,
    Dict,
    DottedObjectName,
    Enum,
    Float,
    ForwardDeclaredInstance,
    ForwardDeclaredType,
    HasDescriptors,
    HasTraits,
    Instance,
    Int,
    Integer,
    List,
    Long,
    MetaHasTraits,
    ObjectName,
    Set,
    TCPAddress,
    This,
    TraitError,
    TraitType,
    Tuple,
    Type,
    Undefined,
    Unicode,
    Union,
    default,
    directional_link,
    link,
    observe,
    observe_compat,
    traitlets,
    validate,
)
from traitlets.utils import cast_unicode

from ._warnings import expected_warnings


def change_dict(*ordered_values):
    change_names = ("name", "old", "new", "owner", "type")
    return dict(zip(change_names, ordered_values))


# -----------------------------------------------------------------------------
# Helper classes for testing
# -----------------------------------------------------------------------------


class HasTraitsStub(HasTraits):
    def notify_change(self, change):
        self._notify_name = change["name"]
        self._notify_old = change["old"]
        self._notify_new = change["new"]
        self._notify_type = change["type"]


class CrossValidationStub(HasTraits):
    _cross_validation_lock = False


# -----------------------------------------------------------------------------
# Test classes
# -----------------------------------------------------------------------------


class TestTraitType(TestCase):
    def test_get_undefined(self):
        class A(HasTraits):
            a = TraitType

        a = A()
        assert a.a is Undefined  # type:ignore

    def test_set(self):
        class A(HasTraitsStub):
            a = TraitType

        a = A()
        a.a = 10  # type:ignore
        self.assertEqual(a.a, 10)
        self.assertEqual(a._notify_name, "a")
        self.assertEqual(a._notify_old, Undefined)
        self.assertEqual(a._notify_new, 10)

    def test_validate(self):
        class MyTT(TraitType[int, int]):
            def validate(self, inst, value):
                return -1

        class A(HasTraitsStub):
            tt = MyTT

        a = A()
        a.tt = 10  # type:ignore
        self.assertEqual(a.tt, -1)

        a = A(tt=11)
        self.assertEqual(a.tt, -1)

    def test_default_validate(self):
        class MyIntTT(TraitType[int, int]):
            def validate(self, obj, value):
                if isinstance(value, int):
                    return value
                self.error(obj, value)

        class A(HasTraits):
            tt = MyIntTT(10)

        a = A()
        self.assertEqual(a.tt, 10)

        # Defaults are validated when the HasTraits is instantiated
        class B(HasTraits):
            tt = MyIntTT("bad default")

        self.assertRaises(TraitError, getattr, B(), "tt")

    def test_info(self):
        class A(HasTraits):
            tt = TraitType

        a = A()
        self.assertEqual(A.tt.info(), "any value")  # type:ignore

    def test_error(self):
        class A(HasTraits):
            tt = TraitType[int, int]()

        a = A()
        self.assertRaises(TraitError, A.tt.error, a, 10)

    def test_deprecated_dynamic_initializer(self):
        class A(HasTraits):
            x = Int(10)

            def _x_default(self):
                return 11

        class B(A):
            x = Int(20)

        class C(A):
            def _x_default(self):
                return 21

        a = A()
        self.assertEqual(a._trait_values, {})
        self.assertEqual(a.x, 11)
        self.assertEqual(a._trait_values, {"x": 11})
        b = B()
        self.assertEqual(b.x, 20)
        self.assertEqual(b._trait_values, {"x": 20})
        c = C()
        self.assertEqual(c._trait_values, {})
        self.assertEqual(c.x, 21)
        self.assertEqual(c._trait_values, {"x": 21})
        # Ensure that the base class remains unmolested when the _default
        # initializer gets overridden in a subclass.
        a = A()
        c = C()
        self.assertEqual(a._trait_values, {})
        self.assertEqual(a.x, 11)
        self.assertEqual(a._trait_values, {"x": 11})

    def test_deprecated_method_warnings(self):
        with expected_warnings([]):

            class ShouldntWarn(HasTraits):
                x = Integer()

                @default("x")
                def _x_default(self):
                    return 10

                @validate("x")
                def _x_validate(self, proposal):
                    return proposal.value

                @observe("x")
                def _x_changed(self, change):
                    pass

            obj = ShouldntWarn()
            obj.x = 5

        assert obj.x == 5

        with expected_warnings(["@validate", "@observe"]) as w:

            class ShouldWarn(HasTraits):
                x = Integer()

                def _x_default(self):
                    return 10

                def _x_validate(self, value, _):
                    return value

                def _x_changed(self):
                    pass

            obj = ShouldWarn()  # type:ignore
            obj.x = 5

        assert obj.x == 5

    def test_dynamic_initializer(self):
        class A(HasTraits):
            x = Int(10)

            @default("x")
            def _default_x(self):
                return 11

        class B(A):
            x = Int(20)

        class C(A):
            @default("x")
            def _default_x(self):
                return 21

        a = A()
        self.assertEqual(a._trait_values, {})
        self.assertEqual(a.x, 11)
        self.assertEqual(a._trait_values, {"x": 11})
        b = B()
        self.assertEqual(b.x, 20)
        self.assertEqual(b._trait_values, {"x": 20})
        c = C()
        self.assertEqual(c._trait_values, {})
        self.assertEqual(c.x, 21)
        self.assertEqual(c._trait_values, {"x": 21})
        # Ensure that the base class remains unmolested when the _default
        # initializer gets overridden in a subclass.
        a = A()
        c = C()
        self.assertEqual(a._trait_values, {})
        self.assertEqual(a.x, 11)
        self.assertEqual(a._trait_values, {"x": 11})

    def test_tag_metadata(self):
        class MyIntTT(TraitType[int, int]):
            metadata = {"a": 1, "b": 2}

        a = MyIntTT(10).tag(b=3, c=4)
        self.assertEqual(a.metadata, {"a": 1, "b": 3, "c": 4})

    def test_metadata_localized_instance(self):
        class MyIntTT(TraitType[int, int]):
            metadata = {"a": 1, "b": 2}

        a = MyIntTT(10)
        b = MyIntTT(10)
        a.metadata["c"] = 3
        # make sure that changing a's metadata didn't change b's metadata
        self.assertNotIn("c", b.metadata)

    def test_union_metadata(self):
        class Foo(HasTraits):
            bar = (Int().tag(ta=1) | Dict().tag(ta=2, ti="b")).tag(ti="a")

        foo = Foo()
        # At this point, no value has been set for bar, so value-specific
        # is not set.
        self.assertEqual(foo.trait_metadata("bar", "ta"), None)
        self.assertEqual(foo.trait_metadata("bar", "ti"), "a")
        foo.bar = {}
        self.assertEqual(foo.trait_metadata("bar", "ta"), 2)
        self.assertEqual(foo.trait_metadata("bar", "ti"), "b")
        foo.bar = 1
        self.assertEqual(foo.trait_metadata("bar", "ta"), 1)
        self.assertEqual(foo.trait_metadata("bar", "ti"), "a")

    def test_union_default_value(self):
        class Foo(HasTraits):
            bar = Union([Dict(), Int()], default_value=1)

        foo = Foo()
        self.assertEqual(foo.bar, 1)

    def test_union_validation_priority(self):
        class Foo(HasTraits):
            bar = Union([CInt(), Unicode()])

        foo = Foo()
        foo.bar = "1"
        # validation in order of the TraitTypes given
        self.assertEqual(foo.bar, 1)

    def test_union_trait_default_value(self):
        class Foo(HasTraits):
            bar = Union([Dict(), Int()])

        self.assertEqual(Foo().bar, {})

    def test_deprecated_metadata_access(self):
        class MyIntTT(TraitType[int, int]):
            metadata = {"a": 1, "b": 2}

        a = MyIntTT(10)
        with expected_warnings(["use the instance .metadata dictionary directly"] * 2):
            a.set_metadata("key", "value")
            v = a.get_metadata("key")
        self.assertEqual(v, "value")
        with expected_warnings(["use the instance .help string directly"] * 2):
            a.set_metadata("help", "some help")
            v = a.get_metadata("help")
        self.assertEqual(v, "some help")

    def test_trait_types_deprecated(self):
        with expected_warnings(["Traits should be given as instances"]):

            class C(HasTraits):
                t = Int

    def test_trait_types_list_deprecated(self):
        with expected_warnings(["Traits should be given as instances"]):

            class C(HasTraits):
                t = List(Int)

    def test_trait_types_tuple_deprecated(self):
        with expected_warnings(["Traits should be given as instances"]):

            class C(HasTraits):
                t = Tuple(Int)

    def test_trait_types_dict_deprecated(self):
        with expected_warnings(["Traits should be given as instances"]):

            class C(HasTraits):
                t = Dict(Int)


class TestHasDescriptorsMeta(TestCase):
    def test_metaclass(self):
        self.assertEqual(type(HasTraits), MetaHasTraits)

        class A(HasTraits):
            a = Int()

        a = A()
        self.assertEqual(type(a.__class__), MetaHasTraits)
        self.assertEqual(a.a, 0)
        a.a = 10
        self.assertEqual(a.a, 10)

        class B(HasTraits):
            b = Int()

        b = B()
        self.assertEqual(b.b, 0)
        b.b = 10
        self.assertEqual(b.b, 10)

        class C(HasTraits):
            c = Int(30)

        c = C()
        self.assertEqual(c.c, 30)
        c.c = 10
        self.assertEqual(c.c, 10)

    def test_this_class(self):
        class A(HasTraits):
            t = This["A"]()
            tt = This["A"]()

        class B(A):
            tt = This["A"]()
            ttt = This["A"]()

        self.assertEqual(A.t.this_class, A)
        self.assertEqual(B.t.this_class, A)
        self.assertEqual(B.tt.this_class, B)
        self.assertEqual(B.ttt.this_class, B)


class TestHasDescriptors(TestCase):
    def test_setup_instance(self):
        class FooDescriptor(BaseDescriptor):
            def instance_init(self, inst):
                foo = inst.foo  # instance should have the attr

        class HasFooDescriptors(HasDescriptors):
            fd = FooDescriptor()

            def setup_instance(self, *args, **kwargs):
                self.foo = kwargs.get("foo", None)
                super().setup_instance(*args, **kwargs)

        hfd = HasFooDescriptors(foo="bar")


class TestHasTraitsNotify(TestCase):
    def setUp(self):
        self._notify1 = []
        self._notify2 = []

    def notify1(self, name, old, new):
        self._notify1.append((name, old, new))

    def notify2(self, name, old, new):
        self._notify2.append((name, old, new))

    def test_notify_all(self):
        class A(HasTraits):
            a = Int()
            b = Float()

        a = A()
        a.on_trait_change(self.notify1)
        a.a = 0
        self.assertEqual(len(self._notify1), 0)
        a.b = 0.0
        self.assertEqual(len(self._notify1), 0)
        a.a = 10
        self.assertTrue(("a", 0, 10) in self._notify1)
        a.b = 10.0
        self.assertTrue(("b", 0.0, 10.0) in self._notify1)
        self.assertRaises(TraitError, setattr, a, "a", "bad string")
        self.assertRaises(TraitError, setattr, a, "b", "bad string")
        self._notify1 = []
        a.on_trait_change(self.notify1, remove=True)
        a.a = 20
        a.b = 20.0
        self.assertEqual(len(self._notify1), 0)

    def test_notify_one(self):
        class A(HasTraits):
            a = Int()
            b = Float()

        a = A()
        a.on_trait_change(self.notify1, "a")
        a.a = 0
        self.assertEqual(len(self._notify1), 0)
        a.a = 10
        self.assertTrue(("a", 0, 10) in self._notify1)
        self.assertRaises(TraitError, setattr, a, "a", "bad string")

    def test_subclass(self):
        class A(HasTraits):
            a = Int()

        class B(A):
            b = Float()

        b = B()
        self.assertEqual(b.a, 0)
        self.assertEqual(b.b, 0.0)
        b.a = 100
        b.b = 100.0
        self.assertEqual(b.a, 100)
        self.assertEqual(b.b, 100.0)

    def test_notify_subclass(self):
        class A(HasTraits):
            a = Int()

        class B(A):
            b = Float()

        b = B()
        b.on_trait_change(self.notify1, "a")
        b.on_trait_change(self.notify2, "b")
        b.a = 0
        b.b = 0.0
        self.assertEqual(len(self._notify1), 0)
        self.assertEqual(len(self._notify2), 0)
        b.a = 10
        b.b = 10.0
        self.assertTrue(("a", 0, 10) in self._notify1)
        self.assertTrue(("b", 0.0, 10.0) in self._notify2)

    def test_static_notify(self):
        class A(HasTraits):
            a = Int()
            _notify1 = []

            def _a_changed(self, name, old, new):
                self._notify1.append((name, old, new))

        a = A()
        a.a = 0
        # This is broken!!!
        self.assertEqual(len(a._notify1), 0)
        a.a = 10
        self.assertTrue(("a", 0, 10) in a._notify1)

        class B(A):
            b = Float()
            _notify2 = []

            def _b_changed(self, name, old, new):
                self._notify2.append((name, old, new))

        b = B()
        b.a = 10
        b.b = 10.0
        self.assertTrue(("a", 0, 10) in b._notify1)
        self.assertTrue(("b", 0.0, 10.0) in b._notify2)

    def test_notify_args(self):
        def callback0():
            self.cb = ()

        def callback1(name):
            self.cb = (name,)  # type:ignore

        def callback2(name, new):
            self.cb = (name, new)  # type:ignore

        def callback3(name, old, new):
            self.cb = (name, old, new)  # type:ignore

        def callback4(name, old, new, obj):
            self.cb = (name, old, new, obj)  # type:ignore

        class A(HasTraits):
            a = Int()

        a = A()
        a.on_trait_change(callback0, "a")
        a.a = 10
        self.assertEqual(self.cb, ())
        a.on_trait_change(callback0, "a", remove=True)

        a.on_trait_change(callback1, "a")
        a.a = 100
        self.assertEqual(self.cb, ("a",))
        a.on_trait_change(callback1, "a", remove=True)

        a.on_trait_change(callback2, "a")
        a.a = 1000
        self.assertEqual(self.cb, ("a", 1000))
        a.on_trait_change(callback2, "a", remove=True)

        a.on_trait_change(callback3, "a")
        a.a = 10000
        self.assertEqual(self.cb, ("a", 1000, 10000))
        a.on_trait_change(callback3, "a", remove=True)

        a.on_trait_change(callback4, "a")
        a.a = 100000
        self.assertEqual(self.cb, ("a", 10000, 100000, a))
        self.assertEqual(len(a._trait_notifiers["a"]["change"]), 1)
        a.on_trait_change(callback4, "a", remove=True)

        self.assertEqual(len(a._trait_notifiers["a"]["change"]), 0)

    def test_notify_only_once(self):
        class A(HasTraits):
            listen_to = ["a"]

            a = Int(0)
            b = 0

            def __init__(self, **kwargs):
                super().__init__(**kwargs)
                self.on_trait_change(self.listener1, ["a"])

            def listener1(self, name, old, new):
                self.b += 1

        class B(A):
            c = 0
            d = 0

            def __init__(self, **kwargs):
                super().__init__(**kwargs)
                self.on_trait_change(self.listener2)

            def listener2(self, name, old, new):
                self.c += 1

            def _a_changed(self, name, old, new):
                self.d += 1

        b = B()
        b.a += 1
        self.assertEqual(b.b, b.c)
        self.assertEqual(b.b, b.d)
        b.a += 1
        self.assertEqual(b.b, b.c)
        self.assertEqual(b.b, b.d)


class TestObserveDecorator(TestCase):
    def setUp(self):
        self._notify1 = []
        self._notify2 = []

    def notify1(self, change):
        self._notify1.append(change)

    def notify2(self, change):
        self._notify2.append(change)

    def test_notify_all(self):
        class A(HasTraits):
            a = Int()
            b = Float()

        a = A()
        a.observe(self.notify1)
        a.a = 0
        self.assertEqual(len(self._notify1), 0)
        a.b = 0.0
        self.assertEqual(len(self._notify1), 0)
        a.a = 10
        change = change_dict("a", 0, 10, a, "change")
        self.assertTrue(change in self._notify1)
        a.b = 10.0
        change = change_dict("b", 0.0, 10.0, a, "change")
        self.assertTrue(change in self._notify1)
        self.assertRaises(TraitError, setattr, a, "a", "bad string")
        self.assertRaises(TraitError, setattr, a, "b", "bad string")
        self._notify1 = []
        a.unobserve(self.notify1)
        a.a = 20
        a.b = 20.0
        self.assertEqual(len(self._notify1), 0)

    def test_notify_one(self):
        class A(HasTraits):
            a = Int()
            b = Float()

        a = A()
        a.observe(self.notify1, "a")
        a.a = 0
        self.assertEqual(len(self._notify1), 0)
        a.a = 10
        change = change_dict("a", 0, 10, a, "change")
        self.assertTrue(change in self._notify1)
        self.assertRaises(TraitError, setattr, a, "a", "bad string")

    def test_subclass(self):
        class A(HasTraits):
            a = Int()

        class B(A):
            b = Float()

        b = B()
        self.assertEqual(b.a, 0)
        self.assertEqual(b.b, 0.0)
        b.a = 100
        b.b = 100.0
        self.assertEqual(b.a, 100)
        self.assertEqual(b.b, 100.0)

    def test_notify_subclass(self):
        class A(HasTraits):
            a = Int()

        class B(A):
            b = Float()

        b = B()
        b.observe(self.notify1, "a")
        b.observe(self.notify2, "b")
        b.a = 0
        b.b = 0.0
        self.assertEqual(len(self._notify1), 0)
        self.assertEqual(len(self._notify2), 0)
        b.a = 10
        b.b = 10.0
        change = change_dict("a", 0, 10, b, "change")
        self.assertTrue(change in self._notify1)
        change = change_dict("b", 0.0, 10.0, b, "change")
        self.assertTrue(change in self._notify2)

    def test_static_notify(self):
        class A(HasTraits):
            a = Int()
            b = Int()
            _notify1 = []
            _notify_any = []

            @observe("a")
            def _a_changed(self, change):
                self._notify1.append(change)

            @observe(All)
            def _any_changed(self, change):
                self._notify_any.append(change)

        a = A()
        a.a = 0
        self.assertEqual(len(a._notify1), 0)
        a.a = 10
        change = change_dict("a", 0, 10, a, "change")
        self.assertTrue(change in a._notify1)
        a.b = 1
        self.assertEqual(len(a._notify_any), 2)
        change = change_dict("b", 0, 1, a, "change")
        self.assertTrue(change in a._notify_any)

        class B(A):
            b = Float()  # type:ignore
            _notify2 = []

            @observe("b")
            def _b_changed(self, change):
                self._notify2.append(change)

        b = B()
        b.a = 10
        b.b = 10.0  # type:ignore
        change = change_dict("a", 0, 10, b, "change")
        self.assertTrue(change in b._notify1)
        change = change_dict("b", 0.0, 10.0, b, "change")
        self.assertTrue(change in b._notify2)

    def test_notify_args(self):
        def callback0():
            self.cb = ()

        def callback1(change):
            self.cb = change

        class A(HasTraits):
            a = Int()

        a = A()
        a.on_trait_change(callback0, "a")
        a.a = 10
        self.assertEqual(self.cb, ())
        a.unobserve(callback0, "a")

        a.observe(callback1, "a")
        a.a = 100
        change = change_dict("a", 10, 100, a, "change")
        self.assertEqual(self.cb, change)
        self.assertEqual(len(a._trait_notifiers["a"]["change"]), 1)
        a.unobserve(callback1, "a")

        self.assertEqual(len(a._trait_notifiers["a"]["change"]), 0)

    def test_notify_only_once(self):
        class A(HasTraits):
            listen_to = ["a"]

            a = Int(0)
            b = 0

            def __init__(self, **kwargs):
                super().__init__(**kwargs)
                self.observe(self.listener1, ["a"])

            def listener1(self, change):
                self.b += 1

        class B(A):
            c = 0
            d = 0

            def __init__(self, **kwargs):
                super().__init__(**kwargs)
                self.observe(self.listener2)

            def listener2(self, change):
                self.c += 1

            @observe("a")
            def _a_changed(self, change):
                self.d += 1

        b = B()
        b.a += 1
        self.assertEqual(b.b, b.c)
        self.assertEqual(b.b, b.d)
        b.a += 1
        self.assertEqual(b.b, b.c)
        self.assertEqual(b.b, b.d)


class TestHasTraits(TestCase):
    def test_trait_names(self):
        class A(HasTraits):
            i = Int()
            f = Float()

        a = A()
        self.assertEqual(sorted(a.trait_names()), ["f", "i"])
        self.assertEqual(sorted(A.class_trait_names()), ["f", "i"])
        self.assertTrue(a.has_trait("f"))
        self.assertFalse(a.has_trait("g"))

    def test_trait_has_value(self):
        class A(HasTraits):
            i = Int()
            f = Float()

        a = A()
        self.assertFalse(a.trait_has_value("f"))
        self.assertFalse(a.trait_has_value("g"))
        a.i = 1
        a.f
        self.assertTrue(a.trait_has_value("i"))
        self.assertTrue(a.trait_has_value("f"))

    def test_trait_metadata_deprecated(self):
        with expected_warnings([r"metadata should be set using the \.tag\(\) method"]):

            class A(HasTraits):
                i = Int(config_key="MY_VALUE")

        a = A()
        self.assertEqual(a.trait_metadata("i", "config_key"), "MY_VALUE")

    def test_trait_metadata(self):
        class A(HasTraits):
            i = Int().tag(config_key="MY_VALUE")

        a = A()
        self.assertEqual(a.trait_metadata("i", "config_key"), "MY_VALUE")

    def test_trait_metadata_default(self):
        class A(HasTraits):
            i = Int()

        a = A()
        self.assertEqual(a.trait_metadata("i", "config_key"), None)
        self.assertEqual(a.trait_metadata("i", "config_key", "default"), "default")

    def test_traits(self):
        class A(HasTraits):
            i = Int()
            f = Float()

        a = A()
        self.assertEqual(a.traits(), dict(i=A.i, f=A.f))
        self.assertEqual(A.class_traits(), dict(i=A.i, f=A.f))

    def test_traits_metadata(self):
        class A(HasTraits):
            i = Int().tag(config_key="VALUE1", other_thing="VALUE2")
            f = Float().tag(config_key="VALUE3", other_thing="VALUE2")
            j = Int(0)

        a = A()
        self.assertEqual(a.traits(), dict(i=A.i, f=A.f, j=A.j))
        traits = a.traits(config_key="VALUE1", other_thing="VALUE2")
        self.assertEqual(traits, dict(i=A.i))

        # This passes, but it shouldn't because I am replicating a bug in
        # traits.
        traits = a.traits(config_key=lambda v: True)
        self.assertEqual(traits, dict(i=A.i, f=A.f, j=A.j))

    def test_traits_metadata_deprecated(self):
        with expected_warnings([r"metadata should be set using the \.tag\(\) method"] * 2):

            class A(HasTraits):
                i = Int(config_key="VALUE1", other_thing="VALUE2")
                f = Float(config_key="VALUE3", other_thing="VALUE2")
                j = Int(0)

        a = A()
        self.assertEqual(a.traits(), dict(i=A.i, f=A.f, j=A.j))
        traits = a.traits(config_key="VALUE1", other_thing="VALUE2")
        self.assertEqual(traits, dict(i=A.i))

        # This passes, but it shouldn't because I am replicating a bug in
        # traits.
        traits = a.traits(config_key=lambda v: True)
        self.assertEqual(traits, dict(i=A.i, f=A.f, j=A.j))

    def test_init(self):
        class A(HasTraits):
            i = Int()
            x = Float()

        a = A(i=1, x=10.0)
        self.assertEqual(a.i, 1)
        self.assertEqual(a.x, 10.0)

    def test_positional_args(self):
        class A(HasTraits):
            i = Int(0)

            def __init__(self, i):
                super().__init__()
                self.i = i

        a = A(5)
        self.assertEqual(a.i, 5)
        # should raise TypeError if no positional arg given
        self.assertRaises(TypeError, A)


# -----------------------------------------------------------------------------
# Tests for specific trait types
# -----------------------------------------------------------------------------


class TestType(TestCase):
    def test_default(self):
        class B:
            pass

        class A(HasTraits):
            klass = Type(allow_none=True)

        a = A()
        self.assertEqual(a.klass, object)

        a.klass = B
        self.assertEqual(a.klass, B)
        self.assertRaises(TraitError, setattr, a, "klass", 10)

    def test_default_options(self):
        class B:
            pass

        class C(B):
            pass

        class A(HasTraits):
            # Different possible combinations of options for default_value
            # and klass. default_value=None is only valid with allow_none=True.
            k1 = Type()
            k2 = Type(None, allow_none=True)
            k3 = Type(B)
            k4 = Type(klass=B)
            k5 = Type(default_value=None, klass=B, allow_none=True)
            k6 = Type(default_value=C, klass=B)

        self.assertIs(A.k1.default_value, object)
        self.assertIs(A.k1.klass, object)
        self.assertIs(A.k2.default_value, None)
        self.assertIs(A.k2.klass, object)
        self.assertIs(A.k3.default_value, B)
        self.assertIs(A.k3.klass, B)
        self.assertIs(A.k4.default_value, B)
        self.assertIs(A.k4.klass, B)
        self.assertIs(A.k5.default_value, None)
        self.assertIs(A.k5.klass, B)
        self.assertIs(A.k6.default_value, C)
        self.assertIs(A.k6.klass, B)

        a = A()
        self.assertIs(a.k1, object)
        self.assertIs(a.k2, None)
        self.assertIs(a.k3, B)
        self.assertIs(a.k4, B)
        self.assertIs(a.k5, None)
        self.assertIs(a.k6, C)

    def test_value(self):
        class B:
            pass

        class C:
            pass

        class A(HasTraits):
            klass = Type(B)

        a = A()
        self.assertEqual(a.klass, B)
        self.assertRaises(TraitError, setattr, a, "klass", C)
        self.assertRaises(TraitError, setattr, a, "klass", object)
        a.klass = B

    def test_allow_none(self):
        class B:
            pass

        class C(B):
            pass

        class A(HasTraits):
            klass = Type(B)

        a = A()
        self.assertEqual(a.klass, B)
        self.assertRaises(TraitError, setattr, a, "klass", None)
        a.klass = C
        self.assertEqual(a.klass, C)

    def test_validate_klass(self):
        class A(HasTraits):
            klass = Type("no strings allowed")

        self.assertRaises(ImportError, A)

        class A(HasTraits):  # type:ignore
            klass = Type("rub.adub.Duck")

        self.assertRaises(ImportError, A)

    def test_validate_default(self):
        class B:
            pass

        class A(HasTraits):
            klass = Type("bad default", B)

        self.assertRaises(ImportError, A)

        class C(HasTraits):
            klass = Type(None, B)

        self.assertRaises(TraitError, getattr, C(), "klass")

    def test_str_klass(self):
        class A(HasTraits):
            klass = Type("traitlets.config.Config")

        from traitlets.config import Config

        a = A()
        a.klass = Config
        self.assertEqual(a.klass, Config)

        self.assertRaises(TraitError, setattr, a, "klass", 10)

    def test_set_str_klass(self):
        class A(HasTraits):
            klass = Type()

        a = A(klass="traitlets.config.Config")
        from traitlets.config import Config

        self.assertEqual(a.klass, Config)


class TestInstance(TestCase):
    def test_basic(self):
        class Foo:
            pass

        class Bar(Foo):
            pass

        class Bah:
            pass

        class A(HasTraits):
            inst = Instance(Foo, allow_none=True)

        a = A()
        self.assertTrue(a.inst is None)
        a.inst = Foo()
        self.assertTrue(isinstance(a.inst, Foo))
        a.inst = Bar()
        self.assertTrue(isinstance(a.inst, Foo))
        self.assertRaises(TraitError, setattr, a, "inst", Foo)
        self.assertRaises(TraitError, setattr, a, "inst", Bar)
        self.assertRaises(TraitError, setattr, a, "inst", Bah())

    def test_default_klass(self):
        class Foo:
            pass

        class Bar(Foo):
            pass

        class Bah:
            pass

        class FooInstance(Instance[Foo]):
            klass = Foo

        class A(HasTraits):
            inst = FooInstance(allow_none=True)

        a = A()
        self.assertTrue(a.inst is None)
        a.inst = Foo()
        self.assertTrue(isinstance(a.inst, Foo))
        a.inst = Bar()
        self.assertTrue(isinstance(a.inst, Foo))
        self.assertRaises(TraitError, setattr, a, "inst", Foo)
        self.assertRaises(TraitError, setattr, a, "inst", Bar)
        self.assertRaises(TraitError, setattr, a, "inst", Bah())

    def test_unique_default_value(self):
        class Foo:
            pass

        class A(HasTraits):
            inst = Instance(Foo, (), {})

        a = A()
        b = A()
        self.assertTrue(a.inst is not b.inst)

    def test_args_kw(self):
        class Foo:
            def __init__(self, c):
                self.c = c

        class Bar:
            pass

        class Bah:
            def __init__(self, c, d):
                self.c = c
                self.d = d

        class A(HasTraits):
            inst = Instance(Foo, (10,))

        a = A()
        self.assertEqual(a.inst.c, 10)

        class B(HasTraits):
            inst = Instance(Bah, args=(10,), kw=dict(d=20))

        b = B()
        self.assertEqual(b.inst.c, 10)
        self.assertEqual(b.inst.d, 20)

        class C(HasTraits):
            inst = Instance(Foo, allow_none=True)

        c = C()
        self.assertTrue(c.inst is None)

    def test_bad_default(self):
        class Foo:
            pass

        class A(HasTraits):
            inst = Instance(Foo)

        a = A()
        with self.assertRaises(TraitError):
            a.inst

    def test_instance(self):
        class Foo:
            pass

        def inner():
            class A(HasTraits):
                inst = Instance(Foo())  # type:ignore

        self.assertRaises(TraitError, inner)


class TestThis(TestCase):
    def test_this_class(self):
        class Foo(HasTraits):
            this = This["Foo"]()

        f = Foo()
        self.assertEqual(f.this, None)
        g = Foo()
        f.this = g
        self.assertEqual(f.this, g)
        self.assertRaises(TraitError, setattr, f, "this", 10)

    def test_this_inst(self):
        class Foo(HasTraits):
            this = This["Foo"]()

        f = Foo()
        f.this = Foo()
        self.assertTrue(isinstance(f.this, Foo))

    def test_subclass(self):
        class Foo(HasTraits):
            t = This["Foo"]()

        class Bar(Foo):
            pass

        f = Foo()
        b = Bar()
        f.t = b
        b.t = f
        self.assertEqual(f.t, b)
        self.assertEqual(b.t, f)

    def test_subclass_override(self):
        class Foo(HasTraits):
            t = This["Foo"]()

        class Bar(Foo):
            t = This()

        f = Foo()
        b = Bar()
        f.t = b
        self.assertEqual(f.t, b)
        self.assertRaises(TraitError, setattr, b, "t", f)

    def test_this_in_container(self):
        class Tree(HasTraits):
            value = Unicode()
            leaves = List(This())

        tree = Tree(value="foo", leaves=[Tree(value="bar"), Tree(value="buzz")])

        with self.assertRaises(TraitError):
            tree.leaves = [1, 2]


class TraitTestBase(TestCase):
    """A best testing class for basic trait types."""

    def assign(self, value):
        self.obj.value = value  # type:ignore

    def coerce(self, value):
        return value

    def test_good_values(self):
        if hasattr(self, "_good_values"):
            for value in self._good_values:
                self.assign(value)
                self.assertEqual(self.obj.value, self.coerce(value))  # type:ignore

    def test_bad_values(self):
        if hasattr(self, "_bad_values"):
            for value in self._bad_values:
                try:
                    self.assertRaises(TraitError, self.assign, value)
                except AssertionError:
                    assert False, value  # noqa: PT015

    def test_default_value(self):
        if hasattr(self, "_default_value"):
            self.assertEqual(self._default_value, self.obj.value)  # type:ignore

    def test_allow_none(self):
        if (
            hasattr(self, "_bad_values")
            and hasattr(self, "_good_values")
            and None in self._bad_values
        ):
            trait = self.obj.traits()["value"]  # type:ignore
            try:
                trait.allow_none = True
                self._bad_values.remove(None)
                # skip coerce. Allow None casts None to None.
                self.assign(None)
                self.assertEqual(self.obj.value, None)  # type:ignore
                self.test_good_values()
                self.test_bad_values()
            finally:
                # tear down
                trait.allow_none = False
                self._bad_values.append(None)

    def tearDown(self):
        # restore default value after tests, if set
        if hasattr(self, "_default_value"):
            self.obj.value = self._default_value  # type:ignore


class AnyTrait(HasTraits):
    value = Any()


class AnyTraitTest(TraitTestBase):
    obj = AnyTrait()

    _default_value = None
    _good_values = [10.0, "ten", [10], {"ten": 10}, (10,), None, 1j]
    _bad_values: t.Any = []


class UnionTrait(HasTraits):
    value = Union([Type(), Bool()])


class UnionTraitTest(TraitTestBase):
    obj = UnionTrait(value="traitlets.config.Config")
    _good_values = [int, float, True]
    _bad_values = [[], (0,), 1j]


class CallableTrait(HasTraits):
    value = Callable()


class CallableTraitTest(TraitTestBase):
    obj = CallableTrait(value=lambda x: type(x))
    _good_values = [int, sorted, lambda x: print(x)]
    _bad_values = [[], 1, ""]


class OrTrait(HasTraits):
    value = Bool() | Unicode()


class OrTraitTest(TraitTestBase):
    obj = OrTrait()
    _good_values = [True, False, "ten"]
    _bad_values = [[], (0,), 1j]


class IntTrait(HasTraits):
    value = Int(99, min=-100)


class TestInt(TraitTestBase):
    obj = IntTrait()
    _default_value = 99
    _good_values = [10, -10]
    _bad_values = [
        "ten",
        [10],
        {"ten": 10},
        (10,),
        None,
        1j,
        10.1,
        -10.1,
        "10L",
        "-10L",
        "10.1",
        "-10.1",
        "10",
        "-10",
        -200,
    ]


class CIntTrait(HasTraits):
    value = CInt("5")


class TestCInt(TraitTestBase):
    obj = CIntTrait()

    _default_value = 5
    _good_values = ["10", "-10", 10, 10.0, -10.0, 10.1]
    _bad_values = ["ten", [10], {"ten": 10}, (10,), None, 1j, "10.1"]

    def coerce(self, n):
        return int(n)


class MinBoundCIntTrait(HasTraits):
    value = CInt("5", min=3)


class TestMinBoundCInt(TestCInt):
    obj = MinBoundCIntTrait()  # type:ignore

    _default_value = 5
    _good_values = [3, 3.0, "3"]
    _bad_values = [2.6, 2, -3, -3.0]


class LongTrait(HasTraits):
    value = Long(99)


class TestLong(TraitTestBase):
    obj = LongTrait()

    _default_value = 99
    _good_values = [10, -10]
    _bad_values = [
        "ten",
        [10],
        {"ten": 10},
        (10,),
        None,
        1j,
        10.1,
        -10.1,
        "10",
        "-10",
        "10L",
        "-10L",
        "10.1",
        "-10.1",
    ]


class MinBoundLongTrait(HasTraits):
    value = Long(99, min=5)


class TestMinBoundLong(TraitTestBase):
    obj = MinBoundLongTrait()

    _default_value = 99
    _good_values = [5, 10]
    _bad_values = [4, -10]


class MaxBoundLongTrait(HasTraits):
    value = Long(5, max=10)


class TestMaxBoundLong(TraitTestBase):
    obj = MaxBoundLongTrait()

    _default_value = 5
    _good_values = [10, -2]
    _bad_values = [11, 20]


class CLongTrait(HasTraits):
    value = CLong("5")


class TestCLong(TraitTestBase):
    obj = CLongTrait()

    _default_value = 5
    _good_values = ["10", "-10", 10, 10.0, -10.0, 10.1]
    _bad_values = ["ten", [10], {"ten": 10}, (10,), None, 1j, "10.1"]

    def coerce(self, n):
        return int(n)


class MaxBoundCLongTrait(HasTraits):
    value = CLong("5", max=10)


class TestMaxBoundCLong(TestCLong):
    obj = MaxBoundCLongTrait()  # type:ignore

    _default_value = 5
    _good_values = [10, "10", 10.3]
    _bad_values = [11.0, "11"]


class IntegerTrait(HasTraits):
    value = Integer(1)


class TestInteger(TestLong):
    obj = IntegerTrait()  # type:ignore
    _default_value = 1

    def coerce(self, n):
        return int(n)


class MinBoundIntegerTrait(HasTraits):
    value = Integer(5, min=3)


class TestMinBoundInteger(TraitTestBase):
    obj = MinBoundIntegerTrait()

    _default_value = 5
    _good_values = 3, 20
    _bad_values = [2, -10]


class MaxBoundIntegerTrait(HasTraits):
    value = Integer(1, max=3)


class TestMaxBoundInteger(TraitTestBase):
    obj = MaxBoundIntegerTrait()

    _default_value = 1
    _good_values = 3, -2
    _bad_values = [4, 10]


class FloatTrait(HasTraits):
    value = Float(99.0, max=200.0)


class TestFloat(TraitTestBase):
    obj = FloatTrait()

    _default_value = 99.0
    _good_values = [10, -10, 10.1, -10.1]
    _bad_values = [
        "ten",
        [10],
        {"ten": 10},
        (10,),
        None,
        1j,
        "10",
        "-10",
        "10L",
        "-10L",
        "10.1",
        "-10.1",
        201.0,
    ]


class CFloatTrait(HasTraits):
    value = CFloat("99.0", max=200.0)


class TestCFloat(TraitTestBase):
    obj = CFloatTrait()

    _default_value = 99.0
    _good_values = [10, 10.0, 10.5, "10.0", "10", "-10"]
    _bad_values = ["ten", [10], {"ten": 10}, (10,), None, 1j, 200.1, "200.1"]

    def coerce(self, v):
        return float(v)


class ComplexTrait(HasTraits):
    value = Complex(99.0 - 99.0j)


class TestComplex(TraitTestBase):
    obj = ComplexTrait()

    _default_value = 99.0 - 99.0j
    _good_values = [
        10,
        -10,
        10.1,
        -10.1,
        10j,
        10 + 10j,
        10 - 10j,
        10.1j,
        10.1 + 10.1j,
        10.1 - 10.1j,
    ]
    _bad_values = ["10L", "-10L", "ten", [10], {"ten": 10}, (10,), None]


class BytesTrait(HasTraits):
    value = Bytes(b"string")


class TestBytes(TraitTestBase):
    obj = BytesTrait()

    _default_value = b"string"
    _good_values = [b"10", b"-10", b"10L", b"-10L", b"10.1", b"-10.1", b"string"]
    _bad_values = [10, -10, 10.1, -10.1, 1j, [10], ["ten"], {"ten": 10}, (10,), None, "string"]


class UnicodeTrait(HasTraits):
    value = Unicode("unicode")


class TestUnicode(TraitTestBase):
    obj = UnicodeTrait()

    _default_value = "unicode"
    _good_values = ["10", "-10", "10L", "-10L", "10.1", "-10.1", "", "string", "€", b"bytestring"]
    _bad_values = [10, -10, 10.1, -10.1, 1j, [10], ["ten"], {"ten": 10}, (10,), None]

    def coerce(self, v):
        return cast_unicode(v)


class ObjectNameTrait(HasTraits):
    value = ObjectName("abc")


class TestObjectName(TraitTestBase):
    obj = ObjectNameTrait()

    _default_value = "abc"
    _good_values = ["a", "gh", "g9", "g_", "_G", "a345_"]
    _bad_values = [
        1,
        "",
        "€",
        "9g",
        "!",
        "#abc",
        "aj@",
        "a.b",
        "a()",
        "a[0]",
        None,
        object(),
        object,
    ]
    _good_values.append("þ")  # þ=1 is valid in Python 3 (PEP 3131).


class DottedObjectNameTrait(HasTraits):
    value = DottedObjectName("a.b")


class TestDottedObjectName(TraitTestBase):
    obj = DottedObjectNameTrait()

    _default_value = "a.b"
    _good_values = ["A", "y.t", "y765.__repr__", "os.path.join"]
    _bad_values = [1, "abc.€", "_.@", ".", ".abc", "abc.", ".abc.", None]

    _good_values.append("t.þ")


class TCPAddressTrait(HasTraits):
    value = TCPAddress()


class TestTCPAddress(TraitTestBase):
    obj = TCPAddressTrait()

    _default_value = ("127.0.0.1", 0)
    _good_values = [("localhost", 0), ("192.168.0.1", 1000), ("www.google.com", 80)]
    _bad_values = [(0, 0), ("localhost", 10.0), ("localhost", -1), None]


class ListTrait(HasTraits):
    value = List(Int())


class TestList(TraitTestBase):
    obj = ListTrait()

    _default_value: t.List[t.Any] = []
    _good_values = [[], [1], list(range(10)), (1, 2)]
    _bad_values = [10, [1, "a"], "a"]

    def coerce(self, value):
        if value is not None:
            value = list(value)
        return value


class SetTrait(HasTraits):
    value = Set(Unicode())


class TestSet(TraitTestBase):
    obj = SetTrait()

    _default_value: t.Set[str] = set()
    _good_values = [{"a", "b"}, "ab"]
    _bad_values = [1]

    def coerce(self, value):
        if isinstance(value, str):
            # compatibility handling: convert string to set containing string
            value = {value}
        return value


class Foo:
    pass


class NoneInstanceListTrait(HasTraits):
    value = List(Instance(Foo))


class TestNoneInstanceList(TraitTestBase):
    obj = NoneInstanceListTrait()

    _default_value: t.List[t.Any] = []
    _good_values = [[Foo(), Foo()], []]
    _bad_values = [[None], [Foo(), None]]


class InstanceListTrait(HasTraits):
    value = List(Instance(__name__ + ".Foo"))


class TestInstanceList(TraitTestBase):
    obj = InstanceListTrait()

    def test_klass(self):
        """Test that the instance klass is properly assigned."""
        self.assertIs(self.obj.traits()["value"]._trait.klass, Foo)

    _default_value: t.List[t.Any] = []
    _good_values = [[Foo(), Foo()], []]
    _bad_values = [
        [
            "1",
            2,
        ],
        "1",
        [Foo],
        None,
    ]


class UnionListTrait(HasTraits):
    value = List(Int() | Bool())


class TestUnionListTrait(TraitTestBase):
    obj = UnionListTrait()

    _default_value: t.List[t.Any] = []
    _good_values = [[True, 1], [False, True]]
    _bad_values = [[1, "True"], False]


class LenListTrait(HasTraits):
    value = List(Int(), [0], minlen=1, maxlen=2)


class TestLenList(TraitTestBase):
    obj = LenListTrait()

    _default_value = [0]
    _good_values = [[1], [1, 2], (1, 2)]
    _bad_values = [10, [1, "a"], "a", [], list(range(3))]

    def coerce(self, value):
        if value is not None:
            value = list(value)
        return value


class TupleTrait(HasTraits):
    value = Tuple(Int(allow_none=True), default_value=(1,))


class TestTupleTrait(TraitTestBase):
    obj = TupleTrait()

    _default_value = (1,)
    _good_values = [(1,), (0,), [1]]
    _bad_values = [10, (1, 2), ("a"), (), None]

    def coerce(self, value):
        if value is not None:
            value = tuple(value)
        return value

    def test_invalid_args(self):
        self.assertRaises(TypeError, Tuple, 5)
        self.assertRaises(TypeError, Tuple, default_value="hello")
        t = Tuple(Int(), CBytes(), default_value=(1, 5))


class LooseTupleTrait(HasTraits):
    value = Tuple((1, 2, 3))


class TestLooseTupleTrait(TraitTestBase):
    obj = LooseTupleTrait()

    _default_value = (1, 2, 3)
    _good_values = [(1,), [1], (0,), tuple(range(5)), tuple("hello"), ("a", 5), ()]
    _bad_values = [10, "hello", {}, None]

    def coerce(self, value):
        if value is not None:
            value = tuple(value)
        return value

    def test_invalid_args(self):
        self.assertRaises(TypeError, Tuple, 5)
        self.assertRaises(TypeError, Tuple, default_value="hello")
        t = Tuple(Int(), CBytes(), default_value=(1, 5))


class MultiTupleTrait(HasTraits):
    value = Tuple(Int(), Bytes(), default_value=[99, b"bottles"])


class TestMultiTuple(TraitTestBase):
    obj = MultiTupleTrait()

    _default_value = (99, b"bottles")
    _good_values = [(1, b"a"), (2, b"b")]
    _bad_values = ((), 10, b"a", (1, b"a", 3), (b"a", 1), (1, "a"))


@pytest.mark.parametrize(
    "Trait",
    (  # noqa: PT007
        List,
        Tuple,
        Set,
        Dict,
        Integer,
        Unicode,
    ),
)
def test_allow_none_default_value(Trait):
    class C(HasTraits):
        t = Trait(default_value=None, allow_none=True)

    # test default value
    c = C()
    assert c.t is None

    # and in constructor
    c = C(t=None)
    assert c.t is None


@pytest.mark.parametrize(
    "Trait, default_value",
    ((List, []), (Tuple, ()), (Set, set()), (Dict, {}), (Integer, 0), (Unicode, "")),  # noqa: PT007
)
def test_default_value(Trait, default_value):
    class C(HasTraits):
        t = Trait()

    # test default value
    c = C()
    assert type(c.t) is type(default_value)
    assert c.t == default_value


@pytest.mark.parametrize(
    "Trait, default_value",
    ((List, []), (Tuple, ()), (Set, set())),  # noqa: PT007
)
def test_subclass_default_value(Trait, default_value):
    """Test deprecated default_value=None behavior for Container subclass traits"""

    class SubclassTrait(Trait):  # type:ignore
        def __init__(self, default_value=None):
            super().__init__(default_value=default_value)

    class C(HasTraits):
        t = SubclassTrait()

    # test default value
    c = C()
    assert type(c.t) is type(default_value)
    assert c.t == default_value


class CRegExpTrait(HasTraits):
    value = CRegExp(r"")


class TestCRegExp(TraitTestBase):
    def coerce(self, value):
        return re.compile(value)

    obj = CRegExpTrait()

    _default_value = re.compile(r"")
    _good_values = [r"\d+", re.compile(r"\d+")]
    _bad_values = ["(", None, ()]


class DictTrait(HasTraits):
    value = Dict()


def test_dict_assignment():
    d: t.Dict[str, int] = {}
    c = DictTrait()
    c.value = d
    d["a"] = 5
    assert d == c.value
    assert c.value is d


class UniformlyValueValidatedDictTrait(HasTraits):
    value = Dict(value_trait=Unicode(), default_value={"foo": "1"})


class TestInstanceUniformlyValueValidatedDict(TraitTestBase):
    obj = UniformlyValueValidatedDictTrait()

    _default_value = {"foo": "1"}
    _good_values = [{"foo": "0", "bar": "1"}]
    _bad_values = [{"foo": 0, "bar": "1"}]


class NonuniformlyValueValidatedDictTrait(HasTraits):
    value = Dict(per_key_traits={"foo": Int()}, default_value={"foo": 1})


class TestInstanceNonuniformlyValueValidatedDict(TraitTestBase):
    obj = NonuniformlyValueValidatedDictTrait()

    _default_value = {"foo": 1}
    _good_values = [{"foo": 0, "bar": "1"}, {"foo": 0, "bar": 1}]
    _bad_values = [{"foo": "0", "bar": "1"}]


class KeyValidatedDictTrait(HasTraits):
    value = Dict(key_trait=Unicode(), default_value={"foo": "1"})


class TestInstanceKeyValidatedDict(TraitTestBase):
    obj = KeyValidatedDictTrait()

    _default_value = {"foo": "1"}
    _good_values = [{"foo": "0", "bar": "1"}]
    _bad_values = [{"foo": "0", 0: "1"}]


class FullyValidatedDictTrait(HasTraits):
    value = Dict(
        value_trait=Unicode(),
        key_trait=Unicode(),
        per_key_traits={"foo": Int()},
        default_value={"foo": 1},
    )


class TestInstanceFullyValidatedDict(TraitTestBase):
    obj = FullyValidatedDictTrait()

    _default_value = {"foo": 1}
    _good_values = [{"foo": 0, "bar": "1"}, {"foo": 1, "bar": "2"}]
    _bad_values = [{"foo": 0, "bar": 1}, {"foo": "0", "bar": "1"}, {"foo": 0, 0: "1"}]


def test_dict_default_value():
    """Check that the `{}` default value of the Dict traitlet constructor is
    actually copied."""

    class Foo(HasTraits):
        d1 = Dict()
        d2 = Dict()

    foo = Foo()
    assert foo.d1 == {}
    assert foo.d2 == {}
    assert foo.d1 is not foo.d2


class TestValidationHook(TestCase):
    def test_parity_trait(self):
        """Verify that the early validation hook is effective"""

        class Parity(HasTraits):
            value = Int(0)
            parity = Enum(["odd", "even"], default_value="even")

            @validate("value")
            def _value_validate(self, proposal):
                value = proposal["value"]
                if self.parity == "even" and value % 2:
                    raise TraitError("Expected an even number")
                if self.parity == "odd" and (value % 2 == 0):
                    raise TraitError("Expected an odd number")
                return value

        u = Parity()
        u.parity = "odd"
        u.value = 1  # OK
        with self.assertRaises(TraitError):
            u.value = 2  # Trait Error

        u.parity = "even"
        u.value = 2  # OK

    def test_multiple_validate(self):
        """Verify that we can register the same validator to multiple names"""

        class OddEven(HasTraits):
            odd = Int(1)
            even = Int(0)

            @validate("odd", "even")
            def check_valid(self, proposal):
                if proposal["trait"].name == "odd" and not proposal["value"] % 2:
                    raise TraitError("odd should be odd")
                if proposal["trait"].name == "even" and proposal["value"] % 2:
                    raise TraitError("even should be even")

        u = OddEven()
        u.odd = 3  # OK
        with self.assertRaises(TraitError):
            u.odd = 2  # Trait Error

        u.even = 2  # OK
        with self.assertRaises(TraitError):
            u.even = 3  # Trait Error

    def test_validate_used(self):
        """Verify that the validate value is being used"""

        class FixedValue(HasTraits):
            value = Int(0)

            @validate("value")
            def _value_validate(self, proposal):
                return -1

        u = FixedValue(value=2)
        assert u.value == -1

        u = FixedValue()
        u.value = 3
        assert u.value == -1


class TestLink(TestCase):
    def test_connect_same(self):
        """Verify two traitlets of the same type can be linked together using link."""

        # Create two simple classes with Int traitlets.
        class A(HasTraits):
            value = Int()

        a = A(value=9)
        b = A(value=8)

        # Connect the two classes.
        c = link((a, "value"), (b, "value"))

        # Make sure the values are the same at the point of linking.
        self.assertEqual(a.value, b.value)

        # Change one of the values to make sure they stay in sync.
        a.value = 5
        self.assertEqual(a.value, b.value)
        b.value = 6
        self.assertEqual(a.value, b.value)

    def test_link_different(self):
        """Verify two traitlets of different types can be linked together using link."""

        # Create two simple classes with Int traitlets.
        class A(HasTraits):
            value = Int()

        class B(HasTraits):
            count = Int()

        a = A(value=9)
        b = B(count=8)

        # Connect the two classes.
        c = link((a, "value"), (b, "count"))

        # Make sure the values are the same at the point of linking.
        self.assertEqual(a.value, b.count)

        # Change one of the values to make sure they stay in sync.
        a.value = 5
        self.assertEqual(a.value, b.count)
        b.count = 4
        self.assertEqual(a.value, b.count)

    def test_unlink_link(self):
        """Verify two linked traitlets can be unlinked and relinked."""

        # Create two simple classes with Int traitlets.
        class A(HasTraits):
            value = Int()

        a = A(value=9)
        b = A(value=8)

        # Connect the two classes.
        c = link((a, "value"), (b, "value"))
        a.value = 4
        c.unlink()

        # Change one of the values to make sure they don't stay in sync.
        a.value = 5
        self.assertNotEqual(a.value, b.value)
        c.link()
        self.assertEqual(a.value, b.value)
        a.value += 1
        self.assertEqual(a.value, b.value)

    def test_callbacks(self):
        """Verify two linked traitlets have their callbacks called once."""

        # Create two simple classes with Int traitlets.
        class A(HasTraits):
            value = Int()

        class B(HasTraits):
            count = Int()

        a = A(value=9)
        b = B(count=8)

        # Register callbacks that count.
        callback_count = []

        def a_callback(name, old, new):
            callback_count.append("a")

        a.on_trait_change(a_callback, "value")

        def b_callback(name, old, new):
            callback_count.append("b")

        b.on_trait_change(b_callback, "count")

        # Connect the two classes.
        c = link((a, "value"), (b, "count"))

        # Make sure b's count was set to a's value once.
        self.assertEqual("".join(callback_count), "b")
        del callback_count[:]

        # Make sure a's value was set to b's count once.
        b.count = 5
        self.assertEqual("".join(callback_count), "ba")
        del callback_count[:]

        # Make sure b's count was set to a's value once.
        a.value = 4
        self.assertEqual("".join(callback_count), "ab")
        del callback_count[:]

    def test_tranform(self):
        """Test transform link."""

        # Create two simple classes with Int traitlets.
        class A(HasTraits):
            value = Int()

        a = A(value=9)
        b = A(value=8)

        # Connect the two classes.
        c = link((a, "value"), (b, "value"), transform=(lambda x: 2 * x, lambda x: int(x / 2.0)))

        # Make sure the values are correct at the point of linking.
        self.assertEqual(b.value, 2 * a.value)

        # Change one the value of the source and check that it modifies the target.
        a.value = 5
        self.assertEqual(b.value, 10)
        # Change one the value of the target and check that it modifies the
        # source.
        b.value = 6
        self.assertEqual(a.value, 3)

    def test_link_broken_at_source(self):
        class MyClass(HasTraits):
            i = Int()
            j = Int()

            @observe("j")
            def another_update(self, change):
                self.i = change.new * 2

        mc = MyClass()
        l = link((mc, "i"), (mc, "j"))  # noqa: E741
        self.assertRaises(TraitError, setattr, mc, "i", 2)

    def test_link_broken_at_target(self):
        class MyClass(HasTraits):
            i = Int()
            j = Int()

            @observe("i")
            def another_update(self, change):
                self.j = change.new * 2

        mc = MyClass()
        l = link((mc, "i"), (mc, "j"))  # noqa: E741
        self.assertRaises(TraitError, setattr, mc, "j", 2)


class TestDirectionalLink(TestCase):
    def test_connect_same(self):
        """Verify two traitlets of the same type can be linked together using directional_link."""

        # Create two simple classes with Int traitlets.
        class A(HasTraits):
            value = Int()

        a = A(value=9)
        b = A(value=8)

        # Connect the two classes.
        c = directional_link((a, "value"), (b, "value"))

        # Make sure the values are the same at the point of linking.
        self.assertEqual(a.value, b.value)

        # Change one the value of the source and check that it synchronizes the target.
        a.value = 5
        self.assertEqual(b.value, 5)
        # Change one the value of the target and check that it has no impact on the source
        b.value = 6
        self.assertEqual(a.value, 5)

    def test_tranform(self):
        """Test transform link."""

        # Create two simple classes with Int traitlets.
        class A(HasTraits):
            value = Int()

        a = A(value=9)
        b = A(value=8)

        # Connect the two classes.
        c = directional_link((a, "value"), (b, "value"), lambda x: 2 * x)

        # Make sure the values are correct at the point of linking.
        self.assertEqual(b.value, 2 * a.value)

        # Change one the value of the source and check that it modifies the target.
        a.value = 5
        self.assertEqual(b.value, 10)
        # Change one the value of the target and check that it has no impact on the source
        b.value = 6
        self.assertEqual(a.value, 5)

    def test_link_different(self):
        """Verify two traitlets of different types can be linked together using link."""

        # Create two simple classes with Int traitlets.
        class A(HasTraits):
            value = Int()

        class B(HasTraits):
            count = Int()

        a = A(value=9)
        b = B(count=8)

        # Connect the two classes.
        c = directional_link((a, "value"), (b, "count"))

        # Make sure the values are the same at the point of linking.
        self.assertEqual(a.value, b.count)

        # Change one the value of the source and check that it synchronizes the target.
        a.value = 5
        self.assertEqual(b.count, 5)
        # Change one the value of the target and check that it has no impact on the source
        b.value = 6  # type:ignore
        self.assertEqual(a.value, 5)

    def test_unlink_link(self):
        """Verify two linked traitlets can be unlinked and relinked."""

        # Create two simple classes with Int traitlets.
        class A(HasTraits):
            value = Int()

        a = A(value=9)
        b = A(value=8)

        # Connect the two classes.
        c = directional_link((a, "value"), (b, "value"))
        a.value = 4
        c.unlink()

        # Change one of the values to make sure they don't stay in sync.
        a.value = 5
        self.assertNotEqual(a.value, b.value)
        c.link()
        self.assertEqual(a.value, b.value)
        a.value += 1
        self.assertEqual(a.value, b.value)


class Pickleable(HasTraits):
    i = Int()

    @observe("i")
    def _i_changed(self, change):
        pass

    @validate("i")
    def _i_validate(self, commit):
        return commit["value"]

    j = Int()

    def __init__(self):
        with self.hold_trait_notifications():
            self.i = 1
        self.on_trait_change(self._i_changed, "i")


def test_pickle_hastraits():
    c = Pickleable()
    for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
        p = pickle.dumps(c, protocol)
        c2 = pickle.loads(p)
        assert c2.i == c.i
        assert c2.j == c.j

    c.i = 5
    for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
        p = pickle.dumps(c, protocol)
        c2 = pickle.loads(p)
        assert c2.i == c.i
        assert c2.j == c.j


def test_hold_trait_notifications():
    changes = []

    class Test(HasTraits):
        a = Integer(0)
        b = Integer(0)

        def _a_changed(self, name, old, new):
            changes.append((old, new))

        def _b_validate(self, value, trait):
            if value != 0:
                raise TraitError("Only 0 is a valid value")
            return value

    # Test context manager and nesting
    t = Test()
    with t.hold_trait_notifications():
        with t.hold_trait_notifications():
            t.a = 1
            assert t.a == 1
            assert changes == []
        t.a = 2
        assert t.a == 2
        with t.hold_trait_notifications():
            t.a = 3
            assert t.a == 3
            assert changes == []
            t.a = 4
            assert t.a == 4
            assert changes == []
        t.a = 4
        assert t.a == 4
        assert changes == []

    assert changes == [(0, 4)]
    # Test roll-back
    try:
        with t.hold_trait_notifications():
            t.b = 1  # raises a Trait error
    except Exception:
        pass
    assert t.b == 0


class RollBack(HasTraits):
    bar = Int()

    def _bar_validate(self, value, trait):
        if value:
            raise TraitError("foobar")
        return value


class TestRollback(TestCase):
    def test_roll_back(self):
        def assign_rollback():
            RollBack(bar=1)

        self.assertRaises(TraitError, assign_rollback)


class CacheModification(HasTraits):
    foo = Int()
    bar = Int()

    def _bar_validate(self, value, trait):
        self.foo = value
        return value

    def _foo_validate(self, value, trait):
        self.bar = value
        return value


def test_cache_modification():
    CacheModification(foo=1)
    CacheModification(bar=1)


class OrderTraits(HasTraits):
    notified = Dict()

    a = Unicode()
    b = Unicode()
    c = Unicode()
    d = Unicode()
    e = Unicode()
    f = Unicode()
    g = Unicode()
    h = Unicode()
    i = Unicode()
    j = Unicode()
    k = Unicode()
    l = Unicode()  # noqa: E741

    def _notify(self, name, old, new):
        """check the value of all traits when each trait change is triggered

        This verifies that the values are not sensitive
        to dict ordering when loaded from kwargs
        """
        # check the value of the other traits
        # when a given trait change notification fires
        self.notified[name] = {c: getattr(self, c) for c in "abcdefghijkl"}

    def __init__(self, **kwargs):
        self.on_trait_change(self._notify)
        super().__init__(**kwargs)


def test_notification_order():
    d = {c: c for c in "abcdefghijkl"}
    obj = OrderTraits()
    assert obj.notified == {}
    obj = OrderTraits(**d)
    notifications = {c: d for c in "abcdefghijkl"}
    assert obj.notified == notifications


###
# Traits for Forward Declaration Tests
###
class ForwardDeclaredInstanceTrait(HasTraits):
    value = ForwardDeclaredInstance["ForwardDeclaredBar"]("ForwardDeclaredBar", allow_none=True)


class ForwardDeclaredTypeTrait(HasTraits):
    value = ForwardDeclaredType[t.Any, t.Any]("ForwardDeclaredBar", allow_none=True)


class ForwardDeclaredInstanceListTrait(HasTraits):
    value = List(ForwardDeclaredInstance("ForwardDeclaredBar"))


class ForwardDeclaredTypeListTrait(HasTraits):
    value = List(ForwardDeclaredType("ForwardDeclaredBar"))


###
# End Traits for Forward Declaration Tests
###


###
# Classes for Forward Declaration Tests
###
class ForwardDeclaredBar:
    pass


class ForwardDeclaredBarSub(ForwardDeclaredBar):
    pass


###
# End Classes for Forward Declaration Tests
###


###
# Forward Declaration Tests
###
class TestForwardDeclaredInstanceTrait(TraitTestBase):
    obj = ForwardDeclaredInstanceTrait()
    _default_value = None
    _good_values = [None, ForwardDeclaredBar(), ForwardDeclaredBarSub()]
    _bad_values = ["foo", 3, ForwardDeclaredBar, ForwardDeclaredBarSub]


class TestForwardDeclaredTypeTrait(TraitTestBase):
    obj = ForwardDeclaredTypeTrait()
    _default_value = None
    _good_values = [None, ForwardDeclaredBar, ForwardDeclaredBarSub]
    _bad_values = ["foo", 3, ForwardDeclaredBar(), ForwardDeclaredBarSub()]


class TestForwardDeclaredInstanceList(TraitTestBase):
    obj = ForwardDeclaredInstanceListTrait()

    def test_klass(self):
        """Test that the instance klass is properly assigned."""
        self.assertIs(self.obj.traits()["value"]._trait.klass, ForwardDeclaredBar)

    _default_value: t.List[t.Any] = []
    _good_values = [
        [ForwardDeclaredBar(), ForwardDeclaredBarSub()],
        [],
    ]
    _bad_values = [
        ForwardDeclaredBar(),
        [ForwardDeclaredBar(), 3, None],
        "1",
        # Note that this is the type, not an instance.
        [ForwardDeclaredBar],
        [None],
        None,
    ]


class TestForwardDeclaredTypeList(TraitTestBase):
    obj = ForwardDeclaredTypeListTrait()

    def test_klass(self):
        """Test that the instance klass is properly assigned."""
        self.assertIs(self.obj.traits()["value"]._trait.klass, ForwardDeclaredBar)

    _default_value: t.List[t.Any] = []
    _good_values = [
        [ForwardDeclaredBar, ForwardDeclaredBarSub],
        [],
    ]
    _bad_values = [
        ForwardDeclaredBar,
        [ForwardDeclaredBar, 3],
        "1",
        # Note that this is an instance, not the type.
        [ForwardDeclaredBar()],
        [None],
        None,
    ]


###
# End Forward Declaration Tests
###


class TestDynamicTraits(TestCase):
    def setUp(self):
        self._notify1 = []

    def notify1(self, name, old, new):
        self._notify1.append((name, old, new))

    @t.no_type_check
    def test_notify_all(self):
        class A(HasTraits):
            pass

        a = A()
        self.assertTrue(not hasattr(a, "x"))
        self.assertTrue(not hasattr(a, "y"))

        # Dynamically add trait x.
        a.add_traits(x=Int())
        self.assertTrue(hasattr(a, "x"))
        self.assertTrue(isinstance(a, (A,)))

        # Dynamically add trait y.
        a.add_traits(y=Float())
        self.assertTrue(hasattr(a, "y"))
        self.assertTrue(isinstance(a, (A,)))
        self.assertEqual(a.__class__.__name__, A.__name__)

        # Create a new instance and verify that x and y
        # aren't defined.
        b = A()
        self.assertTrue(not hasattr(b, "x"))
        self.assertTrue(not hasattr(b, "y"))

        # Verify that notification works like normal.
        a.on_trait_change(self.notify1)
        a.x = 0
        self.assertEqual(len(self._notify1), 0)
        a.y = 0.0
        self.assertEqual(len(self._notify1), 0)
        a.x = 10
        self.assertTrue(("x", 0, 10) in self._notify1)
        a.y = 10.0
        self.assertTrue(("y", 0.0, 10.0) in self._notify1)
        self.assertRaises(TraitError, setattr, a, "x", "bad string")
        self.assertRaises(TraitError, setattr, a, "y", "bad string")
        self._notify1 = []
        a.on_trait_change(self.notify1, remove=True)
        a.x = 20
        a.y = 20.0
        self.assertEqual(len(self._notify1), 0)


def test_enum_no_default():
    class C(HasTraits):
        t = Enum(["a", "b"])

    c = C()
    c.t = "a"
    assert c.t == "a"

    c = C()

    with pytest.raises(TraitError):
        t = c.t

    c = C(t="b")
    assert c.t == "b"


def test_default_value_repr():
    class C(HasTraits):
        t = Type("traitlets.HasTraits")
        t2 = Type(HasTraits)
        n = Integer(0)
        lis = List()
        d = Dict()

    assert C.t.default_value_repr() == "'traitlets.HasTraits'"
    assert C.t2.default_value_repr() == "'traitlets.traitlets.HasTraits'"
    assert C.n.default_value_repr() == "0"
    assert C.lis.default_value_repr() == "[]"
    assert C.d.default_value_repr() == "{}"


class TransitionalClass(HasTraits):
    d = Any()

    @default("d")
    def _d_default(self):
        return TransitionalClass

    parent_super = False
    calls_super = Integer(0)

    @default("calls_super")
    def _calls_super_default(self):
        return -1

    @observe("calls_super")
    @observe_compat
    def _calls_super_changed(self, change):
        self.parent_super = change

    parent_override = False
    overrides = Integer(0)

    @observe("overrides")
    @observe_compat
    def _overrides_changed(self, change):
        self.parent_override = change


class SubClass(TransitionalClass):
    def _d_default(self):
        return SubClass

    subclass_super = False

    def _calls_super_changed(self, name, old, new):
        self.subclass_super = True
        super()._calls_super_changed(name, old, new)

    subclass_override = False

    def _overrides_changed(self, name, old, new):
        self.subclass_override = True


def test_subclass_compat():
    obj = SubClass()
    obj.calls_super = 5
    assert obj.parent_super
    assert obj.subclass_super
    obj.overrides = 5
    assert obj.subclass_override
    assert not obj.parent_override
    assert obj.d is SubClass


class DefinesHandler(HasTraits):
    parent_called = False

    trait = Integer()

    @observe("trait")
    def handler(self, change):
        self.parent_called = True


class OverridesHandler(DefinesHandler):
    child_called = False

    @observe("trait")
    def handler(self, change):
        self.child_called = True


def test_subclass_override_observer():
    obj = OverridesHandler()
    obj.trait = 5
    assert obj.child_called
    assert not obj.parent_called


class DoesntRegisterHandler(DefinesHandler):
    child_called = False

    def handler(self, change):
        self.child_called = True


def test_subclass_override_not_registered():
    """Subclass that overrides observer and doesn't re-register unregisters both"""
    obj = DoesntRegisterHandler()
    obj.trait = 5
    assert not obj.child_called
    assert not obj.parent_called


class AddsHandler(DefinesHandler):
    child_called = False

    @observe("trait")
    def child_handler(self, change):
        self.child_called = True


def test_subclass_add_observer():
    obj = AddsHandler()
    obj.trait = 5
    assert obj.child_called
    assert obj.parent_called


def test_observe_iterables():
    class C(HasTraits):
        i = Integer()
        s = Unicode()

    c = C()
    recorded = {}

    def record(change):
        recorded["change"] = change

    # observe with names=set
    c.observe(record, names={"i", "s"})
    c.i = 5
    assert recorded["change"].name == "i"
    assert recorded["change"].new == 5
    c.s = "hi"
    assert recorded["change"].name == "s"
    assert recorded["change"].new == "hi"

    # observe with names=custom container with iter, contains
    class MyContainer:
        def __init__(self, container):
            self.container = container

        def __iter__(self):
            return iter(self.container)

        def __contains__(self, key):
            return key in self.container

    c.observe(record, names=MyContainer({"i", "s"}))
    c.i = 10
    assert recorded["change"].name == "i"
    assert recorded["change"].new == 10
    c.s = "ok"
    assert recorded["change"].name == "s"
    assert recorded["change"].new == "ok"


def test_super_args():
    class SuperRecorder:
        def __init__(self, *args, **kwargs):
            self.super_args = args
            self.super_kwargs = kwargs

    class SuperHasTraits(HasTraits, SuperRecorder):
        i = Integer()

    obj = SuperHasTraits("a1", "a2", b=10, i=5, c="x")
    assert obj.i == 5
    assert not hasattr(obj, "b")
    assert not hasattr(obj, "c")
    assert obj.super_args == ("a1", "a2")
    assert obj.super_kwargs == {"b": 10, "c": "x"}


def test_super_bad_args():
    class SuperHasTraits(HasTraits):
        a = Integer()

    w = ["Passing unrecognized arguments"]
    with expected_warnings(w):
        obj = SuperHasTraits(a=1, b=2)
    assert obj.a == 1
    assert not hasattr(obj, "b")


def test_default_mro():
    """Verify that default values follow mro"""

    class Base(HasTraits):
        trait = Unicode("base")
        attr = "base"

    class A(Base):
        pass

    class B(Base):
        trait = Unicode("B")
        attr = "B"

    class AB(A, B):
        pass

    class BA(B, A):
        pass

    assert A().trait == "base"
    assert A().attr == "base"
    assert BA().trait == "B"
    assert BA().attr == "B"
    assert AB().trait == "B"
    assert AB().attr == "B"


def test_cls_self_argument():
    class X(HasTraits):
        def __init__(__self, cls, self):
            pass

    x = X(cls=None, self=None)


def test_override_default():
    class C(HasTraits):
        a = Unicode("hard default")

        def _a_default(self):
            return "default method"

    C._a_default = lambda self: "overridden"  # type:ignore
    c = C()
    assert c.a == "overridden"


def test_override_default_decorator():
    class C(HasTraits):
        a = Unicode("hard default")

        @default("a")
        def _a_default(self):
            return "default method"

    C._a_default = lambda self: "overridden"  # type:ignore
    c = C()
    assert c.a == "overridden"


def test_override_default_instance():
    class C(HasTraits):
        a = Unicode("hard default")

        @default("a")
        def _a_default(self):
            return "default method"

    c = C()
    c._a_default = lambda self: "overridden"
    assert c.a == "overridden"


def test_copy_HasTraits():
    from copy import copy

    class C(HasTraits):
        a = Int()

    c = C(a=1)
    assert c.a == 1

    cc = copy(c)
    cc.a = 2
    assert cc.a == 2
    assert c.a == 1


def _from_string_test(traittype, s, expected):
    """Run a test of trait.from_string"""
    if isinstance(traittype, TraitType):
        trait = traittype
    else:
        trait = traittype(allow_none=True)
    if isinstance(s, list):
        cast = trait.from_string_list  # type:ignore
    else:
        cast = trait.from_string
    if type(expected) is type and issubclass(expected, Exception):
        with pytest.raises(expected):  # noqa: PT012
            value = cast(s)
            trait.validate(CrossValidationStub(), value)  # type:ignore
    else:
        value = cast(s)
        assert value == expected


@pytest.mark.parametrize(
    "s, expected",
    [("xyz", "xyz"), ("1", "1"), ('"xx"', "xx"), ("'abc'", "abc"), ("None", None)],
)
def test_unicode_from_string(s, expected):
    _from_string_test(Unicode, s, expected)


@pytest.mark.parametrize(
    "s, expected",
    [("xyz", "xyz"), ("1", "1"), ('"xx"', "xx"), ("'abc'", "abc"), ("None", None)],
)
def test_cunicode_from_string(s, expected):
    _from_string_test(CUnicode, s, expected)


@pytest.mark.parametrize(
    "s, expected",
    [("xyz", b"xyz"), ("1", b"1"), ('b"xx"', b"xx"), ("b'abc'", b"abc"), ("None", None)],
)
def test_bytes_from_string(s, expected):
    _from_string_test(Bytes, s, expected)


@pytest.mark.parametrize(
    "s, expected",
    [("xyz", b"xyz"), ("1", b"1"), ('b"xx"', b"xx"), ("b'abc'", b"abc"), ("None", None)],
)
def test_cbytes_from_string(s, expected):
    _from_string_test(CBytes, s, expected)


@pytest.mark.parametrize(
    "s, expected",
    [("x", ValueError), ("1", 1), ("123", 123), ("2.0", ValueError), ("None", None)],
)
def test_int_from_string(s, expected):
    _from_string_test(Integer, s, expected)


@pytest.mark.parametrize(
    "s, expected",
    [("x", ValueError), ("1", 1.0), ("123.5", 123.5), ("2.5", 2.5), ("None", None)],
)
def test_float_from_string(s, expected):
    _from_string_test(Float, s, expected)


@pytest.mark.parametrize(
    "s, expected",
    [
        ("x", ValueError),
        ("1", 1.0),
        ("123.5", 123.5),
        ("2.5", 2.5),
        ("1+2j", 1 + 2j),
        ("None", None),
    ],
)
def test_complex_from_string(s, expected):
    _from_string_test(Complex, s, expected)


@pytest.mark.parametrize(
    "s, expected",
    [
        ("true", True),
        ("TRUE", True),
        ("1", True),
        ("0", False),
        ("False", False),
        ("false", False),
        ("1.0", ValueError),
        ("None", None),
    ],
)
def test_bool_from_string(s, expected):
    _from_string_test(Bool, s, expected)


@pytest.mark.parametrize(
    "s, expected",
    [
        ("{}", {}),
        ("1", TraitError),
        ("{1: 2}", {1: 2}),
        ('{"key": "value"}', {"key": "value"}),
        ("x", TraitError),
        ("None", None),
    ],
)
def test_dict_from_string(s, expected):
    _from_string_test(Dict, s, expected)


@pytest.mark.parametrize(
    "s, expected",
    [
        ("[]", []),
        ('[1, 2, "x"]', [1, 2, "x"]),
        (["1", "x"], ["1", "x"]),
        (["None"], None),
    ],
)
def test_list_from_string(s, expected):
    _from_string_test(List, s, expected)


@pytest.mark.parametrize(
    "s, expected, value_trait",
    [
        (["1", "2", "3"], [1, 2, 3], Integer()),
        (["x"], ValueError, Integer()),
        (["1", "x"], ["1", "x"], Unicode()),
        (["None"], [None], Unicode(allow_none=True)),
        (["None"], ["None"], Unicode(allow_none=False)),
    ],
)
def test_list_items_from_string(s, expected, value_trait):
    _from_string_test(List(value_trait), s, expected)


@pytest.mark.parametrize(
    "s, expected",
    [
        ("[]", set()),
        ('[1, 2, "x"]', {1, 2, "x"}),
        ('{1, 2, "x"}', {1, 2, "x"}),
        (["1", "x"], {"1", "x"}),
        (["None"], None),
    ],
)
def test_set_from_string(s, expected):
    _from_string_test(Set, s, expected)


@pytest.mark.parametrize(
    "s, expected, value_trait",
    [
        (["1", "2", "3"], {1, 2, 3}, Integer()),
        (["x"], ValueError, Integer()),
        (["1", "x"], {"1", "x"}, Unicode()),
        (["None"], {None}, Unicode(allow_none=True)),
    ],
)
def test_set_items_from_string(s, expected, value_trait):
    _from_string_test(Set(value_trait), s, expected)


@pytest.mark.parametrize(
    "s, expected",
    [
        ("[]", ()),
        ("()", ()),
        ('[1, 2, "x"]', (1, 2, "x")),
        ('(1, 2, "x")', (1, 2, "x")),
        (["1", "x"], ("1", "x")),
        (["None"], None),
    ],
)
def test_tuple_from_string(s, expected):
    _from_string_test(Tuple, s, expected)


@pytest.mark.parametrize(
    "s, expected, value_traits",
    [
        (["1", "2", "3"], (1, 2, 3), [Integer(), Integer(), Integer()]),
        (["x"], ValueError, [Integer()]),
        (["1", "x"], ("1", "x"), [Unicode()]),
        (["None"], ("None",), [Unicode(allow_none=False)]),
        (["None"], (None,), [Unicode(allow_none=True)]),
    ],
)
def test_tuple_items_from_string(s, expected, value_traits):
    _from_string_test(Tuple(*value_traits), s, expected)


@pytest.mark.parametrize(
    "s, expected",
    [
        ("x", "x"),
        ("mod.submod", "mod.submod"),
        ("not an identifier", TraitError),
        ("1", "1"),
        ("None", None),
    ],
)
def test_object_from_string(s, expected):
    _from_string_test(DottedObjectName, s, expected)


@pytest.mark.parametrize(
    "s, expected",
    [
        ("127.0.0.1:8000", ("127.0.0.1", 8000)),
        ("host.tld:80", ("host.tld", 80)),
        ("host:notaport", ValueError),
        ("127.0.0.1", ValueError),
        ("None", None),
    ],
)
def test_tcp_from_string(s, expected):
    _from_string_test(TCPAddress, s, expected)


@pytest.mark.parametrize(
    "s, expected",
    [("[]", []), ("{}", "{}")],
)
def test_union_of_list_and_unicode_from_string(s, expected):
    _from_string_test(Union([List(), Unicode()]), s, expected)


@pytest.mark.parametrize(
    "s, expected",
    [("1", 1), ("1.5", 1.5)],
)
def test_union_of_int_and_float_from_string(s, expected):
    _from_string_test(Union([Int(), Float()]), s, expected)


@pytest.mark.parametrize(
    "s, expected, allow_none",
    [("[]", [], False), ("{}", {}, False), ("None", TraitError, False), ("None", None, True)],
)
def test_union_of_list_and_dict_from_string(s, expected, allow_none):
    _from_string_test(Union([List(), Dict()], allow_none=allow_none), s, expected)


def test_all_attribute():
    """Verify all trait types are added to `traitlets.__all__`"""
    names = dir(traitlets)
    for name in names:
        value = getattr(traitlets, name)
        if not name.startswith("_") and isinstance(value, type) and issubclass(value, TraitType):
            if name not in traitlets.__all__:
                raise ValueError(f"{name} not in __all__")

    for name in traitlets.__all__:
        if name not in names:
            raise ValueError(f"{name} should be removed from __all__")