def test_implementation(self): self.failUnless(verifyObject(interfaces.IVocabulary, self.list_vocab)) self.failUnless( verifyObject(interfaces.IVocabularyTokenized, self.list_vocab)) self.failUnless(verifyObject(interfaces.IVocabulary, self.items_vocab)) self.failUnless( verifyObject(interfaces.IVocabularyTokenized, self.items_vocab))
def test_configuration(self): """Verify reference block configuration. """ context = self.root.page.get_editable() view = MockView(context) configurations = get_block_configuration(ReferenceBlock, context) self.assertTrue(verifyObject(IBlockConfigurations, configurations)) self.assertEqual(len(configurations.get_all()), 1) configuration = configurations.get_by_identifier() self.assertTrue(verifyObject(IBlockConfiguration, configuration)) self.assertEqual( configuration.identifier, 'site-content') self.assertEqual( configuration.title, 'Site content') self.assertEqual( configuration.block, ReferenceBlock) self.assertEqual( configuration.get_icon(view), 'http://localhost/++resource++icon-blocks-site-content.png') self.assertTrue(configuration.is_available(view))
def test_IProcessTransport(self): """ The protocol itself should be useable as a transport for some other protocol. """ verifyObject(interfaces.IProcessTransport, Channel3Protocol('name', None, None))
def test_import_text_block_with_references(self): importer = self.assertImportFile( 'test_import_text_block_with_references.silvaxml', ['/root/model', '/root/link']) self.assertEqual(importer.getProblems(), []) model = self.root._getOb('model') self.assertTrue(verifyObject(IPageModel, model)) version = model.get_editable() self.assertTrue(verifyObject(IPageModelVersion, version)) manager = IBlockManager(version) slot1 = manager.get_slot('one') self.assertEqual(1, len(slot1)) _, text_block = slot1[0] self.assertIsInstance(text_block, TextBlock) references = list( getUtility(IReferenceService).get_references_from(version)) self.assertEqual(1, len(references)) reference = references[0] link = reference.target self.assertTrue(ILink.providedBy(link)) self.assertEqual(2, len(reference.tags)) reference_type = reference.tags[0] self.assertEqual("%s link" % text_block.identifier, reference_type)
def test_configuration(self): """Verify slot block configuration. """ context = self.root.page.get_editable() view = MockView(context) configurations = get_block_configuration(BlockSlot, context) self.assertTrue(verifyObject(IBlockConfigurations, configurations)) self.assertEqual(len(configurations.get_all()), 1) configuration = configurations.get_by_identifier() self.assertTrue(verifyObject(IBlockConfiguration, configuration)) self.assertEqual( configuration.identifier, 'slot') self.assertEqual( configuration.title, 'Slot') self.assertEqual( configuration.block, BlockSlot) self.assertEqual( configuration.get_icon(view), 'http://localhost/++resource++icon-blocks-slot.png') # This block is only available on models. self.assertFalse(configuration.is_available(view)) view = MockView(self.root.model.get_editable()) self.assertTrue(configuration.is_available(view))
def get_message_listener(self): for listener in self.listeners: try: verifyObject(MessageListener, listener) return listener except DoesNotImplement: pass
def registerPlugin(self, plugin): """Registers a plugin.""" plugin_types = { 'presence': IPresencePlugin, 'chat': IChatPlugin, 'population': IPopulationPlugin, 'base_plugin': BaseInterface, } # Everything is, at least, a base plugin. valid_types = ['baseplugin'] # Loop through the types of plugins and check for implentation of each. claimed_compliances = list(implementedBy(type(plugin))) # Can we use this as a map instead? for t, interface in plugin_types.iteritems(): if interface in claimed_compliances: try: verifyObject(interface, plugin) # If the above succeeded, then `plugin` implementes `interface`. self.plugins[t].append(plugin) self.plugins[t].sort() valid_types.append(t) except DoesNotImplement: log.error('Plugin %s claims to be a %s, but is not!', plugin.name, t) plugin.setup(self) log.info('registered plugin %s as %s', plugin.name, valid_types)
def rpc_message(self, sender, pubkey, encrypted): try: box = Box(PrivateKey(self.signing_key.encode(nacl.encoding.RawEncoder)), PublicKey(pubkey)) plaintext = box.decrypt(encrypted) p = PlaintextMessage() p.ParseFromString(plaintext) signature = p.signature p.ClearField("signature") verify_key = nacl.signing.VerifyKey(p.signed_pubkey[64:]) verify_key.verify(p.SerializeToString(), signature) h = nacl.hash.sha512(p.signed_pubkey) pow_hash = h[64:128] if int(pow_hash[:6], 16) >= 50 or p.sender_guid.encode("hex") != h[:40] or p.sender_guid != sender.id: raise Exception('Invalid guid') self.log.info("received a message from %s" % sender) self.router.addContact(sender) for listener in self.listeners: try: verifyObject(MessageListener, listener) listener.notify(p, signature) except DoesNotImplement: pass return ["True"] except Exception: self.log.warning("received invalid message from %s" % sender) return ["False"]
def get_notification_listener(self): for listener in self.listeners: try: verifyObject(NotificationListener, listener) return listener except DoesNotImplement: pass
def retrieve_plugins(interface, cached=True, cache={}): """ Look up all plugins for a certain interface. If the plugin cache is enabled, this function will not attempt to reload plugins from disk or discover new plugins. :param interface interface: the interface to use :param bool cached: whether to use the in-memory plugin cache :returns: a dict of plugins, keyed by name :raises PluginException: no plugins could be found for the given interface """ if cached and interface in cache: return cache[interface] log.msg("Discovering %s..." % interface) d = {} for p in getPlugins(interface, bravo.plugins): try: verifyObject(interface, p) log.msg(" ( ^^) Plugin: %s" % p.name) d[p.name] = p except BrokenImplementation, bi: if hasattr(p, "name"): log.msg(" ( ~~) Plugin %s is missing attribute %r!" % (p.name, bi.name)) else: log.msg(" ( >&) Plugin %s is unnamed and useless!" % p) except BrokenMethodImplementation, bmi: log.msg(" ( Oo) Plugin %s has a broken %s()!" % (p.name, bmi.method)) log.err()
def rpc_follow(self, sender, proto, signature): self.log.info("received follow request from %s" % sender) self.router.addContact(sender) try: verify_key = nacl.signing.VerifyKey(sender.signed_pubkey[64:]) verify_key.verify(proto, signature) f = Followers.Follower() f.ParseFromString(proto) if f.guid != sender.id: raise Exception('GUID does not match sending node') if f.following != self.node.id: raise Exception('Following wrong node') f.signature = signature self.db.FollowData().set_follower(f) proto = Profile(self.db).get(False) m = Metadata() m.name = proto.name m.handle = proto.handle m.avatar_hash = proto.avatar_hash m.short_description = proto.short_description m.nsfw = proto.nsfw for listener in self.listeners: try: verifyObject(NotificationListener, listener) listener.notify(sender.id, f.metadata.handle, "follow", "", "", f.metadata.avatar_hash) except DoesNotImplement: pass return ["True", m.SerializeToString(), self.signing_key.sign(m.SerializeToString())[:64]] except Exception: self.log.warning("failed to validate follower") return ["False"]
def test_interfaces(self): """The serivce maker implements both IServiceMaker and IPlugin. """ sm = WebsiteServiceMaker() verifyObject(IServiceMaker, sm) verifyObject(IPlugin, sm)
def test_folder(self): """When pasting a folder as a ghost, its content is ghosted and any versioned content (ghost) in it are published. """ manager = IContainerManager(self.root.target) with assertTriggersEvents('ObjectWillBeAddedEvent', 'ObjectAddedEvent', 'ContainerModifiedEvent'): with manager.ghoster() as ghoster: ghost = ghoster(self.root.source) self.assertTrue(verifyObject(IGhostFolder, ghost)) self.assertEqual(ghost.get_link_status(), None) self.assertEqual(ghost.get_haunted(), self.root.source) self.assertIn('source', self.root.target.objectIds()) # The ghost folder is created inside the target folder and is # already haunting the source. ghost = self.root.target.source self.assertTrue(verifyObject(IGhostFolder, ghost)) self.assertEqual(ghost.get_link_status(), None) self.assertEqual(ghost.get_haunted(), self.root.source) self.assertItemsEqual( ghost.objectIds(), ['toc', 'data', 'folder', 'logo']) self.assertTrue(verifyObject(IGhost, ghost.toc)) self.assertEqual(ghost.toc.get_haunted(), self.root.source.toc) self.assertTrue(verifyObject(IGhost, ghost.data)) self.assertEqual(ghost.data.get_haunted(), self.root.source.data) self.assertEqual(ghost.data.is_published(), True) self.assertTrue(verifyObject(IGhostFolder, ghost.folder)) self.assertEqual(ghost.folder.get_haunted(), self.root.source.folder)
def test64(self): from zope.interface.verify import verifyObject import BTrees from BTrees.LOBTree import LOTreeSet verifyObject(BTrees.Interfaces.IBTreeFamily, BTrees.family64) self.assertEqual( BTrees.family64.IO, BTrees.LOBTree) self.assertEqual( BTrees.family64.OI, BTrees.OLBTree) self.assertEqual( BTrees.family64.II, BTrees.LLBTree) self.assertEqual( BTrees.family64.IF, BTrees.LFBTree) self.assertEqual( BTrees.family64.OO, BTrees.OOBTree) s = LOTreeSet() s.insert(BTrees.family64.maxint) self.assertTrue(BTrees.family64.maxint in s) s = LOTreeSet() s.insert(BTrees.family64.minint) self.assertTrue(BTrees.family64.minint in s) s = LOTreeSet() # XXX why oh why do we expect ValueError here, but TypeError in test32? self.assertRaises(ValueError, s.insert, BTrees.family64.maxint + 1) self.assertRaises(ValueError, s.insert, BTrees.family64.minint - 1) self.check_pickling(BTrees.family64)
def test_interface(self): """ An instance of the reactor has all of the methods defined on L{IReactorWin32Events}. """ reactor = self.buildReactor() verifyObject(IReactorWin32Events, reactor)
def _test_object(fixture_name): print x = getattr(fixtures, fixture_name) formatter = formatter_for_object(x, "default") verifyObject(IFormatter, formatter) s = formatter.format(x) print " -- format:default %s -- " % (type(x)) print s format_spec = "default:precision=4,aa,bb" print " -- format %s -- " % (format_spec) s = format(x, format_spec) print s format_spec = "" print " -- format <empty-string> -- " s = format(x, format_spec) print s print " -- format <missing> -- " s = format(x) print s
def test32(self): from zope.interface.verify import verifyObject import BTrees from BTrees.IOBTree import IOTreeSet verifyObject(BTrees.Interfaces.IBTreeFamily, BTrees.family32) self.assertEqual( BTrees.family32.IO, BTrees.IOBTree) self.assertEqual( BTrees.family32.OI, BTrees.OIBTree) self.assertEqual( BTrees.family32.II, BTrees.IIBTree) self.assertEqual( BTrees.family32.IF, BTrees.IFBTree) self.assertEqual( BTrees.family32.OO, BTrees.OOBTree) s = IOTreeSet() s.insert(BTrees.family32.maxint) self.assertTrue(BTrees.family32.maxint in s) s = IOTreeSet() s.insert(BTrees.family32.minint) self.assertTrue(BTrees.family32.minint in s) s = IOTreeSet() # this next bit illustrates an, um, "interesting feature". If # the characteristics change to match the 64 bit version, please # feel free to change. with self.assertRaises((TypeError, OverflowError)): s.insert(BTrees.family32.maxint + 1) with self.assertRaises((TypeError, OverflowError)): s.insert(BTrees.family32.minint - 1) self.check_pickling(BTrees.family32)
def test_language_interfaces(self): """ Test that the language modules all satisfy the proper interface. """ for langModule in (structspec.languages.c, structspec.languages.python): verifyObject(structspec.interfaces.ILanguage, langModule)
def test_field_dicts(): print # [Dict, TextLine] f = zope.schema.Dict( title=u"A map of keywords", key_type=zope.schema.Choice(vocabulary=SimpleVocabulary.fromValues(("alpha", "alpha-el", "nonsence"))), value_type=zope.schema.TextLine(title=u"Keyword"), ) v = {"alpha": u"alpha", "alpha-el": u"αλφα", "nonsence": u'ειμαι "βράχος"'} f.validate(v) for name in ["default"]: formatter = formatter_for_field(f, name) verifyObject(IFormatter, formatter) s = formatter.format(v) print " -- format:%s %s -- " % (name, type(f)) print s # [Dict, *] f = schemata.IFooMetadata.get("contacts") v = {"personal": fixtures.contact1, "office": fixtures.contact2} f.validate(v) for name in ["default"]: formatter = formatter_for_field(f, name) verifyObject(IFormatter, formatter) s = formatter.format(v) print " -- format:%s %s -- " % (name, type(f)) print s
def test_collection_provides_ICollection(self): """ The return value of .get_row_collection() is an object that provides ICollection. """ collection = yield self.mk_collection("owner-1") verifyObject(ICollection, collection)
def test_write_interfaces(self): """ Test that outputters all satisfy the appropriate interface. """ for outputter in (structspec.common.writeOut, structspec.common.writeOutBlock): verifyObject(structspec.interfaces.IOutputter, outputter)
def test_interfaces(self): """ L{Protocol} instances provide L{IProtocol} and L{ILoggingContext}. """ proto = Protocol() self.assertTrue(verifyObject(IProtocol, proto)) self.assertTrue(verifyObject(ILoggingContext, proto))
def test_implementsInterface(self): """ L{checkers.UNIXAuthorizedKeysFiles} implements L{checkers.IAuthorizedKeysDB}. """ keydb = checkers.UNIXAuthorizedKeysFiles(self.userdb) verifyObject(checkers.IAuthorizedKeysDB, keydb)
def test_instance_conforms_to_IUserLocator(self): from zope.interface.verify import verifyObject from ...interfaces import IUserLocator context = object() request = {} verifyObject(IUserLocator, self._makeOne())
def test_implementsInterface(self): """ L{checkers.InMemorySSHKeyDB} implements L{checkers.IAuthorizedKeysDB} """ keydb = checkers.InMemorySSHKeyDB({'alice': ['key']}) verifyObject(checkers.IAuthorizedKeysDB, keydb)
def verify_plugin(interface, plugin): """ Plugin interface verification. This function will call ``verifyObject()`` and ``validateInvariants()`` on the plugins passed to it. The primary purpose of this wrapper is to do logging, but it also permits code to be slightly cleaner, easier to test, and callable from other modules. """ converted = interface(plugin, None) if converted is None: raise PluginException("Couldn't convert %s to %s" % (plugin, interface)) try: verifyObject(interface, converted) interface.validateInvariants(converted) log.msg(" ( ^^) Plugin: %s" % converted.name) except BrokenImplementation, bi: if hasattr(plugin, "name"): log.msg(" ( ~~) Plugin %s is missing attribute %r!" % (plugin.name, bi.name)) else: log.msg(" ( >&) Plugin %s is unnamed and useless!" % plugin)
def test_writeConnectionLost(self): """ The protocol created by L{flowFountFromEndpoint} provides half-close support, and when it receives an EOF (i.e.: C{writeConnectionLost}) it will signal the end of the flow to its drain's fount, but not to its fount's drain. """ endpoint, ports = fakeEndpointWithPorts() fffep = flowFountFromEndpoint(endpoint) fffep.callback(None) flowFount = self.successResultOf(fffep) protocol = ports[0].factory.buildProtocol(None) verifyObject(IHalfCloseableProtocol, protocol) aTransport = StringTransport() protocol.makeConnection(aTransport) accepted = FakeDrain() flowFount.flowTo(accepted) [flow] = accepted.received receivedData = FakeDrain() dataSender = FakeFount() flow.fount.flowTo(receivedData) dataSender.flowTo(flow.drain) self.assertEqual(len(receivedData.stopped), 0) self.assertEqual(dataSender.flowIsStopped, False) protocol.writeConnectionLost() self.assertEqual(len(receivedData.stopped), 0) self.assertEqual(dataSender.flowIsStopped, 1) protocol.connectionLost(ConnectionDone()) self.assertEqual(len(receivedData.stopped), 1) self.assertEqual(dataSender.flowIsStopped, 1)
def _add_formatter(self, formatter): try: verifyObject(IAnnotationFormatter, formatter) except DoesNotImplement: raise ValueError('formatter is not implementing IAnnotationFormatter interface') self._formatters.append(formatter)
def test00_interface(self): portal_modifier = self.portal.portal_modifier # test interface conformance #verifyObject(IModifier, portal_modifier) verifyObject(IModifierRegistrySet, portal_modifier) verifyObject(IModifierRegistryQuery, portal_modifier)
def test_instance_implements_ITemplate(self): from zope.interface.verify import verifyObject from pyramid.interfaces import ITemplateRenderer path = self._getTemplatePath("minimal.pt") lookup = DummyLookup() verifyObject(ITemplateRenderer, self._makeOne(path, lookup))
def test_interfaces(self): """ interface implementations """ plugin = self._make_one() self.assert_(verifyObject(IPropertiesPlugin, plugin))
def test_verifyObject(self): from zope.interface.verify import verifyObject from zope.lifecycleevent.interfaces import IObjectMovedEvent verifyObject(IObjectMovedEvent, self._makeOne(None, None, None, None, None))
def test_instance_implements_ITemplate(self): from zope.interface.verify import verifyObject from pyramid.interfaces import ITemplateRenderer verifyObject(ITemplateRenderer, self._makeOne(None, None, None))
def test_implementsConstrainTypes(self): iface = ISelectableConstrainTypes self.assertTrue(iface.providedBy(self._ATCT)) self.assertTrue(verifyObject(iface, self._ATCT))
def test_implementsATBTreeFolder(self): iface = IATBTreeFolder self.assertTrue(iface.providedBy(self._ATCT)) self.assertTrue(verifyObject(iface, self._ATCT))
def test_implementsOrderInterface(self): self.assertTrue(IOrderedContainer.providedBy(self._ATCT)) self.assertTrue(verifyObject(IOrderedContainer, self._ATCT))
def test_implementsConstrainTypes(self): self.assertTrue(ISelectableConstrainTypes.providedBy(self._ATCT)) self.assertTrue(verifyObject(ISelectableConstrainTypes, self._ATCT))
def test_instance_conforms_to_IApplication(self): from OFS.interfaces import IApplication from zope.interface.verify import verifyObject verifyObject(IApplication, self._makeOne())
def test_verify_obj(self): obj = self._cut(self._meeting()) self.assertTrue(verifyObject(IProposalIds, obj))
def test_instance_conforms_to_ICatalogIndex(self): from zope.interface.verify import verifyObject from repoze.catalog.interfaces import ICatalogIndex verifyObject(ICatalogIndex, self._makeOne())
def test_instance_conforms_to_IQuip(self): from zope.interface.verify import verifyObject from karl.models.interfaces import IQuip verifyObject(IQuip, self._makeOne())
def test_interface(self): """ L{SSHChannel} instances provide L{interfaces.ITransport}. """ self.assertTrue(verifyObject(interfaces.ITransport, self.channel))
def testBeforeStreaming(self): e = PubBeforeStreaming(_Response()) verifyObject(IPubBeforeStreaming, e)
def test_instance_conforms_to_IChatterbox(self): from zope.interface.verify import verifyObject from karl.models.interfaces import IChatterbox verifyObject(IChatterbox, self._makeOne())
def testAfterTraversal(self): e = PubAfterTraversal(_Request()) verifyObject(IPubAfterTraversal, e)
def test_interface(self): translated_language = self.getTranslatedLanguage(self.language) self.assertTrue(verifyObject(ITranslatedLanguage, translated_language))
def testPubStart(self): verifyObject(IPubStart, PubStart(_Request()))
def testBeforeCommit(self): e = PubBeforeCommit(_Request()) verifyObject(IPubBeforeCommit, e)
def test_connection_interface(self): from ZODB.interfaces import IConnection db = databaseFromString("<zodb>\n<mappingstorage/>\n</zodb>") cn = db.open() verifyObject(IConnection, cn)
def testPubSuccess(self): e = PubSuccess(_Request()) verifyObject(IPubSuccess, e) verifyObject(IPubEnd, e)
def test_instance_conforms_to_ICredentialsUpdatedEvent(self): from zope.interface.verify import verifyObject from Products.PluggableAuthService.interfaces.events \ import ICredentialsUpdatedEvent verifyObject(ICredentialsUpdatedEvent, self._makeOne())
def test_verify_object(self): self.assertTrue(verifyObject(IPoll, self._cut()))
def test_instance_conforms_to_IPEP302Loader(self): from zope.interface.verify import verifyObject from pyramid.interfaces import IPEP302Loader verifyObject(IPEP302Loader, self._makeOne())
def test_instance_conforms_to_IPrincipalDeletedEvent(self): from zope.interface.verify import verifyObject from Products.PluggableAuthService.interfaces.events \ import IPrincipalDeletedEvent verifyObject(IPrincipalDeletedEvent, self._makeOne())
def test_instance_conforms_to_IPermission(self): from zope.interface.verify import verifyObject from zope.security.interfaces import IPermission verifyObject(IPermission, self._makeOne('testing'))
def test_interface(self): """ The object implements ``IStatePersister``. """ state_persister, get_state = fixture(self) verifyObject(IStatePersister, state_persister)
def test_icon_component(self): self.load_zcml( '<logo:icon base="{}" />'.format(icon)) registry = getMultiAdapter((None, None), IIconConfig) self.assertEqual(icon, registry.base) verifyObject(IIconConfig, registry)
def test_instance_conforms_to_IPackageOverrides(self): from zope.interface.verify import verifyObject from pyramid.interfaces import IPackageOverrides verifyObject(IPackageOverrides, self._makeOne())
def test_logo_component(self): self.load_zcml('<logo:logo base="{}" />'.format(logo)) registry = getMultiAdapter((None, None), ILogoConfig) self.assertEqual(logo, registry.base) verifyObject(ILogoConfig, registry)
def test_instance_conforms_to_IZCLexicon(self): from Products.ZCTextIndex.interfaces import IZCLexicon from zope.interface.verify import verifyObject verifyObject(IZCLexicon, self._makeOne())