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
|
##############################################################################
#
# Copyright (c) 2001, 2002 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 Interface implementation
"""
# Things we let slide because it's a test
# pylint:disable=protected-access,blacklisted-name,attribute-defined-outside-init
# pylint:disable=too-many-public-methods,too-many-lines,abstract-method
# pylint:disable=redefined-builtin,signature-differs,arguments-differ
# Things you get inheriting from Interface
# pylint:disable=inherit-non-class,no-self-argument,no-method-argument
# Things you get using methods of an Interface 'subclass'
# pylint:disable=no-value-for-parameter
import unittest
from zope.interface._compat import _skip_under_py3k
from __tests__.tests import MissingSomeAttrs
from __tests__.tests import OptimizationTestMixin
from __tests__.tests import CleanUp
_marker = object()
class Test_invariant(unittest.TestCase):
def test_w_single(self):
from zope.interface.interface import invariant
from zope.interface.interface import TAGGED_DATA
def _check(*args, **kw):
raise NotImplementedError()
class Foo(object):
invariant(_check)
self.assertEqual(getattr(Foo, TAGGED_DATA, None),
{'invariants': [_check]})
def test_w_multiple(self):
from zope.interface.interface import invariant
from zope.interface.interface import TAGGED_DATA
def _check(*args, **kw):
raise NotImplementedError()
def _another_check(*args, **kw):
raise NotImplementedError()
class Foo(object):
invariant(_check)
invariant(_another_check)
self.assertEqual(getattr(Foo, TAGGED_DATA, None),
{'invariants': [_check, _another_check]})
class Test_taggedValue(unittest.TestCase):
def test_w_single(self):
from zope.interface.interface import taggedValue
from zope.interface.interface import TAGGED_DATA
class Foo(object):
taggedValue('bar', ['baz'])
self.assertEqual(getattr(Foo, TAGGED_DATA, None),
{'bar': ['baz']})
def test_w_multiple(self):
from zope.interface.interface import taggedValue
from zope.interface.interface import TAGGED_DATA
class Foo(object):
taggedValue('bar', ['baz'])
taggedValue('qux', 'spam')
self.assertEqual(getattr(Foo, TAGGED_DATA, None),
{'bar': ['baz'], 'qux': 'spam'})
def test_w_multiple_overwriting(self):
from zope.interface.interface import taggedValue
from zope.interface.interface import TAGGED_DATA
class Foo(object):
taggedValue('bar', ['baz'])
taggedValue('qux', 'spam')
taggedValue('bar', 'frob')
self.assertEqual(getattr(Foo, TAGGED_DATA, None),
{'bar': 'frob', 'qux': 'spam'})
class ElementTests(unittest.TestCase):
DEFAULT_NAME = 'AnElement'
def _getTargetClass(self):
from zope.interface.interface import Element
return Element
def _makeOne(self, name=None):
if name is None:
name = self.DEFAULT_NAME
return self._getTargetClass()(name)
def test_ctor_defaults(self):
element = self._makeOne()
self.assertEqual(element.__name__, self.DEFAULT_NAME)
self.assertEqual(element.getName(), self.DEFAULT_NAME)
self.assertEqual(element.__doc__, '')
self.assertEqual(element.getDoc(), '')
self.assertEqual(list(element.getTaggedValueTags()), [])
def test_ctor_no_doc_space_in_name(self):
element = self._makeOne('An Element')
self.assertEqual(element.__name__, None)
self.assertEqual(element.__doc__, 'An Element')
def test_getTaggedValue_miss(self):
element = self._makeOne()
self.assertRaises(KeyError, element.getTaggedValue, 'nonesuch')
def test_getDirectTaggedValueTags(self):
element = self._makeOne()
self.assertEqual([], list(element.getDirectTaggedValueTags()))
element.setTaggedValue('foo', 'bar')
self.assertEqual(['foo'], list(element.getDirectTaggedValueTags()))
def test_queryTaggedValue_miss(self):
element = self._makeOne()
self.assertEqual(element.queryTaggedValue('nonesuch'), None)
def test_queryTaggedValue_miss_w_default(self):
element = self._makeOne()
self.assertEqual(element.queryTaggedValue('nonesuch', 'bar'), 'bar')
def test_getDirectTaggedValue_miss(self):
element = self._makeOne()
self.assertRaises(KeyError, element.getDirectTaggedValue, 'nonesuch')
def test_queryDirectTaggedValue_miss(self):
element = self._makeOne()
self.assertEqual(element.queryDirectTaggedValue('nonesuch'), None)
def test_queryDirectTaggedValue_miss_w_default(self):
element = self._makeOne()
self.assertEqual(element.queryDirectTaggedValue('nonesuch', 'bar'), 'bar')
def test_setTaggedValue(self):
element = self._makeOne()
element.setTaggedValue('foo', 'bar')
self.assertEqual(list(element.getTaggedValueTags()), ['foo'])
self.assertEqual(element.getTaggedValue('foo'), 'bar')
self.assertEqual(element.queryTaggedValue('foo'), 'bar')
def test_verifies(self):
from zope.interface.interfaces import IElement
from zope.interface.verify import verifyObject
element = self._makeOne()
verifyObject(IElement, element)
class GenericSpecificationBaseTests(unittest.TestCase):
# Tests that work with both implementations
def _getFallbackClass(self):
from zope.interface.interface import SpecificationBasePy # pylint:disable=no-name-in-module
return SpecificationBasePy
_getTargetClass = _getFallbackClass
def _makeOne(self):
return self._getTargetClass()()
def test_providedBy_miss(self):
from zope.interface import interface
from zope.interface.declarations import _empty
sb = self._makeOne()
def _providedBy(obj):
return _empty
with _Monkey(interface, providedBy=_providedBy):
self.assertFalse(sb.providedBy(object()))
def test_implementedBy_miss(self):
from zope.interface import interface
from zope.interface.declarations import _empty
sb = self._makeOne()
def _implementedBy(obj):
return _empty
with _Monkey(interface, implementedBy=_implementedBy):
self.assertFalse(sb.implementedBy(object()))
class SpecificationBaseTests(GenericSpecificationBaseTests,
OptimizationTestMixin):
# Tests that use the C implementation
def _getTargetClass(self):
from zope.interface.interface import SpecificationBase
return SpecificationBase
class SpecificationBasePyTests(GenericSpecificationBaseTests):
# Tests that only work with the Python implementation
def test___call___miss(self):
sb = self._makeOne()
sb._implied = {} # not defined by SpecificationBasePy
self.assertFalse(sb.isOrExtends(object()))
def test___call___hit(self):
sb = self._makeOne()
testing = object()
sb._implied = {testing: {}} # not defined by SpecificationBasePy
self.assertTrue(sb(testing))
def test_isOrExtends_miss(self):
sb = self._makeOne()
sb._implied = {} # not defined by SpecificationBasePy
self.assertFalse(sb.isOrExtends(object()))
def test_isOrExtends_hit(self):
sb = self._makeOne()
testing = object()
sb._implied = {testing: {}} # not defined by SpecificationBasePy
self.assertTrue(sb(testing))
def test_implementedBy_hit(self):
from zope.interface import interface
sb = self._makeOne()
class _Decl(object):
_implied = {sb: {},}
def _implementedBy(obj):
return _Decl()
with _Monkey(interface, implementedBy=_implementedBy):
self.assertTrue(sb.implementedBy(object()))
def test_providedBy_hit(self):
from zope.interface import interface
sb = self._makeOne()
class _Decl(object):
_implied = {sb: {},}
def _providedBy(obj):
return _Decl()
with _Monkey(interface, providedBy=_providedBy):
self.assertTrue(sb.providedBy(object()))
class NameAndModuleComparisonTestsMixin(CleanUp):
def _makeOneToCompare(self):
return self._makeOne('a', 'b')
def __check_NotImplemented_comparison(self, name):
# Without the correct attributes of __name__ and __module__,
# comparison switches to the reverse direction.
import operator
ib = self._makeOneToCompare()
op = getattr(operator, name)
meth = getattr(ib, '__%s__' % name)
# If either the __name__ or __module__ attribute
# is missing from the other object, then we return
# NotImplemented.
class RaisesErrorOnMissing(object):
Exc = AttributeError
def __getattribute__(self, name):
try:
return object.__getattribute__(self, name)
except AttributeError:
exc = RaisesErrorOnMissing.Exc
raise exc(name)
class RaisesErrorOnModule(RaisesErrorOnMissing):
def __init__(self):
self.__name__ = 'foo'
@property
def __module__(self):
raise AttributeError
class RaisesErrorOnName(RaisesErrorOnMissing):
def __init__(self):
self.__module__ = 'foo'
self.assertEqual(RaisesErrorOnModule().__name__, 'foo')
self.assertEqual(RaisesErrorOnName().__module__, 'foo')
with self.assertRaises(AttributeError):
getattr(RaisesErrorOnModule(), '__module__')
with self.assertRaises(AttributeError):
getattr(RaisesErrorOnName(), '__name__')
for cls in RaisesErrorOnModule, RaisesErrorOnName:
self.assertIs(meth(cls()), NotImplemented)
# If the other object has a comparison function, returning
# NotImplemented means Python calls it.
class AllowsAnyComparison(RaisesErrorOnMissing):
def __eq__(self, other):
return True
__lt__ = __eq__
__le__ = __eq__
__gt__ = __eq__
__ge__ = __eq__
__ne__ = __eq__
self.assertTrue(op(ib, AllowsAnyComparison()))
self.assertIs(meth(AllowsAnyComparison()), NotImplemented)
# If it doesn't have the comparison, Python raises a TypeError.
class AllowsNoComparison(object):
__eq__ = None
__lt__ = __eq__
__le__ = __eq__
__gt__ = __eq__
__ge__ = __eq__
__ne__ = __eq__
self.assertIs(meth(AllowsNoComparison()), NotImplemented)
with self.assertRaises(TypeError):
op(ib, AllowsNoComparison())
# Errors besides AttributeError are passed
class MyException(Exception):
pass
RaisesErrorOnMissing.Exc = MyException
with self.assertRaises(MyException):
getattr(RaisesErrorOnModule(), '__module__')
with self.assertRaises(MyException):
getattr(RaisesErrorOnName(), '__name__')
for cls in RaisesErrorOnModule, RaisesErrorOnName:
with self.assertRaises(MyException):
op(ib, cls())
with self.assertRaises(MyException):
meth(cls())
def test__lt__NotImplemented(self):
self.__check_NotImplemented_comparison('lt')
def test__le__NotImplemented(self):
self.__check_NotImplemented_comparison('le')
def test__gt__NotImplemented(self):
self.__check_NotImplemented_comparison('gt')
def test__ge__NotImplemented(self):
self.__check_NotImplemented_comparison('ge')
class InterfaceBaseTestsMixin(NameAndModuleComparisonTestsMixin):
# Tests for both C and Python implementation
def _getTargetClass(self):
raise NotImplementedError
def _getFallbackClass(self):
# pylint:disable=no-name-in-module
from zope.interface.interface import InterfaceBasePy
return InterfaceBasePy
def _makeOne(self, object_should_provide=False, name=None, module=None):
class IB(self._getTargetClass()):
def _call_conform(self, conform):
return conform(self)
def providedBy(self, obj):
return object_should_provide
return IB(name, module)
def test___call___w___conform___returning_value(self):
ib = self._makeOne(False)
conformed = object()
class _Adapted(object):
def __conform__(self, iface):
return conformed
self.assertIs(ib(_Adapted()), conformed)
def test___call___wo___conform___ob_no_provides_w_alternate(self):
ib = self._makeOne(False)
__traceback_info__ = ib, self._getTargetClass()
adapted = object()
alternate = object()
self.assertIs(ib(adapted, alternate), alternate)
def test___call___w___conform___ob_no_provides_wo_alternate(self):
ib = self._makeOne(False)
with self.assertRaises(TypeError) as exc:
ib(object())
self.assertIn('Could not adapt', str(exc.exception))
def test___call___w_no_conform_catches_only_AttributeError(self):
MissingSomeAttrs.test_raises(self, self._makeOne(), expected_missing='__conform__')
class InterfaceBaseTests(InterfaceBaseTestsMixin,
OptimizationTestMixin,
unittest.TestCase):
# Tests that work with the C implementation
def _getTargetClass(self):
from zope.interface.interface import InterfaceBase
return InterfaceBase
class InterfaceBasePyTests(InterfaceBaseTestsMixin, unittest.TestCase):
# Tests that only work with the Python implementation
_getTargetClass = InterfaceBaseTestsMixin._getFallbackClass
def test___call___w___conform___miss_ob_provides(self):
ib = self._makeOne(True)
class _Adapted(object):
def __conform__(self, iface):
return None
adapted = _Adapted()
self.assertIs(ib(adapted), adapted)
def test___adapt___ob_provides(self):
ib = self._makeOne(True)
adapted = object()
self.assertIs(ib.__adapt__(adapted), adapted)
def test___adapt___ob_no_provides_uses_hooks(self):
from zope.interface import interface
ib = self._makeOne(False)
adapted = object()
_missed = []
def _hook_miss(iface, obj):
_missed.append((iface, obj))
def _hook_hit(iface, obj):
return obj
with _Monkey(interface, adapter_hooks=[_hook_miss, _hook_hit]):
self.assertIs(ib.__adapt__(adapted), adapted)
self.assertEqual(_missed, [(ib, adapted)])
class SpecificationTests(unittest.TestCase):
def _getTargetClass(self):
from zope.interface.interface import Specification
return Specification
def _makeOne(self, bases=_marker):
if bases is _marker:
return self._getTargetClass()()
return self._getTargetClass()(bases)
def test_ctor(self):
from zope.interface.interface import Interface
spec = self._makeOne()
self.assertEqual(spec.__bases__, ())
self.assertEqual(len(spec._implied), 2)
self.assertTrue(spec in spec._implied)
self.assertTrue(Interface in spec._implied)
self.assertEqual(len(spec.dependents), 0)
def test_subscribe_first_time(self):
spec = self._makeOne()
dep = DummyDependent()
spec.subscribe(dep)
self.assertEqual(len(spec.dependents), 1)
self.assertEqual(spec.dependents[dep], 1)
def test_subscribe_again(self):
spec = self._makeOne()
dep = DummyDependent()
spec.subscribe(dep)
spec.subscribe(dep)
self.assertEqual(spec.dependents[dep], 2)
def test_unsubscribe_miss(self):
spec = self._makeOne()
dep = DummyDependent()
self.assertRaises(KeyError, spec.unsubscribe, dep)
def test_unsubscribe(self):
spec = self._makeOne()
dep = DummyDependent()
spec.subscribe(dep)
spec.subscribe(dep)
spec.unsubscribe(dep)
self.assertEqual(spec.dependents[dep], 1)
spec.unsubscribe(dep)
self.assertFalse(dep in spec.dependents)
def test___setBases_subscribes_bases_and_notifies_dependents(self):
from zope.interface.interface import Interface
spec = self._makeOne()
dep = DummyDependent()
spec.subscribe(dep)
class I(Interface):
pass
class J(Interface):
pass
spec.__bases__ = (I,)
self.assertEqual(dep._changed, [spec])
self.assertEqual(I.dependents[spec], 1)
spec.__bases__ = (J,)
self.assertEqual(I.dependents.get(spec), None)
self.assertEqual(J.dependents[spec], 1)
def test_changed_clears_volatiles_and_implied(self):
from zope.interface.interface import Interface
class I(Interface):
pass
spec = self._makeOne()
spec._v_attrs = 'Foo'
spec._implied[I] = ()
spec.changed(spec)
self.assertIsNone(spec._v_attrs)
self.assertFalse(I in spec._implied)
def test_interfaces_skips_already_seen(self):
from zope.interface.interface import Interface
class IFoo(Interface):
pass
spec = self._makeOne([IFoo, IFoo])
self.assertEqual(list(spec.interfaces()), [IFoo])
def test_extends_strict_wo_self(self):
from zope.interface.interface import Interface
class IFoo(Interface):
pass
spec = self._makeOne(IFoo)
self.assertFalse(spec.extends(IFoo, strict=True))
def test_extends_strict_w_self(self):
spec = self._makeOne()
self.assertFalse(spec.extends(spec, strict=True))
def test_extends_non_strict_w_self(self):
spec = self._makeOne()
self.assertTrue(spec.extends(spec, strict=False))
def test_get_hit_w__v_attrs(self):
spec = self._makeOne()
foo = object()
spec._v_attrs = {'foo': foo}
self.assertTrue(spec.get('foo') is foo)
def test_get_hit_from_base_wo__v_attrs(self):
from zope.interface.interface import Attribute
from zope.interface.interface import Interface
class IFoo(Interface):
foo = Attribute('foo')
class IBar(Interface):
bar = Attribute('bar')
spec = self._makeOne([IFoo, IBar])
self.assertTrue(spec.get('foo') is IFoo.get('foo'))
self.assertTrue(spec.get('bar') is IBar.get('bar'))
def test_multiple_inheritance_no_interfaces(self):
# If we extend an object that implements interfaces,
# plus one that doesn't, we do not interject `Interface`
# early in the resolution order. It stays at the end,
# like it should.
# See https://github.com/zopefoundation/zope.interface/issues/8
from zope.interface.interface import Interface
from zope.interface.declarations import implementer
from zope.interface.declarations import implementedBy
class IDefaultViewName(Interface):
pass
class Context(object):
pass
class RDBModel(Context):
pass
class IOther(Interface):
pass
@implementer(IOther)
class OtherBase(object):
pass
class Model(OtherBase, Context):
pass
self.assertEqual(
implementedBy(Model).__sro__,
(
implementedBy(Model),
implementedBy(OtherBase),
IOther,
implementedBy(Context),
implementedBy(object),
Interface, # This used to be wrong, it used to be 2 too high.
)
)
class InterfaceClassTests(unittest.TestCase):
def _getTargetClass(self):
from zope.interface.interface import InterfaceClass
return InterfaceClass
def _makeOne(self, name='ITest', bases=(), attrs=None, __doc__=None,
__module__=None):
return self._getTargetClass()(name, bases, attrs, __doc__, __module__)
def test_ctor_defaults(self):
klass = self._getTargetClass()
inst = klass('ITesting')
self.assertEqual(inst.__name__, 'ITesting')
self.assertEqual(inst.__doc__, '')
self.assertEqual(inst.__bases__, ())
self.assertEqual(inst.getBases(), ())
def test_ctor_bad_bases(self):
klass = self._getTargetClass()
self.assertRaises(TypeError, klass, 'ITesting', (object(),))
def test_ctor_w_attrs_attrib_methods(self):
from zope.interface.interface import Attribute
from zope.interface.interface import fromFunction
def _bar():
"""DOCSTRING"""
ATTRS = {'foo': Attribute('Foo', ''),
'bar': fromFunction(_bar),
}
klass = self._getTargetClass()
inst = klass('ITesting', attrs=ATTRS)
self.assertEqual(inst.__name__, 'ITesting')
self.assertEqual(inst.__doc__, '')
self.assertEqual(inst.__bases__, ())
self.assertEqual(inst.names(), ATTRS.keys())
def test_ctor_attrs_w___locals__(self):
ATTRS = {'__locals__': {}}
klass = self._getTargetClass()
inst = klass('ITesting', attrs=ATTRS)
self.assertEqual(inst.__name__, 'ITesting')
self.assertEqual(inst.__doc__, '')
self.assertEqual(inst.__bases__, ())
self.assertEqual(list(inst.names()), [])
def test_ctor_attrs_w___annotations__(self):
ATTRS = {'__annotations__': {}}
klass = self._getTargetClass()
inst = klass('ITesting', attrs=ATTRS)
self.assertEqual(inst.__name__, 'ITesting')
self.assertEqual(inst.__doc__, '')
self.assertEqual(inst.__bases__, ())
self.assertEqual(list(inst.names()), [])
def test_ctor_attrs_w__decorator_non_return(self):
from zope.interface.interface import _decorator_non_return
ATTRS = {'dropme': _decorator_non_return}
klass = self._getTargetClass()
inst = klass('ITesting', attrs=ATTRS)
self.assertEqual(inst.__name__, 'ITesting')
self.assertEqual(inst.__doc__, '')
self.assertEqual(inst.__bases__, ())
self.assertEqual(list(inst.names()), [])
def test_ctor_attrs_w_invalid_attr_type(self):
from zope.interface.exceptions import InvalidInterface
ATTRS = {'invalid': object()}
klass = self._getTargetClass()
self.assertRaises(InvalidInterface, klass, 'ITesting', attrs=ATTRS)
def test_ctor_w_explicit___doc__(self):
ATTRS = {'__doc__': 'ATTR'}
klass = self._getTargetClass()
inst = klass('ITesting', attrs=ATTRS, __doc__='EXPLICIT')
self.assertEqual(inst.__doc__, 'EXPLICIT')
def test_interfaces(self):
iface = self._makeOne()
self.assertEqual(list(iface.interfaces()), [iface])
def test_getBases(self):
iface = self._makeOne()
sub = self._makeOne('ISub', bases=(iface,))
self.assertEqual(sub.getBases(), (iface,))
def test_isEqualOrExtendedBy_identity(self):
iface = self._makeOne()
self.assertTrue(iface.isEqualOrExtendedBy(iface))
def test_isEqualOrExtendedBy_subiface(self):
iface = self._makeOne()
sub = self._makeOne('ISub', bases=(iface,))
self.assertTrue(iface.isEqualOrExtendedBy(sub))
self.assertFalse(sub.isEqualOrExtendedBy(iface))
def test_isEqualOrExtendedBy_unrelated(self):
one = self._makeOne('One')
another = self._makeOne('Another')
self.assertFalse(one.isEqualOrExtendedBy(another))
self.assertFalse(another.isEqualOrExtendedBy(one))
def test_names_w_all_False_ignores_bases(self):
from zope.interface.interface import Attribute
from zope.interface.interface import fromFunction
def _bar():
"""DOCSTRING"""
BASE_ATTRS = {'foo': Attribute('Foo', ''),
'bar': fromFunction(_bar),
}
DERIVED_ATTRS = {'baz': Attribute('Baz', ''),
}
base = self._makeOne('IBase', attrs=BASE_ATTRS)
derived = self._makeOne('IDerived', bases=(base,), attrs=DERIVED_ATTRS)
self.assertEqual(sorted(derived.names(all=False)), ['baz'])
def test_names_w_all_True_no_bases(self):
from zope.interface.interface import Attribute
from zope.interface.interface import fromFunction
def _bar():
"""DOCSTRING"""
ATTRS = {'foo': Attribute('Foo', ''),
'bar': fromFunction(_bar),
}
one = self._makeOne(attrs=ATTRS)
self.assertEqual(sorted(one.names(all=True)), ['bar', 'foo'])
def test_names_w_all_True_w_bases_simple(self):
from zope.interface.interface import Attribute
from zope.interface.interface import fromFunction
def _bar():
"""DOCSTRING"""
BASE_ATTRS = {'foo': Attribute('Foo', ''),
'bar': fromFunction(_bar),
}
DERIVED_ATTRS = {'baz': Attribute('Baz', ''),
}
base = self._makeOne('IBase', attrs=BASE_ATTRS)
derived = self._makeOne('IDerived', bases=(base,), attrs=DERIVED_ATTRS)
self.assertEqual(sorted(derived.names(all=True)), ['bar', 'baz', 'foo'])
def test_names_w_all_True_bases_w_same_names(self):
from zope.interface.interface import Attribute
from zope.interface.interface import fromFunction
def _bar():
"""DOCSTRING"""
def _foo():
"""DOCSTRING"""
BASE_ATTRS = {'foo': Attribute('Foo', ''),
'bar': fromFunction(_bar),
}
DERIVED_ATTRS = {'foo': fromFunction(_foo),
'baz': Attribute('Baz', ''),
}
base = self._makeOne('IBase', attrs=BASE_ATTRS)
derived = self._makeOne('IDerived', bases=(base,), attrs=DERIVED_ATTRS)
self.assertEqual(sorted(derived.names(all=True)), ['bar', 'baz', 'foo'])
def test___iter__(self):
from zope.interface.interface import Attribute
from zope.interface.interface import fromFunction
def _bar():
"""DOCSTRING"""
def _foo():
"""DOCSTRING"""
BASE_ATTRS = {'foo': Attribute('Foo', ''),
'bar': fromFunction(_bar),
}
DERIVED_ATTRS = {'foo': fromFunction(_foo),
'baz': Attribute('Baz', ''),
}
base = self._makeOne('IBase', attrs=BASE_ATTRS)
derived = self._makeOne('IDerived', bases=(base,), attrs=DERIVED_ATTRS)
self.assertEqual(sorted(derived), ['bar', 'baz', 'foo'])
def test_namesAndDescriptions_w_all_False_ignores_bases(self):
from zope.interface.interface import Attribute
from zope.interface.interface import fromFunction
def _bar():
"""DOCSTRING"""
BASE_ATTRS = {'foo': Attribute('Foo', ''),
'bar': fromFunction(_bar),
}
DERIVED_ATTRS = {'baz': Attribute('Baz', ''),
}
base = self._makeOne('IBase', attrs=BASE_ATTRS)
derived = self._makeOne('IDerived', bases=(base,), attrs=DERIVED_ATTRS)
self.assertEqual(sorted(derived.namesAndDescriptions(all=False)),
[('baz', DERIVED_ATTRS['baz']),
])
def test_namesAndDescriptions_w_all_True_no_bases(self):
from zope.interface.interface import Attribute
from zope.interface.interface import fromFunction
def _bar():
"""DOCSTRING"""
ATTRS = {'foo': Attribute('Foo', ''),
'bar': fromFunction(_bar),
}
one = self._makeOne(attrs=ATTRS)
self.assertEqual(sorted(one.namesAndDescriptions(all=False)),
[('bar', ATTRS['bar']),
('foo', ATTRS['foo']),
])
def test_namesAndDescriptions_w_all_True_simple(self):
from zope.interface.interface import Attribute
from zope.interface.interface import fromFunction
def _bar():
"""DOCSTRING"""
BASE_ATTRS = {'foo': Attribute('Foo', ''),
'bar': fromFunction(_bar),
}
DERIVED_ATTRS = {'baz': Attribute('Baz', ''),
}
base = self._makeOne('IBase', attrs=BASE_ATTRS)
derived = self._makeOne('IDerived', bases=(base,), attrs=DERIVED_ATTRS)
self.assertEqual(sorted(derived.namesAndDescriptions(all=True)),
[('bar', BASE_ATTRS['bar']),
('baz', DERIVED_ATTRS['baz']),
('foo', BASE_ATTRS['foo']),
])
def test_namesAndDescriptions_w_all_True_bases_w_same_names(self):
from zope.interface.interface import Attribute
from zope.interface.interface import fromFunction
def _bar():
"""DOCSTRING"""
def _foo():
"""DOCSTRING"""
BASE_ATTRS = {'foo': Attribute('Foo', ''),
'bar': fromFunction(_bar),
}
DERIVED_ATTRS = {'foo': fromFunction(_foo),
'baz': Attribute('Baz', ''),
}
base = self._makeOne('IBase', attrs=BASE_ATTRS)
derived = self._makeOne('IDerived', bases=(base,), attrs=DERIVED_ATTRS)
self.assertEqual(sorted(derived.namesAndDescriptions(all=True)),
[('bar', BASE_ATTRS['bar']),
('baz', DERIVED_ATTRS['baz']),
('foo', DERIVED_ATTRS['foo']),
])
def test_getDescriptionFor_miss(self):
one = self._makeOne()
self.assertRaises(KeyError, one.getDescriptionFor, 'nonesuch')
def test_getDescriptionFor_hit(self):
from zope.interface.interface import Attribute
from zope.interface.interface import fromFunction
def _bar():
"""DOCSTRING"""
ATTRS = {'foo': Attribute('Foo', ''),
'bar': fromFunction(_bar),
}
one = self._makeOne(attrs=ATTRS)
self.assertEqual(one.getDescriptionFor('foo'), ATTRS['foo'])
self.assertEqual(one.getDescriptionFor('bar'), ATTRS['bar'])
def test___getitem___miss(self):
one = self._makeOne()
def _test():
return one['nonesuch']
self.assertRaises(KeyError, _test)
def test___getitem___hit(self):
from zope.interface.interface import Attribute
from zope.interface.interface import fromFunction
def _bar():
"""DOCSTRING"""
ATTRS = {'foo': Attribute('Foo', ''),
'bar': fromFunction(_bar),
}
one = self._makeOne(attrs=ATTRS)
self.assertEqual(one['foo'], ATTRS['foo'])
self.assertEqual(one['bar'], ATTRS['bar'])
def test___contains___miss(self):
one = self._makeOne()
self.assertFalse('nonesuch' in one)
def test___contains___hit(self):
from zope.interface.interface import Attribute
from zope.interface.interface import fromFunction
def _bar():
"""DOCSTRING"""
ATTRS = {'foo': Attribute('Foo', ''),
'bar': fromFunction(_bar),
}
one = self._makeOne(attrs=ATTRS)
self.assertTrue('foo' in one)
self.assertTrue('bar' in one)
def test_direct_miss(self):
one = self._makeOne()
self.assertEqual(one.direct('nonesuch'), None)
def test_direct_hit_local_miss_bases(self):
from zope.interface.interface import Attribute
from zope.interface.interface import fromFunction
def _bar():
"""DOCSTRING"""
def _foo():
"""DOCSTRING"""
BASE_ATTRS = {'foo': Attribute('Foo', ''),
'bar': fromFunction(_bar),
}
DERIVED_ATTRS = {'foo': fromFunction(_foo),
'baz': Attribute('Baz', ''),
}
base = self._makeOne('IBase', attrs=BASE_ATTRS)
derived = self._makeOne('IDerived', bases=(base,), attrs=DERIVED_ATTRS)
self.assertEqual(derived.direct('foo'), DERIVED_ATTRS['foo'])
self.assertEqual(derived.direct('baz'), DERIVED_ATTRS['baz'])
self.assertEqual(derived.direct('bar'), None)
def test_queryDescriptionFor_miss(self):
iface = self._makeOne()
self.assertEqual(iface.queryDescriptionFor('nonesuch'), None)
def test_queryDescriptionFor_hit(self):
from zope.interface import Attribute
ATTRS = {'attr': Attribute('Title', 'Description')}
iface = self._makeOne(attrs=ATTRS)
self.assertEqual(iface.queryDescriptionFor('attr'), ATTRS['attr'])
def test_validateInvariants_pass(self):
_called_with = []
def _passable(*args, **kw):
_called_with.append((args, kw))
return True
iface = self._makeOne()
obj = object()
iface.setTaggedValue('invariants', [_passable])
self.assertEqual(iface.validateInvariants(obj), None)
self.assertEqual(_called_with, [((obj,), {})])
def test_validateInvariants_fail_wo_errors_passed(self):
from zope.interface.exceptions import Invalid
_passable_called_with = []
def _passable(*args, **kw):
_passable_called_with.append((args, kw))
return True
_fail_called_with = []
def _fail(*args, **kw):
_fail_called_with.append((args, kw))
raise Invalid
iface = self._makeOne()
obj = object()
iface.setTaggedValue('invariants', [_passable, _fail])
self.assertRaises(Invalid, iface.validateInvariants, obj)
self.assertEqual(_passable_called_with, [((obj,), {})])
self.assertEqual(_fail_called_with, [((obj,), {})])
def test_validateInvariants_fail_w_errors_passed(self):
from zope.interface.exceptions import Invalid
_errors = []
_fail_called_with = []
def _fail(*args, **kw):
_fail_called_with.append((args, kw))
raise Invalid
iface = self._makeOne()
obj = object()
iface.setTaggedValue('invariants', [_fail])
self.assertRaises(Invalid, iface.validateInvariants, obj, _errors)
self.assertEqual(_fail_called_with, [((obj,), {})])
self.assertEqual(len(_errors), 1)
self.assertTrue(isinstance(_errors[0], Invalid))
def test_validateInvariants_fail_in_base_wo_errors_passed(self):
from zope.interface.exceptions import Invalid
_passable_called_with = []
def _passable(*args, **kw):
_passable_called_with.append((args, kw))
return True
_fail_called_with = []
def _fail(*args, **kw):
_fail_called_with.append((args, kw))
raise Invalid
base = self._makeOne('IBase')
derived = self._makeOne('IDerived', (base,))
obj = object()
base.setTaggedValue('invariants', [_fail])
derived.setTaggedValue('invariants', [_passable])
self.assertRaises(Invalid, derived.validateInvariants, obj)
self.assertEqual(_passable_called_with, [((obj,), {})])
self.assertEqual(_fail_called_with, [((obj,), {})])
def test_validateInvariants_fail_in_base_w_errors_passed(self):
from zope.interface.exceptions import Invalid
_errors = []
_passable_called_with = []
def _passable(*args, **kw):
_passable_called_with.append((args, kw))
return True
_fail_called_with = []
def _fail(*args, **kw):
_fail_called_with.append((args, kw))
raise Invalid
base = self._makeOne('IBase')
derived = self._makeOne('IDerived', (base,))
obj = object()
base.setTaggedValue('invariants', [_fail])
derived.setTaggedValue('invariants', [_passable])
self.assertRaises(Invalid, derived.validateInvariants, obj, _errors)
self.assertEqual(_passable_called_with, [((obj,), {})])
self.assertEqual(_fail_called_with, [((obj,), {})])
self.assertEqual(len(_errors), 1)
self.assertTrue(isinstance(_errors[0], Invalid))
def test_validateInvariants_inherited_not_called_multiple_times(self):
_passable_called_with = []
def _passable(*args, **kw):
_passable_called_with.append((args, kw))
return True
obj = object()
base = self._makeOne('IBase')
base.setTaggedValue('invariants', [_passable])
derived = self._makeOne('IDerived', (base,))
derived.validateInvariants(obj)
self.assertEqual(1, len(_passable_called_with))
def test___reduce__(self):
iface = self._makeOne('PickleMe')
self.assertEqual(iface.__reduce__(), 'PickleMe')
def test___hash___normal(self):
iface = self._makeOne('HashMe')
self.assertEqual(hash(iface),
hash((('HashMe',
'__tests__.tests.test_interface'))))
def test___hash___missing_required_attrs(self):
class Derived(self._getTargetClass()):
def __init__(self): # pylint:disable=super-init-not-called
pass # Don't call base class.
derived = Derived()
with self.assertRaises(AttributeError):
hash(derived)
def test_comparison_with_None(self):
# pylint:disable=singleton-comparison,misplaced-comparison-constant
iface = self._makeOne()
self.assertTrue(iface < None)
self.assertTrue(iface <= None)
self.assertFalse(iface == None)
self.assertTrue(iface != None)
self.assertFalse(iface >= None)
self.assertFalse(iface > None)
self.assertFalse(None < iface)
self.assertFalse(None <= iface)
self.assertFalse(None == iface)
self.assertTrue(None != iface)
self.assertTrue(None >= iface)
self.assertTrue(None > iface)
def test_comparison_with_same_instance(self):
# pylint:disable=comparison-with-itself
iface = self._makeOne()
self.assertFalse(iface < iface)
self.assertTrue(iface <= iface)
self.assertTrue(iface == iface)
self.assertFalse(iface != iface)
self.assertTrue(iface >= iface)
self.assertFalse(iface > iface)
def test_comparison_with_same_named_instance_in_other_module(self):
one = self._makeOne('IName', __module__='__tests__.tests.one')
other = self._makeOne('IName', __module__='__tests__.tests.other')
self.assertTrue(one < other)
self.assertFalse(other < one)
self.assertTrue(one <= other)
self.assertFalse(other <= one)
self.assertFalse(one == other)
self.assertFalse(other == one)
self.assertTrue(one != other)
self.assertTrue(other != one)
self.assertFalse(one >= other)
self.assertTrue(other >= one)
self.assertFalse(one > other)
self.assertTrue(other > one)
def test_assignment_to__class__(self):
# https://github.com/zopefoundation/zope.interface/issues/6
class MyException(Exception):
pass
class MyInterfaceClass(self._getTargetClass()):
def __call__(self, target):
raise MyException(target)
IFoo = self._makeOne('IName')
self.assertIsInstance(IFoo, self._getTargetClass())
self.assertIs(type(IFoo), self._getTargetClass())
with self.assertRaises(TypeError):
IFoo(1)
IFoo.__class__ = MyInterfaceClass
self.assertIsInstance(IFoo, MyInterfaceClass)
self.assertIs(type(IFoo), MyInterfaceClass)
with self.assertRaises(MyException):
IFoo(1)
def test_assignment_to__class__2(self):
# https://github.com/zopefoundation/zope.interface/issues/6
# This is essentially a transcription of the
# test presented in the bug report.
from zope.interface import Interface
class MyInterfaceClass(self._getTargetClass()):
def __call__(self, *args):
return args
IFoo = MyInterfaceClass('IFoo', (Interface,))
self.assertEqual(IFoo(1), (1,))
class IBar(IFoo):
pass
self.assertEqual(IBar(1), (1,))
class ISpam(Interface):
pass
with self.assertRaises(TypeError):
ISpam()
ISpam.__class__ = MyInterfaceClass
self.assertEqual(ISpam(1), (1,))
def test__module__is_readonly(self):
inst = self._makeOne()
with self.assertRaises((AttributeError, TypeError)):
# CPython 2.7 raises TypeError. Everything else
# raises AttributeError.
inst.__module__ = 'different.module'
class InterfaceTests(unittest.TestCase):
def test_attributes_link_to_interface(self):
from zope.interface import Interface
from zope.interface import Attribute
class I1(Interface):
attr = Attribute("My attr")
self.assertTrue(I1['attr'].interface is I1)
def test_methods_link_to_interface(self):
from zope.interface import Interface
class I1(Interface):
def method(foo, bar, bingo):
"A method"
self.assertTrue(I1['method'].interface is I1)
def test_classImplements_simple(self):
from zope.interface import Interface
from zope.interface import implementedBy
from zope.interface import providedBy
class ICurrent(Interface):
def method1(a, b):
"""docstring"""
def method2(a, b):
"""docstring"""
class IOther(Interface):
pass
class Current(object):
__implemented__ = ICurrent
def method1(self, a, b):
raise NotImplementedError()
def method2(self, a, b):
raise NotImplementedError()
current = Current()
self.assertTrue(ICurrent.implementedBy(Current))
self.assertFalse(IOther.implementedBy(Current))
self.assertEqual(ICurrent, ICurrent)
self.assertTrue(ICurrent in implementedBy(Current))
self.assertFalse(IOther in implementedBy(Current))
self.assertTrue(ICurrent in providedBy(current))
self.assertFalse(IOther in providedBy(current))
def test_classImplements_base_not_derived(self):
from zope.interface import Interface
from zope.interface import implementedBy
from zope.interface import providedBy
class IBase(Interface):
def method():
"""docstring"""
class IDerived(IBase):
pass
class Current():
__implemented__ = IBase
def method(self):
raise NotImplementedError()
current = Current()
self.assertTrue(IBase.implementedBy(Current))
self.assertFalse(IDerived.implementedBy(Current))
self.assertTrue(IBase in implementedBy(Current))
self.assertFalse(IDerived in implementedBy(Current))
self.assertTrue(IBase in providedBy(current))
self.assertFalse(IDerived in providedBy(current))
def test_classImplements_base_and_derived(self):
from zope.interface import Interface
from zope.interface import implementedBy
from zope.interface import providedBy
class IBase(Interface):
def method():
"""docstring"""
class IDerived(IBase):
pass
class Current(object):
__implemented__ = IDerived
def method(self):
raise NotImplementedError()
current = Current()
self.assertTrue(IBase.implementedBy(Current))
self.assertTrue(IDerived.implementedBy(Current))
self.assertFalse(IBase in implementedBy(Current))
self.assertTrue(IBase in implementedBy(Current).flattened())
self.assertTrue(IDerived in implementedBy(Current))
self.assertFalse(IBase in providedBy(current))
self.assertTrue(IBase in providedBy(current).flattened())
self.assertTrue(IDerived in providedBy(current))
def test_classImplements_multiple(self):
from zope.interface import Interface
from zope.interface import implementedBy
from zope.interface import providedBy
class ILeft(Interface):
def method():
"""docstring"""
class IRight(ILeft):
pass
class Left(object):
__implemented__ = ILeft
def method(self):
raise NotImplementedError()
class Right(object):
__implemented__ = IRight
class Ambi(Left, Right):
pass
ambi = Ambi()
self.assertTrue(ILeft.implementedBy(Ambi))
self.assertTrue(IRight.implementedBy(Ambi))
self.assertTrue(ILeft in implementedBy(Ambi))
self.assertTrue(IRight in implementedBy(Ambi))
self.assertTrue(ILeft in providedBy(ambi))
self.assertTrue(IRight in providedBy(ambi))
def test_classImplements_multiple_w_explict_implements(self):
from zope.interface import Interface
from zope.interface import implementedBy
from zope.interface import providedBy
class ILeft(Interface):
def method():
"""docstring"""
class IRight(ILeft):
pass
class IOther(Interface):
pass
class Left():
__implemented__ = ILeft
def method(self):
raise NotImplementedError()
class Right(object):
__implemented__ = IRight
class Other(object):
__implemented__ = IOther
class Mixed(Left, Right):
__implemented__ = Left.__implemented__, Other.__implemented__
mixed = Mixed()
self.assertTrue(ILeft.implementedBy(Mixed))
self.assertFalse(IRight.implementedBy(Mixed))
self.assertTrue(IOther.implementedBy(Mixed))
self.assertTrue(ILeft in implementedBy(Mixed))
self.assertFalse(IRight in implementedBy(Mixed))
self.assertTrue(IOther in implementedBy(Mixed))
self.assertTrue(ILeft in providedBy(mixed))
self.assertFalse(IRight in providedBy(mixed))
self.assertTrue(IOther in providedBy(mixed))
def testInterfaceExtendsInterface(self):
from zope.interface import Interface
new = Interface.__class__
FunInterface = new('FunInterface')
BarInterface = new('BarInterface', (FunInterface,))
BobInterface = new('BobInterface')
BazInterface = new('BazInterface', (BobInterface, BarInterface,))
self.assertTrue(BazInterface.extends(BobInterface))
self.assertTrue(BazInterface.extends(BarInterface))
self.assertTrue(BazInterface.extends(FunInterface))
self.assertFalse(BobInterface.extends(FunInterface))
self.assertFalse(BobInterface.extends(BarInterface))
self.assertTrue(BarInterface.extends(FunInterface))
self.assertFalse(BarInterface.extends(BazInterface))
def test_verifyClass(self):
from zope.interface import Attribute
from zope.interface import Interface
from zope.interface.verify import verifyClass
class ICheckMe(Interface):
attr = Attribute(u'My attr')
def method():
"A method"
class CheckMe(object):
__implemented__ = ICheckMe
attr = 'value'
def method(self):
raise NotImplementedError()
self.assertTrue(verifyClass(ICheckMe, CheckMe))
def test_verifyObject(self):
from zope.interface import Attribute
from zope.interface import Interface
from zope.interface.verify import verifyObject
class ICheckMe(Interface):
attr = Attribute(u'My attr')
def method():
"A method"
class CheckMe(object):
__implemented__ = ICheckMe
attr = 'value'
def method(self):
raise NotImplementedError()
check_me = CheckMe()
self.assertTrue(verifyObject(ICheckMe, check_me))
def test_interface_object_provides_Interface(self):
from zope.interface import Interface
class AnInterface(Interface):
pass
self.assertTrue(Interface.providedBy(AnInterface))
def test_names_simple(self):
from zope.interface import Attribute
from zope.interface import Interface
class ISimple(Interface):
attr = Attribute(u'My attr')
def method():
"""docstring"""
self.assertEqual(sorted(ISimple.names()), ['attr', 'method'])
def test_names_derived(self):
from zope.interface import Attribute
from zope.interface import Interface
class IBase(Interface):
attr = Attribute(u'My attr')
def method():
"""docstring"""
class IDerived(IBase):
attr2 = Attribute(u'My attr2')
def method():
"""docstring"""
def method2():
"""docstring"""
self.assertEqual(sorted(IDerived.names()),
['attr2', 'method', 'method2'])
self.assertEqual(sorted(IDerived.names(all=True)),
['attr', 'attr2', 'method', 'method2'])
def test_namesAndDescriptions_simple(self):
from zope.interface import Attribute
from zope.interface.interface import Method
from zope.interface import Interface
class ISimple(Interface):
attr = Attribute(u'My attr')
def method():
"My method"
name_values = sorted(ISimple.namesAndDescriptions())
self.assertEqual(len(name_values), 2)
self.assertEqual(name_values[0][0], 'attr')
self.assertTrue(isinstance(name_values[0][1], Attribute))
self.assertEqual(name_values[0][1].__name__, 'attr')
self.assertEqual(name_values[0][1].__doc__, 'My attr')
self.assertEqual(name_values[1][0], 'method')
self.assertTrue(isinstance(name_values[1][1], Method))
self.assertEqual(name_values[1][1].__name__, 'method')
self.assertEqual(name_values[1][1].__doc__, 'My method')
def test_namesAndDescriptions_derived(self):
from zope.interface import Attribute
from zope.interface import Interface
from zope.interface.interface import Method
class IBase(Interface):
attr = Attribute(u'My attr')
def method():
"My method"
class IDerived(IBase):
attr2 = Attribute(u'My attr2')
def method():
"My method, overridden"
def method2():
"My method2"
name_values = sorted(IDerived.namesAndDescriptions())
self.assertEqual(len(name_values), 3)
self.assertEqual(name_values[0][0], 'attr2')
self.assertTrue(isinstance(name_values[0][1], Attribute))
self.assertEqual(name_values[0][1].__name__, 'attr2')
self.assertEqual(name_values[0][1].__doc__, 'My attr2')
self.assertEqual(name_values[1][0], 'method')
self.assertTrue(isinstance(name_values[1][1], Method))
self.assertEqual(name_values[1][1].__name__, 'method')
self.assertEqual(name_values[1][1].__doc__, 'My method, overridden')
self.assertEqual(name_values[2][0], 'method2')
self.assertTrue(isinstance(name_values[2][1], Method))
self.assertEqual(name_values[2][1].__name__, 'method2')
self.assertEqual(name_values[2][1].__doc__, 'My method2')
name_values = sorted(IDerived.namesAndDescriptions(all=True))
self.assertEqual(len(name_values), 4)
self.assertEqual(name_values[0][0], 'attr')
self.assertTrue(isinstance(name_values[0][1], Attribute))
self.assertEqual(name_values[0][1].__name__, 'attr')
self.assertEqual(name_values[0][1].__doc__, 'My attr')
self.assertEqual(name_values[1][0], 'attr2')
self.assertTrue(isinstance(name_values[1][1], Attribute))
self.assertEqual(name_values[1][1].__name__, 'attr2')
self.assertEqual(name_values[1][1].__doc__, 'My attr2')
self.assertEqual(name_values[2][0], 'method')
self.assertTrue(isinstance(name_values[2][1], Method))
self.assertEqual(name_values[2][1].__name__, 'method')
self.assertEqual(name_values[2][1].__doc__, 'My method, overridden')
self.assertEqual(name_values[3][0], 'method2')
self.assertTrue(isinstance(name_values[3][1], Method))
self.assertEqual(name_values[3][1].__name__, 'method2')
self.assertEqual(name_values[3][1].__doc__, 'My method2')
def test_getDescriptionFor_nonesuch_no_default(self):
from zope.interface import Interface
class IEmpty(Interface):
pass
self.assertRaises(KeyError, IEmpty.getDescriptionFor, 'nonesuch')
def test_getDescriptionFor_simple(self):
from zope.interface import Attribute
from zope.interface.interface import Method
from zope.interface import Interface
class ISimple(Interface):
attr = Attribute(u'My attr')
def method():
"My method"
a_desc = ISimple.getDescriptionFor('attr')
self.assertTrue(isinstance(a_desc, Attribute))
self.assertEqual(a_desc.__name__, 'attr')
self.assertEqual(a_desc.__doc__, 'My attr')
m_desc = ISimple.getDescriptionFor('method')
self.assertTrue(isinstance(m_desc, Method))
self.assertEqual(m_desc.__name__, 'method')
self.assertEqual(m_desc.__doc__, 'My method')
def test_getDescriptionFor_derived(self):
from zope.interface import Attribute
from zope.interface.interface import Method
from zope.interface import Interface
class IBase(Interface):
attr = Attribute(u'My attr')
def method():
"My method"
class IDerived(IBase):
attr2 = Attribute(u'My attr2')
def method():
"My method, overridden"
def method2():
"My method2"
a_desc = IDerived.getDescriptionFor('attr')
self.assertTrue(isinstance(a_desc, Attribute))
self.assertEqual(a_desc.__name__, 'attr')
self.assertEqual(a_desc.__doc__, 'My attr')
m_desc = IDerived.getDescriptionFor('method')
self.assertTrue(isinstance(m_desc, Method))
self.assertEqual(m_desc.__name__, 'method')
self.assertEqual(m_desc.__doc__, 'My method, overridden')
a2_desc = IDerived.getDescriptionFor('attr2')
self.assertTrue(isinstance(a2_desc, Attribute))
self.assertEqual(a2_desc.__name__, 'attr2')
self.assertEqual(a2_desc.__doc__, 'My attr2')
m2_desc = IDerived.getDescriptionFor('method2')
self.assertTrue(isinstance(m2_desc, Method))
self.assertEqual(m2_desc.__name__, 'method2')
self.assertEqual(m2_desc.__doc__, 'My method2')
def test___getitem__nonesuch(self):
from zope.interface import Interface
class IEmpty(Interface):
pass
self.assertRaises(KeyError, IEmpty.__getitem__, 'nonesuch')
def test___getitem__simple(self):
from zope.interface import Attribute
from zope.interface.interface import Method
from zope.interface import Interface
class ISimple(Interface):
attr = Attribute(u'My attr')
def method():
"My method"
a_desc = ISimple['attr']
self.assertTrue(isinstance(a_desc, Attribute))
self.assertEqual(a_desc.__name__, 'attr')
self.assertEqual(a_desc.__doc__, 'My attr')
m_desc = ISimple['method']
self.assertTrue(isinstance(m_desc, Method))
self.assertEqual(m_desc.__name__, 'method')
self.assertEqual(m_desc.__doc__, 'My method')
def test___getitem___derived(self):
from zope.interface import Attribute
from zope.interface.interface import Method
from zope.interface import Interface
class IBase(Interface):
attr = Attribute(u'My attr')
def method():
"My method"
class IDerived(IBase):
attr2 = Attribute(u'My attr2')
def method():
"My method, overridden"
def method2():
"My method2"
a_desc = IDerived['attr']
self.assertTrue(isinstance(a_desc, Attribute))
self.assertEqual(a_desc.__name__, 'attr')
self.assertEqual(a_desc.__doc__, 'My attr')
m_desc = IDerived['method']
self.assertTrue(isinstance(m_desc, Method))
self.assertEqual(m_desc.__name__, 'method')
self.assertEqual(m_desc.__doc__, 'My method, overridden')
a2_desc = IDerived['attr2']
self.assertTrue(isinstance(a2_desc, Attribute))
self.assertEqual(a2_desc.__name__, 'attr2')
self.assertEqual(a2_desc.__doc__, 'My attr2')
m2_desc = IDerived['method2']
self.assertTrue(isinstance(m2_desc, Method))
self.assertEqual(m2_desc.__name__, 'method2')
self.assertEqual(m2_desc.__doc__, 'My method2')
def test___contains__nonesuch(self):
from zope.interface import Interface
class IEmpty(Interface):
pass
self.assertFalse('nonesuch' in IEmpty)
def test___contains__simple(self):
from zope.interface import Attribute
from zope.interface import Interface
class ISimple(Interface):
attr = Attribute(u'My attr')
def method():
"My method"
self.assertTrue('attr' in ISimple)
self.assertTrue('method' in ISimple)
def test___contains__derived(self):
from zope.interface import Attribute
from zope.interface import Interface
class IBase(Interface):
attr = Attribute(u'My attr')
def method():
"My method"
class IDerived(IBase):
attr2 = Attribute(u'My attr2')
def method():
"My method, overridden"
def method2():
"My method2"
self.assertTrue('attr' in IDerived)
self.assertTrue('method' in IDerived)
self.assertTrue('attr2' in IDerived)
self.assertTrue('method2' in IDerived)
def test___iter__empty(self):
from zope.interface import Interface
class IEmpty(Interface):
pass
self.assertEqual(list(IEmpty), [])
def test___iter__simple(self):
from zope.interface import Attribute
from zope.interface import Interface
class ISimple(Interface):
attr = Attribute(u'My attr')
def method():
"My method"
self.assertEqual(sorted(list(ISimple)), ['attr', 'method'])
def test___iter__derived(self):
from zope.interface import Attribute
from zope.interface import Interface
class IBase(Interface):
attr = Attribute(u'My attr')
def method():
"My method"
class IDerived(IBase):
attr2 = Attribute(u'My attr2')
def method():
"My method, overridden"
def method2():
"My method2"
self.assertEqual(sorted(list(IDerived)),
['attr', 'attr2', 'method', 'method2'])
def test_function_attributes_become_tagged_values(self):
from zope.interface import Interface
class ITagMe(Interface):
def method():
"""docstring"""
method.optional = 1
method = ITagMe['method']
self.assertEqual(method.getTaggedValue('optional'), 1)
def test___doc___non_element(self):
from zope.interface import Interface
class IHaveADocString(Interface):
"xxx"
self.assertEqual(IHaveADocString.__doc__, "xxx")
self.assertEqual(list(IHaveADocString), [])
def test___doc___as_element(self):
from zope.interface import Attribute
from zope.interface import Interface
class IHaveADocString(Interface):
"xxx"
__doc__ = Attribute('the doc')
self.assertEqual(IHaveADocString.__doc__, "")
self.assertEqual(list(IHaveADocString), ['__doc__'])
def _errorsEqual(self, has_invariant, error_len, error_msgs, iface):
from zope.interface.exceptions import Invalid
self.assertRaises(Invalid, iface.validateInvariants, has_invariant)
e = []
try:
iface.validateInvariants(has_invariant, e)
self.fail("validateInvariants should always raise")
except Invalid as error:
self.assertEqual(error.args[0], e)
self.assertEqual(len(e), error_len)
msgs = [error.args[0] for error in e]
msgs.sort()
for msg in msgs:
self.assertEqual(msg, error_msgs.pop(0))
def test_invariant_simple(self):
from zope.interface import Attribute
from zope.interface import Interface
from zope.interface import directlyProvides
from zope.interface import invariant
class IInvariant(Interface):
foo = Attribute('foo')
bar = Attribute('bar; must eval to Boolean True if foo does')
invariant(_ifFooThenBar)
class HasInvariant(object):
pass
# set up
has_invariant = HasInvariant()
directlyProvides(has_invariant, IInvariant)
# the tests
self.assertEqual(IInvariant.getTaggedValue('invariants'),
[_ifFooThenBar])
self.assertEqual(IInvariant.validateInvariants(has_invariant), None)
has_invariant.bar = 27
self.assertEqual(IInvariant.validateInvariants(has_invariant), None)
has_invariant.foo = 42
self.assertEqual(IInvariant.validateInvariants(has_invariant), None)
del has_invariant.bar
self._errorsEqual(has_invariant, 1, ['If Foo, then Bar!'],
IInvariant)
def test_invariant_nested(self):
from zope.interface import Attribute
from zope.interface import Interface
from zope.interface import directlyProvides
from zope.interface import invariant
class IInvariant(Interface):
foo = Attribute('foo')
bar = Attribute('bar; must eval to Boolean True if foo does')
invariant(_ifFooThenBar)
class ISubInvariant(IInvariant):
invariant(_barGreaterThanFoo)
class HasInvariant(object):
pass
# nested interfaces with invariants:
self.assertEqual(ISubInvariant.getTaggedValue('invariants'),
[_barGreaterThanFoo])
has_invariant = HasInvariant()
directlyProvides(has_invariant, ISubInvariant)
has_invariant.foo = 42
# even though the interface has changed, we should still only have one
# error.
self._errorsEqual(has_invariant, 1, ['If Foo, then Bar!'],
ISubInvariant)
# however, if we set foo to 0 (Boolean False) and bar to a negative
# number then we'll get the new error
has_invariant.foo = 2
has_invariant.bar = 1
self._errorsEqual(has_invariant, 1,
['Please, Boo MUST be greater than Foo!'],
ISubInvariant)
# and if we set foo to a positive number and boo to 0, we'll
# get both errors!
has_invariant.foo = 1
has_invariant.bar = 0
self._errorsEqual(has_invariant, 2,
['If Foo, then Bar!',
'Please, Boo MUST be greater than Foo!'],
ISubInvariant)
# for a happy ending, we'll make the invariants happy
has_invariant.foo = 1
has_invariant.bar = 2
self.assertEqual(IInvariant.validateInvariants(has_invariant), None)
def test_invariant_mutandis(self):
from zope.interface import Attribute
from zope.interface import Interface
from zope.interface import directlyProvides
from zope.interface import invariant
class IInvariant(Interface):
foo = Attribute('foo')
bar = Attribute('bar; must eval to Boolean True if foo does')
invariant(_ifFooThenBar)
class HasInvariant(object):
pass
# now we'll do two invariants on the same interface,
# just to make sure that a small
# multi-invariant interface is at least minimally tested.
has_invariant = HasInvariant()
directlyProvides(has_invariant, IInvariant)
has_invariant.foo = 42
# if you really need to mutate, then this would be the way to do it.
# Probably a bad idea, though. :-)
old_invariants = IInvariant.getTaggedValue('invariants')
invariants = old_invariants[:]
invariants.append(_barGreaterThanFoo)
IInvariant.setTaggedValue('invariants', invariants)
# even though the interface has changed, we should still only have one
# error.
self._errorsEqual(has_invariant, 1, ['If Foo, then Bar!'],
IInvariant)
# however, if we set foo to 0 (Boolean False) and bar to a negative
# number then we'll get the new error
has_invariant.foo = 2
has_invariant.bar = 1
self._errorsEqual(has_invariant, 1,
['Please, Boo MUST be greater than Foo!'], IInvariant)
# and if we set foo to a positive number and boo to 0, we'll
# get both errors!
has_invariant.foo = 1
has_invariant.bar = 0
self._errorsEqual(has_invariant, 2,
['If Foo, then Bar!',
'Please, Boo MUST be greater than Foo!'],
IInvariant)
# for another happy ending, we'll make the invariants happy again
has_invariant.foo = 1
has_invariant.bar = 2
self.assertEqual(IInvariant.validateInvariants(has_invariant), None)
# clean up
IInvariant.setTaggedValue('invariants', old_invariants)
def test___doc___element(self):
from zope.interface import Interface
from zope.interface import Attribute
class IDocstring(Interface):
"xxx"
self.assertEqual(IDocstring.__doc__, "xxx")
self.assertEqual(list(IDocstring), [])
class IDocstringAndAttribute(Interface):
"xxx"
__doc__ = Attribute('the doc')
self.assertEqual(IDocstringAndAttribute.__doc__, "")
self.assertEqual(list(IDocstringAndAttribute), ['__doc__'])
@_skip_under_py3k
def testIssue228(self):
# Test for http://collector.zope.org/Zope3-dev/228
# Old style classes don't have a '__class__' attribute
# No old style classes in Python 3, so the test becomes moot.
from zope.interface import Interface
class I(Interface):
"xxx"
class OldStyle:
__providedBy__ = None
self.assertRaises(AttributeError, I.providedBy, OldStyle)
def test_invariant_as_decorator(self):
from zope.interface import Interface
from zope.interface import Attribute
from zope.interface import implementer
from zope.interface import invariant
from zope.interface.exceptions import Invalid
class IRange(Interface):
min = Attribute("Lower bound")
max = Attribute("Upper bound")
@invariant
def range_invariant(ob):
if ob.max < ob.min:
raise Invalid('max < min')
@implementer(IRange)
class Range(object):
def __init__(self, min, max):
self.min, self.max = min, max
IRange.validateInvariants(Range(1, 2))
IRange.validateInvariants(Range(1, 1))
try:
IRange.validateInvariants(Range(2, 1))
except Invalid as e:
self.assertEqual(str(e), 'max < min')
def test_taggedValue(self):
from zope.interface import Attribute
from zope.interface import Interface
from zope.interface import taggedValue
class ITagged(Interface):
foo = Attribute('foo')
bar = Attribute('bar; must eval to Boolean True if foo does')
taggedValue('qux', 'Spam')
class IDerived(ITagged):
taggedValue('qux', 'Spam Spam')
taggedValue('foo', 'bar')
class IDerived2(IDerived):
pass
self.assertEqual(ITagged.getTaggedValue('qux'), 'Spam')
self.assertRaises(KeyError, ITagged.getTaggedValue, 'foo')
self.assertEqual(list(ITagged.getTaggedValueTags()), ['qux'])
self.assertEqual(IDerived2.getTaggedValue('qux'), 'Spam Spam')
self.assertEqual(IDerived2.getTaggedValue('foo'), 'bar')
self.assertEqual(set(IDerived2.getTaggedValueTags()), set(['qux', 'foo']))
def _make_taggedValue_tree(self, base):
from zope.interface import taggedValue
from zope.interface import Attribute
O = base
class F(O):
taggedValue('tag', 'F')
tag = Attribute('F')
class E(O):
taggedValue('tag', 'E')
tag = Attribute('E')
class D(O):
taggedValue('tag', 'D')
tag = Attribute('D')
class C(D, F):
taggedValue('tag', 'C')
tag = Attribute('C')
class B(D, E):
pass
class A(B, C):
pass
return A
def test_getTaggedValue_follows__iro__(self):
# And not just looks at __bases__.
# https://github.com/zopefoundation/zope.interface/issues/190
from zope.interface import Interface
# First, confirm that looking at a true class
# hierarchy follows the __mro__.
class_A = self._make_taggedValue_tree(object)
self.assertEqual(class_A.tag.__name__, 'C')
# Now check that Interface does, both for attributes...
iface_A = self._make_taggedValue_tree(Interface)
self.assertEqual(iface_A['tag'].__name__, 'C')
# ... and for tagged values.
self.assertEqual(iface_A.getTaggedValue('tag'), 'C')
self.assertEqual(iface_A.queryTaggedValue('tag'), 'C')
# Of course setting something lower overrides it.
assert iface_A.__bases__[0].__name__ == 'B'
iface_A.__bases__[0].setTaggedValue('tag', 'B')
self.assertEqual(iface_A.getTaggedValue('tag'), 'B')
def test_getDirectTaggedValue_ignores__iro__(self):
# https://github.com/zopefoundation/zope.interface/issues/190
from zope.interface import Interface
A = self._make_taggedValue_tree(Interface)
self.assertIsNone(A.queryDirectTaggedValue('tag'))
self.assertEqual([], list(A.getDirectTaggedValueTags()))
with self.assertRaises(KeyError):
A.getDirectTaggedValue('tag')
A.setTaggedValue('tag', 'A')
self.assertEqual(A.queryDirectTaggedValue('tag'), 'A')
self.assertEqual(A.getDirectTaggedValue('tag'), 'A')
self.assertEqual(['tag'], list(A.getDirectTaggedValueTags()))
assert A.__bases__[1].__name__ == 'C'
C = A.__bases__[1]
self.assertEqual(C.queryDirectTaggedValue('tag'), 'C')
self.assertEqual(C.getDirectTaggedValue('tag'), 'C')
self.assertEqual(['tag'], list(C.getDirectTaggedValueTags()))
def test_description_cache_management(self):
# See https://bugs.launchpad.net/zope.interface/+bug/185974
# There was a bug where the cache used by Specification.get() was not
# cleared when the bases were changed.
from zope.interface import Interface
from zope.interface import Attribute
class I1(Interface):
a = Attribute('a')
class I2(I1):
pass
class I3(I2):
pass
self.assertTrue(I3.get('a') is I1.get('a'))
I2.__bases__ = (Interface,)
self.assertTrue(I3.get('a') is None)
def test___call___defers_to___conform___(self):
from zope.interface import Interface
from zope.interface import implementer
class I(Interface):
pass
@implementer(I)
class C(object):
def __conform__(self, proto):
return 0
self.assertEqual(I(C()), 0)
def test___call___object_implements(self):
from zope.interface import Interface
from zope.interface import implementer
class I(Interface):
pass
@implementer(I)
class C(object):
pass
c = C()
self.assertTrue(I(c) is c)
def test___call___miss_wo_alternate(self):
from zope.interface import Interface
class I(Interface):
pass
class C(object):
pass
c = C()
self.assertRaises(TypeError, I, c)
def test___call___miss_w_alternate(self):
from zope.interface import Interface
class I(Interface):
pass
class C(object):
pass
c = C()
self.assertTrue(I(c, self) is self)
def test___call___w_adapter_hook(self):
from zope.interface import Interface
from zope.interface.interface import adapter_hooks
def _miss(iface, obj):
pass
def _hit(iface, obj):
return self
class I(Interface):
pass
class C(object):
pass
c = C()
old_adapter_hooks = adapter_hooks[:]
adapter_hooks[:] = [_miss, _hit]
try:
self.assertTrue(I(c) is self)
finally:
adapter_hooks[:] = old_adapter_hooks
def test___call___w_overridden_adapt(self):
from zope.interface import Interface
from zope.interface import interfacemethod
from zope.interface import implementer
class I(Interface):
@interfacemethod
def __adapt__(self, obj):
return 42
@implementer(I)
class O(object):
pass
self.assertEqual(42, I(object()))
# __adapt__ can ignore the fact that the object provides
# the interface if it chooses.
self.assertEqual(42, I(O()))
def test___call___w_overridden_adapt_and_conform(self):
# Conform is first, taking precedence over __adapt__,
# *if* it returns non-None
from zope.interface import Interface
from zope.interface import interfacemethod
from zope.interface import implementer
class IAdapt(Interface):
@interfacemethod
def __adapt__(self, obj):
return 42
class ISimple(Interface):
"""Nothing special."""
@implementer(IAdapt)
class Conform24(object):
def __conform__(self, iface):
return 24
@implementer(IAdapt)
class ConformNone(object):
def __conform__(self, iface):
return None
self.assertEqual(42, IAdapt(object()))
self.assertEqual(24, ISimple(Conform24()))
self.assertEqual(24, IAdapt(Conform24()))
with self.assertRaises(TypeError):
ISimple(ConformNone())
self.assertEqual(42, IAdapt(ConformNone()))
def test___call___w_overridden_adapt_call_super(self):
import sys
from zope.interface import Interface
from zope.interface import interfacemethod
from zope.interface import implementer
class I(Interface):
@interfacemethod
def __adapt__(self, obj):
if not self.providedBy(obj):
return 42
if sys.version_info[:2] > (3, 5):
# Python 3.5 raises 'RuntimeError: super() __class__ is not a type'
return super().__adapt__(obj)
return super(type(I), self).__adapt__(obj)
@implementer(I)
class O(object):
pass
self.assertEqual(42, I(object()))
o = O()
self.assertIs(o, I(o))
def test___adapt___as_method_and_implementation(self):
from zope.interface import Interface
from zope.interface import interfacemethod
class I(Interface):
@interfacemethod
def __adapt__(self, obj):
return 42
def __adapt__(to_adapt):
"This is a protocol"
self.assertEqual(42, I(object()))
self.assertEqual(I['__adapt__'].getSignatureString(), '(to_adapt)')
def test___adapt__inheritance_and_type(self):
from zope.interface import Interface
from zope.interface import interfacemethod
class IRoot(Interface):
"""Root"""
class IWithAdapt(IRoot):
@interfacemethod
def __adapt__(self, obj):
return 42
class IOther(IRoot):
"""Second branch"""
class IUnrelated(Interface):
"""Unrelated"""
class IDerivedAdapt(IUnrelated, IWithAdapt, IOther):
"""Inherits an adapt"""
# Order of "inheritance" matters here.
class IDerived2Adapt(IDerivedAdapt):
"""Overrides an inherited custom adapt."""
@interfacemethod
def __adapt__(self, obj):
return 24
self.assertEqual(42, IDerivedAdapt(object()))
for iface in IRoot, IWithAdapt, IOther, IUnrelated, IDerivedAdapt:
self.assertEqual(__name__, iface.__module__)
for iface in IRoot, IOther, IUnrelated:
self.assertEqual(type(IRoot), type(Interface))
# But things that implemented __adapt__ got a new type
self.assertNotEqual(type(Interface), type(IWithAdapt))
self.assertEqual(type(IWithAdapt), type(IDerivedAdapt))
self.assertIsInstance(IWithAdapt, type(Interface))
self.assertEqual(24, IDerived2Adapt(object()))
self.assertNotEqual(type(IDerived2Adapt), type(IDerivedAdapt))
self.assertIsInstance(IDerived2Adapt, type(IDerivedAdapt))
def test_interfacemethod_is_general(self):
from zope.interface import Interface
from zope.interface import interfacemethod
class I(Interface):
@interfacemethod
def __call__(self, obj):
"""Replace an existing method"""
return 42
@interfacemethod
def this_is_new(self):
return 42
self.assertEqual(I(self), 42)
self.assertEqual(I.this_is_new(), 42)
class AttributeTests(ElementTests):
DEFAULT_NAME = 'TestAttribute'
def _getTargetClass(self):
from zope.interface.interface import Attribute
return Attribute
def test__repr__w_interface(self):
method = self._makeOne()
method.interface = type(self)
r = repr(method)
self.assertTrue(r.startswith('<zope.interface.interface.Attribute object at'), r)
self.assertTrue(r.endswith(' ' + __name__ + '.AttributeTests.TestAttribute>'), r)
def test__repr__wo_interface(self):
method = self._makeOne()
r = repr(method)
self.assertTrue(r.startswith('<zope.interface.interface.Attribute object at'), r)
self.assertTrue(r.endswith(' TestAttribute>'), r)
def test__str__w_interface(self):
method = self._makeOne()
method.interface = type(self)
r = str(method)
self.assertEqual(r, __name__ + '.AttributeTests.TestAttribute')
def test__str__wo_interface(self):
method = self._makeOne()
r = str(method)
self.assertEqual(r, 'TestAttribute')
class MethodTests(AttributeTests):
DEFAULT_NAME = 'TestMethod'
def _getTargetClass(self):
from zope.interface.interface import Method
return Method
def test_optional_as_property(self):
method = self._makeOne()
self.assertEqual(method.optional, {})
method.optional = {'foo': 'bar'}
self.assertEqual(method.optional, {'foo': 'bar'})
del method.optional
self.assertEqual(method.optional, {})
def test___call___raises_BrokenImplementation(self):
from zope.interface.exceptions import BrokenImplementation
method = self._makeOne()
try:
method()
except BrokenImplementation as e:
self.assertEqual(e.interface, None)
self.assertEqual(e.name, self.DEFAULT_NAME)
else:
self.fail('__call__ should raise BrokenImplementation')
def test_getSignatureInfo_bare(self):
method = self._makeOne()
info = method.getSignatureInfo()
self.assertEqual(list(info['positional']), [])
self.assertEqual(list(info['required']), [])
self.assertEqual(info['optional'], {})
self.assertEqual(info['varargs'], None)
self.assertEqual(info['kwargs'], None)
def test_getSignatureString_bare(self):
method = self._makeOne()
self.assertEqual(method.getSignatureString(), '()')
def test_getSignatureString_w_only_required(self):
method = self._makeOne()
method.positional = method.required = ['foo']
self.assertEqual(method.getSignatureString(), '(foo)')
def test_getSignatureString_w_optional(self):
method = self._makeOne()
method.positional = method.required = ['foo']
method.optional = {'foo': 'bar'}
self.assertEqual(method.getSignatureString(), "(foo='bar')")
def test_getSignatureString_w_varargs(self):
method = self._makeOne()
method.varargs = 'args'
self.assertEqual(method.getSignatureString(), "(*args)")
def test_getSignatureString_w_kwargs(self):
method = self._makeOne()
method.kwargs = 'kw'
self.assertEqual(method.getSignatureString(), "(**kw)")
def test__repr__w_interface(self):
method = self._makeOne()
method.kwargs = 'kw'
method.interface = type(self)
r = repr(method)
self.assertTrue(r.startswith('<zope.interface.interface.Method object at'), r)
self.assertTrue(r.endswith(' ' + __name__ + '.MethodTests.TestMethod(**kw)>'), r)
def test__repr__wo_interface(self):
method = self._makeOne()
method.kwargs = 'kw'
r = repr(method)
self.assertTrue(r.startswith('<zope.interface.interface.Method object at'), r)
self.assertTrue(r.endswith(' TestMethod(**kw)>'), r)
def test__str__w_interface(self):
method = self._makeOne()
method.kwargs = 'kw'
method.interface = type(self)
r = str(method)
self.assertEqual(r, __name__ + '.MethodTests.TestMethod(**kw)')
def test__str__wo_interface(self):
method = self._makeOne()
method.kwargs = 'kw'
r = str(method)
self.assertEqual(r, 'TestMethod(**kw)')
class Test_fromFunction(unittest.TestCase):
def _callFUT(self, *args, **kw):
from zope.interface.interface import fromFunction
return fromFunction(*args, **kw)
def test_bare(self):
def _func():
"DOCSTRING"
method = self._callFUT(_func)
self.assertEqual(method.getName(), '_func')
self.assertEqual(method.getDoc(), 'DOCSTRING')
self.assertEqual(method.interface, None)
self.assertEqual(list(method.getTaggedValueTags()), [])
info = method.getSignatureInfo()
self.assertEqual(list(info['positional']), [])
self.assertEqual(list(info['required']), [])
self.assertEqual(info['optional'], {})
self.assertEqual(info['varargs'], None)
self.assertEqual(info['kwargs'], None)
def test_w_interface(self):
from zope.interface.interface import InterfaceClass
class IFoo(InterfaceClass):
pass
def _func():
"DOCSTRING"
method = self._callFUT(_func, interface=IFoo)
self.assertEqual(method.interface, IFoo)
def test_w_name(self):
def _func():
"DOCSTRING"
method = self._callFUT(_func, name='anotherName')
self.assertEqual(method.getName(), 'anotherName')
def test_w_only_required(self):
def _func(foo):
"DOCSTRING"
method = self._callFUT(_func)
info = method.getSignatureInfo()
self.assertEqual(list(info['positional']), ['foo'])
self.assertEqual(list(info['required']), ['foo'])
self.assertEqual(info['optional'], {})
self.assertEqual(info['varargs'], None)
self.assertEqual(info['kwargs'], None)
def test_w_optional(self):
def _func(foo='bar'):
"DOCSTRING"
method = self._callFUT(_func)
info = method.getSignatureInfo()
self.assertEqual(list(info['positional']), ['foo'])
self.assertEqual(list(info['required']), [])
self.assertEqual(info['optional'], {'foo': 'bar'})
self.assertEqual(info['varargs'], None)
self.assertEqual(info['kwargs'], None)
def test_w_optional_self(self):
# This is a weird case, trying to cover the following code in
# FUT::
#
# nr = na-len(defaults)
# if nr < 0:
# defaults=defaults[-nr:]
# nr = 0
def _func(self='bar'):
"DOCSTRING"
method = self._callFUT(_func, imlevel=1)
info = method.getSignatureInfo()
self.assertEqual(list(info['positional']), [])
self.assertEqual(list(info['required']), [])
self.assertEqual(info['optional'], {})
self.assertEqual(info['varargs'], None)
self.assertEqual(info['kwargs'], None)
def test_w_varargs(self):
def _func(*args):
"DOCSTRING"
method = self._callFUT(_func)
info = method.getSignatureInfo()
self.assertEqual(list(info['positional']), [])
self.assertEqual(list(info['required']), [])
self.assertEqual(info['optional'], {})
self.assertEqual(info['varargs'], 'args')
self.assertEqual(info['kwargs'], None)
def test_w_kwargs(self):
def _func(**kw):
"DOCSTRING"
method = self._callFUT(_func)
info = method.getSignatureInfo()
self.assertEqual(list(info['positional']), [])
self.assertEqual(list(info['required']), [])
self.assertEqual(info['optional'], {})
self.assertEqual(info['varargs'], None)
self.assertEqual(info['kwargs'], 'kw')
def test_full_spectrum(self):
def _func(foo, bar='baz', *args, **kw): # pylint:disable=keyword-arg-before-vararg
"DOCSTRING"
method = self._callFUT(_func)
info = method.getSignatureInfo()
self.assertEqual(list(info['positional']), ['foo', 'bar'])
self.assertEqual(list(info['required']), ['foo'])
self.assertEqual(info['optional'], {'bar': 'baz'})
self.assertEqual(info['varargs'], 'args')
self.assertEqual(info['kwargs'], 'kw')
class Test_fromMethod(unittest.TestCase):
def _callFUT(self, *args, **kw):
from zope.interface.interface import fromMethod
return fromMethod(*args, **kw)
def test_no_args(self):
class Foo(object):
def bar(self):
"DOCSTRING"
method = self._callFUT(Foo.bar)
self.assertEqual(method.getName(), 'bar')
self.assertEqual(method.getDoc(), 'DOCSTRING')
self.assertEqual(method.interface, None)
self.assertEqual(list(method.getTaggedValueTags()), [])
info = method.getSignatureInfo()
self.assertEqual(list(info['positional']), [])
self.assertEqual(list(info['required']), [])
self.assertEqual(info['optional'], {})
self.assertEqual(info['varargs'], None)
self.assertEqual(info['kwargs'], None)
def test_full_spectrum(self):
class Foo(object):
def bar(self, foo, bar='baz', *args, **kw): # pylint:disable=keyword-arg-before-vararg
"DOCSTRING"
method = self._callFUT(Foo.bar)
info = method.getSignatureInfo()
self.assertEqual(list(info['positional']), ['foo', 'bar'])
self.assertEqual(list(info['required']), ['foo'])
self.assertEqual(info['optional'], {'bar': 'baz'})
self.assertEqual(info['varargs'], 'args')
self.assertEqual(info['kwargs'], 'kw')
def test_w_non_method(self):
def foo():
"DOCSTRING"
method = self._callFUT(foo)
self.assertEqual(method.getName(), 'foo')
self.assertEqual(method.getDoc(), 'DOCSTRING')
self.assertEqual(method.interface, None)
self.assertEqual(list(method.getTaggedValueTags()), [])
info = method.getSignatureInfo()
self.assertEqual(list(info['positional']), [])
self.assertEqual(list(info['required']), [])
self.assertEqual(info['optional'], {})
self.assertEqual(info['varargs'], None)
self.assertEqual(info['kwargs'], None)
class DummyDependent(object):
def __init__(self):
self._changed = []
def changed(self, originally_changed):
self._changed.append(originally_changed)
def _barGreaterThanFoo(obj):
from zope.interface.exceptions import Invalid
foo = getattr(obj, 'foo', None)
bar = getattr(obj, 'bar', None)
if foo is not None and isinstance(foo, type(bar)):
# type checking should be handled elsewhere (like, say,
# schema); these invariants should be intra-interface
# constraints. This is a hacky way to do it, maybe, but you
# get the idea
if not bar > foo:
raise Invalid('Please, Boo MUST be greater than Foo!')
def _ifFooThenBar(obj):
from zope.interface.exceptions import Invalid
if getattr(obj, 'foo', None) and not getattr(obj, 'bar', None):
raise Invalid('If Foo, then Bar!')
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 = {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)
|