Esempio n. 1
0
    def testRenameEvents(self):
        self.assertRaises(KeyError, self.reflecto.manage_renameObjects,
                          ('monty', ), ('python', ))
        self.assertEqual(len(getEvents()), 0)

        self.assertRaises(KeyError, self.reflecto.manage_renameObjects,
                          ('foo', 'monty'), ('bar', 'python'))
        self.assertEqual(len(getEvents()), 1)
        events = getEvents(IObjectWillBeMovedEvent)
        self.assertEqual(len(events), 1)
        self.assertEqual(events[0].oldName, 'foo')
        self.assertEqual(events[0].newName, 'bar')

        self.assertEqual(
            self.reflecto.manage_renameObjects(('foo', ), ('bar', )), ['foo'])
        events = getEvents()
        self.assertEqual(len(events), 4)
        self.assertTrue(IObjectWillBeMovedEvent.providedBy(events[1]))

        self.assertTrue(IObjectMovedEvent.providedBy(events[2]))
        self.assertEqual(events[2].oldName, 'foo')
        self.assertEqual(events[2].newName, 'bar')

        self.assertTrue(IContainerModifiedEvent.providedBy(events[3]))
        self.assertTrue(events[3].object is self.reflecto)
Esempio n. 2
0
    def test_createAndAdd(self):

        @implementer(IAdding)
        class Adding(object):

            def __init__(self, test):
                self.test = test

            def add(self, ob):
                self.ob = ob
                self.test.assertEqual(
                    ob.__dict__,
                    {'args': ("bar", "baz"),
                     'kw': {'email': '*****@*****.**'},
                     '_foo': 'foo',
                    })
                return ob
            def nextURL(self):
                return "."

        adding = Adding(self)
        self._invoke_add()
        (descriminator, callable, args, kw) = self._context.last_action
        factory = AddViewFactory(*args)
        request = TestRequest()
        view = getMultiAdapter((adding, request), name='addthis')

        view.createAndAdd(SampleData.__dict__)

        self.assertEqual(adding.ob.extra1, "extra1")
        self.assertEqual(adding.ob.extra2, "extra2")
        self.assertEqual(adding.ob.name, "foo")
        self.assertEqual(adding.ob.address, "aa")
        self.assertEqual(len(getEvents(IObjectCreatedEvent)), 1)
        self.assertEqual(len(getEvents(IObjectModifiedEvent)), 1)
Esempio n. 3
0
    def testRenameEvents(self):
        self.assertRaises(KeyError, self.reflecto.manage_renameObjects,
                          ('monty',), ('python',))
        self.assertEqual(len(getEvents()), 0)

        self.assertRaises(KeyError, self.reflecto.manage_renameObjects,
                          ('foo', 'monty'), ('bar', 'python'))
        self.assertEqual(len(getEvents()), 1)
        events = getEvents(IObjectWillBeMovedEvent)
        self.assertEqual(len(events), 1)
        self.assertEqual(events[0].oldName, 'foo')
        self.assertEqual(events[0].newName, 'bar')

        self.assertEqual(self.reflecto.manage_renameObjects(('foo',), ('bar',)),
                         ['foo'])
        events = getEvents()
        self.assertEqual(len(events), 4)
        self.assertTrue(IObjectWillBeMovedEvent.providedBy(events[1]))

        self.assertTrue(IObjectMovedEvent.providedBy(events[2]))
        self.assertEqual(events[2].oldName, 'foo')
        self.assertEqual(events[2].newName, 'bar')

        self.assertTrue(IContainerModifiedEvent.providedBy(events[3]))
        self.assertTrue(events[3].object is self.reflecto)
Esempio n. 4
0
    def test_createAndAdd(self):

        @implementer(IAdding)
        class Adding(object):

            def __init__(self, test):
                self.test = test

            def add(self, ob):
                self.ob = ob
                self.test.assertEqual(
                    ob.__dict__,
                    {'args': ("bar", "baz"),
                     'kw': {'email': '*****@*****.**'},
                     '_foo': 'foo',
                    })
                return ob
            def nextURL(self):
                return "."

        adding = Adding(self)
        self._invoke_add()
        (descriminator, callable, args, kw) = self._context.last_action
        factory = AddViewFactory(*args)
        request = TestRequest()
        view = getMultiAdapter((adding, request), name='addthis')

        view.createAndAdd(SampleData.__dict__)

        self.assertEqual(adding.ob.extra1, "extra1")
        self.assertEqual(adding.ob.extra2, "extra2")
        self.assertEqual(adding.ob.name, "foo")
        self.assertEqual(adding.ob.address, "aa")
        self.assertEqual(len(getEvents(IObjectCreatedEvent)), 1)
        self.assertEqual(len(getEvents(IObjectModifiedEvent)), 1)
Esempio n. 5
0
def test_setitem():

    item = Item()
    container = {}

    setitem(container, container.__setitem__, u'c', item)
    assert container[u'c'] is item
    assert item.__parent__ is container
    assert item.__name__ == u'c'

    # We should get events
    assert len(getEvents(IObjectAddedEvent)) == 1

    event = getEvents(IObjectAddedEvent)[-1]
    assert event.object is item
    assert event.newParent is container
    assert event.newName == u'c'
    assert event.oldParent is None
    assert event.oldName is None

    # As well as a modification event for the container
    assert len(getEvents(IObjectModifiedEvent)) == 1
    assert getEvents(IObjectModifiedEvent)[-1].object is container

    # The item's hooks have been called:
    assert item.added is event
    assert item.moved is event

    # we clean our test.
    clearEvents()
 def testChangingHEaderMatchFiresEvent(self):
     plugin = self._makeOne()
     self.assertEqual(eventtesting.getEvents(), [])
     plugin.manage_changeProperties(match_roles=[r'REMOTE_ADDR;^10\.0\.(100|101)\.;Authenticated,Member'])
     self.assertEqual(len(eventtesting.getEvents()), 1)
     event = eventtesting.getEvents()[0]
     self.assertEqual(event.__class__.__name__, 'ConfigurationChangedEvent')
     self.assertEqual(event.object, plugin)
     self.assertEqual(event.object.match_roles, (r'REMOTE_ADDR;^10\.0\.(100|101)\.;Authenticated,Member',))
Esempio n. 7
0
 def testChangingIPRolesFiresEvent(self):
     plugin = self._makeOne()
     self.assertEqual(eventtesting.getEvents(), [])
     plugin.manage_changeProperties(ip_roles=['127.0.0.0/24:Authenticated'])
     self.assertEqual(len(eventtesting.getEvents()), 1)
     event = eventtesting.getEvents()[0]
     self.assertEqual(event.__class__.__name__, 'ConfigurationChangedEvent')
     self.assertEqual(event.object, plugin)
     self.assertEqual(event.object.ip_roles, ('127.0.0.0/24:Authenticated',))
Esempio n. 8
0
 def testChangingIPRolesFiresEvent(self):
     plugin = self._makeOne()
     self.assertEqual(eventtesting.getEvents(), [])
     plugin.manage_changeProperties(ip_roles=['127.0.0.0/24:Authenticated'])
     self.assertEqual(len(eventtesting.getEvents()), 1)
     event = eventtesting.getEvents()[0]
     self.assertEqual(event.__class__.__name__, 'ConfigurationChangedEvent')
     self.assertEqual(event.object, plugin)
     self.assertEqual(event.object.ip_roles,
                      ('127.0.0.0/24:Authenticated', ))
Esempio n. 9
0
    def test_before_object_assigned_event_not_fired_invalid_value(self):

        with self.assertRaises(SchemaNotProvided):
            validate_named_field_value(Bar(), IBar, 'thing', object())

        events = eventtesting.getEvents(IBeforeObjectAssignedEvent)
        assert_that(events, has_length(0))

        events = eventtesting.getEvents(IFieldUpdatedEvent)
        assert_that(events, has_length(0))
Esempio n. 10
0
    def test_before_object_assigned_event_fired_valid_value(self):

        thing = Thing()
        root = Bar()

        validate_named_field_value(root, IBar, 'thing', thing)()

        events = eventtesting.getEvents(IBeforeObjectAssignedEvent)
        assert_that(events, has_length(1))
        assert_that(events[0], has_attr('object', is_(same_instance(thing))))

        events = eventtesting.getEvents(IFieldUpdatedEvent)
        assert_that(events, has_length(1))
 def testChangingHEaderMatchFiresEvent(self):
     plugin = self._makeOne()
     self.assertEqual(eventtesting.getEvents(), [])
     plugin.manage_changeProperties(match_roles=[
         r'REMOTE_ADDR;^10\.0\.(100|101)\.;Authenticated,Member;python:True'
     ])
     self.assertEqual(len(eventtesting.getEvents()), 1)
     event = eventtesting.getEvents()[0]
     self.assertEqual(event.__class__.__name__, 'ConfigurationChangedEvent')
     self.assertEqual(event.object, plugin)
     self.assertEqual(event.object.match_roles, (
         r'REMOTE_ADDR;^10\.0\.(100|101)\.;Authenticated,Member;python:True',
     ))
Esempio n. 12
0
    def test_order_events(self):
        # Prepare the setup::
        from zope.container.contained import ContainerModifiedEvent

        # Prepare some objects::

        from zope.container.ordered import OrderedContainer
        oc = OrderedContainer()
        oc['foo'] = 'bar'
        oc['baz'] = 'quux'
        oc['zork'] = 'grue'
        self.assertEqual(oc.keys(),
                         ['foo', 'baz', 'zork'])

        # Now change the order::

        clearEvents()
        oc.updateOrder(['baz', 'foo', 'zork'])
        self.assertEqual(oc.keys(),
                         ['baz', 'foo', 'zork'])

        # Check what events have been sent::

        events = getEvents()
        self.assertEqual(1, len(events))
        self.assertIsInstance(events[0], ContainerModifiedEvent)

        # This is in fact a specialized modification event::

        from zope.lifecycleevent.interfaces import IObjectModifiedEvent
        self.assertTrue(IObjectModifiedEvent.providedBy(events[0]))
Esempio n. 13
0
    def test_order_events(self):
        # Prepare the setup::
        from zope.container.contained import ContainerModifiedEvent

        # Prepare some objects::

        from zope.container.ordered import OrderedContainer
        oc = OrderedContainer()
        oc['foo'] = 'bar'
        oc['baz'] = 'quux'
        oc['zork'] = 'grue'
        self.assertEqual(oc.keys(), ['foo', 'baz', 'zork'])

        # Now change the order::

        clearEvents()
        oc.updateOrder(['baz', 'foo', 'zork'])
        self.assertEqual(oc.keys(), ['baz', 'foo', 'zork'])

        # Check what events have been sent::

        events = getEvents()
        self.assertEqual(1, len(events))
        self.assertIsInstance(events[0], ContainerModifiedEvent)

        # This is in fact a specialized modification event::

        from zope.lifecycleevent.interfaces import IObjectModifiedEvent
        self.assertTrue(IObjectModifiedEvent.providedBy(events[0]))
Esempio n. 14
0
    def test_before_object_assigned_event_fired_invalid_value_fixed(self):
        thing = Thing()
        root = Bar()

        class NotThing(object):
            def __conform__(self, iface):
                return thing if iface is IThing else None

        validate_named_field_value(root, IBar, 'thing', NotThing())()

        events = eventtesting.getEvents(IBeforeObjectAssignedEvent)
        assert_that(events, has_length(1))
        assert_that(events[0], has_attr('object', is_(same_instance(thing))))

        events = eventtesting.getEvents(IFieldUpdatedEvent)
        assert_that(events, has_length(1))
    def test_remove_group(self):
        browser = self._connect_as_manager()
        self._create_group(browser)
        browser.getControl(name="remove-folder-members").click()
        self.assertNotIn("remove-folder-members", browser.contents)
        self.assertIn("Folder members", browser.contents)
        events = eventtesting.getEvents(IGroupRemoved)
#        self.assertEqual(len(events), 1)
        self.assertTrue(len(events) > 1)
 def test_payment_event(self):
     """Check that the MollieIdealPaymentEvent was fired."""
     request = TestRequest(
         form=dict(transaction_id=self.transaction_id))
     payment_view = getMultiAdapter((self.foo, request),
                                    name='report_multiple_payment_status')
     payment_view()
     payment_events = [event for event in eventtesting.getEvents()
                       if IMollieIdealPaymentEvent.providedBy(event)]
     self.assertTrue(len(payment_events) > 0)
Esempio n. 17
0
 def test_poll(self):
     cacher = self.layer.cacher
     config = self._get_poller_config('3', 'c') # poll time 0, should loop once
     config.update({'exit_': threading.Event()})
     
     # poll once
     t1 = threading.Thread(target=cacher.poll, kwargs=(config))
     t1.start()
     t1.join(.1)
     self.assertFalse(t1.is_alive())
     self.assertEquals(len(getEvents(
                         ICompletedCachableSourcePoll)), 1)
     
     # poll again
     t2 = threading.Thread(target=cacher.poll, kwargs=(config))
     t2.start()
     t2.join(.1)
     self.assertFalse(t2.is_alive())
     self.assertEquals(len(getEvents(
                         ICompletedCachableSourcePoll)), 2)
Esempio n. 18
0
def test_no_event():
    """We can suppress events and hooks by setting the `__parent__` and
    `__name__` first
    """
    item = Item()
    container = {}

    # By setting the __parent__ and __name, we act as if we were
    # already contained.
    item.__parent__, item.__name__ = container, 'c'
    setitem(container, container.__setitem__, u'c', item)

    assert len(container) == 1
    assert len(getEvents(IObjectAddedEvent)) == 0
    assert len(getEvents(IObjectModifiedEvent)) == 0

    assert getattr(item, 'added', None) is None
    assert getattr(item, 'moved', None) is None

    # we clean our test.
    clearEvents()
Esempio n. 19
0
    def test_file_download_no_notification_when_system(self):
        _original_security = AccessControl.getSecurityManager()

        _system_user = AccessControl.SecurityManagement.SpecialUsers.system
        AccessControl.SecurityManagement.newSecurityManager(None, _system_user)
        self.index_html()
        events = [e for e in eventtesting.getEvents()
                  if IFileDownloadedEvent.providedBy(e)]
        self.assertEqual(0, len(events))
        AccessControl.SecurityManagement.setSecurityManager(
            _original_security)
        _original_security = None
Esempio n. 20
0
    def testDeleteEvents(self):
        self.assertRaises(KeyError, self.reflecto.manage_delObjects, ('monty',))
        self.assertEqual(len(getEvents()), 0)

        self.assertRaises(KeyError, self.reflecto.manage_delObjects,
                          ('foo', 'monty',))
        self.assertEqual(len(getEvents()), 1)
        events = getEvents(IObjectWillBeRemovedEvent)
        self.assertEqual(len(events), 1)
        self.assertEqual(events[0].oldName, 'foo')

        self.assertEqual(self.reflecto.manage_delObjects(('foo',)), None)
        events = getEvents()
        self.assertEqual(len(events), 4)
        self.assertTrue(IObjectWillBeRemovedEvent.providedBy(events[1]))

        self.assertTrue(IObjectRemovedEvent.providedBy(events[2]))
        self.assertEqual(events[2].oldName, 'foo')

        self.assertTrue(IContainerModifiedEvent.providedBy(events[3]))
        self.assertTrue(events[3].object is self.reflecto)
Esempio n. 21
0
    def test_register_available_tiles_record(self):
        registry = getUtility(IRegistry)
        record = 'collective.cover.controlpanel.ICoverSettings.available_tiles'

        eventtesting.setUp()

        # calling the handler here should have no effect as we are running the
        # latest profile version
        eventtesting.clearEvents()
        register_available_tiles_record(self.portal)
        events = eventtesting.getEvents(IRecordAddedEvent)
        self.assertEqual(len(events), 0)

        # now we delete the record and rerun the handler to verify the record
        # was added
        del registry.records[record]
        eventtesting.clearEvents()
        register_available_tiles_record(self.portal)
        events = eventtesting.getEvents(IRecordAddedEvent)
        self.assertNotEqual(len(events), 0)
        self.assertIn(record, registry.records)
        eventtesting.clearEvents()
Esempio n. 22
0
 def test_send_mail_journalized(self, browser):
     eventtesting.clearEvents()
     browser.login().visit(self.file_, view='send-mail-form')
     browser.fill({'Recipients': '*****@*****.**',
                   'Comment': 'Test'})
     browser.find('Send').click()
     events = [e for e in eventtesting.getEvents()
               if IJournalEntryEvent.providedBy(e)]
     self.assertEqual(1, len(events))
     self.assertIn(
         '*****@*****.**',
         self.file_.translate(events[0].action))
     self.assertEqual(u'Test', events[0].comment)
 def test_payment_event_content(self):
     """Check that the MollieIdealPaymentEvent has the content we need."""
     request = TestRequest(
         form=dict(transaction_id=self.transaction_id))
     payment_view = getMultiAdapter((self.foo, request),
                                    name='report_multiple_payment_status')
     payment_view()
     payment_events = [event for event in eventtesting.getEvents()
                       if IMollieIdealPaymentEvent.providedBy(event)]
     event = payment_events[0]
     self.assertEqual(event.context, self.foo)
     self.assertEqual(event.request, request)
     self.assertEqual(event.transaction_id, self.transaction_id)
Esempio n. 24
0
    def test_register_styles_record(self):
        registry = getUtility(IRegistry)
        record = 'collective.cover.controlpanel.ICoverSettings.styles'

        eventtesting.setUp()

        # calling the handler here should have no effect as we are running the
        # latest profile version
        eventtesting.clearEvents()
        register_styles_record(self.portal)
        events = eventtesting.getEvents(IRecordAddedEvent)
        self.assertEqual(len(events), 0)

        # now we delete the record and rerun the handler to verify the record
        # was added
        del registry.records[record]
        eventtesting.clearEvents()
        register_styles_record(self.portal)
        events = eventtesting.getEvents(IRecordAddedEvent)
        self.assertNotEqual(len(events), 0)
        self.assertIn(record, registry.records)
        eventtesting.clearEvents()
Esempio n. 25
0
def test_uncontained():
    item = Item()
    container = {u'foo': item}
    x, event = containedEvent(item, container, u'foo')

    assert item.__parent__ is container
    assert item.__name__ == u'foo'

    uncontained(item, container, u'foo')
    assert item.__parent__ is None
    assert item.__name__ is None

    assert len(getEvents(IObjectRemovedEvent)) == 1

    event = getEvents(IObjectRemovedEvent)[-1]
    assert event.object is item
    assert event.oldParent is container
    assert event.oldName == u'foo'
    assert event.newParent is None
    assert event.newName is None

    assert len(getEvents(IObjectModifiedEvent)) == 1
    assert getEvents(IObjectModifiedEvent)[-1].object is container

    # Events are never triggered twice
    uncontained(item, container, u'foo')
    assert len(getEvents(IObjectRemovedEvent)) == 1
    assert len(getEvents(IObjectModifiedEvent)) == 1

    item.__parent__, item.__name__ = container, None
    uncontained(item, container, u'foo')
    assert len(getEvents(IObjectRemovedEvent)) == 1
    assert len(getEvents(IObjectModifiedEvent)) == 2

    item.__parent__, item.__name__ = None, u'bar'
    uncontained(item, container, u'foo')
    assert len(getEvents(IObjectRemovedEvent)) == 1
    assert len(getEvents(IObjectModifiedEvent)) == 3
Esempio n. 26
0
    def test_event(self):
        u = IntIds("_ds_id")

        obj = P()
        stub = ConnectionStub()
        stub.add(obj)
        assert_that(stub.db(), is_(stub))

        assert_that(obj, 
                    has_property('_p_jar', is_(stub)))

        count = 1
        assert_that(calling(u.getId).with_args(obj), raises(KeyError))
        assert_that(calling(u.getId).with_args(P()), raises(KeyError))

        assert_that(u.queryId(obj), is_(none()))
        assert_that(u.queryId(obj, 42), is_(42))
        assert_that(u.queryId(P(), 42), is_(42))
        assert_that(u.queryObject(42), is_(none()))
        assert_that(u.queryObject(42, obj), is_(obj))

        uid = u.register(obj)
        assert_that(u.getObject(uid), is_(obj))
        assert_that(u.queryObject(uid), is_(obj))
        assert_that(u.getId(obj), is_(uid))
        assert_that(u.queryId(obj), is_(uid))
        assert_that(eventtesting.getEvents(IIdAddedEvent), has_length(count))

        uid2 = u.register(obj)
        assert_that(uid, is_(uid2))

        u.unregister(obj)
        assert_that(calling(u.getObject).with_args(uid), raises(KeyError))
        assert_that(calling(u.getId).with_args(obj), raises(KeyError))
        assert_that(eventtesting.getEvents(IIdRemovedEvent), has_length(count))

        next_id = u._v_nextid
        assert_that(u.randomize(), is_not(next_id))
Esempio n. 27
0
def test_replace():
    """If we try to replace an item without deleting it first, we'll get
    an error.
    """
    container = {}

    # We create a first item
    item = Item()
    setitem(container, container.__setitem__, u'c', item)

    # We try to override
    with pytest.raises(KeyError):
        setitem(container, container.__setitem__, u'c', [])

    # We have to delete to replace a key
    del container[u'c']
    setitem(container, container.__setitem__, u'c', [])

    assert len(getEvents(IObjectAddedEvent)) == 2
    assert len(getEvents(IObjectModifiedEvent)) == 2

    # we clean our test.
    clearEvents()
Esempio n. 28
0
def test_interface_providing():
    """If the object implements `ILocation`, but not `IContained`, set it's
    `__parent__` and `__name__` attributes *and* declare that it
    implements `IContained`.
    """
    container = {}

    item = Location()
    assert not IContained.providedBy(item)

    setitem(container, container.__setitem__, u'l', item)
    assert container[u'l'] is item
    assert item.__parent__ is container
    assert item.__name__ == u'l'
    assert IContained.providedBy(item)

    # We get added and modification events:
    assert len(getEvents(IObjectAddedEvent)) == 1
    assert len(getEvents(IObjectModifiedEvent)) == 1

    # If the object doesn't even implement `ILocation`, put a
    # `ContainedProxy` around it:
    item = []
    setitem(container, container.__setitem__, u'i', item)
    assert container[u'i'] == []
    assert not container[u'i'] is item

    item = container[u'i']
    assert item.__parent__ is container
    assert item.__name__ == u'i'

    assert IContained.providedBy(item)
    assert len(getEvents(IObjectAddedEvent)) == 2
    assert len(getEvents(IObjectModifiedEvent)) == 2

    # we clean our test.
    clearEvents()
Esempio n. 29
0
    def test_register_styles_record(self):
        registry = getUtility(IRegistry)
        record = 'collective.cover.controlpanel.ICoverSettings.styles'

        eventtesting.setUp()

        # just delete the existing record and rerun the handler to verify it
        # was added again
        del registry.records[record]
        eventtesting.clearEvents()
        register_styles_record(self.portal)
        events = eventtesting.getEvents(IRecordAddedEvent)
        self.assertNotEqual(len(events), 0)
        self.assertIn(record, registry.records)
        eventtesting.clearEvents()
Esempio n. 30
0
    def testDeleteEvents(self):
        self.assertRaises(KeyError, self.reflecto.manage_delObjects,
                          ('monty', ))
        self.assertEqual(len(getEvents()), 0)

        self.assertRaises(KeyError, self.reflecto.manage_delObjects, (
            'foo',
            'monty',
        ))
        self.assertEqual(len(getEvents()), 1)
        events = getEvents(IObjectWillBeRemovedEvent)
        self.assertEqual(len(events), 1)
        self.assertEqual(events[0].oldName, 'foo')

        self.assertEqual(self.reflecto.manage_delObjects(('foo', )), None)
        events = getEvents()
        self.assertEqual(len(events), 4)
        self.assertTrue(IObjectWillBeRemovedEvent.providedBy(events[1]))

        self.assertTrue(IObjectRemovedEvent.providedBy(events[2]))
        self.assertEqual(events[2].oldName, 'foo')

        self.assertTrue(IContainerModifiedEvent.providedBy(events[3]))
        self.assertTrue(events[3].object is self.reflecto)
Esempio n. 31
0
    def test_accept_token_view(self):
        token_id, token_url = self.util.generate_new_token(usage_limit=1)
        self.assertTrue(self.util.valid(token_id))

        view = getMultiAdapter((self.portal, self.request), name=u"accept-token")
        url = view.publishTraverse(self.request, token_id)()
        self.assertEqual(url, self.portal.absolute_url())
        self.assertFalse(self.util.valid(token_id))
        events = eventtesting.getEvents(ITokenAccepted)
        self.assertEqual(len(events), 1)
        self.assertEqual(events[0].token_id, token_id)

        token_id, token_url = self.util.generate_new_token(redirect_path="a/b/c")
        url = view.publishTraverse(self.request, token_id)()
        self.assertEqual(url, self.portal.absolute_url() + "/a/b/c")
Esempio n. 32
0
    def test_automatic_purging(self):
        # z3c.caching must purge objects automatically on modified,
        # moved, renamed or removed; testing the whole enchilada is out
        # of the scope of this package
        from z3c.caching.interfaces import IPurgeEvent
        from zope.component import eventtesting
        from zope.event import notify
        from zope.lifecycleevent import ObjectModifiedEvent
        eventtesting.setUp()

        # modifying the poll must fire a Purge event
        notify(ObjectModifiedEvent(self.poll))
        events = eventtesting.getEvents()
        # XXX: Purge event is fired more than once
        #      https://community.plone.org/t/6411?u=hvelarde
        self.assertEventFiredOnce(IPurgeEvent, events)
 def test_update_via_adapter(self):
     f = Foo()
     request = TestRequest()
     v = BarV(f, request)
     # check adapter
     self.assertEqual(f.foo, u'Foo foo')
     a = IBar(f)
     self.assertEqual(a.bar, u'Foo foo')
     # update
     request.form[Update] = ''
     request.form['field.bar'] = u'r bar'
     message = v.update()
     self.assertTrue(message.startswith('Updated '), message)
     self.assertEqual(a.bar, u'r bar')
     # wrong update
     self.assertFalse(getEvents())
Esempio n. 34
0
    def test_automatic_purging(self):
        # z3c.caching must purge objects automatically on modified,
        # moved, renamed or removed; testing the whole enchilada is out
        # of the scope of this package
        from z3c.caching.interfaces import IPurgeEvent
        from zope.component import eventtesting
        from zope.event import notify
        from zope.lifecycleevent import ObjectModifiedEvent
        eventtesting.setUp()

        # modifying the poll must fire a Purge event
        notify(ObjectModifiedEvent(self.poll))
        events = eventtesting.getEvents()
        # XXX: Purge event is fired more than once
        #      https://community.plone.org/t/6411?u=hvelarde
        self.assertEventFiredOnce(IPurgeEvent, events)
Esempio n. 35
0
    def testCopyEvents(self):
        cp = self.reflecto.manage_copyObjects(('foo', ))
        self.reflecto.manage_pasteObjects(cp)

        events = getEvents()
        self.assertEqual(len(events), 3)

        self.assertTrue(IObjectCopiedEvent.providedBy(events[0]))
        self.assertEqual(events[0].original.getId(), 'foo')
        self.assertEqual(events[0].object.getId(), 'copy_of_foo')

        self.assertTrue(IObjectClonedEvent.providedBy(events[1]))
        self.assertEqual(events[1].object.getId(), 'copy_of_foo')

        self.assertTrue(IContainerModifiedEvent.providedBy(events[2]))
        self.assertTrue(events[2].object is self.reflecto)
Esempio n. 36
0
    def testCopyEvents(self):
        cp = self.reflecto.manage_copyObjects(('foo',))
        self.reflecto.manage_pasteObjects(cp)

        events = getEvents()
        self.assertEqual(len(events), 3)

        self.assertTrue(IObjectCopiedEvent.providedBy(events[0]))
        self.assertEqual(events[0].original.getId(), 'foo')
        self.assertEqual(events[0].object.getId(), 'copy_of_foo')

        self.assertTrue(IObjectClonedEvent.providedBy(events[1]))
        self.assertEqual(events[1].object.getId(), 'copy_of_foo')

        self.assertTrue(IContainerModifiedEvent.providedBy(events[2]))
        self.assertTrue(events[2].object is self.reflecto)
Esempio n. 37
0
 def test_update_via_adapter(self):
     f = Foo()
     request = TestRequest()
     v = BarV(f, request)
     # check adapter
     self.assertEqual(f.foo, u'Foo foo')
     a = IBar(f)
     self.assertEqual(a.bar, u'Foo foo')
     # update
     request.form[Update] = ''
     request.form['field.bar'] = u'r bar'
     message = v.update()
     self.failUnless(message.startswith('Updated '), message)
     self.assertEqual(a.bar, u'r bar')
     # wrong update
     self.failIf(getEvents())
Esempio n. 38
0
 def assertImportZip(self, filename, imported, replace=False, update=False,
                     ignore_top_level=False):
     """Import a ZIP file.
     """
     clearEvents()
     request = TestRequest()
     importer = ZipImporter(self.root, request, {
             'replace_content': replace,
             'update_content': update,
             'ignore_top_level_content': ignore_top_level})
     with self.layer.open_fixture(filename) as source:
         importer.importStream(source)
     self.assertItemsEqual(
         map(lambda event:  '/'.join(event.object.getPhysicalPath()),
             getEvents(IContentImported)),
         imported)
     return importer
Esempio n. 39
0
    def test_accept_token_view(self):
        token_id, token_url = self.util.generate_new_token(usage_limit=1)
        self.assertTrue(self.util.valid(token_id))

        view = getMultiAdapter((self.portal, self.request),
                               name=u'accept-token')
        url = view.publishTraverse(self.request, token_id)()
        self.assertEqual(url, self.portal.absolute_url())
        self.assertFalse(self.util.valid(token_id))
        events = eventtesting.getEvents(ITokenAccepted)
        self.assertEqual(len(events), 1)
        self.assertEqual(events[0].token_id, token_id)

        token_id, token_url = self.util.generate_new_token(
            redirect_path='a/b/c')
        url = view.publishTraverse(self.request, token_id)()
        self.assertEqual(url, self.portal.absolute_url() + '/a/b/c')
Esempio n. 40
0
    def test_download_file_by_token_journal(self, browser):
        eventtesting.clearEvents()
        folder = create(Builder('folder').in_state('private'))
        file_ = create(Builder('file')
                       .with_dummy_content()
                       .within(folder))

        with self.assertRaises(Unauthorized):
            browser.visit(file_)

        downloadtoken = self.storage.add(file_, '*****@*****.**')
        url = self.storage.url(downloadtoken)
        transaction.commit()
        browser.open(url)
        events = [e for e in eventtesting.getEvents()
                  if IJournalEntryEvent.providedBy(e)]
        self.assertEqual(1, len(events))
        self.assertEqual(u'*****@*****.**', events[0].actor)
Esempio n. 41
0
def test_order_events():
    oc = OrderedBTreeContainer()

    oc['foo'] = 'bar'
    oc['baz'] = 'quux'
    oc['zork'] = 'grue'

    assert oc.keys() == ['foo', 'baz', 'zork']

    clearEvents()
    oc.updateOrder(['baz', 'foo', 'zork'])
    assert oc.keys() == ['baz', 'foo', 'zork']

    events = getEvents()
    assert [event.__class__.__name__ for event in events] == (
        ['ContainerModifiedEvent'])

    assert IObjectModifiedEvent.providedBy(events[0])
Esempio n. 42
0
    def test_disable_disabled_member(self, DT):
        """Test disabling an already disabled member. This should not happen
        often, but it still could."""
        DT.return_value = DateTime('2012/01/01')

        # first disable a member
        self.test_disable_enabled_member()

        # now let's say a month goes by and we get another notification from
        # IPN that this member is disabled
        DT.return_value = DateTime('2012/02/01')
        self.ipn.disable_member(
            email='*****@*****.**',
            product_id='1',
            trans_type='CANCEL',
        )

        # test event emitted
        events = list(set(eventtesting.getEvents(IMemberDisabledEvent)))
        self.assertEquals(len(events), 2)
        self.assertEquals(events[0].username, '*****@*****.**')
        self.assertEquals(events[1].username, '*****@*****.**')

        # test member history
        self.assert_member_history(
            username='******',
            history=[
                '2012/01/01 00:00:00|disable_member|1|CANCEL|'
                'removed from groups: ipn_1, ',
                '2012/02/01 00:00:00|disable_member|1|CANCEL|',
            ]
        )

        # test log output
        for record in self.log.records:
            self.assertNotIn(
                "Adding member '*****@*****.**' to Disabled group.",
                record.getMessage(),
            )

            self.assertNotIn(
                "Revoking member '*****@*****.**' the Member role.",
                record.getMessage(),
            )
Esempio n. 43
0
    def testCutEvents(self):
        cp = self.reflecto.manage_cutObjects(('foo', ))
        self.reflecto['subdir'].manage_pasteObjects(cp)

        events = getEvents()
        self.assertEqual(len(events), 4)

        self.assertTrue(IObjectWillBeMovedEvent.providedBy(events[0]))
        self.assertEqual(events[0].oldName, 'foo')
        self.assertEqual(events[0].oldParent, self.reflecto)
        self.assertEqual(events[0].newName, 'foo')
        self.assertEqual(events[0].newParent, self.reflecto['subdir'])

        self.assertTrue(IObjectMovedEvent.providedBy(events[1]))
        self.assertEqual(events[1].object.getId(), 'foo')

        self.assertTrue(IContainerModifiedEvent.providedBy(events[2]))
        self.assertEqual(events[2].object, self.reflecto)
        self.assertTrue(IContainerModifiedEvent.providedBy(events[3]))
        self.assertEqual(events[3].object, self.reflecto['subdir'])
Esempio n. 44
0
    def test_delete_tile_persistent_data(self):
        eventtesting.clearEvents()
        # First, let's assign an id to the tile and store some data
        self.tile.id = 'test-tile'
        data_mgr = ITileDataManager(self.tile)
        data_mgr.set({'test': 'data'})

        # We see that the data persists
        self.assertEqual(data_mgr.get(), {'test': 'data'})

        # Call the delete method
        self.tile.delete()

        # Now we should not see the stored data anymore
        self.assertEqual(data_mgr.get(), {})

        events = eventtesting.getEvents()

        # Finally, test that ObjectModifiedEvent was fired for the cover
        self.assertEqual(events[0].object, self.portal)
    def test_delete_tile_persistent_data(self):
        eventtesting.clearEvents()
        # First, let's store some data on the tile
        data_mgr = ITileDataManager(self.tile)
        data_mgr.set({'test': 'data'})

        # We see that the data persists
        self.assertIn('test', data_mgr.get())
        self.assertEqual(data_mgr.get()['test'], 'data')

        # Call the delete method
        self.tile.delete()

        # Now we should not see the stored data anymore
        self.assertNotIn('test', data_mgr.get())

        events = eventtesting.getEvents()

        # Finally, test that ObjectModifiedEvent was fired for the cover
        self.assertEqual(events[0].object, self.cover)
Esempio n. 46
0
    def test_delete_tile_persistent_data(self):
        eventtesting.clearEvents()
        # First, let's store some data on the tile
        data_mgr = ITileDataManager(self.tile)
        data_mgr.set({'test': 'data'})

        # We see that the data persists
        self.assertIn('test', data_mgr.get())
        self.assertEqual(data_mgr.get()['test'], 'data')

        # Call the delete method
        self.tile.delete()

        # Now we should not see the stored data anymore
        self.assertNotIn('test', data_mgr.get())

        events = eventtesting.getEvents()

        # Finally, test that ObjectModifiedEvent was fired for the cover
        self.assertEqual(events[0].object, self.cover)
Esempio n. 47
0
    def testCutEvents(self):
        cp = self.reflecto.manage_cutObjects(('foo',))
        self.reflecto['subdir'].manage_pasteObjects(cp)

        events = getEvents()
        self.assertEqual(len(events), 4)

        self.assertTrue(IObjectWillBeMovedEvent.providedBy(events[0]))
        self.assertEqual(events[0].oldName, 'foo')
        self.assertEqual(events[0].oldParent, self.reflecto)
        self.assertEqual(events[0].newName, 'foo')
        self.assertEqual(events[0].newParent, self.reflecto['subdir'])

        self.assertTrue(IObjectMovedEvent.providedBy(events[1]))
        self.assertEqual(events[1].object.getId(), 'foo')

        self.assertTrue(IContainerModifiedEvent.providedBy(events[2]))
        self.assertEqual(events[2].object, self.reflecto)
        self.assertTrue(IContainerModifiedEvent.providedBy(events[3]))
        self.assertEqual(events[3].object, self.reflecto['subdir'])
Esempio n. 48
0
def test_move_event():
    """If the item had a parent or name (as in a move or rename),
    we generate a move event, rather than an add event.
    """
    container = {}

    # We create a first item
    item = Item()
    setitem(container, container.__setitem__, u'c1', item)

    # Add operation are "moved" events.
    assert len(getEvents(IObjectMovedEvent)) == 1

    # We created an item already contained.
    item = Item()
    item.__parent__, item.__name__ = container, 'c2'
    setitem(container, container.__setitem__, u'c2', item)

    assert len(container) == 2
    assert len(getEvents(IObjectAddedEvent)) == 1
    assert len(getEvents(IObjectModifiedEvent)) == 1
    assert len(getEvents(IObjectMovedEvent)) == 1

    # We now rewrite 'c2' under another name
    # Thus, we created a move event : +1 modification +1 move.
    setitem(container, container.__setitem__, u'c3', item)

    assert len(container) == 3
    assert len(getEvents(IObjectAddedEvent)) == 1
    assert len(getEvents(IObjectModifiedEvent)) == 2
    assert len(getEvents(IObjectMovedEvent)) == 2

    # We also get the move hook called, but not the add hook:
    event = getEvents(IObjectMovedEvent)[-1]
    assert getattr(item, 'added', None) is None
    assert item.moved is event

    # we clean our test.
    clearEvents()
Esempio n. 49
0
    def _test_question_answered(self):
        context = self.portal.questions
        manager_name = 'plone.belowcontent'
        viewlet_name = 'question-add'
        layer = ISiyavulaWhatLayer
        viewlet = self._find_viewlet(context, manager_name, viewlet_name,
                                     layer)

        question = self._createQuestion()
        eventtesting.clearEvents()
        request = self.portal.REQUEST
        request.form[
            'siyavula.what.questionslist.form.submitted'] = 'submitted'
        request.form['questionid'] = question.getId()
        request.form['answer'] = 'first answer'
        request.form['action'] = 'add-answer'
        viewlet[0].update()

        events = eventtesting.getEvents(
            IObjectModifiedEvent, filter=lambda obj: IQuestion.providedBy(obj))
        self.assertTrue(len(events) > 0, 'Missing event.')
Esempio n. 50
0
 def test_update_no_update(self):
     c = C()
     request = TestRequest()
     v = EV(c, request)
     self.assertEqual(v.update(), '')
     self.assertEqual(c.foo, u'c foo')
     self.assertEqual(c.bar, u'c bar')
     self.assertEqual(c.a, u'c a')
     self.assertEqual(c.b, u'c b')
     self.assertEqual(c.getbaz(), u'c baz')
     request.form['field.foo'] = u'r foo'
     request.form['field.bar'] = u'r bar'
     request.form['field.a'] = u'r a'
     request.form['field.b'] = u'r b'
     request.form['field.getbaz'] = u'r baz'
     self.assertEqual(v.update(), '')
     self.assertEqual(c.foo, u'c foo')
     self.assertEqual(c.bar, u'c bar')
     self.assertEqual(c.a, u'c a')
     self.assertEqual(c.b, u'c b')
     self.assertEqual(c.getbaz(), u'c baz')
     self.failIf(getEvents())
Esempio n. 51
0
 def assertImportZip(self,
                     filename,
                     imported,
                     replace=False,
                     update=False,
                     ignore_top_level=False):
     """Import a ZIP file.
     """
     clearEvents()
     request = TestRequest()
     importer = ZipImporter(
         self.root, request, {
             'replace_content': replace,
             'update_content': update,
             'ignore_top_level_content': ignore_top_level
         })
     with self.layer.open_fixture(filename) as source:
         importer.importStream(source)
     self.assertItemsEqual(
         map(lambda event: '/'.join(event.object.getPhysicalPath()),
             getEvents(IContentImported)), imported)
     return importer
Esempio n. 52
0
    def testChangeTitle(self):
        container = self._TestView__newContext()
        document = Document()
        container['document'] = document

        from zope.dublincore.interfaces import IDCDescriptiveProperties

        class FauxDCDescriptiveProperties(object):
            implements(IDCDescriptiveProperties)

            __Security_checker__ = checker.Checker(
                {
                    "title": "zope.Public",
                }, {"title": "zope.app.dublincore.change"})

            def __init__(self, context):
                self.context = context

            def setTitle(self, title):
                self.context.title = title

            def getTitle(self):
                return self.context.title

            title = property(getTitle, setTitle)

        ztapi.provideAdapter(IDocument, IDCDescriptiveProperties,
                             FauxDCDescriptiveProperties)

        fc = self._TestView__newView(container)

        dc = IDCDescriptiveProperties(document)

        fc.request.form.update({'retitle_id': 'document', 'new_value': 'new'})
        fc.changeTitle()
        events = getEvents()
        self.assertEquals(dc.title, 'new')
        self.failIf('title' not in events[-1].descriptions[0].attributes)
Esempio n. 53
0
    def test_delete_tile_removes_persistent_data(self):
        # https://github.com/scmos.scmos.cover/issues/765
        from scmos.cover.config import CONFIGURATION_PREFIX
        from scmos.cover.config import PERMISSIONS_PREFIX
        from zope.annotation import IAnnotations
        from zope.component import eventtesting
        from zope.lifecycleevent import IObjectModifiedEvent
        eventtesting.setUp()
        annotations = IAnnotations(self.tile.context)

        data_mgr = ITileDataManager(self.tile)
        data_mgr.set({'test': 'data'})
        self.assertIn('test', data_mgr.get())
        self.assertEqual(data_mgr.get()['test'], 'data')

        permissions = getMultiAdapter((self.cover, self.request, self.tile),
                                      ITilesPermissions)
        permissions.set_allowed_edit('masters_of_the_universe')
        self.assertIn(PERMISSIONS_PREFIX + '.test', annotations)

        configuration = getMultiAdapter((self.cover, self.request, self.tile),
                                        ITilesConfigurationScreen)
        configuration.set_configuration({'uuid': 'c1d2e3f4g5jrw'})
        self.assertIn(CONFIGURATION_PREFIX + '.test', annotations)

        # Call the delete method
        eventtesting.clearEvents()
        self.tile.delete()

        # Now we should not see the persistent data anymore
        self.assertNotIn('test', data_mgr.get())
        self.assertNotIn(PERMISSIONS_PREFIX + '.test', annotations)
        self.assertNotIn(CONFIGURATION_PREFIX + '.test', annotations)

        # Finally, test that ObjectModifiedEvent was fired for the cover
        events = eventtesting.getEvents()
        self.assertEqual(len(events), 1)
        self.assertTrue(IObjectModifiedEvent.providedBy(events[0]))
Esempio n. 54
0
 def testChangingTitleFiresNoEvent(self):
     plugin = self._makeOne()
     self.assertEqual(eventtesting.getEvents(), [])
     plugin.manage_changeProperties(title='Foo')
     self.assertEqual(eventtesting.getEvents(), [])