~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
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
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
Sending the Bug Notifications
=============================

As explained in bugnotifications.txt, a change to a bug causes a bug
notification to be added. These notifications should be assembled into
an email notification, and sent to the appropriate people.

Before we start, let's ensure that there are no pending notifications to
be sent:

    >>> import pytz
    >>> from datetime import datetime, timedelta
    >>> now = datetime.now(pytz.timezone('UTC'))
    >>> ten_minutes_ago = now - timedelta(minutes=10)
    >>> from lp.bugs.interfaces.bugnotification import IBugNotificationSet
    >>> len(getUtility(IBugNotificationSet).getNotificationsToSend())
    0

And let's define functions to make printing out the notifications
easier.

    >>> def print_notification_headers(email_notification):
    ...     for header in ['To', 'From', 'Subject',
    ...                    'X-Launchpad-Message-Rationale',
    ...                    'X-Launchpad-Subscription']:
    ...         if email_notification[header]:
    ...             print "%s: %s" % (header, email_notification[header])

    >>> def print_notification(email_notification):
    ...     print_notification_headers(email_notification)
    ...     print
    ...     print email_notification.get_payload(decode=True)
    ...     print "-" * 70

We'll also import a helper function to help us with database users.

    >>> from lp.testing.dbuser import lp_dbuser

You'll note that we are printing out an X-Launchpad-Message-Rationale
header. This header is a simple string that allows people to filter
bugmail according to the reason they are getting emailed. For instance,
the person may want to specially filter mail for bugs which they are
assigned to.

Anyway, let's start our demonstration by adding a comment to a bug:

    >>> login('test@canonical.com')
    >>> from lp.services.messages.interfaces.message import IMessageSet
    >>> from lp.bugs.interfaces.bug import IBugSet
    >>> bug_one = getUtility(IBugSet).get(1)
    >>> sample_person = getUtility(ILaunchBag).user
    >>> comment = getUtility(IMessageSet).fromText(
    ...     'subject', 'a comment.', sample_person,
    ...     datecreated=ten_minutes_ago)
    >>> bug_one.addCommentNotification(comment)

    >>> notifications = getUtility(
    ...     IBugNotificationSet).getNotificationsToSend()
    >>> len(notifications)
    1

If we pass these notifications to get_email_notifications, we get a
list of emails to send:

    >>> from lp.bugs.scripts.bugnotification import (
    ...     get_email_notifications)
    >>> email_notifications = get_email_notifications(notifications)
    >>> for bug_notifications, omitted, messages in email_notifications:
    ...     for message in messages:
    ...         print_notification(message)
    To: foo.bar@canonical.com
    From: Sample Person <1@bugs.launchpad.net>
    Subject: [Bug 1] subject
    X-Launchpad-Message-Rationale: Subscriber (mozilla-firefox in Ubuntu)
    <BLANKLINE>
    a comment.
    <BLANKLINE>
    ...
    ----------------------------------------------------------------------
    To: mark@example.com
    From: Sample Person <1@bugs.launchpad.net>
    Subject: [Bug 1] subject
    X-Launchpad-Message-Rationale: Assignee
    <BLANKLINE>
    a comment.
    <BLANKLINE>
    ...
    ----------------------------------------------------------------------
    To: support@ubuntu.com
    From: Sample Person <1@bugs.launchpad.net>
    Subject: [Bug 1] subject
    X-Launchpad-Message-Rationale: Registrant (Ubuntu) @ubuntu-team
    <BLANKLINE>
    a comment.
    <BLANKLINE>
    ...
    ----------------------------------------------------------------------
    To: test@canonical.com
    From: Sample Person <1@bugs.launchpad.net>
    Subject: [Bug 1] subject
    X-Launchpad-Message-Rationale: Subscriber
    <BLANKLINE>
    a comment.
    <BLANKLINE>
    ...
    ----------------------------------------------------------------------

You can see that the message above contains the bug's initial comment's
message id as its reference, in order to make it thread properly in the
email client.

    >>> print bug_one.initial_message.rfc822msgid
    sdsdfsfd

The notification is still pending to be sent, since date_emailed is
still None:

    >>> notifications[0].date_emailed is None
    True
    >>> pending_notifications = getUtility(
    ...     IBugNotificationSet).getNotificationsToSend()
    >>> list(pending_notifications) == list(notifications)
    True

Setting date_emailed to some date causes it not to be pending anymore:

    >>> from canonical.database.sqlbase import flush_database_updates
    >>> notifications[0].date_emailed = datetime.now(pytz.timezone('UTC'))
    >>> flush_database_updates()
    >>> pending_notifications = getUtility(
    ...     IBugNotificationSet).getNotificationsToSend()
    >>> len(pending_notifications)
    0

Let's define a helper function to do that for all pending notifications:

    >>> def flush_notifications():
    ...     utc_now = datetime.now(pytz.timezone('UTC'))
    ...     pending_notifications = getUtility(
    ...         IBugNotificationSet).getNotificationsToSend()
    ...     for notification in pending_notifications:
    ...         notification.date_emailed = utc_now
    ...     flush_database_updates()

To every message that gets sent out, [Bug $bugid] is prefixed to the
subject. It gets prefixed only if it's not already present in the
subject, though, which is often the case when someone replies via email.

    >>> comment = getUtility(IMessageSet).fromText(
    ...     'Re: [Bug 1] subject', 'a new comment.', sample_person,
    ...     datecreated=ten_minutes_ago)
    >>> bug_one.addCommentNotification(comment)
    >>> pending_notifications = getUtility(
    ...     IBugNotificationSet).getNotificationsToSend()
    >>> email_notifications = get_email_notifications(pending_notifications)
    >>> for bug_notifications, omitted, messages in email_notifications:
    ...     for message in messages:
    ...         print_notification(message)
    To: foo.bar@canonical.com
    ...
    To: mark@example.com
    ...
    To: support@ubuntu.com
    From: Sample Person <1@bugs.launchpad.net>
    Subject: Re: [Bug 1] subject
    X-Launchpad-Message-Rationale: Registrant (Ubuntu) @ubuntu-team
    <BLANKLINE>
    a new comment.
    <BLANKLINE>
    ...
    ----------------------------------------------------------------------
    To: test@canonical.com
    ...

    >>> flush_notifications()

Let's add a few changes and see how it looks like:

    >>> from lp.bugs.adapters.bugchange import (
    ...     BugTitleChange, BugVisibilityChange)

    >>> bug_one.addChange(
    ...     BugTitleChange(
    ...         ten_minutes_ago, sample_person, "title",
    ...         "Old summary", "New summary"))
    >>> bug_one.addChange(
    ...     BugVisibilityChange(
    ...         ten_minutes_ago, sample_person, "private",
    ...         False, True))
    >>> pending_notifications = getUtility(
    ...     IBugNotificationSet).getNotificationsToSend()
    >>> len(pending_notifications)
    2

    >>> email_notifications = get_email_notifications(pending_notifications)
    >>> for bug_notifications, omitted, messages in email_notifications:
    ...     for message in messages:
    ...         print_notification(message)
    To: foo.bar@canonical.com
    ...
    To: mark@example.com
    ...
    To: support@ubuntu.com
    From: Sample Person <1@bugs.launchpad.net>
    Subject: [Bug 1] Re: Firefox does not support SVG
    X-Launchpad-Message-Rationale: Registrant (Ubuntu) @ubuntu-team
    <BLANKLINE>
    ** Summary changed:
    - Old summary
    + New summary
    <BLANKLINE>
    ** Visibility changed to: Private
    <BLANKLINE>
    --
    ...
    ----------------------------------------------------------------------
    To: test@canonical.com
    ...

If we insert a comment and some more changes, they will be included in
the constructed email:

    >>> comment = getUtility(IMessageSet).fromText(
    ...     'subject', 'a new comment.', sample_person,
    ...     datecreated=ten_minutes_ago)
    >>> bug_one.addCommentNotification(comment)
    >>> bug_one.addChange(
    ...     BugTitleChange(
    ...         ten_minutes_ago, sample_person, "title",
    ...         "New summary", "Another summary"))
    >>> bug_one.addChange(
    ...     BugVisibilityChange(
    ...         ten_minutes_ago, sample_person, "private",
    ...         True, False))
    >>> pending_notifications = getUtility(
    ...     IBugNotificationSet).getNotificationsToSend()
    >>> len(pending_notifications)
    5

Notice how the comment is in the top of the email, and the changes are
in the order they were added:

    >>> email_notifications = get_email_notifications(pending_notifications)
    >>> for bug_notifications, omitted, messages in email_notifications:
    ...     for message in messages:
    ...         print_notification(message)
    To: foo.bar@canonical.com
    ...
    To: mark@example.com
    ...
    To: support@ubuntu.com
    From: Sample Person <1@bugs.launchpad.net>
    Subject: [Bug 1] Re: Firefox does not support SVG
    X-Launchpad-Message-Rationale: Registrant (Ubuntu) @ubuntu-team
    <BLANKLINE>
    a new comment.
    <BLANKLINE>
    ** Summary changed:
    - Old summary
    + New summary
    <BLANKLINE>
    ** Summary changed:
    - New summary
    + Another summary
    <BLANKLINE>
    --
    ...
    ----------------------------------------------------------------------
    To: test@canonical.com
    ...

If you look carefully, there's a surprise in that output: the visibility
changes are not reported.  This is because they are done and then undone
within the same notification.  Undone changes like that are omitted.
moreover, if the email only would have reported done/undone changes, it
is not sent at all.  This is tested elsewhere (see
lp/bugs/tests/test_bugnotification.py), and not demonstrated here.

Another thing worth noting is that there's a blank line before the
signature, and the signature marker has a trailing space.

    >>> message.get_payload(decode=True).splitlines()
    [...,
     '',
     '-- ',
     'You received this bug notification because you are subscribed to the bug',
     'report.',
     'http://bugs.launchpad.dev/bugs/1',
     '',
     'Title:',
     '  Firefox does not support SVG'...]

    >>> flush_notifications()

We send the notification only if the user hasn't done any other changes
for the last 5 minutes:

    >>> now = datetime.now(pytz.timezone('UTC'))
    >>> for minutes_ago in reversed(range(10)):
    ...     bug_one.addChange(
    ...         BugVisibilityChange(
    ...             now - timedelta(minutes=minutes_ago), sample_person,
    ...             "private", False, True))
    >>> pending_notifications = getUtility(
    ...     IBugNotificationSet).getNotificationsToSend()
    >>> len(pending_notifications)
    0

    >>> flush_notifications()

If a team without a contact address is subscribed to the bug, the
notification will be sent to all members individually.

    >>> with lp_dbuser():
    ...     owner = factory.makePerson(email='owner@example.com')
    ...     addressless = factory.makeTeam(
    ...         owner=owner, name='addressless',
    ...         displayname='Addressless Team')
    >>> addressless.preferredemail is None
    True
    >>> for member in addressless.activemembers:
    ...     print member.preferredemail.email
    owner@example.com

    >>> with lp_dbuser():
    ...     ignored = bug_one.subscribe(addressless, addressless)
    ...     comment = getUtility(IMessageSet).fromText(
    ...         'subject', 'a comment.', sample_person,
    ...         datecreated=ten_minutes_ago)
    ...     bug_one.addCommentNotification(comment)

    >>> pending_notifications = getUtility(
    ...     IBugNotificationSet).getNotificationsToSend()
    >>> len(pending_notifications)
    1

    >>> email_notifications = get_email_notifications(pending_notifications)
    >>> for bug_notifications, omitted, messages in email_notifications:
    ...     for message in messages:
    ...         print message['To']
    foo.bar@canonical.com
    mark@example.com
    owner@example.com
    support@ubuntu.com
    test@canonical.com

    >>> flush_notifications()

Duplicates
----------

We will need some helper functions.

    >>> from canonical.config import config
    >>> from canonical.database.sqlbase import commit
    >>> from canonical.testing import LaunchpadZopelessLayer

    >>> def switch_db_to_launchpad():
    ...     commit()
    ...     LaunchpadZopelessLayer.switchDbUser('launchpad')

    >>> def switch_db_to_bugnotification():
    ...     commit()
    ...     LaunchpadZopelessLayer.switchDbUser(
    ...         config.malone.bugnotification_dbuser)

We will also need a fresh new bug.

    >>> from lp.bugs.interfaces.bug import CreateBugParams
    >>> from lp.registry.interfaces.distribution import IDistributionSet
    >>> ubuntu = getUtility(IDistributionSet).getByName('ubuntu')
    >>> description = getUtility(IMessageSet).fromText(
    ...     'subject', 'a description of the bug.', sample_person,
    ...     datecreated=ten_minutes_ago)
    >>> params = CreateBugParams(
    ...     msg=description, owner=sample_person, title='new bug')

    >>> with lp_dbuser():
    ...     new_bug = ubuntu.createBug(params)

If a bug is a duplicate of another bug, a marker gets inserted at the
top of the email:

    >>> flush_notifications()
    >>> with lp_dbuser():
    ...     new_bug.markAsDuplicate(bug_one)
    >>> comment = getUtility(IMessageSet).fromText(
    ...     'subject', 'a comment.', sample_person,
    ...     datecreated=ten_minutes_ago)
    >>> new_bug.addCommentNotification(comment)
    >>> notifications = getUtility(
    ...     IBugNotificationSet).getNotificationsToSend()
    >>> len(notifications)
    1

    >>> for bug_notifications, omitted, messages in (
    ...     get_email_notifications(notifications)):
    ...     for message in messages:
    ...         print_notification(message)
    To: support@ubuntu.com
    From: Sample Person <16@bugs.launchpad.net>
    Subject: [Bug 16] subject
    X-Launchpad-Message-Rationale: Registrant (Ubuntu) @ubuntu-team
    <BLANKLINE>
    *** This bug is a duplicate of bug 1 ***
        http://bugs.launchpad.dev/bugs/1
    ...
    ----------------------------------------------------------------------
    To: test@canonical.com
    From: Sample Person <16@bugs.launchpad.net>
    Subject: [Bug 16] subject
    X-Launchpad-Message-Rationale: Subscriber
    <BLANKLINE>
    *** This bug is a duplicate of bug 1 ***
        http://bugs.launchpad.dev/bugs/1
    ...
    ----------------------------------------------------------------------

    >>> flush_notifications()


Security Vulnerabilities
------------------------

When a new security related bug is filed, a small notification is
inserted at the top of the message body.

    >>> sec_vuln_description = getUtility(IMessageSet).fromText(
    ...     'Zero-day on Frobulator', 'Woah.', sample_person,
    ...     datecreated=ten_minutes_ago)

    >>> with lp_dbuser():
    ...     sec_vuln_bug = ubuntu.createBug(CreateBugParams(
    ...         msg=sec_vuln_description, owner=sample_person,
    ...         title='Zero-day on Frobulator',
    ...         security_related=True, private=True))

    >>> sec_vuln_bug.security_related
    True
    >>> sec_vuln_bug.private
    True

    >>> notifications = (
    ...     getUtility(IBugNotificationSet).getNotificationsToSend())
    >>> email_notifications = get_email_notifications(notifications)
    >>> for bug_notifications, omitted, messages in email_notifications:
    ...     for message in messages:
    ...         print_notification(message)
    To: support@ubuntu.com
    From: Sample Person <...@bugs.launchpad.net>
    Subject: [Bug ...] [NEW] Zero-day on Frobulator
    X-Launchpad-Message-Rationale: Subscriber @ubuntu-team
    <BLANKLINE>
    *** This bug is a security vulnerability ***
    <BLANKLINE>
    ...

    >>> flush_notifications()

The message is only inserted for new bugs, not for modified bugs:

    >>> comment = getUtility(IMessageSet).fromText(
    ...     'subject', 'a comment.', sample_person,
    ...     datecreated=ten_minutes_ago)
    >>> sec_vuln_bug.addCommentNotification(comment)

    >>> notifications = (
    ...     getUtility(IBugNotificationSet).getNotificationsToSend())
    >>> email_notifications = get_email_notifications(notifications)
    >>> for bug_notifications, omitted, messages in email_notifications:
    ...     for message in messages:
    ...         print_notification(message)
    To: support@ubuntu.com
    From: Sample Person <...@bugs.launchpad.net>
    Subject: [Bug ...] subject
    X-Launchpad-Message-Rationale: Subscriber @ubuntu-team
    <BLANKLINE>
    a comment.
    <BLANKLINE>
    ...

    >>> flush_notifications()


The cronscript
--------------

There's a cronsript which does the sending of the email. Let's add a
few notifications to show that it works.

    >>> comment = getUtility(IMessageSet).fromText(
    ...     'subject', 'a comment.', sample_person,
    ...     datecreated=ten_minutes_ago)
    >>> bug_one.addCommentNotification(comment)
    >>> bug_one.addChange(
    ...     BugTitleChange(
    ...         ten_minutes_ago, sample_person, "title",
    ...         "Another summary", "New summary"))
    >>> comment = getUtility(IMessageSet).fromText(
    ...     'subject', 'another comment.', sample_person,
    ...     datecreated=ten_minutes_ago)
    >>> bug_one.addCommentNotification(comment)
    >>> bug_one.addChange(
    ...     BugTitleChange(
    ...         ten_minutes_ago, sample_person, "title",
    ...         "Summary #431", "Summary bleugh I'm going mad"))

    >>> bug_two = getUtility(IBugSet).get(2)
    >>> comment = getUtility(IMessageSet).fromText(
    ...     'subject', 'a comment.', sample_person,
    ...     datecreated=ten_minutes_ago)
    >>> bug_two.addCommentNotification(comment)
    >>> bug_two.addChange(
    ...     BugTitleChange(
    ...         ten_minutes_ago, sample_person, "title",
    ...         "Old summary", "New summary"))
    >>> bug_two.addChange(
    ...     BugVisibilityChange(
    ...         ten_minutes_ago, sample_person, "title",
    ...         False, True))
    >>> bug_two.addChange(
    ...     BugVisibilityChange(
    ...         ten_minutes_ago, sample_person, "title",
    ...         True, False))

    >>> notifications = getUtility(
    ...     IBugNotificationSet).getNotificationsToSend()
    >>> len(notifications)
    8

We need to commit the transaction so that the cronscript will see the
notifications.

    >>> import transaction
    >>> transaction.commit()

Now, let's run the cronscript and look at the output. Passing -v to it
makes it write out the emails it sends.

    >>> import subprocess
    >>> process = subprocess.Popen(
    ...     'cronscripts/send-bug-notifications.py -v', shell=True,
    ...     stdin=subprocess.PIPE, stdout=subprocess.PIPE,
    ...     stderr=subprocess.PIPE)
    >>> (out, err) = process.communicate()
    >>> process.returncode
    0
    >>> print err
    DEBUG   ...
    INFO    Notifying support@ubuntu.com about bug 2.
    ...
    INFO    Notifying test@canonical.com about bug 2.
    ...
    From: Sample Person <...@bugs.launchpad.net>
    To: test@canonical.com
    Reply-To: Bug 2 <2@bugs.launchpad.net>
    ...
    References: foo@example.com-332342--1231
    ...
    X-Launchpad-Message-Rationale: Assignee
    ...
    INFO    Notifying foo.bar@canonical.com about bug 1.
    ...
    From: Sample Person <...@bugs.launchpad.net>
    To: foo.bar@canonical.com
    Reply-To: Bug 1 <1@bugs.launchpad.net>
    ...
    References: sdsdfsfd
    ...
    X-Launchpad-Message-Rationale: Subscriber (mozilla-firefox in Ubuntu)
    ...
    INFO    Notifying mark@example.com about bug 1.
    ...
    INFO    Notifying owner@example.com about bug 1.
    ...
    INFO    Notifying support@ubuntu.com about bug 1.
    ...
    INFO    Notifying test@canonical.com about bug 1.
    ...
    INFO    Notifying foo.bar@canonical.com about bug 1.
    ...
    From: Sample Person <...@bugs.launchpad.net>
    To: foo.bar@canonical.com
    Reply-To: Bug 1 <1@bugs.launchpad.net>
    ...
    References: sdsdfsfd
    ...
    X-Launchpad-Message-Rationale: Subscriber (mozilla-firefox in Ubuntu)
    Errors-To: bounces@canonical.com
    Return-Path: bounces@canonical.com
    Precedence: bulk
    ...
    <BLANKLINE>
    another comment.
    <BLANKLINE>
    ** Summary changed:
    - Summary #431
    + Summary bleugh I'm going mad
    <BLANKLINE>
    -- =
    <BLANKLINE>
    You received this bug notification because...
    INFO    Notifying mark@example.com about bug 1.
    ...
    INFO    Notifying owner@example.com about bug 1.
    ...
    INFO    Notifying support@ubuntu.com about bug 1.
    ...
    INFO    Notifying test@canonical.com about bug 1.
    ...

Note that the message omitted the undone visibility change.

The cronscript has to be sure to mark all notifications, omitted and
otherwise, as sent.  It also marks the omitted notifications with a status,
so if there are any problems we can identify which notifications were omitted
during analysis.  We'll commit a transaction to synchronize the database,
and then look at the notifications available.

    >>> transaction.commit()

    >>> notifications = getUtility(
    ...     IBugNotificationSet).getNotificationsToSend()
    >>> len(notifications)
    0

They have all been marked as sent, including the omitted ones.  Let's look
more carefully at the notifications just to see that the status has
been set properly.

    >>> from lp.bugs.model.bugnotification import BugNotification
    >>> for notification in BugNotification.select(orderBy='id')[-8:]:
    ...     if notification.is_comment:
    ...         identifier = 'comment'
    ...     else:
    ...         identifier = notification.activity.whatchanged
    ...     print identifier, notification.status.title
    comment Sent
    summary Sent
    comment Sent
    summary Sent
    comment Sent
    summary Sent
    visibility Omitted
    visibility Omitted


The X-Launchpad-Bug header
--------------------------

When a notification is sent out about a bug, the X-Launchpad-Bug header is
filled with data about that bug:

    >>> bug_three = getUtility(IBugSet).get(3)
    >>> subscription = bug_three.subscribe(sample_person, sample_person)

    >>> comment = getUtility(IMessageSet).fromText(
    ...     'subject', 'a short comment.', sample_person,
    ...     datecreated=ten_minutes_ago)
    >>> bug_three.addCommentNotification(comment)
    >>> notifications = getUtility(
    ...     IBugNotificationSet).getNotificationsToSend()
    >>> len(notifications)
    1

If we take a closer look at a notification, we can see that
X-Launchpad-Bug headers were added:

    >>> email_notifications = get_email_notifications(notifications)
    >>> for bug_notifications, omitted, messages in email_notifications:
    ...     for message in messages:
    ...         sorted(message.get_all('X-Launchpad-Bug'))
    [u'distribution=debian; distroseries=sarge;... milestone=3.1;...',
     u'distribution=debian; distroseries=woody;...',
     u'distribution=debian; sourcepackage=mozilla-firefox; component=...']

The milestone field in X-Launchpad-Bug won't be filled where no milestone is
specified:

    >>> for line in sorted(message.get_all('X-Launchpad-Bug')):
    ...     'milestone' in line
    True
    False
    False


The X-Launchpad-Bug-Tags header
-------------------------------

First, a helper function that triggers notifications by adding a
comment to a given bug, another that returns a sorted list of new
email messages, and a third that combines the first two.

    >>> def trigger_notifications(bug):
    ...     comment = getUtility(IMessageSet).fromText(
    ...         'subject', 'a short comment.', sample_person,
    ...         datecreated=ten_minutes_ago)
    ...     bug.addCommentNotification(comment)
    ...     return getUtility(
    ...         IBugNotificationSet).getNotificationsToSend()

    >>> def get_email_messages(notifications):
    ...     messages = (message
    ...         for bug_notifications, omitted, messages in
    ...             get_email_notifications(notifications)
    ...         for message in messages)
    ...     return sorted(messages, key=lambda message: message['To'])

    >>> def trigger_and_get_email_messages(bug):
    ...     flush_notifications()
    ...     notifications = trigger_notifications(bug)
    ...     return get_email_messages(notifications)

If a bug is tagged, those tags will be included in the message in the
X-Launchpad-Bug-Tags header.

    >>> bug_three.tags
    [u'layout-test']

    >>> for message in trigger_and_get_email_messages(bug_three):
    ...     message.get_all('X-Launchpad-Bug-Tags')
    [u'layout-test']

If we add a tag to bug three that will also be included in the header.
The tags will be space-separated to allow the list to be wrapped if it
gets over-long.

    >>> with lp_dbuser():
    ...     bug_three.tags = [u'layout-test', u'another-tag', u'yet-another']

    >>> bug_three = getUtility(IBugSet).get(3)
    >>> for message in trigger_and_get_email_messages(bug_three):
    ...     message.get_all('X-Launchpad-Bug-Tags')
    [u'another-tag layout-test yet-another']

If we remove the tags from the bug, the X-Launchpad-Bug-Tags header
won't be included.

    >>> with lp_dbuser():
    ...     bug_three.tags = []

    >>> bug_three = getUtility(IBugSet).get(3)
    >>> for message in trigger_and_get_email_messages(bug_three):
    ...     message.get_all('X-Launchpad-Bug-Tags')

    >>> #bug_three.unsubscribe(sample_person, sample_person)


The X-Launchpad-Bug-Private header
----------------------------------

When a notification is sent out about a bug, the
X-Launchpad-Bug-Private header shows if the bug is marked as
private. It can have the value "yes" or "no".

    >>> bug_three.private
    False

    >>> for message in trigger_and_get_email_messages(bug_three):
    ...     print message['To'], message.get_all('X-Launchpad-Bug-Private')
    test@canonical.com ['no']

Predictably, private bugs are sent with a slightly different header:

    >>> with lp_dbuser():
    ...     bug_three.setPrivate(True, sample_person)
    True
    >>> bug_three.private
    True

    >>> for message in trigger_and_get_email_messages(bug_three):
    ...     print message['To'], message.get_all('X-Launchpad-Bug-Private')
    test@canonical.com ['yes']


The X-Launchpad-Bug-Security-Vulnerability header
-------------------------------------------------

When a notification is sent out about a bug, the
X-Launchpad-Bug-Security-Vulnerability header records if the bug is a
security vulnerability. It can have the value "yes" or "no".

    >>> bug_three.security_related
    False

    >>> for message in trigger_and_get_email_messages(bug_three):
    ...     print message['To'], (
    ...         message.get_all('X-Launchpad-Bug-Security-Vulnerability'))
    test@canonical.com ['no']

The presence of the security flag on a bug is, surprise, denoted by a
simple "yes":

    >>> with lp_dbuser():
    ...     bug_three.setSecurityRelated(True)
    True
    >>> bug_three.security_related
    True

    >>> for message in trigger_and_get_email_messages(bug_three):
    ...     print message['To'], (
    ...         message.get_all('X-Launchpad-Bug-Security-Vulnerability'))
    test@canonical.com ['yes']


The X-Launchpad-Bug-Commenters header
-------------------------------------

The X-Launchpad-Bug-Recipient-Commented header lists all user IDs of
people who have ever commented on the bug. It's a space-separated
list.

    >>> for message in trigger_and_get_email_messages(bug_three):
    ...     print message.get('X-Launchpad-Bug-Commenters')
    name12

    >>> from lp.registry.interfaces.person import IPersonSet
    >>> foo_bar = getUtility(IPersonSet).getByEmail('foo.bar@canonical.com')

    >>> from lp.bugs.interfaces.bugmessage import IBugMessageSet
    >>> with lp_dbuser():
    ...     ignored = getUtility(IBugMessageSet).createMessage(
    ...         'Hungry', bug_three, foo_bar, "Make me a sandwich.")

    >>> for message in trigger_and_get_email_messages(bug_three):
    ...     print message.get('X-Launchpad-Bug-Commenters')
    name12 name16

It only lists each user once, no matter how many comments they've
made.

    >>> with lp_dbuser():
    ...     ignored = getUtility(IBugMessageSet).createMessage(
    ...         'Hungry', bug_three, foo_bar, "Make me a sandwich.")

    >>> for message in trigger_and_get_email_messages(bug_three):
    ...     print message.get('X-Launchpad-Bug-Commenters')
    name12 name16


The X-Launchpad-Bug-Reporter header
-----------------------------------

The X-Launchpad-Bug-Reporter header contains information about the Launchpad
user who originally reported the bug and opened the bug's first bug task.

    >>> for message in trigger_and_get_email_messages(bug_three):
    ...     print message.get('X-Launchpad-Bug-Reporter')
    Foo Bar (name16)


Verbose bug notifications
-------------------------

It is possible for users to have all the bug notifications which they
receive include the bug description and status. This helps in those
cases where the user doesn't save bug notifications, which can make
subsequent notifications seem somewhat obscure.

To demonstrate verbose notifications, we'll create a bug, and subscribe
some very picky users to it. Verbose Person wants verbose emails, while
Concise Person does not. We'll also create teams and give them members
with different verbose_bugnotifications settings.

    >>> with lp_dbuser():
    ...     bug = factory.makeBug(
    ...         product=factory.makeProduct(title='Foo'),
    ...         title='In the beginning, the universe was created. This '
    ...             'has made a lot of people very angry and has been '
    ...             'widely regarded as a bad move',
    ...         description="This is a long description of the bug, which "
    ...             "will be automatically wrapped by the BugNotification "
    ...             "machinery. Ain't technology great?")
    ...     verbose_person = factory.makePerson(
    ...         displayname='Verbose Person', email='verbose@example.com',
    ...         selfgenerated_bugnotifications=True)
    ...     verbose_person.verbose_bugnotifications = True
    ...     ignored = bug.subscribe(verbose_person, verbose_person)
    ...     concise_person = factory.makePerson(
    ...         displayname='Concise Person', email='concise@example.com')
    ...     concise_person.verbose_bugnotifications = False
    ...     ignored = bug.subscribe(concise_person, concise_person)


Concise Team doesn't want verbose notifications, while Concise Team
Person, a member, does.

    >>> with lp_dbuser():
    ...     concise_team = factory.makeTeam(
    ...         name='conciseteam', displayname='Concise Team')
    ...     concise_team.verbose_bugnotifications = False
    ...     concise_team_person = factory.makePerson(
    ...         displayname='Concise Team Person',
    ...         email='conciseteam@example.com')
    ...     concise_team_person.verbose_bugnotifications = True
    ...     ignored = concise_team.addMember(
    ...         concise_team_person, concise_team_person)
    ...     ignored = bug.subscribe(concise_team, concise_team_person)

Verbose Team wants verbose notifications, while Verbose Team Person, a
member, does not.

    >>> with lp_dbuser():
    ...     verbose_team = factory.makeTeam(
    ...         name='verboseteam', displayname='Verbose Team')
    ...     verbose_team.verbose_bugnotifications = True
    ...     verbose_team_person = factory.makePerson(
    ...         displayname='Verbose Team Person',
    ...         email='verboseteam@example.com')
    ...     verbose_team_person.verbose_bugnotifications = False
    ...     ignored = verbose_team.addMember(
    ...         verbose_team_person, verbose_team_person)
    ...     ignored = bug.subscribe(verbose_team, verbose_team_person)

We'll expire all existing notifications since we're not interested in
them:

    >>> notifications = getUtility(
    ...     IBugNotificationSet).getNotificationsToSend()
    >>> len(notifications)
    1

    >>> from canonical.launchpad.ftests import syncUpdate
    >>> for notification in notifications:
    ...     notification.date_emailed = datetime.now(pytz.timezone('UTC'))
    ...     syncUpdate(notification)


If we then add a comment to the bug, the subscribers will receive
notifications containing that comment.

    >>> comment = getUtility(IMessageSet).fromText(
    ...     'subject', 'a really simple comment.', verbose_person,
    ...     datecreated=ten_minutes_ago)
    >>> bug.addCommentNotification(comment)

    >>> notifications = getUtility(
    ...     IBugNotificationSet).getNotificationsToSend()
    >>> len(notifications)
    1

If we pass this notifcation to get_email_notifications we can see that
Verbose Person and Team Person will receive notifications which contain
the bug description and the status in all of its targets. All other
subscribers will receive standard notifications that don't include the
bug description. To help with demonstrating this, we'll define a helper
function.

    >>> def collate_messages_by_recipient(messages):
    ...     messages_by_recipient = {}
    ...     for message in messages:
    ...         recipient = message['To']
    ...         if recipient in messages_by_recipient:
    ...             messages_by_recipient[recipient].append(message)
    ...         else:
    ...             messages_by_recipient[recipient] = [message]
    ...     return messages_by_recipient

    >>> from itertools import chain
    >>> collated_messages = collate_messages_by_recipient(
    ...     chain(*(messages for bug_notifications, omitted, messages in
    ...             get_email_notifications(notifications))))

We can see that Concise Person doesn't receive verbose notifications:

    >>> print_notification(collated_messages['concise@example.com'][0])
    To: concise@example.com
    From: Verbose Person <verbose@example.com>
    Subject: [Bug ...] subject
    X-Launchpad-Message-Rationale: Subscriber
    <BLANKLINE>
    a really simple comment.
    <BLANKLINE>
    --
    You received this bug notification because you are subscribed to the bug
    report.
    http://bugs.launchpad.dev/bugs/...
    <BLANKLINE>
    Title:
      In the beginning...
    ----------------------------------------------------------------------

However, Concise Person does get an unsubscribe link.

    >>> print_notification(collated_messages['concise@example.com'][0])
    To: concise@example.com
    ...
    To manage notifications about this bug go to:...

Verbose Team Person gets a concise email, even though they belong to a team
that gets verbose email.

    >>> print_notification(collated_messages['verboseteam@example.com'][0])
    To: verboseteam@example.com
    From: Verbose Person <verbose@example.com>
    Subject: [Bug ...] subject
    X-Launchpad-Message-Rationale: Subscriber @verboseteam
    <BLANKLINE>
    a really simple comment.
    <BLANKLINE>
    --
    You received this bug notification because you are a member of Verbose
    Team, which is subscribed to the bug report.
    http://bugs.launchpad.dev/bugs/...
    <BLANKLINE>
    Title:
      In the beginning...
    ----------------------------------------------------------------------

Whereas Verbose Person does get the description and task status:

    >>> print_notification(collated_messages['verbose@example.com'][0])
    To: verbose@example.com
    From: Verbose Person <verbose@example.com>
    Subject: [Bug ...] subject
    X-Launchpad-Message-Rationale: Subscriber
    <BLANKLINE>
    a really simple comment.
    <BLANKLINE>
    --
    You received this bug notification because you are subscribed to the bug
    report.
    http://bugs.launchpad.dev/bugs/...
    <BLANKLINE>
    Title:
      In the beginning...
    <BLANKLINE>
    Status in Foo:
      New
    <BLANKLINE>
    Bug description:
       This is a long description of the bug, which
       will be automatically wrapped by the BugNotification
       machinery. Ain't technology great?
    <BLANKLINE>
    To manage notifications about this bug go to:
    http://bugs.launchpad.dev/.../+bug/.../+subscriptions
    ----------------------------------------------------------------------

And Concise Team Person does too, even though his team doesn't want them:

    >>> print_notification(collated_messages['conciseteam@example.com'][0])
    To: conciseteam@example.com
    From: Verbose Person <verbose@example.com>
    Subject: [Bug ...] subject
    X-Launchpad-Message-Rationale: Subscriber @conciseteam
    <BLANKLINE>
    a really simple comment.
    <BLANKLINE>
    --
    You received this bug notification because you are a member of Concise
    Team, which is subscribed to the bug report.
    http://bugs.launchpad.dev/bugs/...
    <BLANKLINE>
    Title:
      In the beginning...
    <BLANKLINE>
    Status in Foo:
      New
    <BLANKLINE>
    Bug description:
       This is a long description of the bug, which
       will be automatically wrapped by the BugNotification
       machinery. Ain't technology great?
    <BLANKLINE>
    To manage notifications about this bug go to:
    http://bugs.launchpad.dev/.../+bug/.../+subscriptions
    ----------------------------------------------------------------------

It's important to note that the bug title and description are wrapped
and indented correctly in verbose notifications.

    >>> message = collated_messages['conciseteam@example.com'][0]
    >>> payload = message.get_payload(decode=True)
    >>> print payload.split('\n')
    [...
     'Title:',
     '  In the beginning, the universe was created. This has made a lot of',
     '  people very angry and has been widely regarded as a bad move',
     ...
     'Bug description:',
     '  This is a long description of the bug, which will be automatically',
     "  wrapped by the BugNotification machinery. Ain't technology great?"...]

The title is also wrapped and indented in normal notifications.

    >>> message = collated_messages['verboseteam@example.com'][0]
    >>> payload = message.get_payload(decode=True)
    >>> print payload.strip().split('\n')
    [...
     'Title:',
     '  In the beginning, the universe was created. This has made a lot of',
     '  people very angry and has been widely regarded as a bad move'...]

Self-Generated Bug Notifications
--------------------------------

People (not teams) will have the choice to receive notifications from actions
they generated.  For now, everyone receives these notifications whether they
want them or not.

    >>> with lp_dbuser():
    ...     person = factory.makePerson()
    >>> person.selfgenerated_bugnotifications
    False
    >>> with lp_dbuser():
    ...     person.selfgenerated_bugnotifications = True

Teams provide this attribute read-only.

    >>> with lp_dbuser():
    ...     team = factory.makeTeam()
    >>> team.selfgenerated_bugnotifications
    False
    >>> with lp_dbuser():
    ...     team.selfgenerated_bugnotifications = True
    Traceback (most recent call last):
    ...
    NotImplementedError: Teams do not support changing this attribute.

Notification Recipients
-----------------------

Bug notifications are sent to direct subscribers of a bug as well as to
structural subscribers. Structural subcribers can select the
notification level of the subscription.

    >>> flush_notifications()

    >>> from lp.bugs.enum import BugNotificationLevel
    >>> from lp.registry.interfaces.product import IProductSet
    >>> firefox = getUtility(IProductSet).getByName('firefox')
    >>> mr_no_privs = getUtility(IPersonSet).getByName('no-priv')
    >>> with lp_dbuser():
    ...     subscription_no_priv = firefox.addBugSubscription(
    ...         mr_no_privs, mr_no_privs)

The notifications generated by addCommentNotification() are sent only to
structural subscribers with no filters, or with the notification level
of COMMENTS or higher. Sample Person's subscription currently does not
have any filters other than the initial catch-all one, so he receives these
notifications.

    >>> print subscription_no_priv.bug_filters.count()
    1
    >>> comment = getUtility(IMessageSet).fromText(
    ...     'subject', 'another comment.', sample_person,
    ...     datecreated=ten_minutes_ago)
    >>> bug_one.addCommentNotification(comment)
    >>> pending_notifications = getUtility(
    ...     IBugNotificationSet).getNotificationsToSend()
    >>> email_notifications = get_email_notifications(pending_notifications)
    >>> for bug_notifications, omitted, messages in email_notifications:
    ...     for message in messages:
    ...         print_notification(message)
    To: foo.bar@canonical.com
    ...
    You received this bug notification because you are subscribed to
    mozilla-firefox in Ubuntu.
    ...
    ----------------------------------------------------------------------
    To: mark@example.com
    ...
    You received this bug notification because you are a bug assignee.
    ...
    ----------------------------------------------------------------------
    To: no-priv@canonical.com
    From: Sample Person <...@bugs.launchpad.net>
    Subject: [Bug 1] subject
    X-Launchpad-Message-Rationale: Subscriber (Mozilla Firefox)
    <BLANKLINE>
    another comment.
    <BLANKLINE>
    --
    You received this bug notification because you are subscribed to Mozilla
    Firefox.
    ...
    ----------------------------------------------------------------------
    To: owner@example.com
    ...
    You received this bug notification because you are a member of 
    Addressless Team, which is subscribed to the bug report.
    ...
    ----------------------------------------------------------------------
    To: support@ubuntu.com
    ...
    You received this bug notification because you are a member of Ubuntu
    Team, which is the registrant for Ubuntu.
    ...
    ----------------------------------------------------------------------
    To: test@canonical.com
    ...
    You received this bug notification because you are subscribed to the bug
    report.
    ...
    ----------------------------------------------------------------------

If Sample Person gets a filter with an explicit notification level of
COMMENTS, he also receives these notifications.


    >>> flush_notifications()
    >>> with lp_dbuser():
    ...     filter = subscription_no_priv.newBugFilter()
    ...     filter.bug_notification_level = BugNotificationLevel.COMMENTS
    ...     filter.description = u"Allow-comments filter"

    >>> comment = getUtility(IMessageSet).fromText(
    ...     'subject', 'another comment.', sample_person,
    ...     datecreated=ten_minutes_ago)
    >>> bug_one.addCommentNotification(comment)
    >>> pending_notifications = getUtility(
    ...     IBugNotificationSet).getNotificationsToSend()
    >>> email_notifications = get_email_notifications(pending_notifications)
    >>> for bug_notifications, omitted, messages in email_notifications:
    ...     for message in messages:
    ...         print_notification(message)
    To: foo.bar@canonical.com
    ...
    You received this bug notification because you are subscribed to
    mozilla-firefox in Ubuntu.
    ...
    ----------------------------------------------------------------------
    To: mark@example.com
    ...
    You received this bug notification because you are a bug assignee.
    ...
    ----------------------------------------------------------------------
    To: no-priv@canonical.com
    From: Sample Person <...@bugs.launchpad.net>
    Subject: [Bug 1] subject
    X-Launchpad-Message-Rationale: Subscriber (Mozilla Firefox)
    X-Launchpad-Subscription: Allow-comments filter
    <BLANKLINE>
    another comment.
    <BLANKLINE>
    --
    You received this bug notification because you are subscribed to Mozilla
    Firefox.
    Matching subscriptions: Allow-comments filter
    ...
    ----------------------------------------------------------------------
    To: owner@example.com
    ...
    You received this bug notification because you are a member of 
    Addressless Team, which is subscribed to the bug report.
    ...
    ----------------------------------------------------------------------
    To: support@ubuntu.com
    ...
    You received this bug notification because you are a member of Ubuntu
    Team, which is the registrant for Ubuntu.
    ...
    ----------------------------------------------------------------------
    To: test@canonical.com
    ...
    You received this bug notification because you are subscribed to the bug
    report.
    ...
    ----------------------------------------------------------------------

If Sample Person's notification level is set to METADATA, he receives
no comment notifications.

    >>> flush_notifications()
    >>> with lp_dbuser():
    ...     filter.bug_notification_level = BugNotificationLevel.METADATA

    >>> comment = getUtility(IMessageSet).fromText(
    ...     'subject', 'no comment for no-priv.', sample_person,
    ...     datecreated=ten_minutes_ago)
    >>> bug_one.addCommentNotification(comment)
    >>> pending_notifications = getUtility(
    ...     IBugNotificationSet).getNotificationsToSend()
    >>> email_notifications = get_email_notifications(pending_notifications)
    >>> for bug_notifications, omitted, messages in email_notifications:
    ...     for message in messages:
    ...         print_notification(message)
    To: foo.bar@canonical.com
    ...
    You received this bug notification because you are subscribed to
    mozilla-firefox in Ubuntu.
    ...
    ----------------------------------------------------------------------
    To: mark@example.com
    ...
    You received this bug notification because you are a bug assignee.
    ...
    ----------------------------------------------------------------------
    To: owner@example.com
    From: Sample Person <...@bugs.launchpad.net>
    Subject: [Bug 1] subject
    X-Launchpad-Message-Rationale: Subscriber @addressless
    <BLANKLINE>
    no comment for no-priv.
    <BLANKLINE>
    --
    You received this bug notification because you are a member of 
    Addressless Team, which is subscribed to the bug report.
    ...
    ----------------------------------------------------------------------
    To: support@ubuntu.com
    ...
    You received this bug notification because you are a member of Ubuntu
    Team, which is the registrant for Ubuntu.
    ...
    ----------------------------------------------------------------------
    To: test@canonical.com
    ...
    You received this bug notification because you are subscribed to the bug
    report.
    ...
    ----------------------------------------------------------------------

The notifications generated by addChange() are sent only to structural
subscribers with the notification level METADATA or higher. The
notification level of Sample Person is currently METADATA, hence he
receives these notifications.

    >>> bug_one.addChange(
    ...     BugTitleChange(
    ...         ten_minutes_ago, sample_person, "title",
    ...         "New summary", "Whatever"))
    >>> pending_notifications = getUtility(
    ...     IBugNotificationSet).getNotificationsToSend()
    >>> email_notifications = get_email_notifications(pending_notifications)
    >>> for bug_notifications, omitted, messages in email_notifications:
    ...     for message in messages:
    ...         print_notification(message)
    To: foo.bar@canonical.com
    ...
    You received this bug notification because you are subscribed to
    mozilla-firefox in Ubuntu.
    http://bugs.launchpad.dev/bugs/1
    ...
    ----------------------------------------------------------------------
    To: mark@example.com
    ...
    You received this bug notification because you are a bug assignee.
    ...
    ----------------------------------------------------------------------
    To: no-priv@canonical.com
    From: Sample Person <...@bugs.launchpad.net>
    Subject: [Bug 1] subject
    X-Launchpad-Message-Rationale: Subscriber (Mozilla Firefox)
    X-Launchpad-Subscription: Allow-comments filter
    <BLANKLINE>
    no comment for no-priv.
    <BLANKLINE>
    ** Summary changed:
    - New summary
    + Whatever
    <BLANKLINE>
    --
    You received this bug notification because you are subscribed to Mozilla
    Firefox.
    Matching subscriptions: Allow-comments filter
    ...
    ----------------------------------------------------------------------
    To: owner@example.com
    ...
    You received this bug notification because you are a member of 
    Addressless Team, which is subscribed to the bug report.
    ...
    ----------------------------------------------------------------------
    To: support@ubuntu.com
    ...
    You received this bug notification because you are a member of Ubuntu
    Team, which is the registrant for Ubuntu.
    ...
    ----------------------------------------------------------------------
    To: test@canonical.com
    ...
    You received this bug notification because you are subscribed to the bug
    report.
    ...
    ----------------------------------------------------------------------

If Sample Person sets his notification level to LIFECYCLE, he receives
no notifications created by addChange().

    >>> flush_notifications()
    >>> with lp_dbuser():
    ...     filter.bug_notification_level = BugNotificationLevel.LIFECYCLE

    >>> bug_one.addChange(
    ...     BugTitleChange(
    ...         ten_minutes_ago, sample_person, "title",
    ...         "Whatever", "Whatever else"))
    >>> pending_notifications = getUtility(
    ...     IBugNotificationSet).getNotificationsToSend()
    >>> email_notifications = get_email_notifications(pending_notifications)
    >>> for bug_notifications, omitted, messages in email_notifications:
    ...     for message in messages:
    ...         print_notification(message)
    To: foo.bar@canonical.com
    ...
    You received this bug notification because you are subscribed to
    mozilla-firefox in Ubuntu.
    ...
    ----------------------------------------------------------------------
    To: mark@example.com
    ...
    You received this bug notification because you are a bug assignee.
    ...
    ----------------------------------------------------------------------
    To: owner@example.com
    From: Sample Person <...@bugs.launchpad.net>
    Subject: [Bug 1] Re: Firefox does not support SVG
    X-Launchpad-Message-Rationale: Subscriber @addressless
    <BLANKLINE>
    ** Summary changed:
    - Whatever
    + Whatever else
    <BLANKLINE>
    --
    You received this bug notification because you are a member of 
    Addressless Team, which is subscribed to the bug report.
    http://bugs.launchpad.dev/bugs/1
    ...
    ----------------------------------------------------------------------
    To: support@ubuntu.com
    ...
    You received this bug notification because you are a member of Ubuntu
    Team, which is the registrant for Ubuntu.
    ...
    ----------------------------------------------------------------------
    To: test@canonical.com
    ...
    You received this bug notification because you are subscribed to the bug
    report.
    ...
    ----------------------------------------------------------------------

Note that, if two filters exist and they both match the same bug, the
more inclusive filter wins.  Therefore, while we saw before that the
filter did not allow the change notification through, if we add another
filter that includes metadata then the notification will be sent out
after all.

    >>> flush_notifications()
    >>> with lp_dbuser():
    ...     filter2 = subscription_no_priv.newBugFilter()
    ...     filter2.bug_notification_level = BugNotificationLevel.METADATA

    >>> bug_one.addChange(
    ...     BugTitleChange(
    ...         ten_minutes_ago, sample_person, "title",
    ...         "I'm losing my", "Marbles"))
    >>> pending_notifications = getUtility(
    ...     IBugNotificationSet).getNotificationsToSend()
    >>> email_notifications = get_email_notifications(pending_notifications)
    >>> for bug_notifications, omitted, messages in email_notifications:
    ...     for message in messages:
    ...         print_notification(message)
    To: foo.bar@canonical.com
    ...
    You received this bug notification because you are subscribed to
    mozilla-firefox in Ubuntu.
    http://bugs.launchpad.dev/bugs/1
    ...
    ----------------------------------------------------------------------
    To: mark@example.com
    ...
    You received this bug notification because you are a bug assignee.
    ...
    ----------------------------------------------------------------------
    To: no-priv@canonical.com
    From: Sample Person <...@bugs.launchpad.net>
    Subject: [Bug 1] Re: Firefox does not support SVG
    X-Launchpad-Message-Rationale: Subscriber (Mozilla Firefox)
    <BLANKLINE>
    ** Summary changed:
    - I'm losing my
    + Marbles
    <BLANKLINE>
    --
    You received this bug notification because you are subscribed to Mozilla
    Firefox.
    ...
    ----------------------------------------------------------------------
    To: owner@example.com
    ...
    You received this bug notification because you are a member of 
    Addressless Team, which is subscribed to the bug report.
    ...
    ----------------------------------------------------------------------
    To: support@ubuntu.com
    ...
    You received this bug notification because you are a member of Ubuntu
    Team, which is the registrant for Ubuntu.
    ...
    ----------------------------------------------------------------------
    To: test@canonical.com
    ...
    You received this bug notification because you are subscribed to the bug
    report.
    ...
    ----------------------------------------------------------------------