~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
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
# Copyright 2009-2011 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
from BeautifulSoup import BeautifulSoup
from lp.registry.interfaces.person import PersonVisibility

__metaclass__ = type

from contextlib import contextmanager
from datetime import (
    datetime,
    timedelta,
    )
import re
import simplejson
import urllib

from lazr.lifecycle.event import ObjectModifiedEvent
from lazr.restful.interfaces import IJSONRequestCache
from lazr.lifecycle.snapshot import Snapshot
from pytz import UTC
import soupmatchers
from storm.store import Store
from testtools.matchers import (
    LessThan,
    Not,
    )
import transaction
from zope.component import (
    getMultiAdapter,
    getUtility,
    )
from zope.event import notify
from zope.interface import providedBy
from zope.security.proxy import removeSecurityProxy

from canonical.config import config
from canonical.database.constants import UTC_NOW
from canonical.launchpad.ftests import (
    ANONYMOUS,
    login,
    login_person,
    )
from canonical.launchpad.testing.pages import find_tag_by_id
from canonical.launchpad.webapp import canonical_url
from canonical.launchpad.webapp.authorization import clear_cache
from canonical.launchpad.webapp.interfaces import (
    ILaunchBag,
    ILaunchpadRoot,
    )
from canonical.launchpad.webapp.servers import LaunchpadTestRequest
from canonical.testing.layers import (
    DatabaseFunctionalLayer,
    LaunchpadFunctionalLayer,
    )
from lp.app.interfaces.launchpad import ILaunchpadCelebrities
from lp.bugs.adapters.bugchange import BugTaskStatusChange
from lp.bugs.browser.bugtask import (
    BugActivityItem,
    BugListingBatchNavigator,
    BugTaskEditView,
    BugTaskListingItem,
    BugTasksAndNominationsView,
    )
from lp.bugs.interfaces.bugactivity import IBugActivitySet
from lp.bugs.interfaces.bugnomination import IBugNomination
from lp.bugs.interfaces.bugtask import (
    BugTaskStatus,
    IBugTask,
    IBugTaskSet,
    )
from lp.services.features.testing import FeatureFixture
from lp.services.propertycache import get_property_cache
from lp.soyuz.interfaces.component import IComponentSet
from lp.testing import (
    BrowserTestCase,
    celebrity_logged_in,
    feature_flags,
    person_logged_in,
    set_feature_flag,
    TestCaseWithFactory,
    )
from lp.testing._webservice import QueryCollector
from lp.testing.matchers import (
    BrowsesWithQueryLimit,
    HasQueryCount,
    )
from lp.testing.sampledata import (
    ADMIN_EMAIL,
    NO_PRIVILEGE_EMAIL,
    USER_EMAIL,
    )
from lp.testing.views import create_initialized_view


DELETE_BUGTASK_ENABLED = {u"disclosure.delete_bugtask.enabled": u"on"}


class TestBugTaskView(TestCaseWithFactory):

    layer = LaunchpadFunctionalLayer

    def invalidate_caches(self, obj):
        store = Store.of(obj)
        # Make sure everything is in the database.
        store.flush()
        # And invalidate the cache (not a reset, because that stops us using
        # the domain objects)
        store.invalidate()

    def test_rendered_query_counts_constant_with_team_memberships(self):
        login(ADMIN_EMAIL)
        task = self.factory.makeBugTask()
        person_no_teams = self.factory.makePerson(password='test')
        person_with_teams = self.factory.makePerson(password='test')
        for _ in range(10):
            self.factory.makeTeam(members=[person_with_teams])
        # count with no teams
        url = canonical_url(task)
        recorder = QueryCollector()
        recorder.register()
        self.addCleanup(recorder.unregister)
        self.invalidate_caches(task)
        self.getUserBrowser(url, person_no_teams)
        # This may seem large: it is; there is easily another 30% fat in
        # there.
        self.assertThat(recorder, HasQueryCount(LessThan(85)))
        count_with_no_teams = recorder.count
        # count with many teams
        self.invalidate_caches(task)
        self.getUserBrowser(url, person_with_teams)
        # Allow an increase of one because storm bug 619017 causes additional
        # queries, revalidating things unnecessarily. An increase which is
        # less than the number of new teams shows it is definitely not
        # growing per-team.
        self.assertThat(recorder, HasQueryCount(
            LessThan(count_with_no_teams + 3),
            ))

    def test_rendered_query_counts_constant_with_attachments(self):
        with celebrity_logged_in('admin'):
            browses_under_limit = BrowsesWithQueryLimit(
                88, self.factory.makePerson())

            # First test with a single attachment.
            task = self.factory.makeBugTask()
            self.factory.makeBugAttachment(bug=task.bug)
        self.assertThat(task, browses_under_limit)

        with celebrity_logged_in('admin'):
            # And now with 10.
            task = self.factory.makeBugTask()
            self.factory.makeBugTask(bug=task.bug)
            for i in range(10):
                self.factory.makeBugAttachment(bug=task.bug)
        self.assertThat(task, browses_under_limit)

    def makeLinkedBranchMergeProposal(self, sourcepackage, bug, owner):
        with person_logged_in(owner):
            f = self.factory
            target_branch = f.makePackageBranch(
                sourcepackage=sourcepackage, owner=owner)
            source_branch = f.makeBranchTargetBranch(
                target_branch.target, owner=owner)
            bug.linkBranch(source_branch, owner)
            return f.makeBranchMergeProposal(
                target_branch=target_branch,
                registrant=owner,
                source_branch=source_branch)

    def test_rendered_query_counts_reduced_with_branches(self):
        f = self.factory
        owner = f.makePerson()
        ds = f.makeDistroSeries()
        bug = f.makeBug()
        sourcepackages = [
            f.makeSourcePackage(distroseries=ds, publish=True)
            for i in range(5)]
        for sp in sourcepackages:
            f.makeBugTask(bug=bug, owner=owner, target=sp)
        url = canonical_url(bug.default_bugtask)
        recorder = QueryCollector()
        recorder.register()
        self.addCleanup(recorder.unregister)
        self.invalidate_caches(bug.default_bugtask)
        self.getUserBrowser(url, owner)
        # At least 20 of these should be removed.
        self.assertThat(recorder, HasQueryCount(LessThan(101)))
        count_with_no_branches = recorder.count
        for sp in sourcepackages:
            self.makeLinkedBranchMergeProposal(sp, bug, owner)
        self.invalidate_caches(bug.default_bugtask)
        self.getUserBrowser(url, owner)  # This triggers the query recorder.
        # Ideally this should be much fewer, but this tries to keep a win of
        # removing more than half of these.
        self.assertThat(recorder, HasQueryCount(
            LessThan(count_with_no_branches + 46),
            ))

    def test_interesting_activity(self):
        # The interesting_activity property returns a tuple of interesting
        # `BugActivityItem`s.
        bug = self.factory.makeBug()
        view = create_initialized_view(
            bug.default_bugtask, name=u'+index', rootsite='bugs')

        def add_activity(what, old=None, new=None, message=None):
            getUtility(IBugActivitySet).new(
                bug, datetime.now(UTC), bug.owner, whatchanged=what,
                oldvalue=old, newvalue=new, message=message)
            del get_property_cache(view).interesting_activity

        # A fresh bug has no interesting activity.
        self.assertEqual((), view.interesting_activity)

        # Some activity is not considered interesting.
        add_activity("boring")
        self.assertEqual((), view.interesting_activity)

        # A description change is interesting.
        add_activity("description")
        self.assertEqual(1, len(view.interesting_activity))
        [activity] = view.interesting_activity
        self.assertEqual("description", activity.whatchanged)

    def test_error_for_changing_target_with_invalid_status(self):
        # If a user moves a bug task with a restricted status (say,
        # Triaged) to a target where they do not have permission to set
        # that status, they will be unable to complete the retargeting
        # and will instead receive an error in the UI.
        person = self.factory.makePerson()
        product = self.factory.makeProduct(
            name='product1', owner=person, official_malone=True)
        with person_logged_in(person):
            product.setBugSupervisor(person, person)
        product_2 = self.factory.makeProduct(
            name='product2', official_malone=True)
        with person_logged_in(product_2.owner):
            product_2.setBugSupervisor(product_2.owner, product_2.owner)
        bug = self.factory.makeBug(
            product=product, owner=person)
        # We need to commit here, otherwise all the sample data we
        # created gets destroyed when the transaction is rolled back.
        transaction.commit()
        with person_logged_in(person):
            form_data = {
                '%s.target' % product.name: 'product',
                '%s.target.product' % product.name: product_2.name,
                '%s.status' % product.name: BugTaskStatus.TRIAGED.title,
                '%s.actions.save' % product.name: 'Save Changes',
                }
            view = create_initialized_view(
                bug.default_bugtask, name=u'+editstatus',
                form=form_data)
            # The bugtask's target won't have changed, since an error
            # happend. The error will be listed in the view.
            self.assertEqual(1, len(view.errors))
            self.assertEqual(product, bug.default_bugtask.target)


class TestBugTasksAndNominationsView(TestCaseWithFactory):

    layer = DatabaseFunctionalLayer

    def setUp(self):
        super(TestBugTasksAndNominationsView, self).setUp()
        login(ADMIN_EMAIL)
        self.bug = self.factory.makeBug()
        self.view = BugTasksAndNominationsView(
            self.bug, LaunchpadTestRequest())

    def refresh(self):
        # The view caches, to see different scenarios, a refresh is needed.
        self.view = BugTasksAndNominationsView(
            self.bug, LaunchpadTestRequest())

    def test_current_user_affected_status(self):
        self.failUnlessEqual(
            None, self.view.current_user_affected_status)
        self.bug.markUserAffected(self.view.user, True)
        self.refresh()
        self.failUnlessEqual(
            True, self.view.current_user_affected_status)
        self.bug.markUserAffected(self.view.user, False)
        self.refresh()
        self.failUnlessEqual(
            False, self.view.current_user_affected_status)

    def test_current_user_affected_js_status(self):
        self.failUnlessEqual(
            'null', self.view.current_user_affected_js_status)
        self.bug.markUserAffected(self.view.user, True)
        self.refresh()
        self.failUnlessEqual(
            'true', self.view.current_user_affected_js_status)
        self.bug.markUserAffected(self.view.user, False)
        self.refresh()
        self.failUnlessEqual(
            'false', self.view.current_user_affected_js_status)

    def test_not_many_bugtasks(self):
        for count in range(10 - len(self.bug.bugtasks) - 1):
            self.factory.makeBugTask(bug=self.bug)
        self.view.initialize()
        self.failIf(self.view.many_bugtasks)
        row_view = self.view._getTableRowView(
            self.bug.default_bugtask, False, False)
        self.failIf(row_view.many_bugtasks)

    def test_many_bugtasks(self):
        for count in range(10 - len(self.bug.bugtasks)):
            self.factory.makeBugTask(bug=self.bug)
        self.view.initialize()
        self.failUnless(self.view.many_bugtasks)
        row_view = self.view._getTableRowView(
            self.bug.default_bugtask, False, False)
        self.failUnless(row_view.many_bugtasks)

    def test_other_users_affected_count(self):
        # The number of other users affected does not change when the
        # logged-in user marked him or herself as affected or not.
        self.failUnlessEqual(
            1, self.view.other_users_affected_count)
        self.bug.markUserAffected(self.view.user, True)
        self.refresh()
        self.failUnlessEqual(
            1, self.view.other_users_affected_count)
        self.bug.markUserAffected(self.view.user, False)
        self.refresh()
        self.failUnlessEqual(
            1, self.view.other_users_affected_count)

    def test_other_users_affected_count_other_users(self):
        # The number of other users affected only changes when other
        # users mark themselves as affected.
        self.failUnlessEqual(
            1, self.view.other_users_affected_count)
        other_user_1 = self.factory.makePerson()
        self.bug.markUserAffected(other_user_1, True)
        self.refresh()
        self.failUnlessEqual(
            2, self.view.other_users_affected_count)
        other_user_2 = self.factory.makePerson()
        self.bug.markUserAffected(other_user_2, True)
        self.refresh()
        self.failUnlessEqual(
            3, self.view.other_users_affected_count)
        self.bug.markUserAffected(other_user_1, False)
        self.refresh()
        self.failUnlessEqual(
            2, self.view.other_users_affected_count)
        self.bug.markUserAffected(self.view.user, True)
        self.refresh()
        self.failUnlessEqual(
            2, self.view.other_users_affected_count)

    def makeDuplicate(self):
        user2 = self.factory.makePerson()
        self.bug2 = self.factory.makeBug()
        self.bug2.markUserAffected(user2, True)
        self.assertEqual(
            2, self.bug2.users_affected_count)
        self.bug2.markAsDuplicate(self.bug)
        # After this there are three users already affected: the creators of
        # the two bugs, plus user2.  The current user is not yet affected by
        # any of them.

    def test_counts_user_unaffected(self):
        self.useFixture(FeatureFixture(
            {'bugs.affected_count_includes_dupes.disabled': ''}))
        self.makeDuplicate()
        self.assertEqual(
            3, self.view.total_users_affected_count)
        self.assertEqual(
            "This bug affects 3 people. Does this bug affect you?",
            self.view.affected_statement)
        self.assertEqual(
            "This bug affects 3 people",
            self.view.anon_affected_statement)
        self.assertEqual(
            self.view.other_users_affected_count,
            3)

    def test_counts_affected_by_duplicate(self):
        self.useFixture(FeatureFixture(
            {'bugs.affected_count_includes_dupes.disabled': ''}))
        self.makeDuplicate()
        # Now with you affected by the duplicate, but not the master.
        self.bug2.markUserAffected(self.view.user, True)
        self.refresh()
        self.assertEqual(
            "This bug affects 3 people. Does this bug affect you?",
            self.view.affected_statement)
        self.assertEqual(
            "This bug affects 4 people",
            self.view.anon_affected_statement)
        self.assertEqual(
            self.view.other_users_affected_count,
            3)

    def test_counts_affected_by_master(self):
        self.useFixture(FeatureFixture(
            {'bugs.affected_count_includes_dupes.disabled': ''}))
        self.makeDuplicate()
        # And now with you also affected by the master.
        self.bug.markUserAffected(self.view.user, True)
        self.refresh()
        self.assertEqual(
            "This bug affects you and 3 other people",
            self.view.affected_statement)
        self.assertEqual(
            "This bug affects 4 people",
            self.view.anon_affected_statement)
        self.assertEqual(
            self.view.other_users_affected_count,
            3)

    def test_counts_affected_by_duplicate_not_by_master(self):
        self.useFixture(FeatureFixture(
            {'bugs.affected_count_includes_dupes.disabled': ''}))
        self.makeDuplicate()
        self.bug2.markUserAffected(self.view.user, True)
        self.bug.markUserAffected(self.view.user, False)
        # You're not included in this count, even though you are affected by
        # the dupe.
        self.assertEqual(
            "This bug affects 3 people, but not you",
            self.view.affected_statement)
        # It would be reasonable for Anon to see this bug cluster affecting
        # either 3 or 4 people.  However at the moment the "No" answer on the
        # master is more authoritative than the "Yes" on the dupe.
        self.assertEqual(
            "This bug affects 3 people",
            self.view.anon_affected_statement)
        self.assertEqual(
            self.view.other_users_affected_count,
            3)

    def test_total_users_affected_count_without_dupes(self):
        self.useFixture(FeatureFixture(
            {'bugs.affected_count_includes_dupes.disabled': 'on'}))
        self.makeDuplicate()
        self.refresh()
        # Does not count the two users of bug2, so just 1.
        self.assertEqual(
            1, self.view.total_users_affected_count)
        self.assertEqual(
            "This bug affects 1 person. Does this bug affect you?",
            self.view.affected_statement)
        self.assertEqual(
            "This bug affects 1 person",
            self.view.anon_affected_statement)
        self.assertEqual(
            1,
            self.view.other_users_affected_count)

    def test_affected_statement_no_one_affected(self):
        self.bug.markUserAffected(self.bug.owner, False)
        self.failUnlessEqual(
            0, self.view.other_users_affected_count)
        self.failUnlessEqual(
            "Does this bug affect you?",
            self.view.affected_statement)

    def test_affected_statement_only_you(self):
        self.view.context.markUserAffected(self.view.user, True)
        self.failUnless(self.bug.isUserAffected(self.view.user))
        self.view.context.markUserAffected(self.bug.owner, False)
        self.failUnlessEqual(
            0, self.view.other_users_affected_count)
        self.failUnlessEqual(
            "This bug affects you",
            self.view.affected_statement)

    def test_affected_statement_only_not_you(self):
        self.view.context.markUserAffected(self.view.user, False)
        self.failIf(self.bug.isUserAffected(self.view.user))
        self.view.context.markUserAffected(self.bug.owner, False)
        self.failUnlessEqual(
            0, self.view.other_users_affected_count)
        self.failUnlessEqual(
            "This bug doesn't affect you",
            self.view.affected_statement)

    def test_affected_statement_1_person_not_you(self):
        self.assertIs(None, self.bug.isUserAffected(self.view.user))
        self.failUnlessEqual(
            1, self.view.other_users_affected_count)
        self.failUnlessEqual(
            "This bug affects 1 person. Does this bug affect you?",
            self.view.affected_statement)

    def test_affected_statement_1_person_and_you(self):
        self.view.context.markUserAffected(self.view.user, True)
        self.failUnless(self.bug.isUserAffected(self.view.user))
        self.failUnlessEqual(
            1, self.view.other_users_affected_count)
        self.failUnlessEqual(
            "This bug affects you and 1 other person",
            self.view.affected_statement)

    def test_affected_statement_1_person_and_not_you(self):
        self.view.context.markUserAffected(self.view.user, False)
        self.failIf(self.bug.isUserAffected(self.view.user))
        self.failUnlessEqual(
            1, self.view.other_users_affected_count)
        self.failUnlessEqual(
            "This bug affects 1 person, but not you",
            self.view.affected_statement)

    def test_affected_statement_more_than_1_person_not_you(self):
        self.assertIs(None, self.bug.isUserAffected(self.view.user))
        other_user = self.factory.makePerson()
        self.view.context.markUserAffected(other_user, True)
        self.failUnlessEqual(
            2, self.view.other_users_affected_count)
        self.failUnlessEqual(
            "This bug affects 2 people. Does this bug affect you?",
            self.view.affected_statement)

    def test_affected_statement_more_than_1_person_and_you(self):
        self.view.context.markUserAffected(self.view.user, True)
        self.failUnless(self.bug.isUserAffected(self.view.user))
        other_user = self.factory.makePerson()
        self.view.context.markUserAffected(other_user, True)
        self.failUnlessEqual(
            2, self.view.other_users_affected_count)
        self.failUnlessEqual(
            "This bug affects you and 2 other people",
            self.view.affected_statement)

    def test_affected_statement_more_than_1_person_and_not_you(self):
        self.view.context.markUserAffected(self.view.user, False)
        self.failIf(self.bug.isUserAffected(self.view.user))
        other_user = self.factory.makePerson()
        self.view.context.markUserAffected(other_user, True)
        self.failUnlessEqual(
            2, self.view.other_users_affected_count)
        self.failUnlessEqual(
            "This bug affects 2 people, but not you",
            self.view.affected_statement)

    def test_anon_affected_statement_no_one_affected(self):
        self.bug.markUserAffected(self.bug.owner, False)
        self.failUnlessEqual(0, self.bug.users_affected_count)
        self.assertIs(None, self.view.anon_affected_statement)

    def test_anon_affected_statement_1_user_affected(self):
        self.failUnlessEqual(1, self.bug.users_affected_count)
        self.failUnlessEqual(
            "This bug affects 1 person",
            self.view.anon_affected_statement)

    def test_anon_affected_statement_2_users_affected(self):
        self.view.context.markUserAffected(self.view.user, True)
        self.failUnlessEqual(2, self.bug.users_affected_count)
        self.failUnlessEqual(
            "This bug affects 2 people",
            self.view.anon_affected_statement)

    def test_getTargetLinkTitle_product(self):
        # The target link title is always none for products.
        target = self.factory.makeProduct()
        bug_task = self.factory.makeBugTask(bug=self.bug, target=target)
        self.view.initialize()
        self.assertEqual(None, self.view.getTargetLinkTitle(bug_task.target))

    def test_getTargetLinkTitle_productseries(self):
        # The target link title is always none for productseries.
        target = self.factory.makeProductSeries()
        bug_task = self.factory.makeBugTask(bug=self.bug, target=target)
        self.view.initialize()
        self.assertEqual(None, self.view.getTargetLinkTitle(bug_task.target))

    def test_getTargetLinkTitle_distribution(self):
        # The target link title is always none for distributions.
        target = self.factory.makeDistribution()
        bug_task = self.factory.makeBugTask(bug=self.bug, target=target)
        self.view.initialize()
        self.assertEqual(None, self.view.getTargetLinkTitle(bug_task.target))

    def test_getTargetLinkTitle_distroseries(self):
        # The target link title is always none for distroseries.
        target = self.factory.makeDistroSeries()
        bug_task = self.factory.makeBugTask(bug=self.bug, target=target)
        self.view.initialize()
        self.assertEqual(None, self.view.getTargetLinkTitle(bug_task.target))

    def test_getTargetLinkTitle_unpublished_distributionsourcepackage(self):
        # The target link title states that the package is not published
        # in the current release.
        distribution = self.factory.makeDistribution(name='boy')
        spn = self.factory.makeSourcePackageName('badger')
        component = getUtility(IComponentSet)['universe']
        maintainer = self.factory.makePerson(name="jim")
        creator = self.factory.makePerson(name="tim")
        self.factory.makeSourcePackagePublishingHistory(
            distroseries=distribution.currentseries, version='2.0',
            component=component, sourcepackagename=spn,
            date_uploaded=datetime(2008, 7, 18, 10, 20, 30, tzinfo=UTC),
            maintainer=maintainer, creator=creator)
        target = distribution.getSourcePackage('badger')
        bug_task = self.factory.makeBugTask(
            bug=self.bug, target=target, publish=False)
        self.view.initialize()
        self.assertEqual({}, self.view.target_releases)
        self.assertEqual(
            'No current release for this source package in Boy',
            self.view.getTargetLinkTitle(bug_task.target))

    def test_getTargetLinkTitle_published_distributionsourcepackage(self):
        # The target link title states the information about the current
        # package in the distro.
        distribution = self.factory.makeDistribution(name='koi')
        distroseries = self.factory.makeDistroSeries(
            distribution=distribution)
        spn = self.factory.makeSourcePackageName('finch')
        component = getUtility(IComponentSet)['universe']
        maintainer = self.factory.makePerson(name="jim")
        creator = self.factory.makePerson(name="tim")
        self.factory.makeSourcePackagePublishingHistory(
            distroseries=distroseries, version='2.0',
            component=component, sourcepackagename=spn,
            date_uploaded=datetime(2008, 7, 18, 10, 20, 30, tzinfo=UTC),
            maintainer=maintainer, creator=creator)
        target = distribution.getSourcePackage('finch')
        bug_task = self.factory.makeBugTask(
            bug=self.bug, target=target, publish=False)
        self.view.initialize()
        self.assertTrue(
            target in self.view.target_releases.keys())
        self.assertEqual(
            'Latest release: 2.0, uploaded to universe on '
            '2008-07-18 10:20:30+00:00 by Tim (tim), maintained by Jim (jim)',
            self.view.getTargetLinkTitle(bug_task.target))

    def test_getTargetLinkTitle_published_sourcepackage(self):
        # The target link title states the information about the current
        # package in the distro.
        distroseries = self.factory.makeDistroSeries()
        spn = self.factory.makeSourcePackageName('bunny')
        component = getUtility(IComponentSet)['universe']
        maintainer = self.factory.makePerson(name="jim")
        creator = self.factory.makePerson(name="tim")
        self.factory.makeSourcePackagePublishingHistory(
            distroseries=distroseries, version='2.0',
            component=component, sourcepackagename=spn,
            date_uploaded=datetime(2008, 7, 18, 10, 20, 30, tzinfo=UTC),
            maintainer=maintainer, creator=creator)
        target = distroseries.getSourcePackage('bunny')
        bug_task = self.factory.makeBugTask(
            bug=self.bug, target=target, publish=False)
        self.view.initialize()
        self.assertTrue(
            target in self.view.target_releases.keys())
        self.assertEqual(
            'Latest release: 2.0, uploaded to universe on '
            '2008-07-18 10:20:30+00:00 by Tim (tim), maintained by Jim (jim)',
            self.view.getTargetLinkTitle(bug_task.target))

    def _get_object_type(self, task_or_nomination):
        if IBugTask.providedBy(task_or_nomination):
            return "bugtask"
        elif IBugNomination.providedBy(task_or_nomination):
            return "nomination"
        else:
            return "unknown"

    def test_bugtask_listing_for_inactive_projects(self):
        # Bugtasks should only be listed for active projects.

        product_foo = self.factory.makeProduct(name="foo")
        product_bar = self.factory.makeProduct(name="bar")
        foo_bug = self.factory.makeBug(product=product_foo)
        bugtask_set = getUtility(IBugTaskSet)
        bugtask_set.createTask(foo_bug, foo_bug.owner, product_bar)
        removeSecurityProxy(product_bar).active = False

        request = LaunchpadTestRequest()
        foo_bugtasks_and_nominations_view = getMultiAdapter(
            (foo_bug, request), name="+bugtasks-and-nominations-portal")
        foo_bugtasks_and_nominations_view.initialize()

        task_and_nomination_views = (
            foo_bugtasks_and_nominations_view.getBugTaskAndNominationViews())
        actual_results = []
        for task_or_nomination_view in task_and_nomination_views:
            task_or_nomination = task_or_nomination_view.context
            actual_results.append((
                self._get_object_type(task_or_nomination),
                task_or_nomination.status.title,
                task_or_nomination.target.bugtargetdisplayname))
        # Only the one active project's task should be listed.
        self.assertEqual([("bugtask", "New", "Foo")], actual_results)

    def test_listing_with_no_bugtasks(self):
        # Test the situation when there are no bugtasks to show.

        product_foo = self.factory.makeProduct(name="foo")
        foo_bug = self.factory.makeBug(product=product_foo)
        removeSecurityProxy(product_foo).active = False

        request = LaunchpadTestRequest()
        foo_bugtasks_and_nominations_view = getMultiAdapter(
            (foo_bug, request), name="+bugtasks-and-nominations-portal")
        foo_bugtasks_and_nominations_view.initialize()

        task_and_nomination_views = (
            foo_bugtasks_and_nominations_view.getBugTaskAndNominationViews())
        self.assertEqual([], task_and_nomination_views)

    def test_bugtarget_parent_shown_for_orphaned_series_tasks(self):
        # Test that a row is shown for the parent of a series task, even
        # if the parent doesn't actually have a task.
        series = self.factory.makeProductSeries()
        bug = self.factory.makeBug(series=series)
        self.assertEqual(2, len(bug.bugtasks))
        new_prod = self.factory.makeProduct()
        bug.getBugTask(series.product).transitionToTarget(new_prod)

        view = create_initialized_view(bug, "+bugtasks-and-nominations-table")
        subviews = view.getBugTaskAndNominationViews()
        self.assertEqual([
            (series.product, '+bugtasks-and-nominations-table-row'),
            (bug.getBugTask(series), '+bugtasks-and-nominations-table-row'),
            (bug.getBugTask(new_prod), '+bugtasks-and-nominations-table-row'),
            ], [(v.context, v.__name__) for v in subviews])

        content = subviews[0]()
        self.assertIn(
            'href="%s"' % canonical_url(
                series.product, path_only_if_possible=True),
            content)
        self.assertIn(series.product.displayname, content)

    def test_bugtask_listing_for_private_assignees(self):
        # Private assignees are rendered in the bug portal view.

        # Create a bugtask with a private assignee.
        product_foo = self.factory.makeProduct(name="foo")
        foo_bug = self.factory.makeBug(product=product_foo)
        assignee = self.factory.makeTeam(
            name="assignee",
            visibility=PersonVisibility.PRIVATE)
        foo_bug.default_bugtask.transitionToAssignee(assignee)

        # Render the view.
        request = LaunchpadTestRequest()
        any_person = self.factory.makePerson()
        login_person(any_person, request)
        foo_bugtasks_and_nominations_view = getMultiAdapter(
            (foo_bug, request), name="+bugtasks-and-nominations-portal")
        foo_bugtasks_and_nominations_view.initialize()
        task_and_nomination_views = (
            foo_bugtasks_and_nominations_view.getBugTaskAndNominationViews())
        getUtility(ILaunchBag).add(foo_bug.default_bugtask)
        self.assertEqual(1, len(task_and_nomination_views))
        content = task_and_nomination_views[0]()

        # Check the result.
        soup = BeautifulSoup(content)
        tag = soup.find('label', attrs={'for': "foo.assignee.assigned_to"})
        tag_text = tag.renderContents().strip()
        self.assertEqual(assignee.unique_displayname, tag_text)


class TestBugTaskDeleteLinks(TestCaseWithFactory):
    """ Test that the delete icons/links are correctly rendered.

        Bug task deletion is protected by a feature flag.
        """

    layer = DatabaseFunctionalLayer

    def test_cannot_delete_only_bugtask(self):
        # The last bugtask cannot be deleted.
        bug = self.factory.makeBug()
        login_person(bug.owner)
        view = create_initialized_view(
            bug, name='+bugtasks-and-nominations-table')
        row_view = view._getTableRowView(bug.default_bugtask, False, False)
        self.assertFalse(row_view.user_can_delete_bugtask)
        del get_property_cache(row_view).user_can_delete_bugtask
        with FeatureFixture(DELETE_BUGTASK_ENABLED):
            self.assertFalse(row_view.user_can_delete_bugtask)

    def test_can_delete_bugtask_if_authorised(self):
        # The bugtask can be deleted if the user if authorised.
        bug = self.factory.makeBug()
        bugtask = self.factory.makeBugTask(bug=bug)
        login_person(bugtask.owner)
        view = create_initialized_view(
            bug, name='+bugtasks-and-nominations-table',
            principal=bugtask.owner)
        row_view = view._getTableRowView(bugtask, False, False)
        self.assertFalse(row_view.user_can_delete_bugtask)
        del get_property_cache(row_view).user_can_delete_bugtask
        clear_cache()
        with FeatureFixture(DELETE_BUGTASK_ENABLED):
            self.assertTrue(row_view.user_can_delete_bugtask)

    def test_bugtask_delete_icon(self):
        # The bugtask delete icon is rendered correctly for those tasks the
        # user is allowed to delete.
        bug = self.factory.makeBug()
        bugtask_owner = self.factory.makePerson()
        bugtask = self.factory.makeBugTask(bug=bug, owner=bugtask_owner)
        with FeatureFixture(DELETE_BUGTASK_ENABLED):
            login_person(bugtask.owner)
            getUtility(ILaunchBag).add(bug.default_bugtask)
            view = create_initialized_view(
                bug, name='+bugtasks-and-nominations-table',
                principal=bugtask.owner)
            # We render the bug task table rows - there are 2 bug tasks.
            subviews = view.getBugTaskAndNominationViews()
            self.assertEqual(2, len(subviews))
            default_bugtask_contents = subviews[0]()
            bugtask_contents = subviews[1]()
            # bugtask can be deleted because the user owns it.
            delete_icon = find_tag_by_id(
                bugtask_contents, 'bugtask-delete-task%d' % bugtask.id)
            delete_url = canonical_url(
                bugtask, rootsite='bugs', view_name='+delete')
            self.assertEqual(delete_url, delete_icon['href'])
            # default_bugtask cannot be deleted.
            delete_icon = find_tag_by_id(
                default_bugtask_contents,
                'bugtask-delete-task%d' % bug.default_bugtask.id)
            self.assertIsNone(delete_icon)

    def test_client_cache_contents(self):
        """ Test that the client cache contains the expected data.

        The cache data is used by the Javascript to enable the delete
        links to work as expected.
        """
        bug = self.factory.makeBug()
        bugtask_owner = self.factory.makePerson()
        bugtask = self.factory.makeBugTask(bug=bug, owner=bugtask_owner)
        with FeatureFixture(DELETE_BUGTASK_ENABLED):
            login_person(bugtask.owner)
            getUtility(ILaunchBag).add(bug.default_bugtask)
            view = create_initialized_view(
                bug, name='+bugtasks-and-nominations-table',
                principal=bugtask.owner)
            view.render()
            cache = IJSONRequestCache(view.request)
            all_bugtask_data = cache.objects['bugtask_data']

            def check_bugtask_data(bugtask, can_delete):
                self.assertIn(bugtask.id, all_bugtask_data)
                bugtask_data = all_bugtask_data[bugtask.id]
                self.assertEqual(
                    'task%d' % bugtask.id, bugtask_data['form_row_id'])
                self.assertEqual(
                    'tasksummary%d' % bugtask.id, bugtask_data['row_id'])
                self.assertEqual(can_delete, bugtask_data['user_can_delete'])

            check_bugtask_data(bug.default_bugtask, False)
            check_bugtask_data(bugtask, True)


class TestBugTaskDeleteView(TestCaseWithFactory):
    """Test the bug task delete form."""

    layer = DatabaseFunctionalLayer

    def test_delete_view_rendering(self):
        # Test the view rendering, including confirmation message, cancel url.
        bug = self.factory.makeBug()
        bugtask = self.factory.makeBugTask(bug=bug)
        bug_url = canonical_url(bugtask.bug, rootsite='bugs')
        # Set up request so that the ReturnToReferrerMixin can correctly
        # extra the referer url.
        server_url = canonical_url(
            getUtility(ILaunchpadRoot), rootsite='bugs')
        extra = {'HTTP_REFERER': bug_url}
        with FeatureFixture(DELETE_BUGTASK_ENABLED):
            login_person(bugtask.owner)
            view = create_initialized_view(
                bugtask, name='+delete', principal=bugtask.owner,
                server_url=server_url, **extra)
            contents = view.render()
            confirmation_message = find_tag_by_id(
                contents, 'confirmation-message')
            self.assertIsNotNone(confirmation_message)
            self.assertEqual(bug_url, view.cancel_url)

    def test_delete_action(self):
        # Test that the delete action works as expected.
        bug = self.factory.makeBug()
        bugtask = self.factory.makeBugTask(bug=bug)
        target_name = bugtask.bugtargetdisplayname
        with FeatureFixture(DELETE_BUGTASK_ENABLED):
            login_person(bugtask.owner)
            form = {
                'field.actions.delete_bugtask': 'Delete',
                }
            view = create_initialized_view(
                bugtask, name='+delete', form=form, principal=bugtask.owner)
            self.assertEqual([bug.default_bugtask], bug.bugtasks)
            notifications = view.request.response.notifications
            self.assertEqual(1, len(notifications))
            expected = 'This bug no longer affects %s.' % target_name
            self.assertEqual(expected, notifications[0].message)

    def test_delete_only_bugtask(self):
        # Test that the deleting the only bugtask results in an error message.
        bug = self.factory.makeBug()
        with FeatureFixture(DELETE_BUGTASK_ENABLED):
            login_person(bug.owner)
            form = {
                'field.actions.delete_bugtask': 'Delete',
                }
            view = create_initialized_view(
                bug.default_bugtask, name='+delete', form=form,
                principal=bug.owner)
            self.assertEqual([bug.default_bugtask], bug.bugtasks)
            notifications = view.request.response.notifications
            self.assertEqual(1, len(notifications))
            expected = ('Cannot delete only bugtask affecting: %s.'
                % bug.default_bugtask.target.bugtargetdisplayname)
            self.assertEqual(expected, notifications[0].message)

    def _create_bugtask_to_delete(self):
        bug = self.factory.makeBug()
        bugtask = self.factory.makeBugTask(bug=bug)
        target_name = bugtask.bugtargetdisplayname
        bugtask_url = canonical_url(bugtask, rootsite='bugs')
        return bug, bugtask, target_name, bugtask_url

    def test_ajax_delete_current_bugtask(self):
        # Test that deleting the current bugtask returns a JSON dict
        # containing the URL of the bug's default task to redirect to.
        bug, bugtask, target_name, bugtask_url = (
            self._create_bugtask_to_delete())
        with FeatureFixture(DELETE_BUGTASK_ENABLED):
            login_person(bugtask.owner)
            # Set up the request so that we correctly simulate an XHR call
            # from the URL of the bugtask we are deleting.
            server_url = canonical_url(
                getUtility(ILaunchpadRoot), rootsite='bugs')
            extra = {
                'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest',
                'HTTP_REFERER': bugtask_url,
                }
            form = {
                'field.actions.delete_bugtask': 'Delete'
                }
            view = create_initialized_view(
                bugtask, name='+delete', server_url=server_url, form=form,
                principal=bugtask.owner, **extra)
            result_data = simplejson.loads(view.render())
            self.assertEqual([bug.default_bugtask], bug.bugtasks)
            notifications = simplejson.loads(
                view.request.response.getHeader('X-Lazr-Notifications'))
            self.assertEqual(1, len(notifications))
            expected = 'This bug no longer affects %s.' % target_name
            self.assertEqual(expected, notifications[0][1])
            self.assertEqual(
                'application/json',
                view.request.response.getHeader('content-type'))
            expected_url = canonical_url(bug.default_bugtask, rootsite='bugs')
            self.assertEqual(dict(bugtask_url=expected_url), result_data)

    def test_ajax_delete_only_bugtask(self):
        # Test that deleting the only bugtask returns an empty JSON response
        # with an error notification.
        bug = self.factory.makeBug()
        with FeatureFixture(DELETE_BUGTASK_ENABLED):
            login_person(bug.owner)
            # Set up the request so that we correctly simulate an XHR call
            # from the URL of the bugtask we are deleting.
            server_url = canonical_url(
                getUtility(ILaunchpadRoot), rootsite='bugs')
            extra = {
                'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest',
                }
            form = {
                'field.actions.delete_bugtask': 'Delete'
                }
            view = create_initialized_view(
                bug.default_bugtask, name='+delete', server_url=server_url,
                form=form, principal=bug.owner, **extra)
            result_data = simplejson.loads(view.render())
            self.assertEqual([bug.default_bugtask], bug.bugtasks)
            notifications = simplejson.loads(
                view.request.response.getHeader('X-Lazr-Notifications'))
            self.assertEqual(1, len(notifications))
            expected = ('Cannot delete only bugtask affecting: %s.'
                % bug.default_bugtask.target.bugtargetdisplayname)
            self.assertEqual(expected, notifications[0][1])
            self.assertEqual(
                'application/json',
                view.request.response.getHeader('content-type'))
            self.assertEqual(None, result_data)

    def test_ajax_delete_non_current_bugtask(self):
        # Test that deleting the non-current bugtask returns the new bugtasks
        # table as HTML.
        bug, bugtask, target_name, bugtask_url = (
            self._create_bugtask_to_delete())
        default_bugtask_url = canonical_url(
            bug.default_bugtask, rootsite='bugs')
        with FeatureFixture(DELETE_BUGTASK_ENABLED):
            login_person(bugtask.owner)
            # Set up the request so that we correctly simulate an XHR call
            # from the URL of the default bugtask, not the one we are
            # deleting.
            server_url = canonical_url(
                getUtility(ILaunchpadRoot), rootsite='bugs')
            extra = {
                'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest',
                'HTTP_REFERER': default_bugtask_url,
                }
            form = {
                'field.actions.delete_bugtask': 'Delete'
                }
            view = create_initialized_view(
                bugtask, name='+delete', server_url=server_url, form=form,
                principal=bugtask.owner, **extra)
            result_html = view.render()
            self.assertEqual([bug.default_bugtask], bug.bugtasks)
            notifications = view.request.response.notifications
            self.assertEqual(1, len(notifications))
            expected = 'This bug no longer affects %s.' % target_name
            self.assertEqual(expected, notifications[0].message)
            self.assertEqual(
                view.request.response.getHeader('content-type'), 'text/html')
            table = find_tag_by_id(result_html, 'affected-software')
            self.assertIsNotNone(table)
            [row] = table.tbody.findAll('tr', {'class': 'highlight'})
            target_link = row.find('a', {'class': 'sprite product'})
            self.assertIn(
                bug.default_bugtask.bugtargetdisplayname, target_link)


class TestBugTasksAndNominationsViewAlsoAffects(TestCaseWithFactory):
    """ Tests the boolean methods on the view used to indicate whether the
        Also Affects... links should be allowed or not. Currently these
        restrictions are only used for private bugs. ie where body.private
        is true.

        A feature flag is used to turn off the new restrictions. Each test
        is performed with and without the feature flag.
    """

    layer = DatabaseFunctionalLayer

    feature_flag = {'disclosure.allow_multipillar_private_bugs.enabled': 'on'}

    def _createView(self, bug):
        request = LaunchpadTestRequest()
        bugtasks_and_nominations_view = getMultiAdapter(
            (bug, request), name="+bugtasks-and-nominations-portal")
        return bugtasks_and_nominations_view

    def test_project_bug_cannot_affect_something_else(self):
        # A bug affecting a project cannot also affect another project or
        # package.
        bug = self.factory.makeBug()
        view = self._createView(bug)
        self.assertFalse(view.canAddProjectTask())
        self.assertFalse(view.canAddPackageTask())
        with FeatureFixture(self.feature_flag):
            self.assertTrue(view.canAddProjectTask())
            self.assertTrue(view.canAddPackageTask())

    def test_distro_bug_cannot_affect_project(self):
        # A bug affecting a distro cannot also affect another project but it
        # could affect another package.
        distro = self.factory.makeDistribution()
        bug = self.factory.makeBug(distribution=distro)
        view = self._createView(bug)
        self.assertFalse(view.canAddProjectTask())
        self.assertTrue(view.canAddPackageTask())
        with FeatureFixture(self.feature_flag):
            self.assertTrue(view.canAddProjectTask())
            self.assertTrue(view.canAddPackageTask())

    def test_sourcepkg_bug_cannot_affect_project(self):
        # A bug affecting a source pkg cannot also affect another project but
        # it could affect another package.
        distro = self.factory.makeDistribution()
        distroseries = self.factory.makeDistroSeries(distribution=distro)
        sp_name = self.factory.getOrMakeSourcePackageName()
        self.factory.makeSourcePackage(
            sourcepackagename=sp_name, distroseries=distroseries)
        bug = self.factory.makeBug(
            distribution=distro, sourcepackagename=sp_name)
        view = self._createView(bug)
        self.assertFalse(view.canAddProjectTask())
        self.assertTrue(view.canAddPackageTask())
        with FeatureFixture(self.feature_flag):
            self.assertTrue(view.canAddProjectTask())
            self.assertTrue(view.canAddPackageTask())


class TestBugTaskEditViewStatusField(TestCaseWithFactory):
    """We show only those options as possible value in the status
    field that the user can select.
    """

    layer = DatabaseFunctionalLayer

    def setUp(self):
        super(TestBugTaskEditViewStatusField, self).setUp()
        product_owner = self.factory.makePerson(name='product-owner')
        bug_supervisor = self.factory.makePerson(name='bug-supervisor')
        product = self.factory.makeProduct(
            owner=product_owner, bug_supervisor=bug_supervisor)
        self.bug = self.factory.makeBug(product=product)

    def getWidgetOptionTitles(self, widget):
        """Return the titles of options of the given choice widget."""
        return [
            item.value.title for item in widget.field.vocabulary]

    def test_status_field_items_for_anonymous(self):
        # Anonymous users see only the current value.
        login(ANONYMOUS)
        view = BugTaskEditView(
            self.bug.default_bugtask, LaunchpadTestRequest())
        view.initialize()
        self.assertEqual(
            ['New'], self.getWidgetOptionTitles(view.form_fields['status']))

    def test_status_field_items_for_ordinary_users(self):
        # Ordinary users can set the status to all values except Won't fix,
        # Expired, Triaged, Unknown.
        login(NO_PRIVILEGE_EMAIL)
        view = BugTaskEditView(
            self.bug.default_bugtask, LaunchpadTestRequest())
        view.initialize()
        self.assertEqual(
            ['New', 'Incomplete', 'Opinion', 'Invalid', 'Confirmed',
             'In Progress', 'Fix Committed', 'Fix Released'],
            self.getWidgetOptionTitles(view.form_fields['status']))

    def test_status_field_privileged_persons(self):
        # The bug target owner and the bug target supervisor can set
        # the status to any value except Unknown and Expired.
        for user in (
            self.bug.default_bugtask.pillar.owner,
            self.bug.default_bugtask.pillar.bug_supervisor):
            login_person(user)
            view = BugTaskEditView(
                self.bug.default_bugtask, LaunchpadTestRequest())
            view.initialize()
            self.assertEqual(
                ['New', 'Incomplete', 'Opinion', 'Invalid', "Won't Fix",
                 'Confirmed', 'Triaged', 'In Progress', 'Fix Committed',
                 'Fix Released'],
                self.getWidgetOptionTitles(view.form_fields['status']),
                'Unexpected set of settable status options for %s'
                % user.name)

    def test_status_field_bug_task_in_status_unknown(self):
        # If a bugtask has the status Unknown, this status is included
        # in the options.
        owner = self.bug.default_bugtask.pillar.owner
        login_person(owner)
        self.bug.default_bugtask.transitionToStatus(
            BugTaskStatus.UNKNOWN, owner)
        login(NO_PRIVILEGE_EMAIL)
        view = BugTaskEditView(
            self.bug.default_bugtask, LaunchpadTestRequest())
        view.initialize()
        self.assertEqual(
            ['New', 'Incomplete', 'Opinion', 'Invalid', 'Confirmed',
             'In Progress', 'Fix Committed', 'Fix Released', 'Unknown'],
            self.getWidgetOptionTitles(view.form_fields['status']))

    def test_status_field_bug_task_in_status_expired(self):
        # If a bugtask has the status Expired, this status is included
        # in the options.
        removeSecurityProxy(self.bug.default_bugtask)._status = (
            BugTaskStatus.EXPIRED)
        login(NO_PRIVILEGE_EMAIL)
        view = BugTaskEditView(
            self.bug.default_bugtask, LaunchpadTestRequest())
        view.initialize()
        self.assertEqual(
            ['New', 'Incomplete', 'Opinion', 'Invalid', 'Expired',
             'Confirmed', 'In Progress', 'Fix Committed', 'Fix Released'],
            self.getWidgetOptionTitles(view.form_fields['status']))


class TestBugTaskEditViewAssigneeField(TestCaseWithFactory):

    layer = DatabaseFunctionalLayer

    def setUp(self):
        super(TestBugTaskEditViewAssigneeField, self).setUp()
        self.owner = self.factory.makePerson()
        self.product = self.factory.makeProduct(owner=self.owner)
        self.bugtask = self.factory.makeBug(
            product=self.product).default_bugtask

    def test_assignee_vocabulary_regular_user_with_bug_supervisor(self):
        # For regular users, the assignee vocabulary is
        # AllUserTeamsParticipation if there is a bug supervisor defined.
        login_person(self.owner)
        self.product.setBugSupervisor(self.owner, self.owner)
        login(USER_EMAIL)
        view = BugTaskEditView(self.bugtask, LaunchpadTestRequest())
        view.initialize()
        self.assertEqual(
            'AllUserTeamsParticipation',
            view.form_fields['assignee'].field.vocabularyName)

    def test_assignee_vocabulary_regular_user_without_bug_supervisor(self):
        # For regular users, the assignee vocabulary is
        # ValidAssignee is there is not a bug supervisor defined.
        login_person(self.owner)
        self.product.setBugSupervisor(None, self.owner)
        login(USER_EMAIL)
        view = BugTaskEditView(self.bugtask, LaunchpadTestRequest())
        view.initialize()
        self.assertEqual(
            'ValidAssignee',
            view.form_fields['assignee'].field.vocabularyName)

    def test_assignee_field_vocabulary_privileged_user(self):
        # Privileged users, like the bug task target owner, can
        # assign anybody.
        login_person(self.bugtask.target.owner)
        view = BugTaskEditView(self.bugtask, LaunchpadTestRequest())
        view.initialize()
        self.assertEqual(
            'ValidAssignee',
            view.form_fields['assignee'].field.vocabularyName)


class TestBugTaskEditView(TestCaseWithFactory):
    """Test the bug task edit form."""

    layer = DatabaseFunctionalLayer

    def test_retarget_already_exists_error(self):
        user = self.factory.makePerson()
        login_person(user)
        ubuntu = getUtility(ILaunchpadCelebrities).ubuntu
        dsp_1 = self.factory.makeDistributionSourcePackage(
            distribution=ubuntu, sourcepackagename='mouse')
        self.factory.makeSourcePackagePublishingHistory(
            distroseries=ubuntu.currentseries,
            sourcepackagename=dsp_1.sourcepackagename)
        bug_task_1 = self.factory.makeBugTask(target=dsp_1)
        dsp_2 = self.factory.makeDistributionSourcePackage(
            distribution=ubuntu, sourcepackagename='rabbit')
        self.factory.makeSourcePackagePublishingHistory(
            distroseries=ubuntu.currentseries,
            sourcepackagename=dsp_2.sourcepackagename)
        bug_task_2 = self.factory.makeBugTask(
            bug=bug_task_1.bug, target=dsp_2)
        form = {
            'ubuntu_rabbit.actions.save': 'Save Changes',
            'ubuntu_rabbit.status': 'In Progress',
            'ubuntu_rabbit.importance': 'High',
            'ubuntu_rabbit.assignee.option':
                'ubuntu_rabbit.assignee.assign_to_nobody',
            'ubuntu_rabbit.target': 'package',
            'ubuntu_rabbit.target.distribution': 'ubuntu',
            'ubuntu_rabbit.target.package': 'mouse',
            }
        view = create_initialized_view(
            bug_task_2, name='+editstatus', form=form, principal=user)
        self.assertEqual(1, len(view.errors))
        self.assertEqual(
            'A fix for this bug has already been requested for mouse in '
            'Ubuntu',
            view.errors[0])

    def setUpRetargetMilestone(self):
        """Setup a bugtask with a milestone and a product to retarget to."""
        first_product = self.factory.makeProduct(name='bunny')
        with person_logged_in(first_product.owner):
            first_product.official_malone = True
            bug = self.factory.makeBug(product=first_product)
            bug_task = bug.bugtasks[0]
            milestone = self.factory.makeMilestone(
                productseries=first_product.development_focus, name='1.0')
            bug_task.transitionToMilestone(milestone, first_product.owner)
        second_product = self.factory.makeProduct(name='duck')
        with person_logged_in(second_product.owner):
            second_product.official_malone = True
        return bug_task, second_product

    def test_retarget_product_with_milestone(self):
        # Milestones are always cleared when retargeting a product bug task.
        bug_task, second_product = self.setUpRetargetMilestone()
        user = self.factory.makePerson()
        login_person(user)
        form = {
            'bunny.status': 'In Progress',
            'bunny.assignee.option': 'bunny.assignee.assign_to_nobody',
            'bunny.target': 'product',
            'bunny.target.product': 'duck',
            'bunny.actions.save': 'Save Changes',
            }
        view = create_initialized_view(
            bug_task, name='+editstatus', form=form)
        self.assertEqual([], view.errors)
        self.assertEqual(second_product, bug_task.target)
        self.assertEqual(None, bug_task.milestone)
        notifications = view.request.response.notifications
        self.assertEqual(1, len(notifications))
        expected = ('The Bunny 1.0 milestone setting has been removed')
        self.assertTrue(notifications.pop().message.startswith(expected))

    def test_retarget_product_and_assign_milestone(self):
        # Milestones are always cleared when retargeting a product bug task.
        bug_task, second_product = self.setUpRetargetMilestone()
        login_person(bug_task.target.owner)
        milestone_id = bug_task.milestone.id
        bug_task.transitionToMilestone(None, bug_task.target.owner)
        form = {
            'bunny.status': 'In Progress',
            'bunny.assignee.option': 'bunny.assignee.assign_to_nobody',
            'bunny.target': 'product',
            'bunny.target.product': 'duck',
            'bunny.milestone': milestone_id,
            'bunny.actions.save': 'Save Changes',
            }
        view = create_initialized_view(
            bug_task, name='+editstatus', form=form)
        self.assertEqual([], view.errors)
        self.assertEqual(second_product, bug_task.target)
        self.assertEqual(None, bug_task.milestone)
        notifications = view.request.response.notifications
        self.assertEqual(1, len(notifications))
        expected = ('The milestone setting was ignored')
        self.assertTrue(notifications.pop().message.startswith(expected))

    def createNameChangingViewForSourcePackageTask(self, bug_task, new_name):
        login_person(bug_task.owner)
        form_prefix = '%s_%s_%s' % (
            bug_task.target.distroseries.distribution.name,
            bug_task.target.distroseries.name,
            bug_task.target.sourcepackagename.name)
        form = {
            form_prefix + '.sourcepackagename': new_name,
            form_prefix + '.actions.save': 'Save Changes',
            }
        view = create_initialized_view(
            bug_task, name='+editstatus', form=form)
        return view

    def test_retarget_sourcepackage(self):
        # The sourcepackagename of a SourcePackage task can be changed.
        ds = self.factory.makeDistroSeries()
        sp1 = self.factory.makeSourcePackage(distroseries=ds, publish=True)
        sp2 = self.factory.makeSourcePackage(distroseries=ds, publish=True)
        bug_task = self.factory.makeBugTask(target=sp1)

        view = self.createNameChangingViewForSourcePackageTask(
            bug_task, sp2.sourcepackagename.name)
        self.assertEqual([], view.errors)
        self.assertEqual(sp2, bug_task.target)
        notifications = view.request.response.notifications
        self.assertEqual(0, len(notifications))

    def test_retarget_sourcepackage_to_binary_name(self):
        # The sourcepackagename of a SourcePackage task can be changed
        # to a binarypackagename, which gets mapped back to the source.
        ds = self.factory.makeDistroSeries()
        das = self.factory.makeDistroArchSeries(distroseries=ds)
        sp1 = self.factory.makeSourcePackage(distroseries=ds, publish=True)
        # Now create a binary and its corresponding SourcePackage.
        bp = self.factory.makeBinaryPackagePublishingHistory(
            distroarchseries=das)
        bpr = bp.binarypackagerelease
        spn = bpr.build.source_package_release.sourcepackagename
        sp2 = self.factory.makeSourcePackage(
            distroseries=ds, sourcepackagename=spn, publish=True)
        bug_task = self.factory.makeBugTask(target=sp1)

        view = self.createNameChangingViewForSourcePackageTask(
            bug_task, bpr.binarypackagename.name)
        self.assertEqual([], view.errors)
        self.assertEqual(sp2, bug_task.target)
        notifications = view.request.response.notifications
        self.assertEqual(1, len(notifications))
        expected = (
            "'%s' is a binary package. This bug has been assigned to its "
            "source package '%s' instead."
            % (bpr.binarypackagename.name, spn.name))
        self.assertTrue(notifications.pop().message.startswith(expected))

    def test_retarget_sourcepackage_to_distroseries(self):
        # A SourcePackage task can be changed to a DistroSeries one.
        ds = self.factory.makeDistroSeries()
        sp = self.factory.makeSourcePackage(distroseries=ds, publish=True)
        bug_task = self.factory.makeBugTask(target=sp)

        view = self.createNameChangingViewForSourcePackageTask(
            bug_task, '')
        self.assertEqual([], view.errors)
        self.assertEqual(ds, bug_task.target)
        notifications = view.request.response.notifications
        self.assertEqual(0, len(notifications))

    def test_retarget_private_bug(self):
        # If a private bug is re-targetted such that the bug is no longer
        # visible to the user, they are redirected to the pillar's bug index
        # page with a suitable message. This corner case can occur when the
        # disclosure.private_bug_visibility_rules.enabled feature flag is on
        # and a bugtask is re-targetted to a pillar for which the user is not
        # authorised to see any private bugs.
        first_product = self.factory.makeProduct(name='bunny')
        with person_logged_in(first_product.owner):
            bug = self.factory.makeBug(product=first_product, private=True)
            bug_task = bug.bugtasks[0]
        second_product = self.factory.makeProduct(name='duck')

        # The first product owner can see the private bug. We will re-target
        # it to second_product where it will not be visible to that user.
        with person_logged_in(first_product.owner):
            form = {
                'bunny.target': 'product',
                'bunny.target.product': 'duck',
                'bunny.actions.save': 'Save Changes',
                }
            with FeatureFixture({
                'disclosure.private_bug_visibility_rules.enabled': 'on'}):
                view = create_initialized_view(
                    bug_task, name='+editstatus', form=form)
            self.assertEqual(
                canonical_url(bug_task.pillar, rootsite='bugs'),
                view.next_url)
        self.assertEqual([], view.errors)
        self.assertEqual(second_product, bug_task.target)
        notifications = view.request.response.notifications
        self.assertEqual(1, len(notifications))
        expected = ('The bug you have just updated is now a private bug for')
        self.assertTrue(notifications.pop().message.startswith(expected))


class TestPersonBugs(TestCaseWithFactory):
    """Test the bugs overview page for distributions."""

    layer = DatabaseFunctionalLayer

    def setUp(self):
        super(TestPersonBugs, self).setUp()
        self.target = self.factory.makePerson()

    def test_shouldShowStructuralSubscriberWidget(self):
        view = create_initialized_view(
            self.target, name=u'+bugs', rootsite='bugs')
        self.assertTrue(view.shouldShowStructuralSubscriberWidget())

    def test_structural_subscriber_label(self):
        view = create_initialized_view(
            self.target, name=u'+bugs', rootsite='bugs')
        self.assertEqual(
            'Project, distribution, package, or series subscriber',
            view.structural_subscriber_label)


class TestDistributionBugs(TestCaseWithFactory):
    """Test the bugs overview page for distributions."""

    layer = DatabaseFunctionalLayer

    def setUp(self):
        super(TestDistributionBugs, self).setUp()
        self.target = self.factory.makeDistribution()

    def test_shouldShowStructuralSubscriberWidget(self):
        view = create_initialized_view(
            self.target, name=u'+bugs', rootsite='bugs')
        self.assertTrue(view.shouldShowStructuralSubscriberWidget())

    def test_structural_subscriber_label(self):
        view = create_initialized_view(
            self.target, name=u'+bugs', rootsite='bugs')
        self.assertEqual(
            'Package, or series subscriber', view.structural_subscriber_label)


class TestDistroSeriesBugs(TestCaseWithFactory):
    """Test the bugs overview page for distro series."""

    layer = DatabaseFunctionalLayer

    def setUp(self):
        super(TestDistroSeriesBugs, self).setUp()
        self.target = self.factory.makeDistroSeries()

    def test_shouldShowStructuralSubscriberWidget(self):
        view = create_initialized_view(
            self.target, name=u'+bugs', rootsite='bugs')
        self.assertTrue(view.shouldShowStructuralSubscriberWidget())

    def test_structural_subscriber_label(self):
        view = create_initialized_view(
            self.target, name=u'+bugs', rootsite='bugs')
        self.assertEqual(
            'Package subscriber', view.structural_subscriber_label)


class TestDistributionSourcePackageBugs(TestCaseWithFactory):
    """Test the bugs overview page for distribution source packages."""

    layer = DatabaseFunctionalLayer

    def setUp(self):
        super(TestDistributionSourcePackageBugs, self).setUp()
        self.target = self.factory.makeDistributionSourcePackage()

    def test_shouldShowStructuralSubscriberWidget(self):
        view = create_initialized_view(
            self.target, name=u'+bugs', rootsite='bugs')
        self.assertFalse(view.shouldShowStructuralSubscriberWidget())


class TestDistroSeriesSourcePackageBugs(TestCaseWithFactory):
    """Test the bugs overview page for distro series source packages."""

    layer = DatabaseFunctionalLayer

    def setUp(self):
        super(TestDistroSeriesSourcePackageBugs, self).setUp()
        self.target = self.factory.makeSourcePackage()

    def test_shouldShowStructuralSubscriberWidget(self):
        view = create_initialized_view(
            self.target, name=u'+bugs', rootsite='bugs')
        self.assertFalse(view.shouldShowStructuralSubscriberWidget())


class TestProductBugs(TestCaseWithFactory):
    """Test the bugs overview page for projects."""

    layer = DatabaseFunctionalLayer

    def setUp(self):
        super(TestProductBugs, self).setUp()
        self.target = self.factory.makeProduct()

    def test_shouldShowStructuralSubscriberWidget(self):
        view = create_initialized_view(
            self.target, name=u'+bugs', rootsite='bugs')
        self.assertTrue(view.shouldShowStructuralSubscriberWidget())

    def test_structural_subscriber_label(self):
        view = create_initialized_view(
            self.target, name=u'+bugs', rootsite='bugs')
        self.assertEqual(
            'Series subscriber', view.structural_subscriber_label)


class TestProductSeriesBugs(TestCaseWithFactory):
    """Test the bugs overview page for project series."""

    layer = DatabaseFunctionalLayer

    def setUp(self):
        super(TestProductSeriesBugs, self).setUp()
        self.target = self.factory.makeProductSeries()

    def test_shouldShowStructuralSubscriberWidget(self):
        view = create_initialized_view(
            self.target, name=u'+bugs', rootsite='bugs')
        self.assertFalse(view.shouldShowStructuralSubscriberWidget())


class TestProjectGroupBugs(TestCaseWithFactory):
    """Test the bugs overview page for project groups."""

    layer = DatabaseFunctionalLayer

    def setUp(self):
        super(TestProjectGroupBugs, self).setUp()
        self.owner = self.factory.makePerson(name='bob')
        self.projectgroup = self.factory.makeProject(name='container',
                                                     owner=self.owner)

    def makeSubordinateProduct(self, tracks_bugs_in_lp):
        """Create a new product and add it to the project group."""
        product = self.factory.makeProduct(official_malone=tracks_bugs_in_lp)
        with person_logged_in(product.owner):
            product.project = self.projectgroup

    def test_empty_project_group(self):
        # An empty project group does not use Launchpad for bugs.
        view = create_initialized_view(
            self.projectgroup, name=u'+bugs', rootsite='bugs')
        self.assertFalse(self.projectgroup.hasProducts())
        self.assertFalse(view.should_show_bug_information)

    def test_project_group_with_subordinate_not_using_launchpad(self):
        # A project group with all subordinates not using Launchpad
        # will itself be marked as not using Launchpad for bugs.
        self.makeSubordinateProduct(False)
        self.assertTrue(self.projectgroup.hasProducts())
        view = create_initialized_view(
            self.projectgroup, name=u'+bugs', rootsite='bugs')
        self.assertFalse(view.should_show_bug_information)

    def test_project_group_with_subordinate_using_launchpad(self):
        # A project group with one subordinate using Launchpad
        # will itself be marked as using Launchpad for bugs.
        self.makeSubordinateProduct(True)
        self.assertTrue(self.projectgroup.hasProducts())
        view = create_initialized_view(
            self.projectgroup, name=u'+bugs', rootsite='bugs')
        self.assertTrue(view.should_show_bug_information)

    def test_project_group_with_mixed_subordinates(self):
        # A project group with one or more subordinates using Launchpad
        # will itself be marked as using Launchpad for bugs.
        self.makeSubordinateProduct(False)
        self.makeSubordinateProduct(True)
        self.assertTrue(self.projectgroup.hasProducts())
        view = create_initialized_view(
            self.projectgroup, name=u'+bugs', rootsite='bugs')
        self.assertTrue(view.should_show_bug_information)

    def test_project_group_has_no_portlets_if_not_using_LP(self):
        # A project group that has no projects using Launchpad will not have
        # bug portlets.
        self.makeSubordinateProduct(False)
        view = create_initialized_view(
            self.projectgroup, name=u'+bugs', rootsite='bugs',
            current_request=True)
        self.assertFalse(view.should_show_bug_information)
        contents = view.render()
        report_a_bug = find_tag_by_id(contents, 'bug-portlets')
        self.assertIs(None, report_a_bug)

    def test_project_group_has_portlets_link_if_using_LP(self):
        # A project group that has projects using Launchpad will have a
        # portlets.
        self.makeSubordinateProduct(True)
        view = create_initialized_view(
            self.projectgroup, name=u'+bugs', rootsite='bugs',
            current_request=True)
        self.assertTrue(view.should_show_bug_information)
        contents = view.render()
        report_a_bug = find_tag_by_id(contents, 'bug-portlets')
        self.assertIsNot(None, report_a_bug)

    def test_project_group_has_help_link_if_not_using_LP(self):
        # A project group that has no projects using Launchpad will have
        # a 'Getting started' help link.
        self.makeSubordinateProduct(False)
        view = create_initialized_view(
            self.projectgroup, name=u'+bugs', rootsite='bugs',
            current_request=True)
        contents = view.render()
        help_link = find_tag_by_id(contents, 'getting-started-help')
        self.assertIsNot(None, help_link)

    def test_project_group_has_no_help_link_if_using_LP(self):
        # A project group that has no projects using Launchpad will not have
        # a 'Getting started' help link.
        self.makeSubordinateProduct(True)
        view = create_initialized_view(
            self.projectgroup, name=u'+bugs', rootsite='bugs',
            current_request=True)
        contents = view.render()
        help_link = find_tag_by_id(contents, 'getting-started-help')
        self.assertIs(None, help_link)

    def test_shouldShowStructuralSubscriberWidget(self):
        view = create_initialized_view(
            self.projectgroup, name=u'+bugs', rootsite='bugs')
        self.assertTrue(view.shouldShowStructuralSubscriberWidget())

    def test_structural_subscriber_label(self):
        view = create_initialized_view(
            self.projectgroup, name=u'+bugs', rootsite='bugs')
        self.assertEqual(
            'Project or series subscriber', view.structural_subscriber_label)


class TestBugActivityItem(TestCaseWithFactory):

    layer = DatabaseFunctionalLayer

    def setAttribute(self, obj, attribute, value):
        obj_before_modification = Snapshot(obj, providing=providedBy(obj))
        setattr(removeSecurityProxy(obj), attribute, value)
        notify(ObjectModifiedEvent(
            obj, obj_before_modification, [attribute],
            self.factory.makePerson()))

    def test_escapes_assignee(self):
        with celebrity_logged_in('admin'):
            task = self.factory.makeBugTask()
            self.setAttribute(
                task, 'assignee',
                self.factory.makePerson(displayname="Foo &<>", name='foo'))
        self.assertEquals(
            "nobody &#8594; Foo &amp;&lt;&gt; (foo)",
            BugActivityItem(task.bug.activity[-1]).change_details)

    def test_escapes_title(self):
        with celebrity_logged_in('admin'):
            bug = self.factory.makeBug(title="foo")
            self.setAttribute(bug, 'title', "bar &<>")
        self.assertEquals(
            "- foo<br />+ bar &amp;&lt;&gt;",
            BugActivityItem(bug.activity[-1]).change_details)


class TestBugTaskBatchedCommentsAndActivityView(TestCaseWithFactory):
    """Tests for the BugTaskBatchedCommentsAndActivityView class."""

    layer = LaunchpadFunctionalLayer

    def _makeNoisyBug(self, comments_only=False, number_of_comments=10,
                      number_of_changes=10):
        """Create and return a bug with a lot of comments and activity."""
        bug = self.factory.makeBug()
        with person_logged_in(bug.owner):
            if not comments_only:
                for i in range(number_of_changes):
                    change = BugTaskStatusChange(
                        bug.default_bugtask, UTC_NOW,
                        bug.default_bugtask.product.owner, 'status',
                        BugTaskStatus.NEW, BugTaskStatus.TRIAGED)
                    bug.addChange(change)
            for i in range(number_of_comments):
                msg = self.factory.makeMessage(
                    owner=bug.owner, content="Message %i." % i)
                bug.linkMessage(msg, user=bug.owner)
        return bug

    def _assertThatUnbatchedAndBatchedActivityMatch(self, unbatched_activity,
                                                    batched_activity):
        zipped_activity = zip(
            unbatched_activity, batched_activity)
        for index, items in enumerate(zipped_activity):
            unbatched_item, batched_item = items
            self.assertEqual(
                unbatched_item['comment'].index,
                batched_item['comment'].index,
                "The comments at index %i don't match. Expected to see "
                "comment %i, got comment %i instead." %
                (index, unbatched_item['comment'].index,
                batched_item['comment'].index))

    def test_offset(self):
        # BugTaskBatchedCommentsAndActivityView.offset returns the
        # current offset being used to select a batch of bug comments
        # and activity. If one is not specified, the offset will be the
        # view's visible_initial_comments count + 1 (so that comments
        # already shown on the page won't appear twice).
        bug_task = self.factory.makeBugTask()
        view = create_initialized_view(bug_task, '+batched-comments')
        self.assertEqual(view.visible_initial_comments + 1, view.offset)
        view = create_initialized_view(
            bug_task, '+batched-comments', form={'offset': 100})
        self.assertEqual(100, view.offset)

    def test_batch_size(self):
        # BugTaskBatchedCommentsAndActivityView.batch_size returns the
        # current batch_size being used to select a batch of bug comments
        # and activity or the default configured batch size if one has
        # not been specified.
        bug_task = self.factory.makeBugTask()
        view = create_initialized_view(bug_task, '+batched-comments')
        self.assertEqual(
            config.malone.comments_list_default_batch_size,
            view.batch_size)
        view = create_initialized_view(
            bug_task, '+batched-comments', form={'batch_size': 20})
        self.assertEqual(20, view.batch_size)

    def test_event_groups_only_returns_batch_size_results(self):
        # BugTaskBatchedCommentsAndActivityView._event_groups will
        # return only batch_size results.
        bug = self._makeNoisyBug(number_of_comments=20)
        view = create_initialized_view(
            bug.default_bugtask, '+batched-comments',
            form={'batch_size': 10, 'offset': 1})
        self.assertEqual(10, len([group for group in view._event_groups]))

    def test_event_groups_excludes_visible_recent_comments(self):
        # BugTaskBatchedCommentsAndActivityView._event_groups will
        # not return the last view comments - those covered by the
        # visible_recent_comments property.
        bug = self._makeNoisyBug(number_of_comments=20, comments_only=True)
        batched_view = create_initialized_view(
            bug.default_bugtask, '+batched-comments',
            form={'batch_size': 10, 'offset': 10})
        expected_length = 10 - batched_view.visible_recent_comments
        actual_length = len([group for group in batched_view._event_groups])
        self.assertEqual(
            expected_length, actual_length,
            "Expected %i comments, got %i." %
            (expected_length, actual_length))
        unbatched_view = create_initialized_view(
            bug.default_bugtask, '+index', form={'comments': 'all'})
        self._assertThatUnbatchedAndBatchedActivityMatch(
            unbatched_view.activity_and_comments[9:],
            batched_view.activity_and_comments)

    def test_activity_and_comments_matches_unbatched_version(self):
        # BugTaskBatchedCommentsAndActivityView extends BugTaskView in
        # order to add the batching logic and reduce rendering
        # overheads. The results of activity_and_comments is the same
        # for both.
        # We create a bug with comments only so that we can test the
        # contents of activity_and_comments properly. Trying to test it
        # with multiply different datatypes is fragile at best.
        bug = self._makeNoisyBug(comments_only=True, number_of_comments=20)
        # We create a batched view with an offset of 0 so that all the
        # comments are returned.
        batched_view = create_initialized_view(
            bug.default_bugtask, '+batched-comments',
            {'offset': 5, 'batch_size': 10})
        unbatched_view = create_initialized_view(
            bug.default_bugtask, '+index', form={'comments': 'all'})
        # It may look slightly confusing, but it's because the unbatched
        # view's activity_and_comments list is indexed from comment 1,
        # whereas the batched view indexes from zero for ease-of-coding.
        # Comment 0 is the original bug description and so is rarely
        # returned.
        self._assertThatUnbatchedAndBatchedActivityMatch(
            unbatched_view.activity_and_comments[4:],
            batched_view.activity_and_comments)


def make_bug_task_listing_item(factory):
    owner = factory.makePerson()
    bug = factory.makeBug(
        owner=owner, private=True, security_related=True)
    bugtask = bug.default_bugtask
    bug_task_set = getUtility(IBugTaskSet)
    bug_badge_properties = bug_task_set.getBugTaskBadgeProperties(
        [bugtask])
    badge_property = bug_badge_properties[bugtask]
    return owner, BugTaskListingItem(
        bugtask,
        badge_property['has_branch'],
        badge_property['has_specification'],
        badge_property['has_patch'],
        target_context=bugtask.target)


class TestBugTaskSearchListingView(BrowserTestCase):

    layer = DatabaseFunctionalLayer

    client_listing = soupmatchers.Tag(
        'client-listing', True, attrs={'id': 'client-listing'})

    def makeView(self, bugtask=None, size=None, memo=None, orderby=None,
                 forwards=True, cookie=None):
        """Make a BugTaskSearchListingView.

        :param bugtask: The task to use for searching.
        :param size: The size of the batches.  Required if forwards is False.
        :param memo: Batch identifier.
        :param orderby: The way to order the batch.
        :param forwards: If true, walk forwards from the memo.  Else walk
            backwards.

        """
        query_vars = {}
        if size is not None:
            query_vars['batch'] = size
        if memo is not None:
            query_vars['memo'] = memo
            if forwards:
                query_vars['start'] = memo
            else:
                query_vars['start'] = int(memo) - size
        if not forwards:
            query_vars['direction'] = 'backwards'
        query_string = urllib.urlencode(query_vars)
        request = LaunchpadTestRequest(
            QUERY_STRING=query_string, orderby=orderby, HTTP_COOKIE=cookie)
        if bugtask is None:
            bugtask = self.factory.makeBugTask()
        view = getMultiAdapter((bugtask.target, request), name='+bugs')
        view.initialize()
        return view

    @contextmanager
    def dynamic_listings(self):
        """Context manager to enable new bug listings."""
        with feature_flags():
            set_feature_flag(u'bugs.dynamic_bug_listings.enabled', u'on')
            yield

    def test_mustache_model_missing_if_no_flag(self):
        """The IJSONRequestCache should contain mustache_model."""
        view = self.makeView()
        cache = IJSONRequestCache(view.request)
        self.assertIs(None, cache.objects.get('mustache_model'))

    def test_mustache_model_in_json(self):
        """The IJSONRequestCache should contain mustache_model.

        mustache_model should contain bugtasks, the BugTaskListingItem.model
        for each BugTask.
        """
        owner, item = make_bug_task_listing_item(self.factory)
        self.useContext(person_logged_in(owner))
        with self.dynamic_listings():
            view = self.makeView(item.bugtask)
        cache = IJSONRequestCache(view.request)
        bugtasks = cache.objects['mustache_model']['bugtasks']
        self.assertEqual(1, len(bugtasks))
        combined = dict(item.model)
        combined.update(view.search().field_visibility)
        self.assertEqual(combined, bugtasks[0])

    def test_no_next_prev_for_single_batch(self):
        """The IJSONRequestCache should contain data about ajacent batches.

        mustache_model should contain bugtasks, the BugTaskListingItem.model
        for each BugTask.
        """
        owner, item = make_bug_task_listing_item(self.factory)
        self.useContext(person_logged_in(owner))
        with self.dynamic_listings():
            view = self.makeView(item.bugtask)
        cache = IJSONRequestCache(view.request)
        self.assertIs(None, cache.objects.get('next'))
        self.assertIs(None, cache.objects.get('prev'))

    def test_next_for_multiple_batch(self):
        """The IJSONRequestCache should contain data about the next batch.

        mustache_model should contain bugtasks, the BugTaskListingItem.model
        for each BugTask.
        """
        task = self.factory.makeBugTask()
        self.factory.makeBugTask(target=task.target)
        with self.dynamic_listings():
            view = self.makeView(task, size=1)
        cache = IJSONRequestCache(view.request)
        self.assertEqual({'memo': '1', 'start': 1}, cache.objects.get('next'))

    def test_prev_for_multiple_batch(self):
        """The IJSONRequestCache should contain data about the next batch.

        mustache_model should contain bugtasks, the BugTaskListingItem.model
        for each BugTask.
        """
        task = self.factory.makeBugTask()
        task2 = self.factory.makeBugTask(target=task.target)
        with self.dynamic_listings():
            view = self.makeView(task2, size=1, memo=1)
        cache = IJSONRequestCache(view.request)
        self.assertEqual({'memo': '1', 'start': 0}, cache.objects.get('prev'))

    def test_provides_view_name(self):
        """The IJSONRequestCache should provide the view's name."""
        self.useContext(self.dynamic_listings())
        view = self.makeView()
        cache = IJSONRequestCache(view.request)
        self.assertEqual('+bugs', cache.objects['view_name'])
        person = self.factory.makePerson()
        commentview = getMultiAdapter(
            (person, LaunchpadTestRequest()), name='+commentedbugs')
        commentview.initialize()
        cache = IJSONRequestCache(commentview.request)
        self.assertEqual('+commentedbugs', cache.objects['view_name'])

    def test_default_order_by(self):
        """order_by defaults to '-importance in JSONRequestCache"""
        task = self.factory.makeBugTask()
        with self.dynamic_listings():
            view = self.makeView(task)
        cache = IJSONRequestCache(view.request)
        self.assertEqual('-importance', cache.objects['order_by'])

    def test_order_by_importance(self):
        """order_by follows query params in JSONRequestCache"""
        task = self.factory.makeBugTask()
        with self.dynamic_listings():
            view = self.makeView(task, orderby='importance')
        cache = IJSONRequestCache(view.request)
        self.assertEqual('importance', cache.objects['order_by'])

    def test_cache_has_all_batch_vars_defaults(self):
        """Cache has all the needed variables.

        order_by, memo, start, forwards.  These default to sane values.
        """
        task = self.factory.makeBugTask()
        with self.dynamic_listings():
            view = self.makeView(task)
        cache = IJSONRequestCache(view.request)
        self.assertEqual('-importance', cache.objects['order_by'])
        self.assertIs(None, cache.objects['memo'])
        self.assertEqual(0, cache.objects['start'])
        self.assertTrue(cache.objects['forwards'])
        self.assertEqual(1, cache.objects['total'])

    def test_cache_has_all_batch_vars_specified(self):
        """Cache has all the needed variables.

        order_by, memo, start, forwards.  These are calculated appropriately.
        """
        task = self.factory.makeBugTask()
        with self.dynamic_listings():
            view = self.makeView(task, memo=1, forwards=False, size=1)
        cache = IJSONRequestCache(view.request)
        self.assertEqual('1', cache.objects['memo'])
        self.assertEqual(0, cache.objects['start'])
        self.assertFalse(cache.objects['forwards'])
        self.assertEqual(0, cache.objects['last_start'])

    def test_cache_field_visibility(self):
        """Cache contains sane-looking field_visibility values."""
        task = self.factory.makeBugTask()
        with self.dynamic_listings():
            view = self.makeView(task, memo=1, forwards=False, size=1)
        cache = IJSONRequestCache(view.request)
        field_visibility = cache.objects['field_visibility']
        self.assertTrue(field_visibility['show_id'])

    def test_cache_cookie_name(self):
        """The cookie name should be in cache for js code access."""
        task = self.factory.makeBugTask()
        with self.dynamic_listings():
            view = self.makeView(task, memo=1, forwards=False, size=1)
        cache = IJSONRequestCache(view.request)
        cookie_name = cache.objects['cbl_cookie_name']
        self.assertEqual('anon-buglist-fields', cookie_name)

    def test_cache_field_visibility_matches_cookie(self):
        """Cache contains cookie-matching values for field_visibiliy."""
        task = self.factory.makeBugTask()
        cookie = (
            'anon-buglist-fields=show_age=true&show_reporter=true'
            '&show_id=true&show_bugtarget=true'
            '&show_milestone_name=true&show_last_updated=true'
            '&show_assignee=true&show_bug_heat=true&show_tags=true'
            '&show_importance=true&show_status=true')
        with self.dynamic_listings():
            view = self.makeView(
                task, memo=1, forwards=False, size=1, cookie=cookie)
        cache = IJSONRequestCache(view.request)
        field_visibility = cache.objects['field_visibility']
        self.assertTrue(field_visibility['show_tags'])

    def test_exclude_unsupported_cookie_values(self):
        """Cookie values not present in defaults are ignored."""
        task = self.factory.makeBugTask()
        cookie = (
            'anon-buglist-fields=show_age=true&show_reporter=true'
            '&show_id=true&show_bugtarget=true'
            '&show_milestone_name=true&show_last_updated=true'
            '&show_assignee=true&show_bug_heat=true&show_tags=true'
            '&show_importance=true&show_status=true&show_title=true')
        with self.dynamic_listings():
            view = self.makeView(
                task, memo=1, forwards=False, size=1, cookie=cookie)
        cache = IJSONRequestCache(view.request)
        field_visibility = cache.objects['field_visibility']
        self.assertNotIn('show_title', field_visibility)

    def test_add_defaults_to_cookie_values(self):
        """Where cookie values are missing, defaults are used"""
        task = self.factory.makeBugTask()
        cookie = (
            'anon-buglist-fields=show_age=true&show_reporter=true'
            '&show_id=true&show_bugtarget=true'
            '&show_milestone_name=true&show_last_updated=true'
            '&show_assignee=true&show_bug_heat=true&show_tags=true'
            '&show_importance=true&show_title=true')
        with self.dynamic_listings():
            view = self.makeView(
                task, memo=1, forwards=False, size=1, cookie=cookie)
        cache = IJSONRequestCache(view.request)
        field_visibility = cache.objects['field_visibility']
        self.assertIn('show_status', field_visibility)

    def test_cache_field_visibility_defaults(self):
        """Cache contains sane-looking field_visibility_defaults values."""
        task = self.factory.makeBugTask()
        with self.dynamic_listings():
            view = self.makeView(task, memo=1, forwards=False, size=1)
        cache = IJSONRequestCache(view.request)
        field_visibility_defaults = cache.objects['field_visibility_defaults']
        self.assertTrue(field_visibility_defaults['show_id'])

    def getBugtaskBrowser(self, title=None, no_login=False):
        """Return a browser for a new bugtask."""
        bugtask = self.factory.makeBugTask()
        with person_logged_in(bugtask.target.owner):
            bugtask.target.official_malone = True
            if title is not None:
                bugtask.bug.title = title
        browser = self.getViewBrowser(
            bugtask.target, '+bugs', rootsite='bugs', no_login=no_login)
        return bugtask, browser

    def assertHTML(self, browser, *tags, **kwargs):
        """Assert something about a browser's HTML."""
        matcher = soupmatchers.HTMLContains(*tags)
        if kwargs.get('invert', False):
            matcher = Not(matcher)
        self.assertThat(browser.contents, matcher)

    @staticmethod
    def getBugNumberTag(bug_task):
        """Bug numbers with a leading hash are unique to new rendering."""
        bug_number_re = re.compile(r'\#%d' % bug_task.bug.id)
        return soupmatchers.Tag('bugnumber', 'span', text=bug_number_re)

    def test_mustache_rendering_missing_if_no_flag(self):
        """If the flag is missing, then no mustache features appear."""
        bug_task, browser = self.getBugtaskBrowser()
        number_tag = self.getBugNumberTag(bug_task)
        self.assertHTML(browser, number_tag, invert=True)
        self.assertHTML(browser, self.client_listing, invert=True)

    def test_mustache_rendering(self):
        """If the flag is present, then all mustache features appear."""
        with self.dynamic_listings():
            bug_task, browser = self.getBugtaskBrowser()
        bug_number = self.getBugNumberTag(bug_task)
        self.assertHTML(browser, self.client_listing, bug_number)

    def test_mustache_rendering_obfuscation(self):
        """For anonymous users, email addresses are obfuscated."""
        with self.dynamic_listings():
            bug_task, browser = self.getBugtaskBrowser(title='a@example.com',
                no_login=True)
        self.assertNotIn('a@example.com', browser.contents)

    def getNavigator(self):
        request = LaunchpadTestRequest()
        navigator = BugListingBatchNavigator([], request, [], 1)
        cache = IJSONRequestCache(request)
        bugtask = {
            'age': 'age1',
            'assignee': 'assignee1',
            'bugtarget': 'bugtarget1',
            'bugtarget_css': 'bugtarget_css1',
            'bug_heat_html': 'bug_heat_html1',
            'bug_url': 'bug_url1',
            'id': '3.14159',
            'importance': 'importance1',
            'importance_class': 'importance_class1',
            'last_updated': 'updated1',
            'milestone_name': 'milestone_name1',
            'status': 'status1',
            'reporter': 'reporter1',
            'tags': 'tags1',
            'title': 'title1',
        }
        bugtask.update(navigator.field_visibility)
        cache.objects['mustache_model'] = {
            'bugtasks': [bugtask],
        }
        mustache_model = cache.objects['mustache_model']
        return navigator, mustache_model

    def test_hiding_bug_number(self):
        """Hiding a bug number makes it disappear from the page."""
        navigator, mustache_model = self.getNavigator()
        self.assertIn('3.14159', navigator.mustache)
        mustache_model['bugtasks'][0]['show_id'] = False
        self.assertNotIn('3.14159', navigator.mustache)

    def test_hiding_status(self):
        """Hiding status makes it disappear from the page."""
        navigator, mustache_model = self.getNavigator()
        self.assertIn('status1', navigator.mustache)
        mustache_model['bugtasks'][0]['show_status'] = False
        self.assertNotIn('status1', navigator.mustache)

    def test_hiding_importance(self):
        """Hiding importance removes the text and CSS."""
        navigator, mustache_model = self.getNavigator()
        self.assertIn('importance1', navigator.mustache)
        self.assertIn('importance_class1', navigator.mustache)
        mustache_model['bugtasks'][0]['show_importance'] = False
        self.assertNotIn('importance1', navigator.mustache)
        self.assertNotIn('importance_class1', navigator.mustache)

    def test_hiding_bugtarget(self):
        """Hiding bugtarget removes the text and CSS."""
        navigator, mustache_model = self.getNavigator()
        self.assertIn('bugtarget1', navigator.mustache)
        self.assertIn('bugtarget_css1', navigator.mustache)
        mustache_model['bugtasks'][0]['show_bugtarget'] = False
        self.assertNotIn('bugtarget1', navigator.mustache)
        self.assertNotIn('bugtarget_css1', navigator.mustache)

    def test_hiding_bug_heat(self):
        """Hiding bug heat removes the html and CSS."""
        navigator, mustache_model = self.getNavigator()
        self.assertIn('bug_heat_html1', navigator.mustache)
        self.assertIn('bug-heat-icons', navigator.mustache)
        mustache_model['bugtasks'][0]['show_bug_heat'] = False
        self.assertNotIn('bug_heat_html1', navigator.mustache)
        self.assertNotIn('bug-heat-icons', navigator.mustache)

    def test_hiding_milstone_name(self):
        """Showing milestone name shows the text."""
        navigator, mustache_model = self.getNavigator()
        self.assertNotIn('milestone_name1', navigator.mustache)
        mustache_model['bugtasks'][0]['show_milestone_name'] = True
        self.assertIn('milestone_name1', navigator.mustache)

    def test_hiding_assignee(self):
        """Showing milestone name shows the text."""
        navigator, mustache_model = self.getNavigator()
        self.assertIn('show_assignee', navigator.field_visibility)
        self.assertNotIn('Assignee: assignee1', navigator.mustache)
        mustache_model['bugtasks'][0]['show_assignee'] = True
        self.assertIn('Assignee: assignee1', navigator.mustache)

    def test_hiding_age(self):
        """Showing age shows the text."""
        navigator, mustache_model = self.getNavigator()
        self.assertIn('show_age', navigator.field_visibility)
        self.assertNotIn('age1', navigator.mustache)
        mustache_model['bugtasks'][0]['show_age'] = True
        self.assertIn('age1', navigator.mustache)

    def test_hiding_tags(self):
        """Showing tags shows the text."""
        navigator, mustache_model = self.getNavigator()
        self.assertIn('show_tags', navigator.field_visibility)
        self.assertNotIn('tags1', navigator.mustache)
        mustache_model['bugtasks'][0]['show_tags'] = True
        self.assertIn('tags1', navigator.mustache)

    def test_hiding_reporter(self):
        """Showing reporter shows the text."""
        navigator, mustache_model = self.getNavigator()
        self.assertIn('show_reporter', navigator.field_visibility)
        self.assertNotIn('Reporter: reporter1', navigator.mustache)
        mustache_model['bugtasks'][0]['show_reporter'] = True
        self.assertIn('Reporter: reporter1', navigator.mustache)

    def test_hiding_last_updated(self):
        """Showing last_updated shows the text."""
        navigator, mustache_model = self.getNavigator()
        self.assertIn('show_last_updated', navigator.field_visibility)
        self.assertNotIn('Last updated updated1', navigator.mustache)
        mustache_model['bugtasks'][0]['show_last_updated'] = True
        self.assertIn('Last updated updated1', navigator.mustache)


class TestBugListingBatchNavigator(TestCaseWithFactory):

    layer = DatabaseFunctionalLayer

    def test_mustache_listings_escaped(self):
        """Mustache template is encoded such that it has no unescaped tags."""
        navigator = BugListingBatchNavigator(
            [], LaunchpadTestRequest(), [], 0)
        self.assertNotIn('<', navigator.mustache_listings)
        self.assertNotIn('>', navigator.mustache_listings)


class TestBugTaskListingItem(TestCaseWithFactory):

    layer = DatabaseFunctionalLayer

    def test_model(self):
        """Model contains expected fields with expected values."""
        owner, item = make_bug_task_listing_item(self.factory)
        with person_logged_in(owner):
            model = item.model
            self.assertEqual('Undecided', model['importance'])
            self.assertEqual('importanceUNDECIDED', model['importance_class'])
            self.assertEqual('New', model['status'])
            self.assertEqual('statusNEW', model['status_class'])
            self.assertEqual(item.bug.title, model['title'])
            self.assertEqual(item.bug.id, model['id'])
            self.assertEqual(canonical_url(item.bugtask), model['bug_url'])
            self.assertEqual(item.bugtargetdisplayname, model['bugtarget'])
            self.assertEqual('sprite product', model['bugtarget_css'])
            self.assertEqual(item.bug_heat_html, model['bug_heat_html'])
            self.assertEqual(
                '<span alt="private" title="Private" class="sprite private">'
                '&nbsp;</span>', model['badges'])
            self.assertEqual(None, model['milestone_name'])
            item.bugtask.milestone = self.factory.makeMilestone(
                product=item.bugtask.target)
            milestone_name = item.milestone.displayname
            self.assertEqual(milestone_name, item.model['milestone_name'])

    def test_model_assignee(self):
        """Model contains expected fields with expected values."""
        owner, item = make_bug_task_listing_item(self.factory)
        with person_logged_in(owner):
            self.assertIs(None, item.model['assignee'])
            assignee = self.factory.makePerson(displayname='Example Person')
            item.bugtask.transitionToAssignee(assignee)
            self.assertEqual('Example Person', item.model['assignee'])

    def test_model_age(self):
        """Model contains bug age."""
        owner, item = make_bug_task_listing_item(self.factory)
        with person_logged_in(owner):
            item.bug.datecreated = datetime.now(UTC) - timedelta(3, 0, 0)
            self.assertEqual('3 days old', item.model['age'])

    def test_model_tags(self):
        """Model contains bug tags."""
        owner, item = make_bug_task_listing_item(self.factory)
        with person_logged_in(owner):
            item.bug.tags = ['tag1', 'tag2']
            self.assertEqual('tag1 tag2', item.model['tags'])

    def test_model_reporter(self):
        """Model contains bug reporter."""
        owner, item = make_bug_task_listing_item(self.factory)
        with person_logged_in(owner):
            self.assertEqual(owner.displayname, item.model['reporter'])

    def test_model_last_updated_date_last_updated(self):
        """last_updated uses date_last_updated if newer."""
        owner, item = make_bug_task_listing_item(self.factory)
        with person_logged_in(owner):
            item.bug.date_last_updated = datetime(2001, 1, 1, tzinfo=UTC)
            removeSecurityProxy(item.bug).date_last_message = datetime(
                2000, 1, 1, tzinfo=UTC)
            self.assertEqual(
                'on 2001-01-01', item.model['last_updated'])

    def test_model_last_updated_date_last_message(self):
        """last_updated uses date_last_message if newer."""
        owner, item = make_bug_task_listing_item(self.factory)
        with person_logged_in(owner):
            item.bug.date_last_updated = datetime(2000, 1, 1, tzinfo=UTC)
            removeSecurityProxy(item.bug).date_last_message = datetime(
                2001, 1, 1, tzinfo=UTC)
            self.assertEqual(
                'on 2001-01-01', item.model['last_updated'])