trac-mq / t11148 / t11148_r11782_IEntityChangeListener_v2.diff

  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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
# HG changeset patch
# Parent 8d0c3223a81860370202a5184fa812081129fe43
An alternative proposal is based on ticket comments and google groups discussion. The proposal introduces IEntityChangeListener interface .

diff -r 8d0c3223a818 trac/core.py
--- a/trac/core.py	Thu Apr 18 14:30:21 2013 +0000
+++ b/trac/core.py	Wed Apr 24 19:11:37 2013 -0500
@@ -165,7 +165,6 @@
 
         locals_.setdefault('_implements', []).extend(interfaces)
 
-
 implements = Component.implements
 
 
@@ -236,3 +235,98 @@
         with the given class will not be available.
         """
         return True
+
+class NotificationChangeInfo(object):
+    """Additional information about entity change.
+    """
+
+    def __init__(self, comment=None, author=None):
+        self.comment = comment
+        self.author = author
+        self.event_args = None
+        self.action = None
+
+
+class IEntityChangeListener(Interface):
+    """Extension point interface for components that require notification
+    when model entities are created, modified, or deleted.
+
+    :param     entity: parameter is instance of the a entity e.g. ticket,
+                       milestone, etc.
+    :param changeinfo: is instance of NotificationChangeInfo. The changeinfo
+                       parameter content depends on an entity type and may be
+                       None.
+    :param     kwargs: receives in the form of excess keyword arguments 
+                       custom event data supported by resource-specific
+                       interfaces. 
+    """
+
+    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.
+
+        :param old_values: is a dictionary containing the previous values of
+                           the entity properties that changed. Properties
+                           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."""
+
+    def entity_event(entity, changeinfo):
+        """Called when a custom entity event takes place.
+        
+        :param changeinfo: an instance of `NotificationChangeInfo` with
+                           - `action` set to custom event name
+                           - `event_args` set to a mapping object populated
+                                          with event-specific data.
+        """
+
+
+class ListenerNotifier(Component):
+    required = True
+
+    BUILTIN_EVENTS = set(['created', 'changed', 'deleted', 'reparented'])
+
+    def notify(self, method, **kwargs):
+        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)
+
+        xp = ExtensionPoint(interface)
+        # FIXME : Sender component rather than self. Change method signature
+        for listener in xp.extensions(self):
+            getattr(listener, method_name)(**kwargs)
+
+        xp = ExtensionPoint(IEntityChangeListener)
+        generic_listeners = xp.extensions(self)
+        if generic_listeners:
+            #TODO : Include `interface` in kwargs ?
+            parts = method_name.split('_', 1)
+            action = parts[-1]
+            changeinfo = kwargs.setdefault('changeinfo', 
+                                           NotificationChangeInfo())
+            target_args = set(('changeinfo', 'entity'))
+            if action in self.BUILTIN_EVENTS:
+                method_name = 'entity_' + action
+                if action == 'changed':
+                    target_args.add('old_values')
+            else:
+                method_name = 'entity_event'
+                changeinfo.action = action
+            changeinfo.event_args = dict([k, kwargs.pop(k)]
+                                         for k in kwargs.copy()
+                                         if k not in target_args)
+
+            for listener in generic_listeners:
+                getattr(listener, method_name)(**kwargs)
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	Wed Apr 24 19:11:37 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 (Interface, IEntityChangeListener, ListenerNotifier,
+                       TracError)
 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,11 @@
                 except ValueError:
                     pass # Ignore cast error for this non-essential operation
             TicketSystem(self.env).reset_ticket_fields()
+
+        interface = self.change_listener_interface
+        ListenerNotifier(self.env).notify(getattr(interface, 
+                    interface._entity_listener_prefix + '_deleted'),
+                    entity=self)
         self.value = self._old_value = None
         self.name = self._old_name = None
 
@@ -788,6 +795,10 @@
 
         self._old_name = self.name
         self._old_value = self.value
+        interface = self.change_listener_interface
+        ListenerNotifier(self.env).notify(getattr(interface, 
+                    interface._entity_listener_prefix + '_created'),
+                    entity=self)
 
     def update(self, db=None):
         """Update the enum value.
@@ -811,8 +822,17 @@
                    (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
+        interface = self.change_listener_interface
+        ListenerNotifier(self.env).notify(getattr(interface, 
+                    interface._entity_listener_prefix + '_changed'),
+                    entity=self, old_values=old_values)
 
     @classmethod
     def select(cls, env, db=None):
@@ -831,9 +851,33 @@
                 yield obj
 
 
+class ITypeChangeListener(Interface):
+    """Extension point interface for components that require notification
+    when ticket types are created, modified, or deleted.
+
+    :param     entity: target ticket type.
+    :param changeinfo: always set to None.
+    """
+    _entity_listener_prefix = 'type'
+
+    def type_created(entity, changeinfo = None):
+        """Called when an ticket type is created."""
+
+    def type_changed(entity, old_values, changeinfo = None):
+        """Called when a ticket type is modified.
+
+        :param old_values: is a dictionary containing the previous 
+                           `name` and `value` of target ticket type
+        """
+
+    def type_deleted(entity, changeinfo = None):
+        """Called when a ticket type is deleted."""
+
+
 class Type(AbstractEnum):
     type = 'ticket_type'
     ticket_col = 'type'
+    change_listener_interface = ITypeChangeListener
 
 
 class Status(object):
@@ -848,16 +892,112 @@
             yield status
 
 
+class IResolutionChangeListener(Interface):
+    """Extension point interface for components that require notification
+    when ticket resolution are created, modified, or deleted.
+
+    :param     entity: target ticket resolution.
+    :param changeinfo: always set to None.
+    """
+    _entity_listener_prefix = 'resolution'
+
+    def resolution_created(entity, changeinfo = None):
+        """Called when an ticket resolution is created."""
+
+    def resolution_changed(entity, old_values, changeinfo = None):
+        """Called when a ticket resolution is modified.
+
+        :param old_values: is a dictionary containing the previous 
+                           `name` and `value` of target ticket resolution
+        """
+
+    def resolution_deleted(entity, changeinfo = None):
+        """Called when a ticket resolution is deleted."""
+
+
 class Resolution(AbstractEnum):
     type = 'resolution'
+    change_listener_interface = IResolutionChangeListener
+
+
+class IPriorityChangeListener(Interface):
+    """Extension point interface for components that require notification
+    when ticket priority are created, modified, or deleted.
+
+    :param     entity: target ticket priority.
+    :param changeinfo: always set to None.
+    """
+    _entity_listener_prefix = 'priority'
+
+    def priority_created(entity, changeinfo = None):
+        """Called when an ticket priority is created."""
+
+    def priority_changed(entity, old_values, changeinfo = None):
+        """Called when a ticket priority is modified.
+
+        :param old_values: is a dictionary containing the previous 
+                           `name` and `value` of target ticket priority
+        """
+
+    def priority_deleted(entity, changeinfo = None):
+        """Called when a ticket priority is deleted."""
 
 
 class Priority(AbstractEnum):
     type = 'priority'
+    change_listener_interface = IPriorityChangeListener
+
+
+class ISeverityChangeListener(Interface):
+    """Extension point interface for components that require notification
+    when ticket severity are created, modified, or deleted.
+
+    :param     entity: target ticket severity.
+    :param changeinfo: always set to None.
+    """
+    _entity_listener_prefix = 'severity'
+
+    def severity_created(entity, changeinfo = None):
+        """Called when an ticket severity is created."""
+
+    def severity_changed(entity, old_values, changeinfo = None):
+        """Called when a ticket severity is modified.
+
+        :param old_values: is a dictionary containing the previous 
+                           `name` and `value` of target ticket severity
+        """
+
+    def severity_deleted(entity, changeinfo = None):
+        """Called when a ticket severity is deleted."""
 
 
 class Severity(AbstractEnum):
     type = 'severity'
+    change_listener_interface = ISeverityChangeListener
+
+
+class IComponentChangeListener(Interface):
+    """Extension point interface for components that require notification
+    when ticket component are created, modified, or deleted.
+
+    :param     entity: target ticket component.
+    :param changeinfo: always set to None.
+    """
+    _entity_listener_prefix = 'component'
+
+    def component_created(entity, changeinfo = None):
+        """Called when an ticket component is created."""
+
+    def component_changed(entity, old_values, changeinfo = None):
+        """Called when a ticket component is modified.
+
+        :param old_values: is a dictionary containing the previous 
+                           `name`, `owner` and `description` of
+                           target ticket component
+        """
+
+    def component_deleted(entity, changeinfo = None):
+        """Called when a ticket component is deleted."""
 
 
 class Component(object):
@@ -893,9 +1033,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.component_deleted, entity=self)
+
+        self.name = self._old_name = None
+
     def insert(self, db=None):
         """Insert a new component.
 
@@ -915,6 +1059,9 @@
             self._old_name = self.name
             TicketSystem(self.env).reset_ticket_fields()
 
+        ListenerNotifier(self.env).notify(
+                    IComponentChangeListener.component_created, entity=self)
+
     def update(self, db=None):
         """Update the component.
 
@@ -926,6 +1073,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 +1087,14 @@
                 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.component_changed, 
+                    entity=self, old_values=old_values)
+
     @classmethod
     def select(cls, env, db=None):
         """
@@ -1170,6 +1326,30 @@
     return groups
 
 
+class IVersionChangeListener(Interface):
+    """Extension point interface for components that require notification
+    when ticket version are created, modified, or deleted.
+
+    :param     entity: target ticket version.
+    :param changeinfo: always set to None.
+    """
+    _entity_listener_prefix = 'version'
+
+    def version_created(entity, changeinfo = None):
+        """Called when an ticket version is created."""
+
+    def version_changed(entity, old_values, changeinfo = None):
+        """Called when a ticket version is modified.
+
+        :param old_values: is a dictionary containing the previous 
+                           `name`, `time` and `description` of
+                           target ticket version
+        """
+
+    def version_deleted(entity, changeinfo = None):
+        """Called when a ticket version is deleted."""
+
+
 class Version(object):
     def __init__(self, env, name=None, db=None):
         self.env = env
@@ -1199,9 +1379,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.version_deleted, entity=self)
+        self.name = self._old_name = None
+
     def insert(self, db=None):
         """Insert a new version.
 
@@ -1220,6 +1403,9 @@
             self._old_name = self.name
             TicketSystem(self.env).reset_ticket_fields()
 
+        ListenerNotifier(self.env).notify(
+            IVersionChangeListener.version_created, entity=self)
+
     def update(self, db=None):
         """Update the version.
 
@@ -1231,6 +1417,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 +1431,15 @@
                 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.version_changed, 
+            entity=self, old_values=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	Wed Apr 24 19:11:37 2013 -0500
@@ -9,11 +9,11 @@
 
 from trac import core
 from trac.attachment import Attachment
-from trac.core import TracError, implements
+from trac.core import implements, TracError
 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,389 @@
         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, kwargs=None):
+        pass
+
+    def _entity_created(self, entity, changeinfo = None, **kwargs):
+        self.action = "created"
+        self.entity = entity
+        self.changeinfo = changeinfo
+        self.kwargs = kwargs
+        self.callback(self.action, entity, changeinfo, kwargs)
+
+    def _entity_changed(self, entity, old_values, changeinfo = None, **kwargs):
+        self.action = "changed"
+        self.entity = entity
+        self.old_values = old_values
+        self.changeinfo = changeinfo
+        self.kwargs = kwargs
+        self.callback(
+            self.action, entity, changeinfo, old_values, kwargs)
+
+    def _entity_deleted(self, entity, changeinfo = None, **kwargs):
+        self.action = "deleted"
+        self.entity = entity
+        self.changeinfo = changeinfo
+        self.kwargs = kwargs
+        self.callback(self.action, entity, changeinfo, kwargs)
+
+    def _entity_reparented(self, entity, changeinfo = None, **kwargs):
+        self.action = "reparented"
+        self.entity = entity
+        self.changeinfo = changeinfo
+        self.kwargs = kwargs
+        self.callback(self.action, entity, changeinfo, kwargs)
+
+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, kwargs=None):
+        self.entity_name = self._get_entity_name(entity)
+
+
+class ComponentChangeListenerMock(EntityChangeListenerMock):
+    implements(IComponentChangeListener)
+
+    def component_created(self, entity, changeinfo = None):
+        return self._entity_created(entity, changeinfo)
+
+    def component_changed(self, entity, old_values, changeinfo = None):
+        return self._entity_changed(entity, old_values, changeinfo)
+
+    def component_deleted(self, entity, changeinfo = None):
+        return self._entity_deleted(entity, changeinfo)
+
+    def component_reparented(self, entity, changeinfo = None):
+        return self._entity_reparented(entity, changeinfo)
+
+
+class ComponentEntityChangeListenerTestCase(
+    BaseEntityChangeListenerTestCase):
+    entity_type = Component
+    entityChangeListener = ComponentChangeListenerMock
+
+    def test_all_methods(self):
+        self.assertTrue(hasattr(IComponentChangeListener, 'component_created'))
+        self.assertTrue(hasattr(IComponentChangeListener, 'component_changed'))
+        self.assertTrue(hasattr(IComponentChangeListener, 'component_deleted'))
+
+
+class VersionChangeListenerMock(EntityChangeListenerMock):
+    implements(IVersionChangeListener)
+    entity_type = Component
+
+    def version_created(self, entity, changeinfo = None):
+        return self._entity_created(entity, changeinfo)
+
+    def version_changed(self, entity, old_values, changeinfo = None):
+        return self._entity_changed(entity, old_values, changeinfo)
+
+    def version_deleted(self, entity, changeinfo = None):
+        return self._entity_deleted(entity, changeinfo)
+
+
+class VersionEntityChangeListenerTestCase(
+    BaseEntityChangeListenerTestCase):
+    entity_type = Version
+    entityChangeListener = VersionChangeListenerMock
+
+    def test_all_methods(self):
+        self.assertTrue(hasattr(IVersionChangeListener, 'version_created'))
+        self.assertTrue(hasattr(IVersionChangeListener, 'version_changed'))
+        self.assertTrue(hasattr(IVersionChangeListener, 'version_deleted'))
+
+
+class PriorityChangeListenerMock(EntityChangeListenerMock):
+    implements(IPriorityChangeListener)
+
+    def priority_created(self, entity, changeinfo = None):
+        return self._entity_created(entity, changeinfo)
+
+    def priority_changed(self, entity, old_values, changeinfo = None):
+        return self._entity_changed(entity, old_values, changeinfo)
+
+    def priority_deleted(self, entity, changeinfo = None):
+        return self._entity_deleted(entity, changeinfo)
+
+
+class PriorityEntityChangeListenerTestCase(
+    BaseEntityChangeListenerTestCase):
+    entity_type = Priority
+    entityChangeListener = PriorityChangeListenerMock
+
+    def test_all_methods(self):
+        self.assertTrue(hasattr(IPriorityChangeListener, 'priority_created'))
+        self.assertTrue(hasattr(IPriorityChangeListener, 'priority_changed'))
+        self.assertTrue(hasattr(IPriorityChangeListener, 'priority_deleted'))
+
+
+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 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
+
+
+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
+
+
+class GenericEntitiesChangeListenerMock(core.Component):
+    implements(core.IEntityChangeListener)
+
+    def __init__(self):
+        self.details = []
+        self.action = []
+
+    def _handle(self, kwargs):
+        cls = kwargs['entity'].__class__
+        self.action.append(cls.__name__.lower() + '_' + kwargs['action'])
+
+        # Remove reference to self
+        del kwargs['self']
+        # Add action for custom events
+        changeinfo = kwargs.get('changeinfo')
+        if changeinfo is not None and changeinfo.action:
+            kwargs['action'] = changeinfo.action
+        # Add custom args and clear changeinfo
+        kwargs.update(changeinfo.event_args or {}, changeinfo=None)
+        self.details.append(kwargs)
+
+    def entity_created(self, entity, changeinfo=None):
+        kwargs = locals()
+        kwargs.update(action='created')
+        self._handle(kwargs)
+
+    def entity_changed(self, entity, old_values, changeinfo = None):
+        kwargs = locals()
+        kwargs.update(action='changed')
+        self._handle(kwargs)
+
+    def entity_deleted(self, entity, changeinfo = None):
+        kwargs = locals()
+        kwargs.update(action='deleted')
+        self._handle(kwargs)
+
+    def entity_reparented(self, entity, changeinfo = None):
+        kwargs = locals()
+        kwargs.update(action='reparented')
+        self._handle(kwargs)
+
+    def entity_event(self, entity, changeinfo = None):
+        kwargs = locals()
+        self._handle(kwargs)
+
+
+class GenericEntitiesChangeListenerTestCase(MultipleEntitiesChangeListenerTestCase):
+
+    def setUp(self):
+        self.env = EnvironmentStub(default_data=True)
+        self.listener = GenericEntitiesChangeListenerMock(self.env)
+
+    def test_custom_events(self):
+
+        class ISomethingListener(core.Interface):
+            """Listener interface written from scratch
+            """
+            def something_created(entity, changeinfo = None):
+                """Called when an entity is created."""
+
+            def something_changed(entity, old_values, required_arg,
+                                  changeinfo=None, optional_arg=None):
+                """Update event with required and optional custom args."""
+
+            def something_deleted(entity, changeinfo = None):
+                """Called when an entity is deleted."""
+
+            def something_reparented(entity, changeinfo = None):
+                """Never invoked. May be removed."""
+
+        class Something(object):
+            def __init__(self, env):
+                self.env = env
+                self.required_arg = 999
+
+            # Just trigger notifications
+            def delete(self, db=None):
+                notifier = core.ListenerNotifier(self.env)
+                notifier.notify(ISomethingListener.something_deleted, 
+                                entity=self)
+
+            def insert(self, db=None):
+                notifier = core.ListenerNotifier(self.env)
+                notifier.notify(ISomethingListener.something_created,
+                                entity=self)
+
+            def update(self, db=None):
+                notifier = core.ListenerNotifier(self.env)
+                optional_args = dict(optional_arg=self.optional_arg) \
+                                if hasattr(self, 'optional_arg') \
+                                else {}
+                notifier.notify(ISomethingListener.something_changed,
+                                entity=self,
+                                old_values=dict(),
+                                required_arg=self.required_arg,
+                                **optional_args)
+
+        class SomethingListener(core.Component):
+            """Replicate the same behavior of generic listener
+            """
+            implements(ISomethingListener)
+
+            def __init__(self):
+                self.details = []
+
+            def _handle(self, kwargs):
+                del kwargs['self']
+                if 'optional_arg' in kwargs and kwargs['optional_arg'] is None:
+                    del kwargs['optional_arg']
+                self.details.append(kwargs)
+
+            def something_created(self, entity, changeinfo=None):
+                args = locals()
+                args['action'] = 'created'
+                self._handle(args)
+
+            def something_changed(self, entity, old_values, required_arg,
+                                  changeinfo=None, optional_arg=None):
+                args = locals()
+                args['action'] = 'changed'
+                self._handle(args)
+
+            def something_deleted(self, entity, changeinfo=None):
+                args = locals()
+                args['action'] = 'deleted'
+                self._handle(args)
+
+            def something_reparented(self, entity, changeinfo=None):
+                args = locals()
+                args['action'] = 'reparented'
+                self._handle(args)
+
+        resource_listener = SomethingListener(self.env)
+
+        # CRUD operations
+        something = Something(self.env)
+        something.insert()
+        something.update()
+        something.required_arg = 7
+        something.optional_arg = 44
+        something.update()
+        something.delete()
+
+        expected = [
+                    {'action' : 'created',
+                     'entity' : something,
+                     'changeinfo' : None},
+                    {'action' : 'changed',
+                     'entity' : something,
+                     'old_values' : {},
+                     'required_arg' : 999,
+                     'changeinfo' : None},
+                    {'action' : 'changed',
+                     'entity' : something,
+                     'old_values' : {},
+                     'required_arg' : 7,
+                     'optional_arg' : 44,
+                     'changeinfo' : None},
+                    {'action' : 'deleted',
+                     'entity' : something,
+                     'changeinfo' : None},
+                    ]
+
+        self.assertEquals(expected, self.listener.details,
+                          'Generic listener event sequence')
+        self.assertEquals(expected, resource_listener.details,
+                          'Resource-specific listener event sequence')
+
 
 def suite():
     suite = unittest.TestSuite()
@@ -1107,6 +1490,17 @@
     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'))
+    suite.addTest(unittest.makeSuite(
+        GenericEntitiesChangeListenerTestCase, 'test'))
+
     return suite
 
 if __name__ == '__main__':
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.