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
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
|
# Copyright 2010-2011 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
__metaclass__ = type
from datetime import (
datetime,
timedelta,
)
from pytz import UTC
from storm.store import Store
from testtools.testcase import ExpectedException
from zope.component import getUtility
from zope.security.proxy import removeSecurityProxy
from lp.bugs.adapters.bugchange import BugTitleChange
from lp.bugs.enum import (
BugNotificationLevel,
BugNotificationStatus,
)
from lp.bugs.errors import BugCannotBePrivate
from lp.bugs.interfaces.bugnotification import IBugNotificationSet
from lp.bugs.interfaces.bugtask import BugTaskStatus
from lp.bugs.model.bug import (
BugNotification,
BugSubscriptionInfo,
)
from lp.bugs.model.bugnotification import BugNotificationRecipient
from lp.bugs.scripts.bugnotification import get_email_notifications
from lp.registry.interfaces.person import PersonVisibility
from lp.services.database.lpstorm import IStore
from lp.services.features.testing import FeatureFixture
from lp.testing import (
feature_flags,
login_person,
person_logged_in,
set_feature_flag,
StormStatementRecorder,
TestCaseWithFactory,
)
from lp.testing.layers import DatabaseFunctionalLayer
from lp.testing.matchers import (
Equals,
HasQueryCount,
LessThan,
)
class TestBug(TestCaseWithFactory):
layer = DatabaseFunctionalLayer
def test_markAsDuplicate_None(self):
# Calling markAsDuplicate(None) on a bug that is not currently a
# duplicate works correctly, and does not raise an AttributeError.
bug = self.factory.makeBug()
with ExpectedException(AssertionError, 'AttributeError not raised'):
with ExpectedException(AttributeError, ''):
with person_logged_in(self.factory.makePerson()):
bug.markAsDuplicate(None)
def test_get_subscribers_for_person_unsubscribed(self):
bug = self.factory.makeBug()
person = self.factory.makePerson()
self.assertTrue(bug.getSubscribersForPerson(person).is_empty())
def test_get_subscribers_for_person_direct_subscription(self):
bug = self.factory.makeBug()
person = self.factory.makePerson()
with person_logged_in(person):
bug.subscribe(person, person)
self.assertEqual([person], list(bug.getSubscribersForPerson(person)))
def test_get_subscribers_for_person_indirect_subscription(self):
bug = self.factory.makeBug()
person = self.factory.makePerson()
team1 = self.factory.makeTeam(members=[person])
self.factory.makeTeam(members=[person])
with person_logged_in(person):
bug.subscribe(team1, person)
self.assertEqual([team1], list(bug.getSubscribersForPerson(person)))
def test_get_subscribers_for_person_many_subscriptions(self):
bug = self.factory.makeBug()
person = self.factory.makePerson()
team1 = self.factory.makeTeam(members=[person])
team2 = self.factory.makeTeam(members=[person])
with person_logged_in(person):
bug.subscribe(team1, person)
bug.subscribe(team2, person)
bug.subscribe(person, person)
self.assertEqual(
set([person, team1, team2]),
set(bug.getSubscribersForPerson(person)))
def test_get_subscribers_for_person_from_duplicates_too(self):
bug = self.factory.makeBug()
real_bug = self.factory.makeBug()
person = self.factory.makePerson()
team1 = self.factory.makeTeam(members=[person])
team2 = self.factory.makeTeam(members=[person])
with person_logged_in(person):
bug.subscribe(team1, person)
bug.subscribe(team2, person)
bug.subscribe(person, person)
bug.markAsDuplicate(real_bug)
self.assertEqual(
set([person, team1, team2]),
set(real_bug.getSubscribersForPerson(person)))
def test_getSubscriptionsFromDuplicates(self):
# getSubscriptionsFromDuplicates() will return only the earliest
# subscription if a user is subscribed to a bug via more than one
# duplicate.
user = self.factory.makePerson()
login_person(user)
bug = self.factory.makeBug(owner=user)
dupe1 = self.factory.makeBug(owner=user)
dupe1.markAsDuplicate(bug)
subscription = dupe1.subscribe(user, user)
dupe2 = self.factory.makeBug(owner=user)
dupe2.markAsDuplicate(bug)
dupe2.subscribe(user, user)
self.assertEqual(
[subscription], list(bug.getSubscriptionsFromDuplicates()))
def test_get_also_notified_subscribers_with_private_team(self):
product = self.factory.makeProduct()
bug = self.factory.makeBug(product=product)
member = self.factory.makePerson()
team = self.factory.makeTeam(
owner=member, visibility=PersonVisibility.PRIVATE)
with person_logged_in(member):
product.addSubscription(team, member)
self.assertTrue(team in bug.getAlsoNotifiedSubscribers())
def test_get_indirect_subscribers_with_private_team(self):
product = self.factory.makeProduct()
bug = self.factory.makeBug(product=product)
member = self.factory.makePerson()
team = self.factory.makeTeam(
owner=member, visibility=PersonVisibility.PRIVATE)
with person_logged_in(member):
product.addSubscription(team, member)
self.assertTrue(team in bug.getIndirectSubscribers())
def test_get_direct_subscribers_with_private_team(self):
product = self.factory.makeProduct()
bug = self.factory.makeBug(product=product)
member = self.factory.makePerson()
team = self.factory.makeTeam(
owner=member, visibility=PersonVisibility.PRIVATE)
with person_logged_in(member):
bug.subscribe(team, member)
self.assertTrue(team in bug.getDirectSubscribers())
def test_get_direct_subscribers_query_count(self):
bug = self.factory.makeBug()
# Make lots of subscribers.
for i in xrange(10):
subscriber = self.factory.makePerson()
with person_logged_in(subscriber):
bug.subscribe(subscriber, subscriber)
Store.of(bug).flush()
with StormStatementRecorder() as recorder:
subscribers = list(bug.getDirectSubscribers())
self.assertThat(len(subscribers), Equals(10 + 1))
self.assertThat(recorder, HasQueryCount(Equals(1)))
def test_mark_as_duplicate_query_count(self):
bug = self.factory.makeBug()
# Make lots of duplicate bugs.
previous_dup = None
for i in xrange(10):
dup = self.factory.makeBug()
# Make lots of subscribers.
for j in xrange(10):
subscriber = self.factory.makePerson()
with person_logged_in(subscriber):
dup.subscribe(subscriber, subscriber)
if previous_dup is not None:
with person_logged_in(previous_dup.owner):
previous_dup.markAsDuplicate(dup)
previous_dup = dup
with person_logged_in(bug.owner):
Store.of(bug).flush()
with StormStatementRecorder() as recorder:
previous_dup.markAsDuplicate(bug)
self.assertThat(recorder, HasQueryCount(LessThan(95)))
def _get_notifications(self, status):
return self.store.find(
BugNotification,
BugNotification.date_emailed == None,
BugNotification.status == status)
def _get_pending(self):
return self._get_notifications(BugNotificationStatus.PENDING)
def _get_deferred(self):
return self._get_notifications(BugNotificationStatus.DEFERRED)
def _add_subscribers(self, bug, number):
for i in xrange(number):
subscriber = self.factory.makePerson()
with person_logged_in(subscriber):
bug.subscribe(subscriber, subscriber)
def test_duplicate_subscriber_notifications(self):
# Notifications for duplicate bugs are deferred where notifications
# for direct subscribers of the original bug are pending.
bug = self.factory.makeBug(title="bug-0")
self._add_subscribers(bug, 3)
self.store = Store.of(bug)
duplicates = []
# Make a few duplicate bugs.
for i in xrange(3):
duplicates.append(self.factory.makeBug(title="bug-%d" % (i + 1)))
# Pending messages exist for the bug creation.
self.assertEqual(4, self._get_pending().count())
self.assertEqual(0, self._get_deferred().count())
previous_dup = None
for dup in duplicates:
# Make a few subscribers.
self._add_subscribers(dup, 3)
if previous_dup is not None:
with person_logged_in(previous_dup.owner):
previous_dup.markAsDuplicate(dup)
previous_dup = dup
# Pending messages are still all from bug creation.
# Only one deferred notification has been created, since notices for
# the primary bug are not deferred and are created by the calling
# process (browser or API).
self.assertEqual(4, self._get_pending().count())
self.assertEqual(1, self._get_deferred().count())
with person_logged_in(bug.owner):
previous_dup.markAsDuplicate(bug)
# Now there are two new deferred messages, for the duplicates to the
# last bug.
self.assertEqual(4, self._get_pending().count())
self.assertEqual(3, self._get_deferred().count())
# The method for retrieving deferred notification reports them all.
deferred = getUtility(IBugNotificationSet).getDeferredNotifications()
self.assertEqual(3, deferred.count())
def test_get_subscribers_from_duplicates_with_private_team(self):
product = self.factory.makeProduct()
bug = self.factory.makeBug(product=product)
dupe_bug = self.factory.makeBug()
member = self.factory.makePerson()
team = self.factory.makeTeam(
owner=member, visibility=PersonVisibility.PRIVATE)
with person_logged_in(member):
dupe_bug.subscribe(team, member)
dupe_bug.markAsDuplicate(bug)
self.assertTrue(team in bug.getSubscribersFromDuplicates())
def test_subscribe_with_level(self):
# It's possible to subscribe to a bug at a different
# BugNotificationLevel by passing a `level` parameter to
# subscribe().
bug = self.factory.makeBug()
for level in BugNotificationLevel.items:
subscriber = self.factory.makePerson()
with person_logged_in(subscriber):
subscription = bug.subscribe(
subscriber, subscriber, level=level)
self.assertEqual(level, subscription.bug_notification_level)
def test_resubscribe_with_level(self):
# If you pass a new level to subscribe with an existing subscription,
# the level is set on the existing subscription.
bug = self.factory.makeBug()
subscriber = self.factory.makePerson()
levels = list(BugNotificationLevel.items)
with person_logged_in(subscriber):
subscription = bug.subscribe(
subscriber, subscriber, level=levels[-1])
for level in levels:
with person_logged_in(subscriber):
bug.subscribe(subscriber, subscriber, level=level)
self.assertEqual(level, subscription.bug_notification_level)
def test_get_direct_subscribers_with_level(self):
# It's possible to pass a level parameter to
# getDirectSubscribers() to filter the subscribers returned.
# When a `level` is passed to getDirectSubscribers(), the
# subscribers returned will be those of that level of
# subscription or higher.
bug = self.factory.makeBug()
# We unsubscribe the bug's owner because if we don't there will
# be two COMMENTS-level subscribers.
with person_logged_in(bug.owner):
bug.unsubscribe(bug.owner, bug.owner)
reversed_levels = sorted(
BugNotificationLevel.items, reverse=True)
subscribers = []
for level in reversed_levels:
subscriber = self.factory.makePerson()
subscribers.append(subscriber)
with person_logged_in(subscriber):
bug.subscribe(subscriber, subscriber, level=level)
direct_subscribers = bug.getDirectSubscribers(level=level)
# All the previous subscribers will be included because
# their level of subscription is such that they also receive
# notifications at the current level.
self.assertEqual(
set(subscribers), set(direct_subscribers),
"Subscribers did not match expected value.")
def test_get_direct_subscribers_default_level(self):
# If no `level` parameter is passed to getDirectSubscribers(),
# the assumed `level` is BugNotification.LIFECYCLE.
bug = self.factory.makeBug()
# We unsubscribe the bug's owner because if we don't there will
# be two COMMENTS-level subscribers.
with person_logged_in(bug.owner):
bug.unsubscribe(bug.owner, bug.owner)
subscribers = []
for level in BugNotificationLevel.items:
subscriber = self.factory.makePerson()
subscribers.append(subscriber)
with person_logged_in(subscriber):
bug.subscribe(subscriber, subscriber, level=level)
# All the subscribers should be returned by
# getDirectSubscribers() because it defaults to returning
# subscribers at level LIFECYCLE, which everything is higher than.
direct_subscribers = bug.getDirectSubscribers()
self.assertEqual(
set(subscribers), set(direct_subscribers),
"Subscribers did not match expected value.")
def test_get_direct_subscribers_with_details_other_subscriber(self):
# getDirectSubscribersWithDetails() returns
# Person and BugSubscription records in one go as well as the
# BugSubscription.subscribed_by person.
bug = self.factory.makeBug()
with person_logged_in(bug.owner):
# Unsubscribe bug owner so it doesn't taint the result.
bug.unsubscribe(bug.owner, bug.owner)
subscriber = self.factory.makePerson()
subscribee = self.factory.makePerson()
with person_logged_in(subscriber):
subscription = bug.subscribe(
subscribee, subscriber, level=BugNotificationLevel.LIFECYCLE)
self.assertContentEqual(
[(subscribee, subscriber, subscription)],
bug.getDirectSubscribersWithDetails())
def test_get_direct_subscribers_with_details_self_subscribed(self):
# getDirectSubscribersWithDetails() returns
# Person and BugSubscription records in one go as well as the
# BugSubscription.subscribed_by person.
bug = self.factory.makeBug()
with person_logged_in(bug.owner):
# Unsubscribe bug owner so it doesn't taint the result.
bug.unsubscribe(bug.owner, bug.owner)
subscriber = self.factory.makePerson()
with person_logged_in(subscriber):
subscription = bug.subscribe(
subscriber, subscriber, level=BugNotificationLevel.LIFECYCLE)
self.assertContentEqual(
[(subscriber, subscriber, subscription)],
bug.getDirectSubscribersWithDetails())
def test_get_direct_subscribers_with_details_mute_excludes(self):
# getDirectSubscribersWithDetails excludes muted subscriptions.
bug = self.factory.makeBug()
with person_logged_in(bug.owner):
# Unsubscribe bug owner so it doesn't taint the result.
bug.unsubscribe(bug.owner, bug.owner)
subscriber = self.factory.makePerson()
with person_logged_in(subscriber):
bug.subscribe(
subscriber, subscriber, level=BugNotificationLevel.LIFECYCLE)
bug.mute(subscriber, subscriber)
self.assertContentEqual(
[], bug.getDirectSubscribersWithDetails())
def test_subscribers_from_dupes_uses_level(self):
# When getSubscribersFromDuplicates() is passed a `level`
# parameter it will include only subscribers subscribed to
# duplicates at that BugNotificationLevel or higher.
bug = self.factory.makeBug()
duplicate_bug = self.factory.makeBug()
with person_logged_in(duplicate_bug.owner):
duplicate_bug.markAsDuplicate(bug)
# We unsubscribe the owner of the duplicate to avoid muddling
# the results retuned by getSubscribersFromDuplicates()
duplicate_bug.unsubscribe(
duplicate_bug.owner, duplicate_bug.owner)
for level in BugNotificationLevel.items:
subscriber = self.factory.makePerson()
with person_logged_in(subscriber):
duplicate_bug.subscribe(subscriber, subscriber, level=level)
# Only the most recently subscribed person will be included
# because the previous subscribers are subscribed at a lower
# level.
self.assertEqual(
(subscriber,),
bug.getSubscribersFromDuplicates(level=level))
def test_subscribers_from_dupes_overrides_using_level(self):
# Bug.getSubscribersFromDuplicates() does not return subscribers
# who also have a direct subscription to the master bug provided
# that the subscription to the master bug is of the same level
# or higher as the subscription to the duplicate.
bug = self.factory.makeBug()
duplicate_bug = self.factory.makeBug()
with person_logged_in(duplicate_bug.owner):
duplicate_bug.markAsDuplicate(bug)
# We unsubscribe the owner of the duplicate to avoid muddling
# the results retuned by getSubscribersFromDuplicates()
duplicate_bug.unsubscribe(
duplicate_bug.owner, duplicate_bug.owner)
subscriber = self.factory.makePerson()
with person_logged_in(subscriber):
bug.subscribe(
subscriber, subscriber, level=BugNotificationLevel.LIFECYCLE)
duplicate_bug.subscribe(
subscriber, subscriber, level=BugNotificationLevel.METADATA)
duplicate_subscribers = bug.getSubscribersFromDuplicates()
self.assertTrue(
subscriber not in duplicate_subscribers,
"Subscriber should not be in duplicate_subscribers.")
def test_getSubscriptionInfo(self):
# getSubscriptionInfo() returns a BugSubscriptionInfo object.
bug = self.factory.makeBug()
with person_logged_in(bug.owner):
info = bug.getSubscriptionInfo()
self.assertIsInstance(info, BugSubscriptionInfo)
self.assertEqual(bug, info.bug)
self.assertEqual(BugNotificationLevel.LIFECYCLE, info.level)
# A level can also be specified.
with person_logged_in(bug.owner):
info = bug.getSubscriptionInfo(BugNotificationLevel.METADATA)
self.assertEqual(BugNotificationLevel.METADATA, info.level)
def test_getVisibleLinkedBranches_doesnt_rtn_inaccessible_branches(self):
# If a Bug has branches linked to it that the current user
# cannot access, those branches will not be returned in its
# linked_branches property.
bug = self.factory.makeBug()
private_branch_owner = self.factory.makePerson()
private_branch = self.factory.makeBranch(
owner=private_branch_owner, private=True)
with person_logged_in(private_branch_owner):
bug.linkBranch(private_branch, private_branch.registrant)
public_branch_owner = self.factory.makePerson()
public_branches = [
self.factory.makeBranch() for i in range(4)]
with person_logged_in(public_branch_owner):
for public_branch in public_branches:
bug.linkBranch(public_branch, public_branch.registrant)
with StormStatementRecorder() as recorder:
linked_branches = [
bug_branch.branch for bug_branch in
bug.getVisibleLinkedBranches(user=public_branch_owner)]
# We check that the query count is low, since that's
# part of the point of the way that linked_branches is
# implemented. If we try eager-loading all the linked
# branches the query count jumps up by 6, which is not
# what we want.
self.assertThat(recorder, HasQueryCount(LessThan(7)))
self.assertContentEqual(public_branches, linked_branches)
self.assertNotIn(private_branch, linked_branches)
class TestBugPrivateAndSecurityRelatedUpdatesMixin:
layer = DatabaseFunctionalLayer
def setUp(self):
super(TestBugPrivateAndSecurityRelatedUpdatesMixin, self).setUp()
f_flag_str = 'disclosure.enhanced_private_bug_subscriptions.enabled'
feature_flag = {f_flag_str: 'on'}
flags = FeatureFixture(feature_flag)
flags.setUp()
self.addCleanup(flags.cleanUp)
def test_setPrivate_subscribes_person_who_makes_bug_private(self):
# When setPrivate(True) is called on a bug, the person who is
# marking the bug private is subscribed to the bug.
bug = self.factory.makeBug()
person = self.factory.makePerson()
with person_logged_in(person):
bug.setPrivate(True, person)
self.assertTrue(bug.personIsDirectSubscriber(person))
def test_setPrivate_does_not_subscribe_member_of_subscribed_team(self):
# When setPrivate(True) is called on a bug, the person who is
# marking the bug private will not be subscribed if they're
# already a member of a team which is a direct subscriber.
bug = self.factory.makeBug()
team = self.factory.makeTeam()
person = team.teamowner
with person_logged_in(person):
bug.subscribe(team, person)
bug.setPrivate(True, person)
self.assertFalse(bug.personIsDirectSubscriber(person))
def createBugTasksAndSubscribers(self, private_security_related=False):
# Used with the various setPrivateAndSecurityRelated tests to create
# a bug and add some initial subscribers.
bug_owner = self.factory.makePerson(name='bugowner')
bug_supervisor = self.factory.makePerson(
name='bugsupervisor', email='bugsupervisor@example.com')
product_owner = self.factory.makePerson(name='productowner')
product_driver = self.factory.makePerson(name='productdriver')
security_contact = self.factory.makePerson(
name='securitycontact', email='securitycontact@example.com')
bug_product = self.factory.makeProduct(
owner=product_owner, bug_supervisor=bug_supervisor,
driver=product_driver, security_contact=security_contact)
if self.private_project:
removeSecurityProxy(bug_product).private_bugs = True
bug = self.factory.makeBug(owner=bug_owner, product=bug_product)
with person_logged_in(bug_owner):
bug.setPrivacyAndSecurityRelated(
private_security_related, private_security_related, bug_owner)
owner_a = self.factory.makePerson(name='ownera')
product_series_a = self.factory.makeProductSeries(
product=bug_product, owner=owner_a)
owner_b = self.factory.makePerson(name='ownerb')
product_series_b = self.factory.makeProductSeries(
product=bug_product, owner=owner_b)
bugtask_a = self.factory.makeBugTask(bug=bug, target=product_series_a)
bugtask_b = self.factory.makeBugTask(bug=bug, target=product_series_b)
naked_bugtask_a = removeSecurityProxy(bugtask_a)
naked_bugtask_b = removeSecurityProxy(bugtask_b)
naked_default_bugtask = removeSecurityProxy(bug.default_bugtask)
return (bug, bug_owner, naked_bugtask_a, naked_bugtask_b,
naked_default_bugtask)
def test_setPrivateTrueAndSecurityRelatedTrue(self):
# When a bug is marked as private=true and security_related=true, the
# direct subscribers should include:
# - the bug reporter
# - the bugtask pillar security contacts (if set)
# - the person changing the state
# - and bug/pillar owners, drivers if they are already subscribed
# If the bug is for a private project, then other direct subscribers
# should be unsubscribed.
(bug, bug_owner, bugtask_a, bugtask_b, default_bugtask) = (
self.createBugTasksAndSubscribers())
initial_subscribers = set((
self.factory.makePerson(), bugtask_a.owner, bug_owner,
bugtask_a.pillar.security_contact, bugtask_a.pillar.driver))
with person_logged_in(bug_owner):
for subscriber in initial_subscribers:
bug.subscribe(subscriber, bug_owner)
who = self.factory.makePerson()
bug.setPrivacyAndSecurityRelated(
private=True, security_related=True, who=who)
subscribers = bug.getDirectSubscribers()
expected_subscribers = set((
bugtask_a.owner,
default_bugtask.pillar.bug_supervisor,
default_bugtask.pillar.driver,
default_bugtask.pillar.security_contact,
bug_owner, who))
if not self.private_project:
expected_subscribers.update(initial_subscribers)
self.assertContentEqual(expected_subscribers, subscribers)
def test_setPrivateTrueAndSecurityRelatedFalse(self):
# When a bug is marked as private=true and security_related=false, the
# direct subscribers should include:
# - the bug reporter
# - the bugtask pillar bug supervisors (if set)
# - the person changing the state
# - and bug/pillar owners, drivers if they are already subscribed
# If the bug is for a private project, then other direct subscribers
# should be unsubscribed.
(bug, bug_owner, bugtask_a, bugtask_b, default_bugtask) = (
self.createBugTasksAndSubscribers(private_security_related=True))
initial_subscribers = set((
self.factory.makePerson(), bug_owner,
bugtask_a.pillar.security_contact, bugtask_a.pillar.driver))
with person_logged_in(bug_owner):
for subscriber in initial_subscribers:
bug.subscribe(subscriber, bug_owner)
who = self.factory.makePerson()
bug.setPrivacyAndSecurityRelated(
private=True, security_related=False, who=who)
subscribers = bug.getDirectSubscribers()
expected_subscribers = set((
default_bugtask.pillar.bug_supervisor,
default_bugtask.pillar.driver,
bug_owner, who))
if not self.private_project:
expected_subscribers.update(initial_subscribers)
expected_subscribers.remove(bugtask_a.pillar.security_contact)
self.assertContentEqual(expected_subscribers, subscribers)
def test_setPrivateFalseAndSecurityRelatedTrue(self):
# When a bug is marked as private=false and security_related=true, the
# direct subscribers should include:
# - the bug reporter
# - the bugtask pillar security contacts (if set)
# - and bug/pillar owners, drivers if they are already subscribed
# If the bug is for a private project, then other direct subscribers
# should be unsubscribed.
(bug, bug_owner, bugtask_a, bugtask_b, default_bugtask) = (
self.createBugTasksAndSubscribers(private_security_related=True))
initial_subscribers = set((
self.factory.makePerson(), bug_owner,
bugtask_a.pillar.security_contact, bugtask_a.pillar.driver,
bugtask_a.pillar.bug_supervisor))
with person_logged_in(bug_owner):
for subscriber in initial_subscribers:
bug.subscribe(subscriber, bug_owner)
who = self.factory.makePerson()
bug.setPrivacyAndSecurityRelated(
private=False, security_related=True, who=who)
subscribers = bug.getDirectSubscribers()
expected_subscribers = set((
default_bugtask.pillar.driver,
default_bugtask.pillar.security_contact,
bug_owner))
if not self.private_project:
expected_subscribers.update(initial_subscribers)
expected_subscribers.remove(default_bugtask.pillar.bug_supervisor)
self.assertContentEqual(expected_subscribers, subscribers)
def test_setPrivateFalseAndSecurityRelatedFalse(self):
# When a bug is marked as private=false and security_related=false,
# any existing subscriptions are left alone.
(bug, bug_owner, bugtask_a, bugtask_b, default_bugtask) = (
self.createBugTasksAndSubscribers(private_security_related=True))
initial_subscribers = set((
self.factory.makePerson(), bug_owner,
bugtask_a.pillar.security_contact, bugtask_a.pillar.driver))
with person_logged_in(bug_owner):
for subscriber in initial_subscribers:
bug.subscribe(subscriber, bug_owner)
who = self.factory.makePerson()
expected_direct_subscribers = set(bug.getDirectSubscribers())
bug.setPrivacyAndSecurityRelated(
private=False, security_related=False, who=who)
subscribers = set(bug.getDirectSubscribers())
expected_direct_subscribers.difference_update(
(default_bugtask.pillar.security_contact,
default_bugtask.pillar.bug_supervisor,
bugtask_a.pillar.security_contact))
self.assertContentEqual(expected_direct_subscribers, subscribers)
def test_setPillarOwnerSubscribedIfNoBugSupervisor(self):
# The pillar owner is subscribed if the bug supervisor is not set.
bug_owner = self.factory.makePerson(name='bugowner')
bug = self.factory.makeBug(owner=bug_owner)
with person_logged_in(bug_owner):
who = self.factory.makePerson()
bug.setPrivacyAndSecurityRelated(
private=True, security_related=False, who=who)
subscribers = bug.getDirectSubscribers()
naked_bugtask = removeSecurityProxy(bug.default_bugtask)
self.assertContentEqual(
set((naked_bugtask.pillar.owner, bug_owner, who)),
subscribers)
def test_setPillarOwnerSubscribedIfNoSecurityContact(self):
# The pillar owner is subscribed if the security contact is not set.
bug_owner = self.factory.makePerson(name='bugowner')
bug = self.factory.makeBug(owner=bug_owner)
with person_logged_in(bug_owner):
who = self.factory.makePerson()
bug.setPrivacyAndSecurityRelated(
private=False, security_related=True, who=who)
subscribers = bug.getDirectSubscribers()
naked_bugtask = removeSecurityProxy(bug.default_bugtask)
self.assertContentEqual(
set((naked_bugtask.pillar.owner, bug_owner)),
subscribers)
def _fetch_notifications(self, bug, reason_header):
store = IStore(BugNotification)
return store.find(
BugNotification,
BugNotificationRecipient.bug_notificationID == BugNotification.id,
BugNotificationRecipient.reason_header == reason_header,
BugNotification.bug == bug,
BugNotification.status == BugNotificationStatus.PENDING,
BugNotification.date_emailed == None)
def _check_email_content(self, message, expected_headers,
expected_body_text):
# Ensure that the email header values and message body text is as
# expected.
headers = {}
for header in ['X-Launchpad-Message-Rationale',
'X-Launchpad-Bug-Security-Vulnerability',
'X-Launchpad-Bug-Private']:
if message[header]:
headers[header] = message[header]
self.assertEqual(expected_headers, headers)
body_text = message.get_payload(decode=True)
self.assertTrue(expected_body_text in body_text)
def _check_notifications(self, bug, expected_recipients,
expected_body_text, expected_reason_body,
is_private, is_security_related, role):
# Ensure that the content of the pending email notifications is
# correct.
notifications = self._fetch_notifications(bug, role)
actual_recipients = []
email_notifications = get_email_notifications(notifications)
for bug_notifications, omitted, messages in email_notifications:
for message in messages:
expected_headers = {
'X-Launchpad-Bug-Private':
'yes' if is_private else 'no',
'X-Launchpad-Bug-Security-Vulnerability':
'yes' if is_security_related else 'no',
'X-Launchpad-Message-Rationale': role,
}
self._check_email_content(
message, expected_headers, expected_body_text)
expected_reason_header = role
for notification in bug_notifications:
for recipient in notification.recipients:
self.assertEqual(
expected_reason_header, recipient.reason_header)
self.assertEqual(
expected_reason_body, recipient.reason_body)
actual_recipients.append(recipient.person)
self.assertContentEqual(expected_recipients, actual_recipients)
def test_bugSupervisorUnsubscribedIfBugMadePublic(self):
# The bug supervisors are unsubscribed if a bug is made public and an
# email is sent telling them they have been unsubscribed.
(bug, bug_owner, bugtask_a, bugtask_b, default_bugtask) = (
self.createBugTasksAndSubscribers(private_security_related=True))
with person_logged_in(bug_owner):
bug.subscribe(default_bugtask.pillar.bug_supervisor, bug_owner)
who = self.factory.makePerson(name="who")
bug.setPrivacyAndSecurityRelated(
private=False, security_related=True, who=who)
subscribers = bug.getDirectSubscribers()
self.assertNotIn(
default_bugtask.pillar.bug_supervisor, subscribers)
expected_recipients = [
default_bugtask.pillar.bug_supervisor,
]
expected_body_text = '** This bug is no longer private'
expected_reason_body = ('You received this bug notification '
'because you are a bug supervisor.')
self._check_notifications(
bug, expected_recipients, expected_body_text,
expected_reason_body, False, True, 'Bug Supervisor')
def test_structural_bug_supervisor_becomes_direct_on_private(self):
# If a bug supervisor has a structural subscription to the bug, and
# the bug is marked as private, the supervisor should get a direct
# subscription. Otherwise they should be removed, per other tests.
bug_supervisor = self.factory.makePerson()
product = self.factory.makeProduct(bug_supervisor=bug_supervisor)
bug_owner = self.factory.makePerson()
bug = self.factory.makeBug(owner=bug_owner, product=product)
with person_logged_in(product.owner):
product.addSubscription(bug_supervisor, bug_supervisor)
self.assertFalse(bug_supervisor in bug.getDirectSubscribers())
with person_logged_in(bug_owner):
who = self.factory.makePerson(name="who")
bug.setPrivacyAndSecurityRelated(
private=True, security_related=False, who=who)
self.assertTrue(bug_supervisor in bug.getDirectSubscribers())
def test_securityContactUnsubscribedIfBugNotSecurityRelated(self):
# The security contacts are unsubscribed if a bug has security_related
# set to false and an email is sent telling them they have been
# unsubscribed.
(bug, bug_owner, bugtask_a, bugtask_b, default_bugtask) = (
self.createBugTasksAndSubscribers(private_security_related=True))
with person_logged_in(bug_owner):
bug.subscribe(bugtask_a.pillar.security_contact, bug_owner)
who = self.factory.makePerson(name="who")
bug.setPrivacyAndSecurityRelated(
private=True, security_related=False, who=who)
subscribers = bug.getDirectSubscribers()
self.assertFalse(bugtask_a.pillar.security_contact in subscribers)
expected_recipients = [
bugtask_a.pillar.security_contact,
]
expected_body_text = '** This bug is no longer security related'
expected_reason_body = ('You received this bug notification '
'because you are a security contact.')
self._check_notifications(
bug, expected_recipients, expected_body_text,
expected_reason_body, True, False, 'Security Contact')
class TestBugPrivacy(TestCaseWithFactory):
layer = DatabaseFunctionalLayer
def test_multipillar_private_bugs_disallowed(self):
# A multi-pillar bug cannot be made private.
bug = self.factory.makeBug()
product = self.factory.makeProduct()
self.factory.makeBugTask(bug=bug, target=product)
login_person(bug.owner)
self.assertRaises(
BugCannotBePrivate, bug.setPrivacyAndSecurityRelated, True, False,
bug.owner)
self.assertRaises(
BugCannotBePrivate, bug.setPrivate, True, bug.owner)
# Some teams though need multi-pillar private bugs.
feature_flag = {
'disclosure.allow_multipillar_private_bugs.enabled': 'on'
}
with FeatureFixture(feature_flag):
bug.setPrivacyAndSecurityRelated(True, False, bug.owner)
self.assertTrue(bug.private)
class TestBugPrivateAndSecurityRelatedUpdatesPrivateProject(
TestBugPrivateAndSecurityRelatedUpdatesMixin, TestCaseWithFactory):
def setUp(self):
s = super(TestBugPrivateAndSecurityRelatedUpdatesPrivateProject, self)
s.setUp()
self.private_project = True
class TestBugPrivateAndSecurityRelatedUpdatesPublicProject(
TestBugPrivateAndSecurityRelatedUpdatesMixin, TestCaseWithFactory):
def setUp(self):
s = super(TestBugPrivateAndSecurityRelatedUpdatesPublicProject, self)
s.setUp()
self.private_project = False
class TestBugActivityMethods(TestCaseWithFactory):
layer = DatabaseFunctionalLayer
def setUp(self):
super(TestBugActivityMethods, self).setUp()
self.now = datetime.now(UTC)
def _makeActivityForBug(self, bug, activity_ages):
with person_logged_in(bug.owner):
for days_ago in activity_ages:
activity = BugTitleChange(
when=self.now - timedelta(days=days_ago),
person=bug.owner, what_changed='title',
old_value='foo', new_value='baz')
bug.addChange(activity)
def test_getActivityForDateRange_returns_items_between_dates(self):
# Bug.getActivityForDateRange() will return the activity for
# that bug that falls within a given date range.
bug = self.factory.makeBug(
date_created=self.now - timedelta(days=365))
self._makeActivityForBug(bug, activity_ages=[200, 100])
start_date = self.now - timedelta(days=250)
end_date = self.now - timedelta(days=150)
activity = bug.getActivityForDateRange(
start_date=start_date, end_date=end_date)
expected_activity = bug.activity[1:2]
self.assertContentEqual(expected_activity, activity)
def test_getActivityForDateRange_is_inclusive_of_date_limits(self):
# Bug.getActivityForDateRange() will return the activity that
# falls on the start_ and end_ dates.
bug = self.factory.makeBug(
date_created=self.now - timedelta(days=365))
self._makeActivityForBug(bug, activity_ages=[300, 200, 100])
start_date = self.now - timedelta(days=300)
end_date = self.now - timedelta(days=100)
activity = bug.getActivityForDateRange(
start_date=start_date, end_date=end_date)
expected_activity = bug.activity[1:]
self.assertContentEqual(expected_activity, activity)
class TestBugAutoConfirmation(TestCaseWithFactory):
"""Tests for auto confirming bugs"""
layer = DatabaseFunctionalLayer
def test_shouldConfirmBugtasks_initial_False(self):
# After a bug is created, only one person is affected, and we should
# not try to confirm bug tasks.
bug = self.factory.makeBug()
self.assertFalse(bug.shouldConfirmBugtasks())
def test_shouldConfirmBugtasks_after_another_positively_affected(self):
# We should confirm bug tasks if the number of affected users is
# more than one.
bug = self.factory.makeBug()
person = self.factory.makePerson()
with person_logged_in(person):
bug.markUserAffected(person)
self.assertTrue(bug.shouldConfirmBugtasks())
def test_shouldConfirmBugtasks_after_another_persons_dupe(self):
# We should confirm bug tasks if someone else files a dupe.
bug = self.factory.makeBug()
duplicate_bug = self.factory.makeBug()
with person_logged_in(duplicate_bug.owner):
duplicate_bug.markAsDuplicate(bug)
self.assertTrue(bug.shouldConfirmBugtasks())
def test_shouldConfirmBugtasks_after_same_persons_dupe_False(self):
# We should not confirm bug tasks if same person files a dupe.
bug = self.factory.makeBug()
with person_logged_in(bug.owner):
duplicate_bug = self.factory.makeBug(owner=bug.owner)
duplicate_bug.markAsDuplicate(bug)
self.assertFalse(bug.shouldConfirmBugtasks())
def test_shouldConfirmBugtasks_honors_negatively_affected(self):
# We should confirm bug tasks if the number of affected users is
# more than one.
bug = self.factory.makeBug()
with person_logged_in(bug.owner):
bug.markUserAffected(bug.owner, False)
person = self.factory.makePerson()
with person_logged_in(person):
bug.markUserAffected(person)
self.assertFalse(bug.shouldConfirmBugtasks())
def test_markUserAffected_autoconfirms(self):
# markUserAffected will auto confirm if appropriate.
# When feature flag code is removed, remove the next two lines and
# dedent the rest.
with feature_flags():
set_feature_flag(u'bugs.autoconfirm.enabled_product_names', u'*')
bug = self.factory.makeBug()
person = self.factory.makePerson()
with person_logged_in(person):
bug.markUserAffected(person)
self.assertEqual(BugTaskStatus.CONFIRMED, bug.bugtasks[0].status)
def test_markUserAffected_does_not_autoconfirm_wrongly(self):
# markUserAffected will not auto confirm if incorrect.
# When feature flag code is removed, remove the next two lines and
# dedent the rest.
with feature_flags():
set_feature_flag(u'bugs.autoconfirm.enabled_product_names', u'*')
bug = self.factory.makeBug()
person = self.factory.makePerson()
with person_logged_in(bug.owner):
bug.markUserAffected(bug.owner, False)
with person_logged_in(person):
bug.markUserAffected(person)
self.assertEqual(BugTaskStatus.NEW, bug.bugtasks[0].status)
def test_markAsDuplicate_autoconfirms(self):
# markAsDuplicate will auto confirm if appropriate.
# When feature flag code is removed, remove the next two lines and
# dedent the rest.
with feature_flags():
set_feature_flag(u'bugs.autoconfirm.enabled_product_names', u'*')
bug = self.factory.makeBug()
duplicate_bug = self.factory.makeBug()
with person_logged_in(duplicate_bug.owner):
duplicate_bug.markAsDuplicate(bug)
self.assertEqual(BugTaskStatus.CONFIRMED, bug.bugtasks[0].status)
def test_markAsDuplicate_does_not_autoconfirm_wrongly(self):
# markAsDuplicate will not auto confirm if incorrect.
# When feature flag code is removed, remove the next two lines and
# dedent the rest.
with feature_flags():
set_feature_flag(u'bugs.autoconfirm.enabled_product_names', u'*')
bug = self.factory.makeBug()
with person_logged_in(bug.owner):
duplicate_bug = self.factory.makeBug(owner=bug.owner)
duplicate_bug.markAsDuplicate(bug)
self.assertEqual(BugTaskStatus.NEW, bug.bugtasks[0].status)
|