Source

trac-mq / t11148 / t11148_r11782_IEntityChangeListener_extends_with_prefix.diff

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
# HG changeset patch
# Parent 8d0c3223a81860370202a5184fa812081129fe43
An alternative proposal is based on ticket comments and google groups discussion. The proposal introduces IEntityChangeListener interface and extends_with_prefix instruction.

diff -r 8d0c3223a818 trac/core.py
--- a/trac/core.py	Thu Apr 18 14:30:21 2013 +0000
+++ b/trac/core.py	Thu Apr 18 21:56:04 2013 -0500
@@ -165,8 +165,14 @@
 
         locals_.setdefault('_implements', []).extend(interfaces)
 
+implements = Component.implements
 
-implements = Component.implements
+def extends_with_prefix(prefix):
+    def prefix_decorator(class_):
+        class_._extends_with_prefix = prefix
+        return class_
+
+    return prefix_decorator
 
 
 class ComponentManager(object):
@@ -236,3 +242,92 @@
         with the given class will not be available.
         """
         return True
+
+class NotificationChangeInfo(object):
+    def __init__(self, comment, author):
+        self.comment = comment
+        self.author = author
+
+class IEntityChangeListener(Interface):
+    """Extension point interface for components that require notification
+    when model entities are created, modified, or deleted.
+
+    * entity: parameter is instance of the a entity e.g. ticket, milestone
+    etc.
+    * changeinfo: is instance of NotificationChangeInfo. The changeinfo
+    parameter content depends on an entity type and may be None.
+    """
+
+    def entity_created(entity, changeinfo = None):
+        """
+        Called when an entity is created.
+        """
+
+    def entity_changed(entity, old_values, changeinfo = None):
+        """Called when an entity is modified.
+
+        `old_values` is a dictionary containing the previous values of the
+        entity properties that changed. Properties are specific for entity
+        type.
+        """
+
+    def entity_deleted(entity, changeinfo = None):
+        """Called when an entity is deleted."""
+
+    def entity_reparented(entity, changeinfo = None):
+        """Called when an entity has been re-parented."""
+
+class ListenerNotifier(Component):
+    METHOD_DELIMITER = "_"
+
+    def _get_listeners_for_interface(self, interface):
+        """Return a list of components that declare to implement the
+        extension point interface.
+        """
+        classes = ComponentMeta._registry.get(interface, ())
+        components = [self.env[cls] for cls in classes]
+        return [c for c in components if c]
+
+    def notify(self, method, *args):
+        interface = method.im_class
+        method_name = method.__name__
+        if interface is None:
+            raise TracError(
+                "Notification interface can not be None. " +
+                "Target method name is %s" % method_name)
+
+        if hasattr(interface, "_extends_with_prefix"):
+            prefix = interface._extends_with_prefix
+            if prefix:
+                prefixed_method_name =  self._get_prefixed_method_name(
+                    method_name, prefix)
+
+        for listener in self._get_listeners_for_interface(interface):
+            if hasattr(listener, prefixed_method_name):
+                method_to_call = prefixed_method_name
+            else:
+                method_to_call = method_name
+            getattr(listener, method_to_call)(*args)
+
+        #TBD: we can also call listeners implemented IEntityChangeListener here
+        #if community will agree that generic event listeners support is needed
+
+    def _get_prefixed_method_name(self, method_name, prefix):
+        """
+        Replaces the first method name part with prefix. For example,
+        for method_name "entity_created" and prefix "xxx" return
+        "xxx_created",
+        for input method_name "created" and prefix "xxx" return
+        "xxx_created",
+        """
+        method_parts = method_name.split(self.METHOD_DELIMITER)
+        if len(method_parts) == 1:
+            #method name contains only one part, just add prefix before
+            # the method name
+            prefixed_method = self.METHOD_DELIMITER.join((prefix, method_name))
+        else:
+            #replace the first part of the method name with prefix
+            method_parts[0] = prefix
+            prefixed_method = self.METHOD_DELIMITER.join(method_parts)
+        return prefixed_method
+
diff -r 8d0c3223a818 trac/ticket/model.py
--- a/trac/ticket/model.py	Thu Apr 18 14:30:21 2013 +0000
+++ b/trac/ticket/model.py	Thu Apr 18 21:56:04 2013 -0500
@@ -25,7 +25,8 @@
 from trac.attachment import Attachment
 from trac import core
 from trac.cache import cached
-from trac.core import TracError
+from trac.core import (TracError, ListenerNotifier, IEntityChangeListener,
+                       extends_with_prefix)
 from trac.resource import Resource, ResourceNotFound
 from trac.ticket.api import TicketSystem
 from trac.util import embedded_numbers, partition
@@ -718,6 +719,7 @@
 class AbstractEnum(object):
     type = None
     ticket_col = None
+    change_listener_interface = None
 
     def __init__(self, env, name=None, db=None):
         if not self.ticket_col:
@@ -761,6 +763,10 @@
                 except ValueError:
                     pass # Ignore cast error for this non-essential operation
             TicketSystem(self.env).reset_ticket_fields()
+
+        ListenerNotifier(self.env).notify(
+            self.change_listener_interface.entity_deleted,
+            self)
         self.value = self._old_value = None
         self.name = self._old_name = None
 
@@ -788,6 +794,9 @@
 
         self._old_name = self.name
         self._old_value = self.value
+        ListenerNotifier(self.env).notify(
+            self.change_listener_interface.entity_created,
+            self)
 
     def update(self, db=None):
         """Update the enum value.
@@ -811,8 +820,15 @@
                    (self.name, self._old_name))
             TicketSystem(self.env).reset_ticket_fields()
 
+        old_values = dict()
+        if self.name != self._old_name:
+            old_values["name"] = self._old_name
+        if self.value != self._old_value:
+            old_values["value"] = self._old_value
         self._old_name = self.name
         self._old_value = self.value
+        ListenerNotifier(self.env).notify(
+            self.change_listener_interface.entity_changed, self, old_values)
 
     @classmethod
     def select(cls, env, db=None):
@@ -831,9 +847,15 @@
                 yield obj
 
 
+@extends_with_prefix("type")
+class ITypeChangeListener(IEntityChangeListener):
+    pass
+
+
 class Type(AbstractEnum):
     type = 'ticket_type'
     ticket_col = 'type'
+    change_listener_interface = ITypeChangeListener
 
 
 class Status(object):
@@ -848,16 +870,39 @@
             yield status
 
 
+@extends_with_prefix("resolution")
+class IResolutionChangeListener(IEntityChangeListener):
+    pass
+
+
 class Resolution(AbstractEnum):
     type = 'resolution'
+    change_listener_interface = IResolutionChangeListener
+
+
+@extends_with_prefix("priority")
+class IPriorityChangeListener(IEntityChangeListener):
+    pass
 
 
 class Priority(AbstractEnum):
     type = 'priority'
+    change_listener_interface = IPriorityChangeListener
+
+
+@extends_with_prefix("severity")
+class ISeverityChangeListener(IEntityChangeListener):
+    pass
 
 
 class Severity(AbstractEnum):
     type = 'severity'
+    change_listener_interface = ISeverityChangeListener
+
+
+@extends_with_prefix("component")
+class IComponentChangeListener(IEntityChangeListener):
+   pass 
 
 
 class Component(object):
@@ -893,9 +938,13 @@
         with self.env.db_transaction as db:
             self.env.log.info("Deleting component %s", self.name)
             db("DELETE FROM component WHERE name=%s", (self.name,))
-            self.name = self._old_name = None
             TicketSystem(self.env).reset_ticket_fields()
 
+        ListenerNotifier(self.env).notify(
+            IComponentChangeListener.entity_deleted, self)
+
+        self.name = self._old_name = None
+
     def insert(self, db=None):
         """Insert a new component.
 
@@ -915,6 +964,9 @@
             self._old_name = self.name
             TicketSystem(self.env).reset_ticket_fields()
 
+        ListenerNotifier(self.env).notify(
+            IComponentChangeListener.entity_created, self)
+
     def update(self, db=None):
         """Update the component.
 
@@ -926,6 +978,7 @@
         if not self.name:
             raise TracError(_("Invalid component name."))
 
+        old_name = self._old_name
         with self.env.db_transaction as db:
             self.env.log.info("Updating component '%s'", self.name)
             db("""UPDATE component SET name=%s,owner=%s, description=%s
@@ -939,6 +992,13 @@
                 self._old_name = self.name
             TicketSystem(self.env).reset_ticket_fields()
 
+        #todo:add support of old_values for owner and description fields
+        old_values = dict()
+        if self.name != old_name:
+            old_values["name"] = old_name
+        ListenerNotifier(self.env).notify(
+            IComponentChangeListener.entity_changed, self, old_values)
+
     @classmethod
     def select(cls, env, db=None):
         """
@@ -1170,6 +1230,11 @@
     return groups
 
 
+@extends_with_prefix("version")
+class IVersionChangeListener(IEntityChangeListener):
+    pass
+
+
 class Version(object):
     def __init__(self, env, name=None, db=None):
         self.env = env
@@ -1199,9 +1264,12 @@
         with self.env.db_transaction as db:
             self.env.log.info("Deleting version %s", self.name)
             db("DELETE FROM version WHERE name=%s", (self.name,))
-            self.name = self._old_name = None
             TicketSystem(self.env).reset_ticket_fields()
 
+        ListenerNotifier(self.env).notify(
+            IVersionChangeListener.entity_deleted, self)
+        self.name = self._old_name = None
+
     def insert(self, db=None):
         """Insert a new version.
 
@@ -1220,6 +1288,9 @@
             self._old_name = self.name
             TicketSystem(self.env).reset_ticket_fields()
 
+        ListenerNotifier(self.env).notify(
+            IVersionChangeListener.entity_created, self)
+
     def update(self, db=None):
         """Update the version.
 
@@ -1231,6 +1302,7 @@
         if not self.name:
             raise TracError(_("Invalid version name."))
 
+        old_name=self._old_name
         with self.env.db_transaction as db:
             self.env.log.info("Updating version '%s'", self.name)
             db("""UPDATE version
@@ -1244,6 +1316,14 @@
                 self._old_name = self.name
             TicketSystem(self.env).reset_ticket_fields()
 
+        #todo: add support of old_values for time and description fields
+        old_values = dict()
+        if self.name != old_name:
+            old_values["name"] = old_name
+
+        ListenerNotifier(self.env).notify(
+            IVersionChangeListener.entity_changed, self, old_values)
+
     @classmethod
     def select(cls, env, db=None):
         """
diff -r 8d0c3223a818 trac/ticket/tests/model.py
--- a/trac/ticket/tests/model.py	Thu Apr 18 14:30:21 2013 +0000
+++ b/trac/ticket/tests/model.py	Thu Apr 18 21:56:04 2013 -0500
@@ -12,8 +12,8 @@
 from trac.core import TracError, implements
 from trac.resource import ResourceNotFound
 from trac.ticket.model import (
-    Ticket, Component, Milestone, Priority, Type, Version
-)
+    Ticket, Component, Milestone, Priority, Type, Version,
+    IComponentChangeListener, IVersionChangeListener, IPriorityChangeListener)
 from trac.ticket.api import (
     IMilestoneChangeListener, ITicketChangeListener, TicketSystem
 )
@@ -1097,6 +1097,169 @@
         self.assertEqual([('Test', 0, 'Some text')], self.env.db_query(
             "SELECT name, time, description FROM version WHERE name='Test'"))
 
+class EntityChangeListenerMock(core.Component):
+ 
+    def callback(self, action, entity, changeinfo, old_values = None):
+        pass
+
+    def entity_created(self, entity, changeinfo = None):
+        self.action = "created"
+        self.entity = entity
+        self.changeinfo = changeinfo
+        self.callback(self.action, entity, changeinfo)
+
+    def entity_changed(self, entity, old_values, changeinfo = None):
+        self.action = "changed"
+        self.entity = entity
+        self.old_values = old_values
+        self.changeinfo = changeinfo
+        self.callback(
+            self.action, entity, changeinfo, old_values=self.old_values)
+
+    def entity_deleted(self, entity, changeinfo = None):
+        self.action = "deleted"
+        self.entity = entity
+        self.changeinfo = changeinfo
+        self.callback(self.action, entity, changeinfo)
+
+    def entity_reparented(self, entity, changeinfo = None):
+        self.action = "reparented"
+        self.entity = entity
+        self.changeinfo = changeinfo
+        self.callback(self.action, entity, changeinfo)
+
+class BaseEntityChangeListenerTestCase(unittest.TestCase):
+    DUMMY_ENTITY_NAME = "Entity 1"
+    name_field = "name"
+    entityChangeListener = None
+    entity_type = None
+
+    def setUp(self):
+        self.env = EnvironmentStub(default_data=True)
+        self.listener = self.entityChangeListener(self.env)
+        self.listener.callback = self.listener_callback
+
+    def tearDown(self):
+        self.env.reset_db()
+
+    def test_change_listener_created(self):
+        self._create_entity(self.DUMMY_ENTITY_NAME)
+        self.assertEqual('created', self.listener.action)
+        self.assertTrue(isinstance(self.listener.entity, self.entity_type))
+        self.assertEqual(
+            self.DUMMY_ENTITY_NAME,
+            self.entity_name)
+
+    def test_change_listener_changed(self):
+        entity = self._create_entity(self.DUMMY_ENTITY_NAME)
+        self._rename_entity(entity, "UpdatedName")
+        self.assertEqual('changed', self.listener.action)
+        self.assertTrue(isinstance(self.listener.entity, self.entity_type))
+        self.assertEqual("UpdatedName", self.entity_name)
+        self.assertEqual(
+            self.DUMMY_ENTITY_NAME,
+            self.listener.old_values[self.name_field])
+
+    def test_change_listener_deleted(self):
+        entity = self._create_entity(self.DUMMY_ENTITY_NAME)
+        entity.delete()
+        self.assertEqual('deleted', self.listener.action)
+        self.assertTrue(isinstance(self.listener.entity, self.entity_type))
+        self.assertEqual(self.DUMMY_ENTITY_NAME, self.entity_name)
+
+    def _create_entity(self, name):
+        entity = self.entity_type(self.env)
+        entity.name = name
+        entity.insert()
+        return entity
+
+    def _rename_entity(self, entity, new_name):
+        entity.name = new_name
+        entity.update()
+        return entity
+
+    def _get_entity_name(self, enity):
+        return enity.name
+
+    def listener_callback(self, action, entity, changeinfo, old_values = None):
+        self.entity_name = self._get_entity_name(entity)
+
+class ComponentChangeListenerMock(EntityChangeListenerMock):
+    implements(IComponentChangeListener)
+
+class ComponentEntityChangeListenerTestCase(
+    BaseEntityChangeListenerTestCase):
+    entity_type = Component
+    entityChangeListener = ComponentChangeListenerMock
+
+class VersionChangeListenerMock(EntityChangeListenerMock):
+    implements(IVersionChangeListener)
+    entity_type = Component
+
+class VersionEntityChangeListenerTestCase(
+    BaseEntityChangeListenerTestCase):
+    entity_type = Version
+    entityChangeListener = VersionChangeListenerMock
+
+class PriorityChangeListenerMock(EntityChangeListenerMock):
+    implements(IPriorityChangeListener)
+
+class PriorityEntityChangeListenerTestCase(
+    BaseEntityChangeListenerTestCase):
+    entity_type = Priority
+    entityChangeListener = PriorityChangeListenerMock
+
+class MultipleEntitiesChangeListenerMock(core.Component):
+    implements(IComponentChangeListener, IVersionChangeListener)
+
+    def __init__(self):
+        self.action = []
+
+    def component_created(self, entity, changeinfo = None):
+        self.action.append("component_created")
+
+    def component_changed(self, entity, old_values, changeinfo = None):
+        pass
+
+    def component_deleted(self, entity, changeinfo = None):
+        pass
+
+    def component_reparented(self, entity, changeinfo = None):
+        pass
+
+    def version_created(self, entity, changeinfo = None):
+        self.action.append("version_created")
+
+    def version_changed(self, entity, old_values, changeinfo = None):
+        pass
+
+    def version_deleted(self, entity, changeinfo = None):
+        pass
+
+    def version_reparented(self, entity, changeinfo = None):
+        pass
+
+class MultipleEntitiesChangeListenerTestCase(unittest.TestCase):
+
+    def setUp(self):
+        self.env = EnvironmentStub(default_data=True)
+        self.listener = MultipleEntitiesChangeListenerMock(self.env)
+
+    def tearDown(self):
+        self.env.reset_db()
+
+    def test_can_receive_events_from_different_entities(self):
+        self._create_entity(Component, "Component1")
+        self._create_entity(Version, "Version1")
+        self.assertEqual(
+            ["component_created", "version_created"], self.listener.action)
+
+    def _create_entity(self, entity_type, name):
+        entity = entity_type(self.env)
+        entity.name = name
+        entity.insert()
+        return entity
+
 
 def suite():
     suite = unittest.TestSuite()
@@ -1107,6 +1270,14 @@
     suite.addTest(unittest.makeSuite(MilestoneTestCase, 'test'))
     suite.addTest(unittest.makeSuite(ComponentTestCase, 'test'))
     suite.addTest(unittest.makeSuite(VersionTestCase, 'test'))
+    suite.addTest(unittest.makeSuite(
+        ComponentEntityChangeListenerTestCase, 'test'))
+    suite.addTest(unittest.makeSuite(
+        VersionEntityChangeListenerTestCase, 'test'))
+    suite.addTest(unittest.makeSuite(
+        PriorityEntityChangeListenerTestCase, 'test'))
+    suite.addTest(unittest.makeSuite(
+        MultipleEntitiesChangeListenerTestCase, 'test'))
     return suite
 
 if __name__ == '__main__':