test_declarations.py 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658
  1. ##############################################################################
  2. #
  3. # Copyright (c) 2003 Zope Foundation and Contributors.
  4. # All Rights Reserved.
  5. #
  6. # This software is subject to the provisions of the Zope Public License,
  7. # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
  8. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
  9. # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  10. # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
  11. # FOR A PARTICULAR PURPOSE.
  12. #
  13. ##############################################################################
  14. """Test the new API for making and checking interface declarations
  15. """
  16. import unittest
  17. from zope.interface._compat import _skip_under_py3k
  18. class _Py3ClassAdvice(object):
  19. def _run_generated_code(self, code, globs, locs,
  20. fails_under_py3k=True,
  21. ):
  22. import warnings
  23. from zope.interface._compat import PYTHON3
  24. with warnings.catch_warnings(record=True) as log:
  25. warnings.resetwarnings()
  26. if not PYTHON3:
  27. exec(code, globs, locs)
  28. self.assertEqual(len(log), 0) # no longer warn
  29. return True
  30. else:
  31. try:
  32. exec(code, globs, locs)
  33. except TypeError:
  34. return False
  35. else:
  36. if fails_under_py3k:
  37. self.fail("Didn't raise TypeError")
  38. class NamedTests(unittest.TestCase):
  39. def test_class(self):
  40. from zope.interface.declarations import named
  41. @named(u'foo')
  42. class Foo(object):
  43. pass
  44. self.assertEqual(Foo.__component_name__, u'foo')
  45. def test_function(self):
  46. from zope.interface.declarations import named
  47. @named(u'foo')
  48. def doFoo(o):
  49. raise NotImplementedError()
  50. self.assertEqual(doFoo.__component_name__, u'foo')
  51. def test_instance(self):
  52. from zope.interface.declarations import named
  53. class Foo(object):
  54. pass
  55. foo = Foo()
  56. named(u'foo')(foo)
  57. self.assertEqual(foo.__component_name__, u'foo')
  58. class DeclarationTests(unittest.TestCase):
  59. def _getTargetClass(self):
  60. from zope.interface.declarations import Declaration
  61. return Declaration
  62. def _makeOne(self, *args, **kw):
  63. return self._getTargetClass()(*args, **kw)
  64. def test_ctor_no_bases(self):
  65. decl = self._makeOne()
  66. self.assertEqual(list(decl.__bases__), [])
  67. def test_ctor_w_interface_in_bases(self):
  68. from zope.interface.interface import InterfaceClass
  69. IFoo = InterfaceClass('IFoo')
  70. decl = self._makeOne(IFoo)
  71. self.assertEqual(list(decl.__bases__), [IFoo])
  72. def test_ctor_w_implements_in_bases(self):
  73. from zope.interface.declarations import Implements
  74. impl = Implements()
  75. decl = self._makeOne(impl)
  76. self.assertEqual(list(decl.__bases__), [impl])
  77. def test_changed_wo_existing__v_attrs(self):
  78. decl = self._makeOne()
  79. decl.changed(decl) # doesn't raise
  80. self.assertFalse('_v_attrs' in decl.__dict__)
  81. def test_changed_w_existing__v_attrs(self):
  82. decl = self._makeOne()
  83. decl._v_attrs = object()
  84. decl.changed(decl)
  85. self.assertFalse('_v_attrs' in decl.__dict__)
  86. def test___contains__w_self(self):
  87. from zope.interface.interface import InterfaceClass
  88. IFoo = InterfaceClass('IFoo')
  89. decl = self._makeOne()
  90. self.assertFalse(decl in decl)
  91. def test___contains__w_unrelated_iface(self):
  92. from zope.interface.interface import InterfaceClass
  93. IFoo = InterfaceClass('IFoo')
  94. decl = self._makeOne()
  95. self.assertFalse(IFoo in decl)
  96. def test___contains__w_base_interface(self):
  97. from zope.interface.interface import InterfaceClass
  98. IFoo = InterfaceClass('IFoo')
  99. decl = self._makeOne(IFoo)
  100. self.assertTrue(IFoo in decl)
  101. def test___iter___empty(self):
  102. decl = self._makeOne()
  103. self.assertEqual(list(decl), [])
  104. def test___iter___single_base(self):
  105. from zope.interface.interface import InterfaceClass
  106. IFoo = InterfaceClass('IFoo')
  107. decl = self._makeOne(IFoo)
  108. self.assertEqual(list(decl), [IFoo])
  109. def test___iter___multiple_bases(self):
  110. from zope.interface.interface import InterfaceClass
  111. IFoo = InterfaceClass('IFoo')
  112. IBar = InterfaceClass('IBar')
  113. decl = self._makeOne(IFoo, IBar)
  114. self.assertEqual(list(decl), [IFoo, IBar])
  115. def test___iter___inheritance(self):
  116. from zope.interface.interface import InterfaceClass
  117. IFoo = InterfaceClass('IFoo')
  118. IBar = InterfaceClass('IBar', (IFoo,))
  119. decl = self._makeOne(IBar)
  120. self.assertEqual(list(decl), [IBar]) #IBar.interfaces() omits bases
  121. def test___iter___w_nested_sequence_overlap(self):
  122. from zope.interface.interface import InterfaceClass
  123. IFoo = InterfaceClass('IFoo')
  124. IBar = InterfaceClass('IBar')
  125. decl = self._makeOne(IBar, (IFoo, IBar))
  126. self.assertEqual(list(decl), [IBar, IFoo])
  127. def test_flattened_empty(self):
  128. from zope.interface.interface import Interface
  129. decl = self._makeOne()
  130. self.assertEqual(list(decl.flattened()), [Interface])
  131. def test_flattened_single_base(self):
  132. from zope.interface.interface import Interface
  133. from zope.interface.interface import InterfaceClass
  134. IFoo = InterfaceClass('IFoo')
  135. decl = self._makeOne(IFoo)
  136. self.assertEqual(list(decl.flattened()), [IFoo, Interface])
  137. def test_flattened_multiple_bases(self):
  138. from zope.interface.interface import Interface
  139. from zope.interface.interface import InterfaceClass
  140. IFoo = InterfaceClass('IFoo')
  141. IBar = InterfaceClass('IBar')
  142. decl = self._makeOne(IFoo, IBar)
  143. self.assertEqual(list(decl.flattened()), [IFoo, IBar, Interface])
  144. def test_flattened_inheritance(self):
  145. from zope.interface.interface import Interface
  146. from zope.interface.interface import InterfaceClass
  147. IFoo = InterfaceClass('IFoo')
  148. IBar = InterfaceClass('IBar', (IFoo,))
  149. decl = self._makeOne(IBar)
  150. self.assertEqual(list(decl.flattened()), [IBar, IFoo, Interface])
  151. def test_flattened_w_nested_sequence_overlap(self):
  152. from zope.interface.interface import Interface
  153. from zope.interface.interface import InterfaceClass
  154. IFoo = InterfaceClass('IFoo')
  155. IBar = InterfaceClass('IBar')
  156. decl = self._makeOne(IBar, (IFoo, IBar))
  157. # Note that decl.__iro__ has IFoo first.
  158. self.assertEqual(list(decl.flattened()), [IFoo, IBar, Interface])
  159. def test___sub___unrelated_interface(self):
  160. from zope.interface.interface import InterfaceClass
  161. IFoo = InterfaceClass('IFoo')
  162. IBar = InterfaceClass('IBar')
  163. before = self._makeOne(IFoo)
  164. after = before - IBar
  165. self.assertTrue(isinstance(after, self._getTargetClass()))
  166. self.assertEqual(list(after), [IFoo])
  167. def test___sub___related_interface(self):
  168. from zope.interface.interface import InterfaceClass
  169. IFoo = InterfaceClass('IFoo')
  170. before = self._makeOne(IFoo)
  171. after = before - IFoo
  172. self.assertEqual(list(after), [])
  173. def test___sub___related_interface_by_inheritance(self):
  174. from zope.interface.interface import InterfaceClass
  175. IFoo = InterfaceClass('IFoo')
  176. IBar = InterfaceClass('IBar', (IFoo,))
  177. before = self._makeOne(IBar)
  178. after = before - IBar
  179. self.assertEqual(list(after), [])
  180. def test___add___unrelated_interface(self):
  181. from zope.interface.interface import InterfaceClass
  182. IFoo = InterfaceClass('IFoo')
  183. IBar = InterfaceClass('IBar')
  184. before = self._makeOne(IFoo)
  185. after = before + IBar
  186. self.assertTrue(isinstance(after, self._getTargetClass()))
  187. self.assertEqual(list(after), [IFoo, IBar])
  188. def test___add___related_interface(self):
  189. from zope.interface.interface import InterfaceClass
  190. IFoo = InterfaceClass('IFoo')
  191. IBar = InterfaceClass('IBar')
  192. IBaz = InterfaceClass('IBaz')
  193. before = self._makeOne(IFoo, IBar)
  194. other = self._makeOne(IBar, IBaz)
  195. after = before + other
  196. self.assertEqual(list(after), [IFoo, IBar, IBaz])
  197. class TestImplements(unittest.TestCase):
  198. def _getTargetClass(self):
  199. from zope.interface.declarations import Implements
  200. return Implements
  201. def _makeOne(self, *args, **kw):
  202. return self._getTargetClass()(*args, **kw)
  203. def test_ctor_no_bases(self):
  204. impl = self._makeOne()
  205. self.assertEqual(impl.inherit, None)
  206. self.assertEqual(impl.declared, ())
  207. self.assertEqual(impl.__name__, '?')
  208. self.assertEqual(list(impl.__bases__), [])
  209. def test___repr__(self):
  210. impl = self._makeOne()
  211. impl.__name__ = 'Testing'
  212. self.assertEqual(repr(impl), '<implementedBy Testing>')
  213. def test___reduce__(self):
  214. from zope.interface.declarations import implementedBy
  215. impl = self._makeOne()
  216. self.assertEqual(impl.__reduce__(), (implementedBy, (None,)))
  217. def test_sort(self):
  218. from zope.interface.declarations import implementedBy
  219. class A(object):
  220. pass
  221. class B(object):
  222. pass
  223. from zope.interface.interface import InterfaceClass
  224. IFoo = InterfaceClass('IFoo')
  225. self.assertEqual(implementedBy(A), implementedBy(A))
  226. self.assertEqual(hash(implementedBy(A)), hash(implementedBy(A)))
  227. self.assertTrue(implementedBy(A) < None)
  228. self.assertTrue(None > implementedBy(A))
  229. self.assertTrue(implementedBy(A) < implementedBy(B))
  230. self.assertTrue(implementedBy(A) > IFoo)
  231. self.assertTrue(implementedBy(A) <= implementedBy(B))
  232. self.assertTrue(implementedBy(A) >= IFoo)
  233. self.assertTrue(implementedBy(A) != IFoo)
  234. def test_proxy_equality(self):
  235. # https://github.com/zopefoundation/zope.interface/issues/55
  236. class Proxy(object):
  237. def __init__(self, wrapped):
  238. self._wrapped = wrapped
  239. def __getattr__(self, name):
  240. raise NotImplementedError()
  241. def __eq__(self, other):
  242. return self._wrapped == other
  243. def __ne__(self, other):
  244. return self._wrapped != other
  245. from zope.interface.declarations import implementedBy
  246. class A(object):
  247. pass
  248. class B(object):
  249. pass
  250. implementedByA = implementedBy(A)
  251. implementedByB = implementedBy(B)
  252. proxy = Proxy(implementedByA)
  253. # The order of arguments to the operators matters,
  254. # test both
  255. self.assertTrue(implementedByA == implementedByA)
  256. self.assertTrue(implementedByA != implementedByB)
  257. self.assertTrue(implementedByB != implementedByA)
  258. self.assertTrue(proxy == implementedByA)
  259. self.assertTrue(implementedByA == proxy)
  260. self.assertFalse(proxy != implementedByA)
  261. self.assertFalse(implementedByA != proxy)
  262. self.assertTrue(proxy != implementedByB)
  263. self.assertTrue(implementedByB != proxy)
  264. class Test_implementedByFallback(unittest.TestCase):
  265. def _callFUT(self, *args, **kw):
  266. from zope.interface.declarations import implementedByFallback
  267. return implementedByFallback(*args, **kw)
  268. def test_dictless_wo_existing_Implements_wo_registrations(self):
  269. class Foo(object):
  270. __slots__ = ('__implemented__',)
  271. foo = Foo()
  272. foo.__implemented__ = None
  273. self.assertEqual(list(self._callFUT(foo)), [])
  274. def test_dictless_wo_existing_Implements_cant_assign___implemented__(self):
  275. class Foo(object):
  276. def _get_impl(self):
  277. raise NotImplementedError()
  278. def _set_impl(self, val):
  279. raise TypeError
  280. __implemented__ = property(_get_impl, _set_impl)
  281. def __call__(self):
  282. # act like a factory
  283. raise NotImplementedError()
  284. foo = Foo()
  285. self.assertRaises(TypeError, self._callFUT, foo)
  286. def test_dictless_wo_existing_Implements_w_registrations(self):
  287. from zope.interface import declarations
  288. class Foo(object):
  289. __slots__ = ('__implemented__',)
  290. foo = Foo()
  291. foo.__implemented__ = None
  292. reg = object()
  293. with _MonkeyDict(declarations,
  294. 'BuiltinImplementationSpecifications') as specs:
  295. specs[foo] = reg
  296. self.assertTrue(self._callFUT(foo) is reg)
  297. def test_dictless_w_existing_Implements(self):
  298. from zope.interface.declarations import Implements
  299. impl = Implements()
  300. class Foo(object):
  301. __slots__ = ('__implemented__',)
  302. foo = Foo()
  303. foo.__implemented__ = impl
  304. self.assertTrue(self._callFUT(foo) is impl)
  305. def test_dictless_w_existing_not_Implements(self):
  306. from zope.interface.interface import InterfaceClass
  307. class Foo(object):
  308. __slots__ = ('__implemented__',)
  309. foo = Foo()
  310. IFoo = InterfaceClass('IFoo')
  311. foo.__implemented__ = (IFoo,)
  312. self.assertEqual(list(self._callFUT(foo)), [IFoo])
  313. def test_w_existing_attr_as_Implements(self):
  314. from zope.interface.declarations import Implements
  315. impl = Implements()
  316. class Foo(object):
  317. __implemented__ = impl
  318. self.assertTrue(self._callFUT(Foo) is impl)
  319. def test_builtins_added_to_cache(self):
  320. from zope.interface import declarations
  321. from zope.interface.declarations import Implements
  322. from zope.interface._compat import _BUILTINS
  323. with _MonkeyDict(declarations,
  324. 'BuiltinImplementationSpecifications') as specs:
  325. self.assertEqual(list(self._callFUT(tuple)), [])
  326. self.assertEqual(list(self._callFUT(list)), [])
  327. self.assertEqual(list(self._callFUT(dict)), [])
  328. for typ in (tuple, list, dict):
  329. spec = specs[typ]
  330. self.assertTrue(isinstance(spec, Implements))
  331. self.assertEqual(repr(spec),
  332. '<implementedBy %s.%s>'
  333. % (_BUILTINS, typ.__name__))
  334. def test_builtins_w_existing_cache(self):
  335. from zope.interface import declarations
  336. t_spec, l_spec, d_spec = object(), object(), object()
  337. with _MonkeyDict(declarations,
  338. 'BuiltinImplementationSpecifications') as specs:
  339. specs[tuple] = t_spec
  340. specs[list] = l_spec
  341. specs[dict] = d_spec
  342. self.assertTrue(self._callFUT(tuple) is t_spec)
  343. self.assertTrue(self._callFUT(list) is l_spec)
  344. self.assertTrue(self._callFUT(dict) is d_spec)
  345. def test_oldstyle_class_no_assertions(self):
  346. # TODO: Figure out P3 story
  347. class Foo:
  348. pass
  349. self.assertEqual(list(self._callFUT(Foo)), [])
  350. def test_no_assertions(self):
  351. # TODO: Figure out P3 story
  352. class Foo(object):
  353. pass
  354. self.assertEqual(list(self._callFUT(Foo)), [])
  355. def test_w_None_no_bases_not_factory(self):
  356. class Foo(object):
  357. __implemented__ = None
  358. foo = Foo()
  359. self.assertRaises(TypeError, self._callFUT, foo)
  360. def test_w_None_no_bases_w_factory(self):
  361. from zope.interface.declarations import objectSpecificationDescriptor
  362. class Foo(object):
  363. __implemented__ = None
  364. def __call__(self):
  365. raise NotImplementedError()
  366. foo = Foo()
  367. foo.__name__ = 'foo'
  368. spec = self._callFUT(foo)
  369. self.assertEqual(spec.__name__,
  370. 'zope.interface.tests.test_declarations.foo')
  371. self.assertTrue(spec.inherit is foo)
  372. self.assertTrue(foo.__implemented__ is spec)
  373. self.assertTrue(foo.__providedBy__ is objectSpecificationDescriptor)
  374. self.assertFalse('__provides__' in foo.__dict__)
  375. def test_w_None_no_bases_w_class(self):
  376. from zope.interface.declarations import ClassProvides
  377. class Foo(object):
  378. __implemented__ = None
  379. spec = self._callFUT(Foo)
  380. self.assertEqual(spec.__name__,
  381. 'zope.interface.tests.test_declarations.Foo')
  382. self.assertTrue(spec.inherit is Foo)
  383. self.assertTrue(Foo.__implemented__ is spec)
  384. self.assertTrue(isinstance(Foo.__providedBy__, ClassProvides))
  385. self.assertTrue(isinstance(Foo.__provides__, ClassProvides))
  386. self.assertEqual(Foo.__provides__, Foo.__providedBy__)
  387. def test_w_existing_Implements(self):
  388. from zope.interface.declarations import Implements
  389. impl = Implements()
  390. class Foo(object):
  391. __implemented__ = impl
  392. self.assertTrue(self._callFUT(Foo) is impl)
  393. class Test_implementedBy(Test_implementedByFallback):
  394. # Repeat tests for C optimizations
  395. def _callFUT(self, *args, **kw):
  396. from zope.interface.declarations import implementedBy
  397. return implementedBy(*args, **kw)
  398. def test_optimizations(self):
  399. from zope.interface.declarations import implementedByFallback
  400. from zope.interface.declarations import implementedBy
  401. try:
  402. import zope.interface._zope_interface_coptimizations
  403. except ImportError:
  404. self.assertIs(implementedBy, implementedByFallback)
  405. else:
  406. self.assertIsNot(implementedBy, implementedByFallback)
  407. class Test_classImplementsOnly(unittest.TestCase):
  408. def _callFUT(self, *args, **kw):
  409. from zope.interface.declarations import classImplementsOnly
  410. return classImplementsOnly(*args, **kw)
  411. def test_no_existing(self):
  412. from zope.interface.declarations import ClassProvides
  413. from zope.interface.interface import InterfaceClass
  414. class Foo(object):
  415. pass
  416. ifoo = InterfaceClass('IFoo')
  417. self._callFUT(Foo, ifoo)
  418. spec = Foo.__implemented__
  419. self.assertEqual(spec.__name__,
  420. 'zope.interface.tests.test_declarations.Foo')
  421. self.assertTrue(spec.inherit is None)
  422. self.assertTrue(Foo.__implemented__ is spec)
  423. self.assertTrue(isinstance(Foo.__providedBy__, ClassProvides))
  424. self.assertTrue(isinstance(Foo.__provides__, ClassProvides))
  425. self.assertEqual(Foo.__provides__, Foo.__providedBy__)
  426. def test_w_existing_Implements(self):
  427. from zope.interface.declarations import Implements
  428. from zope.interface.interface import InterfaceClass
  429. IFoo = InterfaceClass('IFoo')
  430. IBar = InterfaceClass('IBar')
  431. impl = Implements(IFoo)
  432. impl.declared = (IFoo,)
  433. class Foo(object):
  434. __implemented__ = impl
  435. impl.inherit = Foo
  436. self._callFUT(Foo, IBar)
  437. # Same spec, now different values
  438. self.assertTrue(Foo.__implemented__ is impl)
  439. self.assertEqual(impl.inherit, None)
  440. self.assertEqual(impl.declared, (IBar,))
  441. class Test_classImplements(unittest.TestCase):
  442. def _callFUT(self, *args, **kw):
  443. from zope.interface.declarations import classImplements
  444. return classImplements(*args, **kw)
  445. def test_no_existing(self):
  446. from zope.interface.declarations import ClassProvides
  447. from zope.interface.interface import InterfaceClass
  448. class Foo(object):
  449. pass
  450. IFoo = InterfaceClass('IFoo')
  451. self._callFUT(Foo, IFoo)
  452. spec = Foo.__implemented__
  453. self.assertEqual(spec.__name__,
  454. 'zope.interface.tests.test_declarations.Foo')
  455. self.assertTrue(spec.inherit is Foo)
  456. self.assertTrue(Foo.__implemented__ is spec)
  457. self.assertTrue(isinstance(Foo.__providedBy__, ClassProvides))
  458. self.assertTrue(isinstance(Foo.__provides__, ClassProvides))
  459. self.assertEqual(Foo.__provides__, Foo.__providedBy__)
  460. def test_w_existing_Implements(self):
  461. from zope.interface.declarations import Implements
  462. from zope.interface.interface import InterfaceClass
  463. IFoo = InterfaceClass('IFoo')
  464. IBar = InterfaceClass('IBar')
  465. impl = Implements(IFoo)
  466. impl.declared = (IFoo,)
  467. class Foo(object):
  468. __implemented__ = impl
  469. impl.inherit = Foo
  470. self._callFUT(Foo, IBar)
  471. # Same spec, now different values
  472. self.assertTrue(Foo.__implemented__ is impl)
  473. self.assertEqual(impl.inherit, Foo)
  474. self.assertEqual(impl.declared, (IFoo, IBar,))
  475. def test_w_existing_Implements_w_bases(self):
  476. from zope.interface.declarations import Implements
  477. from zope.interface.interface import InterfaceClass
  478. IFoo = InterfaceClass('IFoo')
  479. IBar = InterfaceClass('IBar')
  480. IBaz = InterfaceClass('IBaz', IFoo)
  481. b_impl = Implements(IBaz)
  482. impl = Implements(IFoo)
  483. impl.declared = (IFoo,)
  484. class Base1(object):
  485. __implemented__ = b_impl
  486. class Base2(object):
  487. __implemented__ = b_impl
  488. class Foo(Base1, Base2):
  489. __implemented__ = impl
  490. impl.inherit = Foo
  491. self._callFUT(Foo, IBar)
  492. # Same spec, now different values
  493. self.assertTrue(Foo.__implemented__ is impl)
  494. self.assertEqual(impl.inherit, Foo)
  495. self.assertEqual(impl.declared, (IFoo, IBar,))
  496. self.assertEqual(impl.__bases__, (IFoo, IBar, b_impl))
  497. class Test__implements_advice(unittest.TestCase):
  498. def _callFUT(self, *args, **kw):
  499. from zope.interface.declarations import _implements_advice
  500. return _implements_advice(*args, **kw)
  501. def test_no_existing_implements(self):
  502. from zope.interface.declarations import classImplements
  503. from zope.interface.declarations import Implements
  504. from zope.interface.interface import InterfaceClass
  505. IFoo = InterfaceClass('IFoo')
  506. class Foo(object):
  507. __implements_advice_data__ = ((IFoo,), classImplements)
  508. self._callFUT(Foo)
  509. self.assertFalse('__implements_advice_data__' in Foo.__dict__)
  510. self.assertTrue(isinstance(Foo.__implemented__, Implements))
  511. self.assertEqual(list(Foo.__implemented__), [IFoo])
  512. class Test_implementer(unittest.TestCase):
  513. def _getTargetClass(self):
  514. from zope.interface.declarations import implementer
  515. return implementer
  516. def _makeOne(self, *args, **kw):
  517. return self._getTargetClass()(*args, **kw)
  518. def test_oldstyle_class(self):
  519. # TODO Py3 story
  520. from zope.interface.declarations import ClassProvides
  521. from zope.interface.interface import InterfaceClass
  522. IFoo = InterfaceClass('IFoo')
  523. class Foo:
  524. pass
  525. decorator = self._makeOne(IFoo)
  526. returned = decorator(Foo)
  527. self.assertTrue(returned is Foo)
  528. spec = Foo.__implemented__
  529. self.assertEqual(spec.__name__,
  530. 'zope.interface.tests.test_declarations.Foo')
  531. self.assertTrue(spec.inherit is Foo)
  532. self.assertTrue(Foo.__implemented__ is spec)
  533. self.assertTrue(isinstance(Foo.__providedBy__, ClassProvides))
  534. self.assertTrue(isinstance(Foo.__provides__, ClassProvides))
  535. self.assertEqual(Foo.__provides__, Foo.__providedBy__)
  536. def test_newstyle_class(self):
  537. from zope.interface.declarations import ClassProvides
  538. from zope.interface.interface import InterfaceClass
  539. IFoo = InterfaceClass('IFoo')
  540. class Foo(object):
  541. pass
  542. decorator = self._makeOne(IFoo)
  543. returned = decorator(Foo)
  544. self.assertTrue(returned is Foo)
  545. spec = Foo.__implemented__
  546. self.assertEqual(spec.__name__,
  547. 'zope.interface.tests.test_declarations.Foo')
  548. self.assertTrue(spec.inherit is Foo)
  549. self.assertTrue(Foo.__implemented__ is spec)
  550. self.assertTrue(isinstance(Foo.__providedBy__, ClassProvides))
  551. self.assertTrue(isinstance(Foo.__provides__, ClassProvides))
  552. self.assertEqual(Foo.__provides__, Foo.__providedBy__)
  553. def test_nonclass_cannot_assign_attr(self):
  554. from zope.interface.interface import InterfaceClass
  555. IFoo = InterfaceClass('IFoo')
  556. decorator = self._makeOne(IFoo)
  557. self.assertRaises(TypeError, decorator, object())
  558. def test_nonclass_can_assign_attr(self):
  559. from zope.interface.interface import InterfaceClass
  560. IFoo = InterfaceClass('IFoo')
  561. class Foo(object):
  562. pass
  563. foo = Foo()
  564. decorator = self._makeOne(IFoo)
  565. returned = decorator(foo)
  566. self.assertTrue(returned is foo)
  567. spec = foo.__implemented__
  568. self.assertEqual(spec.__name__, 'zope.interface.tests.test_declarations.?')
  569. self.assertTrue(spec.inherit is None)
  570. self.assertTrue(foo.__implemented__ is spec)
  571. class Test_implementer_only(unittest.TestCase):
  572. def _getTargetClass(self):
  573. from zope.interface.declarations import implementer_only
  574. return implementer_only
  575. def _makeOne(self, *args, **kw):
  576. return self._getTargetClass()(*args, **kw)
  577. def test_function(self):
  578. from zope.interface.interface import InterfaceClass
  579. IFoo = InterfaceClass('IFoo')
  580. decorator = self._makeOne(IFoo)
  581. def _function():
  582. raise NotImplementedError()
  583. self.assertRaises(ValueError, decorator, _function)
  584. def test_method(self):
  585. from zope.interface.interface import InterfaceClass
  586. IFoo = InterfaceClass('IFoo')
  587. decorator = self._makeOne(IFoo)
  588. class Bar:
  589. def _method():
  590. raise NotImplementedError()
  591. self.assertRaises(ValueError, decorator, Bar._method)
  592. def test_oldstyle_class(self):
  593. # TODO Py3 story
  594. from zope.interface.declarations import Implements
  595. from zope.interface.interface import InterfaceClass
  596. IFoo = InterfaceClass('IFoo')
  597. IBar = InterfaceClass('IBar')
  598. old_spec = Implements(IBar)
  599. class Foo:
  600. __implemented__ = old_spec
  601. decorator = self._makeOne(IFoo)
  602. returned = decorator(Foo)
  603. self.assertTrue(returned is Foo)
  604. spec = Foo.__implemented__
  605. self.assertEqual(spec.__name__, '?')
  606. self.assertTrue(spec.inherit is None)
  607. self.assertTrue(Foo.__implemented__ is spec)
  608. def test_newstyle_class(self):
  609. from zope.interface.declarations import Implements
  610. from zope.interface.interface import InterfaceClass
  611. IFoo = InterfaceClass('IFoo')
  612. IBar = InterfaceClass('IBar')
  613. old_spec = Implements(IBar)
  614. class Foo(object):
  615. __implemented__ = old_spec
  616. decorator = self._makeOne(IFoo)
  617. returned = decorator(Foo)
  618. self.assertTrue(returned is Foo)
  619. spec = Foo.__implemented__
  620. self.assertEqual(spec.__name__, '?')
  621. self.assertTrue(spec.inherit is None)
  622. self.assertTrue(Foo.__implemented__ is spec)
  623. # Test '_implements' by way of 'implements{,Only}', its only callers.
  624. class Test_implementsOnly(unittest.TestCase, _Py3ClassAdvice):
  625. def test_simple(self):
  626. import warnings
  627. from zope.interface.declarations import implementsOnly
  628. from zope.interface._compat import PYTHON3
  629. from zope.interface.interface import InterfaceClass
  630. IFoo = InterfaceClass("IFoo")
  631. globs = {'implementsOnly': implementsOnly,
  632. 'IFoo': IFoo,
  633. }
  634. locs = {}
  635. CODE = "\n".join([
  636. 'class Foo(object):'
  637. ' implementsOnly(IFoo)',
  638. ])
  639. with warnings.catch_warnings(record=True) as log:
  640. warnings.resetwarnings()
  641. try:
  642. exec(CODE, globs, locs)
  643. except TypeError:
  644. self.assertTrue(PYTHON3, "Must be Python 3")
  645. else:
  646. if PYTHON3:
  647. self.fail("Didn't raise TypeError")
  648. Foo = locs['Foo']
  649. spec = Foo.__implemented__
  650. self.assertEqual(list(spec), [IFoo])
  651. self.assertEqual(len(log), 0) # no longer warn
  652. def test_called_once_from_class_w_bases(self):
  653. from zope.interface.declarations import implements
  654. from zope.interface.declarations import implementsOnly
  655. from zope.interface.interface import InterfaceClass
  656. IFoo = InterfaceClass("IFoo")
  657. IBar = InterfaceClass("IBar")
  658. globs = {'implements': implements,
  659. 'implementsOnly': implementsOnly,
  660. 'IFoo': IFoo,
  661. 'IBar': IBar,
  662. }
  663. locs = {}
  664. CODE = "\n".join([
  665. 'class Foo(object):',
  666. ' implements(IFoo)',
  667. 'class Bar(Foo):'
  668. ' implementsOnly(IBar)',
  669. ])
  670. if self._run_generated_code(CODE, globs, locs):
  671. Bar = locs['Bar']
  672. spec = Bar.__implemented__
  673. self.assertEqual(list(spec), [IBar])
  674. class Test_implements(unittest.TestCase, _Py3ClassAdvice):
  675. def test_called_from_function(self):
  676. import warnings
  677. from zope.interface.declarations import implements
  678. from zope.interface.interface import InterfaceClass
  679. IFoo = InterfaceClass("IFoo")
  680. globs = {'implements': implements, 'IFoo': IFoo}
  681. locs = {}
  682. CODE = "\n".join([
  683. 'def foo():',
  684. ' implements(IFoo)'
  685. ])
  686. if self._run_generated_code(CODE, globs, locs, False):
  687. foo = locs['foo']
  688. with warnings.catch_warnings(record=True) as log:
  689. warnings.resetwarnings()
  690. self.assertRaises(TypeError, foo)
  691. self.assertEqual(len(log), 0) # no longer warn
  692. def test_called_twice_from_class(self):
  693. import warnings
  694. from zope.interface.declarations import implements
  695. from zope.interface.interface import InterfaceClass
  696. from zope.interface._compat import PYTHON3
  697. IFoo = InterfaceClass("IFoo")
  698. IBar = InterfaceClass("IBar")
  699. globs = {'implements': implements, 'IFoo': IFoo, 'IBar': IBar}
  700. locs = {}
  701. CODE = "\n".join([
  702. 'class Foo(object):',
  703. ' implements(IFoo)',
  704. ' implements(IBar)',
  705. ])
  706. with warnings.catch_warnings(record=True) as log:
  707. warnings.resetwarnings()
  708. try:
  709. exec(CODE, globs, locs)
  710. except TypeError:
  711. if not PYTHON3:
  712. self.assertEqual(len(log), 0) # no longer warn
  713. else:
  714. self.fail("Didn't raise TypeError")
  715. def test_called_once_from_class(self):
  716. from zope.interface.declarations import implements
  717. from zope.interface.interface import InterfaceClass
  718. IFoo = InterfaceClass("IFoo")
  719. globs = {'implements': implements, 'IFoo': IFoo}
  720. locs = {}
  721. CODE = "\n".join([
  722. 'class Foo(object):',
  723. ' implements(IFoo)',
  724. ])
  725. if self._run_generated_code(CODE, globs, locs):
  726. Foo = locs['Foo']
  727. spec = Foo.__implemented__
  728. self.assertEqual(list(spec), [IFoo])
  729. class ProvidesClassTests(unittest.TestCase):
  730. def _getTargetClass(self):
  731. from zope.interface.declarations import ProvidesClass
  732. return ProvidesClass
  733. def _makeOne(self, *args, **kw):
  734. return self._getTargetClass()(*args, **kw)
  735. def test_simple_class_one_interface(self):
  736. from zope.interface.interface import InterfaceClass
  737. IFoo = InterfaceClass("IFoo")
  738. class Foo(object):
  739. pass
  740. spec = self._makeOne(Foo, IFoo)
  741. self.assertEqual(list(spec), [IFoo])
  742. def test___reduce__(self):
  743. from zope.interface.declarations import Provides # the function
  744. from zope.interface.interface import InterfaceClass
  745. IFoo = InterfaceClass("IFoo")
  746. class Foo(object):
  747. pass
  748. spec = self._makeOne(Foo, IFoo)
  749. klass, args = spec.__reduce__()
  750. self.assertTrue(klass is Provides)
  751. self.assertEqual(args, (Foo, IFoo))
  752. def test___get___class(self):
  753. from zope.interface.interface import InterfaceClass
  754. IFoo = InterfaceClass("IFoo")
  755. class Foo(object):
  756. pass
  757. spec = self._makeOne(Foo, IFoo)
  758. Foo.__provides__ = spec
  759. self.assertTrue(Foo.__provides__ is spec)
  760. def test___get___instance(self):
  761. from zope.interface.interface import InterfaceClass
  762. IFoo = InterfaceClass("IFoo")
  763. class Foo(object):
  764. pass
  765. spec = self._makeOne(Foo, IFoo)
  766. Foo.__provides__ = spec
  767. def _test():
  768. foo = Foo()
  769. return foo.__provides__
  770. self.assertRaises(AttributeError, _test)
  771. class Test_Provides(unittest.TestCase):
  772. def _callFUT(self, *args, **kw):
  773. from zope.interface.declarations import Provides
  774. return Provides(*args, **kw)
  775. def test_no_cached_spec(self):
  776. from zope.interface import declarations
  777. from zope.interface.interface import InterfaceClass
  778. IFoo = InterfaceClass("IFoo")
  779. cache = {}
  780. class Foo(object):
  781. pass
  782. with _Monkey(declarations, InstanceDeclarations=cache):
  783. spec = self._callFUT(Foo, IFoo)
  784. self.assertEqual(list(spec), [IFoo])
  785. self.assertTrue(cache[(Foo, IFoo)] is spec)
  786. def test_w_cached_spec(self):
  787. from zope.interface import declarations
  788. from zope.interface.interface import InterfaceClass
  789. IFoo = InterfaceClass("IFoo")
  790. prior = object()
  791. class Foo(object):
  792. pass
  793. cache = {(Foo, IFoo): prior}
  794. with _Monkey(declarations, InstanceDeclarations=cache):
  795. spec = self._callFUT(Foo, IFoo)
  796. self.assertTrue(spec is prior)
  797. class Test_directlyProvides(unittest.TestCase):
  798. def _callFUT(self, *args, **kw):
  799. from zope.interface.declarations import directlyProvides
  800. return directlyProvides(*args, **kw)
  801. def test_w_normal_object(self):
  802. from zope.interface.declarations import ProvidesClass
  803. from zope.interface.interface import InterfaceClass
  804. IFoo = InterfaceClass("IFoo")
  805. class Foo(object):
  806. pass
  807. obj = Foo()
  808. self._callFUT(obj, IFoo)
  809. self.assertTrue(isinstance(obj.__provides__, ProvidesClass))
  810. self.assertEqual(list(obj.__provides__), [IFoo])
  811. def test_w_class(self):
  812. from zope.interface.declarations import ClassProvides
  813. from zope.interface.interface import InterfaceClass
  814. IFoo = InterfaceClass("IFoo")
  815. class Foo(object):
  816. pass
  817. self._callFUT(Foo, IFoo)
  818. self.assertTrue(isinstance(Foo.__provides__, ClassProvides))
  819. self.assertEqual(list(Foo.__provides__), [IFoo])
  820. @_skip_under_py3k
  821. def test_w_non_descriptor_aware_metaclass(self):
  822. # There are no non-descriptor-aware types in Py3k
  823. from zope.interface.interface import InterfaceClass
  824. IFoo = InterfaceClass("IFoo")
  825. class MetaClass(type):
  826. def __getattribute__(cls, name):
  827. # Emulate metaclass whose base is not the type object.
  828. if name == '__class__':
  829. return cls
  830. # Under certain circumstances, the implementedByFallback
  831. # can get here for __dict__
  832. return type.__getattribute__(cls, name) # pragma: no cover
  833. class Foo(object):
  834. __metaclass__ = MetaClass
  835. obj = Foo()
  836. self.assertRaises(TypeError, self._callFUT, obj, IFoo)
  837. def test_w_classless_object(self):
  838. from zope.interface.declarations import ProvidesClass
  839. from zope.interface.interface import InterfaceClass
  840. IFoo = InterfaceClass("IFoo")
  841. the_dict = {}
  842. class Foo(object):
  843. def __getattribute__(self, name):
  844. # Emulate object w/o any class
  845. if name == '__class__':
  846. return None
  847. raise NotImplementedError(name)
  848. def __setattr__(self, name, value):
  849. the_dict[name] = value
  850. obj = Foo()
  851. self._callFUT(obj, IFoo)
  852. self.assertTrue(isinstance(the_dict['__provides__'], ProvidesClass))
  853. self.assertEqual(list(the_dict['__provides__']), [IFoo])
  854. class Test_alsoProvides(unittest.TestCase):
  855. def _callFUT(self, *args, **kw):
  856. from zope.interface.declarations import alsoProvides
  857. return alsoProvides(*args, **kw)
  858. def test_wo_existing_provides(self):
  859. from zope.interface.declarations import ProvidesClass
  860. from zope.interface.interface import InterfaceClass
  861. IFoo = InterfaceClass("IFoo")
  862. class Foo(object):
  863. pass
  864. obj = Foo()
  865. self._callFUT(obj, IFoo)
  866. self.assertTrue(isinstance(obj.__provides__, ProvidesClass))
  867. self.assertEqual(list(obj.__provides__), [IFoo])
  868. def test_w_existing_provides(self):
  869. from zope.interface.declarations import directlyProvides
  870. from zope.interface.declarations import ProvidesClass
  871. from zope.interface.interface import InterfaceClass
  872. IFoo = InterfaceClass("IFoo")
  873. IBar = InterfaceClass("IBar")
  874. class Foo(object):
  875. pass
  876. obj = Foo()
  877. directlyProvides(obj, IFoo)
  878. self._callFUT(obj, IBar)
  879. self.assertTrue(isinstance(obj.__provides__, ProvidesClass))
  880. self.assertEqual(list(obj.__provides__), [IFoo, IBar])
  881. class Test_noLongerProvides(unittest.TestCase):
  882. def _callFUT(self, *args, **kw):
  883. from zope.interface.declarations import noLongerProvides
  884. return noLongerProvides(*args, **kw)
  885. def test_wo_existing_provides(self):
  886. from zope.interface.interface import InterfaceClass
  887. IFoo = InterfaceClass("IFoo")
  888. class Foo(object):
  889. pass
  890. obj = Foo()
  891. self._callFUT(obj, IFoo)
  892. self.assertEqual(list(obj.__provides__), [])
  893. def test_w_existing_provides_hit(self):
  894. from zope.interface.declarations import directlyProvides
  895. from zope.interface.interface import InterfaceClass
  896. IFoo = InterfaceClass("IFoo")
  897. class Foo(object):
  898. pass
  899. obj = Foo()
  900. directlyProvides(obj, IFoo)
  901. self._callFUT(obj, IFoo)
  902. self.assertEqual(list(obj.__provides__), [])
  903. def test_w_existing_provides_miss(self):
  904. from zope.interface.declarations import directlyProvides
  905. from zope.interface.interface import InterfaceClass
  906. IFoo = InterfaceClass("IFoo")
  907. IBar = InterfaceClass("IBar")
  908. class Foo(object):
  909. pass
  910. obj = Foo()
  911. directlyProvides(obj, IFoo)
  912. self._callFUT(obj, IBar)
  913. self.assertEqual(list(obj.__provides__), [IFoo])
  914. def test_w_iface_implemented_by_class(self):
  915. from zope.interface.declarations import implementer
  916. from zope.interface.interface import InterfaceClass
  917. IFoo = InterfaceClass("IFoo")
  918. @implementer(IFoo)
  919. class Foo(object):
  920. pass
  921. obj = Foo()
  922. self.assertRaises(ValueError, self._callFUT, obj, IFoo)
  923. class ClassProvidesBaseFallbackTests(unittest.TestCase):
  924. def _getTargetClass(self):
  925. from zope.interface.declarations import ClassProvidesBaseFallback
  926. return ClassProvidesBaseFallback
  927. def _makeOne(self, klass, implements):
  928. # Don't instantiate directly: the C version can't have attributes
  929. # assigned.
  930. class Derived(self._getTargetClass()):
  931. def __init__(self, k, i):
  932. self._cls = k
  933. self._implements = i
  934. return Derived(klass, implements)
  935. def test_w_same_class_via_class(self):
  936. from zope.interface.interface import InterfaceClass
  937. IFoo = InterfaceClass("IFoo")
  938. class Foo(object):
  939. pass
  940. cpbp = Foo.__provides__ = self._makeOne(Foo, IFoo)
  941. self.assertTrue(Foo.__provides__ is cpbp)
  942. def test_w_same_class_via_instance(self):
  943. from zope.interface.interface import InterfaceClass
  944. IFoo = InterfaceClass("IFoo")
  945. class Foo(object):
  946. pass
  947. foo = Foo()
  948. cpbp = Foo.__provides__ = self._makeOne(Foo, IFoo)
  949. self.assertTrue(foo.__provides__ is IFoo)
  950. def test_w_different_class(self):
  951. from zope.interface.interface import InterfaceClass
  952. IFoo = InterfaceClass("IFoo")
  953. class Foo(object):
  954. pass
  955. class Bar(Foo):
  956. pass
  957. bar = Bar()
  958. cpbp = Foo.__provides__ = self._makeOne(Foo, IFoo)
  959. self.assertRaises(AttributeError, getattr, Bar, '__provides__')
  960. self.assertRaises(AttributeError, getattr, bar, '__provides__')
  961. class ClassProvidesBaseTests(ClassProvidesBaseFallbackTests):
  962. # Repeat tests for C optimizations
  963. def _getTargetClass(self):
  964. from zope.interface.declarations import ClassProvidesBase
  965. return ClassProvidesBase
  966. def test_optimizations(self):
  967. from zope.interface.declarations import ClassProvidesBaseFallback
  968. try:
  969. import zope.interface._zope_interface_coptimizations
  970. except ImportError:
  971. self.assertIs(self._getTargetClass(), ClassProvidesBaseFallback)
  972. else:
  973. self.assertIsNot(self._getTargetClass(), ClassProvidesBaseFallback)
  974. class ClassProvidesTests(unittest.TestCase):
  975. def _getTargetClass(self):
  976. from zope.interface.declarations import ClassProvides
  977. return ClassProvides
  978. def _makeOne(self, *args, **kw):
  979. return self._getTargetClass()(*args, **kw)
  980. def test_w_simple_metaclass(self):
  981. from zope.interface.declarations import implementer
  982. from zope.interface.interface import InterfaceClass
  983. IFoo = InterfaceClass("IFoo")
  984. IBar = InterfaceClass("IBar")
  985. @implementer(IFoo)
  986. class Foo(object):
  987. pass
  988. cp = Foo.__provides__ = self._makeOne(Foo, type(Foo), IBar)
  989. self.assertTrue(Foo.__provides__ is cp)
  990. self.assertEqual(list(Foo().__provides__), [IFoo])
  991. def test___reduce__(self):
  992. from zope.interface.declarations import implementer
  993. from zope.interface.interface import InterfaceClass
  994. IFoo = InterfaceClass("IFoo")
  995. IBar = InterfaceClass("IBar")
  996. @implementer(IFoo)
  997. class Foo(object):
  998. pass
  999. cp = Foo.__provides__ = self._makeOne(Foo, type(Foo), IBar)
  1000. self.assertEqual(cp.__reduce__(),
  1001. (self._getTargetClass(), (Foo, type(Foo), IBar)))
  1002. class Test_directlyProvidedBy(unittest.TestCase):
  1003. def _callFUT(self, *args, **kw):
  1004. from zope.interface.declarations import directlyProvidedBy
  1005. return directlyProvidedBy(*args, **kw)
  1006. def test_wo_declarations_in_class_or_instance(self):
  1007. class Foo(object):
  1008. pass
  1009. foo = Foo()
  1010. self.assertEqual(list(self._callFUT(foo)), [])
  1011. def test_w_declarations_in_class_but_not_instance(self):
  1012. from zope.interface.declarations import implementer
  1013. from zope.interface.interface import InterfaceClass
  1014. IFoo = InterfaceClass("IFoo")
  1015. @implementer(IFoo)
  1016. class Foo(object):
  1017. pass
  1018. foo = Foo()
  1019. self.assertEqual(list(self._callFUT(foo)), [])
  1020. def test_w_declarations_in_instance_but_not_class(self):
  1021. from zope.interface.declarations import directlyProvides
  1022. from zope.interface.interface import InterfaceClass
  1023. IFoo = InterfaceClass("IFoo")
  1024. class Foo(object):
  1025. pass
  1026. foo = Foo()
  1027. directlyProvides(foo, IFoo)
  1028. self.assertEqual(list(self._callFUT(foo)), [IFoo])
  1029. def test_w_declarations_in_instance_and_class(self):
  1030. from zope.interface.declarations import directlyProvides
  1031. from zope.interface.declarations import implementer
  1032. from zope.interface.interface import InterfaceClass
  1033. IFoo = InterfaceClass("IFoo")
  1034. IBar = InterfaceClass("IBar")
  1035. @implementer(IFoo)
  1036. class Foo(object):
  1037. pass
  1038. foo = Foo()
  1039. directlyProvides(foo, IBar)
  1040. self.assertEqual(list(self._callFUT(foo)), [IBar])
  1041. class Test_classProvides(unittest.TestCase, _Py3ClassAdvice):
  1042. def test_called_from_function(self):
  1043. import warnings
  1044. from zope.interface.declarations import classProvides
  1045. from zope.interface.interface import InterfaceClass
  1046. from zope.interface._compat import PYTHON3
  1047. IFoo = InterfaceClass("IFoo")
  1048. globs = {'classProvides': classProvides, 'IFoo': IFoo}
  1049. locs = {}
  1050. CODE = "\n".join([
  1051. 'def foo():',
  1052. ' classProvides(IFoo)'
  1053. ])
  1054. exec(CODE, globs, locs)
  1055. foo = locs['foo']
  1056. with warnings.catch_warnings(record=True) as log:
  1057. warnings.resetwarnings()
  1058. self.assertRaises(TypeError, foo)
  1059. if not PYTHON3:
  1060. self.assertEqual(len(log), 0) # no longer warn
  1061. def test_called_twice_from_class(self):
  1062. import warnings
  1063. from zope.interface.declarations import classProvides
  1064. from zope.interface.interface import InterfaceClass
  1065. from zope.interface._compat import PYTHON3
  1066. IFoo = InterfaceClass("IFoo")
  1067. IBar = InterfaceClass("IBar")
  1068. globs = {'classProvides': classProvides, 'IFoo': IFoo, 'IBar': IBar}
  1069. locs = {}
  1070. CODE = "\n".join([
  1071. 'class Foo(object):',
  1072. ' classProvides(IFoo)',
  1073. ' classProvides(IBar)',
  1074. ])
  1075. with warnings.catch_warnings(record=True) as log:
  1076. warnings.resetwarnings()
  1077. try:
  1078. exec(CODE, globs, locs)
  1079. except TypeError:
  1080. if not PYTHON3:
  1081. self.assertEqual(len(log), 0) # no longer warn
  1082. else:
  1083. self.fail("Didn't raise TypeError")
  1084. def test_called_once_from_class(self):
  1085. from zope.interface.declarations import classProvides
  1086. from zope.interface.interface import InterfaceClass
  1087. IFoo = InterfaceClass("IFoo")
  1088. globs = {'classProvides': classProvides, 'IFoo': IFoo}
  1089. locs = {}
  1090. CODE = "\n".join([
  1091. 'class Foo(object):',
  1092. ' classProvides(IFoo)',
  1093. ])
  1094. if self._run_generated_code(CODE, globs, locs):
  1095. Foo = locs['Foo']
  1096. spec = Foo.__providedBy__
  1097. self.assertEqual(list(spec), [IFoo])
  1098. # Test _classProvides_advice through classProvides, its only caller.
  1099. class Test_provider(unittest.TestCase):
  1100. def _getTargetClass(self):
  1101. from zope.interface.declarations import provider
  1102. return provider
  1103. def _makeOne(self, *args, **kw):
  1104. return self._getTargetClass()(*args, **kw)
  1105. def test_w_class(self):
  1106. from zope.interface.declarations import ClassProvides
  1107. from zope.interface.interface import InterfaceClass
  1108. IFoo = InterfaceClass("IFoo")
  1109. @self._makeOne(IFoo)
  1110. class Foo(object):
  1111. pass
  1112. self.assertTrue(isinstance(Foo.__provides__, ClassProvides))
  1113. self.assertEqual(list(Foo.__provides__), [IFoo])
  1114. class Test_moduleProvides(unittest.TestCase):
  1115. def test_called_from_function(self):
  1116. from zope.interface.declarations import moduleProvides
  1117. from zope.interface.interface import InterfaceClass
  1118. IFoo = InterfaceClass("IFoo")
  1119. globs = {'__name__': 'zope.interface.tests.foo',
  1120. 'moduleProvides': moduleProvides, 'IFoo': IFoo}
  1121. locs = {}
  1122. CODE = "\n".join([
  1123. 'def foo():',
  1124. ' moduleProvides(IFoo)'
  1125. ])
  1126. exec(CODE, globs, locs)
  1127. foo = locs['foo']
  1128. self.assertRaises(TypeError, foo)
  1129. def test_called_from_class(self):
  1130. from zope.interface.declarations import moduleProvides
  1131. from zope.interface.interface import InterfaceClass
  1132. IFoo = InterfaceClass("IFoo")
  1133. globs = {'__name__': 'zope.interface.tests.foo',
  1134. 'moduleProvides': moduleProvides, 'IFoo': IFoo}
  1135. locs = {}
  1136. CODE = "\n".join([
  1137. 'class Foo(object):',
  1138. ' moduleProvides(IFoo)',
  1139. ])
  1140. with self.assertRaises(TypeError):
  1141. exec(CODE, globs, locs)
  1142. def test_called_once_from_module_scope(self):
  1143. from zope.interface.declarations import moduleProvides
  1144. from zope.interface.interface import InterfaceClass
  1145. IFoo = InterfaceClass("IFoo")
  1146. globs = {'__name__': 'zope.interface.tests.foo',
  1147. 'moduleProvides': moduleProvides, 'IFoo': IFoo}
  1148. CODE = "\n".join([
  1149. 'moduleProvides(IFoo)',
  1150. ])
  1151. exec(CODE, globs)
  1152. spec = globs['__provides__']
  1153. self.assertEqual(list(spec), [IFoo])
  1154. def test_called_twice_from_module_scope(self):
  1155. from zope.interface.declarations import moduleProvides
  1156. from zope.interface.interface import InterfaceClass
  1157. IFoo = InterfaceClass("IFoo")
  1158. globs = {'__name__': 'zope.interface.tests.foo',
  1159. 'moduleProvides': moduleProvides, 'IFoo': IFoo}
  1160. locs = {}
  1161. CODE = "\n".join([
  1162. 'moduleProvides(IFoo)',
  1163. 'moduleProvides(IFoo)',
  1164. ])
  1165. with self.assertRaises(TypeError):
  1166. exec(CODE, globs)
  1167. class Test_getObjectSpecificationFallback(unittest.TestCase):
  1168. def _callFUT(self, *args, **kw):
  1169. from zope.interface.declarations import getObjectSpecificationFallback
  1170. return getObjectSpecificationFallback(*args, **kw)
  1171. def test_wo_existing_provides_classless(self):
  1172. the_dict = {}
  1173. class Foo(object):
  1174. def __getattribute__(self, name):
  1175. # Emulate object w/o any class
  1176. if name == '__class__':
  1177. raise AttributeError(name)
  1178. try:
  1179. return the_dict[name]
  1180. except KeyError:
  1181. raise AttributeError(name)
  1182. def __setattr__(self, name, value):
  1183. raise NotImplementedError()
  1184. foo = Foo()
  1185. spec = self._callFUT(foo)
  1186. self.assertEqual(list(spec), [])
  1187. def test_existing_provides_is_spec(self):
  1188. from zope.interface.declarations import directlyProvides
  1189. from zope.interface.interface import InterfaceClass
  1190. IFoo = InterfaceClass("IFoo")
  1191. def foo():
  1192. raise NotImplementedError()
  1193. directlyProvides(foo, IFoo)
  1194. spec = self._callFUT(foo)
  1195. self.assertTrue(spec is foo.__provides__)
  1196. def test_existing_provides_is_not_spec(self):
  1197. def foo():
  1198. raise NotImplementedError()
  1199. foo.__provides__ = object() # not a valid spec
  1200. spec = self._callFUT(foo)
  1201. self.assertEqual(list(spec), [])
  1202. def test_existing_provides(self):
  1203. from zope.interface.declarations import directlyProvides
  1204. from zope.interface.interface import InterfaceClass
  1205. IFoo = InterfaceClass("IFoo")
  1206. class Foo(object):
  1207. pass
  1208. foo = Foo()
  1209. directlyProvides(foo, IFoo)
  1210. spec = self._callFUT(foo)
  1211. self.assertEqual(list(spec), [IFoo])
  1212. def test_wo_provides_on_class_w_implements(self):
  1213. from zope.interface.declarations import implementer
  1214. from zope.interface.interface import InterfaceClass
  1215. IFoo = InterfaceClass("IFoo")
  1216. @implementer(IFoo)
  1217. class Foo(object):
  1218. pass
  1219. foo = Foo()
  1220. spec = self._callFUT(foo)
  1221. self.assertEqual(list(spec), [IFoo])
  1222. def test_wo_provides_on_class_wo_implements(self):
  1223. class Foo(object):
  1224. pass
  1225. foo = Foo()
  1226. spec = self._callFUT(foo)
  1227. self.assertEqual(list(spec), [])
  1228. class Test_getObjectSpecification(Test_getObjectSpecificationFallback):
  1229. # Repeat tests for C optimizations
  1230. def _callFUT(self, *args, **kw):
  1231. from zope.interface.declarations import getObjectSpecification
  1232. return getObjectSpecification(*args, **kw)
  1233. def test_optimizations(self):
  1234. from zope.interface.declarations import getObjectSpecificationFallback
  1235. from zope.interface.declarations import getObjectSpecification
  1236. try:
  1237. import zope.interface._zope_interface_coptimizations
  1238. except ImportError:
  1239. self.assertIs(getObjectSpecification,
  1240. getObjectSpecificationFallback)
  1241. else:
  1242. self.assertIsNot(getObjectSpecification,
  1243. getObjectSpecificationFallback)
  1244. class Test_providedByFallback(unittest.TestCase):
  1245. def _callFUT(self, *args, **kw):
  1246. from zope.interface.declarations import providedByFallback
  1247. return providedByFallback(*args, **kw)
  1248. def test_wo_providedBy_on_class_wo_implements(self):
  1249. class Foo(object):
  1250. pass
  1251. foo = Foo()
  1252. spec = self._callFUT(foo)
  1253. self.assertEqual(list(spec), [])
  1254. def test_w_providedBy_valid_spec(self):
  1255. from zope.interface.declarations import Provides
  1256. from zope.interface.interface import InterfaceClass
  1257. IFoo = InterfaceClass("IFoo")
  1258. class Foo(object):
  1259. pass
  1260. foo = Foo()
  1261. foo.__providedBy__ = Provides(Foo, IFoo)
  1262. spec = self._callFUT(foo)
  1263. self.assertEqual(list(spec), [IFoo])
  1264. def test_w_providedBy_invalid_spec(self):
  1265. class Foo(object):
  1266. pass
  1267. foo = Foo()
  1268. foo.__providedBy__ = object()
  1269. spec = self._callFUT(foo)
  1270. self.assertEqual(list(spec), [])
  1271. def test_w_providedBy_invalid_spec_class_w_implements(self):
  1272. from zope.interface.declarations import implementer
  1273. from zope.interface.interface import InterfaceClass
  1274. IFoo = InterfaceClass("IFoo")
  1275. @implementer(IFoo)
  1276. class Foo(object):
  1277. pass
  1278. foo = Foo()
  1279. foo.__providedBy__ = object()
  1280. spec = self._callFUT(foo)
  1281. self.assertEqual(list(spec), [IFoo])
  1282. def test_w_providedBy_invalid_spec_w_provides_no_provides_on_class(self):
  1283. class Foo(object):
  1284. pass
  1285. foo = Foo()
  1286. foo.__providedBy__ = object()
  1287. expected = foo.__provides__ = object()
  1288. spec = self._callFUT(foo)
  1289. self.assertTrue(spec is expected)
  1290. def test_w_providedBy_invalid_spec_w_provides_diff_provides_on_class(self):
  1291. class Foo(object):
  1292. pass
  1293. foo = Foo()
  1294. foo.__providedBy__ = object()
  1295. expected = foo.__provides__ = object()
  1296. Foo.__provides__ = object()
  1297. spec = self._callFUT(foo)
  1298. self.assertTrue(spec is expected)
  1299. def test_w_providedBy_invalid_spec_w_provides_same_provides_on_class(self):
  1300. from zope.interface.declarations import implementer
  1301. from zope.interface.interface import InterfaceClass
  1302. IFoo = InterfaceClass("IFoo")
  1303. @implementer(IFoo)
  1304. class Foo(object):
  1305. pass
  1306. foo = Foo()
  1307. foo.__providedBy__ = object()
  1308. foo.__provides__ = Foo.__provides__ = object()
  1309. spec = self._callFUT(foo)
  1310. self.assertEqual(list(spec), [IFoo])
  1311. class Test_providedBy(Test_providedByFallback):
  1312. # Repeat tests for C optimizations
  1313. def _callFUT(self, *args, **kw):
  1314. from zope.interface.declarations import providedBy
  1315. return providedBy(*args, **kw)
  1316. def test_optimizations(self):
  1317. from zope.interface.declarations import providedByFallback
  1318. from zope.interface.declarations import providedBy
  1319. try:
  1320. import zope.interface._zope_interface_coptimizations
  1321. except ImportError:
  1322. self.assertIs(providedBy, providedByFallback)
  1323. else:
  1324. self.assertIsNot(providedBy, providedByFallback)
  1325. class ObjectSpecificationDescriptorFallbackTests(unittest.TestCase):
  1326. def _getTargetClass(self):
  1327. from zope.interface.declarations \
  1328. import ObjectSpecificationDescriptorFallback
  1329. return ObjectSpecificationDescriptorFallback
  1330. def _makeOne(self, *args, **kw):
  1331. return self._getTargetClass()(*args, **kw)
  1332. def test_accessed_via_class(self):
  1333. from zope.interface.declarations import Provides
  1334. from zope.interface.interface import InterfaceClass
  1335. IFoo = InterfaceClass("IFoo")
  1336. class Foo(object):
  1337. pass
  1338. Foo.__provides__ = Provides(Foo, IFoo)
  1339. Foo.__providedBy__ = self._makeOne()
  1340. self.assertEqual(list(Foo.__providedBy__), [IFoo])
  1341. def test_accessed_via_inst_wo_provides(self):
  1342. from zope.interface.declarations import implementer
  1343. from zope.interface.declarations import Provides
  1344. from zope.interface.interface import InterfaceClass
  1345. IFoo = InterfaceClass("IFoo")
  1346. IBar = InterfaceClass("IBar")
  1347. @implementer(IFoo)
  1348. class Foo(object):
  1349. pass
  1350. Foo.__provides__ = Provides(Foo, IBar)
  1351. Foo.__providedBy__ = self._makeOne()
  1352. foo = Foo()
  1353. self.assertEqual(list(foo.__providedBy__), [IFoo])
  1354. def test_accessed_via_inst_w_provides(self):
  1355. from zope.interface.declarations import directlyProvides
  1356. from zope.interface.declarations import implementer
  1357. from zope.interface.declarations import Provides
  1358. from zope.interface.interface import InterfaceClass
  1359. IFoo = InterfaceClass("IFoo")
  1360. IBar = InterfaceClass("IBar")
  1361. IBaz = InterfaceClass("IBaz")
  1362. @implementer(IFoo)
  1363. class Foo(object):
  1364. pass
  1365. Foo.__provides__ = Provides(Foo, IBar)
  1366. Foo.__providedBy__ = self._makeOne()
  1367. foo = Foo()
  1368. directlyProvides(foo, IBaz)
  1369. self.assertEqual(list(foo.__providedBy__), [IBaz, IFoo])
  1370. class ObjectSpecificationDescriptorTests(
  1371. ObjectSpecificationDescriptorFallbackTests):
  1372. # Repeat tests for C optimizations
  1373. def _getTargetClass(self):
  1374. from zope.interface.declarations import ObjectSpecificationDescriptor
  1375. return ObjectSpecificationDescriptor
  1376. def test_optimizations(self):
  1377. from zope.interface.declarations import (
  1378. ObjectSpecificationDescriptorFallback)
  1379. try:
  1380. import zope.interface._zope_interface_coptimizations
  1381. except ImportError:
  1382. self.assertIs(self._getTargetClass(),
  1383. ObjectSpecificationDescriptorFallback)
  1384. else:
  1385. self.assertIsNot(self._getTargetClass(),
  1386. ObjectSpecificationDescriptorFallback)
  1387. # Test _normalizeargs through its callers.
  1388. class _Monkey(object):
  1389. # context-manager for replacing module names in the scope of a test.
  1390. def __init__(self, module, **kw):
  1391. self.module = module
  1392. self.to_restore = dict([(key, getattr(module, key)) for key in kw])
  1393. for key, value in kw.items():
  1394. setattr(module, key, value)
  1395. def __enter__(self):
  1396. return self
  1397. def __exit__(self, exc_type, exc_val, exc_tb):
  1398. for key, value in self.to_restore.items():
  1399. setattr(self.module, key, value)
  1400. class _MonkeyDict(object):
  1401. # context-manager for restoring a dict w/in a module in the scope of a test.
  1402. def __init__(self, module, attrname, **kw):
  1403. self.module = module
  1404. self.target = getattr(module, attrname)
  1405. self.to_restore = self.target.copy()
  1406. self.target.clear()
  1407. self.target.update(kw)
  1408. def __enter__(self):
  1409. return self.target
  1410. def __exit__(self, exc_type, exc_val, exc_tb):
  1411. self.target.clear()
  1412. self.target.update(self.to_restore)