def testAddMenuRelativeToNonStructuralFolder(self): self.folder.invokeFactory('Folder', 'f1') directlyProvides(self.folder.f1, INonStructuralFolder) items = self.menu.getMenuItems(self.folder.f1, self.request) factoriesMenuItem = [i for i in items if i['extra']['id'] == 'plone-contentmenu-factories'] self.failIf(factoriesMenuItem)
def test_process_message_report(self): from zope.interface import directlyProvides from pyramid.testing import DummyModel from karl.models.interfaces import IPeopleDirectory INFO = {'targets': [{'report': 'section+testing', 'community': None, 'tool': None,}], 'author': 'phreddy', 'subject': 'Feedback' } text = 'This entry stinks!' attachments = [('foo.txt', 'text/plain', 'My attachment')] message = DummyMessage(INFO, text, attachments) self._set_up_queue([message,]) mailin = self._makeOne() pd = mailin.root['people'] = DummyModel() directlyProvides(pd, IPeopleDirectory) section = pd['section'] = DummyModel() testing = section['testing'] = DummyModel() mailin() self.assertEqual(len(self.handlers), 1) handler = self.handlers[0] self.failUnless(handler.context is testing) self.assertEqual(handler.handle_args, (message, INFO, text, attachments)) self.assertEqual(len(self.mailer), 0)
def test_in_intranet(self): from karl.content.interfaces import IIntranets from zope.interface import directlyProvides intranet = testing.DummyModel() directlyProvides(intranet, IIntranets) intranet['foo'] = context = testing.DummyModel() self.failIf(self._call_fut(context, None))
def test_show_workflow_custom_acl(self): from repoze.workflow.testing import DummyWorkflow from zope.interface import Interface from zope.interface import directlyProvides workflow = DummyWorkflow() def state_info(context, request): return [{'name': 'foo', 'current': True, 'transitions': True}, {'name': 'bar', 'current': False, 'transitions': True}] workflow.state_info = state_info def get_dummy_workflow(*args, **kw): return workflow import karl.views.acl old_f = karl.views.acl.get_context_workflow karl.views.acl.get_context_workflow = get_dummy_workflow try: context = testing.DummyModel() context.state = 'foo' context.__custom_acl__ = [] directlyProvides(Interface) request = testing.DummyRequest() renderer = karl.testing.registerDummyRenderer('templates/edit_acl.pt') self._callFUT(context, request) self.assertEqual(renderer.security_state, 'CUSTOM') self.assertEqual(renderer.security_states, ['CUSTOM', 'foo', 'bar']) finally: karl.views.acl.get_context_workflow = old_f
def create_viewlet(self, viewlet, context=None, view=None, manager=None): if context is None: context = self.portal request = TestRequest() directlyProvides(request, IAttributeAnnotatable) request.set = mock.Mock() return viewlet(context, request, view, manager)
def proxyForInterface(iface, originalAttribute='original'): """ Create a class which proxies all method calls which adhere to an interface to another provider of that interface. This function is intended for creating specialized proxies. The typical way to use it is by subclassing the result:: class MySpecializedProxy(proxyForInterface(IFoo)): def someInterfaceMethod(self, arg): if arg == 3: return 3 return self.original.someInterfaceMethod(arg) @param iface: The Interface to which the resulting object will conform, and which the wrapped object must provide. @param originalAttribute: name of the attribute used to save the original object in the resulting class. Default to C{original}. @type originalAttribute: C{str} @return: A class whose constructor takes the original object as its only argument. Constructing the class creates the proxy. """ def __init__(self, original): setattr(self, originalAttribute, original) contents = {"__init__": __init__} for name in iface: contents[name] = _ProxyDescriptor(name, originalAttribute) proxy = type("(Proxy for %s)" % (reflect.qual(iface),), (object,), contents) directlyProvides(proxy, iface) return proxy
def test_it(self): class DummyModel(testing.DummyModel): def _p_deactivate(self): self.deactivated = True from repoze.folder.interfaces import IFolder from zope.interface import directlyProvides request = testing.DummyRequest() context2 = DummyModel() context2.__acl__ = ['Allow', 'fred', ('read',)] context2.security_state = 'fred-ish' context = DummyModel() context['context2'] = context2 directlyProvides(context, IFolder) renderer = karl.testing.registerDummyRenderer('templates/acl_tree.pt') self._callFUT(context, request) self.assertEqual(len(renderer.acls), 2) context_acl = renderer.acls[0] self.assertEqual(context_acl, {'path': '/', 'acl': None, 'name': '/', 'offset': 0, 'url':'http://example.com/', 'security_state':None}) context2_acl = renderer.acls[1] self.assertEqual(context2_acl, {'path': '/context2', 'acl': ['Allow', 'fred', ('read',)], 'name': 'context2', 'offset': 1, 'url':'http://example.com/context2/', 'security_state':'fred-ish'}) self.assertEqual(context.deactivated, True) self.assertEqual(context2.deactivated, True)
def test_it(self): from zope.interface import Interface from zope.interface import directlyProvides from karl.models.interfaces import ICatalogSearch from karl.models.interfaces import ICommunity context = testing.DummyModel() directlyProvides(context, ICommunity) context.member_names = set('a',) context.moderator_names = set() request = testing.DummyRequest(params={'val':'a'}) profiles = testing.DummyModel() profile_1 = karltesting.DummyProfile(__name__='a', security_state='active') profile_2 = karltesting.DummyProfile(__name__='b', security_state='active') profile_3 = karltesting.DummyProfile(__name__='c', security_state='active') profile_4 = karltesting.DummyProfile(__name__='d', security_state='inactive') def resolver(docid): d = {1:profile_1, 2:profile_2, 3:profile_3, 4:profile_4} return d.get(docid) def dummy_catalog_search(context): def search(**kw): return 3, [1,2,3], resolver return search karltesting.registerAdapter(dummy_catalog_search, (Interface), ICatalogSearch) response = self._callFUT(context, request) self.assertEqual( response.body, '[{"text": "title", "id": "b"}, ' '{"text": "title", "id": "c"}]')
def _makeCommunity(self): from karl.models.interfaces import ICommunity from karl.models.interfaces import IInvitation from zope.interface import directlyProvides community = testing.DummyModel() community.member_names = set(['a']) community.moderator_names = set(['b', 'c']) site = testing.DummyModel() site['communities'] = testing.DummyModel() site['communities']['community'] = community profiles = testing.DummyModel() profiles['a'] = karltesting.DummyProfile() profiles['b'] = karltesting.DummyProfile() profiles['c'] = karltesting.DummyProfile() invitation = testing.DummyModel(email='*****@*****.**', message='message') directlyProvides(invitation, IInvitation) community['invitation'] = invitation site['profiles'] = profiles users = karltesting.DummyUsers(community) site.users = users directlyProvides(community, ICommunity) community.moderators_group_name = 'moderators' community.members_group_name = 'members' return community
def test_handle_submit_success(self): self._register() from zope.interface import directlyProvides from karl.models.interfaces import ISite from karl.models.interfaces import ICommunity from repoze.lemonade.interfaces import IContentFactory context = testing.DummyModel() directlyProvides(context, ISite) tags = context.tags = testing.DummyModel() _tagged = [] def _update(item, user, tags): _tagged.append((item, user, tags)) tags.update = _update testing.registerDummySecurityPolicy('userid') workflow = self._registerDummyWorkflow() testing.registerAdapter(lambda *arg: DummyCommunity, (ICommunity,), IContentFactory) dummy_tool_factory = DummyToolFactory() self._registerAddables([{'name':'blog', 'title':'blog', 'component':dummy_tool_factory}]) context.users = karltesting.DummyUsers({}) context.catalog = karltesting.DummyCatalog({1:'/foo'}) request = testing.DummyRequest() controller = self._makeOne(context, request) converted = {'title':'Thetitle yo', 'description':'thedescription', 'text':'thetext', 'tools': ['blog'], 'security_state': 'private', 'tags': ['foo'], 'default_tool': 'blog', } result = controller.handle_submit(converted) rl = 'http://example.com/thetitle-yo/members/add_existing.html' self.failUnless(result.location.startswith(rl)) community = context['thetitle-yo'] self.assertEqual(community.title, 'Thetitle yo') self.assertEqual(community.description, 'thedescription') self.assertEqual(community.text, 'thetext') self.assertEqual(community.default_tool, 'blog') self.assertEqual(community.creator, 'userid') self.assertEqual(community.modified_by, 'userid') self.assertEqual( context.users.added_groups, [('userid', 'moderators'), ('userid', 'members') ] ) self.assertEqual(dummy_tool_factory.added, True) self.assertEqual(len(_tagged), 1) self.assertEqual(_tagged[0][0], None) self.assertEqual(_tagged[0][1], 'userid') self.assertEqual(_tagged[0][2], ['foo']) self.assertEqual(workflow.transitioned[0]['to_state'], 'private') # try again w/ an invalid default_tool converted['title'] = 'Another title yo' converted['default_tool'] = 'wiki' result = controller.handle_submit(converted) community = context['another-title-yo'] self.failUnless(community.default_tool is None)
def __init__(self, terms, *interfaces, **kwargs): """Initialize the vocabulary given a list of terms. The vocabulary keeps a reference to the list of terms passed in; it should never be modified while the vocabulary is used. One or more interfaces may also be provided so that alternate widgets may be bound without subclassing. By default, ValueErrors are thrown if duplicate values or tokens are passed in. If you want to swallow these exceptions, pass in swallow_duplicates=True. In this case, the values will override themselves. """ self.by_value = {} self.by_token = {} self._terms = terms for term in self._terms: swallow_dupes = kwargs.get('swallow_duplicates', False) if not swallow_dupes: if term.value in self.by_value: raise ValueError( 'term values must be unique: %s' % repr(term.value)) if term.token in self.by_token: raise ValueError( 'term tokens must be unique: %s' % repr(term.token)) self.by_value[term.value] = term self.by_token[term.token] = term if interfaces: directlyProvides(self, *interfaces)
def startTLS(self, contextFactory, normal=True): """ @see: L{ITLSTransport.startTLS} """ # Figure out which direction the SSL goes in. If normal is True, # we'll go in the direction indicated by the subclass. Otherwise, # we'll go the other way (client = not normal ^ _tlsClientDefault, # in other words). if normal: client = self._tlsClientDefault else: client = not self._tlsClientDefault tlsFactory = TLSMemoryBIOFactory(contextFactory, client, None) tlsProtocol = TLSMemoryBIOProtocol(tlsFactory, self.protocol, False) self.protocol = tlsProtocol self.getHandle = tlsProtocol.getHandle self.getPeerCertificate = tlsProtocol.getPeerCertificate # Mark the transport as secure. directlyProvides(self, interfaces.ISSLTransport) # Remember we did this so that write and writeSequence can send the # data to the right place. self._tls = True # Hook it up self.protocol.makeConnection(_BypassTLS(self))
def test_call_view_registered_specific_success(self): from zope.interface import Interface from zope.interface import directlyProvides class IContext(Interface): pass from pyramid.interfaces import IRequest from pyramid.interfaces import IViewClassifier context = DummyContext() directlyProvides(context, IContext) self._registerTraverserFactory(context) self._registerRootFactory(context) response = DummyResponse() response.app_iter = ['Hello world'] view = DummyView(response) environ = self._makeEnviron() self._registerView(view, '', IViewClassifier, IRequest, IContext) router = self._makeOne() start_response = DummyStartResponse() result = router(environ, start_response) self.assertEqual(result, ['Hello world']) self.assertEqual(start_response.headers, ()) self.assertEqual(start_response.status, '200 OK') request = view.request self.assertEqual(request.view_name, '') self.assertEqual(request.subpath, []) self.assertEqual(request.context, context) self.assertEqual(request.root, context)
def test_call_view_exception_propagating(self): from zope.interface import Interface from zope.interface import directlyProvides class IContext(Interface): pass from pyramid.interfaces import IRequest from pyramid.interfaces import IViewClassifier from pyramid.interfaces import IRequestFactory def rfactory(environ): return request self.registry.registerUtility(rfactory, IRequestFactory) from pyramid.request import Request request = Request.blank('/') context = DummyContext() directlyProvides(context, IContext) self._registerTraverserFactory(context, subpath=['']) response = DummyResponse() view = DummyView(response, raise_exception=RuntimeError) environ = self._makeEnviron() self._registerView(view, '', IViewClassifier, IRequest, IContext) router = self._makeOne() start_response = DummyStartResponse() self.assertRaises(RuntimeError, router, environ, start_response) # ``exception`` must be attached to request even if a suitable # exception view cannot be found self.assertEqual(request.exception.__class__, RuntimeError)
def test_including_replace_image_fulldomain(self): import simplejson from karl.content.interfaces import IImage from zope.interface import directlyProvides context = testing.DummyModel() image = context["boo.jpg"] = testing.DummyModel() image.title = "Boo" directlyProvides(image, IImage) # It must also work, when the image url is # a full domain. This happens on IE. # XXX The server should _not_ check the domain # at all, simply use the path. # XXX For a reason unknown, this test passes even # if the traverse the full domain instead of just the # path... while, the same thing fails in "real life" on IE. # So, this test probably does not test what it should... request = testing.DummyRequest( params={"include_image_url": "http://lcd.tv:9876/boo.jpg/thumb", "source": "myrecent"} ) response = self._call_fut(context, request) self.assertEqual(response.status, "200 OK") self.assertEqual( self.dummy_get_images_batch.called, (context, request, {"community": None, "batch_start": 0, "batch_size": 12, "creator": None}), ) data = simplejson.loads(response.body) self.assertEqual(data["images_info"], {"totalRecords": 6, "start": 0, "records": ["Boo", "foo", "bar"]})
def makeConnection(self, transport): directlyProvides(self, providedBy(transport)) Protocol.makeConnection(self, transport) if not self.method in self.allowedMethods: self.sendHeaders({'status': '405 Method Not Supported','allow': ', '.join(self.allowedMethods)}) self.transport.write("\r\n") self.transport.loseConnection() return elif self.method == 'OPTIONS': self.sendHeaders() self.transport.write("") self.transport.loseConnection() return if not self.writeOnly: if self.session in self.factory.sessions: self.wrappedProtocol = self.factory.sessions[self.session] else: self.wrappedProtocol = RelayProtocol(self.factory, self.factory.wrappedFactory.buildProtocol(self.transport.addr), self.session, self) if self.wrappedProtocol.attached: self.wrappedProtocol = None self.failConnect() else: if not self.prepConnection(): self.disconnecting = False self.wrappedProtocol.makeConnection(self) else: if self.session in self.factory.sessions: self.wrappedProtocol = self.factory.sessions[self.session] else: self.sendHeaders({'status': '404 Not Found'}) self.transport.write("\r\n") self.transport.loseConnection()
def test_including_replace_image(self): ## if we are replacing, the passed-in image url ## is added as a fake 1th element. import simplejson from karl.content.interfaces import IImage from zope.interface import directlyProvides context = testing.DummyModel() image = context["boo.jpg"] = testing.DummyModel() image.title = "Boo" directlyProvides(image, IImage) request = testing.DummyRequest(params={"include_image_url": "/boo.jpg", "source": "myrecent"}) response = self._call_fut(context, request) self.assertEqual(response.status, "200 OK") self.assertEqual( self.dummy_get_images_batch.called, (context, request, {"community": None, "batch_start": 0, "batch_size": 12, "creator": None}), ) data = simplejson.loads(response.body) self.assertEqual(data["images_info"], {"totalRecords": 6, "start": 0, "records": ["Boo", "foo", "bar"]}) # if we don't ask for the 0th index: it's not # added, but the sizes and indexes are aligned. request = testing.DummyRequest(params={"include_image_url": "/boo.jpg", "source": "myrecent", "start": "1"}) response = self._call_fut(context, request) self.assertEqual(response.status, "200 OK") self.assertEqual( self.dummy_get_images_batch.called, (context, request, {"community": None, "batch_start": 0, "batch_size": 12, "creator": None}), ) data = simplejson.loads(response.body) self.assertEqual(data["images_info"], {"totalRecords": 6, "start": 1, "records": ["foo", "bar"]})
def test_widget_addform_url_on_addform(self): from plone.app.widgets.dx import AjaxSelectWidget widget = AjaxSelectWidget(self.request) form = Mock() from zope.interface import directlyProvides from z3c.form.interfaces import IAddForm directlyProvides(form, IAddForm) form.request = {'URL': 'http://addform_url'} widget.form = form self.assertEqual( { 'name': None, 'value': u'', 'pattern': 'select2', 'pattern_options': {'separator': ';'}, }, widget._base_args(), ) widget.vocabulary = 'vocabulary1' self.assertEqual( { 'name': None, 'value': u'', 'pattern': 'select2', 'pattern_options': { 'separator': ';', 'vocabularyUrl': 'http://addform_url/@@getVocabulary?name=vocabulary1'} }, widget._base_args(), )
def create_components_registry(parent=None, name='', bases=()): if parent is None: parent = contextualSiteManager() registry = BaseComponents(parent, name, bases) directlyProvides(registry, IComponents) provideUtility(registry, provides=IComponents, name=name) return registry
def setUp(self): self.app = self.layer['app'] self.portal = self.layer['portal'] self.request = self.layer['request'] directlyProvides(self.request, IBrowserLayer) office = create_ombudsoffice(self, 'office') self.claim = api.content.create(office, 'Claim', 'claim')
def test_workflow_transition_from_custom(self): registerDummyRenderer('templates/edit_acl.pt') from repoze.workflow.testing import DummyWorkflow from zope.interface import Interface from zope.interface import directlyProvides workflow = DummyWorkflow() def state_info(context, request): return [{'name': 'foo', 'current': True, 'transitions': True}, {'name': 'bar', 'current': False, 'transitions': True}] workflow.state_info = state_info def get_dummy_workflow(*args, **kw): return workflow import karl.views.acl old_f = karl.views.acl.get_context_workflow karl.views.acl.get_context_workflow = get_dummy_workflow try: context = testing.DummyModel() context.state = 'foo' context.__custom_acl__ = [] directlyProvides(Interface) request = testing.DummyRequest() request.POST['form.security_state'] = 1 request.POST['security_state'] = 'bar' self._callFUT(context, request) self.assertEqual(workflow.transitioned[0]['to_state'], 'bar') self.assertEqual(workflow.resetted, [context,]) self.failIf(hasattr(context, '__custom_acl__')) finally: karl.views.acl.get_context_workflow = old_f
def testInitializedAndEditedEvent(self): component.provideHandler(created_handler, (IObject1, IObjectCreatedEvent,)) component.provideHandler(initialized_handler, (IObject1, IObjectInitializedEvent,)) component.provideHandler(edited_handler, (IObject1, IObjectEditedEvent,)) ob = Dummy('dummy') directlyProvides(ob, IObject1) self.folder._setObject('dummy', ob) ob = self.folder.dummy ob._initializedCaught = False ob._editedCaught = False # Simulate first edit ob._at_creation_flag = True ob.processForm(REQUEST=TestRequest()) self.assertEqual(True, ob._initializedCaught) self.assertEqual(False, ob._editedCaught) # Simulate subsequent edit ob.processForm(REQUEST=TestRequest()) self.assertEqual(True, ob._editedCaught) sm = component.getSiteManager() sm.unregisterHandler(created_handler, (IObject1, IObjectCreatedEvent,)) sm.unregisterHandler(initialized_handler, (IObject1, IObjectCreatedEvent,)) sm.unregisterHandler(edited_handler, (IObject1, IObjectCreatedEvent,))
def test_community_search(self): context = testing.DummyModel() context.title = 'Citizens' context.catalog = {} context['profiles'] = profiles = testing.DummyModel() profiles['tweedle dee'] = testing.DummyModel(title='Tweedle Dee') from webob.multidict import MultiDict from karl.models.interfaces import ICommunity from zope.interface import directlyProvides directlyProvides(context, ICommunity) request = testing.DummyRequest(params=MultiDict({'body':'yo'})) from zope.interface import Interface from karl.models.interfaces import ICatalogSearch from karl.views.interfaces import IAdvancedSearchResultsDisplay from repoze.lemonade.testing import registerContentFactory registerContentFactory(DummyContent, IDummyContent) karltesting.registerAdapter(DummySearch, (Interface), ICatalogSearch) karltesting.registerAdapter(DummySearchResultsDisplay, (Interface, Interface), IAdvancedSearchResultsDisplay) result = self._callFUT(context, request) self.assertEqual(result['community'], 'Citizens') self.assertEqual(result['terms'], ['yo']) self.assertEqual(len(result['results']), 1)
def test_cutpaste_duplicated_id_object(self): root = self.getRootFolder() # Create a principal Folder root['pf'] = PrincipalFolder() pf = root['pf'] # Create a principal with p1 as login principal = Principal('p1') principal.login = '******' directlyProvides(principal, IInternalPrincipal) pf['p1'] = principal transaction.commit() self.assertEqual(len(pf.keys()), 1) #raise str([x for x in pf.keys()]) response = self.publish('/pf/@@contents.html', basic='mgr:mgrpw', form={'ids': [u'p1'], 'container_cut_button': u'Cut'}) self.assertEqual(response.getStatus(), 302) # Try to paste the file try: response = self.publish('/pf/@@contents.html', basic='mgr:mgrpw', form={'container_paste_button': ''}) except UserError, e: self.assertEqual( str(e), "The given name(s) [u'p1'] is / are already being used")
def test_no_content(self): from repoze.lemonade.content import IContent from zope.interface import directlyProvides context = self.context directlyProvides(context, IContent) textrepr = self._callFUT(context, 'default') self.assertEqual(textrepr, 'default')
def publishTraverse(self, request, name): request.survey = self.context utils.setLanguage(request, self.context, self.context.language) if name not in ["view", "index_html"] and \ not self.hasValidSession(request): request.response.redirect( aq_parent(aq_parent(self.context)).absolute_url(), lock=True) return self.context if name not in self.phases: return super(SurveyPublishTraverser, self)\ .publishTraverse(request, name) # Decorate the request with the right skin layer and add to the aq path directlyProvides(request, self.phases[name], *directlyProvidedBy(request)) self.context = PathGhost(name).__of__(self.context) session = SessionManager.session tree_id = find_sql_context(session.id, request['TraversalRequestNameStack']) if tree_id is not None: return build_tree_aq_chain(self.context, tree_id) # No SQL based traversal possible, return the existing context with the # new skin layer applied return self.context
def setUp(self): self.portal = self.layer['portal'] setRoles(self.portal, TEST_USER_ID, ['Manager']) workflowTool = getToolByName(self.portal, 'portal_workflow') workflowTool.setDefaultChain('simple_publication_workflow') workflowTool.updateRoleMappings() f1 = api.content.create(self.portal, 'Folder', 'f1', title=u'Folder 1') directlyProvides(f1, IMicroblogContext) f1.reindexObject() f2 = api.content.create(self.portal, 'Folder', 'f2', title=u'Folder 2') directlyProvides(f2, IMicroblogContext) f2.reindexObject() api.content.transition(f2, 'publish') self.assertEqual(api.content.get_state(f1), 'private') self.assertEqual(api.content.get_state(f2), 'published') tool = queryUtility(IMicroblogTool) self.su1 = su1 = StatusUpdate('test #foo', f1) tool.add(su1) self.su2 = su2 = StatusUpdate('test #foo', f2) tool.add(su2) # the tool is queued tool.flush_queue() # set up new user api.user.create('*****@*****.**', username='******', password='******')
def testDefaultSkin(self): request = TestRequest() self.assertEqual(zapi.queryMultiAdapter((ob, request), name='test'), None) xmlconfig(StringIO(template % ( ''' <browser:layer name="zmi" /> <browser:skin name="zmi" layers="zmi" /> <browser:defaultSkin name="zmi" /> <browser:page name="test" class="zope.app.component.tests.views.VZMI" layer="zmi" for="zope.app.component.tests.views.IC" permission="zope.Public" attribute="index" /> <browser:page name="test" class="zope.app.component.tests.views.V1" for="zope.app.component.tests.views.IC" permission="zope.Public" attribute="index" /> ''' ))) # Simulate Zope Publication behavior in beforeTraversal() adapters = zapi.getSiteManager().adapters skin = adapters.lookup((providedBy(request),), IDefaultSkin, '') directlyProvides(request, skin) v = zapi.queryMultiAdapter((ob, request), name='test') self.assert_(issubclass(v.__class__, VZMI))
def test_statusupdate_context_roundtrip(self): """Unittests fake uuids. Integration test with real uuids.""" self.portal.invokeFactory('Folder', 'f1', title=u"Folder 1") f1 = self.portal['f1'] directlyProvides(f1, IMicroblogContext) update = StatusUpdate('test', context=f1) self.assertEquals(update.context, f1)
def test_handle_submit_valid_nofile_withremove(self): from repoze.bfg.formish import ValidationError from karl.models.interfaces import ISite from zope.interface import directlyProvides from schemaish.type import File as SchemaFile from karl.models.interfaces import IObjectModifiedEvent from karl.content.interfaces import ICommunityFile from repoze.lemonade.interfaces import IContentFactory self._register() context = DummyFile(title='oldtitle') context.__name__ = None context.__parent__ = None context.mimetype = 'old/type' context.filename = 'old_name' context.stream = 'old' context.sessions = DummySessions() context.catalog = DummyCatalog() directlyProvides(context, ISite) converted = { 'title': 'new title', 'file': SchemaFile(None, None, None, metadata={'remove':True}), 'security_state': 'public', 'tags': ['thetesttag'], } testing.registerAdapter(lambda *arg: DummyCommunityFile, (ICommunityFile,), IContentFactory) testing.registerDummySecurityPolicy('testeditor') request = self._makeRequest() controller = self._makeOne(context, request) self.assertRaises(ValidationError, controller.handle_submit, converted)
def test_handle_submit_attachment_is_None(self): """ There seems to be some set of circumstances under which formish will return a None as a value in the attachments sequence. """ from karl.models.interfaces import IObjectModifiedEvent from zope.interface import Interface from karl.models.interfaces import ITagQuery from karl.content.interfaces import IBlogEntry from repoze.lemonade.testing import registerContentFactory from karl.testing import DummyCatalog karl.testing.registerAdapter(DummyTagQuery, (Interface, Interface), ITagQuery) self._registerDummyWorkflow() context = DummyBlogEntry() context.sessions = DummySessions() context.__name__ ='ablogentry' context.catalog = DummyCatalog() context['attachments'] = testing.DummyModel() from karl.models.interfaces import ISite from zope.interface import directlyProvides directlyProvides(context, ISite) converted = {'title':'foo', 'text':'text', 'security_state':'public', 'tags':'thetesttag', 'attachments':[None], } registerContentFactory(DummyBlogEntry, IBlogEntry) L = karl.testing.registerEventListener( (Interface, IObjectModifiedEvent)) karl.testing.registerDummySecurityPolicy('testeditor') request = self._makeRequest() controller = self._makeOne(context, request) response = controller.handle_submit(converted) self.assertEqual(response.location, 'http://example.com/ablogentry/') self.assertEqual(len(L), 2) self.assertEqual(context.title, 'foo') self.assertEqual(context.text, 'text') self.assertEqual(context.modified_by, 'testeditor')
def test_tabs_requestcontext_iscommunity(self): from karl.models.interfaces import ICommunity from karl.models.interfaces import IToolFactory from repoze.lemonade.testing import registerListItem from zope.interface import directlyProvides tool_factory = DummyToolFactory() registerListItem(IToolFactory, tool_factory, 'one', title='One') context = self._makeCommunity() directlyProvides(context, ICommunity) request = testing.DummyRequest() request.context = context adapter = self._makeOne(context, request) tabs = adapter.tabs self.assertEqual(len(tabs), 2) self.assertEqual(tabs[0], {'url': 'http://example.com/view.html', 'css_class': 'curr', 'name': 'OVERVIEW'} ) self.assertEqual(tabs[1], {'url': 'http://example.com/tab', 'css_class': '', 'name': 'ONE'} )
def test_get_info_alpha(self): request = testing.DummyRequest() context = testing.DummyModel() context.alpha = {'A':1} from zope.interface import directlyProvides directlyProvides(context, DummyInterface) adapter = self._makeOne(context) letters = adapter.get_info(request) self.assertEqual(len(letters), 27) self.assertEqual(letters[0]['name'], 'A') self.assertEqual(letters[0]['css_class'], 'notcurrent') self.assertEqual(letters[0]['href'], 'http://example.com?titlestartswith=A') self.assertEqual(letters[0]['is_current'], False) self.assertEqual(letters[1]['name'], 'B') self.assertEqual(letters[1]['css_class'], 'notcurrent') self.assertEqual(letters[1]['href'], None) self.assertEqual(letters[1]['is_current'], False) self.assertEqual(letters[26]['name'], 'Any') self.assertEqual(letters[26]['css_class'], 'current') self.assertEqual(letters[26]['href'], None) self.assertEqual(letters[26]['is_current'], True)
def test_ObjectSpecification(self): c = C() directlyProvides(c, I4) self.assertEqual([i.getName() for i in providedBy(c)], ['I4', 'I31', 'I1', 'I2']) self.assertEqual([i.getName() for i in providedBy(c).flattened()], ['I4', 'I31', 'I3', 'I1', 'I2', 'Interface']) self.failUnless(I1 in providedBy(c)) self.failIf(I3 in providedBy(c)) self.failUnless(providedBy(c).extends(I3)) self.failUnless(providedBy(c).extends(I31)) self.failIf(providedBy(c).extends(I5)) class COnly(A, B): pass classImplementsOnly(COnly, I31) class D(COnly): pass classImplements(D, I5) classImplements(D, I5) c = D() directlyProvides(c, I4) self.assertEqual([i.getName() for i in providedBy(c)], ['I4', 'I5', 'I31']) self.assertEqual([i.getName() for i in providedBy(c).flattened()], ['I4', 'I5', 'I31', 'I3', 'Interface']) self.failIf(I1 in providedBy(c)) self.failIf(I3 in providedBy(c)) self.failUnless(providedBy(c).extends(I3)) self.failIf(providedBy(c).extends(I1)) self.failUnless(providedBy(c).extends(I31)) self.failUnless(providedBy(c).extends(I5)) class COnly(A, B): __implemented__ = I31 class D(COnly): pass classImplements(D, I5) classImplements(D, I5) c = D() directlyProvides(c, I4) self.assertEqual([i.getName() for i in providedBy(c)], ['I4', 'I5', 'I31']) self.assertEqual([i.getName() for i in providedBy(c).flattened()], ['I4', 'I5', 'I31', 'I3', 'Interface']) self.failIf(I1 in providedBy(c)) self.failIf(I3 in providedBy(c)) self.failUnless(providedBy(c).extends(I3)) self.failIf(providedBy(c).extends(I1)) self.failUnless(providedBy(c).extends(I31)) self.failUnless(providedBy(c).extends(I5))
def __call__(self, context, request): if request.get('ploneintranet.layout.app.enabled'): return # manipulate the same request only once, and only for one app request.set('ploneintranet.layout.app.enabled', True) app_layers = list(context.app_layers) # do not undo themeswitching policy = theming_policy(request) if ISwitchableThemingPolicy.providedBy(policy) \ and policy.isFallbackActive(): # only applies to Barceloneta switcher = policy.getSwitcherSettings() # respect themeswitching blacklist remove_layers = [ resolveDottedName(x) for x in switcher.browserlayer_filterlist ] # enable only non-blacklisted IAppLayers app_layers = [x for x in app_layers if x not in remove_layers] active_layers = app_layers + get_layers(request) directlyProvides(request, *active_layers)
def test_getMessageTarget_report_valid_report(self): from zope.interface import directlyProvides from karl.models.interfaces import IPeopleDirectory context = self._makeRoot() pd = context['people'] = self._makeContext() directlyProvides(pd, IPeopleDirectory) section = pd['section'] = self._makeContext() section['extant'] = self._makeContext() mailin = self._makeOne(context) message = DummyMessage() message.to = ('*****@*****.**', ) info = mailin.getMessageTargets(message) self.failIf(info.get('error'), info) targets = info['targets'] self.assertEqual(len(targets), 1) info = targets[0] self.assertEqual(info['report'], 'section+extant') self.assertEqual(info['community'], None) self.assertEqual(info['tool'], None) self.failIf(info.get('in_reply_to'), info)
def testHeadingLinkRootless(self): """ See that heading link points to a global sitemap if no root item is set. """ directlyProvides(self.portal.folder2, INavigationRoot) view = self.renderer(self.portal.folder2, assignment=navigation.Assignment(topLevel=0)) link = view.heading_link_target() # The root is not given -> should render the sitemap in the navigation root self.assertEqual(link, 'http://nohost/plone/folder2/sitemap') # Even if the assignment contains no topLevel options and no self.root # one should get link to the navigation root sitemap view = self.renderer(self.portal.folder2.doc21, assignment=navigation.Assignment()) link = view.heading_link_target() # The root is not given -> should render the sitemap in the navigation root self.assertEqual(link, 'http://nohost/plone/folder2/sitemap') view = self.renderer(self.portal.folder1, assignment=navigation.Assignment(topLevel=0)) link = view.heading_link_target() # The root is not given -> should render the sitemap in the navigation root self.assertEqual(link, 'http://nohost/plone/sitemap')
def transmute(table, annotation=None, __module__=None, **kw): # if no module given, use the callers module if __module__ is None: import sys __module__ = sys._getframe(1).f_globals['__name__'] z3iface = SQLAlchemySchemaTranslator().translate(table, annotation, __module__, **kw) # mark the interface itself as being model driven interface.directlyProvides(z3iface, IIModelInterface) # provide a named annotation adapter to go from the iface back to the annotation if annotation is not None: name = "%s.%s" % (z3iface.__module__, z3iface.__name__) component.provideAdapter(annotation, adapts=(IIModelInterface, ), provides=IModelDescriptor, name=name) return z3iface
def test_show_workflow_custom_acl(self): from repoze.workflow.testing import DummyWorkflow from zope.interface import Interface from zope.interface import directlyProvides workflow = DummyWorkflow() def state_info(context, request): return [{ 'name': 'foo', 'current': True, 'transitions': True }, { 'name': 'bar', 'current': False, 'transitions': True }] workflow.state_info = state_info def get_dummy_workflow(*args, **kw): return workflow import karl.views.acl old_f = karl.views.acl.get_context_workflow karl.views.acl.get_context_workflow = get_dummy_workflow try: context = testing.DummyModel() context.state = 'foo' context.__custom_acl__ = [] directlyProvides(Interface) request = testing.DummyRequest() renderer = karl.testing.registerDummyRenderer( 'templates/edit_acl.pt') self._callFUT(context, request) self.assertEqual(renderer.security_state, 'CUSTOM') self.assertEqual(renderer.security_states, ['CUSTOM', 'foo', 'bar']) finally: karl.views.acl.get_context_workflow = old_f
def _handleRawStream(self): """ Switch the current connection to be a "hijacked" aka raw stream: one where bytes just get naively proxied back and forth. """ def loseWriteConnectionReason(reason): # discard the reason, for compatibility with readConnectionLost self.transport.loseWriteConnection() self.father.transport.readConnectionLost = loseWriteConnectionReason directlyProvides(self.father.transport, IHalfCloseableProtocol) self.http = False self.father.transport.write( "HTTP/1.1 200 OK\r\n" "Content-Type: application/vnd.docker.raw-stream\r\n" "\r\n") def stdinHandler(data): self.transport.write(data) self.father.transport.protocol.dataReceived = stdinHandler self.setStreamingMode(True)
def _makeCommunity(self): from zope.interface import directlyProvides from karl.models.interfaces import ICommunity community = testing.DummyModel(title='thetitle') catalog = karltesting.DummyCatalog({ 1: '/profiles/phred', 2: '/profiles/bharney', 3: '/profiles/wylma', }) phred = testing.DummyModel(__name__='phred') bharney = testing.DummyModel(__name__='bharney') wylma = testing.DummyModel(__name__='wylma') karltesting.registerModels({ '/profiles/phred': phred, '/profiles/bharney': bharney, '/profiles/wylma': wylma, }) community.catalog = catalog community.member_names = set(['phred', 'bharney', 'wylma']) community.moderator_names = set(['bharney']) directlyProvides(community, ICommunity) return community
def test_wo_conflicts(self): from zope.interface import directlyProvides from karl.models.interfaces import IPeopleReportMailingList ALIASES = { 'not_people': '/somewhere/else', } site = testing.DummyModel(list_aliases=ALIASES) peopledir = site['people'] = testing.DummyModel() section = peopledir['section'] = testing.DummyModel() report1 = section['report1'] = testing.DummyModel() ml1 = report1['mailinglist'] = testing.DummyModel(short_address='one') directlyProvides(ml1, IPeopleReportMailingList) report2 = section['report2'] = testing.DummyModel() report3 = section['report3'] = testing.DummyModel() ml3 = report3['mailinglist'] = testing.DummyModel( short_address='three') directlyProvides(ml3, IPeopleReportMailingList) self._callFUT(peopledir) self.assertEqual(len(site.list_aliases), 3) self.assertEqual(site.list_aliases['not_people'], '/somewhere/else') self.assertEqual(site.list_aliases['one'], '/people/section/report1') self.assertEqual(site.list_aliases['three'], '/people/section/report3')
def test_render_sidebar_w_acquired_adapter(self): from zope.interface import directlyProvides from zope.interface import Interface from karl.models.interfaces import ICommunity from karl.views.interfaces import ISidebar parent = testing.DummyModel() directlyProvides(parent, ICommunity) context = parent['child'] = testing.DummyModel() _called_with = [] def _factory(context, request): def _render(api): _called_with.append(api) return 'SIDEBAR' return _render karltesting.registerAdapter(_factory, (ICommunity, Interface), ISidebar) request = testing.DummyRequest() api = self._makeOne(context, request) self.assertEqual(api.render_sidebar(), 'SIDEBAR')
def test_lookup_all(self): filter_all = dict(callable="outpost.filterinc.replacestr", apply_to="file", path="index\.html", content_type="text/*", settings={ "str": "<body>", "new": "<body>Updated!" }, name="Filter example") fc = filtermanager.FilterConf.fromDict(filter_all) response = testing.DummyRequest().response response.content_type = "text/html" directlyProvides(response, filtermanager.IFileRequest) request = testing.DummyRequest() request.url = "http://localhost/files/index.html" request.registry.settings = {"filter": (fc, )} filter = [ f for f in filtermanager.lookupFilter("post", response, request, request.url) ] self.assertTrue(len(filter) == 1)
def testDefaultSkin(self): request = TestRequest() self.assertEqual( component.queryMultiAdapter((ob, request), name='test'), None) XMLConfig('meta.zcml', zope.app.component)() xmlconfig( StringIO(template % (''' <interface interface=" zope.app.publisher.browser.tests.test_directives.ITestSkin" type="zope.publisher.interfaces.browser.IBrowserSkinType" name="Test Skin" /> <browser:defaultSkin name="Test Skin" /> <browser:page name="test" class="zope.app.component.tests.views.VZMI" layer=" zope.app.publisher.browser.tests.test_directives.ITestLayer" for="zope.app.component.tests.views.IC" permission="zope.Public" attribute="index" /> <browser:page name="test" class="zope.app.component.tests.views.V1" for="zope.app.component.tests.views.IC" permission="zope.Public" attribute="index" /> '''))) # Simulate Zope Publication behavior in beforeTraversal() adapters = component.getSiteManager().adapters skin = adapters.lookup((providedBy(request), ), IDefaultSkin, '') directlyProvides(request, skin) v = component.queryMultiAdapter((ob, request), name='test') self.assert_(issubclass(v.__class__, VZMI))
def setUp(self): """Custom shared utility setup for tests.""" self.portal = self.layer['portal'] self.request = self.layer['request'] directlyProvides(self.request, IListUsersLayer) # create some dummy content self.createUser('user1', properties={ 'fullname': 'User 1', 'description': 'User 1 description', 'email': '*****@*****.**', 'location': 'Jupiter', }, groups=['Administrators']) self.createUser('user2', properties={ 'fullname': 'User 2', 'description': 'User 2 description', 'email': '*****@*****.**', 'location': 'Moon', }, groups=['Reviewers']) self.createUser('user3', properties={ 'fullname': 'User 3', 'description': 'User 3 description', 'email': '*****@*****.**', 'location': 'Saturn', }, groups=['Administrators', 'Reviewers']) self.createUser('user4', properties={ 'fullname': 'User 4', 'description': 'User 4 description', 'email': '*****@*****.**', 'location': 'Pluto', }, groups=['Site Administrators'])
def test_it(self): class DummyModel(testing.DummyModel): def _p_deactivate(self): self.deactivated = True from repoze.folder.interfaces import IFolder from zope.interface import directlyProvides request = testing.DummyRequest() context2 = DummyModel() context2.__acl__ = ['Allow', 'fred', ('read', )] context2.security_state = 'fred-ish' context = DummyModel() context['context2'] = context2 directlyProvides(context, IFolder) renderer = karl.testing.registerDummyRenderer('templates/acl_tree.pt') self._callFUT(context, request) self.assertEqual(len(renderer.acls), 2) context_acl = renderer.acls[0] self.assertEqual( context_acl, { 'path': '/', 'acl': None, 'name': '/', 'offset': 0, 'url': 'http://example.com/', 'security_state': None }) context2_acl = renderer.acls[1] self.assertEqual( context2_acl, { 'path': '/context2', 'acl': ['Allow', 'fred', ('read', )], 'name': 'context2', 'offset': 1, 'url': 'http://example.com/context2/', 'security_state': 'fred-ish' }) self.assertEqual(context.deactivated, True) self.assertEqual(context2.deactivated, True)
def test_call_request_has_finished_callbacks_when_view_succeeds(self): from zope.interface import Interface from zope.interface import directlyProvides class IContext(Interface): pass from pyramid.interfaces import IRequest from pyramid.interfaces import IViewClassifier context = DummyContext() directlyProvides(context, IContext) self._registerTraverserFactory(context, subpath=['']) response = DummyResponse('200 OK') def view(context, request): def callback(request): request.environ['called_back'] = True request.finished_callbacks = [callback] return response environ = self._makeEnviron() self._registerView(view, '', IViewClassifier, IRequest, IContext) router = self._makeOne() start_response = DummyStartResponse() router(environ, start_response) self.assertEqual(environ['called_back'], True)
def test_it_interface(self): baz = DummyContext() bar = DummyContext(baz) foo = DummyContext(bar) root = DummyContext(foo) root.__parent__ = None root.__name__ = 'root' foo.__parent__ = root foo.__name__ = 'foo' bar.__parent__ = foo bar.__name__ = 'bar' baz.__parent__ = bar baz.__name__ = 'baz' from zope.interface import directlyProvides from zope.interface import Interface class IFoo(Interface): pass directlyProvides(root, IFoo) result = self._callFUT(baz, IFoo) self.assertEqual(result.__name__, 'root')
def apply(self, contentNode): if not IAttributeAnnotatable.providedBy(self.context): directly = interface.directlyProvidedBy(self.context) interface.directlyProvides(self.context, directly + IAttributeAnnotatable) annotations = IAnnotations(self.context) metadata = annotations.get(self.ANNO_KEY, None) if metadata is None: metadata = PersistentDict() annotations[self.ANNO_KEY] = metadata for dl_el in contentNode.childNodes: if dl_el.nodeName != 'dl': continue term = None for el in dl_el.childNodes: if el.nodeName == 'dt': term = self._extractText(el) elif el.nodeName == 'dd': definition = self._extractText(el) metadata[term] = definition
def test_handle_submit(self): from schemaish.type import File as SchemaFile from karl.models.interfaces import IObjectModifiedEvent from zope.interface import Interface from karl.models.interfaces import ITagQuery from karl.content.interfaces import IBlogEntry from repoze.lemonade.testing import registerContentFactory from karl.testing import DummyCatalog karl.testing.registerAdapter(DummyTagQuery, (Interface, Interface), ITagQuery) self._registerDummyWorkflow() context = DummyBlogEntry() context.sessions = DummySessions() context.__name__ = 'ablogentry' context.catalog = DummyCatalog() context['attachments'] = testing.DummyModel() from karl.models.interfaces import ISite from zope.interface import directlyProvides directlyProvides(context, ISite) converted = { 'title': 'foo', 'text': 'text', 'security_state': 'public', 'tags': 'thetesttag', 'attachments': [SchemaFile(None, None, None)], } registerContentFactory(DummyBlogEntry, IBlogEntry) L = karl.testing.registerEventListener( (Interface, IObjectModifiedEvent)) karl.testing.registerDummySecurityPolicy('testeditor') request = self._makeRequest() controller = self._makeOne(context, request) response = controller.handle_submit(converted) self.assertEqual(response.location, 'http://example.com/ablogentry/') self.assertEqual(len(L), 2) self.assertEqual(context.title, 'foo') self.assertEqual(context.text, 'text') self.assertEqual(context.modified_by, 'testeditor')
def test_show_members(self): from zope.interface import Interface from karl.models.interfaces import ICatalogSearch context = testing.DummyModel() context.member_names = ['a'] context.moderator_names = ['b'] profiles = testing.DummyModel() profiles['a'] = karltesting.DummyProfile() profiles['b'] = karltesting.DummyProfile() context['profiles'] = profiles d = {1: profiles['a'], 2: profiles['b']} searchkw = {} def resolver(docid): return d.get(docid) def dummy_catalog_search(context): def search(**kw): searchkw.update(kw) return 2, [1, 2], resolver return search karltesting.registerAdapter(dummy_catalog_search, (Interface), ICatalogSearch) from karl.models.interfaces import ICommunity from zope.interface import directlyProvides directlyProvides(context, ICommunity) request = testing.DummyRequest() request.view_name = 'list_view.html' response = self._callFUT(context, request) actions = [('Manage Members', 'manage.html'), ('Add Existing', 'add_existing.html'), ('Invite New', 'invite_new.html')] self.assertEqual(response['actions'], actions) self.assertEqual(len(response['members']), 2) self.assertEqual(len(response['moderators']), 1) self.assertEqual(response['hide_pictures'], True) self.assertEqual(len(response['submenu']), 2) self.assertEqual(response['submenu'][0]['make_link'], True) self.assertEqual(response['submenu'][1]['make_link'], False) self.assertEqual(searchkw['sort_index'], 'lastfirst')
def _loginSucceeded(self, avatar, request): """ Callback for successful login. @param avatar: A tuple of the form (interface, avatar) as returned by your realm. @param request: L{IRequest} that encapsulates this auth attempt. @return: the IResource in C{self.wrappedResource} """ request.avatarInterface, request.avatar = avatar directlyProvides(request, IAuthenticatedRequest) def _addAuthenticateHeaders(request, response): """ A response filter that adds www-authenticate headers to an outgoing response if it's code is UNAUTHORIZED (401) and it does not already have them. """ if response.code == responsecode.UNAUTHORIZED: if not response.headers.hasHeader('www-authenticate'): newResp = UnauthorizedResponse(self.credentialFactories, request.remoteAddr) response.headers.setHeader( 'www-authenticate', newResp.headers.getHeader('www-authenticate')) return response _addAuthenticateHeaders.handleErrors = True request.addResponseFilter(_addAuthenticateHeaders) return self.wrappedResource
def test_formLayout(self): # Verify that exactly one of isSingleLineLayout(), isMultiLineLayout() # and isCheckBoxLayout() return True for particular widget. # # If more than one returns True, then that widget may get included # in the form twice. form = LaunchpadFormView(None, None) class FakeWidget: pass widget = FakeWidget() form.widgets = {'widget': widget} # test every combination of the three interfaces: for use_single_line in [False, True]: for use_multi_line in [False, True]: for use_checkbox in [False, True]: provides = [] if use_single_line: provides.append(ISingleLineWidgetLayout) if use_multi_line: provides.append(IMultiLineWidgetLayout) if use_checkbox: provides.append(ICheckBoxWidgetLayout) directlyProvides(widget, *provides) # Now count how many of the is* functions return True: count = 0 if form.isSingleLineLayout('widget'): count += 1 if form.isMultiLineLayout('widget'): count += 1 if form.isCheckBoxLayout('widget'): count += 1 self.assertEqual( count, 1, 'Expected count of 1 for %r. Got %d' % (provides, count))
def setUp(self): import datetime from zope.interface import directlyProvides from karl.content.interfaces import IBlogEntry from karl.models.interfaces import ICommentsFolder cleanUp() karltesting.registerSettings() # Create dummy site skel community = karltesting.DummyCommunity() site = community.__parent__.__parent__ profiles = testing.DummyModel() site["profiles"] = profiles self.profile = profiles["member"] = karltesting.DummyProfile() profiles["creator"] = karltesting.DummyProfile() community["blog"] = testing.DummyModel() community["blog"].__parent__ = community blogentry = testing.DummyModel(text="This is a test") blogentry.created = datetime.datetime(2010, 5, 12, 2, 42) blogentry.creator = 'member' community["blog"]["blogentry"] = blogentry blogentry.__parent__ = community['blog'] blogentry["attachments"] = testing.DummyModel() blogentry["attachments"].__parent__ = blogentry blogentry.title = "Blog Entry" blogentry.docid = 0 directlyProvides(blogentry, IBlogEntry) self.blogentry = blogentry blogentry["comments"] = testing.DummyModel() blogentry["comments"].__parent__ = self.blogentry directlyProvides(blogentry['comments'], ICommentsFolder) self.comment = self._add_comment(blogentry)
def makeConnection(self, transport): """ Connect this wrapper to the given transport and initialize the necessary L{OpenSSL.SSL.Connection} with a memory BIO. """ self._tlsConnection = self.factory._createConnection(self) self._appSendBuffer = [] # Add interfaces provided by the transport we are wrapping: for interface in providedBy(transport): directlyProvides(self, interface) # Intentionally skip ProtocolWrapper.makeConnection - it might call # wrappedProtocol.makeConnection, which we want to make conditional. Protocol.makeConnection(self, transport) self.factory.registerProtocol(self) if self._connectWrapped: # Now that the TLS layer is initialized, notify the application of # the connection. ProtocolWrapper.makeConnection(self, transport) # Now that we ourselves have a transport (initialized by the # ProtocolWrapper.makeConnection call above), kick off the TLS # handshake. # The connection might already be aborted (eg. by a callback during # connection setup), so don't even bother trying to handshake in that # case. if not self._aborted: try: self._tlsConnection.do_handshake() except WantReadError: # This is the expected case - there's no data in the # connection's input buffer yet, so it won't be able to # complete the whole handshake now. If this is the speak-first # side of the connection, then some bytes will be in the send # buffer now; flush them. self._flushSendBIO()
def test_with_tag(self): from zope.interface import directlyProvides from repoze.lemonade.testing import registerContentFactory from karl.models.interfaces import ICommunity root = testing.DummyModel() tags = root.tags = DummyTags() def _getRelated(tag, degree=1, community=None, user=None): assert tag == 'tag1' assert degree == 1 assert community == 'community' assert user is None return ['tag2', 'tag3'] tags.getRelatedTags = _getRelated root.catalog = karltesting.DummyCatalog({1: '/community'}) context = root['community'] = testing.DummyModel() context.title = 'title' karltesting.registerModels({'/community': context}) directlyProvides(context, ICommunity) registerContentFactory(testing.DummyModel, ICommunity) request = testing.DummyRequest() request.subpath = [u'tag1'] result = self._callFUT(context, request) self.assertEqual(result['tag'], u'tag1') self.assertEqual(len(result['entries']), 1) entry = result['entries'][0] self.assertEqual(entry['description'], '') self.assertEqual(entry['title'], 'title') self.assertEqual(entry['href'], 'http://example.com/community/') self.assertEqual(entry['tagusers_count'], '1 person') self.assertEqual(entry['type'], 'Community') self.assertEqual( entry['tagusers_href'], 'http://example.com/community/' 'tagusers.html?tag=tag1&docid=1') self.assertEqual(len(result['related']), 0)
def buy_n_get_m_free(price, n, m): ''' Returns a :class:`checkout.interface.IPricer` which does (a version of) "buy N get M free". For the border-case of wishing to purchase fewer than you're entitled to, we opt for "screw the customer", basically. Alternatively, we could provide a way to update the count to reflect the free items. For example, with "buy 5 get 2 free" if you buy 5 things, you still pay the same as if you bought 6 or 7. ''' if m >= n: raise RuntimeError("Can't buy %d and get %d free." % (n, m)) # here, we implement the IPricer interface (a Functor pattern) not # as a class but as a function directly, to demonstrate # zope.interface's "directlyProvides" functionality and a Python # closure. Note how we satisfy the "description" attribute by # adding it to the method object; that can be done in- or out-side # of the inner method. def buy_n_pricer(count, **kw): groups = count / (n + m) leftover = count % (n + m) free = groups * m paid = (groups * n) if leftover > n: paid = n free = leftover - n else: paid += leftover assert paid + free == count total = paid * price return (None, total) buy_n_pricer.description = 'Buy %d get %d free' % (n, m) directlyProvides(buy_n_pricer, IPricer) return buy_n_pricer
def makeConnection(self, transport): """ Connect this wrapper to the given transport and initialize the necessary L{OpenSSL.SSL.Connection} with a memory BIO. """ tlsContext = self.factory._contextFactory.getContext() self._tlsConnection = Connection(tlsContext, None) if self.factory._isClient: self._tlsConnection.set_connect_state() else: self._tlsConnection.set_accept_state() self._appSendBuffer = [] # Add interfaces provided by the transport we are wrapping: for interface in providedBy(transport): directlyProvides(self, interface) # Intentionally skip ProtocolWrapper.makeConnection - it might call # wrappedProtocol.makeConnection, which we want to make conditional. Protocol.makeConnection(self, transport) self.factory.registerProtocol(self) if self._connectWrapped: # Now that the TLS layer is initialized, notify the application of # the connection. ProtocolWrapper.makeConnection(self, transport) # Now that we ourselves have a transport (initialized by the # ProtocolWrapper.makeConnection call above), kick off the TLS # handshake. try: self._tlsConnection.do_handshake() except WantReadError: # This is the expected case - there's no data in the connection's # input buffer yet, so it won't be able to complete the whole # handshake now. If this is the speak-first side of the # connection, then some bytes will be in the send buffer now; flush # them. self._flushSendBIO()
def test_including_replace_image_fulldomain(self): import simplejson from karl.content.interfaces import IImage from zope.interface import directlyProvides context = testing.DummyModel() image = context['boo.jpg'] = testing.DummyModel() image.title = 'Boo' directlyProvides(image, IImage) # It must also work, when the image url is # a full domain. This happens on IE. # XXX The server should _not_ check the domain # at all, simply use the path. # XXX For a reason unknown, this test passes even # if the traverse the full domain instead of just the # path... while, the same thing fails in "real life" on IE. # So, this test probably does not test what it should... request = testing.DummyRequest( params={ 'include_image_url': 'http://lcd.tv:9876/boo.jpg/thumb', 'source': 'myrecent', }) response = self._call_fut(context, request) self.assertEqual(response.status, '200 OK') self.assertEqual(self.dummy_get_images_batch.called, (context, request, { 'community': None, 'batch_start': 0, 'batch_size': 12, 'creator': None })) data = simplejson.loads(response.body) self.assertEqual(data['images_info'], { 'totalRecords': 6, 'start': 0, 'records': ['Boo', 'foo', 'bar'], })