This file is indexed.

/usr/lib/python2.7/dist-packages/zope/interface/tests/test_declarations.py is in python-zope.interface 4.3.2-1build2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
##############################################################################
#
# Copyright (c) 2003 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Test the new API for making and checking interface declarations
"""
import unittest

from zope.interface._compat import _skip_under_py3k


class _Py3ClassAdvice(object):

    def _run_generated_code(self, code, globs, locs,
                            fails_under_py3k=True,
                           ):
        import warnings
        from zope.interface._compat import PYTHON3
        with warnings.catch_warnings(record=True) as log:
            warnings.resetwarnings()
            if not PYTHON3:
                exec(code, globs, locs)
                self.assertEqual(len(log), 0) # no longer warn
                return True
            else:
                try:
                    exec(code, globs, locs)
                except TypeError:
                    return False
                else:
                    if fails_under_py3k:
                        self.fail("Didn't raise TypeError")


class NamedTests(unittest.TestCase):

    def test_class(self):
        from zope.interface.declarations import named

        @named(u'foo')
        class Foo(object):
            pass

        self.assertEqual(Foo.__component_name__, u'foo')

    def test_function(self):
        from zope.interface.declarations import named

        @named(u'foo')
        def doFoo(object):
            pass

        self.assertEqual(doFoo.__component_name__, u'foo')

    def test_instance(self):
        from zope.interface.declarations import named

        class Foo(object):
            pass
        foo = Foo()
        named(u'foo')(foo)

        self.assertEqual(foo.__component_name__, u'foo')


class DeclarationTests(unittest.TestCase):

    def _getTargetClass(self):
        from zope.interface.declarations import Declaration
        return Declaration

    def _makeOne(self, *args, **kw):
        return self._getTargetClass()(*args, **kw)

    def test_ctor_no_bases(self):
        decl = self._makeOne()
        self.assertEqual(list(decl.__bases__), [])

    def test_ctor_w_interface_in_bases(self):
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        decl = self._makeOne(IFoo)
        self.assertEqual(list(decl.__bases__), [IFoo])

    def test_ctor_w_implements_in_bases(self):
        from zope.interface.declarations import Implements
        impl = Implements()
        decl = self._makeOne(impl)
        self.assertEqual(list(decl.__bases__), [impl])

    def test_changed_wo_existing__v_attrs(self):
        decl = self._makeOne()
        decl.changed(decl) # doesn't raise
        self.assertFalse('_v_attrs' in decl.__dict__)

    def test_changed_w_existing__v_attrs(self):
        decl = self._makeOne()
        decl._v_attrs = object()
        decl.changed(decl)
        self.assertFalse('_v_attrs' in decl.__dict__)

    def test___contains__w_self(self):
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        decl = self._makeOne()
        self.assertFalse(decl in decl)

    def test___contains__w_unrelated_iface(self):
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        decl = self._makeOne()
        self.assertFalse(IFoo in decl)

    def test___contains__w_base_interface(self):
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        decl = self._makeOne(IFoo)
        self.assertTrue(IFoo in decl)

    def test___iter___empty(self):
        decl = self._makeOne()
        self.assertEqual(list(decl), [])

    def test___iter___single_base(self):
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        decl = self._makeOne(IFoo)
        self.assertEqual(list(decl), [IFoo])

    def test___iter___multiple_bases(self):
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        IBar = InterfaceClass('IBar')
        decl = self._makeOne(IFoo, IBar)
        self.assertEqual(list(decl), [IFoo, IBar])

    def test___iter___inheritance(self):
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        IBar = InterfaceClass('IBar', (IFoo,))
        decl = self._makeOne(IBar)
        self.assertEqual(list(decl), [IBar]) #IBar.interfaces() omits bases

    def test___iter___w_nested_sequence_overlap(self):
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        IBar = InterfaceClass('IBar')
        decl = self._makeOne(IBar, (IFoo, IBar))
        self.assertEqual(list(decl), [IBar, IFoo])

    def test_flattened_empty(self):
        from zope.interface.interface import Interface
        decl = self._makeOne()
        self.assertEqual(list(decl.flattened()), [Interface])

    def test_flattened_single_base(self):
        from zope.interface.interface import Interface
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        decl = self._makeOne(IFoo)
        self.assertEqual(list(decl.flattened()), [IFoo, Interface])

    def test_flattened_multiple_bases(self):
        from zope.interface.interface import Interface
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        IBar = InterfaceClass('IBar')
        decl = self._makeOne(IFoo, IBar)
        self.assertEqual(list(decl.flattened()), [IFoo, IBar, Interface])

    def test_flattened_inheritance(self):
        from zope.interface.interface import Interface
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        IBar = InterfaceClass('IBar', (IFoo,))
        decl = self._makeOne(IBar)
        self.assertEqual(list(decl.flattened()), [IBar, IFoo, Interface])

    def test_flattened_w_nested_sequence_overlap(self):
        from zope.interface.interface import Interface
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        IBar = InterfaceClass('IBar')
        decl = self._makeOne(IBar, (IFoo, IBar))
        # Note that decl.__iro__ has IFoo first.
        self.assertEqual(list(decl.flattened()), [IFoo, IBar, Interface])

    def test___sub___unrelated_interface(self):
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        IBar = InterfaceClass('IBar')
        before = self._makeOne(IFoo)
        after = before - IBar
        self.assertTrue(isinstance(after, self._getTargetClass()))
        self.assertEqual(list(after), [IFoo])

    def test___sub___related_interface(self):
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        before = self._makeOne(IFoo)
        after = before - IFoo
        self.assertEqual(list(after), [])

    def test___sub___related_interface_by_inheritance(self):
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        IBar = InterfaceClass('IBar', (IFoo,))
        before = self._makeOne(IBar)
        after = before - IBar
        self.assertEqual(list(after), [])

    def test___add___unrelated_interface(self):
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        IBar = InterfaceClass('IBar')
        before = self._makeOne(IFoo)
        after = before + IBar
        self.assertTrue(isinstance(after, self._getTargetClass()))
        self.assertEqual(list(after), [IFoo, IBar])

    def test___add___related_interface(self):
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        IBar = InterfaceClass('IBar')
        IBaz = InterfaceClass('IBaz')
        before = self._makeOne(IFoo, IBar)
        other = self._makeOne(IBar, IBaz)
        after = before + other
        self.assertEqual(list(after), [IFoo, IBar, IBaz])


class TestImplements(unittest.TestCase):

    def _getTargetClass(self):
        from zope.interface.declarations import Implements
        return Implements

    def _makeOne(self, *args, **kw):
        return self._getTargetClass()(*args, **kw)

    def test_ctor_no_bases(self):
        impl = self._makeOne()
        self.assertEqual(impl.inherit, None)
        self.assertEqual(impl.declared, ())
        self.assertEqual(impl.__name__, '?')
        self.assertEqual(list(impl.__bases__), [])

    def test___repr__(self):
        impl = self._makeOne()
        impl.__name__ = 'Testing'
        self.assertEqual(repr(impl), '<implementedBy Testing>')

    def test___reduce__(self):
        from zope.interface.declarations import implementedBy
        impl = self._makeOne()
        self.assertEqual(impl.__reduce__(), (implementedBy, (None,)))

    def test_sort(self):
        from zope.interface.declarations import implementedBy
        class A(object):
            pass
        class B(object):
            pass
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')

        self.assertEqual(implementedBy(A), implementedBy(A))
        self.assertEqual(hash(implementedBy(A)), hash(implementedBy(A)))
        self.assertTrue(implementedBy(A) < None)
        self.assertTrue(None > implementedBy(A))
        self.assertTrue(implementedBy(A) < implementedBy(B))
        self.assertTrue(implementedBy(A) > IFoo)
        self.assertTrue(implementedBy(A) <= implementedBy(B))
        self.assertTrue(implementedBy(A) >= IFoo)
        self.assertTrue(implementedBy(A) != IFoo)

    def test_proxy_equality(self):
        # https://github.com/zopefoundation/zope.interface/issues/55
        class Proxy(object):
            def __init__(self, wrapped):
                self._wrapped = wrapped

            def __getattr__(self, name):
                return getattr(self._wrapped, name)

            def __eq__(self, other):
                return self._wrapped == other

            def __ne__(self, other):
                return self._wrapped != other

        from zope.interface.declarations import implementedBy
        class A(object):
            pass

        class B(object):
            pass

        implementedByA = implementedBy(A)
        implementedByB = implementedBy(B)
        proxy = Proxy(implementedByA)

        # The order of arguments to the operators matters,
        # test both
        self.assertTrue(implementedByA == implementedByA)
        self.assertTrue(implementedByA != implementedByB)
        self.assertTrue(implementedByB != implementedByA)

        self.assertTrue(proxy == implementedByA)
        self.assertTrue(implementedByA == proxy)
        self.assertFalse(proxy != implementedByA)
        self.assertFalse(implementedByA != proxy)

        self.assertTrue(proxy != implementedByB)
        self.assertTrue(implementedByB != proxy)


class Test_implementedByFallback(unittest.TestCase):

    def _callFUT(self, *args, **kw):
        from zope.interface.declarations import implementedByFallback
        return implementedByFallback(*args, **kw)

    def test_dictless_wo_existing_Implements_wo_registrations(self):
        class Foo(object):
            __slots__ = ('__implemented__',)
        foo = Foo()
        foo.__implemented__ = None
        self.assertEqual(list(self._callFUT(foo)), [])

    def test_dictless_wo_existing_Implements_cant_assign___implemented__(self):
        class Foo(object):
            def _get_impl(self): return None
            def _set_impl(self, val): raise TypeError
            __implemented__ = property(_get_impl, _set_impl)
            def __call__(self): pass  #act like a factory
        foo = Foo()
        self.assertRaises(TypeError, self._callFUT, foo)

    def test_dictless_wo_existing_Implements_w_registrations(self):
        from zope.interface import declarations
        class Foo(object):
            __slots__ = ('__implemented__',)
        foo = Foo()
        foo.__implemented__ = None
        reg = object()
        with _MonkeyDict(declarations,
                         'BuiltinImplementationSpecifications') as specs:
            specs[foo] = reg
            self.assertTrue(self._callFUT(foo) is reg)

    def test_dictless_w_existing_Implements(self):
        from zope.interface.declarations import Implements
        impl = Implements()
        class Foo(object):
            __slots__ = ('__implemented__',)
        foo = Foo()
        foo.__implemented__ = impl
        self.assertTrue(self._callFUT(foo) is impl)

    def test_dictless_w_existing_not_Implements(self):
        from zope.interface.interface import InterfaceClass
        class Foo(object):
            __slots__ = ('__implemented__',)
        foo = Foo()
        IFoo = InterfaceClass('IFoo')
        foo.__implemented__ = (IFoo,)
        self.assertEqual(list(self._callFUT(foo)), [IFoo])

    def test_w_existing_attr_as_Implements(self):
        from zope.interface.declarations import Implements
        impl = Implements()
        class Foo(object):
            __implemented__ = impl
        self.assertTrue(self._callFUT(Foo) is impl)

    def test_builtins_added_to_cache(self):
        from zope.interface import declarations
        from zope.interface.declarations import Implements
        from zope.interface._compat import _BUILTINS
        with _MonkeyDict(declarations,
                         'BuiltinImplementationSpecifications') as specs:
            self.assertEqual(list(self._callFUT(tuple)), [])
            self.assertEqual(list(self._callFUT(list)), [])
            self.assertEqual(list(self._callFUT(dict)), [])
            for typ in (tuple, list, dict):
                spec = specs[typ]
                self.assertTrue(isinstance(spec, Implements))
                self.assertEqual(repr(spec),
                                '<implementedBy %s.%s>'
                                    % (_BUILTINS, typ.__name__))

    def test_builtins_w_existing_cache(self):
        from zope.interface import declarations
        t_spec, l_spec, d_spec = object(), object(), object()
        with _MonkeyDict(declarations,
                         'BuiltinImplementationSpecifications') as specs:
            specs[tuple] = t_spec
            specs[list] = l_spec
            specs[dict] = d_spec
            self.assertTrue(self._callFUT(tuple) is t_spec)
            self.assertTrue(self._callFUT(list) is l_spec)
            self.assertTrue(self._callFUT(dict) is d_spec)

    def test_oldstyle_class_no_assertions(self):
        # TODO: Figure out P3 story
        class Foo:
            pass
        self.assertEqual(list(self._callFUT(Foo)), [])

    def test_no_assertions(self):
        # TODO: Figure out P3 story
        class Foo(object):
            pass
        self.assertEqual(list(self._callFUT(Foo)), [])

    def test_w_None_no_bases_not_factory(self):
        class Foo(object):
            __implemented__ = None
        foo = Foo()
        self.assertRaises(TypeError, self._callFUT, foo)

    def test_w_None_no_bases_w_factory(self):
        from zope.interface.declarations import objectSpecificationDescriptor
        class Foo(object):
            __implemented__ = None
            def __call__(self):
                pass
        foo = Foo()
        foo.__name__ = 'foo'
        spec = self._callFUT(foo)
        self.assertEqual(spec.__name__,
                         'zope.interface.tests.test_declarations.foo')
        self.assertTrue(spec.inherit is foo)
        self.assertTrue(foo.__implemented__ is spec)
        self.assertTrue(foo.__providedBy__ is objectSpecificationDescriptor)
        self.assertFalse('__provides__' in foo.__dict__)

    def test_w_None_no_bases_w_class(self):
        from zope.interface.declarations import ClassProvides
        class Foo(object):
            __implemented__ = None
        spec = self._callFUT(Foo)
        self.assertEqual(spec.__name__,
                         'zope.interface.tests.test_declarations.Foo')
        self.assertTrue(spec.inherit is Foo)
        self.assertTrue(Foo.__implemented__ is spec)
        self.assertTrue(isinstance(Foo.__providedBy__, ClassProvides))
        self.assertTrue(isinstance(Foo.__provides__, ClassProvides))
        self.assertEqual(Foo.__provides__, Foo.__providedBy__)

    def test_w_existing_Implements(self):
        from zope.interface.declarations import Implements
        impl = Implements()
        class Foo(object):
            __implemented__ = impl
        self.assertTrue(self._callFUT(Foo) is impl)


class Test_implementedBy(Test_implementedByFallback):
    # Repeat tests for C optimizations

    def _callFUT(self, *args, **kw):
        from zope.interface.declarations import implementedBy
        return implementedBy(*args, **kw)


class Test_classImplementsOnly(unittest.TestCase):

    def _callFUT(self, *args, **kw):
        from zope.interface.declarations import classImplementsOnly
        return classImplementsOnly(*args, **kw)

    def test_no_existing(self):
        from zope.interface.declarations import ClassProvides
        from zope.interface.interface import InterfaceClass
        class Foo(object):
            pass
        ifoo = InterfaceClass('IFoo')
        self._callFUT(Foo, ifoo)
        spec = Foo.__implemented__
        self.assertEqual(spec.__name__,
                         'zope.interface.tests.test_declarations.Foo')
        self.assertTrue(spec.inherit is None)
        self.assertTrue(Foo.__implemented__ is spec)
        self.assertTrue(isinstance(Foo.__providedBy__, ClassProvides))
        self.assertTrue(isinstance(Foo.__provides__, ClassProvides))
        self.assertEqual(Foo.__provides__, Foo.__providedBy__)

    def test_w_existing_Implements(self):
        from zope.interface.declarations import Implements
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        IBar = InterfaceClass('IBar')
        impl = Implements(IFoo)
        impl.declared = (IFoo,)
        class Foo(object):
            __implemented__ = impl
        impl.inherit = Foo
        self._callFUT(Foo, IBar)
        # Same spec, now different values
        self.assertTrue(Foo.__implemented__ is impl)
        self.assertEqual(impl.inherit, None)
        self.assertEqual(impl.declared, (IBar,))


class Test_classImplements(unittest.TestCase):

    def _callFUT(self, *args, **kw):
        from zope.interface.declarations import classImplements
        return classImplements(*args, **kw)

    def test_no_existing(self):
        from zope.interface.declarations import ClassProvides
        from zope.interface.interface import InterfaceClass
        class Foo(object):
            pass
        IFoo = InterfaceClass('IFoo')
        self._callFUT(Foo, IFoo)
        spec = Foo.__implemented__
        self.assertEqual(spec.__name__,
                         'zope.interface.tests.test_declarations.Foo')
        self.assertTrue(spec.inherit is Foo)
        self.assertTrue(Foo.__implemented__ is spec)
        self.assertTrue(isinstance(Foo.__providedBy__, ClassProvides))
        self.assertTrue(isinstance(Foo.__provides__, ClassProvides))
        self.assertEqual(Foo.__provides__, Foo.__providedBy__)

    def test_w_existing_Implements(self):
        from zope.interface.declarations import Implements
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        IBar = InterfaceClass('IBar')
        impl = Implements(IFoo)
        impl.declared = (IFoo,)
        class Foo(object):
            __implemented__ = impl
        impl.inherit = Foo
        self._callFUT(Foo, IBar)
        # Same spec, now different values
        self.assertTrue(Foo.__implemented__ is impl)
        self.assertEqual(impl.inherit, Foo)
        self.assertEqual(impl.declared, (IFoo, IBar,))

    def test_w_existing_Implements_w_bases(self):
        from zope.interface.declarations import Implements
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        IBar = InterfaceClass('IBar')
        IBaz = InterfaceClass('IBaz', IFoo)
        b_impl = Implements(IBaz)
        impl = Implements(IFoo)
        impl.declared = (IFoo,)
        class Base1(object):
            __implemented__ = b_impl
        class Base2(object):
            __implemented__ = b_impl
        class Foo(Base1, Base2):
            __implemented__ = impl
        impl.inherit = Foo
        self._callFUT(Foo, IBar)
        # Same spec, now different values
        self.assertTrue(Foo.__implemented__ is impl)
        self.assertEqual(impl.inherit, Foo)
        self.assertEqual(impl.declared, (IFoo, IBar,))
        self.assertEqual(impl.__bases__, (IFoo, IBar, b_impl))


class Test__implements_advice(unittest.TestCase):

    def _callFUT(self, *args, **kw):
        from zope.interface.declarations import _implements_advice
        return _implements_advice(*args, **kw)

    def test_no_existing_implements(self):
        from zope.interface.declarations import classImplements
        from zope.interface.declarations import Implements
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        class Foo(object):
            __implements_advice_data__ = ((IFoo,), classImplements)
        self._callFUT(Foo)
        self.assertFalse('__implements_advice_data__' in Foo.__dict__)
        self.assertTrue(isinstance(Foo.__implemented__, Implements))
        self.assertEqual(list(Foo.__implemented__), [IFoo])


class Test_implementer(unittest.TestCase):

    def _getTargetClass(self):
        from zope.interface.declarations import implementer
        return implementer

    def _makeOne(self, *args, **kw):
        return self._getTargetClass()(*args, **kw)

    def test_oldstyle_class(self):
        # TODO Py3 story
        from zope.interface.declarations import ClassProvides
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        class Foo:
            pass
        decorator = self._makeOne(IFoo)
        returned = decorator(Foo)
        self.assertTrue(returned is Foo)
        spec = Foo.__implemented__
        self.assertEqual(spec.__name__,
                         'zope.interface.tests.test_declarations.Foo')
        self.assertTrue(spec.inherit is Foo)
        self.assertTrue(Foo.__implemented__ is spec)
        self.assertTrue(isinstance(Foo.__providedBy__, ClassProvides))
        self.assertTrue(isinstance(Foo.__provides__, ClassProvides))
        self.assertEqual(Foo.__provides__, Foo.__providedBy__)

    def test_newstyle_class(self):
        from zope.interface.declarations import ClassProvides
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        class Foo(object):
            pass
        decorator = self._makeOne(IFoo)
        returned = decorator(Foo)
        self.assertTrue(returned is Foo)
        spec = Foo.__implemented__
        self.assertEqual(spec.__name__,
                         'zope.interface.tests.test_declarations.Foo')
        self.assertTrue(spec.inherit is Foo)
        self.assertTrue(Foo.__implemented__ is spec)
        self.assertTrue(isinstance(Foo.__providedBy__, ClassProvides))
        self.assertTrue(isinstance(Foo.__provides__, ClassProvides))
        self.assertEqual(Foo.__provides__, Foo.__providedBy__)

    def test_nonclass_cannot_assign_attr(self):
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        decorator = self._makeOne(IFoo)
        self.assertRaises(TypeError, decorator, object())

    def test_nonclass_can_assign_attr(self):
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        class Foo(object):
            pass
        foo = Foo()
        decorator = self._makeOne(IFoo)
        returned = decorator(foo)
        self.assertTrue(returned is foo)
        spec = foo.__implemented__
        self.assertEqual(spec.__name__, 'zope.interface.tests.test_declarations.?')
        self.assertTrue(spec.inherit is None)
        self.assertTrue(foo.__implemented__ is spec)


class Test_implementer_only(unittest.TestCase):

    def _getTargetClass(self):
        from zope.interface.declarations import implementer_only
        return implementer_only

    def _makeOne(self, *args, **kw):
        return self._getTargetClass()(*args, **kw)

    def test_function(self):
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        decorator = self._makeOne(IFoo)
        def _function(): pass
        self.assertRaises(ValueError, decorator, _function)

    def test_method(self):
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        decorator = self._makeOne(IFoo)
        class Bar:
            def _method(): pass
        self.assertRaises(ValueError, decorator, Bar._method)

    def test_oldstyle_class(self):
        # TODO Py3 story
        from zope.interface.declarations import Implements
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        IBar = InterfaceClass('IBar')
        old_spec = Implements(IBar)
        class Foo:
            __implemented__ = old_spec
        decorator = self._makeOne(IFoo)
        returned = decorator(Foo)
        self.assertTrue(returned is Foo)
        spec = Foo.__implemented__
        self.assertEqual(spec.__name__, '?')
        self.assertTrue(spec.inherit is None)
        self.assertTrue(Foo.__implemented__ is spec)

    def test_newstyle_class(self):
        from zope.interface.declarations import Implements
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass('IFoo')
        IBar = InterfaceClass('IBar')
        old_spec = Implements(IBar)
        class Foo(object):
            __implemented__ = old_spec
        decorator = self._makeOne(IFoo)
        returned = decorator(Foo)
        self.assertTrue(returned is Foo)
        spec = Foo.__implemented__
        self.assertEqual(spec.__name__, '?')
        self.assertTrue(spec.inherit is None)
        self.assertTrue(Foo.__implemented__ is spec)


# Test '_implements' by way of 'implements{,Only}', its only callers.

class Test_implementsOnly(unittest.TestCase, _Py3ClassAdvice):

    def _getFUT(self):
        from zope.interface.declarations import implementsOnly
        return implementsOnly

    def test_simple(self):
        import warnings
        from zope.interface.declarations import implementsOnly
        from zope.interface._compat import PYTHON3
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        globs = {'implementsOnly': implementsOnly,
                 'IFoo': IFoo,
                }
        locs = {}
        CODE = "\n".join([
            'class Foo(object):'
            '    implementsOnly(IFoo)',
            ])
        with warnings.catch_warnings(record=True) as log:
            warnings.resetwarnings()
            try:
                exec(CODE, globs, locs)
            except TypeError:
                if not PYTHON3:
                    raise
            else:
                if PYTHON3:
                    self.fail("Didn't raise TypeError")
                Foo = locs['Foo']
                spec = Foo.__implemented__
                self.assertEqual(list(spec), [IFoo])
                self.assertEqual(len(log), 0) # no longer warn

    def test_called_once_from_class_w_bases(self):
        from zope.interface.declarations import implements
        from zope.interface.declarations import implementsOnly
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        IBar = InterfaceClass("IBar")
        globs = {'implements': implements,
                 'implementsOnly': implementsOnly,
                 'IFoo': IFoo,
                 'IBar': IBar,
                }
        locs = {}
        CODE = "\n".join([
            'class Foo(object):',
            '    implements(IFoo)',
            'class Bar(Foo):'
            '    implementsOnly(IBar)',
            ])
        if self._run_generated_code(CODE, globs, locs):
            Bar = locs['Bar']
            spec = Bar.__implemented__
            self.assertEqual(list(spec), [IBar])


class Test_implements(unittest.TestCase, _Py3ClassAdvice):

    def _getFUT(self):
        from zope.interface.declarations import implements
        return implements

    def test_called_from_function(self):
        import warnings
        from zope.interface.declarations import implements
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        globs = {'implements': implements, 'IFoo': IFoo}
        locs = {}
        CODE = "\n".join([
            'def foo():',
            '    implements(IFoo)'
            ])
        if self._run_generated_code(CODE, globs, locs, False):
            foo = locs['foo']
            with warnings.catch_warnings(record=True) as log:
                warnings.resetwarnings()
                self.assertRaises(TypeError, foo)
                self.assertEqual(len(log), 0) # no longer warn

    def test_called_twice_from_class(self):
        import warnings
        from zope.interface.declarations import implements
        from zope.interface.interface import InterfaceClass
        from zope.interface._compat import PYTHON3
        IFoo = InterfaceClass("IFoo")
        IBar = InterfaceClass("IBar")
        globs = {'implements': implements, 'IFoo': IFoo, 'IBar': IBar}
        locs = {}
        CODE = "\n".join([
            'class Foo(object):',
            '    implements(IFoo)',
            '    implements(IBar)',
            ])
        with warnings.catch_warnings(record=True) as log:
            warnings.resetwarnings()
            try:
                exec(CODE, globs, locs)
            except TypeError:
                if not PYTHON3:
                    self.assertEqual(len(log), 0) # no longer warn
            else:
                self.fail("Didn't raise TypeError")

    def test_called_once_from_class(self):
        from zope.interface.declarations import implements
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        globs = {'implements': implements, 'IFoo': IFoo}
        locs = {}
        CODE = "\n".join([
            'class Foo(object):',
            '    implements(IFoo)',
            ])
        if self._run_generated_code(CODE, globs, locs):
            Foo = locs['Foo']
            spec = Foo.__implemented__
            self.assertEqual(list(spec), [IFoo])


class ProvidesClassTests(unittest.TestCase):

    def _getTargetClass(self):
        from zope.interface.declarations import ProvidesClass
        return ProvidesClass

    def _makeOne(self, *args, **kw):
        return self._getTargetClass()(*args, **kw)

    def test_simple_class_one_interface(self):
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        class Foo(object):
            pass
        spec = self._makeOne(Foo, IFoo)
        self.assertEqual(list(spec), [IFoo])

    def test___reduce__(self):
        from zope.interface.declarations import Provides # the function
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        class Foo(object):
            pass
        spec = self._makeOne(Foo, IFoo)
        klass, args = spec.__reduce__()
        self.assertTrue(klass is Provides)
        self.assertEqual(args, (Foo, IFoo))

    def test___get___class(self):
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        class Foo(object):
            pass
        spec = self._makeOne(Foo, IFoo)
        Foo.__provides__ = spec
        self.assertTrue(Foo.__provides__ is spec)

    def test___get___instance(self):
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        class Foo(object):
            pass
        spec = self._makeOne(Foo, IFoo)
        Foo.__provides__ = spec
        def _test():
            foo = Foo()
            return foo.__provides__
        self.assertRaises(AttributeError, _test)


class Test_Provides(unittest.TestCase):

    def _callFUT(self, *args, **kw):
        from zope.interface.declarations import Provides
        return Provides(*args, **kw)

    def test_no_cached_spec(self):
        from zope.interface import declarations
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        cache = {}
        class Foo(object):
            pass
        with _Monkey(declarations, InstanceDeclarations=cache):
            spec = self._callFUT(Foo, IFoo)
        self.assertEqual(list(spec), [IFoo])
        self.assertTrue(cache[(Foo, IFoo)] is spec)

    def test_w_cached_spec(self):
        from zope.interface import declarations
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        prior = object()
        class Foo(object):
            pass
        cache = {(Foo, IFoo): prior}
        with _Monkey(declarations, InstanceDeclarations=cache):
            spec = self._callFUT(Foo, IFoo)
        self.assertTrue(spec is prior)


class Test_directlyProvides(unittest.TestCase):

    def _callFUT(self, *args, **kw):
        from zope.interface.declarations import directlyProvides
        return directlyProvides(*args, **kw)

    def test_w_normal_object(self):
        from zope.interface.declarations import ProvidesClass
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        class Foo(object):
            pass
        obj = Foo()
        self._callFUT(obj, IFoo)
        self.assertTrue(isinstance(obj.__provides__, ProvidesClass))
        self.assertEqual(list(obj.__provides__), [IFoo])

    def test_w_class(self):
        from zope.interface.declarations import ClassProvides
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        class Foo(object):
            pass
        self._callFUT(Foo, IFoo)
        self.assertTrue(isinstance(Foo.__provides__, ClassProvides))
        self.assertEqual(list(Foo.__provides__), [IFoo])

    @_skip_under_py3k
    def test_w_non_descriptor_aware_metaclass(self):
        # There are no non-descriptor-aware types in Py3k
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        class MetaClass(type):
            def __getattribute__(self, name):
                # Emulate metaclass whose base is not the type object.
                if name == '__class__':
                    return self
                return type.__getattribute__(self, name)
        class Foo(object):
            __metaclass__ = MetaClass
        obj = Foo()
        self.assertRaises(TypeError, self._callFUT, obj, IFoo)

    def test_w_classless_object(self):
        from zope.interface.declarations import ProvidesClass
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        the_dict = {}
        class Foo(object):
            def __getattribute__(self, name):
                # Emulate object w/o any class
                if name == '__class__':
                    return None
                try:
                    return the_dict[name]
                except KeyError:
                    raise AttributeError(name)
            def __setattr__(self, name, value):
                the_dict[name] = value
        obj = Foo()
        self._callFUT(obj, IFoo)
        self.assertTrue(isinstance(the_dict['__provides__'], ProvidesClass))
        self.assertEqual(list(the_dict['__provides__']), [IFoo])


class Test_alsoProvides(unittest.TestCase):

    def _callFUT(self, *args, **kw):
        from zope.interface.declarations import alsoProvides
        return alsoProvides(*args, **kw)

    def test_wo_existing_provides(self):
        from zope.interface.declarations import ProvidesClass
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        class Foo(object):
            pass
        obj = Foo()
        self._callFUT(obj, IFoo)
        self.assertTrue(isinstance(obj.__provides__, ProvidesClass))
        self.assertEqual(list(obj.__provides__), [IFoo])

    def test_w_existing_provides(self):
        from zope.interface.declarations import directlyProvides
        from zope.interface.declarations import ProvidesClass
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        IBar = InterfaceClass("IBar")
        class Foo(object):
            pass
        obj = Foo()
        directlyProvides(obj, IFoo)
        self._callFUT(obj, IBar)
        self.assertTrue(isinstance(obj.__provides__, ProvidesClass))
        self.assertEqual(list(obj.__provides__), [IFoo, IBar])


class Test_noLongerProvides(unittest.TestCase):

    def _callFUT(self, *args, **kw):
        from zope.interface.declarations import noLongerProvides
        return noLongerProvides(*args, **kw)

    def test_wo_existing_provides(self):
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        class Foo(object):
            pass
        obj = Foo()
        self._callFUT(obj, IFoo)
        self.assertEqual(list(obj.__provides__), [])

    def test_w_existing_provides_hit(self):
        from zope.interface.declarations import directlyProvides
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        class Foo(object):
            pass
        obj = Foo()
        directlyProvides(obj, IFoo)
        self._callFUT(obj, IFoo)
        self.assertEqual(list(obj.__provides__), [])

    def test_w_existing_provides_miss(self):
        from zope.interface.declarations import directlyProvides
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        IBar = InterfaceClass("IBar")
        class Foo(object):
            pass
        obj = Foo()
        directlyProvides(obj, IFoo)
        self._callFUT(obj, IBar)
        self.assertEqual(list(obj.__provides__), [IFoo])

    def test_w_iface_implemented_by_class(self):
        from zope.interface.declarations import implementer
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        @implementer(IFoo)
        class Foo(object):
            pass
        obj = Foo()
        self.assertRaises(ValueError, self._callFUT, obj, IFoo)


class ClassProvidesBaseFallbackTests(unittest.TestCase):

    def _getTargetClass(self):
        from zope.interface.declarations import ClassProvidesBaseFallback
        return ClassProvidesBaseFallback

    def _makeOne(self, klass, implements):
        # Don't instantiate directly:  the C version can't have attributes
        # assigned.
        class Derived(self._getTargetClass()):
            def __init__(self, k, i):
                self._cls = k
                self._implements = i
        return Derived(klass, implements)

    def test_w_same_class_via_class(self):
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        class Foo(object):
            pass
        cpbp = Foo.__provides__ = self._makeOne(Foo, IFoo)
        self.assertTrue(Foo.__provides__ is cpbp)

    def test_w_same_class_via_instance(self):
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        class Foo(object):
            pass
        foo = Foo()
        cpbp = Foo.__provides__ = self._makeOne(Foo, IFoo)
        self.assertTrue(foo.__provides__ is IFoo)

    def test_w_different_class(self):
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        class Foo(object):
            pass
        class Bar(Foo):
            pass
        bar = Bar()
        cpbp = Foo.__provides__ = self._makeOne(Foo, IFoo)
        self.assertRaises(AttributeError, getattr, Bar, '__provides__')
        self.assertRaises(AttributeError, getattr, bar, '__provides__')


class ClassProvidesBaseTests(ClassProvidesBaseFallbackTests):
    # Repeat tests for C optimizations

    def _getTargetClass(self):
        from zope.interface.declarations import ClassProvidesBase
        return ClassProvidesBase


class ClassProvidesTests(unittest.TestCase):

    def _getTargetClass(self):
        from zope.interface.declarations import ClassProvides
        return ClassProvides

    def _makeOne(self, *args, **kw):
        return self._getTargetClass()(*args, **kw)

    def test_w_simple_metaclass(self):
        from zope.interface.declarations import implementer
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        IBar = InterfaceClass("IBar")
        @implementer(IFoo)
        class Foo(object):
            pass
        cp = Foo.__provides__ = self._makeOne(Foo, type(Foo), IBar)
        self.assertTrue(Foo.__provides__ is cp)
        self.assertEqual(list(Foo().__provides__), [IFoo])

    def test___reduce__(self):
        from zope.interface.declarations import implementer
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        IBar = InterfaceClass("IBar")
        @implementer(IFoo)
        class Foo(object):
            pass
        cp = Foo.__provides__ = self._makeOne(Foo, type(Foo), IBar)
        self.assertEqual(cp.__reduce__(),
                         (self._getTargetClass(), (Foo, type(Foo), IBar)))


class Test_directlyProvidedBy(unittest.TestCase):

    def _callFUT(self, *args, **kw):
        from zope.interface.declarations import directlyProvidedBy
        return directlyProvidedBy(*args, **kw)

    def test_wo_declarations_in_class_or_instance(self):
        class Foo(object):
            pass
        foo = Foo()
        self.assertEqual(list(self._callFUT(foo)), [])

    def test_w_declarations_in_class_but_not_instance(self):
        from zope.interface.declarations import implementer
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        @implementer(IFoo)
        class Foo(object):
            pass
        foo = Foo()
        self.assertEqual(list(self._callFUT(foo)), [])

    def test_w_declarations_in_instance_but_not_class(self):
        from zope.interface.declarations import directlyProvides
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        class Foo(object):
            pass
        foo = Foo()
        directlyProvides(foo, IFoo)
        self.assertEqual(list(self._callFUT(foo)), [IFoo])

    def test_w_declarations_in_instance_and_class(self):
        from zope.interface.declarations import directlyProvides
        from zope.interface.declarations import implementer
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        IBar = InterfaceClass("IBar")
        @implementer(IFoo)
        class Foo(object):
            pass
        foo = Foo()
        directlyProvides(foo, IBar)
        self.assertEqual(list(self._callFUT(foo)), [IBar])


class Test_classProvides(unittest.TestCase, _Py3ClassAdvice):

    def _getFUT(self):
        from zope.interface.declarations import classProvides
        return classProvides

    def test_called_from_function(self):
        import warnings
        from zope.interface.declarations import classProvides
        from zope.interface.interface import InterfaceClass
        from zope.interface._compat import PYTHON3
        IFoo = InterfaceClass("IFoo")
        globs = {'classProvides': classProvides, 'IFoo': IFoo}
        locs = {}
        CODE = "\n".join([
            'def foo():',
            '    classProvides(IFoo)'
            ])
        exec(CODE, globs, locs)
        foo = locs['foo']
        with warnings.catch_warnings(record=True) as log:
            warnings.resetwarnings()
            self.assertRaises(TypeError, foo)
            if not PYTHON3:
                self.assertEqual(len(log), 0) # no longer warn

    def test_called_twice_from_class(self):
        import warnings
        from zope.interface.declarations import classProvides
        from zope.interface.interface import InterfaceClass
        from zope.interface._compat import PYTHON3
        IFoo = InterfaceClass("IFoo")
        IBar = InterfaceClass("IBar")
        globs = {'classProvides': classProvides, 'IFoo': IFoo, 'IBar': IBar}
        locs = {}
        CODE = "\n".join([
            'class Foo(object):',
            '    classProvides(IFoo)',
            '    classProvides(IBar)',
            ])
        with warnings.catch_warnings(record=True) as log:
            warnings.resetwarnings()
            try:
                exec(CODE, globs, locs)
            except TypeError:
                if not PYTHON3:
                    self.assertEqual(len(log), 0) # no longer warn
            else:
                self.fail("Didn't raise TypeError")

    def test_called_once_from_class(self):
        from zope.interface.declarations import classProvides
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        globs = {'classProvides': classProvides, 'IFoo': IFoo}
        locs = {}
        CODE = "\n".join([
            'class Foo(object):',
            '    classProvides(IFoo)',
            ])
        if self._run_generated_code(CODE, globs, locs):
            Foo = locs['Foo']
            spec = Foo.__providedBy__
            self.assertEqual(list(spec), [IFoo])

# Test _classProvides_advice through classProvides, its only caller.


class Test_provider(unittest.TestCase):

    def _getTargetClass(self):
        from zope.interface.declarations import provider
        return provider

    def _makeOne(self, *args, **kw):
        return self._getTargetClass()(*args, **kw)

    def test_w_class(self):
        from zope.interface.declarations import ClassProvides
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        @self._makeOne(IFoo)
        class Foo(object):
            pass
        self.assertTrue(isinstance(Foo.__provides__, ClassProvides))
        self.assertEqual(list(Foo.__provides__), [IFoo])


class Test_moduleProvides(unittest.TestCase):

    def _getFUT(self):
        from zope.interface.declarations import moduleProvides
        return moduleProvides

    def test_called_from_function(self):
        from zope.interface.declarations import moduleProvides
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        globs = {'__name__': 'zope.interface.tests.foo',
                 'moduleProvides': moduleProvides, 'IFoo': IFoo}
        locs = {}
        CODE = "\n".join([
            'def foo():',
            '    moduleProvides(IFoo)'
            ])
        exec(CODE, globs, locs)
        foo = locs['foo']
        self.assertRaises(TypeError, foo)

    def test_called_from_class(self):
        from zope.interface.declarations import moduleProvides
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        globs = {'__name__': 'zope.interface.tests.foo',
                 'moduleProvides': moduleProvides, 'IFoo': IFoo}
        locs = {}
        CODE = "\n".join([
            'class Foo(object):',
            '    moduleProvides(IFoo)',
            ])
        try:
            exec(CODE, globs, locs)
        except TypeError:
            pass
        else:
            assert False, 'TypeError not raised'

    def test_called_once_from_module_scope(self):
        from zope.interface.declarations import moduleProvides
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        globs = {'__name__': 'zope.interface.tests.foo',
                 'moduleProvides': moduleProvides, 'IFoo': IFoo}
        CODE = "\n".join([
            'moduleProvides(IFoo)',
            ])
        exec(CODE, globs)
        spec = globs['__provides__']
        self.assertEqual(list(spec), [IFoo])

    def test_called_twice_from_module_scope(self):
        from zope.interface.declarations import moduleProvides
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        globs = {'__name__': 'zope.interface.tests.foo',
                 'moduleProvides': moduleProvides, 'IFoo': IFoo}
        locs = {}
        CODE = "\n".join([
            'moduleProvides(IFoo)',
            'moduleProvides(IFoo)',
            ])
        try:
            exec(CODE, globs)
        except TypeError:
            pass
        else:
            assert False, 'TypeError not raised'


class Test_getObjectSpecificationFallback(unittest.TestCase):

    def _callFUT(self, *args, **kw):
        from zope.interface.declarations import getObjectSpecificationFallback
        return getObjectSpecificationFallback(*args, **kw)

    def test_wo_existing_provides_classless(self):
        the_dict = {}
        class Foo(object):
            def __getattribute__(self, name):
                # Emulate object w/o any class
                if name == '__class__':
                    raise AttributeError(name)
                try:
                    return the_dict[name]
                except KeyError:
                    raise AttributeError(name)
            def __setattr__(self, name, value):
                the_dict[name] = value
        foo = Foo()
        spec = self._callFUT(foo)
        self.assertEqual(list(spec), [])

    def test_existing_provides_is_spec(self):
        from zope.interface.declarations import directlyProvides
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        def foo():
            pass
        directlyProvides(foo, IFoo)
        spec = self._callFUT(foo)
        self.assertTrue(spec is foo.__provides__)

    def test_existing_provides_is_not_spec(self):
        def foo():
            pass
        foo.__provides__ = object() # not a valid spec
        spec = self._callFUT(foo)
        self.assertEqual(list(spec), [])

    def test_existing_provides(self):
        from zope.interface.declarations import directlyProvides
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        class Foo(object):
            pass
        foo = Foo()
        directlyProvides(foo, IFoo)
        spec = self._callFUT(foo)
        self.assertEqual(list(spec), [IFoo])

    def test_wo_provides_on_class_w_implements(self):
        from zope.interface.declarations import implementer
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        @implementer(IFoo)
        class Foo(object):
            pass
        foo = Foo()
        spec = self._callFUT(foo)
        self.assertEqual(list(spec), [IFoo])

    def test_wo_provides_on_class_wo_implements(self):
        class Foo(object):
            pass
        foo = Foo()
        spec = self._callFUT(foo)
        self.assertEqual(list(spec), [])


class Test_getObjectSpecification(Test_getObjectSpecificationFallback):
    # Repeat tests for C optimizations

    def _callFUT(self, *args, **kw):
        from zope.interface.declarations import getObjectSpecification
        return getObjectSpecification(*args, **kw)


class Test_providedByFallback(unittest.TestCase):

    def _callFUT(self, *args, **kw):
        from zope.interface.declarations import providedByFallback
        return providedByFallback(*args, **kw)

    def test_wo_providedBy_on_class_wo_implements(self):
        class Foo(object):
            pass
        foo = Foo()
        spec = self._callFUT(foo)
        self.assertEqual(list(spec), [])

    def test_w_providedBy_valid_spec(self):
        from zope.interface.declarations import Provides
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        class Foo(object):
            pass
        foo = Foo()
        foo.__providedBy__ = Provides(Foo, IFoo)
        spec = self._callFUT(foo)
        self.assertEqual(list(spec), [IFoo])

    def test_w_providedBy_invalid_spec(self):
        class Foo(object):
            pass
        foo = Foo()
        foo.__providedBy__ = object()
        spec = self._callFUT(foo)
        self.assertEqual(list(spec), [])

    def test_w_providedBy_invalid_spec_class_w_implements(self):
        from zope.interface.declarations import implementer
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        @implementer(IFoo)
        class Foo(object):
            pass
        foo = Foo()
        foo.__providedBy__ = object()
        spec = self._callFUT(foo)
        self.assertEqual(list(spec), [IFoo])

    def test_w_providedBy_invalid_spec_w_provides_no_provides_on_class(self):
        class Foo(object):
            pass
        foo = Foo()
        foo.__providedBy__ = object()
        expected = foo.__provides__ = object()
        spec = self._callFUT(foo)
        self.assertTrue(spec is expected)

    def test_w_providedBy_invalid_spec_w_provides_diff_provides_on_class(self):
        class Foo(object):
            pass
        foo = Foo()
        foo.__providedBy__ = object()
        expected = foo.__provides__ = object()
        Foo.__provides__ = object()
        spec = self._callFUT(foo)
        self.assertTrue(spec is expected)

    def test_w_providedBy_invalid_spec_w_provides_same_provides_on_class(self):
        from zope.interface.declarations import implementer
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        @implementer(IFoo)
        class Foo(object):
            pass
        foo = Foo()
        foo.__providedBy__ = object()
        foo.__provides__ = Foo.__provides__ = object()
        spec = self._callFUT(foo)
        self.assertEqual(list(spec), [IFoo])


class Test_providedBy(Test_providedByFallback):
    # Repeat tests for C optimizations

    def _callFUT(self, *args, **kw):
        from zope.interface.declarations import providedBy
        return providedBy(*args, **kw)


class ObjectSpecificationDescriptorFallbackTests(unittest.TestCase):

    def _getTargetClass(self):
        from zope.interface.declarations \
            import ObjectSpecificationDescriptorFallback
        return ObjectSpecificationDescriptorFallback

    def _makeOne(self, *args, **kw):
        return self._getTargetClass()(*args, **kw)

    def test_accessed_via_class(self):
        from zope.interface.declarations import Provides
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        class Foo(object):
            pass
        Foo.__provides__ = Provides(Foo, IFoo)
        Foo.__providedBy__ = self._makeOne()
        self.assertEqual(list(Foo.__providedBy__), [IFoo])

    def test_accessed_via_inst_wo_provides(self):
        from zope.interface.declarations import implementer
        from zope.interface.declarations import Provides
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        IBar = InterfaceClass("IBar")
        @implementer(IFoo)
        class Foo(object):
            pass
        Foo.__provides__ = Provides(Foo, IBar)
        Foo.__providedBy__ = self._makeOne()
        foo = Foo()
        self.assertEqual(list(foo.__providedBy__), [IFoo])

    def test_accessed_via_inst_w_provides(self):
        from zope.interface.declarations import directlyProvides
        from zope.interface.declarations import implementer
        from zope.interface.declarations import Provides
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        IBar = InterfaceClass("IBar")
        IBaz = InterfaceClass("IBaz")
        @implementer(IFoo)
        class Foo(object):
            pass
        Foo.__provides__ = Provides(Foo, IBar)
        Foo.__providedBy__ = self._makeOne()
        foo = Foo()
        directlyProvides(foo, IBaz)
        self.assertEqual(list(foo.__providedBy__), [IBaz, IFoo])


class ObjectSpecificationDescriptorTests(
                ObjectSpecificationDescriptorFallbackTests):
    # Repeat tests for C optimizations

    def _getTargetClass(self):
        from zope.interface.declarations import ObjectSpecificationDescriptor
        return ObjectSpecificationDescriptor


# Test _normalizeargs through its callers.


class _Monkey(object):
    # context-manager for replacing module names in the scope of a test.
    def __init__(self, module, **kw):
        self.module = module
        self.to_restore = dict([(key, getattr(module, key)) for key in kw])
        for key, value in kw.items():
            setattr(module, key, value)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        for key, value in self.to_restore.items():
            setattr(self.module, key, value)


class _MonkeyDict(object):
    # context-manager for restoring a dict w/in a module in the scope of a test.
    def __init__(self, module, attrname, **kw):
        self.module = module
        self.target = getattr(module, attrname)
        self.to_restore = self.target.copy()
        self.target.clear()
        self.target.update(kw)

    def __enter__(self):
        return self.target

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.target.clear()
        self.target.update(self.to_restore)


def test_suite():
    return unittest.TestSuite((
        unittest.makeSuite(DeclarationTests),
        unittest.makeSuite(TestImplements),
        unittest.makeSuite(Test_implementedByFallback),
        unittest.makeSuite(Test_implementedBy),
        unittest.makeSuite(Test_classImplementsOnly),
        unittest.makeSuite(Test_classImplements),
        unittest.makeSuite(Test__implements_advice),
        unittest.makeSuite(Test_implementer),
        unittest.makeSuite(Test_implementer_only),
        unittest.makeSuite(Test_implements),
        unittest.makeSuite(Test_implementsOnly),
        unittest.makeSuite(ProvidesClassTests),
        unittest.makeSuite(Test_Provides),
        unittest.makeSuite(Test_directlyProvides),
        unittest.makeSuite(Test_alsoProvides),
        unittest.makeSuite(Test_noLongerProvides),
        unittest.makeSuite(ClassProvidesBaseFallbackTests),
        unittest.makeSuite(ClassProvidesTests),
        unittest.makeSuite(Test_directlyProvidedBy),
        unittest.makeSuite(Test_classProvides),
        unittest.makeSuite(Test_provider),
        unittest.makeSuite(Test_moduleProvides),
        unittest.makeSuite(Test_getObjectSpecificationFallback),
        unittest.makeSuite(Test_getObjectSpecification),
        unittest.makeSuite(Test_providedByFallback),
        unittest.makeSuite(Test_providedBy),
        unittest.makeSuite(ObjectSpecificationDescriptorFallbackTests),
        unittest.makeSuite(ObjectSpecificationDescriptorTests),
    ))