~launchpad-pqm/launchpad/devel

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
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
# Copyright 2010-2011 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

"""Tests for `StructuralSubscription`."""

__metaclass__ = type

from storm.store import (
    EmptyResultSet,
    ResultSet,
    Store,
    )
from testtools.matchers import StartsWith
from zope.security.interfaces import Unauthorized

from lp.bugs.enum import BugNotificationLevel
from lp.bugs.interfaces.bugtask import (
    BugTaskImportance,
    BugTaskStatus,
    )
from lp.bugs.mail.bugnotificationrecipients import BugNotificationRecipients
from lp.bugs.model.bugsubscriptionfilter import (
    BugSubscriptionFilter,
    BugSubscriptionFilterMute,
    MuteNotAllowed,
    )
from lp.bugs.model.structuralsubscription import (
    get_structural_subscribers,
    get_structural_subscription_targets,
    get_structural_subscriptions,
    get_structural_subscriptions_for_bug,
    )
from lp.services.database.decoratedresultset import DecoratedResultSet
from lp.testing import (
    anonymous_logged_in,
    login_person,
    person_logged_in,
    TestCaseWithFactory,
    )
from lp.testing.factory import is_security_proxied_or_harmless
from lp.testing.layers import (
    DatabaseFunctionalLayer,
    LaunchpadFunctionalLayer,
    )


RESULT_SETS = ResultSet, EmptyResultSet, DecoratedResultSet


class TestStructuralSubscription(TestCaseWithFactory):

    layer = DatabaseFunctionalLayer

    def setUp(self):
        super(TestStructuralSubscription, self).setUp()
        self.product = self.factory.makeProduct()
        with person_logged_in(self.product.owner):
            self.subscription = self.product.addSubscription(
                self.product.owner, self.product.owner)
        self.original_filter = self.subscription.bug_filters[0]

    def test_delete_requires_Edit_permission(self):
        # delete() is only available to the subscriber.
        # We use a lambda here because a security proxy around
        # self.subscription is giving us the behavior we want to
        # demonstrate.  Merely accessing the "delete" name raises
        # Unauthorized, before the method is even called.  Therefore,
        # we use a lambda to make the trigger happen within "assertRaises".
        with anonymous_logged_in():
            self.assertRaises(Unauthorized, lambda: self.subscription.delete)
        with person_logged_in(self.factory.makePerson()):
            self.assertRaises(Unauthorized, lambda: self.subscription.delete)

    def test_simple_delete(self):
        with person_logged_in(self.product.owner):
            self.subscription.delete()
            self.assertEqual(
                self.product.getSubscription(self.product.owner), None)

    def test_delete_cascades_to_filters(self):
        with person_logged_in(self.product.owner):
            subscription_id = self.subscription.id
            self.subscription.newBugFilter()
            self.subscription.delete()
            self.assertEqual(
                self.product.getSubscription(self.product.owner), None)
            store = Store.of(self.product)
            # We know that the filter is gone, because we know the
            # subscription is gone, and the database would have
            # prevented the deletion of a subscription without first
            # deleting the filters.  We'll double-check, to be sure.
            self.assertEqual(
                store.find(
                    BugSubscriptionFilter,
                    BugSubscriptionFilter.structural_subscription_id ==
                        subscription_id).one(),
                None)

    def test_bug_filters_default(self):
        # The bug_filters attribute has a default non-filtering bug filter
        # to begin with.
        self.assertEqual([self.original_filter],
                         list(self.subscription.bug_filters))

    def test_bug_filters(self):
        # The bug_filters attribute returns the BugSubscriptionFilter records
        # associated with this subscription.
        subscription_filter = BugSubscriptionFilter()
        subscription_filter.structural_subscription = self.subscription
        self.assertContentEqual(
            [subscription_filter, self.original_filter],
            list(self.subscription.bug_filters))

    def test_newBugFilter(self):
        # newBugFilter() creates a new subscription filter linked to the
        # subscription.
        with person_logged_in(self.product.owner):
            subscription_filter = self.subscription.newBugFilter()
        self.assertEqual(
            self.subscription,
            subscription_filter.structural_subscription)
        self.assertContentEqual(
            [subscription_filter, self.original_filter],
            list(self.subscription.bug_filters))

    def test_newBugFilter_by_anonymous(self):
        # newBugFilter() is not available to anonymous users.
        with anonymous_logged_in():
            self.assertRaises(
                Unauthorized, lambda: self.subscription.newBugFilter)

    def test_newBugFilter_by_other_user(self):
        # newBugFilter() is only available to the subscriber.
        with person_logged_in(self.factory.makePerson()):
            self.assertRaises(
                Unauthorized, lambda: self.subscription.newBugFilter)


class FilteredStructuralSubscriptionTestBase:
    """Tests for filtered structural subscriptions."""

    layer = LaunchpadFunctionalLayer

    def makeTarget(self):
        raise NotImplementedError(self.makeTarget)

    def makeBugTask(self):
        return self.factory.makeBugTask(target=self.target)

    def setUp(self):
        super(FilteredStructuralSubscriptionTestBase, self).setUp()
        self.ordinary_subscriber = self.factory.makePerson()
        login_person(self.ordinary_subscriber)
        self.target = self.makeTarget()
        self.bugtask = self.makeBugTask()
        self.bug = self.bugtask.bug
        self.subscription = self.target.addSubscription(
            self.ordinary_subscriber, self.ordinary_subscriber)
        self.initial_filter = self.subscription.bug_filters[0]

    def assertSubscribers(
        self, expected_subscribers, level=BugNotificationLevel.LIFECYCLE):
        observed_subscribers = list(
            get_structural_subscribers(self.bugtask, None, level))
        self.assertEqual(expected_subscribers, observed_subscribers)

    def test_getStructuralSubscribers(self):
        # If no one has a filtered subscription for the given bug, the result
        # of get_structural_subscribers() is the same as for
        # the set of people from each subscription in getSubscriptions().
        subscriptions = self.target.getSubscriptions()
        self.assertSubscribers([sub.subscriber for sub in subscriptions])

    def test_getStructuralSubscribers_with_filter_on_status(self):
        # If a status filter exists for a subscription, the result of
        # get_structural_subscribers() may be a subset of getSubscriptions().

        # Without any filters the subscription is found.
        self.assertSubscribers([self.ordinary_subscriber])

        # Filter the subscription to bugs in the CONFIRMED state.
        self.initial_filter.statuses = [BugTaskStatus.CONFIRMED]

        # With the filter the subscription is not found.
        self.assertSubscribers([])

        # If the filter is adjusted, the subscription is found again.
        self.initial_filter.statuses = [self.bugtask.status]
        self.assertSubscribers([self.ordinary_subscriber])

    def test_getStructuralSubscribers_with_filter_on_importance(self):
        # If an importance filter exists for a subscription, the result of
        # get_structural_subscribers() may be a subset of getSubscriptions().

        # Without any filters the subscription is found.
        self.assertSubscribers([self.ordinary_subscriber])

        # Filter the subscription to bugs in the CRITICAL state.
        self.initial_filter.importances = [BugTaskImportance.CRITICAL]

        # With the filter the subscription is not found.
        self.assertSubscribers([])

        # If the filter is adjusted, the subscription is found again.
        self.initial_filter.importances = [self.bugtask.importance]
        self.assertSubscribers([self.ordinary_subscriber])

    def test_getStructuralSubscribers_with_filter_on_level(self):
        # All structural subscriptions have a level for bug notifications
        # which get_structural_subscribers() observes.

        # Adjust the subscription level to METADATA.
        self.initial_filter.bug_notification_level = (
            BugNotificationLevel.METADATA)

        # The subscription is found when looking for LIFECYCLE or above.
        self.assertSubscribers(
            [self.ordinary_subscriber], BugNotificationLevel.LIFECYCLE)
        # The subscription is found when looking for METADATA or above.
        self.assertSubscribers(
            [self.ordinary_subscriber], BugNotificationLevel.METADATA)
        # The subscription is not found when looking for COMMENTS or above.
        self.assertSubscribers(
            [], BugNotificationLevel.COMMENTS)

    def test_getStructuralSubscribers_with_filter_include_any_tags(self):
        # If a subscription filter has include_any_tags, a bug with one or
        # more tags is matched.

        self.initial_filter.include_any_tags = True

        # Without any tags the subscription is not found.
        self.assertSubscribers([])

        # With any tag the subscription is found.
        self.bug.tags = ["foo"]
        self.assertSubscribers([self.ordinary_subscriber])

    def test_getStructuralSubscribers_with_filter_exclude_any_tags(self):
        # If a subscription filter has exclude_any_tags, only bugs with no
        # tags are matched.

        self.initial_filter.exclude_any_tags = True

        # Without any tags the subscription is found.
        self.assertSubscribers([self.ordinary_subscriber])

        # With any tag the subscription is not found.
        self.bug.tags = ["foo"]
        self.assertSubscribers([])

    def test_getStructuralSubscribers_with_filter_for_any_tag(self):
        # If a subscription filter specifies that any of one or more specific
        # tags must be present, bugs with any of those tags are matched.

        # Looking for either the "foo" or the "bar" tag.
        self.initial_filter.tags = [u"foo", u"bar"]
        self.initial_filter.find_all_tags = False

        # Without either tag the subscription is not found.
        self.assertSubscribers([])

        # With either tag the subscription is found.
        self.bug.tags = ["bar", "baz"]
        self.assertSubscribers([self.ordinary_subscriber])

    def test_getStructuralSubscribers_with_filter_for_all_tags(self):
        # If a subscription filter specifies that all of one or more specific
        # tags must be present, bugs with all of those tags are matched.

        # Looking for both the "foo" and the "bar" tag.
        self.initial_filter.tags = [u"foo", u"bar"]
        self.initial_filter.find_all_tags = True

        # Without either tag the subscription is not found.
        self.assertSubscribers([])

        # Without only one of the required tags the subscription is not found.
        self.bug.tags = ["foo"]
        self.assertSubscribers([])

        # With both required tags the subscription is found.
        self.bug.tags = ["foo", "bar"]
        self.assertSubscribers([self.ordinary_subscriber])

    def test_getStructuralSubscribers_with_filter_for_not_any_tag(self):
        # If a subscription filter specifies that any of one or more specific
        # tags must not be present, bugs without any of those tags are
        # matched.

        # Looking to exclude the "foo" or "bar" tags.
        self.initial_filter.tags = [u"-foo", u"-bar"]
        self.initial_filter.find_all_tags = False

        # Without either tag the subscription is found.
        self.assertSubscribers([self.ordinary_subscriber])

        # With both tags, the subscription is omitted.
        self.bug.tags = ["foo", "bar"]
        self.assertSubscribers([])

        # With only one tag, the subscription is found again.
        self.bug.tags = ["foo"]
        self.assertSubscribers([self.ordinary_subscriber])

        # However, if find_all_tags is True, even a single excluded tag
        # causes the subscription to be skipped.
        self.initial_filter.find_all_tags = True
        self.assertSubscribers([])

        # This is also true, of course, if the bug has both tags.
        self.bug.tags = ["foo", "bar"]
        self.assertSubscribers([])

    def test_getStructuralSubscribers_with_filter_for_not_all_tags(self):
        # If a subscription filter specifies that all of one or more specific
        # tags must not be present, bugs without all of those tags are
        # matched.

        # Looking to exclude the "foo" and "bar" tags.
        self.initial_filter.tags = [u"-foo", u"-bar"]
        self.initial_filter.find_all_tags = True

        # Without either tag the subscription is found.
        self.assertSubscribers([self.ordinary_subscriber])

        # With only one of the excluded tags the subscription is not
        # found--we are saying that we want to find both an absence of foo
        # and an absence of bar, and yet foo exists.
        self.bug.tags = ["foo"]
        self.assertSubscribers([])

        # With both tags the subscription is also not found.
        self.bug.tags = ["foo", "bar"]
        self.assertSubscribers([])

    def test_getStructuralSubscribers_with_multiple_filters(self):
        # If multiple filters exist for a subscription, all filters must
        # match.

        # Add the "foo" tag to the bug.
        self.bug.tags = ["foo"]
        self.assertSubscribers([self.ordinary_subscriber])

        # Filter the subscription to bugs in the CRITICAL state.
        self.initial_filter.statuses = [BugTaskStatus.CONFIRMED]
        self.initial_filter.importances = [BugTaskImportance.CRITICAL]

        # With the filter the subscription is not found.
        self.assertSubscribers([])

        # If the filter is adjusted to match status but not importance, the
        # subscription is still not found.
        self.initial_filter.statuses = [self.bugtask.status]
        self.assertSubscribers([])

        # If the filter is adjusted to also match importance, the subscription
        # is found again.
        self.initial_filter.importances = [self.bugtask.importance]
        self.assertSubscribers([self.ordinary_subscriber])

        # If the filter is given some tag criteria, the subscription is not
        # found.
        self.initial_filter.tags = [u"-foo", u"bar", u"baz"]
        self.initial_filter.find_all_tags = False
        self.assertSubscribers([])

        # After removing the "foo" tag and adding the "bar" tag, the
        # subscription is found.
        self.bug.tags = ["bar"]
        self.assertSubscribers([self.ordinary_subscriber])

        # Requiring that all tag criteria are fulfilled causes the
        # subscription to no longer be found.
        self.initial_filter.find_all_tags = True
        self.assertSubscribers([])

        # After adding the "baz" tag, the subscription is found again.
        self.bug.tags = ["bar", "baz"]
        self.assertSubscribers([self.ordinary_subscriber])

    def test_getStructuralSubscribers_any_filter_is_a_match(self):
        # If a subscription has multiple filters, the subscription is selected
        # when any filter is found to match. Put another way, the filters are
        # ORed together.
        subscription_filter1 = self.initial_filter
        subscription_filter1.statuses = [BugTaskStatus.CONFIRMED]
        subscription_filter2 = self.subscription.newBugFilter()
        subscription_filter2.tags = [u"foo"]

        # With the filter the subscription is not found.
        self.assertSubscribers([])

        # If the bugtask is adjusted to match the criteria of the first filter
        # but not those of the second, the subscription is found.
        self.bugtask.transitionToStatus(
            BugTaskStatus.CONFIRMED, self.ordinary_subscriber)
        self.assertSubscribers([self.ordinary_subscriber])

        # If the filter is adjusted to also match the criteria of the second
        # filter, the subscription is still found.
        self.bugtask.bug.tags = [u"foo"]
        self.assertSubscribers([self.ordinary_subscriber])

        # If the bugtask is adjusted to no longer match the criteria of the
        # first filter, the subscription is still found.
        self.bugtask.transitionToStatus(
            BugTaskStatus.INPROGRESS, self.ordinary_subscriber)
        self.assertSubscribers([self.ordinary_subscriber])


class TestStructuralSubscriptionFiltersForDistro(
    FilteredStructuralSubscriptionTestBase, TestCaseWithFactory):

    def makeTarget(self):
        return self.factory.makeDistribution()


class TestStructuralSubscriptionFiltersForProduct(
    FilteredStructuralSubscriptionTestBase, TestCaseWithFactory):

    def makeTarget(self):
        return self.factory.makeProduct()


class TestStructuralSubscriptionFiltersForDistroSourcePackage(
    FilteredStructuralSubscriptionTestBase, TestCaseWithFactory):

    def makeTarget(self):
        return self.factory.makeDistributionSourcePackage()


class TestStructuralSubscriptionFiltersForMilestone(
    FilteredStructuralSubscriptionTestBase, TestCaseWithFactory):

    def makeTarget(self):
        return self.factory.makeMilestone()

    def makeBugTask(self):
        bug = self.factory.makeBug(milestone=self.target)
        return bug.bugtasks[0]


class TestStructuralSubscriptionFiltersForDistroSeries(
    FilteredStructuralSubscriptionTestBase, TestCaseWithFactory):

    def makeTarget(self):
        return self.factory.makeDistroSeries()


class TestStructuralSubscriptionFiltersForProjectGroup(
    FilteredStructuralSubscriptionTestBase, TestCaseWithFactory):

    def makeTarget(self):
        return self.factory.makeProject()

    def makeBugTask(self):
        return self.factory.makeBugTask(
            target=self.factory.makeProduct(project=self.target))


class TestStructuralSubscriptionFiltersForProductSeries(
    FilteredStructuralSubscriptionTestBase, TestCaseWithFactory):

    def makeTarget(self):
        return self.factory.makeProductSeries()


class TestGetStructuralSubscriptionTargets(TestCaseWithFactory):

    layer = DatabaseFunctionalLayer

    def test_product_target(self):
        product = self.factory.makeProduct()
        bug = self.factory.makeBug(product=product)
        bugtask = bug.bugtasks[0]
        result = get_structural_subscription_targets(bug.bugtasks)
        self.assertEqual(list(result), [(bugtask, product)])

    def test_milestone_target(self):
        actor = self.factory.makePerson()
        login_person(actor)
        product = self.factory.makeProduct()
        milestone = self.factory.makeMilestone(product=product)
        bug = self.factory.makeBug(product=product, milestone=milestone)
        bugtask = bug.bugtasks[0]
        result = get_structural_subscription_targets(bug.bugtasks)
        self.assertEqual(set(result), set(
            ((bugtask, product), (bugtask, milestone))))

    def test_sourcepackage_target(self):
        actor = self.factory.makePerson()
        login_person(actor)
        distroseries = self.factory.makeDistroSeries()
        sourcepackage = self.factory.makeSourcePackage(
            distroseries=distroseries, publish=True)
        product = self.factory.makeProduct()
        bug = self.factory.makeBug(product=product)
        bug.addTask(actor, sourcepackage)
        product_bugtask = bug.bugtasks[0]
        sourcepackage_bugtask = bug.bugtasks[1]
        result = get_structural_subscription_targets(bug.bugtasks)
        self.assertEqual(set(result), set(
            ((product_bugtask, product),
             (sourcepackage_bugtask, distroseries))))

    def test_distribution_source_package_target(self):
        actor = self.factory.makePerson()
        login_person(actor)
        distribution = self.factory.makeDistribution()
        dist_sourcepackage = self.factory.makeDistributionSourcePackage(
            distribution=distribution)
        product = self.factory.makeProduct()
        bug = self.factory.makeBug(product=product)
        bug.addTask(actor, dist_sourcepackage)
        product_bugtask = bug.bugtasks[0]
        dist_sourcepackage_bugtask = bug.bugtasks[1]
        result = get_structural_subscription_targets(bug.bugtasks)
        self.assertEqual(set(result), set(
            ((product_bugtask, product),
             (dist_sourcepackage_bugtask, dist_sourcepackage),
             (dist_sourcepackage_bugtask, distribution))))

    def test_product_with_project_group(self):
        # get_structural_subscription_targets() will yield both a
        # product and its parent project group if it has one.
        project = self.factory.makeProject()
        product = self.factory.makeProduct(
            project=project, owner=project.owner)
        subscriber = self.factory.makePerson()
        with person_logged_in(subscriber):
            project.addBugSubscription(subscriber, subscriber)
        # This is a sanity check.
        self.assertEqual(project, product.parent_subscription_target)
        bug = self.factory.makeBug(product=product)
        result = get_structural_subscription_targets(bug.bugtasks)
        self.assertEqual(
            set([(bug.bugtasks[0], product), (bug.bugtasks[0], project)]),
            set(result))


class TestGetStructuralSubscriptionsForBug(TestCaseWithFactory):

    layer = DatabaseFunctionalLayer

    def setUp(self):
        super(TestGetStructuralSubscriptionsForBug, self).setUp()
        self.subscriber = self.factory.makePerson()
        self.team = self.factory.makeTeam(members=[self.subscriber])
        login_person(self.subscriber)
        self.product = self.factory.makeProduct()
        self.milestone = self.factory.makeMilestone(product=self.product)
        self.bug = self.factory.makeBug(
            product=self.product, milestone=self.milestone)

    def getSubscriptions(self, person=None):
        result = get_structural_subscriptions_for_bug(self.bug, person)
        self.assertTrue(is_security_proxied_or_harmless(result))
        return result

    def test_no_subscriptions(self):
        subscriptions = self.getSubscriptions(self.subscriber)
        self.assertEqual([], list(subscriptions))

    def test_one_subscription(self):
        sub = self.product.addBugSubscription(
            self.subscriber, self.subscriber)
        subscriptions = self.getSubscriptions(self.subscriber)
        self.assertEqual([sub], list(subscriptions))

    def test_two_subscriptions(self):
        sub1 = self.product.addBugSubscription(
            self.subscriber, self.subscriber)
        sub2 = self.milestone.addBugSubscription(
            self.subscriber, self.subscriber)
        subscriptions = self.getSubscriptions(self.subscriber)
        self.assertEqual(set([sub1, sub2]), set(subscriptions))

    def test_two_bugtasks_one_subscription(self):
        sub = self.product.addBugSubscription(
            self.subscriber, self.subscriber)
        product2 = self.factory.makeProduct()
        self.bug.addTask(self.subscriber, product2)
        subscriptions = self.getSubscriptions(self.subscriber)
        self.assertEqual([sub], list(subscriptions))

    def test_two_bugtasks_two_subscriptions(self):
        sub1 = self.product.addBugSubscription(
            self.subscriber, self.subscriber)
        product2 = self.factory.makeProduct()
        self.bug.addTask(self.subscriber, product2)
        sub2 = product2.addBugSubscription(
            self.subscriber, self.subscriber)
        subscriptions = self.getSubscriptions(self.subscriber)
        self.assertEqual(set([sub1, sub2]), set(subscriptions))

    def test_ignore_other_subscriptions(self):
        sub1 = self.product.addBugSubscription(
            self.subscriber, self.subscriber)
        another_subscriber = self.factory.makePerson()
        login_person(another_subscriber)
        sub2 = self.product.addBugSubscription(
            another_subscriber, another_subscriber)
        subscriptions = self.getSubscriptions(self.subscriber)
        self.assertEqual([sub1], list(subscriptions))
        subscriptions = self.getSubscriptions(another_subscriber)
        self.assertEqual([sub2], list(subscriptions))

    def test_team_subscription(self):
        with person_logged_in(self.team.teamowner):
            sub = self.product.addBugSubscription(
                self.team, self.team.teamowner)
        subscriptions = self.getSubscriptions(self.subscriber)
        self.assertEqual([sub], list(subscriptions))

    def test_both_subscriptions(self):
        self_sub = self.product.addBugSubscription(
            self.subscriber, self.subscriber)
        with person_logged_in(self.team.teamowner):
            team_sub = self.product.addBugSubscription(
                self.team, self.team.teamowner)
        subscriptions = self.getSubscriptions(self.subscriber)
        self.assertEqual(set([self_sub, team_sub]), set(subscriptions))

    def test_subscriptions_from_parent(self):
        # get_structural_subscriptions_for_bug() will return any
        # structural subscriptions from the parents of the targets of
        # that bug.
        project = self.factory.makeProject()
        product = self.factory.makeProduct(
            project=project, owner=project.owner)
        subscriber = self.factory.makePerson()
        self_sub = project.addBugSubscription(subscriber, subscriber)
        # This is a sanity check.
        self.assertEqual(project, product.parent_subscription_target)
        bug = self.factory.makeBug(product=product)
        subscriptions = get_structural_subscriptions_for_bug(
            bug, subscriber)
        self.assertEqual(set([self_sub]), set(subscriptions))


class TestGetStructuralSubscriptions(TestCaseWithFactory):

    layer = DatabaseFunctionalLayer

    def make_product_with_bug(self):
        product = self.factory.makeProduct()
        bug = self.factory.makeBug(product=product)
        return product, bug

    def test_get_structural_subscriptions_no_subscriptions(self):
        # If there are no subscriptions for any of the bug's targets then no
        # subscriptions will be returned by get_structural_subscriptions().
        product, bug = self.make_product_with_bug()
        subscriptions = get_structural_subscriptions(bug, None)
        self.assertIsInstance(subscriptions, RESULT_SETS)
        self.assertEqual([], list(subscriptions))

    def test_get_structural_subscriptions_single_target(self):
        # Subscriptions for any of the bug's targets are returned.
        subscriber = self.factory.makePerson()
        login_person(subscriber)
        product, bug = self.make_product_with_bug()
        subscription = product.addBugSubscription(subscriber, subscriber)
        self.assertContentEqual(
            [subscription], get_structural_subscriptions(bug, None))

    def test_get_structural_subscriptions_multiple_targets(self):
        # Subscriptions for any of the bug's targets are returned.
        actor = self.factory.makePerson()
        login_person(actor)

        subscriber1 = self.factory.makePerson()
        subscriber2 = self.factory.makePerson()

        product1 = self.factory.makeProduct(owner=actor)
        subscription1 = product1.addBugSubscription(subscriber1, subscriber1)
        product2 = self.factory.makeProduct(owner=actor)
        subscription2 = product2.addBugSubscription(subscriber2, subscriber2)

        bug = self.factory.makeBug(product=product1)
        bug.addTask(actor, product2)

        subscriptions = get_structural_subscriptions(bug, None)
        self.assertIsInstance(subscriptions, RESULT_SETS)
        self.assertContentEqual(
            [subscription1, subscription2], subscriptions)

    def test_get_structural_subscriptions_multiple_targets_2(self):
        # Only the first of multiple subscriptions for a person is returned
        # when they have multiple matching subscriptions.
        actor = self.factory.makePerson()
        login_person(actor)

        subscriber = self.factory.makePerson()
        product1 = self.factory.makeProduct(owner=actor)
        subscription1 = product1.addBugSubscription(subscriber, subscriber)
        product2 = self.factory.makeProduct(owner=actor)
        product2.addBugSubscription(subscriber, subscriber)

        bug = self.factory.makeBug(product=product1)
        bug.addTask(actor, product2)

        subscriptions = get_structural_subscriptions(bug, None)
        self.assertIsInstance(subscriptions, RESULT_SETS)
        self.assertContentEqual([subscription1], subscriptions)

    def test_get_structural_subscriptions_level(self):
        # get_structural_subscriptions() respects the given level.
        subscriber = self.factory.makePerson()
        login_person(subscriber)
        product, bug = self.make_product_with_bug()
        subscription = product.addBugSubscription(subscriber, subscriber)
        filter = subscription.bug_filters.one()
        filter.bug_notification_level = BugNotificationLevel.METADATA
        self.assertContentEqual(
            [subscription], get_structural_subscriptions(
                bug, BugNotificationLevel.METADATA))
        self.assertContentEqual(
            [], get_structural_subscriptions(
                bug, BugNotificationLevel.COMMENTS))

    def test_get_structural_subscriptions_exclude(self):
        # Subscriptions for any of the given excluded subscribers are not
        # returned.
        subscriber = self.factory.makePerson()
        login_person(subscriber)
        product, bug = self.make_product_with_bug()
        product.addBugSubscription(subscriber, subscriber)
        self.assertContentEqual(
            [], get_structural_subscriptions(
                bug, None, exclude=[subscriber]))


class TestGetStructuralSubscribers(TestCaseWithFactory):

    layer = DatabaseFunctionalLayer

    def make_product_with_bug(self):
        product = self.factory.makeProduct()
        bug = self.factory.makeBug(product=product)
        return product, bug

    def test_getStructuralSubscribers_no_subscribers(self):
        # If there are no subscribers for any of the bug's targets then no
        # subscribers will be returned by get_structural_subscribers().
        product, bug = self.make_product_with_bug()
        subscribers = get_structural_subscribers(bug, None, None, None)
        self.assertIsInstance(subscribers, RESULT_SETS)
        self.assertEqual([], list(subscribers))

    def test_getStructuralSubscribers_single_target(self):
        # Subscribers for any of the bug's targets are returned.
        subscriber = self.factory.makePerson()
        login_person(subscriber)
        product, bug = self.make_product_with_bug()
        product.addBugSubscription(subscriber, subscriber)
        self.assertEqual(
            [subscriber], list(
                get_structural_subscribers(bug, None, None, None)))

    def test_getStructuralSubscribers_multiple_targets(self):
        # Subscribers for any of the bug's targets are returned.
        actor = self.factory.makePerson()
        login_person(actor)

        subscriber1 = self.factory.makePerson()
        subscriber2 = self.factory.makePerson()

        product1 = self.factory.makeProduct(owner=actor)
        product1.addBugSubscription(subscriber1, subscriber1)
        product2 = self.factory.makeProduct(owner=actor)
        product2.addBugSubscription(subscriber2, subscriber2)

        bug = self.factory.makeBug(product=product1)
        bug.addTask(actor, product2)

        subscribers = get_structural_subscribers(bug, None, None, None)
        self.assertIsInstance(subscribers, RESULT_SETS)
        self.assertEqual(set([subscriber1, subscriber2]), set(subscribers))

    def test_getStructuralSubscribers_recipients(self):
        # If provided, get_structural_subscribers() calls the appropriate
        # methods on a BugNotificationRecipients object.
        subscriber = self.factory.makePerson()
        login_person(subscriber)
        product, bug = self.make_product_with_bug()
        product.addBugSubscription(subscriber, subscriber)
        recipients = BugNotificationRecipients()
        subscribers = get_structural_subscribers(bug, recipients, None, None)
        # The return value is a list only when populating recipients.
        self.assertIsInstance(subscribers, list)
        self.assertEqual([subscriber], recipients.getRecipients())
        reason, header = recipients.getReason(subscriber)
        self.assertThat(
            reason, StartsWith(
                u"You received this bug notification because "
                u"you are subscribed to "))
        self.assertThat(header, StartsWith(u"Subscriber "))

    def test_getStructuralSubscribers_level(self):
        # get_structural_subscribers() respects the given level.
        subscriber = self.factory.makePerson()
        login_person(subscriber)
        product, bug = self.make_product_with_bug()
        subscription = product.addBugSubscription(subscriber, subscriber)
        filter = subscription.bug_filters.one()
        filter.bug_notification_level = BugNotificationLevel.METADATA
        self.assertEqual(
            [subscriber], list(
                get_structural_subscribers(
                    bug, None, BugNotificationLevel.METADATA, None)))
        filter.bug_notification_level = BugNotificationLevel.METADATA
        self.assertEqual(
            [], list(
                get_structural_subscribers(
                    bug, None, BugNotificationLevel.COMMENTS, None)))


class TestBugSubscriptionFilterMute(TestCaseWithFactory):
    """Tests for the BugSubscriptionFilterMute class."""

    layer = DatabaseFunctionalLayer

    def setUp(self):
        super(TestBugSubscriptionFilterMute, self).setUp()
        self.target = self.factory.makeProduct()
        self.team = self.factory.makeTeam()
        self.team_member = self.factory.makePerson()
        with person_logged_in(self.team.teamowner):
            self.team.addMember(self.team_member, self.team.teamowner)
            self.team_subscription = self.target.addBugSubscription(
                self.team, self.team.teamowner)
            self.filter = self.team_subscription.bug_filters.one()

    def test_isMuteAllowed_returns_true_for_team_subscriptions(self):
        # BugSubscriptionFilter.isMuteAllowed() will return True for
        # subscriptions where the owner of the subscription is a team.
        self.assertTrue(self.filter.isMuteAllowed(self.team_member))

    def test_isMuteAllowed_returns_false_for_non_team_subscriptions(self):
        # BugSubscriptionFilter.isMuteAllowed() will return False for
        # subscriptions where the owner of the subscription is not a team.
        person = self.factory.makePerson()
        with person_logged_in(person):
            non_team_subscription = self.target.addBugSubscription(
                person, person)
        filter = non_team_subscription.bug_filters.one()
        self.assertFalse(filter.isMuteAllowed(person))

    def test_isMuteAllowed_returns_false_for_non_team_members(self):
        # BugSubscriptionFilter.isMuteAllowed() will return False if the
        # user passed to it is not a member of the subscribing team.
        non_team_person = self.factory.makePerson()
        self.assertFalse(self.filter.isMuteAllowed(non_team_person))

    def test_mute_adds_mute(self):
        # BugSubscriptionFilter.mute() adds a mute for the filter.
        filter_id = self.filter.id
        person_id = self.team_member.id
        store = Store.of(self.filter)
        mutes = store.find(
            BugSubscriptionFilterMute,
            BugSubscriptionFilterMute.filter == filter_id,
            BugSubscriptionFilterMute.person == person_id)
        self.assertTrue(mutes.is_empty())
        self.assertFalse(self.filter.muted(self.team_member))
        self.filter.mute(self.team_member)
        self.assertTrue(self.filter.muted(self.team_member))
        store.flush()
        self.assertFalse(mutes.is_empty())

    def test_unmute_removes_mute(self):
        # BugSubscriptionFilter.unmute() removes any mute for a given
        # person on that filter.
        filter_id = self.filter.id
        person_id = self.team_member.id
        store = Store.of(self.filter)
        self.filter.mute(self.team_member)
        store.flush()
        mutes = store.find(
            BugSubscriptionFilterMute,
            BugSubscriptionFilterMute.filter == filter_id,
            BugSubscriptionFilterMute.person == person_id)
        self.assertFalse(mutes.is_empty())
        self.assertTrue(self.filter.muted(self.team_member))
        self.filter.unmute(self.team_member)
        self.assertFalse(self.filter.muted(self.team_member))
        store.flush()
        self.assertTrue(mutes.is_empty())

    def test_mute_is_idempotent(self):
        # Muting works even if the user is already muted.
        store = Store.of(self.filter)
        mute = self.filter.mute(self.team_member)
        store.flush()
        second_mute = self.filter.mute(self.team_member)
        self.assertEqual(mute, second_mute)

    def test_unmute_is_idempotent(self):
        # Unmuting works even if the user is not muted
        store = Store.of(self.filter)
        mutes = store.find(
            BugSubscriptionFilterMute,
            BugSubscriptionFilterMute.filter == self.filter.id,
            BugSubscriptionFilterMute.person == self.team_member.id)
        self.assertTrue(mutes.is_empty())
        self.filter.unmute(self.team_member)
        self.assertTrue(mutes.is_empty())

    def test_mute_raises_error_for_non_team_subscriptions(self):
        # BugSubscriptionFilter.mute() will raise an error if called on
        # a non-team subscription.
        person = self.factory.makePerson()
        with person_logged_in(person):
            non_team_subscription = self.target.addBugSubscription(
                person, person)
        filter = non_team_subscription.bug_filters.one()
        self.assertFalse(filter.isMuteAllowed(person))
        self.assertRaises(MuteNotAllowed, filter.mute, person)

    def test_mute_raises_error_for_non_team_members(self):
        # BugSubscriptionFilter.mute() will raise an error if called on
        # a subscription of which the calling person is not a member.
        non_team_person = self.factory.makePerson()
        self.assertFalse(self.filter.isMuteAllowed(non_team_person))
        self.assertRaises(MuteNotAllowed, self.filter.mute, non_team_person)