def testObject_pasteUncommitOnException(self):
        """Ensure that pasted objects aren't commited if an IObjectMovedEvent raises an exception.
        See https://dev.plone.org/ticket/9365
        """
        # register event handler
        provideHandler(failingEventHandler, [IContentish, IObjectMovedEvent])
        try:
            browser = self.getBrowser()
            browser.open(self.folder['source-folder']['doc'].absolute_url())
            browser.getLink('Cut').click()
            browser.open(self.folder['destination-folder'].absolute_url())
            try:
                browser.getLink('Paste').click()
            except HTTPError:
                # a HTTP 500 Server error is currently expected,
                # unless we find a better way to abort the
                # transaction.
                pass

            # test if document is not moved
            self.assertTrue('doc' in self.folder['source-folder'])
            self.assertFalse('doc' in self.folder['destination-folder'])

        finally:
            # unregister event handler
            getGlobalSiteManager().unregisterHandler(
                failingEventHandler, [IContentish, IObjectMovedEvent])
Пример #2
0
def main(argv=None):
    """
    run this as a cron job and execute all
    time based transitions
    """
    db = create_engine('postgres://localhost/bungeni', echo=False)
    component.provideUtility( db, IDatabaseEngine, 'bungeni-db' )
    model.metadata.bind = db
    session = Session()
    component.provideAdapter(
      bungeni.core.workflows.states.WorkflowState,
      (bungeni.core.interfaces.IBungeniContent,))

    component.provideAdapter(
      bungeni.core.workflows.question.QuestionWorkflowAdapter,
      (domain.Question,))

    component.provideAdapter(
      bungeni.core.workflows.states.StateWorkflowInfo,
      (domain.Question,))

    component.provideHandler(
      bungeni.core.workflows.question.workflowTransitionEventDispatcher)
    # add autitor for time based transitions
    #component.provideAdapter(
    #    (bungeni.core.interfaces.IAuditable, bungeni.core.interfaces.IQuestion, ),
    #    (domain.Question, ))
    #component.provideAdapter( audit.objectModified, 
    #(domain.Question, bungeni.core.interfaces.IAuditable, ))
    
    deferAdmissibleQuestions() 
    session.flush()
    session.commit()
Пример #3
0
def load_notification_config(file_name, domain_class):
    """Loads the notification configuration for each document
    """
    notifications_utility = component.getUtility(INotificationsUtility)
    path = capi.get_path_for("notifications")
    file_path = os.path.join(path, file_name)
    notification = capi.schema.validate_file_rng("notifications", file_path)
    item_type = file_name.split(".")[0]
    notifications_utility.register_item_type(domain_class, item_type)
    for notify in notification.iterchildren("notify"):
        roles = capi.schema.qualified_roles(notify.get("roles"))
        for role in roles:
            assert component.queryUtility(IRole, role, None), \
                "Notifications configuration error : " \
                "Invalid role - %s. file: %s, state : %s" % (
                role, file_name)
        if notify.get("onstate"):
            states = notify.get("onstate").split()
            for state in states:
                notifications_utility.set_transition_based_notification(
                        domain_class, state, roles)
        elif notify.get("afterstate"):
            states = notify.get("afterstate").split()
            time = notify.get("time")
            for state in states:
                notifications_utility.set_time_based_notification(
                        domain_class, state, roles, time)
        else:
            raise ValueError("Please specify either onstate or afterstate")
    # Register subscriber for domain class
    component.provideHandler(queue_notification,
        adapts=(domain_class, IWorkflowTransitionEvent))
Пример #4
0
    def __init__(self, connection_id, site_id, user_id=None,
                 logger=None, handler=None):

        h = self.headers = []
        h.append('User-Agent: AMQP Consuming Server')
        h.append('Accept: text/html,text/plain')
        h.append('Host: %s' % socket.gethostname())

        self.logger = LogHelper(logger)
        self.log_info(("AMQP Consuming Server for connection '%s' started "
                       "(site '%s' user: '******')")\
                      % (connection_id, site_id, user_id))

        if handler is None:
            # for unit testing
            handler = handle
        self.zhandler = handler

        self.connection_id = connection_id
        self.site_id = site_id
        self.user_id = user_id

        self.consumers = []
        provideHandler(self.on_before_broker_connect,
                       [IBeforeBrokerConnectEvent])
    def test_subscriber(self):
        from zope.schema import Text
        field = Text(
            __name__='testing',
            description=u'DESCRIPTION',
            default=u'DEFAULT',
            required=True,
        )
        prop = self._makeOne(field=field)

        class Foo(object):
            testing = prop
        foo = Foo()

        logs = []

        @component.adapter(schema.interfaces.IFieldUpdatedEvent)
        def add_field_event(event):
            logs.append(event)

        component.provideHandler(add_field_event)

        self.assertEqual(len(logs), 0)
        foo.testing = u'Bla'
        self.assertEqual(len(logs), 1)
        event = logs[0]
        self.assertEqual(event.field, field)
        self.assertEqual(event.inst, foo)
Пример #6
0
def setUp(test):
    site = setup.placefulSetUp(True)
    site.__name__ = u'portal'
    setup.setUpTestAsModule(test, name='zojax.principal.users.TESTS')

    setUpContents()

    pau = PluggableAuthentication('xyz_')
    component.provideUtility(pau, IAuthentication)
    component.provideAdapter(SiteManagerAdapter)
    component.provideAdapter(FoundPrincipalFactory)

    component.provideAdapter(foundsubscriber.getInternalPrincipal)
    component.provideHandler(foundsubscriber.foundPrincipalCreated)

    component.provideAdapter(adapters.PrincipalLogin)
    component.provideAdapter(adapters.PasswordChanger)
    component.provideAdapter(adapters.PrincipalMailAddress)

    component.provideUtility(adapters.PrincipalByLogin(),
                             name='zojax.principal.users.principals')
    component.provideUtility(adapters.PrincipalByEMail(),
                             name='zojax.principal.users.principals')

    ptool = PasswordTool()
    ptool.passwordManager = 'MD5'
    component.provideUtility(ptool)
 def test_deserializer_notifies_object_modified(self):
     def handler(obj, event):
         obj._handler_called = True
     provideHandler(handler, (IDexterityItem, IObjectModifiedEvent,))
     self.deserialize(body='{"test_textline_field": "My Item"}')
     self.assertTrue(getattr(self.portal.doc1, '_handler_called', False),
                     'IObjectEditedEvent not notified')
Пример #8
0
 def setUp(cls):
     # Register event subscribers
     from Products.ExtFile.tests.testCopySupportEvents import ITestItem
     from Products.ExtFile.tests.testCopySupportEvents import ITestFolder
     from Products.ExtFile.tests.testCopySupportEvents import eventlog
     component.provideHandler(eventlog.trace, (ITestItem, IObjectEvent))
     component.provideHandler(eventlog.trace, (ITestFolder, IObjectEvent))
Пример #9
0
    def test_events(self):
        events = []

        @adapter(IPloneResourceCreatedEvent)
        def _handleFileCreated(event):
            events.append(event)
        provideHandler(_handleFileCreated)

        @adapter(IPloneResourceModifiedEvent)
        def _handleFileModified(event):
            events.append(event)
        provideHandler(_handleFileModified)

        dir = self._makeOne()
        dir.writeFile('test', 'my test')
        dir.writeFile('test', 'my test is modified')
        self.assertTrue(isinstance(events[0], PloneResourceCreatedEvent))
        self.assertEqual(
            str(events[0].object), 
            'my test'
        )
        self.assertTrue(isinstance(events[1], PloneResourceModifiedEvent))
        self.assertEqual(
            str(events[1].object), 
            'my test is modified'
        )
 def setUp(self):
     self.site = DummySite('site')
     self.site._setObject('portal_types', DummyTool())
     self.site._setObject('portal_workflow', WorkflowTool())
     self._constructDummyWorkflows()
     
     provideHandler(react.object_transitioned)
Пример #11
0
    def __init__(self, parent):

        MicroViewPlugIn.MicroViewPlugIn.__init__(self, parent)

        self._helpLink = "isosurface-isosurface-tool"

        # Create a geometry writer
        (self._writer, self._ft) = vtkLoadWriters.LoadGeometryWriters()

        # create a gui container for this plugin
        MicroViewPlugIn.MicroViewPlugIn.CreatePluginDialogFrame(self, parent)

        self._color = (1.0, 1.0, 1.0)
        self._filename = None

        self._app_states = {}
        self._current_image_index = None

        self._transform = None

        # create remaining gui
        self.CreateGUI()

        # listen to certain zope events
        component.provideHandler(self.onModelModifiedEvent)
        component.provideHandler(self.onROIEnabledEvent)
        component.provideHandler(self.OnImageChangeEvent)
        component.provideHandler(self.OnNoImagesLoadedEvent)
        component.provideHandler(self.OnCurrentImageClosingEvent)

        # Invoke an event to react to currently loaded image
        self.InvokeImageLoadedEvent()
    def testFolderNotifyAddedEvent(self):
        from zope.component import adapter
        from zope.component import provideHandler
        from zope.lifecycleevent import ObjectAddedEvent

        e = GroupByDateAction()
        e.base_folder = "/target"
        e.container = "Folder"

        class Handler(object):
            def __init__(self):
                self.invocations = []
                self.counter = 0

            @adapter(ObjectAddedEvent)
            def handler(self, event):
                obj = event.object
                self.counter += 1
                if obj not in self.invocations:
                    self.invocations.append(obj)

        self.handler = Handler()
        provideHandler(self.handler.handler)

        ex = getMultiAdapter((self.folder, e, DummyEvent(self.folder.d1)), IExecutable)
        self.assertTrue(ex())
        invocations = self.handler.invocations
        self.assertEqual(len(invocations), 3)
        self.assertEqual(self.handler.counter, 3)
        self.assertEqual(invocations[0].getId(), "2009")
        self.assertEqual(invocations[1].getId(), "04")
        self.assertEqual(invocations[2].getId(), "22")
Пример #13
0
    def test_update_inherit(self):
        """ tests update inherit method

        We are owner of the portal, with inheritance we are also owner of
        the repo and dossier. If we disable role aquisition on context,
        we lose the role 'owner' on the context
        """

        # Mock event handlers
        provideHandler(factory=self.mock_event.mock_handler, adapts=[ILocalRolesAcquisitionBlocked])
        provideHandler(factory=self.mock_event.mock_handler, adapts=[ILocalRolesAcquisitionActivated])

        # We disable locale role aquisition on dossier
        self.view_dossier.update_inherit(False, reindex=False)
        last_event = self.mock_event.last_event()
        self.assertTrue(ILocalRolesAcquisitionBlocked.providedBy(last_event))
        self.assertEquals(last_event.object, self.dossier)

        # we disable it again,it shouldn't fire a event because nothing changed
        self.view_dossier.update_inherit(False, reindex=False)
        self.assertEquals(last_event, self.mock_event.last_event())

        # # We enable locale role aquisition on dossier
        self.view_dossier.update_inherit(True, reindex=False)
        # and check the fired event
        last_event = self.mock_event.last_event()
        self.assertTrue(ILocalRolesAcquisitionActivated.providedBy(last_event))
        self.assertEquals(last_event.object, self.dossier)

        # we disable it again,it shouldn't fire a event because nothing changed
        self.view_dossier.update_inherit(True, reindex=False)
        self.assertEquals(last_event, self.mock_event.last_event())
    def test_filtered_handler(self):
        from zope.schema import Text
        field = Text(
            __name__='testing',
            description=u'DESCRIPTION',
            default=u'DEFAULT',
            required=True,
        )
        prop = self._makeOne(field=field)

        class IFoo(interface.Interface):
            """
            """

        @interface.implementer(IFoo)
        class Foo(object):
            testing = prop
        foo = Foo()

        logs = []

        @component.adapter(IFoo, schema.Text, schema.interfaces.IFieldUpdatedEvent)
        def add_field_events(obj, field, event):
            logs.append((obj, field, event))

        component.provideHandler(add_field_events)

        self.assertEqual(len(logs), 0)
        foo.testing = u'Bla'
        self.assertEqual(len(logs), 1)
        event_inst, event_field, _event = logs[0]
        self.assertEqual(event_inst, foo)
        self.assertEqual(event_field, field)
Пример #15
0
def create_eventlog(event=interface.Interface):
    value = []
    @component.adapter(event)
    def log(event):
        value.append(event)
    component.provideHandler(log)
    return value
 def test_deserializer_notifies_object_edited(self):
     def handler(obj, event):
         obj._handler_called = True
     provideHandler(handler, (IBaseObject, IObjectEditedEvent,))
     self.doc1.unmarkCreationFlag()
     self.deserialize(body='{"testStringField": "Updated"}')
     self.assertTrue(getattr(self.doc1, '_handler_called', False),
                     'IObjectEditedEvent not notified')
Пример #17
0
    def setUp(cls):
        import Products

        zcml._initialized = 0
        zcml.load_site()
        setHooks()
        component.provideHandler(eventlog.trace, (ITestItem, IObjectEvent))
        component.provideHandler(eventlog.trace, (IRelationship, IObjectEvent))
Пример #18
0
    def __init__(self, decl_class, name, type, original):
        self.decl_class = decl_class
        self.name = intern(name)
        self._name = intern('_' + name)
        self.type = type
        self.original = original

        component.provideHandler(self._association_changed)
Пример #19
0
 def setUp(self):
     setHooks()
     context = config.ConfigurationMachine()
     xmlconfig.registerCommonDirectives(context)
     for feature in self.features:
         context.provideFeature(feature)
     self.context = self._load_zcml(context)
     provideHandler(events.append, (None,))
Пример #20
0
    def test_events(self):

        events = []

        @adapter(IBeforeTransitionEvent)
        def _handleBefore(event):
            events.append(event)
        provideHandler(_handleBefore)

        @adapter(IAfterTransitionEvent)
        def _handleAfter(event):
            events.append(event)
        provideHandler(_handleAfter)

        wftool = self.site.portal_workflow
        wf = self._getDummyWorkflow()

        dummy = self.site._setObject( 'dummy', DummyContent() )
        wftool.notifyCreated(dummy)
        wf.doActionFor(dummy, 'publish', comment='foo', test='bar')

        self.assertEquals(4, len(events))

        evt = events[0]
        self.failUnless(IBeforeTransitionEvent.providedBy(evt))
        self.assertEquals(dummy, evt.object)
        self.assertEquals('private', evt.old_state.id)
        self.assertEquals('private', evt.new_state.id)
        self.assertEquals(None, evt.transition)
        self.assertEquals({}, evt.status)
        self.assertEquals(None, evt.kwargs)

        evt = events[1]
        self.failUnless(IAfterTransitionEvent.providedBy(evt))
        self.assertEquals(dummy, evt.object)
        self.assertEquals('private', evt.old_state.id)
        self.assertEquals('private', evt.new_state.id)
        self.assertEquals(None, evt.transition)
        self.assertEquals({}, evt.status)
        self.assertEquals(None, evt.kwargs)

        evt = events[2]
        self.failUnless(IBeforeTransitionEvent.providedBy(evt))
        self.assertEquals(dummy, evt.object)
        self.assertEquals('private', evt.old_state.id)
        self.assertEquals('published', evt.new_state.id)
        self.assertEquals('publish', evt.transition.id)
        self.assertEquals({'state': 'private', 'comments': ''}, evt.status)
        self.assertEquals({'test' : 'bar', 'comment' : 'foo'}, evt.kwargs)

        evt = events[3]
        self.failUnless(IAfterTransitionEvent.providedBy(evt))
        self.assertEquals(dummy, evt.object)
        self.assertEquals('private', evt.old_state.id)
        self.assertEquals('published', evt.new_state.id)
        self.assertEquals('publish', evt.transition.id)
        self.assertEquals({'state': 'private', 'comments': ''}, evt.status)
        self.assertEquals({'test' : 'bar', 'comment' : 'foo'}, evt.kwargs)
 def testEVTObjectInitializedEvent(self):
     self.sourceObject = None
     @adapter(IObjectInitializedEvent)
     def setSourceObject(new_event):
         self.sourceObject = new_event.object
     
     component.provideHandler(setSourceObject)
     self.factory.createEvent(ICALSTR, self.folder)
     self.failUnless(self.folder.listFolderContents()[0] == self.sourceObject)
Пример #22
0
    def listen_for_object_events(self):
        """listen for all events so that tests can verify they were sent

           events are stored in the test case "events" attribute"""

        self.events = events = []
        def generic_listener(obj, event):
            events.append((obj, event))
        provideHandler(generic_listener, adapts=[Interface, IObjectEvent])
Пример #23
0
 def __init__(self, *args, **kwargs):
     # Call the original constructor; we'll register handlers
     # afterwards
     f(self, *args, **kwargs)
     handler = getattr(self, fname)
     for t in types:
         # Register the handler. Here's where we use
         # eventtype, which was passed in to the outermost
         # function in this behemoth.
         provideHandler(handler, (t, eventtype))
 def test_modified_event_rebroadcast(self):
     provideHandler(object_event_handler, (IAlias, IObjectModifiedEvent,))
     
     modified(self.folder['d1'])
     
     self.assertEquals(1, len(events_received))
     self.failUnless(self.folder['a1'].aq_base is events_received[0][0].aq_base)
     
     sm = getGlobalSiteManager()
     sm.unregisterHandler(object_event_handler, required=(IAlias, IObjectModifiedEvent,))
Пример #25
0
def setUp(test):
    setup.placelessSetUp(True)
    setup.setUpTestAsModule(test, name='zojax.workflow.TESTS')

    component.provideAdapter(state.WorkflowState)
    component.provideAdapter(info.WorkflowInfo)
    component.provideHandler(workflow.initWorkflow)
    component.provideAdapter(AttributeAnnotations)
    component.provideAdapter(state.contentPermissionsMap,
                             name='workflow.state.permissions')
    def testUserCreationEvent(self):
        provideHandler(userCreatedHandler)
        self.uf.events = []

        self.uf._doAddUser('event1', 'secret', ['role1'], [])

        self.assertEqual(len(self.uf.events), 1)
        event = self.uf.events[0]
        self.assertTrue(IPrincipalCreatedEvent.providedBy(event))
        self.assertEqual(event.principal.getUserName(), 'event1')
        self.assertEqual(event.principal.getId(), 'event1')
Пример #27
0
    def setUp(self):
        from zope.component import provideHandler
        from zope.component.interfaces import IObjectEvent
        from Products.CMFCore.interfaces import ICookieCrumbler
        from Products.CMFCore.CookieCrumbler import handleCookieCrumblerEvent

        PlacelessSetup.setUp(self)
        self._finally = None

        provideHandler(handleCookieCrumblerEvent,
                       adapts=(ICookieCrumbler, IObjectEvent))
Пример #28
0
    def setUp(self):
        from zope.component import provideHandler
        from zope.interface.interfaces import IObjectEvent
        from Products.CMFCore.interfaces import ICookieCrumbler
        from Products.CMFCore.CookieCrumbler import handleCookieCrumblerEvent

        self._finally = None

        eventtesting.setUp()
        provideHandler(handleCookieCrumblerEvent,
                       adapts=(ICookieCrumbler, IObjectEvent))
Пример #29
0
    def setUp(self):
        # Previous test layer might be buggy and have left things
        # behind, so clear everything ourselves before doing setup
        # (like ZopeLite)
        layerCleanUp()

        # Set up this test layer.
        context = config.ConfigurationMachine()
        xmlconfig.registerCommonDirectives(context)
        self.context = self._load_zcml(context)
        provideHandler(events.append, (None,))
Пример #30
0
    def setUp(self):
        from zope.component import provideHandler
        from zope.component.interfaces import IObjectEvent
        from Products.CMFCore.interfaces import ICookieCrumbler
        from Products.CMFCore.CookieCrumbler import handleCookieCrumblerEvent

        PlacelessSetup.setUp(self)
        self._finally = None

        provideHandler(handleCookieCrumblerEvent,
                       adapts=(ICookieCrumbler, IObjectEvent))
Пример #31
0
    def setUp(tc):
        # clean slate!
        cleanUp()

        # init event system
        from zope.component import event

        # register components
        provideHandler(notifyFieldEvent)
        provideAdapter(at_field_retrieval)
        provideSubscriptionAdapter(at_field_storage)
Пример #32
0
    def __init__(self, name, type, lower, upper, *subsets):
        self.name = intern(name)
        self._name = intern('_' + name)
        self.version = 1
        self.type = type
        self.lower = lower
        self.upper = upper
        self.subsets = set(subsets)
        self.single = len(subsets) == 1

        component.provideHandler(self._association_changed)
Пример #33
0
    def test_database_events(self):
        from Zope2.App.startup import startup
        from zope.component import provideHandler
        from zope.processlifetime import IDatabaseOpened
        from zope.processlifetime import IDatabaseOpenedWithRoot

        handler = InstalledHandler('Zope2.App.test_startup')
        provideHandler(logevent, [IDatabaseOpenedWithRoot])
        provideHandler(logevent, [IDatabaseOpened])
        startup()
        self.assertEqual(str(handler), logged)
Пример #34
0
    def test_database_events(self):
        from Zope2.App.startup import startup
        from zope.component import provideHandler
        from zope.processlifetime import IDatabaseOpened
        from zope.processlifetime import IDatabaseOpenedWithRoot

        handler = InstalledHandler('Zope2.App.test_startup')
        provideHandler(logevent, [IDatabaseOpenedWithRoot])
        provideHandler(logevent, [IDatabaseOpened])
        startup()
        self.assertEqual(str(handler), logged)
Пример #35
0
    def test_deserializer_notifies_object_edited(self):
        def handler(obj, event):
            obj._handler_called = True

        provideHandler(handler, (IBaseObject, IObjectEditedEvent))
        self.doc1.unmarkCreationFlag()
        self.deserialize(body='{"testStringField": "Updated"}')
        self.assertTrue(
            getattr(self.doc1, "_handler_called", False),
            "IObjectEditedEvent not notified",
        )
Пример #36
0
def start_monitor(unused):
    """start the request monitor if configured."""
    from App.config import getConfiguration
    config = getConfiguration().product_config.get('requestmonitor')
    if config is None:
        return  # not configured
    # register publication observers
    provideHandler(handle_request_start)
    provideHandler(handle_request_end)
    monitor = _Monitor(config)
    start_new_thread(monitor.run, ())
Пример #37
0
    def setUp(self):
        provideAdapter(persistentFieldAdapter)
        self.registry = Registry()
        self.registry.registerInterface(ICachePurgingSettings)
        provideUtility(self.registry, IRegistry)

        self.settings = self.registry.forInterface(ICachePurgingSettings)
        self.settings.enabled = True
        self.settings.cachingProxies = ('http://localhost:1234', )

        self.handler = Handler()
        provideHandler(self.handler.handler)
Пример #38
0
    def setUp(self):
        TestCase.setUp(self)
        logger = logging.getLogger(self.factory.getUniqueString())
        logger.setLevel(logging.DEBUG)
        self.logger = logger

        @adapter(ILoggingEvent)
        def _log_event(event):
            logger.log(event.level, event.message)

        provideHandler(_log_event)
        self.addCleanup(getGlobalSiteManager().unregisterHandler, _log_event)
Пример #39
0
def start_successlogging(unused):
    """start successlogging if configured."""
    from App.config import getConfiguration
    config = getConfiguration().product_config.get('successlogging')
    if config is None:
        return  # not configured
    global _log_good, _log_bad
    _log_good = Rotator(config['filebase'] + '_good', lock=True)
    _log_bad = Rotator(config['filebase'] + '_bad', lock=True)
    # register publication observers
    provideHandler(handle_request_success)
    provideHandler(handle_request_failure)
    def test_deserializer_modified_event_contains_descriptions(self):
        def handler(obj, event):
            self.event = event

        provideHandler(handler, (
            IDexterityItem,
            IObjectModifiedEvent,
        ))
        self.deserialize(body='{"test_textline_field": "My Item"}')
        self.assertEquals(1, len(self.event.descriptions))
        self.assertEquals(('IDXTestDocumentSchema.test_textline_field', ),
                          self.event.descriptions[0].attributes)
Пример #41
0
    def test_pauser(self):
        SEEN = []
        handler = SEEN.append

        provideHandler(handler, (MyEvent, ))
        notify(MyEvent())
        self.assertEquals(1, len(SEEN))
        with paused(handler):
            notify(MyEvent())
            self.assertEquals(1, len(SEEN))
        self.assertEquals(2, len(SEEN))
        notify(MyEvent())
        self.assertEquals(3, len(SEEN))
Пример #42
0
 def testCredentialsEvent(self):
     provideHandler(PASEventNotify)
     provideHandler(userCredentialsUpdatedHandler)
     def wrap(self, *args):
         self._data.append(args)
         return self._original(*args)
     self.uf._data=[]
     self.uf._original=self.uf.updateCredentials
     self.uf.updateCredentials=wrap
     event.notify(CredentialsUpdated(self.uf.getUserById("user1"), "testpassword"))
     self.assertEqual(len(self.uf._data), 1)
     self.assertEqual(self.uf._data[0][2], "user1")
     self.assertEqual(self.uf._data[0][3], "testpassword")
Пример #43
0
    def test_retry_on_conflict(self):
        self.browser.open(self.layer['portal'].absolute_url())
        self.browser.getLink('Page').click()
        self.browser.getControl('Title', index=0).value = 'Foo'
        component.provideHandler(
            raise_on_first_add, (Interface, IObjectCreatedEvent,))
        self.browser.getControl('Save').click()
        self.assertEqual(len(UIDS), 2)
        self.assertEqual(len(solrSearchResults(SearchableText='Foo')), 1)

        sm = component.getSiteManager()
        sm.unregisterHandler(
            raise_on_first_add, (Interface, IObjectCreatedEvent,))
Пример #44
0
def setUp(test):
    testing.setUp(test)

    # Register adapters and handlers:
    # This query interface relies on a zope.app.catalog to
    # do the job.  Before we can use this catalog, we'll need to register an
    # IIntIds utility and wire in a couple of adatpers defined in the
    # subscribe module.  This is what 'create_subscriptions' does for us:
    from zope.component import provideUtility, provideAdapter, provideHandler
    for adapter in (subscribe.catalog_data,
                    subscribe.SubscriptionSearchableText):
        provideAdapter(adapter)

    from zope.component.event import objectEventNotify
    for handler in (subscribe.subscription_modified,
                    subscribe.subscription_removed, objectEventNotify):
        provideHandler(handler)

    # Set up an IIntIds utility:
    try:
        from zope.intid import IntIds
        from zope.intid.interfaces import IIntIds
        IntIds, IIntIds  # pyflakes
    except ImportError:
        # BBB Plone 4.0 and earlier.
        from zope.app.intid import IntIds
        from zope.app.intid.interfaces import IIntIds
    intids = IntIds()
    provideUtility(intids, IIntIds)

    # We'll register a slight variation of the subscription_added
    # handler that commits the transaction, so that a later lookup of
    # IKeyReference for our subscription will work:
    from ZODB.DemoStorage import DemoStorage
    from ZODB import DB
    global root
    db = DB(DemoStorage())
    root = db.open().root()

    subscription_added.__component_adapts__ = (
        subscribe.subscription_added.__component_adapts__)
    provideHandler(subscription_added)

    # As a last step, we'll register the IKeyReference adapter for all
    # persistent objects:
    from zope.keyreference.persistent import KeyReferenceToPersistent
    from persistent.interfaces import IPersistent
    provideAdapter(KeyReferenceToPersistent, adapts=(IPersistent, ))

    provideAdapter(subscribe.get_subscription_label)
    provideAdapter(subscribe.get_subscription_key)
Пример #45
0
 def setUp(self):
     self.handler = Handler()
     provideHandler(self.handler.handler)
     
     provideHandler(objectEventNotify)
     provideHandler(purgeOnModified)
     provideHandler(purgeOnMovedOrRemoved)
Пример #46
0
    def setUp(self):

        #self.registry = queryUtility(IRegistry)
        #self.registry = Registry()
        #self.registry.registerInterface(ICachePurgingConfiglet)
        #provideUtility(self.registry, IRegistry)

        context = FauxContext()
        self.settings = CachePurgingConfiglet()
        self.settings.enabled = True
        self.settings.cachingProxies = ('http://localhost:1234',)
        
        self.handler = Handler()
        provideHandler(self.handler.handler)
Пример #47
0
    def test_events(self):
        from OFS.interfaces import IObjectWillBeAddedEvent
        from zope.component import adapter
        from zope.component import provideHandler
        from zope.container.interfaces import IContainerModifiedEvent
        from zope.container.interfaces import IObjectAddedEvent
        from zope.lifecycleevent.interfaces import IObjectCreatedEvent
        events = []

        @adapter(IObjectCreatedEvent)
        def _handleObjectCreated(event):
            events.append(event)

        provideHandler(_handleObjectCreated)

        @adapter(IObjectWillBeAddedEvent)
        def _handleObjectWillBeAdded(event):
            events.append(event)

        provideHandler(_handleObjectWillBeAdded)

        @adapter(IObjectAddedEvent)
        def _handleObjectAdded(event):
            events.append(event)

        provideHandler(_handleObjectAdded)

        @adapter(IContainerModifiedEvent)
        def _handleContainerModified(event):
            events.append(event)

        provideHandler(_handleContainerModified)

        self.ti.constructInstance(self.f, 'foo')
        self.assertEqual(len(events), 4)

        evt = events[0]
        self.assertTrue(IObjectCreatedEvent.providedBy(evt))
        self.assertEqual(evt.object, self.f.foo)

        evt = events[1]
        self.assertTrue(IObjectWillBeAddedEvent.providedBy(evt))
        self.assertEqual(evt.object, self.f.foo)
        self.assertEqual(evt.oldParent, None)
        self.assertEqual(evt.oldName, None)
        self.assertEqual(evt.newParent, self.f)
        self.assertEqual(evt.newName, 'foo')

        evt = events[2]
        self.assertTrue(IObjectAddedEvent.providedBy(evt))
        self.assertEqual(evt.object, self.f.foo)
        self.assertEqual(evt.oldParent, None)
        self.assertEqual(evt.oldName, None)
        self.assertEqual(evt.newParent, self.f)
        self.assertEqual(evt.newName, 'foo')

        evt = events[3]
        self.assertTrue(IContainerModifiedEvent.providedBy(evt))
        self.assertEqual(evt.object, self.f)
Пример #48
0
def unpauseHandler(handler, buffer=None, temp_handlers=None):
    """
    First untee temporary handlers; then, reregister handlers paused by
    L{pauseHandler}. Finally, replay the buffered events through the original
    handler.
    """
    unteeHandler(temp_handlers)

    if temp_handlers is not None:
        for temp_handler, required in temp_handlers:
            provideHandler(handler, required)

    if buffer is not None:
        for args, kwargs in buffer:
            handler(*args, **kwargs)
    def test_deserializer_notifies_when_field_is_set_to_null(self):
        def handler(obj, event):
            obj._handler_called = True
            self.event = event

        provideHandler(handler, (IDexterityItem, IObjectModifiedEvent))
        self.deserialize(body='{"test_textline_field": null}')
        self.assertTrue(
            getattr(self.portal.doc1, "_handler_called", False),
            "IObjectModifiedEvent not notified",
        )
        self.assertEqual(
            ("IDXTestDocumentSchema.test_textline_field",),
            self.event.descriptions[0].attributes,
        )
Пример #50
0
 def afterSetUp(self):
     self.catalog = self.portal.portal_catalog
     self.folder.invokeFactory('Folder', id='foo')
     self.folder.invokeFactory('Folder', id='bar')
     self.folder.foo.invokeFactory('Document', id='doc1')
     self.folder.bar.invokeFactory('Document', id='doc2')
     undeletable = Item('no_delete', 'Just Try!')
     # make it undeletable
     directlyProvides(undeletable, ICantBeDeleted)
     component.provideHandler(disallow_delete_handler,
                              [ICantBeDeleted, IObjectRemovedEvent])
     self.folder._setObject('no_delete', undeletable)
     # folder_delete requires a non-GET request
     self.setRequestMethod('POST')
     self.setupAuthenticator()
Пример #51
0
 def __init__(self, avatar, fsroot):
     provideHandler(self.connectionClosed)
     self._avatar = avatar
     self._fs_root = fsroot
     self.uploadfilesystem = UploadFileSystem(tempfile.mkdtemp())
     self._current_upload = self.uploadfilesystem.rootpath
     os.chmod(self._current_upload, 0770)
     self._log = logging.getLogger("poppy-sftp")
     self.hook = Hooks(self._fs_root,
                       self._log,
                       "ubuntu",
                       perms='g+rws',
                       prefix='-sftp')
     self.hook.new_client_hook(self._current_upload, 0, 0)
     self.hook.auth_verify_hook(self._current_upload, None, None)
Пример #52
0
    def test_update_role_settings(self):
        """ Test update_role_settings method
        """
        # Mock event handler
        provideHandler(
            factory=self.mock_event.mock_handler,
            adapts=[
                ILocalRolesModified,
            ],
        )

        # If nothing has changed it needs to be reported accordingly
        changed = self.view_repo.update_role_settings([], False)
        self.assertFalse(changed)

        # We try to add the new local role 'publisher'
        new_settings = \
            [{'type': 'user', 'id': 'test_user_1_', 'roles': ['Publisher']}, ]

        changed = self.view_repo.update_role_settings(new_settings, False)
        self.assertTrue(changed)

        last_event = self.mock_event.last_event()
        # check the event type
        self.assertTrue(ILocalRolesModified.providedBy(last_event))
        # check the event context
        self.assertEquals(last_event.object, self.repo)
        # check the stored localroles
        self.assertEquals(last_event.old_local_roles,
                          {'test_user_1_': ('Owner', )})
        self.assertEquals(last_event.new_local_roles,
                          (('test_user_1_', ('Owner', 'Publisher')), ))

        # now we remvove the local role 'publisher'
        new_settings = \
            [{'type': 'user', 'id': 'test_user_1_', 'roles': []}, ]

        changed = self.view_repo.update_role_settings(new_settings, False)
        self.assertTrue(changed)

        # check event attributes
        last_event = self.mock_event.last_event()
        self.assertTrue(ILocalRolesModified.providedBy(last_event))
        self.assertEquals(last_event.object, self.repo)
        self.assertEquals(last_event.old_local_roles,
                          {'test_user_1_': ('Owner', 'Publisher')})
        self.assertTrue(last_event.new_local_roles == (('test_user_1_',
                                                        ('Owner', )), ))
Пример #53
0
    def __init__(self, name):
        """Initialize a WorkerPool instance.

        ZenHubWorker will specify a "queue" to accept tasks from.  The
        name of the queue is given by the 'name' parameter.

        :param str name: Name of the "queue" associated with this pool.
        """
        # __available contains workers (by ID) available for work
        self.__available = WorkerAvailabilityQueue()
        self.__workers = {}  # Worker refs by worker.sessionId
        self.__services = {}  # Service refs by worker.sessionId
        self.__name = name
        self.__log = getLogger(self)
        # Declare a handler for ReportWorkerStatus events
        provideHandler(self.handleReportStatus)
Пример #54
0
    def setUp(self):
        from zope.site.folder import Folder

        ReferenceSetupMixin.setUp(self)

        sm = getSiteManager(self.root)
        self.utility = addUtility(sm, '1', IIntIds, IntIds())

        self.root['folder1'] = Folder()
        self.root._p_jar = ConnectionStub()
        self.root['folder1']['folder1_1'] = self.folder1_1 = Folder()
        self.root['folder1']['folder1_1']['folder1_1_1'] = Folder()

        sm1_1 = createSiteManager(self.folder1_1)
        self.utility1 = addUtility(sm1_1, '2', IIntIds, IntIds())
        provideHandler(intIdEventNotify)
Пример #55
0
    def setUp(self):
        provideAdapter(AttributeAnnotations)
        provideAdapter(persistentFieldAdapter)
        provideHandler(purge)

        class FauxPurger(object):
            implements(IPurger)

            def __init__(self):
                self.purged = []

            def purgeAsync(self, url, httpVerb='PURGE'):
                self.purged.append(url)

        self.purger = FauxPurger()
        provideUtility(self.purger)
Пример #56
0
    def testConnectEventAndDisconnectEvent(self):
        provideHandler(connectedsubscriber)
        provideHandler(disconnectedsubscriber)
        triples = [(self.objs[0].UID(), self.objs[1].UID(), ruleset.getId())
                   for ruleset in self.rulesets]
        processor.process(self.portal, connect=[triples[0]])
        self.assertEquals(len(connectedresult), 1)
        ref = connectedresult[0]
        self.assertEquals((ref.sourceUID, ref.targetUID),
                          (self.objs[0].UID(), self.objs[1].UID()))

        processor.process(self.portal, disconnect=[triples[0]])
        self.assertEquals(len(disconnectedresult), 1)
        ref = disconnectedresult[0]
        self.assertEquals((ref.sourceUID, ref.targetUID),
                          (self.objs[0].UID(), self.objs[1].UID()))
Пример #57
0
    def test_notifyException(self):
        provideHandler(notifyExceptionHandler)

        tool = self._makeWithTypesAndChain()

        ob = DummyContent('dummy')
        tool.notifyException(ob, 'action', 'exception')

        for wf in tool.a, tool.b:
            notified = wf.notified('exception')
            self.assertEqual(len(notified), 1)
            self.assertEqual(notified[0], (ob, 'action', 'exception'))

            notified = wf.notified('exception-evt')
            self.assertEqual(len(notified), 1)
            self.assertEqual(notified[0], (ob, 'action', 'exception'))
Пример #58
0
    def test_notifySuccess(self):
        provideHandler(notifySuccessHandler)

        tool = self._makeWithTypesAndChain()

        ob = DummyContent('dummy')
        tool.notifySuccess(ob, 'action')

        for wf in tool.a, tool.b:
            notified = wf.notified('success')
            self.assertEqual(len(notified), 1)
            self.assertEqual(notified[0], (ob, 'action', None))

            notified = wf.notified('success-evt')
            self.assertEqual(len(notified), 1)
            self.assertEqual(notified[0], (ob, 'action', None))
Пример #59
0
    def __init__(self,
                 connection_id,
                 site_id,
                 user_id='Anonymous User',
                 scheme='http',
                 hostname=None,
                 port=80,
                 use_vhm=True,
                 vhm_method_prefix='',
                 logger=None,
                 handler=None):

        self.logger = AMQPMedusaLogger(logger)

        from collective.zamqp.utils import logger
        logger.default(
            u"AMQP Consuming Server for connection '%s' started "
            u"(site '%s' user: '******')", connection_id, site_id, user_id)

        self._USE_VHM = use_vhm

        h = self.headers = []
        h.append('User-Agent: AMQP Consuming Server')
        h.append('Accept: text/html,text/plain')
        if not hostname:
            hostname = socket.gethostname()
        if use_vhm or ':' in hostname:
            h.append('Host: {0:s}'.format(hostname))
        else:
            h.append('Host: {0:s}:{1:d}'.format(hostname, port))

        self.hostname = hostname
        self.connection_id = connection_id
        self.site_id = site_id
        self.user_id = user_id
        self.port = port
        self.scheme = scheme
        self.vhm_method_prefix = vhm_method_prefix

        if handler is None:
            # for unit testing
            handler = handle
        self.zhandler = handler

        self.consumers = []
        provideHandler(self.on_before_broker_connect,
                       [IBeforeBrokerConnectEvent])
Пример #60
0
    def testCredentialsEvent(self):
        import functools
        provideHandler(PASEventNotify)
        provideHandler(userCredentialsUpdatedHandler)

        def wrap(self, *args):
            self._data.append(args)
            return self._original(*args)

        self.uf._data = []
        self.uf._original = self.uf.updateCredentials
        self.uf.updateCredentials = functools.partial(wrap, self.uf)
        self.assertEqual(len(self.uf._data), 0)
        event.notify(
            CredentialsUpdated(self.uf.getUserById('user1'), 'testpassword'))
        self.assertEqual(self.uf._data[0][2], 'user1')
        self.assertEqual(self.uf._data[0][3], 'testpassword')