main /Languages/IronPython/Tests/test_class.py

Language Python Lines 3767
MD5 Hash 75df4aa99f461c192d6b7ee2ab82c8ff Estimated Cost $72,849 (why?)
Repository git://github.com/IronLanguages/main.git View Raw File View Project SPDX
   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
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
#####################################################################################
#
#  Copyright (c) Microsoft Corporation. All rights reserved.
#
# This source code is subject to terms and conditions of the Apache License, Version 2.0. A
# copy of the license can be found in the License.html file at the root of this distribution. If
# you cannot locate the  Apache License, Version 2.0, please send an email to
# ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
# by the terms of the Apache License, Version 2.0.
#
# You must not remove this notice, or any other, from this software.
#
#
#####################################################################################

#--IMPORTS---------------------------------------------------------------------
from iptest.assert_util import *
from iptest.type_util import *
import sys

#--HELPERS---------------------------------------------------------------------


############################################################
def test_common_attributes():
    builtin_type_instances = [None, object(), 1, "Hello", [0,1], {"a":0}]
    builtin_hashable_type_instances = [None, object(), 1, "Hello"]
    builtin_types = [type(None), object, int, str, list, dict]

    for i in builtin_type_instances:
        # Read-only attribute
        AssertError(AttributeError, i.__delattr__, "__doc__")
        # Non-existent attribute
        AssertError(AttributeError, i.__delattr__, "foo")
    # Modifying __class__ causes a TypeError
        AssertError(TypeError, i.__delattr__, "__class__")
    
        # Read-only attribute
        AssertError(TypeError, i.__setattr__, "__doc__")
        # Non-existent attribute
        AssertError(AttributeError, i.__setattr__, "foo", "foovalue")
        # Modifying __class__ causes a TypeError
        AssertError(TypeError, i.__setattr__, "__class__")
        
        AreEqual(type(i), i.__getattribute__("__class__"))
        # Non-existent attribute
        AssertError(AttributeError, i.__getattribute__, "foo")
        
        if (is_cli or is_silverlight) and i == None: # !!! Need to expose __reduce__ on all types
            AssertError(TypeError, i.__reduce__)
            AssertError(TypeError, i.__reduce_ex__)
    
    for i in builtin_hashable_type_instances:
        AreEqual(hash(i), i.__hash__())
            
    for i in builtin_types:
          if (is_cli or is_silverlight) and i == type(None):
              continue
          # __init__ and __new__ are implemented by IronPython.Runtime.Operations.InstanceOps
          # We do repr to ensure that we can map back the functions properly
          repr(getattr(i, "__init__"))
          repr(getattr(i, "__new__"))
            
############################################################
def test_set_dict():
    class C: pass
    setdict = C.__dict__
    C.__dict__ = setdict
    
    o1 = C()

    class C:
        def m(self):
            return 42
    
    o2 = C()
    Assert(42 == o2.m())
    
    Assert(o2.__class__ is C)
    Assert(o2.__class__ is not o1.__class__)


############################################################
def test_attrs():
    class C:pass
    
    C.v = 10
    
    Assert(C.v == 10)
    
    success = 0
    try:
        x = C.x
    except AttributeError:
        success = 1
    Assert(success == 1)


############################################################
def test_type_in():
    AreEqual(type in (None, True, False, 1, {}, [], (), 1.0, 1L, (1+0j)), False)

############################################################
def test_init_defaults():
    class A:
        def __init__(self, height=20, width=30):
            self.area = height * width
    
    a = A()
    Assert(a.area == 600)
    a = A(2,3)
    Assert(a.area == 6)
    a = A(2)
    Assert(a.area == 60)
    a = A(width = 2)
    Assert(a.area == 40)

############################################################
def test_getattr():
    class C:
        def __init__(self, name, flag):
            self.f = file(name, flag)
        def __getattr__(self, name):
            return getattr(self.f, name)
    
    tmpfile = "tmpfile.txt"
    
    if not is_silverlight:
        c=C(tmpfile, "w")
        c.write("Hello\n")
        c.close()
        c=C(tmpfile, "r")
        Assert(c.readline() == "Hello\n")
        c.close()

    try:
        import nt
        nt.unlink(tmpfile)
    except:
        pass
            
    # new-style
    class C(object):
        def __getattr__(self, name):
            raise AttributeError(name)
    
    # old-style
    class D:
        def __getattr__(self, name):
            raise AttributeError(name)

    # new-style __getattribute__
    class E(object):
        def __getattribute__(self, name):
            if name == 'xyz':
                raise AttributeError(name)
            if name == 'x':
                return 42
            return object.__getattribute__(self, name)

    # derived new-style type
    class F(E):
        pass

    # verify that base class' __getattribute__ is called.
    AreEqual(F().x, 42)
        
    # exception shouldn't propagate out
    for cls in [C, D, E, F]:
        AreEqual(getattr(cls(), 'xyz', 'DNE'), 'DNE')
        AreEqual(hasattr(cls(), 'xyz'), False)
    
    
    # removing & adding back on __getattribute__ should work
    class foo(object):
        def __getattribute__(self, name): return 42

    x = foo.__getattribute__
    del foo.__getattribute__
    AssertError(AttributeError, getattr, foo(), 'x')
    foo.__getattribute__ = x
    AreEqual(foo().x, 42)
    del foo.__getattribute__
    AssertError(AttributeError, getattr, foo(), 'x')

    # check getattr when the property raises
    class C(object):
        def throw(self):
            raise AttributeError
        foo = property(throw)

    AreEqual(getattr(C(), 'foo', 'abc'), 'abc')

def count_elem(d,n):
    count = 0
    for e in d:
        if e == n:
            count += 1
    return count

############################################################
def test_newstyle_oldstyle_dict():
    """Dictionary and new style classes"""
    
    class class_n(object):
        val1 = "Value"
        def __init__(self):
            self.val2 = self.val1
    
    inst_n = class_n()
    Assert(inst_n.val2 == "Value")
    Assert(not 'val2' in dir(class_n))
    Assert('val1' in dir(class_n))
    Assert('val2' in dir(inst_n))
    Assert('val1' in dir(inst_n))
    Assert('val2' in inst_n.__dict__)
    Assert(inst_n.__dict__['val2'] == "Value")
    Assert(count_elem(dir(inst_n), "val1") == 1)
    inst_n.val1 = 20
    Assert(count_elem(dir(inst_n), "val1") == 1)

    # old style classes:
    
    class class_o:
        val1 = "Value"
        def __init__(self):
            self.val2 = self.val1
    
    inst_o = class_o()
    Assert('val1' in dir(class_o))
    Assert(not 'val2' in dir(class_o))
    Assert('val1' in dir(inst_o))
    Assert('val2' in dir(inst_o))
    Assert('val2' in inst_o.__dict__)
    Assert(inst_o.__dict__['val2'] == "Value")
    Assert(count_elem(dir(inst_o), "val1") == 1)
    inst_n.val1 = 20
    Assert(count_elem(dir(inst_o), "val1") == 1)
    Assert(isinstance(class_o, object))
    Assert(isinstance(inst_o, object))
    Assert(isinstance(None, object))


############################################################
def test_misc():
    class C:
        def x(self):
            return 'C.x'
        def y(self):
            return 'C.y'
    
    class D:
        def z(self):
            return 'D.z'
    
    c = C()
    AreEqual(c.x(), "C.x")
    AreEqual(c.y(), "C.y")
    
    # verify repr and str on old-style class objects have the right format:
    
    # bug# 795
    AreEqual(str(C), __name__+'.C')
    AreEqual(repr(C).index('<class '+__name__+'.C at 0x'), 0)
    
    success=0
    try:
        c.z()
    except AttributeError:
        success=1
    Assert(success==1)
    
    C.__bases__+=(D,)
    
    AreEqual(c.z(), "D.z")

    class C:
        def m(self):
            return "IronPython"
        def n(self, parm):
            return parm
    
    c = C()
    
    y = c.m
    y = c.n
    y = C.m
    y = C.n

    Assert('__dict__' not in str.__dict__)

############################################################
def test_dir_in_init():
    # both of these shouldn't throw
    
    class DirInInit(object):
        def __init__(self):
            dir(self)
    
    a = DirInInit()


############################################################
def test_priv_class():
    class _PrivClass(object):
        def __Mangled(self):
                pass
        def __init__(self):
                a = self.__Mangled
    
    a = _PrivClass()

############################################################
def test_inheritance_attrs_dir():
    class foo:
        def foofunc(self):
            return "foofunc"
    
    class bar(foo):
        def barfunc(self):
            return "barfunc"
    
    class baz(foo, bar):
        def bazfunc(self):
            return "bazfunc"
    
    Assert('foofunc' in dir(foo))
    Assert(dir(foo).count('__doc__') == 1)
    Assert(dir(foo).count('__module__') == 1)
    Assert(len(dir(foo)) == 3)
    Assert('foofunc' in dir(bar))
    Assert('barfunc' in dir(bar))
    Assert(dir(bar).count('__doc__') == 1)
    Assert(dir(bar).count('__module__') == 1)
    Assert(len(dir(bar)) == 4)
    Assert('foofunc' in dir(baz))
    Assert('barfunc' in dir(baz))
    Assert('bazfunc' in dir(baz))
    Assert(dir(baz).count('__doc__') == 1)
    Assert(dir(baz).count('__module__') == 1)
    Assert(len(dir(baz)) == 5)
    
    bz = baz()
    Assert('foofunc' in dir(bz))
    Assert('barfunc' in dir(bz))
    Assert('bazfunc' in dir(bz))
    Assert(dir(bz).count('__doc__') == 1)
    Assert(dir(bz).count('__module__') == 1)
    Assert(len(dir(bz)) == 5)
    
    bz.__module__ = "MODULE"
    Assert(bz.__module__ == "MODULE")
    bz.__module__ = "SOMEOTHERMODULE"
    Assert(bz.__module__ == "SOMEOTHERMODULE")
    bz.__module__ = 33
    Assert(bz.__module__ == 33)
    bz.__module__ = [2, 3, 4]
    Assert(bz.__module__ == [2, 3 , 4])


############################################################
def test_oldstyle_setattr():
    global called
    class C:
        def __setattr__(self, name, value):
            global called
            called = (self, name, value)
            
    a = C()
    a.abc = 'def'
    AreEqual(called, (a, 'abc', 'def'))
    
    del C.__setattr__
    
    a.qrt = 'abc'
    
    AreEqual(called, (a, 'abc', 'def'))
    
    def setattr(self, name, value):
        global called
        called = (self, name, value)
    
    C.__setattr__ = setattr
    
    a.qrt = 'abc'
    
    AreEqual(called, (a, 'qrt', 'abc'))
    
############################################################
def test_oldstyle_getattr():
    """verify we don't access __getattr__ while creating an old
    style class."""
    
    class C:
        def __getattr__(self,name):
            return globals()[name]
    
    a = C()

def test_oldstyle_eq():
    """old style __eq__ shouldn't call __cmp__"""
    class x: pass
    
    inst = type(x())
    
    global cmpCalled
    cmpCalled = False
    class C:
        def __init__(self, value):
            self.value = value
        def __cmp__(self, other):
            global cmpCalled
            cmpCalled = True
            return self.value - other.value
    
    class D:
        def __init__(self, value):
            self.value = value
        def __cmp__(self, other):
            global cmpCalled
            cmpCalled = True
            return self.value - other.value
    
    
    class C2(C): pass
    
    class D2(D): pass
    
    
    AreEqual(inst.__eq__(C(3.0), C(4.5)), NotImplemented)
    AreEqual(inst.__eq__(C(3.0), C2(4.5)), NotImplemented)
    AreEqual(inst.__eq__(C(3.0), D(4.5)), NotImplemented)
    AreEqual(cmpCalled, False)

############################################################
def test_raise_attrerror():
    """raising AttributeError from __getattr__ should be ok,
    and shouldn't be seen by the user"""
    
    class A:
        def __getattr__(self, name):
            raise AttributeError, 'get outta here'
        def __repr__(self):
            return 'foo'
    
    class B:
        def __getattr__(self, name):
            raise AttributeError, 'get outta here'
        def __str__(self):
            return 'foo'
    
    AreEqual(str(A()), 'foo')
    AreEqual(repr(A()), 'foo')
    AreEqual(str(B()), 'foo')
    Assert(repr(B()).find('B instance') != -1)

############################################################

# use exec to define methods on classes:

def test_exec_namespace():
    class oldclasswithexec:
        exec "def oldexecmethod(self): return 'result of oldexecmethod'"
    
    Assert('oldexecmethod' in dir(oldclasswithexec))
    AreEqual(oldclasswithexec().oldexecmethod(), 'result of oldexecmethod')
    
    class newclasswithexec(object):
        exec "def newexecmethod(self): return 'result of newexecmethod'"
    
    Assert('newexecmethod' in dir(newclasswithexec))
    AreEqual(newclasswithexec().newexecmethod(), 'result of newexecmethod')


############################################################
def test_module_name():
    global __name__
    
    mod = sys.modules[__name__]
    name = __name__
    
    mod.__name__ = None
    
    class C: pass
    
    AreEqual(C.__module__, None)
    
    def func1():
        __name__ = "wrong"
        class C: pass
        return C()
    
    def func2():
        class C: pass
        return C()
    
    def func3():
        global __name__
        __name__ = "right"
        class C: pass
        return C()
        
        
    AreEqual(func1().__module__, func2().__module__)
    
    __name__ = "fake"
    AreEqual(func1().__module__, "fake")
    
    AreEqual(func3().__module__, "right")
    mod.__name__ = name
    
    def f(x): x.__module__
    def g(x): getattr(x, '__module__')
    import errno
    for thing in "", 1, errno, 1L, 1+2j, (), [], {}:
        AreEqual(getattr(thing, '__module__', 'does_not_exist'), 'does_not_exist')
        AreEqual(hasattr(thing, '__module__'), False)
        AssertError(AttributeError, f, thing)
        AssertError(AttributeError, g, thing)
    
    AssertErrorWithMessage(TypeError, "can't set function.__module__", type(type(f)).__dict__['__module__'].__set__, type(f), 42)
    
    class x(object): pass
    type(type(x())).__dict__['__module__'].__set__(x, 'fooz')
    AreEqual(x.__module__, 'fooz')
    
    AssertErrorWithMessage(TypeError, "can't delete x.__module__", type(type(x())).__dict__['__module__'].__delete__, x)

############################################################
def test_check_dictionary():
    """tests to verify that Symbol dictionaries do the right thing in dynamic scenarios"""
    def CheckDictionary(C):
        # add a new attribute to the type...
        C.newClassAttr = 'xyz'
        AreEqual(C.newClassAttr, 'xyz')
        
        # add non-string index into the class and instance dictionary
        a = C()
        a.__dict__[1] = '1'
        if object in C.__bases__:
            try:
                C.__dict__[2] = '2'
                AssertUnreachable()
            except TypeError: pass
            AreEqual(C.__dict__.has_key(2), False)

        AreEqual(a.__dict__.has_key(1), True)
        AreEqual(dir(a).__contains__(1), True)

        AreEqual(repr(a.__dict__), "{1: '1'}")
        
        # replace a class dictionary (containing non-string keys) w/ a normal dictionary
        C.newTypeAttr = 1
        AreEqual(hasattr(C, 'newTypeAttr'), True)
        
        class OldClass: pass
        
        if isinstance(C, type(OldClass)):
            C.__dict__ = dict(C.__dict__)
            AreEqual(hasattr(C, 'newTypeAttr'), True)
        else:
            try:
                C.__dict__ = {}
                AssertUnreachable()
            except AttributeError:
                pass
        
        # replace an instance dictionary (containing non-string keys) w/ a new one.
        a.newInstanceAttr = 1
        AreEqual(hasattr(a, 'newInstanceAttr'), True)
        a.__dict__  = dict(a.__dict__)
        AreEqual(hasattr(a, 'newInstanceAttr'), True)
    
        a.abc = 'xyz'
        AreEqual(hasattr(a, 'abc'), True)
        AreEqual(getattr(a, 'abc'), 'xyz')
        
    
    class OldClass:
        def __init__(self):  pass
    
    class NewClass(object):
        def __init__(self):  pass
    
    CheckDictionary(OldClass)
    CheckDictionary(NewClass)


############################################################

def test_call_type_call():
    for stuff in [object, int, str, bool, float]:
        AreEqual(type(type.__call__(stuff)), stuff)
    
    AreEqual(type.__call__(int, 5), 5)
    AreEqual(type.__call__(int), 0)
    
    AreEqual(type.__call__(bool, True), True)
    AreEqual(type.__call__(bool), False)
    
    #User-defined old/new style classes
    call_mapper = {}
    
    class KOld0:
        def __call__(self):
            return 2
    call_mapper[KOld0] = lambda: [type(KOld0()).__call__(KOld0())]
            
    class KOld1:
        def __call__(self, p):
            return 2
    call_mapper[KOld1] = lambda: [type(KOld1()).__call__(KOld1(), 3.14),
                                  type(KOld1()).__call__(KOld1(), p=3.14),
                                  type(KOld1()).__call__(KOld1(), **{"p":3.14}),
                                  type(KOld1()).__call__(KOld1(), (1, 2, 3))  ]
            
    class KOldArgs:
        def __call__(self, *args):
            return 2
    call_mapper[KOldArgs] = lambda: [type(KOldArgs()).__call__(KOldArgs())]
            
    class KOldKwargs:
        def __call__(self, **kwargs):
            return 2
    call_mapper[KOldKwargs] = lambda: [type(KOldKwargs()).__call__(KOldKwargs())]
            
    class KOldArgsKwargs:
        def __call__(self, *args, **kwargs):
            return 2
    call_mapper[KOldArgsKwargs] = lambda: [type(KOldArgsKwargs()).__call__(KOldArgsKwargs())]
            
    
    
    class KNew0(object):
        def __call__(self):
            return 2
    call_mapper[KNew0] = lambda: [type(KNew0()).__call__(KNew0())]
            
    class KNew1(object):
        def __call__(self, p):
            return 2
    call_mapper[KNew1] = lambda: [type(KNew1()).__call__(KNew1(), 3.14),
                                  type(KNew1()).__call__(KNew1(), p=3.14),
                                  type(KNew1()).__call__(KNew1(), **{"p":3.14}),
                                  type(KNew1()).__call__(KNew1(), []),
                                  ]
            
    class KNewArgs(object):
        def __call__(self, *args):
            return 2
    call_mapper[KNewArgs] = lambda: [type(KNewArgs()).__call__(KNewArgs()) ]
            
    class KNewKwargs(object):
        def __call__(self, **kwargs):
            return 2
    call_mapper[KNewKwargs] = lambda: [type(KNewKwargs()).__call__(KNewKwargs())]
            
    class KNewArgsKwargs(object):
        def __call__(self, *args, **kwargs):
            return 2
    call_mapper[KNewArgsKwargs] = lambda: [type(KNewArgsKwargs()).__call__(KNewArgsKwargs())]

    
    for K in call_mapper.keys():        
        for ret_val in call_mapper[K]():
            AreEqual(ret_val, 2)


def test_cp8246():
    
    #...
    class K(object):
        def __call__(self):
            return ((), {})
    AreEqual(K()(), ((), {}))
    
    #...
    class K(object):
        def __call__(self, **kwargs):
            return ((), kwargs)
    AreEqual(K()(), ((), {}))
    AreEqual(K()(**{}), ((), {}))
    AreEqual(K()(**{'a':None}), ((), {'a':None}))
    
    #...
    class K(object):
        def __call__(self, *args):
            return (args, {})
    AreEqual(K()(), ((), {}))
    AreEqual(K()(*()), ((), {}))
    AreEqual(K()(*(None,)), ((None,), {}))
    
    #...
    class K(object):
        def __call__(self, *args, **kwargs):
            return (args, kwargs)
    AreEqual(K()(), ((), {}))
    AreEqual(K()(*()), ((), {}))
    AreEqual(K()(**{}), ((), {}))
    AreEqual(K()(*(), **{}), ((), {}))
    AreEqual(K()(*(None,)), ((None,), {}))
    AreEqual(K()(**{'a':None}), ((), {'a':None}))
    AreEqual(K()(*(None,), **{'a':None}), ((None,), {'a':None}))
    
    
############################################################
def test_mixed_inheritance():
    """inheritance from both old & new style classes..."""
    class foo: pass
    
    class bar(object): pass
    
    class baz1(foo, bar): pass
    
    class baz2(bar, foo): pass
    
    AreEqual(baz1.__bases__, (foo, bar))
    AreEqual(baz2.__bases__, (bar, foo))
    
    class foo:
        abc = 3
    
    class bar(object):
        def get_abc():
            return 42
        def set_abc():
            pass
            
        abc = property(fget=get_abc, fset=set_abc)
    
    class baz(foo, bar): pass
    
    AreEqual(baz().abc, 3)

############################################################
def test_newstyle_unbound_inheritance():
    """verify calling unbound method w/ new-style class on subclass which
    new-style also inherits from works."""
    class foo:
        def func(self): return self
    
    class bar(object, foo):
        def barfunc(self):
                return foo.func(self)
    
    a = bar()
    AreEqual(a.barfunc(), a)

############################################################
def test_mro():
    """mro (method resolution order) support"""
    class A(object): pass
    
    AreEqual(A.__mro__, (A, object))
    
    class B(object): pass
    
    AreEqual(B.__mro__, (B, object))
    
    class C(B): pass
    
    AreEqual(C.__mro__, (C, B, object))
    
    class N(C,B,A): pass
    
    AreEqual(N.__mro__, (N, C, B, A, object))
    
    try:
        class N(A, B,C): pass
        AssertUnreachable("impossible MRO created")
    except TypeError:
        pass
    
    try:
        class N(A, A): pass
        AssertUnreachable("can't dervie from the same base type twice")
    except TypeError:
        pass

############################################################
def test_mro_bases():
    """verify replacing base classes also updates MRO"""
    class C(object):
        def __getattribute__(self, name):
            if(name == 'xyz'): return 'C'
            return super(C, self).__getattribute__(name)
    
    class C1(C):
        def __getattribute__(self, name):
            if(name == 'xyz'):  return 'C1'
            return super(C1, self).__getattribute__(name)
    
    class A(object): pass
    
    class B(object):
        def __getattribute__(self, name):
            if(name == 'xyz'): return 'B'
            return super(B, self).__getattribute__(name)
    
    a = C1()
    AreEqual(a.xyz, 'C1')
    
    C1.__bases__ = (A,B)
    AreEqual(a.xyz, 'C1')
    
    del(C1.__getattribute__)
    AreEqual(a.xyz, 'B')

############################################################
def test_dynamic_mro_bases():
    class C(object):
        pass
    
    def __getattribute__(self, name):
        if (name == 'xyz'):
            return 'C'
        return super(C, self).__getattribute__(name)
    
    C.__getattribute__ = __getattribute__
     
    class C1(C):
        pass
    
    def __getattribute__(self, name):
        if (name == 'xyz'):
            return 'C1'
        return super(C1, self).__getattribute__(name)
    
     
    C1.__getattribute__ = __getattribute__
    
     
    class B(object):
        pass
    
    def __getattribute__(self, name):
        if (name == 'xyz'):
            return 'B'
        return super(B, self).__getattribute__(name)
    
    B.__getattribute__ = __getattribute__
     
    C1.__bases__ = (B, )
    AreEqual(C1().xyz, 'C1')
    
############################################################
def test_builtin_mro():
    """int mro shouldn't include ValueType"""
    AreEqual(int.__mro__, (int, object))

############################################################
def test_mixed_inheritance_mro():
    """mixed inheritance from old-style & new-style classes"""
    
    # we should use old-style MRO when inheriting w/ a single old-style class
    class A: pass
    
    class B(A): pass
    
    class C(A): pass
    
    class D(B, C):pass
    
    class E(D, object): pass
    
    # old-style MRO of D is D, B, A, C, which should
    # be present  in E's mro
    AreEqual(E.__mro__, (E, D, B, A, C, object))
    
    class F(B, C, object): pass
    
    # but when inheriting from multiple old-style classes we switch
    # to new-style MRO, and respect local ordering of classes in the MRO
    AreEqual(F.__mro__, (F, B, C, A, object))
    
    class G(B, object, C): pass
    
    AreEqual(G.__mro__, (G, B, object, C, A))
    
    class H(E): pass
    
    AreEqual(H.__mro__, (H, E, D, B, A, C, object))
    
    try:
        class H(A,B,E): pass
        AssertUnreachable()
    except TypeError:
        pass
    
    
    class H(E,B,A): pass
    
    AreEqual(H.__mro__, (H, E, D, B, A, C, object))

############################################################
def test_depth_first_mro_mixed():
    """Verify given two large, independent class hierarchies
    that we favor them in the order listed.
    
    w/ old-style
    """
    
    class A: pass
    
    class B(A): pass
    
    class C(A): pass
    
    class D(B,C): pass
    
    class E(D, object): pass
    
    class G: pass
    
    class H(G): pass
    
    class I(G): pass
    
    class K(H,I, object): pass
    
    class L(K,E): pass
    
    AreEqual(L.__mro__, (L, K, H, I, G, E, D, B, A, C, object))

############################################################
def test_depth_first_mro():
    """w/o old-style"""
    
    class A(object): pass
    
    class B(A): pass
    
    class C(A): pass
    
    class D(B,C): pass
    
    class E(D, object): pass
    
    class G(object): pass
    
    class H(G): pass
    
    class I(G): pass
    
    class K(H,I, object): pass
    
    class L(K,E): pass
    
    AreEqual(L.__mro__, (L, K, H, I, G, E, D, B, C, A, object))

    
############################################################
def test_newstyle_lookup():
    """new-style classes should only lookup methods from the class, not from the instance"""
    class Strange(object):
        def uselessMethod(self): pass
    
    global obj
    obj = Strange()
    obj.__nonzero__ = lambda: False
    AreEqual(bool(obj), True)
    
    def twoargs(self, other):
        global twoArgsCalled
        twoArgsCalled = True
        return self
    
    def onearg(self):
        return self
        
    def onearg_str(self):
        return 'abc'
    
    # create methods that we can then stick into Strange
    twoargs = type(Strange.uselessMethod)(twoargs, None, Strange)
    onearg = type(Strange.uselessMethod)(onearg, None, Strange)


    class ForwardAndReverseTests:
        testCases = [
            #forward versions
            ('__add__', 'obj + obj'),
            ('__sub__', 'obj - obj'),
            ('__mul__', 'obj * obj'),
            ('__floordiv__', 'obj // obj'),
            ('__mod__', 'obj % obj'),
            ('__divmod__', 'divmod(obj,obj)'),
            ('__pow__', 'pow(obj, obj)'),
            ('__lshift__', 'obj << obj'),
            ('__rshift__', 'obj >> obj'),
            ('__and__', 'obj & obj'),
            ('__xor__', 'obj ^ obj'),
            ('__or__', 'obj | obj'),
            
            # reverse versions
            ('__radd__', '1 + obj'),
            ('__rsub__', '1 - obj'),
            ('__rmul__', '1 * obj'),
            ('__rfloordiv__', '1 // obj'),
            ('__rmod__', '1 % obj'),
            #('__rdivmod__', '1 % obj'), #bug 975
            ('__rpow__', 'pow(1, obj)'),
            ('__rlshift__', '1 << obj'),
            ('__rrshift__', '1 >> obj'),
            ('__rand__', '1  & obj'),
            ('__rxor__', '1 ^ obj'),
            ('__ror__', '1 | obj'),
            ]
        
        @staticmethod
        def NegativeTest(method, testCase):
            setattr(obj, method, twoargs)
            
            try:
                eval(testCase)
                AssertUnreachable()
            except TypeError, e:
                pass
            
            delattr(obj, method)
        
        @staticmethod
        def PositiveTest(method, testCase):
            setattr(Strange, method, twoargs)
            
            AreEqual(eval(testCase), obj)
            
            delattr(Strange, method)
    
    
    class InPlaceTests:
        # in-place versions require exec instead of eval
        testCases = [
            # inplace versions
            ('__iadd__', 'obj += obj'),
            ('__isub__', 'obj -= obj'),
            ('__imul__', 'obj *= obj'),
            ('__ifloordiv__', 'obj //= obj'),
            ('__imod__', 'obj %= obj'),
            ('__ipow__', 'obj **= obj'),
            ('__ilshift__', 'obj <<= obj'),
            ('__irshift__', 'obj >>= obj'),
            ('__iand__', 'obj &= obj'),
            ('__ixor__', 'obj ^= obj'),
            ('__ior__', 'obj |= obj'),
        ]
        
        @staticmethod
        def NegativeTest(method, testCase):
            setattr(obj, method, twoargs)
            
            try:
                exec testCase in globals(), locals()
                AssertUnreachable()
            except TypeError:
                pass
            
            delattr(obj, method)
        
        @staticmethod
        def PositiveTest(method, testCase):
            setattr(Strange, method, twoargs)
            
            global twoArgsCalled
            twoArgsCalled = False
            exec testCase in globals(), locals()
            AreEqual(twoArgsCalled, True)
            
            delattr(Strange, method)
    
    
    class SingleArgTests:
        testCases = [
            # one-argument versions
            ('__neg__', '-obj'),
            ('__pos__', '+obj'),
            ('__abs__', 'abs(obj)'),
            ('__invert__', '~obj'),
            ]
        
        @staticmethod
        def NegativeTest(method, testCase):
            setattr(obj, method, onearg)
        
            try:
                eval(testCase)
                AssertUnreachable()
            except TypeError:
                pass
            
            delattr(obj, method)
        
        @staticmethod
        def PositiveTest(method, testCase):
            setattr(Strange, method, onearg)

            try:
                AreEqual(eval(testCase), obj)
            except TypeError:
                Assert(method == '__oct__' or method == '__hex__')
            
            delattr(Strange, method)
    
    class HexOctTests:
        testCases = [
            ('__oct__', 'oct(obj)'),
            ('__hex__', 'hex(obj)'),
            ]

        @staticmethod
        def NegativeTest(method, testCase):
            setattr(obj, method, onearg)
        
            try:
                eval(testCase)
                AssertUnreachable()
            except TypeError:
                pass
            
            delattr(obj, method)
        
        @staticmethod
        def PositiveTest(method, testCase):
            setattr(Strange, method, onearg_str)

            AreEqual(eval(testCase), 'abc')
            
            delattr(Strange, method)

    class ConversionTests:
        testCases = [
            (('__complex__', 2+0j), 'complex(obj)'),
            (('__int__', 1), 'int(obj)'),
            (('__long__', 1L), 'long(obj)'),
            (('__float__', 1.0), 'float(obj)'),
          ]
          
        @staticmethod
        def NegativeTest(method, testCase):
            setattr(obj, method[0], onearg)
        
            try:
                eval(testCase)
                AssertUnreachable()
            except (TypeError, ValueError), e:
                AreEqual(e.args[0].find('returned') == -1, True)    # shouldn't have returned '__complex__ returned ...'

            delattr(obj, method[0])
            
        @staticmethod
        def PositiveTest(method, testCase):
            def testMethod(self):
                return method[1]
                
            testMethod = type(Strange.uselessMethod)(testMethod, None, Strange)
            setattr(Strange, method[0], testMethod)
    
            AreEqual(eval(testCase), method[1])
            
            delattr(Strange, method[0])
        
    allTests = [ForwardAndReverseTests, InPlaceTests, SingleArgTests, ConversionTests, HexOctTests]
    
    for test in allTests:
        for method,testCase in test.testCases:
            test.NegativeTest(method, testCase)
        for method,testCase in test.testCases:
            test.PositiveTest(method, testCase)
    
    #Verify that the base type's defined special operators get picked up.
    class DerivedStrange(Strange): pass
    
    obj = DerivedStrange()
    for test in allTests:
        for method,testCase in test.testCases:
            test.NegativeTest(method, testCase)
        for method,testCase in test.testCases:
            test.PositiveTest(method, testCase)
    
     
def test_bad_repr():
    # overriding a classes __repr__ and returning a
    # non-string should throw
    
    class C:
        def __repr__(self):
            return None
    
    AssertError(TypeError, repr, C())
    
    class C(object):
        def __repr__(self):
            return None
    
    AssertError(TypeError, repr, C())


############################################################
def test_name():
    """setting __name__ on a class should work"""
    
    class C(object): pass
    
    C.__name__ = 'abc'
    AreEqual(C.__name__, 'abc')

############################################################
def test_mro_super():
    """super for multiple inheritance we should follow the MRO as we go up the super chain"""
    class F:
        def meth(self):
            return 'F'
    
    class G: pass
    
    def gmeth(self): return 'G'
    
    
    class A(object):
        def meth(self):
            if hasattr(super(A, self), 'meth'):
                return 'A' + super(A, self).meth()
            else:
                return "A"
    
    class B(A):
        def __init__(self):
            self.__super = super(B, self)
            super(B, self).__init__()
        def meth(self):
            return "B" + self.__super.meth()
    
    class C(A):
        def __init__(self):
            self.__super = super(C, self)
            super(C, self).__init__()
        def meth(self):
            return "C" + self.__super.meth()
    
    class D(C, B):
        def meth(self):
            return "D" + super(D, self).meth()
    
    AreEqual(D().meth(), 'DCBA')
    
    class D(C, F, B):
        def meth(self):
            return "D" + super(D, self).meth()
    
    AreEqual(D.__mro__, (D,C,F,B,A,object))
    AreEqual(D().meth(), 'DCF')
    
    class D(C, B, F):
        def meth(self):
            return "D" + super(D, self).meth()
    
    AreEqual(D.__mro__, (D,C,B,A,object,F))
    AreEqual(D().meth(), 'DCBAF')
    
    
    class D(C, B, G):
        def meth(self):
            return "D" + super(D, self).meth()
    
    d = D()
    d.meth = type(F.meth)(gmeth, d, G)
    AreEqual(d.meth(), 'G')

############################################################
def test_slots():
    """slots tests"""
    
    # simple slots, assign, delete, etc...
    
    class foo(object):
        __slots__ = ['abc']
        
    class bar(object):
        __slots__ = 'abc'
    
    class baz(object):
        __slots__ = ('abc', )
    
    for slotType in [foo, bar, baz]:
        a = slotType()
        AssertError(AttributeError, lambda: a.abc)
        AreEqual(hasattr(a, 'abc'), False)
        
        a.abc = 'xyz'
        AreEqual(a.abc, 'xyz')
        AreEqual(hasattr(a, 'abc'), True)

        del(a.abc)
        AreEqual(hasattr(a, 'abc'), False)
        AssertError(AttributeError, lambda: a.abc)
        
        # slot classes don't have __dict__
        AreEqual(hasattr(a, '__dict__'), False)
        AssertError(AttributeError, lambda: a.__dict__)
    
    # sub-class of slots class, has no slots, has a __dict__
    class foo(object):
        __slots__ = 'abc'
        def __init__(self):
            self.abc = 23
            
    class bar(foo):
        def __init__(self):
            super(bar, self).__init__()
        
    a = bar()
    AreEqual(a.abc, 23)
    
    del(a.abc)
    AreEqual(hasattr(a, 'abc'), False)
    a.abc = 42
    AreEqual(a.abc, 42)
    
    x = a.__dict__
    AreEqual(x.has_key('abc'), False)
    a.xyz = 'abc'
    AreEqual(a.xyz, 'abc')
    
    # subclass of not-slots class defining slots:
    
    class A(object): pass
    class B(A): __slots__ = 'c'
    
    AreEqual(hasattr(B(), '__dict__'), True)
    AreEqual(hasattr(B, 'c'), True)
    
    # slots & metaclass
    if is_cli or is_silverlight:          # INCOMPATBILE: __slots__ not supported for subtype of type
        class foo(type):
            __slots__ = ['abc']
    
        class bar(object):
            __metaclass__ = foo
    
    # complex slots
    
    class foo(object):
        __slots__ = ['abc']
        def __new__(cls, *args, **kw):
            self = object.__new__(cls)
            dict = object.__getattribute__(self, '__dict__')
            return self
    
    class bar(foo): pass
    
    
    a = bar()
    
    AssertError(AttributeError, foo)
    
    # slots & name-mangling
    
    class foo(object):
        __slots__ = '__bar'
        
    AreEqual(hasattr(foo, '_foo__bar'), True)
    
    # invalid __slots__ values
    for x in ['', None, '3.5']:
        try:
            class C(object):
                __slots__ = x
            AssertUnreachable()
        except TypeError:
            pass
    
    # including __dict__ in slots allows accessing __dict__
    class A(object): __slots__ = '__dict__'
    
    AreEqual(hasattr(A(),"__dict__"), True)
    a = A()
    a.abc = 'xyz'
    AreEqual(a.abc, 'xyz')
    
    class B(A): pass
    AreEqual(hasattr(B(),"__dict__"), True)
    b = A()
    b.abc = 'xyz'
    AreEqual(b.abc, 'xyz')
    
    # including __weakref__ explicitly
    class A(object):
        __slots__ = ["__weakref__"]
    
    hasattr(A(), "__weakref__")
    
    class B(A): pass
    
    hasattr(B(), "__weakref__")
    
    # weird case, including __weakref__ and __dict__ and we allow
    # a subtype to inherit from both

    if is_cli or is_silverlight: types = [object, dict, tuple]    # INCOMPATBILE: __slots__ not supported for tuple
    else: types = [object,dict]
    
    for x in types:
        class A(x):
            __slots__ = ["__dict__"]
        
        class B(x):
            __slots__ = ["__weakref__"]
        
        class C(A,B):
            __slots__ = []
            
        a = C()
        AreEqual(hasattr(a, '__dict__'), True)
        AreEqual(hasattr(a, '__weakref__'), True)
    
        class C(A,B):
            __slots__ = ['xyz']
            
        a = C()
        AreEqual(hasattr(a, '__dict__'), True)
        AreEqual(hasattr(a, '__weakref__'), True)
        AreEqual(hasattr(C, 'xyz'), True)
    
    # calling w/ keyword args
    
    class foo(object):
        __slots__ = ['a', 'b']
        def __new__(cls, one='a', two='b'):
            self = object.__new__(cls)
            self.a = one
            self.b = two
            return self
    
    a = foo('x', two='y')
    AreEqual(a.a, 'x')
    AreEqual(a.b, 'y')
        
    # assign to __dict__
    
    class C(object): pass
    
    a = C()
    a.__dict__ = {'b':1}
    AreEqual(a.b, 1)
    
    
    # base, child define slots, grand-child doesn't
    
    class foo(object): __slots__ = ['fooSlot']
    
    class bar(foo): __slots__ = ['barSlot']
    
    class baz(bar): pass   # shouldn't throw
    
    a = baz()
    a.barSlot = 'xyz'
    a.fooSlot = 'bar'
    a.dictEntry = 'foo'
    
    AreEqual(a.barSlot, 'xyz')
    AreEqual(a.fooSlot, 'bar')
    AreEqual(a.dictEntry, 'foo')
    
    # large number of slots works (nested tuple slots)
    class foo(object):
        __slots__ = [ 'a' + str(x) for x in range(256) ]
        
    a = foo()
    
    for x in range(256):
        setattr(a, 'a' + str(x), x)
        
    for x in range(256):
        AreEqual(x, getattr(a, 'a' + str(x)))


    # new-style / old-style mixed with slots, slots take precedence
    class foo:
        abc = 3

    class bar(object):
        __slots__ = ['abc']
        def __init__(self): self.abc = 5

    class bar2(object):
        abc = 5

    class baz(foo, bar): pass
    
    class baz2(foo, bar2): pass

    AreEqual(baz().abc, 5)
    
    # but if it's just a class member we respect MRO
    AreEqual(baz2().abc, 3)
    
    # getattr and __slots__ should mix well
    class Foo(object):
        __slots__ = ['bar']
        def __getattr__(self, name):
                return name.upper()
    
    AreEqual(Foo().bar, 'BAR')
    
    # slot takes precedence over dictionary member
    class Foo(object):
        __slots__ = ['bar', '__dict__']

    a = Foo()
    a.__dict__['bar'] = 'abc'
    AssertError(AttributeError, lambda : a.bar)

    # members defined the class take precedence over slots
    global initCalled
    class Foo(object):
        __slots__ = ["__init__"]
        def __init__(self):
            global initCalled
            initCalled = True
    
    initCalled = False
    a = Foo()
    AreEqual(initCalled, True)
    
    # the member is readonly because the member slot is gone.
    def f(): a.__init__ = 'abc'
    AssertError(AttributeError, f)
    
    # make sure __init__ isn't special
    class Foo(object):
        __slots__ = ["abc"]
        abc = 3
        
    a = Foo()
    AreEqual(a.abc, 3)
    
    def f(): a.abc = 'abc'
    AssertError(AttributeError, f)

    class Foo(object): __slots__ = 'abc'
    
    AreEqual(repr(Foo.abc), "<member 'abc' of 'Foo' objects>")
    AreEqual(str(Foo.abc), "<member 'abc' of 'Foo' objects>")
    AssertErrorWithPartialMessage(AttributeError, 'abc', lambda: Foo().abc)    
    
    # again w/ empty __slots__ in C1 (409720)
    class C1(object): 
        __slots__ = []

    class C2(object):
        __slots__ = ['a']    
    
    class D1(C1, C2): pass
    
    # name mangling, slots, and classes which start with __
    class __NameStartsWithUnderscore(object):
        __slots__ = [ '__a' ]
        def __init__(self): self.__a = 'a'
        def geta(self): return self.__a
    
    s = __NameStartsWithUnderscore()
    AreEqual(s.geta(), 'a')
    
def test_slots11457():
    class COld:
        __slots__ = ['a']

    class CNew(object):
        __slots__ = ['a']
        
    for C in [COld, CNew]:
        for i in xrange(2):
            setattr(C, 'a', 5)
            AreEqual(C().a, 5)
            
            setattr(C, 'a', 7)
            AreEqual(C().a, 7)
    
############################################################
def test_inheritance_cycle():
    """test for inheritance cycle"""
    class CycleA: pass
    class CycleB: pass
    
    try:
      CycleA.__bases__ = (CycleA,)
      AssertUnreachable()
    except TypeError: pass
    
    try:
      CycleA.__bases__ = (CycleB,)
      CycleB.__bases__ = (CycleA,)
      AssertUnreachable()
    except TypeError: pass

############################################################
def test_hexoct():
    """returning non-string from hex & oct should throw"""
    
    class foo(object):
        def __hex__(self): return self
        def __oct__(self): return self
        
    class bar:
        def __hex__(self): return self
        def __oct__(self): return self
        
    AssertError(TypeError, hex, foo())
    AssertError(TypeError, oct, foo())
    AssertError(TypeError, hex, bar())
    AssertError(TypeError, oct, bar())

@skip("multiple_execute")
def test_no_clr_attributes():
    """verify types have no CLR attributes"""
    # list, 
    class x: pass
    
    for stuff in [object, int, float, bool, str, long, complex, dict, set, 
                  None, NotImplemented, Ellipsis, type(test_no_clr_attributes),
                  classmethod, staticmethod, frozenset, property, sys, 
                  BaseException, type(zip), slice, buffer, enumerate, file,
                  range, xrange, type(x), type(x())]:
        for dir_stuff in dir(stuff):
            if dir_stuff[:1].isalpha():
                Assert(dir_stuff[:1].islower(),
                       "%s should not be an attribute of %s" % (dir_stuff, str(stuff)))

def test_method_correct_name():
    # __str__ is an InstanceOps method (ToStringMethod), but we should 
    # report the proper name in __str__
    Assert(repr(BaseException.__str__).find('__str__') != -1)

@skip("multiple_execute")
def test_no_clr_attributes_sanity():
    AreEqual(hasattr(int, 'MaxValue'), False)
    AreEqual(hasattr(int, 'MinValue'), False)
    AreEqual(hasattr(int, 'Abs'), False)
    AreEqual(hasattr(int, 'BitwiseOr'), False)
    AreEqual(hasattr(int, 'Equals'), False)
    
    AreEqual(hasattr(str, 'Empty'), False)
    AreEqual(hasattr(str, 'Compare'), False)
    AreEqual(hasattr(str, 'Equals'), False)
    AreEqual(hasattr(str, 'IndexOf'), False)

############################################################
def test_outer_scope():
    """do not automatically include outer scopes in closure scenarios"""
    def outer_scope_test():
        class Referenced:
            pass
        class C:
            if Referenced: pass
        Assert("Referenced" not in C.__dict__.keys())
    
    outer_scope_test()
    
    
    for x in [None, 'abc', 3]:
        class foo(object): pass
        a = foo()
        try:
            a.__dict__ = x
            AssertUnreachable()
        except TypeError: pass

def test_default_new_init():
    """test cases to verify we do the right thing for the default new & init
    methods"""

    anyInitList = [
                   int,
                   long,
                   float,
                   complex,
                   tuple,
                  ]
    anyNewList  = [list,        # classes that take any set of args to __new__
                   set,
                   ]
            
    AssertError(TypeError, object().__init__, 1, 2, 3)
    for x in anyInitList:
        x().__init__(1, 2, 3)
            
        AssertError(TypeError, x.__new__, x, 1, 2, 3)
        AreEqual(isinstance(x.__new__(x), x), True)
    
    for x in anyNewList:
        AreEqual(len(x.__new__(x, 1, 2, 3)), 0)
        AssertError(TypeError, x.__new__(x).__init__, 1, 2, 3)


    
    class foo(object): pass
    
    AssertError(TypeError, foo, 1)
    
    class foo(list): pass
    AreEqual(list.__new__(list, sequence='abc'), [])
    
    x = list.__new__(foo, 1, 2, 3)
    AreEqual(len(x), 0)
    AreEqual(type(x), foo)
    
    
    # define only __init__.  __new__ should be the same object
    # for both types, and calling it w/ different types should have
    # different responses.
    class foo(object):
        def __init__(self): pass
                
    AreEqual(id(foo.__new__), id(object.__new__))
    
    AssertError(TypeError, object.__new__, object, 1,2,3)
    AreEqual(type(object.__new__(foo, 1, 2, 3)), foo)

    # inheritance / mutating class hierarchy tests
    
    # overrides __new__ w/ object.__new__
    class x(object):
        __new__ = object.__new__

    AssertError(TypeError, x().__init__, 2)

    # inherits __new__, overrides w/ default __new__
    class x(object):
        def __new__(cls, *args):
            return object.__new__(cls)
    
    class y(x):
        __new__ = object.__new__
    
    AreEqual(y().__init__(2), None)
    
    # then deletes the base __new__
    del x.__new__
    AreEqual(y().__init__(2), None)
    
    # then deletes y.__new__
    del y.__new__
    AreEqual(y().__init__(2), None)

    # dynamically add __new__
    class x(object): pass
    
    x.__new__ = staticmethod(lambda cls : object.__new__(x))
    
    AreEqual(x().__init__(2), None)
    
    # __init__ versions
    # overrides __init__ w/ object.__init__
    class x(object):
        __init__ = object.__init__

    AssertError(TypeError, x, 2)

    # inherits __init__, overrides w/ default __init__
    class x(object):
        def __init__(cls, *args):
            return object.__init__(cls)
    
    class y(x):
        __init__ = object.__init__
    
    AssertError(TypeError, y, 2)
    
    # then deletes the base __init__
    del x.__init__
    AssertError(TypeError, y, 2)
    
    # then deletes y.__init__
    del y.__init__
    AssertError(TypeError, y, 2)

    # dynamically add __init__
    class x(object): pass
    
    x.__init__ = staticmethod(lambda cls : object.__init__(x))
    
    x(2)
    
    # switching bases doesn't change it either
    class x(object):
        def __new__(cls, *args):
            return object.__new__(cls)
    
    class z(object): pass
    
    class y(x):
        pass
    
    AreEqual(y().__init__(2), None)
    y.__bases__ = (z, )
    AreEqual(y().__init__(2), None)

def test_hash():
    for x in [tuple, str, unicode, object, frozenset]:
        inst = x()
        AreEqual(inst.__hash__(), hash(inst))
        
    # old style hash can return longs, the result of which is
    # the hash of the long
    class foo:
        def __hash__(self): return 1<<35L

    if not is_net40: #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=24550
        AreEqual(hash(foo()), 8)

def test_NoneSelf():
    try:
        set.add(None)
        AssertUnreachable()
    except TypeError:
        pass

def test_builtin_classmethod():
    descr = dict.__dict__["fromkeys"]
    AssertError(TypeError, descr.__get__, 42)
    AssertError(TypeError, descr.__get__, None, 42)
    AssertError(TypeError, descr.__get__, None, int)

def test_classmethod():
    if is_ironpython: #http://ironpython.codeplex.com/workitem/27908
        AssertError(TypeError, classmethod, 1)
    else:
        cm = classmethod(1)
        AssertError(TypeError, cm.__get__, None)
        AssertError(TypeError, cm.__get__, None, None)

    def foo(): pass
        
    cm = classmethod(foo)
    AssertError(TypeError, cm.__get__, None)
    AssertError(TypeError, cm.__get__, None, None)
        

def test_EmptyTypes():
    for x in [None, Ellipsis, NotImplemented]:
        Assert(type(x) != str)
        
    AreEqual(repr(Ellipsis), 'Ellipsis')
    AreEqual(repr(NotImplemented), 'NotImplemented')
    AreEqual(repr(type(Ellipsis)), "<type 'ellipsis'>")
    AreEqual(repr(type(NotImplemented)), "<type 'NotImplementedType'>")
    
def test_property():
    prop = property()
    try: prop.fget = test_classmethod
    except TypeError: pass
    else: AssertUnreachable()
    
    try: prop.fdel = test_classmethod
    except TypeError: pass
    else: AssertUnreachable()
    
    try: prop.__doc__ = 'abc'
    except TypeError: pass
    else: AssertUnreachable()
    
    try: prop.fset = test_classmethod
    except TypeError: pass
    else: AssertUnreachable()
    
@skip("win32")
def test_override_mro():
    try:
        class C(object):
            def __mro__(self): pass
    except NotImplementedError: pass
    else: Fail("Expected NotImplementedError, got none")
        
    class C(object):
        def mro(self): pass
    
    try:
        class C(type):
            def mro(self): pass
    except NotImplementedError: pass
    else: Fail("Expected NotImplementedError, got none")
    
    class D(type): pass
        
    try:
        class E(D):
            def mro(self): pass
    except NotImplementedError: pass
    else: Fail("Expected NotImplementedError, got none")

def test_type_mro():
    AssertError(TypeError, type.mro)
    AreEqual(object.mro(), list(object.__mro__))
    AreEqual(type(object.mro()), list)
    AreEqual(type(object.__mro__), tuple)

def test_derived_tuple_eq():
    # verify overriding __eq__ on tuple still allows us to call the super version
    class bazbar(tuple):
        def __eq__(self,other):
            other = bazbar(other)
            return super(bazbar,self).__eq__(other)
    AreEqual(bazbar('abc'), 'abc')
    
def test_new_old_slots():
    class N(object): pass
    class O: pass
    class C(N, O):
        __slots__ = ['a','b']


def test_slots_counter():
    import gc
    class Counter(object):
        c = 0
        def __init__(self):
            Counter.c += 1
        def __del__(self):
            Counter.c -= 1
    def testit():
        class C(object):
            __slots__ = ['a', 'b', 'c']
    
        x = C()
        x.a = Counter()
        x.b = Counter()
        x.c = Counter()
    
        AreEqual(Counter.c, 3)
        del x
    
    testit()
    #collect not defined for silverlight
    if not is_silverlight:
        gc.collect()
        AreEqual(Counter.c, 0)

def test_override_container_contains():
    for x in (dict, list, tuple):
        class C(x):
            def __contains__(self, other):
                return other == "abc"
                
        AreEqual('abc' in C(), True)

def test_override_container_len():
    for x in (dict, list, tuple):
        class C(x):
            def __len__(self): return 2
        
        AreEqual(C().__len__(), 2)
        AreEqual(len(C()), 2)
        
        AreEqual(C(), x())
        
        if x is dict:
            AreEqual(C({1:1}), {1:1})
            d = {1:1, 2:2, 3:3}
            AreEqual(C(d).__cmp__({0:0, 1:1, 2:2}), 1)
            d[4] = 4
            AreEqual(len(list(C(d).iterkeys())), len(list(d.iterkeys())))
        else:
            AreEqual(C([1]), x([1]))
            a = range(4)
            AreEqual(len(list(iter(C(a)))), len(list(iter(x(a)))))

@skip("multiple_execute") #http://www.codeplex.com/IronPython/WorkItem/View.aspx?WorkItemId=17551        
def test_dictproxy_access():
    def f():
        int.__dict__[0] = 0
        
    AssertError(TypeError, f)
    
    class KOld: pass
    class KNew(object): pass
    
    #CodePlex 16001
    AreEqual(int.__dict__.get(0, 'abc'), 'abc')
    AreEqual(int.__dict__.get('__new__'), int.__new__)
    AreEqual(KOld.__dict__.get(0, 'abc'), 'abc')
    AreEqual(KNew.__dict__.get(0, 'abc'), 'abc')
    AreEqual(KNew.__dict__.get('__new__'), None)
    #CodePlex 15702
    AreEqual(int.__dict__.copy(), dict(int.__dict__))
    AreEqual(int.__class__.__dict__.copy(), dict(int.__class__.__dict__))
    AreEqual(KOld.__dict__.copy(), dict(KOld.__dict__))
    AreEqual(KNew.__dict__.copy(), dict(KNew.__dict__))
    #Dev10 4844754
    AreEqual(KNew.__class__.__dict__.copy(), dict(KNew.__class__.__dict__))
    
    AreEqual(set(KNew.__dict__.iteritems()), set(dict(KNew.__dict__).iteritems()))
    AreEqual(set(KNew.__dict__.iterkeys()), set(dict(KNew.__dict__).iterkeys()))
    AreEqual(set(KNew.__dict__.itervalues()), set(dict(KNew.__dict__).itervalues()))
    
    for value in [None, 'abc', 1, object(), KNew(), KOld(), KNew, KOld, property(lambda x: x)]:
        class KNew(object):
            abc = value
            
        AreEqual(KNew.__dict__['abc'], value)
        AreEqual(KNew.__dict__.get('abc'), value)
        AreEqual(KNew.__dict__.get('abc', value), value)
        for items in KNew.__dict__.iteritems(), KNew.__dict__.items(), zip(KNew.__dict__.keys(), KNew.__dict__.values()):
            for k, v in items:
                if k == 'abc':
                    AreEqual(v, value)

# tests w/ special requirements that can't be run in methods..
#Testing the class attributes backed by globals
    
x = 10

class C:
    x = x
    del x
    x = x
    
AreEqual(C.x, 10)
AreEqual(x, 10)

try:
    class C:
        x = x
        del x
        del x
except NameError:
    pass
else:
    Assert("Expecting name error")

AreEqual(x, 10)

class C:
    x = 10
    del x
    b = x
    AreEqual(x, 10)

AreEqual(C.b, 10)
AreEqual(x, 10)

def test_getattribute_getattr():
    # verify object.__getattribute__(name) will call __getattr__
    class Base(object):
        def __getattribute__(self, name):
            return object.__getattribute__(self, name)
    
    class Derived(Base):
        def __getattr__(self, name):
            if name == "bar": return 23
            raise AttributeError(name)
        def __getattribute__(self, name):
            return Base.__getattribute__(self, name)
    
    a = Derived()
    AreEqual(a.bar, 23)

    # getattr doesn't get called when calling object.__getattribute__
    class x(object):
        def __getattr__(self, name): return 23

    AssertError(AttributeError, object.__getattribute__, x(), 'abc')

    # verify __getattr__ gets called after __getattribute__ fails, not
    # during the base call to object.
    state = []
    class Derived(object):
        def __getattr__(self, name):
            if name == "bar":
                AreEqual(state, [])
                return 23
            raise AttributeError(name)
        def __getattribute__(self, name):
            try:
                state.append('getattribute')
                return object.__getattribute__(self, name)
            finally:
                AreEqual(state.pop(), 'getattribute')

    a = Derived()
    AreEqual(a.bar, 23)

def test_dynamic_getattribute_getattr():
    class Base(object):
        pass 
    
    def __getattribute__(self, name):
        return object.__getattribute__(self, name)
    
    Base.__getattribute__ = __getattribute__
    
    class Derived(Base):
        pass
    
    def __getattr__(self, name):
        if name == "bar":
            return 23
        raise AttributeError(name)
    
     
    Derived.__getattr__ = __getattr__
    
    def __getattribute__(self, name):
        return Base.__getattribute__(self, name)
    
    Derived.__getattribute__ = __getattribute__
    
    a = Derived()
    AreEqual(a.bar, 23)

def test_setattr():
    # verify defining __setattr__ works
    global setCalled
    
    class KNew(object):
        def __setattr__(self, name, value):
            global setCalled
            setCalled = True
            object.__setattr__(self, name, value)
            
    class KOld:
        def __setattr__(self, name, value):
            global setCalled
            setCalled = True
            self.__dict__[name] = value

    class KNewSub(KNew): pass
    
    class KOldSub(KOld): pass

    for K in [  KOld,
                KOldSub, #CodePlex 8018
                KNew,
                KNewSub]:
        setCalled = False
        x = K()
        x.abc = 23
        AreEqual(x.abc, 23)
        AreEqual(setCalled, True)

def test_dynamic_getattribute():
    # verify adding / removing __getattribute__ succeeds
    
    # remove
    class foo(object):
        def __getattribute__(self, name):
            raise Exception()
    
    class bar(foo):
        def __getattribute__(self, name):
            return super(bar, self).__getattribute__(name)
    
    del foo.__getattribute__
    a = bar()
    a.xyz = 'abc'
    AreEqual(a.xyz, 'abc')
    
    # add
    class foo(object): pass

    def getattr(self, name):
        if name == 'abc': return 42
    
    foo.__getattribute__ = getattr
    
    AreEqual(foo().abc, 42)

def test_nonstring_name():
    global __name__
    
    name = __name__
    try:
        __name__ = 3
        class C: pass
        
        AreEqual(C.__module__, 3)

        class C(object): pass
        
        AreEqual(C.__module__, 3)
        
        class C(type): pass
        
        AreEqual(C.__module__, 3)
        
        class D(object):
            __metaclass__ = C
            
        AreEqual(D.__module__, 3)
    finally:
        __name__ = name
    
def test_dictproxy_descrs():
    # verify that we get the correct descriptors when we access the dictionary proxy directly
    class foo(object):
        xyz = 'abc'

    AreEqual(foo.__dict__['xyz'], 'abc')
    
    class foo(object):
        def __get__(self, instance, context):
            return 'abc'

    class bar(object):
        xyz = foo()

    AreEqual(bar.__dict__['xyz'].__class__, foo)

## __int__

def test_fastnew_int():
    class C1:
        def __int__(self): return 100
    class C2:
        def __int__(self): return myint(100)
    class C3:
        def __int__(self): return 100L
    class C4:
        def __int__(self): return mylong(100L)
    class C5:
        def __int__(self): return -123456789012345678910
    class C6:
        def __int__(self): return C6()
    class C7:
        def __int__(self): return "100"
    
    for x in [C1, C2, C3, C4]:   AreEqual(int(x()), 100)
    AreEqual(int(C5()), -123456789012345678910)
    for x in [C6, C7]:      AssertError(TypeError, int, x())
        
    class C1(object):
        def __int__(self): return 100
    class C2(object):
        def __int__(self): return myint(100)
    class C3(object):
        def __int__(self): return 100L
    class C4(object):
        def __int__(self): return mylong(100L)
    class C5(object):
        def __int__(self): return -123456789012345678910
    class C6(object):
        def __int__(self): return C6()
    class C7(object):
        def __int__(self): return "100"
    
    for x in [C1, C2, C3, C4]:   AreEqual(int(x()), 100)
    AreEqual(int(C5()), -123456789012345678910)
    for x in [C6, C7]:      AssertError(TypeError, int, x())


def test_type_type_is_type():
    class OS: pass
    class NS(object): pass
    
    true_values = [type, NS, int, float, tuple, str]
    if is_cli:
        import System
        true_values += [System.Boolean, System.Int32, System.Version, System.Exception]
    
    for x in true_values:
        Assert(type(x) is type)
        
    false_values = [OS]
    if is_cli:
        false_values += [ System.Boolean(1), System.Int32(3), System.Version(), System.Exception() ]
        
    for x in false_values:
        Assert(type(x) is not type)
    

def test_hash_return_values():
    # new-style classes do conversion to int
    for retval in [1, 1.0, 1.1, 1L, 1<<30]:
        for type in [object, int, str, float, long]:
            class foo(object):
                def __hash__(self): return retval
            
            AreEqual(hash(foo()), int(retval))
    
    # old-style classes require int or long return value
    for retval in [1.0, 1.1]:
        class foo:
            def __hash__(self): return retval
        
        AssertError(TypeError, hash, foo())

    tests = {   1L:1,
                2L:2,
            }
    if not is_net40: #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=24550
        tests.update( { 1<<32: 1,
                  (1<<32)+1: 2,
                  1<<34: 4,
                 1<<31: -2147483648,
                })
    for retval in tests.keys():
        class foo:
            def __hash__(self): return retval
        
        AreEqual(hash(foo()), tests[retval])

def test_cmp_notimplemented():
    class foo(object):
        def __eq__(self, other):
            ran.append('foo.eq')
            return NotImplemented
        def __ne__(self, other):
            ran.append('foo.ne')
            return NotImplemented
        def __le__(self, other):
            ran.append('foo.le')
            return NotImplemented
        def __lt__(self, other):
            ran.append('foo.lt')
            return NotImplemented
        def __gt__(self, other):
            ran.append('foo.gt')
            return NotImplemented
        def __ge__(self, other):
            ran.append('foo.ge')
            return NotImplemented
        def __cmp__(self, other):
            ran.append('foo.cmp')
            return NotImplemented
    
    
    class bar:
        def __eq__(self, other):
            ran.append('bar.eq')
            return NotImplemented
        def __ne__(self, other):
            ran.append('bar.ne')
            return NotImplemented
        def __le__(self, other):
            ran.append('bar.le')
            return NotImplemented
        def __lt__(self, other):
            ran.append('bar.lt')
            return NotImplemented
        def __gt__(self, other):
            ran.append('bar.gt')
            return NotImplemented
        def __ge__(self, other):
            ran.append('bar.ge')
            return NotImplemented
        def __cmp__(self, other):
            ran.append('bar.cmp')
            return NotImplemented

    ran = []
    cmp(foo(), bar())
    #AreEqual(ran, ['foo.eq', 'bar.eq', 'foo.lt', 'bar.gt', 'foo.gt', 'bar.lt', 'bar.cmp'])
    
    ran = []
    cmp(foo(), foo())
    #AreEqual(ran, ['foo.cmp', 'foo.cmp'])
    
    ran = []
    cmp(bar(), bar())
    #AreEqual(ran, ['bar.cmp', 'bar.cmp', 'bar.eq', 'bar.eq', 'bar.eq', 'bar.eq', 'bar.lt', 'bat.gt', 'bar.gt', 'bar.lt', 'bar.gt', 'bar.lt', 'bar.lt', 'bar.gt', 'bar.cmp', 'bar.cmp'])
    
    ran = []
    cmp(foo(), 1)
    #AreEqual(ran, ['foo.eq', 'foo.lt', 'foo.gt', 'foo.cmp'])


def test_override_repr():
    class KOld:
        def __repr__(self):
            return "old"
            
    class KNew(object):
        def __repr__(self):
            return "new"
            
    AreEqual(repr(KOld()), "old")
    AreEqual(str(KOld()), "old")
    AreEqual(repr(KNew()), "new")
    #IP breaks here because __str__ in new style classes does not call __repr__
    AreEqual(str(KNew()), "new")


def test_mutate_base():
        class basetype(object):
            xyz = 3
        
        class subtype(basetype): pass
        
        AreEqual(subtype.xyz, 3)
        AreEqual(subtype().xyz, 3)
        
        basetype.xyz = 7
        
        AreEqual(subtype.xyz, 7)
        AreEqual(subtype().xyz, 7)

def test_mixed_newstyle_oldstyle_init():
    """mixed new-style & old-style class should run init if its defined in the old-style class"""
    class foo:
        def __init__(self):
            self.x = 3
    
    class bar(foo):
        def __init__(self):
            self.x = 4
    
    class baz(foo): pass
    
    class ns(object): pass
    
    class full(bar, baz, ns): pass
    
    a = full()
    AreEqual(a.x, 4)
    
    class full(bar, baz, ns):
        def __init__(self):
            self.x = 5
    
    a = full()
    AreEqual(a.x, 5)

    class ns(object):
        def __init__(self):
            self.x = 6
    
    class full(bar, baz, ns): pass
    a = full()
    AreEqual(a.x, 4)

def test_mixed_newstyle_oldstyle_new():
    class S:
        pass
    
    class P(S, object):
        def __new__(cls, *a, **kw):
            return object.__new__(cls)
    
    AreEqual(type(P()), P)

def test_mixed_newstyle_oldstyle_descriptor():
    class base:
        @classmethod
        def f(cls):
                return cls
    
    
    class x(base, object):
        pass
    
    AreEqual(x.f(), x)

def test_getattr_exceptions():
    """verify the original exception propagates out"""
    class AttributeTest(object):
        def __getattr__(self, name): raise AttributeError('catch me')
        
    x = AttributeTest()
    try:
        y = x.throws
    except AttributeError, ex:
        AreEqual(ex.args, ('catch me',))
    else: Fail("should have thrown")

def test_descriptor_meta_magic():
    class valueDescriptor(object):
        def __init__(self,x=None): self.value = x
        def __get__(self,ob,cls):   return self.value
        def __set__(self,ob,x):     self.value = x
    
    class Ameta(type):
        def createShared( cls, nm, initValue=None ):
            o = valueDescriptor(initValue)
            setattr( cls,nm, o )
            setattr( cls.__class__,nm, o )
    
    class A:
        __metaclass__ = Ameta
    
    class B( A ):
        A.createShared("cls2",1)
    
    def test(value):
        AreEqual(o.cls2, value)
        AreEqual(o2.cls2, value)
        AreEqual(A.cls2, value)
        AreEqual(B.cls2, value)
        
    o = A()
    o2 = B()
    test(1)
        
    B.cls2 = 2
    test(2)
        
    A.cls2 = 3
    test(3)
    
    o.cls2 = 4
    test(4)
    
    o2.cls2 = 5
    test(5)

def test_missing_attr():
    class foo(object): pass
    
    a = foo()
    def f(): a.dne
    AssertErrorWithMessage(AttributeError, "'foo' object has no attribute 'dne'", f)

def test_method():
    class tst_oc:
        def root(): return 2

    class tst_nc:
        def root(): return 2

    AssertError(TypeError, tst_oc.root)
    AssertError(TypeError, tst_nc.root)
    
    instancemethod = type(tst_oc.root)
    AssertError(TypeError, instancemethod, lambda x:True, None)

def test_descriptors_custom_attrs():
    """verifies the interaction between descriptors and custom attribute access works properly"""
    class mydesc(object):
        def __get__(self, instance, ctx):
            raise AttributeError
    
    class f(object):
        x = mydesc()
        def __getattr__(self, name): return 42
    
    AreEqual(f().x, 42)

def test_cp5801():
    class Foo(object):
        __slots__ = ['bar']
        def __getattr__(self, n):
            return n.upper()
        
    foo = Foo()
    AreEqual(foo.bar, "BAR")


def test_property_always_set_descriptor():
    """verifies that set descriptors take precedence over dictionary entries and
       properties are always treated as set descriptors, even if they have no
       setter function"""
    
    class C(object):
        x = property(lambda self: self._x)
        def __init__(self):
            self._x = 42
    
    
    c = C()
    c.__dict__['x'] = 43
    AreEqual(c.x, 42)

    # now check a user get descriptor
    class MyDescriptor(object):
        def __get__(self, *args): return 42
        
    class C(object):
        x = MyDescriptor()
        
    c = C()
    c.__dict__['x'] = 43
    AreEqual(c.x, 43)
    
    # now check a user get/set descriptor
    class MyDescriptor(object):
        def __get__(self, *args): return 42
        def __set__(self, *args): pass
        
    class C(object):
        x = MyDescriptor()
        
    c = C()
    c.__dict__['x'] = 43
    AreEqual(c.x, 42)

def test_object_as_condition():
    class C(object):
        def __mod__(self, other): return 1
    o = C()
    flag = 0
    if o % o: flag = 1   # the bug was causing cast error before
    AreEqual(flag, 1)

def test_unbound_class_method():
    class C(object):
        def f(): return 1
    
    x = C()
    AssertErrorWithPartialMessage(TypeError, "unbound method f() must be called with", lambda: C.f())
    AssertErrorWithPartialMessage(TypeError, "unbound method f() must be called with", lambda: C.f(C))
    AssertErrorWithPartialMessage(TypeError, "arguments (1 given)", lambda: C.f(x))
    AssertErrorWithPartialMessage(TypeError, "arguments (1 given)", lambda: x.f())

def test_oldinstance_operator_exceptions():
    global called
    def fmaker(name, ex = None):
        def f(self, *args):
            global called
            called.append(name)
            if ex:
                raise ex(name)
            def g(*args):
                return NotImplemented
            return g
        return f

    def fthrowingmaker(name, ex):
        def f(self):
            global called
            called.append(name)
            def g(*args):
                raise ex
            return g
        return f

    class OC:
        __eq__ = property(fmaker('oc_eq', AttributeError))
        __ne__ = property(fmaker('oc_ne', AttributeError))
    
    class OC2:
        __eq__ = property(fthrowingmaker('oc_eq', AttributeError))
        __ne__ = property(fthrowingmaker('oc_ne', AttributeError))

    class OC3:
        def __getattr__(self, name):
            return property(fmaker(name, AttributeError)).__get__(self, OC3)
    
    called = []
    Assert(not OC() == OC())
    AreEqual(called, ['oc_eq']*4)
    
    called = []
    type(OC()).__eq__(OC(), OC())
    AreEqual(called, ['oc_eq']*2)
    
    called =[]
    Assert(OC() != OC())
    AreEqual(called, ['oc_ne']*4)

    called = []
    type(OC()).__ne__(OC(), OC())
    AreEqual(called, ['oc_ne']*2)


    called = []
    AssertError(AttributeError, lambda : not OC2() == OC2())
    AreEqual(called, ['oc_eq'])
    
    called = []
    AssertError(AttributeError, lambda : type(OC2()).__eq__(OC2(), OC2()))
    AreEqual(called, ['oc_eq'])
    
    called =[]
    AssertError(AttributeError, lambda : OC2() != OC2())
    AreEqual(called, ['oc_ne'])

    called = []
    AssertError(AttributeError, lambda : type(OC2()).__ne__(OC2(), OC2()))
    AreEqual(called, ['oc_ne'])
    
    called = []
    AssertError(AttributeError, lambda : type(OC()).__getattribute__(OC(), '__eq__'))
    AreEqual(called, ['oc_eq'])
    
    Assert(not hasattr(OC(), '__eq__'))

    # IronPython still differs on these from CPython:
    # verify other attributes work correctly
    #for x in ['__abs__', '__float__', '__long__', '__int__', '__hex__', '__oct__', '__pos__', '__neg__', '__invert__']:
    #    # unary operators which pass on AttributeError
    #    print x
    #    AssertError(AttributeError, getattr(type(OC3()), x), OC3())
    
    for x in ['__hash__', '__nonzero__', '__str__', '__repr__']:
        # unary operators that catch AttributeError
        getattr(type(OC3()), x)(OC3())
    
    # IronPython still differs on these from CPython:
    #for x in ['__iter__']:
    #    # unary operators that call, catch, and report another error
    #    called = []
    #    AssertError(TypeError, getattr(type(OC3()), x), OC3())
    #    Assert(x in called)
    
    for x in ['__add__', '__iadd__', '__radd__', '__cmp__', '__coerce__']:
        # binary operators catch AttributeError
        getattr(type(OC3()), x)(OC3(), OC3())
        

def test_cp10291():
    class K1(object):
        def __call__(self):
            return "K1"
    
    class K2(K1):
        def __call__(self):
            return "K2" + K1.__call__(self)

    class K1Old:
        def __call__(self):
            return "K1"
    
    class K2Old(K1Old):
        def __call__(self):
            return "K2" + K1Old.__call__(self)


    for k1, k2 in [ (K1, K2),
                    (K1Old, K2Old),
                    ]:
        AreEqual(k1()(), "K1")
        AreEqual(k2()(), "K2K1")

@skip("win32") # should be reenabled against CPython26
def test_cp11760():
    class KNew(object):
        def __str__(self): return "KNew"
    
    class KOld:
        def __str__(self): return "KOld"
    
    for K in [KNew, KOld]:
        dir_str = dir(K().__str__)
        for x in [  '__class__', '__delattr__', '__doc__',
                    '__get__', '__getattribute__', '__hash__', '__init__',
                    '__new__', '__reduce__', '__reduce_ex__', '__repr__',
                    '__setattr__', '__str__', 'im_class',
                    'im_func', '__func__', 'im_self', '__self__',
                    #'__call__', '__cmp__',
                    ]:
            Assert(x in dir_str, x + " is not in dir(K().__str__)")

def test_delattr():
    global called
    class X(object):
        def __delattr__(self, name):
            global called
            called = True
    
    del X().abc
    
    Assert(called)
  
def test_cp10709():
    class KNew(object):
        p1 = property(lambda self: 3.14)
        m1 = lambda self: 3.15
        f1 = lambda: 3.16
        def m2(self, a):
            x = lambda: 3.17
            return x()
            
    class KOld:
        p1 = property(lambda self: 3.14)
        m1 = lambda self: 3.15
        f1 = lambda: 3.16
        def m2(self, a):
            x = lambda: 3.17
            return x()
            
    for temp in dir(KNew) + dir(KNew()) + dir(KOld) + dir(KOld()):
        Assert("lambda" not in temp)
        
def test_oldstyle_fancycallable():
    class C : pass
        
    x = C(*())
    Assert(x.__class__ is C)
    x = C(**{})
    Assert(x.__class__ is C)
    x = C(*(), **{})
    Assert(x.__class__ is C)
    
    class C:
        def __init__(self, a):
            pass
    
    x = C(*(2,))
    #Merlin 382112
    x = C(*(None,))
    Assert(x.__class__ is C)
    x = C(**{'a': None})

def test_oldclass_newclass_construction():
    """calling __new__ on and old-class passing in new-classes should result in a new-style type"""
    class nc(object): pass
    
    class oc: pass
    
    newType = type(oc).__new__(type(oc), 'foo', (nc, oc), {})
    AreEqual(type(newType), type)

def test_inherited_getattribute():
    """inherited getattribute should be respected"""
    class x(object):
        def __getattribute__(self, name):
            if name == 'abc': return 42
            return object.__getattribute__(self, name)
    
    class y(x): pass

    AreEqual(y().abc, 42)

GETATTRIBUTE_CALLED = False
def test_cp13820():
    global GETATTRIBUTE_CALLED
    GETATTRIBUTE_CALLED = False
    
    class KOld:
        def __getattribute__(self, name):
            global GETATTRIBUTE_CALLED
            GETATTRIBUTE_CALLED = True
            print "__getattribute__ was called by:", name
            return 1
            
        def __init__(self):
            return
            
        def __del__(self):
            return
            
        def __str__(self): return ""
        
        def __cmp__(self, other): return 0
        
        def __hash__(self): return 1
        
        def __nonzero__(self): return 1
        
        def __get__(self, instance, owner): return 3
        
        def __delete__(self, instance): return
        
        def __len__(self): return 4
        
        def __getitem__(self, key): return 5
        
        def __setitem__(self, key, value): return
        
        def  __getslice__(self, i, j): return 6
        
        def __contains__(self, obj): return True
        
        def __add__(self, other): return 7
            
        def __hex__(self): return hex(9)
        
        def __coerce__(self, other): return None
        
        def __lt__(self, other): return True
    
    class KNew(object):
        def __getattribute__(self, name):
            global GETATTRIBUTE_CALLED
            GETATTRIBUTE_CALLED = True
            print "__getattribute__ was called by:", name
            return 1
            
        def __init__(self):
            return
            
        def __del__(self):
            return
            
        def __str__(self): return ""
        
        def __cmp__(self, other): return 0
        
        def __hash__(self): return 1
        
        def __nonzero__(self): return 1
        
        def __get__(self, instance, owner): return 3
        
        def __delete__(self, instance): return
        
        def __len__(self): return 4
        
        def __getitem__(self, key): return 5
        
        def __setitem__(self, key, value): return
        
        def  __getslice__(self, i, j): return 6
        
        def __contains__(self, obj): return True
        
        def __add__(self, other): return 7
            
        def __hex__(self): return hex(9)
        
        def __coerce__(self, other): return None
        
        def __lt__(self, other): return True
        
    for K in [KOld, KNew]:
        obj = K()
        str(obj)
        obj==3
        hash(obj)
        bool(obj)
        obj[3]
        obj[3] = 4
        len(obj)
        obj[1:3]
        if K==KOld: hasattr(obj, "abc")
        obj + 3
        hex(obj)
        obj<9
        del obj
        Assert(not GETATTRIBUTE_CALLED)

def test_keyword_type_construction():
    """using type.__call__ should accept keyword arguments"""
    class x(object):
        def __new__(cls, *args, **kwargs):
            return object.__new__(cls)
        def __init__(self, *args, **kwargs):
            for x, y in kwargs.iteritems():
                setattr(self, x, y)
            return object.__init__(self)
    
    obj = type.__call__(x, *(), **{'abc':2})
    AreEqual(obj.abc, 2)
    
    obj = x.__call__(*(), **{'abc':3})
    AreEqual(obj.abc, 3)

def test_mixed_mro_respected():
    """creates a class with an mro of "MC, NC, OC2, NC2, object, OC" and verifies that we get NC2 member, not OC"""
    class OC:
        abc = 3
    
    class OC2(OC):
        pass
    
    class NC(object):
        pass
    
    class NC2(object):
        abc = 5
    
    class MC(NC, OC2, NC2, OC): pass
    
    AreEqual(MC.abc, 5)

def test_descriptor_object_getattribute_interactions():
    class nondata_desc(object):
        def __init__(self, value): self.value = value
        def __get__(self, inst, ctx = None):
            return (self.value, inst, ctx)
    
    class data_desc(object):
        def __init__(self, value): self.value = value
        def __get__(self, inst, ctx = None):
            return (self.value, inst, ctx)
        def __set__(self, inst, value):
            self.value = value
        def __delete__(self, inst):
            del self.value
    
    class readonly_data_desc(object):
        def __init__(self, value): self.value = value
        def __get__(self, inst, ctx = None):
            return (self.value, inst, ctx)
        def __set__(self, inst, value):
            raise AttributeError()
        def __delete__(self, inst):
            raise AttributeError()
    
    class meta(type):
        nondata = nondata_desc(1)
        data = data_desc(2)
        nondata_shadowed_class = nondata_desc(3)
        data_shadowed_class = data_desc(4)
        nondata_shadowed_inst = nondata_desc(5)
        data_shadowed_inst = data_desc(6)
        ro_data = readonly_data_desc(7)
        ro_shadowed_class = readonly_data_desc(8)
        ro_shadowed_inst = readonly_data_desc(9)
    
    class x(object):
        __metaclass__ = meta
        def __init__(self):
            self.nondata_shadowed_inst = "nondata_inst"
            self.data_shadowed_inst = "data_inst"
            self.ro_shadowed_inst = 'ro_inst'
        nondata_shadowed_class = 'nondata_shadowed_class'
        data_shadowed_class = 'data_shadowed_class'
        ro_shadowed_class = 'ro_shadowed_class'
        
    a = x()
    AssertError(AttributeError, object.__getattribute__, a, 'nondata')
    AssertError(AttributeError, object.__getattribute__, a, 'data')
    AssertError(AttributeError, object.__getattribute__, a, 'ro_data')
    
    AreEqual(object.__getattribute__(a, 'nondata_shadowed_class'), 'nondata_shadowed_class')
    AreEqual(object.__getattribute__(a, 'data_shadowed_class'), 'data_shadowed_class')
    AreEqual(object.__getattribute__(a, 'ro_shadowed_class'), 'ro_shadowed_class')
    
    AreEqual(object.__getattribute__(a, 'nondata_shadowed_inst'), 'nondata_inst')
    AreEqual(object.__getattribute__(a, 'data_shadowed_inst'), 'data_inst')
    AreEqual(object.__getattribute__(a, 'ro_shadowed_inst'), 'ro_inst')
    
    AreEqual(object.__getattribute__(x, 'nondata_shadowed_class'), 'nondata_shadowed_class')
    AreEqual(object.__getattribute__(x, 'data_shadowed_class'), (4, x, meta))
    AreEqual(object.__getattribute__(x, 'ro_shadowed_class'), (8, x, meta))
    
    AreEqual(object.__getattribute__(x, 'nondata_shadowed_inst'), (5, x, meta))
    AreEqual(object.__getattribute__(x, 'data_shadowed_inst'), (6, x, meta))
    AreEqual(object.__getattribute__(x, 'ro_shadowed_inst'), (9, x, meta))

    AreEqual(object.__getattribute__(x, 'ro_data'), (7, x, meta))
    AreEqual(object.__getattribute__(x, 'nondata'), (1, x, meta))
    AreEqual(object.__getattribute__(x, 'data'), (2, x, meta))

def test_cp5803():

    #--Simple
    class KSimple(object):
        def __radd__(self, other):
            return
            
    for x in ["", 1, 3.14, None, u"stuff", object, KSimple]:
        AreEqual(x + KSimple(), None)
    AssertErrorWithPartialMessage(TypeError,
                                  "unsupported operand type(s) for +: 'KSimple' and 'str'",
                                  lambda: KSimple() + "")

    #--Addition
    class K(object): pass

    class K0(object):
        def __radd__(self, other):
            return "__radd__:" + str(type(self)) + " " + str(type(other))

    class K1(object):
        def __radd__(self, other):
            return "__radd__:" + str(type(self)) + " " + str(type(other))
            
        def __add__(self, other):
            return "__add__:" + str(type(self)) + " " + str(type(other))
    
    AssertErrorWithMessage(TypeError, "unsupported operand type(s) for +: 'K' and 'K'", lambda: K() + K())
    AreEqual(K() + K0(), "__radd__:<class '" + __name__ + ".K0'> <class '" + __name__ + ".K'>")
    AreEqual(K() + K1(), "__radd__:<class '" + __name__ + ".K1'> <class '" + __name__ + ".K'>")
    
    AssertErrorWithMessage(TypeError, "unsupported operand type(s) for +: 'K0' and 'K'", lambda: K0() + K())
    AssertErrorWithMessage(TypeError, "unsupported operand type(s) for +: 'K0' and 'K0'", lambda: K0() + K0())
    AreEqual(K0() + K1(), "__radd__:<class '" + __name__ + ".K1'> <class '" + __name__ + ".K0'>")

    AreEqual(K1() + K(),  "__add__:<class '" + __name__ + ".K1'> <class '" + __name__ + ".K'>")
    AreEqual(K1() + K0(), "__add__:<class '" + __name__ + ".K1'> <class '" + __name__ + ".K0'>")
    AreEqual(K1() + K1(), "__add__:<class '" + __name__ + ".K1'> <class '" + __name__ + ".K1'>" )
    
    #--Subtraction
    class K(object): pass

    class K0(object):
        def __rsub__(self, other):
            return "__rsub__:" + str(type(self)) + " " + str(type(other))

    class K1(object):
        def __rsub__(self, other):
            return "__rsub__:" + str(type(self)) + " " + str(type(other))
            
        def __sub__(self, other):
            return "__sub__:" + str(type(self)) + " " + str(type(other))
    
    AssertErrorWithMessage(TypeError, "unsupported operand type(s) for -: 'K' and 'K'", lambda: K() - K())
    AreEqual(K() - K0(), "__rsub__:<class '" + __name__ + ".K0'> <class '" + __name__ + ".K'>")
    AreEqual(K() - K1(), "__rsub__:<class '" + __name__ + ".K1'> <class '" + __name__ + ".K'>")
    
    AssertErrorWithMessage(TypeError, "unsupported operand type(s) for -: 'K0' and 'K'", lambda: K0() - K())
    AssertErrorWithMessage(TypeError, "unsupported operand type(s) for -: 'K0' and 'K0'", lambda: K0() - K0())
    AreEqual(K0() - K1(), "__rsub__:<class '" + __name__ + ".K1'> <class '" + __name__ + ".K0'>")

    AreEqual(K1() - K(),  "__sub__:<class '" + __name__ + ".K1'> <class '" + __name__ + ".K'>")
    AreEqual(K1() - K0(), "__sub__:<class '" + __name__ + ".K1'> <class '" + __name__ + ".K0'>")
    AreEqual(K1() - K1(), "__sub__:<class '" + __name__ + ".K1'> <class '" + __name__ + ".K1'>" )

    #--Old style
    class K: pass

    class K0:
        def __radd__(self, other):
            return "__radd__:" + str(type(self)) + " " + str(type(other))

    class K1:
        def __radd__(self, other):
            return "__radd__:" + str(type(self)) + " " + str(type(other))
            
        def __add__(self, other):
            return "__add__:" + str(type(self)) + " " + str(type(other))
    
    AssertError(TypeError, lambda: K() + K())
    AreEqual(K() + K0(), "__radd__:<type 'instance'> <type 'instance'>")
    AreEqual(K() + K1(), "__radd__:<type 'instance'> <type 'instance'>")
    
    AssertError(TypeError, lambda: K0() + K())
    AreEqual(K0() + K0(), "__radd__:<type 'instance'> <type 'instance'>")
    AreEqual(K0() + K1(), "__radd__:<type 'instance'> <type 'instance'>")

    AreEqual(K1() + K(),  "__add__:<type 'instance'> <type 'instance'>")
    AreEqual(K1() + K0(), "__add__:<type 'instance'> <type 'instance'>")
    AreEqual(K1() + K1(), "__add__:<type 'instance'> <type 'instance'>")

def test_special_type_attributes():
    # some attributes on new-style class are alwayed retrieved
    # from the type, not the classes dictionary
    class x(object):
        __dict__ = 'abc'
        __class__ = 'abc'
        __bases__ = 'abc'
        __name__ = 'abc'
        
    class y(object): pass
    
    AreEqual(type(x.__dict__), type(y.__dict__))
    AreEqual(x.__class__, type)
    AreEqual(x.__bases__, (object, ))
    AreEqual(x.__name__, 'x')


def test_issubclass():
    # first argument doesn't need to be new-style or old-style class if it defines __bases__
    class C(object):
        def __getattribute__(self, name):
            if name == "__bases__": return (object, )
            return object.__getattribute__(self, name)
    
    class S(object):
        def __getattribute__(self, name):
            if name == "__bases__": return (x, )
            return C.__getattribute__(self, name)
    
    x = C()
    AreEqual(issubclass(S(), x), True)
    AreEqual(issubclass(S(), (x, )), True)

    # if arg 1 doesn't have __bases__ a TypeError is raised
    class S(object):
        pass 
    
    x = C()
    AssertErrorWithMessage(TypeError, "issubclass() arg 1 must be a class", issubclass, S(), x)
    AssertErrorWithMessage(TypeError, "issubclass() arg 1 must be a class", issubclass, S(), (x, ))
   
    # arg 1 __bases__ must be a tuple
    for arg1 in [[2, 3, 4], 23, 'abc']:
        class S(object):
            def __getattribute__(self, name):
                if name == "__bases__": return arg1
                return C.__getattribute__(self, name)
        AssertErrorWithMessage(TypeError, "issubclass() arg 1 must be a class", issubclass, S(), x)
        AssertErrorWithMessage(TypeError, "issubclass() arg 1 must be a class", issubclass, S(), (x, ))


    # recursively check members returned from __bases__
    class S(object):
        def __getattribute__(self, name):
            if name == "__bases__": return (y, )
            return C.__getattribute__(self, name)
    
    class A(object):
        def __getattribute__(self, name):
            if name == "__bases__": return (x, )
            return C.__getattribute__(self, name)
    
    y = A()
    AreEqual(issubclass(S(), x), True)
    AreEqual(issubclass(S(), (x, )), True)
    
    # but ignore members that don't have __bases__ themselves, don't raise a TypeError
    class S(object):
        def __getattribute__(self, name):
            if name == "__bases__": return (123, )
            return C.__getattribute__(self, name)
    
    AreEqual(issubclass(S(), x), False)
    AreEqual(issubclass(S(), (x, )), False)

    # if __bases__ returns a type we should fallback into subclass(type, typeinfo)
    class C(object):
        def __getattribute__(self, name):
            if name == "__bases__": return (int, )
            return object.__getattribute__(self, name)

    AreEqual(issubclass(C(), object), True)
    AreEqual(issubclass(C(), (object, )), True)
    
    # if __bases__ returns an old-class we should fallback into subclass(oc, typeinfo)
    class OC1: pass
    
    class OC2(OC1): pass
    
    class C(object):
        def __getattribute__(self, name):
            if name == "__bases__": return (OC2, )
            return object.__getattribute__(self, name)

    AreEqual(issubclass(C(), OC1), True)
    AreEqual(issubclass(C(), (OC1, )), True)
    
    # raising an exception from __bases__ propagates out
    
    class C(object):
        def getbases(self):
        	raise RuntimeError
        __bases__ = property(getbases)

    class S(C): pass

    AssertError(RuntimeError, issubclass, C(), S())

    reclimit = sys.getrecursionlimit()
    if reclimit == sys.maxint:
        sys.setrecursionlimit(1001)
        
    # Make sure that calling isinstance with a deeply nested tuple for its
    # argument will raise RuntimeError eventually.
    def blowstack(fxn, arg, compare_to):
        tuple_arg = (compare_to,)
        for cnt in xrange(sys.getrecursionlimit()+5):
            tuple_arg = (tuple_arg,)
            fxn(arg, tuple_arg)
    
    AssertError(RuntimeError, blowstack, issubclass, str, str)

    sys.setrecursionlimit(reclimit)

def test_isinstance_recursion():
    reclimit = sys.getrecursionlimit()
    if reclimit == sys.maxint:
        sys.setrecursionlimit(1001)

    # Make sure that calling isinstance with a deeply nested tuple for its
    # argument will raise RuntimeError eventually.
    def blowstack(fxn, arg, compare_to):
        tuple_arg = (compare_to,)
        for cnt in xrange(sys.getrecursionlimit()+5):
            tuple_arg = (tuple_arg,)
            fxn(arg, tuple_arg)
    
    AssertError(RuntimeError, blowstack, isinstance, '', str)

    sys.setrecursionlimit(reclimit)

def test_call_recursion():
    reclimit = sys.getrecursionlimit()
    if reclimit == sys.maxint:
        sys.setrecursionlimit(1001)
    
    class A(object): pass

    A.__call__ = A()
    AssertError(RuntimeError, A())
    sys.setrecursionlimit(reclimit)
    
def test_metaclass_base_search():
    class MetaClass(type):
        def __init__(cls, clsname, bases, dict):
            setattr(cls, "attr_%s" % clsname, "attribute set on %s by MetaClass" % clsname)
            super(MetaClass, cls).__init__(clsname, bases, dict)
    
    class Mixin(object):
        __metaclass__ = MetaClass
    
    class Parent(object):
        pass
    
    class Child(Parent, Mixin):
        pass
        
    AreEqual(Child.attr_Child, 'attribute set on Child by MetaClass')

def test_binary_operator_subclass():
    """subclassing but not overriding shouldn't call __radd__"""
    class A(object):
        def __add__(self, other):
            return ('a', self.__class__.__name__)
        __radd__ = __add__
    
    class B(A):
        def __add__(self, other):
            return ('b', self.__class__.__name__)
        __radd__ = __add__
    
    class C(A): pass
        
    a = A()
    b = B()
    c = C()
    AreEqual(a + b, ('b', 'B'))
    AreEqual(a + c, ('a', 'A'))

def test_cp2021():
    class KOld:
        def __rmul__(self, other):
            return 7
    
    class KNew(object):
        def __rmul__(self, other):
            return 7
    
    for testdata in [[], [1], [1,2]]:
        AreEqual(testdata * KOld(), 7)
        AreEqual(testdata * KNew(), 7)
        AssertErrorWithMessage(TypeError, "object cannot be interpreted as an index",
                               testdata.__mul__, KOld())
        AssertErrorWithMessage(TypeError, "'KNew' object cannot be interpreted as an index",
                               testdata.__mul__, KNew())

def test_redundant_multiple_bases():
    """specifying an extra base which is implied by a previous one should work ok"""
    class Foo(list, object):
        pass

    class Bar(Foo):
        pass
        
    AreEqual(Bar(), [])

def test_metaclass_keyword_args():
    class MetaType(type):
       def __init__(cls, name, bases, dict):
          super(MetaType, cls).__init__(name, bases, dict)
    
    class Base(object):
        __metaclass__ = MetaType
    
    class A(Base):
        def __init__(self, a, b='b', c=12, d=None, e=None):
            self.d = d
            self.b = b
    
    a = A('empty', *(), **{'d': 'boom'})
    AreEqual(a.d, 'boom')

    a = A('empty', *('foo', ), **{'d': 'boom'})
    AreEqual(a.b, 'foo')
    AreEqual(a.d, 'boom')

def test_oldinstance_creation():
    class C: pass
    
    inst = type(C())
    
    d = {'a': 2}
    i = inst(C, d)
    
    AreEqual(id(d), id(i.__dict__))
    Assert(isinstance(i, C))

    x = inst(C, None)
    AreEqual(x.__dict__, {})
    
def test_metaclass_getattribute():
    class mc(type):
        def __getattr__(self, name):
            return 42
    
    class nc_ga(object):
        __metaclass__ = mc
        
    AreEqual(nc_ga.x, 42)

def test_method_call():
    class K(object):
        def m(self, *args, **kwargs): 
            return args, kwargs
    
    AreEqual(K().m.__call__(), ((), {}))
    AreEqual(K().m.__call__(42), ((42, ), {}))
    AreEqual(K().m.__call__(42, x = 23), ((42, ), {'x': 23}))
    
    Assert('__call__' in dir(K().m))
    
    
def test_metaclass_multiple_bases():
    global log
    log = []
    class C(object): pass
    
    class MT1(type):
        def __new__(cls, name, bases, dict):
            log.append('MT1')
            return super(MT1, cls).__new__(cls, name, bases, dict)
    
    class D(object):
        __metaclass__ = MT1
    
    AreEqual(log, ['MT1'])
    
    class MT2(type):
        def __new__(cls, name, bases, dict):
            log.append('MT2')
            return super(MT2, cls).__new__(cls, name, bases, dict)
    
    class E(object):
        __metaclass__ = MT2
    
    AreEqual(log, ['MT1', 'MT2'])
    class T1(C, D): pass    
    
    AreEqual(log, ['MT1', 'MT2', 'MT1'])
    
    def f(): 
        class T2(C, D, E): pass
        
    AssertError(TypeError, f)
    
    AreEqual(log, ['MT1', 'MT2', 'MT1'])

def test_del_getattribute(): # 409747    
    class B(object): 
        def __getattribute__(self, name): pass
    
    class D(B): pass
    
    def f(): del D.__getattribute__  # AttributeError expected.
    AssertError(AttributeError, f)

def test_metaclass_oldstyle_only_bases():
    class C: pass
    
    AssertError(TypeError, type, 'foo', (C, ), {})

def test_bad_mro_error_message():
    class A(object): pass
    
    class B(A): pass
    
    if is_ironpython: #http://ironpython.codeplex.com/workitem/27907
        AssertErrorWithPartialMessage(TypeError, "A, B", type, "X", (A,B), {})
    else:
        AssertErrorWithPartialMessage(TypeError, "Cannot create a consistent method resolution\norder (MRO) for bases", 
                                      type, "X", (A,B), {})

def test_finalizer():
    """returning the same object from __new__ shouldn't cause it to be finalized"""
    global val, called
    val = None
    called = False
    class X(object):
        def __new__(cls):
            global val
            if val == None:
                val = object.__new__(cls)
            return val
        def __del__(self):
            called = True
    
    a = X()
    b = X()
    AreEqual(id(a), id(b))
    import gc
    gc.collect()
    AreEqual(called, False)

def test_metaclass_attribute_lookup():
    class x(type):
        @property
        def Foo(self): return self._foo
        @Foo.setter
        def Foo(self, value): self._foo = value
    
    class y:
        __metaclass__ = x
        def Foo(self): return 42
        _foo = 0
    
    # data descriptor should lookup in meta class first.
    AreEqual(y.Foo, 0)
    
    class x(type):
        Foo = 42
    
    class y:
        __metaclass__ = x
        Foo = 0
        
    # non-data descriptors lookup in the normal class first
    AreEqual(y.Foo, 0)

def test_len():
    class l(object):
        def __int__(self):
            return 42

    vals = (l(), 42L, 42.0)
    if is_cli:
        from iptest.type_util import clr_all_types
        vals += tuple(t(42) for t in clr_all_types)
    
    for x in vals:
        class C(object):
            def __len__(self):
                return x
        AreEqual(len(C()), 42)


def test_descriptor_exception():
    class desc(object):
        def __get__(self, value, ctx):
            raise AttributeError, 'foo'
    
    class x(object):
        a = 42
    
    class y(x):
        a = desc()    
    
    AssertErrorWithMessage(AttributeError, 'foo', lambda: y().a)

    class y(object):
        a = desc()    
    
    AssertErrorWithMessage(AttributeError, 'foo', lambda: y().a)

def test_mutate_descriptor():
    class desc(object):
        def __get__(self, value, ctx):
            return 42

    class x(object):
        a = desc()

    AreEqual(x().a, 42)
    desc.__get__ = lambda self, value, ctx: 23
    AreEqual(x().a, 23)

def test_method_tuple_type():
    """creates a method who's type is declared to be a tuple"""
    class x(object):
        def f(self): pass
    
    def f(self): return self
    
    AreEqual(type(x.f)(f, None, (int, str))(42), 42)
    AreEqual(type(x.f)(f, None, (int, str))('abc'), 'abc')
    AssertError(TypeError, type(x.f)(f, None, (int, str)), 1L)

def test_mutate_class():
    def f(): object.foo = 42
    def g(): type.foo = 42
    def h(): del type.foo
    def i(): del object.foo
    AssertError(TypeError, f)
    AssertError(TypeError, g)
    AssertError(TypeError, h)
    AssertError(TypeError, i)

def test_wacky_new_init():
    global initCalled

    for base in [object, list]:
        for has_finalizer in [True, False]:
            class CustomInit(object):
                def __get__(self, inst, ctx):
                    return self
                def __call__(self, *args):
                    global initCalled
                    initCalled = 'CustomInit'
            
            class Base(base):
                def __new__(self, toCreate):
                    return base.__new__(toCreate)
                if has_finalizer:
                    def __del__(self): pass
                    
            class Sub(Base):
                def __init__(self, *args):
                    global initCalled
                    initCalled = 'Sub'
            
            class NotSub(base):
                def __init__(self, *args):
                    global initCalled
                    initCalled = 'NotSub'
                
            class OC: pass
            
            class MixedSub(Base, OC):
                def __init__(self, *args):
                    global initCalled
                    initCalled = 'MixedSub'
            
            class CustomSub(Base):
                __init__ = CustomInit()
            
            Base(MixedSub)
            AreEqual(initCalled, 'MixedSub')
            
            Base(Sub)
            AreEqual(initCalled, 'Sub')
            initCalled = None
            
            Base(NotSub)
            AreEqual(initCalled, None)
                
            Base(CustomSub)
            AreEqual(initCalled, 'CustomInit')

def test_new_init_error_combinations():
    class X1(object):
        args = ()
        def __init__(self):
            object.__init__(self, *X1.args)
    
    class X2(object):
        args = ()
        def __new__(cls):
            return object.__new__(cls, *X2.args)
    
    
    
    temp = X1()
    temp = X2()
    for args in [(42,), 
                 (None,), #CP19585
                 (42, 43), ("abc",), 
                    ]:
        X1.args = args
        X2.args = args
        AssertError(TypeError, X1)
        AssertError(TypeError, X2)

    #--args plus kwargs
    class X3(object):
        args = ()
        kwargs = {}
        def __init__(self):
            object.__init__(self, *X3.args, **X3.kwargs)
    
    class X4(object):
        args = ()
        kwargs = {}
        def __new__(cls):
            return object.__new__(cls, *X4.args, **X4.kwargs)
    
    temp = X3()
    temp = X4()
    
    for args, kwargs in [
                            [(42,), {}], 
                            [(None,), {'a':3}], 
                            [(42, 43), {'a':3, 'b': 4}], 
                            [("abc",), {'z':None}], 
                            [(), {'a':3}],
                        ]:
        X3.args = args
        X3.kwargs = kwargs
        X4.args = args
        X4.kwargs = kwargs
        AssertError(TypeError, X3)
        AssertError(TypeError, X4)


def test_oldstyle_splat_dict():
    class C: pass
    
    def E(): return {}
    
    AreEqual(type(C(*E())), type(C()))
    

def test_get_dict_once():
    class x(object): pass

    class y(x): pass

    Assert('__dict__' in x.__dict__)
    Assert('__dict__' not in y.__dict__)

def test_cp22832():
    class KOld:
        KOldStuff = 3
    
    class KNew(object, KOld):
        pass
        
    Assert("KOldStuff" in dir(KNew))

@skip("silverlight")
def test_cp23564():
    global A
    A = 0
    
    class K1(object):
        def __del__(self):
            global A
            A = 1
    
    class K2(K1):
        pass
        
    k = K2()
    k.__class__ = K1
    del k
    force_gc()
    AreEqual(A, 1)


def test_object_delattr():
    class A(object):
        def __init__(self):
            self.abc = 42
            
    x = A()
    object.__delattr__(x, 'abc')
    AreEqual(hasattr(x, 'abc'), False)

def test_cp33622():
    AreEqual(object.__repr__ in (None,), False)
    AreEqual(object.__repr__ in (None,object.__repr__), True)
    AreEqual(object.__repr__ in (None,object.__cmp__), False)
    AreEqual(object.__repr__ in (None,object.__str__), False)

def test_cp24649_gh120():
    import copy

    class Descriptor(object):
        def __get__(self, instance, owner):
            return instance.x

    def clone(cls):
        """Create clone of provided class"""
        attrs = vars(cls).copy()
        skipped = ['__dict__', '__weakref__']
        for attr in skipped:
            try:
                del attrs[attr]
            except KeyError:
                pass
        cattrs = copy.deepcopy(attrs)
        return type(cls.__name__, cls.__bases__, cattrs)

    class C(object):
        a = Descriptor()
        
        def __init__(self, x):
            self.x = x

    # make sure all expected keys are present, and only those
    AreEqual(set(C.__dict__.keys()),
        {'a', '__module__', '__dict__', '__weakref__', '__doc__', '__init__'})
    
    # make sure .items() is the same as indexing
    for key, value in C.__dict__.items():
        AreEqual(C.__dict__[key], value)

    CC = clone(C)
    cc = CC(1)
    AreEqual(cc.x, 1)


#--MAIN------------------------------------------------------------------------
run_test(__name__)
Back to Top