def test_field_event(self):
     from zope.schema import Text
     from zope.interface.verify import verifyObject
     from zope.event import subscribers
     from zope.schema.interfaces import IFieldUpdatedEvent
     from zope.schema.fieldproperty import FieldUpdatedEvent
     log = []
     subscribers.append(log.append)
     self.assertEqual(log, [])
     field = Text(
         __name__='testing',
         description=u'DESCRIPTION',
         default=u'DEFAULT',
         readonly=True,
         required=True,
     )
     self.assertEqual(len(log), 6)
     event = log[0]
     self.assertTrue(isinstance(event, FieldUpdatedEvent))
     self.assertTrue(verifyObject(IFieldUpdatedEvent, event))
     self.assertEqual(event.object, field)
     self.assertEqual(event.old_value, 0)
     self.assertEqual(event.new_value, 0)
     self.assertEqual([ev.field.__name__ for ev in log], [
         'min_length', 'max_length', 'title', 'description', 'required',
         'readonly'
     ])
     # BBB, but test this works.
     self.assertEqual(event.inst, field)
     marker = object()
     event.inst = marker
     self.assertEqual(event.inst, marker)
     self.assertEqual(event.object, marker)
Пример #2
0
 def test_not_empty(self):
     from zope.event import subscribers
     dummy = []
     subscribers.append(dummy.append)
     event = object()
     self._callFUT(event)
     self.assertEqual(dummy, [event])
Пример #3
0
 def test_not_empty(self):
     from zope.event import subscribers
     dummy = []
     subscribers.append(dummy.append)
     event = object()
     self._callFUT(event)
     self.assertEqual(dummy, [event])
    def test_field_event_update(self):
        from zope.schema import Text

        from zope.event import subscribers
        from zope.schema.fieldproperty import FieldUpdatedEvent

        field = Text(__name__="testing", description=u"DESCRIPTION", default=u"DEFAULT", required=True)
        prop = self._makeOne(field=field)

        class Foo(object):
            testing = prop

        foo = Foo()

        log = []
        subscribers.append(log.append)
        foo.testing = u"Bar"
        foo.testing = u"Foo"
        self.assertEqual(len(log), 2)
        event = log[1]
        self.assertTrue(isinstance(event, FieldUpdatedEvent))
        self.assertEqual(event.inst, foo)
        self.assertEqual(event.field, field)
        self.assertEqual(event.old_value, u"Bar")
        self.assertEqual(event.new_value, u"Foo")
 def test_iconifiedchangedevent(self):
     from zope.event import subscribers
     dummy = []
     subscribers.append(dummy.append)
     event = IconifiedChangedEvent(object(), 'old', 'new')
     self._notify(event)
     self.assertEqual(dummy, [event])
Пример #6
0
 def test_field_event(self):
     # fieldproperties are everywhere including in field themselfs
     # so event are triggered
     from zope.schema import Text
     from zope.schema._compat import u
     from zope.event import subscribers
     from zope.schema.fieldproperty import FieldUpdatedEvent
     log = []
     subscribers.append(log.append)
     self.assertEqual(log, [])
     field = Text(
         __name__='testing',
         description=u('DESCRIPTION'),
         default=u('DEFAULT'),
         readonly=True,
         required=True,
     )
     self.assertEqual(len(log), 6)
     # these are fieldproperties in the field
     self.assertEqual(
         [ev.field.__name__ for ev in log],
         ['min_length', 'max_length', 'title', 'description', 'required', 'readonly'])
     event = log[0]
     self.assertTrue(isinstance(event, FieldUpdatedEvent))
     self.assertEqual(event.inst, field)
     self.assertEqual(event.old_value, 0)
     self.assertEqual(event.new_value, 0)
    def test_field_event(self):
        # fieldproperties are everywhere including in field themselfs
        # so event are triggered
        from zope.schema import Text

        from zope.event import subscribers
        from zope.schema.fieldproperty import FieldUpdatedEvent
        log = []
        subscribers.append(log.append)
        self.assertEqual(log, [])
        field = Text(
            __name__='testing',
            description=u'DESCRIPTION',
            default=u'DEFAULT',
            readonly=True,
            required=True,
        )
        self.assertEqual(len(log), 6)
        # these are fieldproperties in the field
        self.assertEqual([ev.field.__name__ for ev in log], [
            'min_length', 'max_length', 'title', 'description', 'required',
            'readonly'
        ])
        event = log[0]
        self.assertTrue(isinstance(event, FieldUpdatedEvent))
        self.assertEqual(event.object, field)
        self.assertEqual(event.old_value, 0)
        self.assertEqual(event.new_value, 0)
    def test_field_event_update(self):
        from zope.schema import Text

        from zope.event import subscribers
        from zope.schema.fieldproperty import FieldUpdatedEvent
        field = Text(
            __name__='testing',
            description=u'DESCRIPTION',
            default=u'DEFAULT',
            required=True,
        )
        prop = self._makeOne(field=field)

        class Foo(object):
            testing = prop

        foo = Foo()

        log = []
        subscribers.append(log.append)
        foo.testing = u'Bar'
        foo.testing = u'Foo'
        self.assertEqual(len(log), 2)
        event = log[1]
        self.assertTrue(isinstance(event, FieldUpdatedEvent))
        self.assertEqual(event.object, foo)
        self.assertEqual(event.field, field)
        self.assertEqual(event.old_value, u'Bar')
        self.assertEqual(event.new_value, u'Foo')
Пример #9
0
    def __init__(self):
        blank = urwid.Divider()
        self.txt = urwid.Text(('text', ''), align='left')
        listbox_content = [self.txt]

        listbox = urwid.ListBox(urwid.SimpleListWalker(listbox_content))

        super().__init__(listbox)

        subscribers.append(self._onevent)
Пример #10
0
    def __init__(self):

        cols = urwid.Columns(
            [('weight', 4, KeyListWidget()),
             ('fixed', 1, urwid.AttrWrap(urwid.SolidFill(u'\u2502'), 'line')),
             ('weight', 6, ContentDisplayPanel())],
            dividechars=1,
            focus_column=0)

        super().__init__(urwid.AttrWrap(cols, 'bg'))

        subscribers.append(self._onevent)
Пример #11
0
    def test_utility_events(self):
        from zope.event import subscribers
        old_subscribers = subscribers[:]
        subscribers[:] = []

        test_object = self.tests.U1(1)
        def log_event(event):
            self.assertEqual(event.object.component, test_object)
        subscribers.append(log_event)
        self.components.registerUtility(test_object)

        subscribers[:] = old_subscribers
Пример #12
0
def init():
    cfg = external_configuration(
        config.plugin.mailman_rest_event.configuration)
    event_webhook_url = cfg.get("general", "webhook_url", fallback=None)
    try:
        timeout = int(cfg.get("general", "timeout", fallback=2))
    except:
        timeout = 2
    auth_user = cfg.get("auth", "user", fallback=None)
    auth_key = cfg.get("auth", "key", fallback=None)

    auth = None
    if auth_user and auth_key:
        auth = (auth_user, auth_key)

    if not event_webhook_url:
        logger.info("Webhook URL not set, will not be sending events")
        return

    logger.info(f"Webhook URL: {event_webhook_url}")

    handlers = {
        SubscriptionEvent: (lambda evt: {
            "event": "user_subscribed",
            "mlist": mlist_to_json(evt.mlist),
            "member": member_to_json(evt.member)
        }),
        UnsubscriptionEvent: (lambda evt: {
            "event": "user_unsubscribed",
            "mlist": mlist_to_json(evt.mlist),
            "member": member_to_json(evt.member)
        }),
        HandledMessageEvent: (lambda evt: {
            "event": "new_message",
            "mlist": mlist_to_json(evt.mlist),
            "message": message_to_obj(evt.msg)
        }),
    }

    def handle_event(evt):
        t = type(evt)
        if t in handlers:
            try:
                logger.info(f"Posting: {type(evt)}")
                result = requests.post(event_webhook_url,
                                       json=handlers[t](evt),
                                       auth=auth,
                                       timeout=timeout)
            except Exception as e:
                logger.error(f"Failed to post: {e}")

    subscribers.append(handle_event)
Пример #13
0
    def test_utility_events(self):
        from zope.event import subscribers
        old_subscribers = subscribers[:]
        subscribers[:] = []

        test_object = U1(1)

        def log_event(event):
            self.assertEqual(event.object.component, test_object)

        subscribers.append(log_event)
        self.components.registerUtility(test_object)

        subscribers[:] = old_subscribers
Пример #14
0
 def test_close_w_broken_subscriber(self):
     # See: https://github.com/zopefoundation/Zope/issues/16
     from zope.event import subscribers
     root, folder = self._makeRootAndFolder()
     r = self._makeOne(root)
     r.other['foo'] = 'Foo'
     BEFORE = subscribers[:]
     def _broken(event):
         raise ValueError("I'm broken")
     subscribers.append(_broken)
     try:
         self.assertRaises(ValueError, r.close)
     finally:
         subscribers[:] = BEFORE
     self.assertEqual(r.other, {})
Пример #15
0
    def setUp(self):
        self.workspace = DummyWorkspace('test')
        self.workspace.storage = 'dummy_storage'

        # register utilities
        zope.component.getSiteManager().registerUtility(
            DummyStorageUtility(), IStorageUtility, name='dummy_storage')
        zope.component.getSiteManager().registerUtility(
            LegacyDummyStorageUtility(), IStorageUtility,
            name='legacy_dummy_storage')

        from zope.event import subscribers
        self._old_subscribers = subscribers[:]
        subscribers[:] = []
        self.subscribers = []
        subscribers.append(self.subscribers.append)
Пример #16
0
    def start_execution(self):
        # subscriber events_handle
        subscribers.append(self.__event_handle)

        self.start_timestamp = datetime.now()
        # UPDATE DATETIME DEADLINE

        logging.info("<Scheduler Manager {}_{}>: - Starting Execution.".format(self.loader.cudalign_task.task_id,
                                                                               self.loader.execution_id))
        logging.info("")

        self.__start_dispatcher()

        # Call checkers loop
        self.__checkers()

        self.__terminate_dispatcher()

        self.__end_of_execution()
    def test_wo_existing_session(self):
        from zope.event import subscribers
        _handled = []
        subscribers.append(_handled.append)

        container = object()
        request = _Request()
        response = request.RESPONSE = _ZopeResponse()
        self._setUpUtility()

        self._callFUT(container, request)

        self.assertTrue(response.set_cookie is not response.setCookie.im_func)
        self.assertEqual(request._lazy.keys(), ['SESSION'])
        self.assertEqual(len(_handled), 0)
        session = request._lazy['SESSION']()
        self.assertEqual(len(_handled), 1)
        event = _handled[0]
        self.assertTrue(event.session is session)

        session['foo'] = 'bar'
        self.assertEqual(response.cookies.keys(), [])

        session['baz'] = 'bam'
        self.assertEqual(response.cookies.keys(), [])

        self.assertEqual(response.counter, 0)  # cookie not set
        self.assertEqual(len(request._response_callbacks), 1)
        request._response_callbacks[0](request, response)
        self.assertEqual(response.counter, 1)
        self.assertEqual(response.cookies.keys(), ['COOKIE'])

        del _handled[:]
        new_request = _Request()
        new_request.cookies['COOKIE'] = response.cookies['COOKIE']
        new_response = new_request.RESPONSE = _ZopeResponse()

        self._callFUT(container, new_request)

        self.assertEqual(len(_handled), 0)
        session = new_request._lazy['SESSION']()
        self.assertEqual(len(_handled), 0)
Пример #18
0
    def test_wo_existing_session(self):
        from zope.event import subscribers
        _handled = []
        subscribers.append(_handled.append)

        container = object()
        request = _Request()
        response = request.RESPONSE = _ZopeResponse()
        self._setUpUtility()

        self._callFUT(container, request)

        self.assertTrue(response.set_cookie is not response.setCookie.im_func)
        self.assertEqual(request._lazy.keys(), ['SESSION'])
        self.assertEqual(len(_handled), 0)
        session = request._lazy['SESSION']()
        self.assertEqual(len(_handled), 1)
        event = _handled[0]
        self.assertTrue(event.session is session)

        session['foo'] = 'bar'
        self.assertEqual(response.cookies.keys(), [])

        session['baz'] = 'bam'
        self.assertEqual(response.cookies.keys(), [])

        self.assertEqual(response.counter, 0)  # cookie not set
        self.assertEqual(len(request._response_callbacks), 1)
        request._response_callbacks[0](request, response)
        self.assertEqual(response.counter, 1)
        self.assertEqual(response.cookies.keys(), ['COOKIE'])

        del _handled[:]
        new_request = _Request()
        new_request.cookies['COOKIE'] = response.cookies['COOKIE']
        new_response = new_request.RESPONSE = _ZopeResponse()

        self._callFUT(container, new_request)

        self.assertEqual(len(_handled), 0)
        session = new_request._lazy['SESSION']()
        self.assertEqual(len(_handled), 0)
Пример #19
0
    def testDeletion(self):
        from zope.event import subscribers
        tree = BTreeContainer()
        item = Contained()
        tree['42'] = item
        events = []
        def subscriber(event):
            events.append(event)
            # events should happen after the deletion, not before)
            self.assertEqual(len(tree), 0)
            self.assertEqual(list(tree), [])
        subscribers.append(subscriber)

        del tree['42']
        self.assertEqual(item.__name__, None)
        self.assertEqual(item.__parent__, None)

        self.assertEqual(len(events), 2)
        self.assertTrue(IObjectRemovedEvent.providedBy(events[0]))
        self.assertTrue(IContainerModifiedEvent.providedBy(events[1]))
    def test_field_event(self):
        from zope.schema import Text

        from zope.event import subscribers
        from zope.schema.fieldproperty import FieldUpdatedEvent

        log = []
        subscribers.append(log.append)
        self.assertEqual(log, [])
        field = Text(__name__="testing", description=u"DESCRIPTION", default=u"DEFAULT", readonly=True, required=True)
        self.assertEqual(len(log), 6)
        event = log[0]
        self.assertTrue(isinstance(event, FieldUpdatedEvent))
        self.assertEqual(event.inst, field)
        self.assertEqual(event.old_value, 0)
        self.assertEqual(event.new_value, 0)
        self.assertEqual(
            [ev.field.__name__ for ev in log],
            ["min_length", "max_length", "title", "description", "required", "readonly"],
        )
Пример #21
0
 def test_field_event(self):
     from zope.schema import Text
     from zope.schema._compat import u
     from zope.event import subscribers
     from zope.schema.fieldproperty import FieldUpdatedEvent
     log = []
     subscribers.append(log.append)
     self.assertEqual(log, [])
     field = Text(
         __name__='testing',
         description=u('DESCRIPTION'),
         default=u('DEFAULT'),
         readonly=True,
         required=True,
     )
     self.assertEqual(len(log), 6)
     event = log[0]
     self.assertTrue(isinstance(event, FieldUpdatedEvent))
     self.assertEqual(event.inst, field)
     self.assertEqual(event.old_value, 0)
     self.assertEqual(event.new_value, 0)
     self.assertEqual(
         [ev.field.__name__ for ev in log],
         ['min_length', 'max_length', 'title', 'description', 'required', 'readonly'])
Пример #22
0
    def test_field_event(self):
        from zope.schema import Text

        from zope.event import subscribers
        from zope.schema.fieldproperty import FieldUpdatedEvent
        log = []
        subscribers.append(log.append)
        self.assertEqual(log, [])
        field = Text(
            __name__='testing',
            description=u'DESCRIPTION',
            default=u'DEFAULT',
            readonly=True,
            required=True,
        )
        self.assertEqual(len(log), 6)
        event = log[0]
        self.assertTrue(isinstance(event, FieldUpdatedEvent))
        self.assertEqual(event.inst, field)
        self.assertEqual(event.old_value, 0)
        self.assertEqual(event.new_value, 0)
        self.assertEqual(
            [ev.field.__name__ for ev in log],
            ['min_length', 'max_length', 'title', 'description', 'required', 'readonly'])
Пример #23
0
def setup():
    from jimfulton_research.db import get_db
    from .resources import setup as content_setup

    db = get_db()
    with db.transaction() as connection:
        root = connection.root

        try:
            content = root.content
        except AttributeError:
            content = Folder()
            root.content = content
            content_setup(content)
            transaction.commit()

        # Setup the threadwatcher to get batches of changes
        content_root = Path(getfile(get_db)).parent / 'contents'
        assert content_root.exists()
        interval = 1
        watcher = ThreadRunner(
            handler_watcher,
            content_root,
            enabled=True,
            interval=interval,
        )

        # Wire up zope.event subscriber for new batches, notification
        # comes from the thread
        subscribers.append(partial(
            handle_newbatch,
            content,
        ), )

        app = App(content=content, watcher=watcher, db=db)
        yield app
Пример #24
0
 def __init__(self):
     self._scheduled = False
     self._events = []
     self._origin = AdapterRegistry()
     self._field = AdapterRegistry()
     subscribers.append(self.watch)
Пример #25
0
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Component Architecture-specific event dispatching

Based on subscription adapters / handlers.
"""

from zope.event import subscribers as event_subscribers

from zope.interface.interfaces import IObjectEvent
from zope.component._api import subscribers as component_subscribers
from zope.component._declaration import adapter


def dispatch(*event):
    component_subscribers(event, None)


event_subscribers.append(dispatch)


@adapter(IObjectEvent)
def objectEventNotify(event):
    """Dispatch ObjectEvents to interested adapters.
    """
    component_subscribers((event.object, event), None)
Пример #26
0
def init():
    if zerodb_autoreindex_dispatcher not in subscribers:
        subscribers.append(zerodb_autoreindex_dispatcher)
Пример #27
0
def subscribe():
    subscribers.append(stacker)
    yield stacker
    subscribers.remove(stacker)
    events_queue.clear()
Пример #28
0
    def __init__(self):

        self._contents = []
        self._update_list_box()

        subscribers.append(self._onevent)
Пример #29
0
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Component Architecture-specific event dispatching

Based on subscription adapters / handlers.
"""

from zope.event import subscribers as event_subscribers

from zope.component.interfaces import IObjectEvent
from zope.component._api import subscribers as component_subscribers
from zope.component._declaration import adapter


def dispatch(*event):
    component_subscribers(event, None)

event_subscribers.append(dispatch)


@adapter(IObjectEvent)
def objectEventNotify(event):
    """Dispatch ObjectEvents to interested adapters.
    """
    component_subscribers((event.object, event), None)
Пример #30
0
def init():
    if zerodb_autoreindex_dispatcher not in subscribers:
        subscribers.append(zerodb_autoreindex_dispatcher)
Пример #31
0
def setup_dispatcher():
    if dispatch not in event_subscribers:
        event_subscribers.append(dispatch)