~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
# Copyright 2010-2012 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
# pylint: disable-msg=F0401,E1002

"""Tests for the source package recipe view classes and templates."""

__metaclass__ = type


from datetime import (
    datetime,
    timedelta,
    )
from textwrap import dedent

from BeautifulSoup import BeautifulSoup
from mechanize import LinkNotFoundError
from pytz import UTC
from testtools.matchers import Equals
import transaction
from zope.component import getUtility
from zope.security.interfaces import Unauthorized
from zope.security.proxy import removeSecurityProxy

from lp.app.interfaces.launchpad import ILaunchpadCelebrities
from lp.buildmaster.enums import BuildStatus
from lp.code.browser.sourcepackagerecipe import (
    SourcePackageRecipeEditView,
    SourcePackageRecipeRequestBuildsView,
    SourcePackageRecipeRequestDailyBuildView,
    SourcePackageRecipeView,
    )
from lp.code.browser.sourcepackagerecipebuild import (
    SourcePackageRecipeBuildView,
    )
from lp.code.interfaces.sourcepackagerecipe import MINIMAL_RECIPE_TEXT
from lp.code.tests.helpers import recipe_parser_newest_version
from lp.registry.interfaces.person import TeamSubscriptionPolicy
from lp.registry.interfaces.pocket import PackagePublishingPocket
from lp.registry.interfaces.series import SeriesStatus
from lp.services.database.constants import UTC_NOW
from lp.services.propertycache import clear_property_cache
from lp.services.webapp import canonical_url
from lp.services.webapp.interfaces import ILaunchpadRoot
from lp.services.webapp.servers import LaunchpadTestRequest
from lp.soyuz.model.processor import ProcessorFamily
from lp.testing import (
    ANONYMOUS,
    BrowserTestCase,
    login,
    login_person,
    person_logged_in,
    TestCaseWithFactory,
    time_counter,
    )
from lp.testing.deprecated import LaunchpadFormHarness
from lp.testing.factory import remove_security_proxy_and_shout_at_engineer
from lp.testing.layers import (
    DatabaseFunctionalLayer,
    LaunchpadFunctionalLayer,
    )
from lp.testing.matchers import (
    MatchesPickerText,
    MatchesTagText,
    )
from lp.testing.pages import (
    extract_text,
    find_main_content,
    find_tag_by_id,
    find_tags_by_class,
    get_feedback_messages,
    get_radio_button_text_for_field,
    )
from lp.testing.views import create_initialized_view


class TestCanonicalUrlForRecipe(TestCaseWithFactory):

    layer = DatabaseFunctionalLayer

    def test_canonical_url(self):
        owner = self.factory.makePerson(name='recipe-owner')
        recipe = self.factory.makeSourcePackageRecipe(
            owner=owner, name=u'recipe-name')
        self.assertEqual(
            'http://code.launchpad.dev/~recipe-owner/+recipe/recipe-name',
            canonical_url(recipe))


class TestCaseForRecipe(BrowserTestCase):
    """Create some sample data for recipe tests."""

    def setUp(self):
        """Provide useful defaults."""
        super(TestCaseForRecipe, self).setUp()
        self.chef = self.factory.makePerson(
            displayname='Master Chef', name='chef', password='test')
        self.user = self.chef
        self.ppa = self.factory.makeArchive(
            displayname='Secret PPA', owner=self.chef, name='ppa')
        self.squirrel = self.factory.makeDistroSeries(
            displayname='Secret Squirrel', name='secret', version='100.04',
            distribution=self.ppa.distribution)
        naked_squirrel = remove_security_proxy_and_shout_at_engineer(
            self.squirrel)
        naked_squirrel.nominatedarchindep = self.squirrel.newArch(
            'i386', ProcessorFamily.get(1), False, self.chef,
            supports_virtualized=True)

    def makeRecipe(self):
        """Create and return a specific recipe."""
        chocolate = self.factory.makeProduct(name='chocolate')
        cake_branch = self.factory.makeProductBranch(
            owner=self.chef, name='cake', product=chocolate)
        return self.factory.makeSourcePackageRecipe(
            owner=self.chef, distroseries=self.squirrel, name=u'cake_recipe',
            description=u'This recipe builds a foo for disto bar, with my'
            ' Secret Squirrel changes.', branches=[cake_branch],
            daily_build_archive=self.ppa)

    def checkRelatedBranches(self, related_series_branch_info,
                             related_package_branch_info, browser_contents):
        """Check that the browser contents contain the correct branch info."""
        login(ANONYMOUS)
        soup = BeautifulSoup(browser_contents)

        # The related branches collapsible section needs to be there.
        related_branches = soup.find('fieldset', {'id': 'related-branches'})
        self.assertIsNot(related_branches, None)

        # Check the related package branches.
        root_url = canonical_url(
            getUtility(ILaunchpadRoot), rootsite='code')
        root_url = root_url.rstrip('/')
        branch_table = soup.find(
            'table', {'id': 'related-package-branches-listing'})
        if not related_package_branch_info:
            self.assertIs(branch_table, None)
        else:
            rows = branch_table.tbody.findAll('tr')

            package_branches_info = []
            for row in rows:
                branch_links = row.findAll('a')
                self.assertEqual(2, len(branch_links))
                package_branches_info.append(
                    '%s%s' % (root_url, branch_links[0]['href']))
                package_branches_info.append(branch_links[0].renderContents())
                package_branches_info.append(
                    '%s%s' % (root_url, branch_links[1]['href']))
                package_branches_info.append(branch_links[1].renderContents())
            expected_branch_info = []
            for branch_info in related_package_branch_info:
                branch = branch_info[0]
                distro_series = branch_info[1]
                expected_branch_info.append(
                    canonical_url(branch, rootsite='code'))
                expected_branch_info.append(branch.displayname)
                expected_branch_info.append(
                    canonical_url(distro_series, rootsite='code'))
                expected_branch_info.append(distro_series.name)
            self.assertEqual(package_branches_info, expected_branch_info)

        # Check the related series branches.
        branch_table = soup.find(
            'table', {'id': 'related-series-branches-listing'})
        if not related_series_branch_info:
            self.assertIs(branch_table, None)
        else:
            rows = branch_table.tbody.findAll('tr')

            series_branches_info = []
            for row in rows:
                branch_links = row.findAll('a')
                self.assertEqual(2, len(branch_links))
                series_branches_info.append(
                    '%s%s' % (root_url, branch_links[0]['href']))
                series_branches_info.append(branch_links[0].renderContents())
                series_branches_info.append(branch_links[1]['href'])
                series_branches_info.append(branch_links[1].renderContents())
            expected_branch_info = []
            for branch_info in related_series_branch_info:
                branch = branch_info[0]
                product_series = branch_info[1]
                expected_branch_info.append(
                    canonical_url(branch,
                                  rootsite='code',
                                  path_only_if_possible=True))
                expected_branch_info.append(branch.displayname)
                expected_branch_info.append(
                    canonical_url(product_series,
                                  path_only_if_possible=True))
                expected_branch_info.append(product_series.name)
            self.assertEqual(expected_branch_info, series_branches_info)


def get_message_text(browser, index):
    """Return the text of a message, specified by index."""
    tags = find_tags_by_class(browser.contents, 'message')[index]
    return extract_text(tags)


class TestSourcePackageRecipeAddViewInitalValues(TestCaseWithFactory):

    layer = DatabaseFunctionalLayer

    def test_project_branch_initial_name(self):
        # When a project branch is used, the initial name is the name of the
        # project followed by "-daily"
        widget = self.factory.makeProduct(name='widget')
        branch = self.factory.makeProductBranch(widget)
        with person_logged_in(branch.owner):
            view = create_initialized_view(branch, '+new-recipe')
        self.assertThat('widget-daily', Equals(view.initial_values['name']))

    def test_package_branch_initial_name(self):
        # When a package branch is used, the initial name is the name of the
        # source package followed by "-daily"
        branch = self.factory.makePackageBranch(sourcepackagename='widget')
        with person_logged_in(branch.owner):
            view = create_initialized_view(branch, '+new-recipe')
        self.assertThat('widget-daily', Equals(view.initial_values['name']))

    def test_personal_branch_initial_name(self):
        # When a personal branch is used, the initial name is the name of the
        # branch followed by "-daily". +junk-daily is not valid nor
        # helpful.
        branch = self.factory.makePersonalBranch(name='widget')
        with person_logged_in(branch.owner):
            view = create_initialized_view(branch, '+new-recipe')
        self.assertThat('widget-daily', Equals(view.initial_values['name']))

    def test_initial_name_exists(self):
        # If the initial name exists, a generator is used to find an unused
        # name by appending a numbered suffix on the end.
        owner = self.factory.makePerson()
        self.factory.makeSourcePackageRecipe(
            owner=owner, name=u'widget-daily')
        widget = self.factory.makeProduct(name='widget')
        branch = self.factory.makeProductBranch(widget)
        with person_logged_in(owner):
            view = create_initialized_view(branch, '+new-recipe')
        self.assertThat('widget-daily-1', Equals(view.initial_values['name']))

    def test_initial_series(self):
        # The initial series are those that are current or in development.
        archive = self.factory.makeArchive()
        experimental = self.factory.makeDistroSeries(
            distribution=archive.distribution,
            status=SeriesStatus.EXPERIMENTAL)
        development = self.factory.makeDistroSeries(
            distribution=archive.distribution,
            status=SeriesStatus.DEVELOPMENT)
        frozen = self.factory.makeDistroSeries(
            distribution=archive.distribution,
            status=SeriesStatus.FROZEN)
        current = self.factory.makeDistroSeries(
            distribution=archive.distribution,
            status=SeriesStatus.CURRENT)
        supported = self.factory.makeDistroSeries(
            distribution=archive.distribution,
            status=SeriesStatus.SUPPORTED)
        obsolete = self.factory.makeDistroSeries(
            distribution=archive.distribution,
            status=SeriesStatus.OBSOLETE)
        future = self.factory.makeDistroSeries(
            distribution=archive.distribution,
            status=SeriesStatus.FUTURE)
        branch = self.factory.makeAnyBranch()
        with person_logged_in(archive.owner):
            view = create_initialized_view(branch, '+new-recipe')
        series = set(view.initial_values['distroseries'])
        initial_series = set([development, current])
        self.assertEqual(initial_series, series.intersection(initial_series))
        other_series = set(
            [experimental, frozen, supported, obsolete, future])
        self.assertEqual(set(), series.intersection(other_series))


class TestSourcePackageRecipeAddView(TestCaseForRecipe):

    layer = DatabaseFunctionalLayer

    def makeBranch(self):
        product = self.factory.makeProduct(
            name='ratatouille', displayname='Ratatouille')
        branch = self.factory.makeBranch(
            owner=self.chef, product=product, name='veggies')
        self.factory.makeSourcePackage(sourcepackagename='ratatouille')
        return branch

    def test_create_new_recipe_not_logged_in(self):
        product = self.factory.makeProduct(
            name='ratatouille', displayname='Ratatouille')
        branch = self.factory.makeBranch(
            owner=self.chef, product=product, name='veggies')

        browser = self.getViewBrowser(branch, no_login=True)
        self.assertRaises(
            Unauthorized, browser.getLink('Create packaging recipe').click)

    def test_create_new_recipe(self):
        branch = self.makeBranch()
        # A new recipe can be created from the branch page.
        browser = self.getUserBrowser(canonical_url(branch), user=self.chef)
        browser.getLink('Create packaging recipe').click()

        browser.getControl(name='field.name').value = 'daily'
        browser.getControl('Description').value = 'Make some food!'
        browser.getControl('Create Recipe').click()

        content = find_main_content(browser.contents)
        self.assertEqual('daily', extract_text(content.h1))
        self.assertThat(
            'Make some food!', MatchesTagText(content, 'edit-description'))
        self.assertThat(
            'Master Chef', MatchesPickerText(content, 'edit-owner'))
        self.assertThat(
            'Secret PPA',
            MatchesPickerText(content, 'edit-daily_build_archive'))

    def test_create_new_recipe_private_branch(self):
        # Recipes can't be created on private branches.
        with person_logged_in(self.chef):
            branch = self.factory.makeBranch(private=True, owner=self.chef)
            branch_url = canonical_url(branch)

        browser = self.getUserBrowser(branch_url, user=self.chef)
        self.assertRaises(
            LinkNotFoundError,
            browser.getLink,
            'Create packaging recipe')

    def test_create_new_recipe_users_teams_as_owner_options(self):
        # Teams that the user is in are options for the recipe owner.
        self.factory.makeTeam(
            name='good-chefs', displayname='Good Chefs', members=[self.chef])
        browser = self.getViewBrowser(
            self.makeBranch(), '+new-recipe', user=self.chef)
        # The options for the owner include the Good Chefs team.
        options = browser.getControl(name='field.owner.owner').displayOptions
        self.assertEquals(
            ['Good Chefs (good-chefs)', 'Master Chef (chef)'],
            sorted([str(option) for option in options]))

    def test_create_new_recipe_team_owner(self):
        # New recipes can be owned by teams that the user is a member of.
        team = self.factory.makeTeam(
            name='good-chefs', displayname='Good Chefs', members=[self.chef])
        browser = self.getViewBrowser(
            self.makeBranch(), '+new-recipe', user=self.chef)
        browser.getControl(name='field.name').value = 'daily'
        browser.getControl('Description').value = 'Make some food!'
        browser.getControl('Other').click()
        browser.getControl(name='field.owner.owner').displayValue = [
            'Good Chefs']
        browser.getControl('Create Recipe').click()

        login(ANONYMOUS)
        recipe = team.getRecipe(u'daily')
        self.assertEqual(team, recipe.owner)
        self.assertEqual('daily', recipe.name)

    def test_create_new_recipe_suggests_user(self):
        """The current user is suggested as a recipe owner, once."""
        branch = self.factory.makeBranch(owner=self.chef)
        text = self.getMainText(branch, '+new-recipe')
        self.assertTextMatchesExpressionIgnoreWhitespace(
            r'Owner: Master Chef \(chef\) Other:', text)

    def test_create_new_recipe_suggests_user_team(self):
        """If current user is a member of branch owner, it is suggested."""
        team = self.factory.makeTeam(
            name='branch-team', displayname='Branch Team',
            members=[self.chef])
        branch = self.factory.makeBranch(owner=team)
        text = self.getMainText(branch, '+new-recipe')
        self.assertTextMatchesExpressionIgnoreWhitespace(
            r'Owner: Master Chef \(chef\)'
            r' Branch Team \(branch-team\) Other:', text)

    def test_create_new_recipe_ignores_non_user_team(self):
        """If current user isn't a member of branch owner, it is ignored."""
        team = self.factory.makeTeam(
            name='branch-team', displayname='Branch Team')
        branch = self.factory.makeBranch(owner=team)
        text = self.getMainText(branch, '+new-recipe')
        self.assertTextMatchesExpressionIgnoreWhitespace(
            r'Owner: Master Chef \(chef\) Other:', text)

    def test_create_recipe_forbidden_instruction(self):
        # We don't allow the "run" instruction in our recipes.  Make sure this
        # is communicated to the user properly.
        product = self.factory.makeProduct(
            name='ratatouille', displayname='Ratatouille')
        branch = self.factory.makeBranch(
            owner=self.chef, product=product, name='veggies')
        browser = self.getViewBrowser(branch, '+new-recipe', user=self.chef)
        browser.getControl('Description').value = 'Make some food!'
        browser.getControl('Recipe text').value = (
            browser.getControl('Recipe text').value + 'run cat /etc/passwd')
        browser.getControl('Create Recipe').click()
        self.assertEqual(
            get_feedback_messages(browser.contents)[1],
            'The bzr-builder instruction "run" is not permitted here.')

    def createRecipe(self, recipe_text, branch=None):
        if branch is None:
            product = self.factory.makeProduct(
                name='ratatouille', displayname='Ratatouille')
            branch = self.factory.makeBranch(
                owner=self.chef, product=product, name='veggies')
        browser = self.getViewBrowser(branch, '+new-recipe', user=self.chef)
        browser.getControl(name='field.name').value = 'daily'
        browser.getControl('Description').value = 'Make some food!'
        browser.getControl('Recipe text').value = recipe_text
        browser.getControl('Create Recipe').click()
        return browser

    def test_create_recipe_usage(self):
        # The error for a recipe with invalid instruction parameters should
        # include instruction usage.
        branch = self.factory.makeBranch(name='veggies')
        self.factory.makeBranch(name='packaging')

        browser = self.createRecipe(
            dedent('''\
                # bzr-builder format 0.2 deb-version 0+{revno}
                %(branch)s
                merge
                ''' % {
                    'branch': branch.bzr_identity,
                }),
            branch=branch)
        self.assertEqual(
            'Error parsing recipe:3:6: '
            'End of line while looking for the branch id.\n'
            'Usage: merge NAME BRANCH [REVISION]',
            get_feedback_messages(browser.contents)[1])

    def test_create_recipe_no_distroseries(self):
        browser = self.getViewBrowser(self.makeBranch(), '+new-recipe')
        browser.getControl(name='field.name').value = 'daily'
        browser.getControl('Description').value = 'Make some food!'
        browser.getControl(name='field.distroseries').value = []
        browser.getControl('Create Recipe').click()
        self.assertEqual(
            'You must specify at least one series for daily builds.',
            get_feedback_messages(browser.contents)[1])

    def test_create_recipe_bad_base_branch(self):
        # If a user tries to create source package recipe with a bad base
        # branch location, they should get an error.
        browser = self.createRecipe(MINIMAL_RECIPE_TEXT % 'foo')
        self.assertEqual(
            get_feedback_messages(browser.contents)[1],
            'foo is not a branch on Launchpad.')

    def test_create_recipe_bad_instruction_branch(self):
        # If a user tries to create source package recipe with a bad
        # instruction branch location, they should get an error.
        product = self.factory.makeProduct(
            name='ratatouille', displayname='Ratatouille')
        branch = self.factory.makeBranch(
            owner=self.chef, product=product, name='veggies')
        recipe = MINIMAL_RECIPE_TEXT % branch.bzr_identity
        recipe += 'nest packaging foo debian'
        browser = self.createRecipe(recipe, branch)
        self.assertEqual(
            get_feedback_messages(browser.contents)[1],
            'foo is not a branch on Launchpad.')

    def test_create_recipe_format_too_new(self):
        # If the recipe's format version is too new, we should notify the
        # user.
        product = self.factory.makeProduct(
            name='ratatouille', displayname='Ratatouille')
        branch = self.factory.makeBranch(
            owner=self.chef, product=product, name='veggies')

        with recipe_parser_newest_version(145.115):
            recipe = dedent(u'''\
              # bzr-builder format 145.115 deb-version {debupstream}-0~{revno}
              %s
              ''') % branch.bzr_identity
            browser = self.createRecipe(recipe, branch)
            self.assertEqual(
                get_feedback_messages(browser.contents)[1],
                'The recipe format version specified is not available.')

    def test_create_dupe_recipe(self):
        # You shouldn't be able to create a duplicate recipe owned by the same
        # person with the same name.
        recipe = self.factory.makeSourcePackageRecipe(owner=self.chef)
        transaction.commit()
        recipe_name = recipe.name

        product = self.factory.makeProduct(
            name='ratatouille', displayname='Ratatouille')
        branch = self.factory.makeBranch(
            owner=self.chef, product=product, name='veggies')

        # A new recipe can be created from the branch page.
        browser = self.getUserBrowser(canonical_url(branch), user=self.chef)
        browser.getLink('Create packaging recipe').click()

        browser.getControl(name='field.name').value = recipe_name
        browser.getControl('Description').value = 'Make some food!'
        browser.getControl('Secret Squirrel').click()
        browser.getControl('Create Recipe').click()

        self.assertEqual(
            get_feedback_messages(browser.contents)[1],
            'There is already a recipe owned by Master Chef with this name.')

    def test_create_recipe_private_branch(self):
        # If a user tries to create source package recipe with a private
        # base branch, they should get an error.
        branch = self.factory.makeAnyBranch(private=True, owner=self.user)
        with person_logged_in(self.user):
            bzr_identity = branch.bzr_identity
        recipe_text = MINIMAL_RECIPE_TEXT % bzr_identity
        browser = self.createRecipe(recipe_text)
        self.assertEqual(
            get_feedback_messages(browser.contents)[1],
            'Recipe may not refer to private branch: %s' % bzr_identity)

    def _test_new_recipe_with_no_related_branches(self, branch):
        # The Related Branches section should not appear if there are no
        # related branches.
        # A new recipe can be created from the branch page.
        browser = self.getUserBrowser(
            canonical_url(branch, view_name='+new-recipe'), user=self.chef)
        # There shouldn't be a related-branches section if there are no
        # related branches..
        soup = BeautifulSoup(browser.contents)
        related_branches = soup.find('fieldset', {'id': 'related-branches'})
        self.assertIs(related_branches, None)

    def test_new_product_branch_with_no_related_branches_recipe(self):
        # We can create a new recipe off a product branch.
        branch = self.factory.makeBranch()
        self._test_new_recipe_with_no_related_branches(branch)

    def test_new_package_branch_with_no_linked_branches_recipe(self):
        # We can create a new recipe off a sourcepackage branch where the
        # sourcepackage has no linked branches.
        branch = self.factory.makePackageBranch()
        self._test_new_recipe_with_no_related_branches(branch)

    def test_new_recipe_with_package_branches(self):
        # The series branches table should not appear if there are none.
        (branch, related_series_branch_info, related_package_branches) = (
            self.factory.makeRelatedBranches(with_series_branches=False))
        browser = self.getUserBrowser(
            canonical_url(branch, view_name='+new-recipe'), user=self.chef)
        soup = BeautifulSoup(browser.contents)
        related_branches = soup.find('fieldset', {'id': 'related-branches'})
        self.assertIsNot(related_branches, None)
        related_branches = soup.find(
            'div', {'id': 'related-package-branches'})
        self.assertIsNot(related_branches, None)
        related_branches = soup.find(
            'div', {'id': 'related-series-branches'})
        self.assertIs(related_branches, None)

    def test_new_recipe_with_series_branches(self):
        # The package branches table should not appear if there are none.
        (branch, related_series_branch_info, related_package_branches) = (
            self.factory.makeRelatedBranches(with_package_branches=False))
        browser = self.getUserBrowser(
            canonical_url(branch, view_name='+new-recipe'), user=self.chef)
        soup = BeautifulSoup(browser.contents)
        related_branches = soup.find('fieldset', {'id': 'related-branches'})
        self.assertIsNot(related_branches, None)
        related_branches = soup.find(
            'div', {'id': 'related-series-branches'})
        self.assertIsNot(related_branches, None)
        related_branches = soup.find(
            'div', {'id': 'related-package-branches'})
        self.assertIs(related_branches, None)

    def test_new_product_branch_recipe_with_related_branches(self):
        # The related branches should be rendered correctly on the page.
        (branch, related_series_branch_info,
            related_package_branch_info) = self.factory.makeRelatedBranches()
        browser = self.getUserBrowser(
            canonical_url(branch, view_name='+new-recipe'), user=self.chef)
        self.checkRelatedBranches(
            related_series_branch_info, related_package_branch_info,
            browser.contents)

    def test_new_sourcepackage_branch_recipe_with_related_branches(self):
        # The related branches should be rendered correctly on the page.
        reference_branch = self.factory.makePackageBranch()
        (branch, ignore, related_package_branch_info) = (
                self.factory.makeRelatedBranches(reference_branch))
        browser = self.getUserBrowser(
            canonical_url(branch, view_name='+new-recipe'), user=self.chef)
        self.checkRelatedBranches(
                set(), related_package_branch_info, browser.contents)

    def test_ppa_selector_not_shown_if_user_has_no_ppas(self):
        # If the user creating a recipe has no existing PPAs, the selector
        # isn't shown, but the field to enter a new PPA name is.
        self.user = self.factory.makePerson(password='test')
        branch = self.factory.makeAnyBranch()
        with person_logged_in(self.user):
            content = self.getMainContent(branch, '+new-recipe')
        ppa_name = content.find(attrs={'id': 'field.ppa_name'})
        self.assertEqual('input', ppa_name.name)
        self.assertEqual('text', ppa_name['type'])
        # The new ppa name field has an initial value.
        self.assertEqual('ppa', ppa_name['value'])
        ppa_chooser = content.find(attrs={'id': 'field.daily_build_archive'})
        self.assertIs(None, ppa_chooser)
        # There is a hidden option to say create a new ppa.
        ppa_options = content.find(attrs={'name': 'field.use_ppa'})
        self.assertEqual('input', ppa_options.name)
        self.assertEqual('hidden', ppa_options['type'])
        self.assertEqual('create-new', ppa_options['value'])

    def test_ppa_selector_shown_if_user_has_ppas(self):
        # If the user creating a recipe has existing PPAs, the selector is
        # shown, along with radio buttons to decide whether to use an existing
        # ppa or to create a new one.
        branch = self.factory.makeAnyBranch()
        with person_logged_in(self.user):
            content = self.getMainContent(branch, '+new-recipe')
        ppa_name = content.find(attrs={'id': 'field.ppa_name'})
        self.assertEqual('input', ppa_name.name)
        self.assertEqual('text', ppa_name['type'])
        # The new ppa name field has no initial value.
        self.assertEqual('', ppa_name['value'])
        ppa_chooser = content.find(attrs={'id': 'field.daily_build_archive'})
        self.assertEqual('select', ppa_chooser.name)
        ppa_options = list(
            get_radio_button_text_for_field(content, 'use_ppa'))
        self.assertEqual(
            ['(*) Use an existing PPA',
             '( ) Create a new PPA for this recipe'''],
            ppa_options)

    def test_create_new_ppa(self):
        # If the user doesn't have any PPAs, a new once can be created.
        self.user = self.factory.makePerson(name='eric', password='test')
        branch = self.factory.makeAnyBranch()

        # A new recipe can be created from the branch page.
        browser = self.getUserBrowser(canonical_url(branch), user=self.user)
        browser.getLink('Create packaging recipe').click()

        browser.getControl(name='field.name').value = 'name'
        browser.getControl('Description').value = 'Make some food!'
        browser.getControl('Secret Squirrel').click()
        browser.getControl('Create Recipe').click()

        # A new recipe is created in a new PPA.
        self.assertTrue(browser.url.endswith('/~eric/+recipe/name'))
        # Since no PPA name was entered, the default name (ppa) was used.
        login(ANONYMOUS)
        new_ppa = self.user.getPPAByName('ppa')
        self.assertIsNot(None, new_ppa)

    def test_create_new_ppa_duplicate(self):
        # If a new PPA is being created, and the user already has a ppa of the
        # name specifed an error is shown.
        self.user = self.factory.makePerson(name='eric', password='test')
        # Make a PPA called 'ppa' using the default.
        self.user.createPPA(name='foo')
        branch = self.factory.makeAnyBranch()

        # A new recipe can be created from the branch page.
        browser = self.getUserBrowser(canonical_url(branch), user=self.user)
        browser.getLink('Create packaging recipe').click()
        browser.getControl(name='field.name').value = 'name'
        browser.getControl('Description').value = 'Make some food!'
        browser.getControl('Secret Squirrel').click()
        browser.getControl('Create a new PPA').click()
        browser.getControl(name='field.ppa_name').value = 'foo'
        browser.getControl('Create Recipe').click()
        self.assertEqual(
            get_feedback_messages(browser.contents)[1],
            "You already have a PPA named 'foo'.")

    def test_create_new_ppa_missing_name(self):
        # If a new PPA is being created, and the user has not specified a
        # name, an error is shown.
        self.user = self.factory.makePerson(name='eric', password='test')
        branch = self.factory.makeAnyBranch()

        # A new recipe can be created from the branch page.
        browser = self.getUserBrowser(canonical_url(branch), user=self.user)
        browser.getLink('Create packaging recipe').click()
        browser.getControl(name='field.name').value = 'name'
        browser.getControl('Description').value = 'Make some food!'
        browser.getControl('Secret Squirrel').click()
        browser.getControl(name='field.ppa_name').value = ''
        browser.getControl('Create Recipe').click()
        self.assertEqual(
            get_feedback_messages(browser.contents)[1],
            "You need to specify a name for the PPA.")

    def test_create_new_ppa_owned_by_recipe_owner(self):
        # The new PPA that is created is owned by the recipe owner.
        self.user = self.factory.makePerson(name='eric', password='test')
        team = self.factory.makeTeam(
            name='vikings', members=[self.user],
            subscription_policy=TeamSubscriptionPolicy.MODERATED)
        branch = self.factory.makeAnyBranch(owner=team)

        # A new recipe can be created from the branch page.
        browser = self.getUserBrowser(canonical_url(branch), user=self.user)
        browser.getLink('Create packaging recipe').click()

        browser.getControl(name='field.name').value = 'name'
        browser.getControl('Description').value = 'Make some food!'
        browser.getControl(name='field.owner').value = ['vikings']
        browser.getControl('Secret Squirrel').click()
        browser.getControl('Create Recipe').click()

        # A new recipe is created in a new PPA.
        self.assertTrue(browser.url.endswith('/~vikings/+recipe/name'))
        # Since no PPA name was entered, the default name (ppa) was used.
        login(ANONYMOUS)
        new_ppa = team.getPPAByName('ppa')
        self.assertIsNot(None, new_ppa)


class TestSourcePackageRecipeEditView(TestCaseForRecipe):
    """Test the editing behaviour of a source package recipe."""

    layer = DatabaseFunctionalLayer

    def test_edit_recipe(self):
        self.factory.makeDistroSeries(
            displayname='Mumbly Midget', name='mumbly',
            distribution=self.ppa.distribution)
        product = self.factory.makeProduct(
            name='ratatouille', displayname='Ratatouille')
        veggie_branch = self.factory.makeBranch(
            owner=self.chef, product=product, name='veggies')
        meat_branch = self.factory.makeBranch(
            owner=self.chef, product=product, name='meat')
        recipe = self.factory.makeSourcePackageRecipe(
            owner=self.chef, registrant=self.chef,
            name=u'things', description=u'This is a recipe',
            distroseries=self.squirrel, branches=[veggie_branch],
            daily_build_archive=self.ppa)
        self.factory.makeArchive(
            distribution=self.ppa.distribution, name='ppa2',
            displayname="PPA 2", owner=self.chef)

        meat_path = meat_branch.bzr_identity

        browser = self.getUserBrowser(canonical_url(recipe), user=self.chef)
        browser.getLink('Edit recipe').click()
        browser.getControl(name='field.name').value = 'fings'
        browser.getControl('Description').value = 'This is stuff'
        browser.getControl('Recipe text').value = (
            MINIMAL_RECIPE_TEXT % meat_path)
        browser.getControl('Secret Squirrel').click()
        browser.getControl('Mumbly Midget').click()
        browser.getControl('PPA 2').click()
        browser.getControl('Update Recipe').click()

        content = find_main_content(browser.contents)
        self.assertThat(
            'This is stuff', MatchesTagText(content, 'edit-description'))
        self.assertThat(
            '# bzr-builder format 0.3 deb-version {debupstream}-0~{revno}\n'
            'lp://dev/~chef/ratatouille/meat',
            MatchesTagText(content, 'edit-recipe_text'))
        self.assertThat(
            'Distribution series: Edit Mumbly Midget',
            MatchesTagText(content, 'distroseries'))
        self.assertThat(
            'PPA 2', MatchesPickerText(content, 'edit-daily_build_archive'))

    def test_edit_recipe_sets_date_last_modified(self):
        """Editing a recipe sets the date_last_modified property."""
        date_created = datetime(2000, 1, 1, 12, tzinfo=UTC)
        recipe = self.factory.makeSourcePackageRecipe(
            owner=self.chef, date_created=date_created)

        login_person(self.chef)
        view = SourcePackageRecipeEditView(recipe, LaunchpadTestRequest())
        view.initialize()
        view.request_action.success({
            'name': u'fings',
            'recipe_text': recipe.recipe_text,
            'distroseries': recipe.distroseries})
        self.assertSqlAttributeEqualsDate(
            recipe, 'date_last_modified', UTC_NOW)

    def test_admin_edit(self):
        self.factory.makeDistroSeries(
            displayname='Mumbly Midget', name='mumbly',
            distribution=self.ppa.distribution)
        product = self.factory.makeProduct(
            name='ratatouille', displayname='Ratatouille')
        veggie_branch = self.factory.makeBranch(
            owner=self.chef, product=product, name='veggies')
        meat_branch = self.factory.makeBranch(
            owner=self.chef, product=product, name='meat')
        recipe = self.factory.makeSourcePackageRecipe(
            owner=self.chef, registrant=self.chef,
            name=u'things', description=u'This is a recipe',
            distroseries=self.squirrel, branches=[veggie_branch],
            daily_build_archive=self.ppa)

        meat_path = meat_branch.bzr_identity
        expert = getUtility(ILaunchpadCelebrities).admin.teamowner

        browser = self.getUserBrowser(canonical_url(recipe), user=expert)
        browser.getLink('Edit recipe').click()

        # There shouldn't be a daily build archive property.
        self.assertRaises(
            LookupError,
            browser.getControl,
            name='field.daily_build_archive')

        browser.getControl(name='field.name').value = 'fings'
        browser.getControl('Description').value = 'This is stuff'
        browser.getControl('Recipe text').value = (
            MINIMAL_RECIPE_TEXT % meat_path)
        browser.getControl('Secret Squirrel').click()
        browser.getControl('Mumbly Midget').click()
        browser.getControl('Update Recipe').click()

        content = find_main_content(browser.contents)
        self.assertEqual('fings', extract_text(content.h1))
        self.assertThat(
            'This is stuff', MatchesTagText(content, 'edit-description'))
        self.assertThat(
            '# bzr-builder format 0.3 deb-version {debupstream}-0~{revno}\n'
            'lp://dev/~chef/ratatouille/meat',
            MatchesTagText(content, 'edit-recipe_text'))
        self.assertThat(
            'Distribution series: Edit Mumbly Midget',
            MatchesTagText(content, 'distroseries'))

    def test_edit_recipe_forbidden_instruction(self):
        self.factory.makeDistroSeries(
            displayname='Mumbly Midget', name='mumbly',
            distribution=self.ppa.distribution)
        product = self.factory.makeProduct(
            name='ratatouille', displayname='Ratatouille')
        veggie_branch = self.factory.makeBranch(
            owner=self.chef, product=product, name='veggies')
        recipe = self.factory.makeSourcePackageRecipe(
            owner=self.chef, registrant=self.chef,
            name=u'things', description=u'This is a recipe',
            distroseries=self.squirrel, branches=[veggie_branch])

        browser = self.getUserBrowser(canonical_url(recipe), user=self.chef)
        browser.getLink('Edit recipe').click()
        browser.getControl('Recipe text').value = (
            browser.getControl('Recipe text').value + 'run cat /etc/passwd')
        browser.getControl('Update Recipe').click()

        self.assertEqual(
            get_feedback_messages(browser.contents)[1],
            'The bzr-builder instruction "run" is not permitted here.')

    def test_edit_recipe_format_too_new(self):
        # If the recipe's format version is too new, we should notify the
        # user.
        self.factory.makeDistroSeries(
            displayname='Mumbly Midget', name='mumbly',
            distribution=self.ppa.distribution)
        product = self.factory.makeProduct(
            name='ratatouille', displayname='Ratatouille')
        veggie_branch = self.factory.makeBranch(
            owner=self.chef, product=product, name='veggies')
        recipe = self.factory.makeSourcePackageRecipe(
            owner=self.chef, registrant=self.chef,
            name=u'things', description=u'This is a recipe',
            distroseries=self.squirrel, branches=[veggie_branch])

        new_recipe_text = dedent(u'''\
            # bzr-builder format 145.115 deb-version {debupstream}-0~{revno}
            %s
            ''') % recipe.base_branch.bzr_identity

        with recipe_parser_newest_version(145.115):
            browser = self.getViewBrowser(recipe)
            browser.getLink('Edit recipe').click()
            browser.getControl('Recipe text').value = new_recipe_text
            browser.getControl('Update Recipe').click()

            self.assertEqual(
                get_feedback_messages(browser.contents)[1],
                'The recipe format version specified is not available.')

    def test_edit_recipe_already_exists(self):
        self.factory.makeDistroSeries(
            displayname='Mumbly Midget', name='mumbly',
            distribution=self.ppa.distribution)
        product = self.factory.makeProduct(
            name='ratatouille', displayname='Ratatouille')
        veggie_branch = self.factory.makeBranch(
            owner=self.chef, product=product, name='veggies')
        meat_branch = self.factory.makeBranch(
            owner=self.chef, product=product, name='meat')
        recipe = self.factory.makeSourcePackageRecipe(
            owner=self.chef, registrant=self.chef,
            name=u'things', description=u'This is a recipe',
            distroseries=self.squirrel, branches=[veggie_branch])
        self.factory.makeSourcePackageRecipe(
            owner=self.chef, registrant=self.chef,
            name=u'fings', description=u'This is a recipe',
            distroseries=self.squirrel, branches=[veggie_branch])

        meat_path = meat_branch.bzr_identity

        browser = self.getUserBrowser(canonical_url(recipe), user=self.chef)
        browser.getLink('Edit recipe').click()
        browser.getControl(name='field.name').value = 'fings'
        browser.getControl('Description').value = 'This is stuff'
        browser.getControl('Recipe text').value = (
            MINIMAL_RECIPE_TEXT % meat_path)
        browser.getControl('Secret Squirrel').click()
        browser.getControl('Mumbly Midget').click()
        browser.getControl('Update Recipe').click()

        self.assertEqual(
            extract_text(find_tags_by_class(browser.contents, 'message')[1]),
            'There is already a recipe owned by Master Chef with this name.')

    def test_edit_recipe_private_branch(self):
        # If a user tries to set source package recipe to use a private
        # branch, they should get an error.
        recipe = self.factory.makeSourcePackageRecipe(owner=self.user)
        branch = self.factory.makeAnyBranch(private=True, owner=self.user)
        with person_logged_in(self.user):
            bzr_identity = branch.bzr_identity
        recipe_text = MINIMAL_RECIPE_TEXT % bzr_identity
        browser = self.getViewBrowser(recipe, '+edit')
        browser.getControl('Recipe text').value = recipe_text
        browser.getControl('Update Recipe').click()
        self.assertEqual(
            get_feedback_messages(browser.contents)[1],
            'Recipe may not refer to private branch: %s' % bzr_identity)

    def test_edit_recipe_no_branch(self):
        # If a user tries to set a source package recipe to use a branch
        # that isn't registred, they will get an error.
        recipe = self.factory.makeSourcePackageRecipe(owner=self.user)
        no_branch_recipe_text = recipe.recipe_text[:-4]
        expected_name = recipe.base_branch.unique_name[:-3]
        browser = self.getViewBrowser(recipe, '+edit')
        browser.getControl('Recipe text').value = no_branch_recipe_text
        browser.getControl('Update Recipe').click()
        self.assertEqual(
            get_feedback_messages(browser.contents)[1],
            'lp://dev/%s is not a branch on Launchpad.' % expected_name)

    def _test_edit_recipe_with_no_related_branches(self, recipe):
        # The Related Branches section should not appear if there are no
        # related branches.
        browser = self.getUserBrowser(canonical_url(recipe), user=self.chef)
        browser.getLink('Edit recipe').click()
        # There shouldn't be a related-branches section if there are no
        # related branches.
        soup = BeautifulSoup(browser.contents)
        related_branches = soup.find('fieldset', {'id': 'related-branches'})
        self.assertIs(related_branches, None)

    def test_edit_product_branch_with_no_related_branches_recipe(self):
        # The Related Branches section should not appear if there are no
        # related branches.
        base_branch = self.factory.makeBranch()
        recipe = self.factory.makeSourcePackageRecipe(
                owner=self.chef, branches=[base_branch])
        self._test_edit_recipe_with_no_related_branches(recipe)

    def test_edit_sourcepackage_branch_with_no_related_branches_recipe(self):
        # The Related Branches section should not appear if there are no
        # related branches.
        base_branch = self.factory.makePackageBranch()
        recipe = self.factory.makeSourcePackageRecipe(
                owner=self.chef, branches=[base_branch])
        self._test_edit_recipe_with_no_related_branches(recipe)

    def test_edit_recipe_with_package_branches(self):
        # The series branches table should not appear if there are none.
        with person_logged_in(self.chef):
            recipe = self.factory.makeSourcePackageRecipe(owner=self.chef)
            self.factory.makeRelatedBranches(
                    reference_branch=recipe.base_branch,
                    with_series_branches=False)
        browser = self.getUserBrowser(canonical_url(recipe), user=self.chef)
        browser.getLink('Edit recipe').click()
        soup = BeautifulSoup(browser.contents)
        related_branches = soup.find('fieldset', {'id': 'related-branches'})
        self.assertIsNot(related_branches, None)
        related_branches = soup.find(
            'div', {'id': 'related-package-branches'})
        self.assertIsNot(related_branches, None)
        related_branches = soup.find(
            'div', {'id': 'related-series-branches'})
        self.assertIs(related_branches, None)

    def test_edit_recipe_with_series_branches(self):
        # The package branches table should not appear if there are none.
        with person_logged_in(self.chef):
            recipe = self.factory.makeSourcePackageRecipe(owner=self.chef)
            self.factory.makeRelatedBranches(
                    reference_branch=recipe.base_branch,
                    with_package_branches=False)
        browser = self.getUserBrowser(canonical_url(recipe), user=self.chef)
        browser.getLink('Edit recipe').click()
        soup = BeautifulSoup(browser.contents)
        related_branches = soup.find('fieldset', {'id': 'related-branches'})
        self.assertIsNot(related_branches, None)
        related_branches = soup.find(
            'div', {'id': 'related-series-branches'})
        self.assertIsNot(related_branches, None)
        related_branches = soup.find(
            'div', {'id': 'related-package-branches'})
        self.assertIs(related_branches, None)

    def test_edit_product_branch_recipe_with_related_branches(self):
        # The related branches should be rendered correctly on the page.
        with person_logged_in(self.chef):
            recipe = self.factory.makeSourcePackageRecipe(owner=self.chef)
            (branch, related_series_branch_info,
                related_package_branch_info) = (
                    self.factory.makeRelatedBranches(
                    reference_branch=recipe.base_branch))
        browser = self.getUserBrowser(
            canonical_url(recipe, view_name='+edit'), user=self.chef)
        self.checkRelatedBranches(
            related_series_branch_info, related_package_branch_info,
            browser.contents)

    def test_edit_sourcepackage_branch_recipe_with_related_branches(self):
        # The related branches should be rendered correctly on the page.
        with person_logged_in(self.chef):
            reference_branch = self.factory.makePackageBranch()
            recipe = self.factory.makeSourcePackageRecipe(
                    owner=self.chef, branches=[reference_branch])
            (branch, ignore, related_package_branch_info) = (
                    self.factory.makeRelatedBranches(reference_branch))
            browser = self.getUserBrowser(
                canonical_url(recipe, view_name='+edit'), user=self.chef)
            self.checkRelatedBranches(
                    set(), related_package_branch_info, browser.contents)


class TestSourcePackageRecipeView(TestCaseForRecipe):

    layer = LaunchpadFunctionalLayer

    def test_index(self):
        recipe = self.makeRecipe()
        build = removeSecurityProxy(self.factory.makeSourcePackageRecipeBuild(
            recipe=recipe, distroseries=self.squirrel, archive=self.ppa))
        build.status = BuildStatus.FULLYBUILT
        build.date_started = datetime(2010, 03, 16, tzinfo=UTC)
        build.date_finished = datetime(2010, 03, 16, tzinfo=UTC)

        self.assertTextMatchesExpressionIgnoreWhitespace("""\
            Master Chef Recipes cake_recipe
            .*
            Description
            This recipe .*changes.

            Recipe information
            Build schedule: Tag help Built on request
            Owner: Master Chef Edit
            Base branch: lp://dev/~chef/chocolate/cake
            Debian version: {debupstream}-0~{revno}
            Daily build archive: Secret PPA Edit
            Distribution series: Edit Secret Squirrel

            Latest builds
            Status When complete Distribution series Archive
            Successful build on 2010-03-16 Secret Squirrel Secret PPA
            Request build\(s\)

            Recipe contents
            # bzr-builder format 0.3 deb-version {debupstream}-0~{revno}
            lp://dev/~chef/chocolate/cake""", self.getMainText(recipe))

    def test_index_success_with_buildlog(self):
        # The buildlog is shown if it is there.
        recipe = self.makeRecipe()
        build = removeSecurityProxy(self.factory.makeSourcePackageRecipeBuild(
            recipe=recipe, distroseries=self.squirrel, archive=self.ppa))
        build.status = BuildStatus.FULLYBUILT
        build.date_started = datetime(2010, 03, 16, tzinfo=UTC)
        build.date_finished = datetime(2010, 03, 16, tzinfo=UTC)
        build.log = self.factory.makeLibraryFileAlias()

        self.assertTextMatchesExpressionIgnoreWhitespace("""\
            Latest builds
            Status .* Archive
            Successful build on 2010-03-16 buildlog \(.*\)
                Secret Squirrel Secret PPA
            Request build\(s\)""", self.getMainText(recipe))

    def test_index_success_with_binary_builds(self):
        # Binary builds are shown after the recipe builds if there are any.
        recipe = self.makeRecipe()
        build = removeSecurityProxy(self.factory.makeSourcePackageRecipeBuild(
            recipe=recipe, distroseries=self.squirrel, archive=self.ppa))
        build.status = BuildStatus.FULLYBUILT
        build.date_started = datetime(2010, 03, 16, tzinfo=UTC)
        build.date_finished = datetime(2010, 03, 16, tzinfo=UTC)
        build.log = self.factory.makeLibraryFileAlias()
        package_name = self.factory.getOrMakeSourcePackageName('chocolate')
        source_package_release = self.factory.makeSourcePackageRelease(
            archive=self.ppa, sourcepackagename=package_name,
            distroseries=self.squirrel, source_package_recipe_build=build,
            version='0+r42')
        self.factory.makeSourcePackagePublishingHistory(
            sourcepackagerelease=source_package_release, archive=self.ppa,
            distroseries=self.squirrel)
        builder = self.factory.makeBuilder()
        binary_build = self.factory.makeBinaryPackageBuild(
            source_package_release=source_package_release,
            distroarchseries=self.squirrel.nominatedarchindep,
            processor=builder.processor)
        binary_build.queueBuild()

        self.assertTextMatchesExpressionIgnoreWhitespace("""\
            Latest builds
            Status .* Archive
            Successful build on 2010-03-16 buildlog \(.*\)
               Secret Squirrel Secret PPA chocolate - 0\+r42 in .*
               \(estimated\) i386
            Request build\(s\)""", self.getMainText(recipe))

    def test_index_success_with_completed_binary_build(self):
        # Binary builds show their buildlog too.
        recipe = self.makeRecipe()
        build = removeSecurityProxy(self.factory.makeSourcePackageRecipeBuild(
            recipe=recipe, distroseries=self.squirrel, archive=self.ppa))
        build.status = BuildStatus.FULLYBUILT
        build.date_started = datetime(2010, 03, 16, tzinfo=UTC)
        build.date_finished = datetime(2010, 03, 16, tzinfo=UTC)
        build.log = self.factory.makeLibraryFileAlias()
        package_name = self.factory.getOrMakeSourcePackageName('chocolate')
        source_package_release = self.factory.makeSourcePackageRelease(
            archive=self.ppa, sourcepackagename=package_name,
            distroseries=self.squirrel, source_package_recipe_build=build,
            version='0+r42')
        self.factory.makeSourcePackagePublishingHistory(
            sourcepackagerelease=source_package_release, archive=self.ppa,
            distroseries=self.squirrel)
        builder = self.factory.makeBuilder()
        binary_build = removeSecurityProxy(
            self.factory.makeBinaryPackageBuild(
                source_package_release=source_package_release,
                distroarchseries=self.squirrel.nominatedarchindep,
                processor=builder.processor))
        binary_build.queueBuild()
        binary_build.status = BuildStatus.FULLYBUILT
        binary_build.date_started = datetime(2010, 04, 16, tzinfo=UTC)
        binary_build.date_finished = datetime(2010, 04, 16, tzinfo=UTC)
        binary_build.log = self.factory.makeLibraryFileAlias()

        self.assertTextMatchesExpressionIgnoreWhitespace("""\
            Latest builds
            Status .* Archive
            Successful build on 2010-03-16 buildlog \(.*\) Secret Squirrel
              Secret PPA chocolate - 0\+r42 on 2010-04-16 buildlog \(.*\) i386
            Request build\(s\)""", self.getMainText(recipe))

    def test_index_success_with_sprb_into_private_ppa(self):
        # The index page hides builds into archives the user can't view.
        recipe = self.makeRecipe()
        archive = self.factory.makeArchive(private=True)
        sprb = removeSecurityProxy(
            self.factory.makeSourcePackageRecipeBuild(
                recipe=recipe, distroseries=self.squirrel, archive=archive))
        sprb.status = BuildStatus.FULLYBUILT
        sprb.date_started = datetime(2010, 04, 16, tzinfo=UTC)
        sprb.date_finished = datetime(2010, 04, 16, tzinfo=UTC)
        sprb.log = self.factory.makeLibraryFileAlias()
        self.assertIn(
            "This recipe has not been built yet.", self.getMainText(recipe))

    def test_index_no_builds(self):
        """A message should be shown when there are no builds."""
        recipe = self.makeRecipe()
        self.assertTextMatchesExpressionIgnoreWhitespace("""\
            Latest builds
            Status .* Archive
            This recipe has not been built yet.""", self.getMainText(recipe))

    def test_index_no_suitable_builders(self):
        recipe = self.makeRecipe()
        removeSecurityProxy(self.factory.makeSourcePackageRecipeBuild(
            recipe=recipe, distroseries=self.squirrel, archive=self.ppa))
        self.assertTextMatchesExpressionIgnoreWhitespace("""
            Latest builds
            Status .* Archive
            No suitable builders Secret Squirrel Secret PPA
            Request build\(s\)""", self.getMainText(recipe))

    def makeBuildJob(self, recipe, date_created=None):
        """Return a build associated with a buildjob."""
        build = self.factory.makeSourcePackageRecipeBuild(
            recipe=recipe, distroseries=self.squirrel, archive=self.ppa,
            date_created=date_created)
        self.factory.makeSourcePackageRecipeBuildJob(recipe_build=build)
        return build

    def test_index_pending(self):
        """Test the listing of a pending build."""
        recipe = self.makeRecipe()
        self.makeBuildJob(recipe)
        self.factory.makeBuilder()
        pattern = """\
            Latest builds
            Status .* Archive
            Pending build in .* \(estimated\) Secret Squirrel Secret PPA
            Request build\(s\)

            Recipe contents"""
        main_text = self.getMainText(recipe)
        self.assertTextMatchesExpressionIgnoreWhitespace(
            pattern, main_text)

    def test_builds(self):
        """Ensure SourcePackageRecipeView.builds is as described."""
        recipe = self.makeRecipe()
        # We create builds in time ascending order (oldest first) since we
        # use id as the ordering attribute and lower ids mean created earlier.
        date_gen = time_counter(
            datetime(2010, 03, 16, tzinfo=UTC), timedelta(days=1))
        build1 = self.makeBuildJob(recipe, date_gen.next())
        build2 = self.makeBuildJob(recipe, date_gen.next())
        build3 = self.makeBuildJob(recipe, date_gen.next())
        build4 = self.makeBuildJob(recipe, date_gen.next())
        build5 = self.makeBuildJob(recipe, date_gen.next())
        build6 = self.makeBuildJob(recipe, date_gen.next())
        view = SourcePackageRecipeView(recipe, None)
        self.assertEqual(
            [build6, build5, build4, build3, build2, build1],
            view.builds)

        def set_status(build, status):
            naked_build = removeSecurityProxy(build)
            naked_build.status = status
            naked_build.date_started = naked_build.date_created
            if status == BuildStatus.FULLYBUILT:
                naked_build.date_finished = (
                    naked_build.date_created + timedelta(minutes=10))
        set_status(build6, BuildStatus.FULLYBUILT)
        set_status(build5, BuildStatus.FAILEDTOBUILD)
        # When there are 4+ pending builds, only the the most
        # recently-completed build is returned (i.e. build1, not build2)
        self.assertEqual(
            [build4, build3, build2, build1, build6],
            view.builds)
        set_status(build4, BuildStatus.FULLYBUILT)
        set_status(build3, BuildStatus.FULLYBUILT)
        set_status(build2, BuildStatus.FULLYBUILT)
        set_status(build1, BuildStatus.FULLYBUILT)
        self.assertEqual(
            [build6, build5, build4, build3, build2], view.builds)

    def test_request_daily_builds_button_stale(self):
        # Recipes that are stale and are built daily have a build now link
        recipe = self.factory.makeSourcePackageRecipe(
            owner=self.chef, daily_build_archive=self.ppa,
            is_stale=True, build_daily=True)
        browser = self.getViewBrowser(recipe)
        build_button = find_tag_by_id(browser.contents, 'field.actions.build')
        self.assertIsNot(None, build_button)

    def test_request_daily_builds_button_not_stale(self):
        # Recipes that are not stale do not have a build now link
        login(ANONYMOUS)
        recipe = self.factory.makeSourcePackageRecipe(
            owner=self.chef, daily_build_archive=self.ppa,
            is_stale=False, build_daily=True)
        browser = self.getViewBrowser(recipe)
        build_button = find_tag_by_id(browser.contents, 'field.actions.build')
        self.assertIs(None, build_button)

    def test_request_daily_builds_button_not_daily(self):
        # Recipes that are not built daily do not have a build now link
        login(ANONYMOUS)
        recipe = self.factory.makeSourcePackageRecipe(
            owner=self.chef, daily_build_archive=self.ppa,
            is_stale=True, build_daily=False)
        browser = self.getViewBrowser(recipe)
        build_button = find_tag_by_id(browser.contents, 'field.actions.build')
        self.assertIs(None, build_button)

    def test_request_daily_builds_button_no_daily_ppa(self):
        # Recipes that have no daily build ppa do not have a build now link
        login(ANONYMOUS)
        recipe = self.factory.makeSourcePackageRecipe(
            owner=self.chef, is_stale=True, build_daily=True)
        naked_recipe = removeSecurityProxy(recipe)
        naked_recipe.daily_build_archive = None
        browser = self.getViewBrowser(recipe)
        build_button = find_tag_by_id(browser.contents, 'field.actions.build')
        self.assertIs(None, build_button)

    def test_request_daily_builds_button_no_recipe_permission(self):
        # Recipes do not have a build now link if the user does not have edit
        # permission on the recipe.
        login(ANONYMOUS)
        recipe = self.factory.makeSourcePackageRecipe(
            owner=self.chef, is_stale=True, build_daily=True)
        person = self.factory.makePerson()
        browser = self.getViewBrowser(recipe, user=person)
        build_button = find_tag_by_id(browser.contents, 'field.actions.build')
        self.assertIs(None, build_button)

    def test_request_daily_builds_button_ppa_with_no_permissions(self):
        # Recipes that have a daily build ppa without upload permissions
        # do not have a build now link
        login(ANONYMOUS)
        distroseries = self.factory.makeSourcePackageRecipeDistroseries()
        person = self.factory.makePerson()
        daily_build_archive = self.factory.makeArchive(
                distribution=distroseries.distribution, owner=person)
        recipe = self.factory.makeSourcePackageRecipe(
            owner=self.chef, daily_build_archive=daily_build_archive,
            is_stale=True, build_daily=True)
        browser = self.getViewBrowser(recipe)
        build_button = find_tag_by_id(browser.contents, 'field.actions.build')
        self.assertIs(None, build_button)

    def test_request_daily_builds_button_ppa_disabled(self):
        # Recipes whose daily build ppa is disabled do not have a build now
        # link.
        distroseries = self.factory.makeSourcePackageRecipeDistroseries()
        daily_build_archive = self.factory.makeArchive(
                distribution=distroseries.distribution, owner=self.user)
        with person_logged_in(self.user):
            daily_build_archive.disable()
        recipe = self.factory.makeSourcePackageRecipe(
            owner=self.chef, daily_build_archive=daily_build_archive,
            is_stale=True, build_daily=True)
        browser = self.getViewBrowser(recipe)
        build_button = find_tag_by_id(browser.contents, 'field.actions.build')
        self.assertIs(None, build_button)

    def test_request_daily_builds_ajax_link_not_rendered(self):
        # The Build now link should not be rendered without javascript.
        recipe = self.factory.makeSourcePackageRecipe(
            owner=self.chef, daily_build_archive=self.ppa,
            is_stale=True, build_daily=True)
        browser = self.getViewBrowser(recipe)
        build_link = find_tag_by_id(browser.contents, 'request-daily-builds')
        self.assertIs(None, build_link)

    def test_request_daily_builds_action(self):
        # Daily builds should be triggered when requested.
        recipe = self.factory.makeSourcePackageRecipe(
            owner=self.chef, daily_build_archive=self.ppa,
            is_stale=True, build_daily=True)
        browser = self.getViewBrowser(recipe)
        browser.getControl('Build now').click()
        login(ANONYMOUS)
        builds = recipe.pending_builds
        build_distros = [
            build.distroseries.displayname for build in builds]
        build_distros.sort()
        # Our recipe has a Warty distroseries
        self.assertEqual(['Warty'], build_distros)
        self.assertEqual(
            set([2505]),
            set(build.buildqueue_record.lastscore for build in builds))

    def test_request_daily_builds_action_over_quota(self):
        recipe = self.factory.makeSourcePackageRecipe(
            owner=self.chef, daily_build_archive=self.ppa,
            name=u'julia', is_stale=True, build_daily=True)
        # Create some previous builds.
        series = list(recipe.distroseries)[0]
        for x in xrange(5):
            build = recipe.requestBuild(
                self.ppa, self.chef, series, PackagePublishingPocket.RELEASE)
            removeSecurityProxy(build).status = BuildStatus.FULLYBUILT
        harness = LaunchpadFormHarness(
            recipe, SourcePackageRecipeRequestDailyBuildView)
        harness.submit('build', {})
        self.assertEqual(
            "You have exceeded your quota for recipe chef/julia "
            "for distroseries ubuntu warty",
            harness.view.request.notifications[0].message)

    def test_request_daily_builds_disabled_archive(self):
        # Requesting a daily build from a disabled archive is a user error.
        recipe = self.factory.makeSourcePackageRecipe(
            owner=self.chef, daily_build_archive=self.ppa,
            name=u'julia', is_stale=True, build_daily=True)
        harness = LaunchpadFormHarness(
            recipe, SourcePackageRecipeRequestDailyBuildView)
        with person_logged_in(self.ppa.owner):
            self.ppa.disable()
        harness.submit('build', {})
        self.assertEqual(
            "Secret PPA is disabled.",
            harness.view.request.notifications[0].message)

    def test_request_builds_page(self):
        """Ensure the +request-builds page is sane."""
        recipe = self.makeRecipe()
        pattern = dedent("""\
            Request builds for cake_recipe
            Master Chef
            Recipes
            cake_recipe
            Request builds for cake_recipe
            Archive:
            Secret PPA
            Distribution series:
            Secret Squirrel
            Hoary
            Warty
            or
            Cancel""")
        main_text = self.getMainText(recipe, '+request-builds')
        self.assertEqual(pattern, main_text)

    def test_request_builds_action(self):
        """Requesting a build creates pending builds."""
        woody = self.factory.makeDistroSeries(
            name='woody', displayname='Woody',
            distribution=self.ppa.distribution)
        naked_woody = remove_security_proxy_and_shout_at_engineer(woody)
        naked_woody.nominatedarchindep = woody.newArch(
            'i386', ProcessorFamily.get(1), False, self.factory.makePerson(),
            supports_virtualized=True)

        recipe = self.makeRecipe()
        browser = self.getViewBrowser(recipe, '+request-builds')
        browser.getControl('Woody').click()
        browser.getControl('Request builds').click()

        login(ANONYMOUS)
        builds = recipe.pending_builds
        build_distros = [
            build.distroseries.displayname for build in builds]
        build_distros.sort()
        # Secret Squirrel is checked by default.
        self.assertEqual(['Secret Squirrel', 'Woody'], build_distros)
        self.assertEqual(
            set([2605]),
            set(build.buildqueue_record.lastscore for build in builds))

    def test_request_builds_action_not_logged_in(self):
        """Requesting a build creates pending builds."""
        woody = self.factory.makeDistroSeries(
            name='woody', displayname='Woody',
            distribution=self.ppa.distribution)
        naked_woody = removeSecurityProxy(woody)
        naked_woody.nominatedarchindep = woody.newArch(
            'i386', ProcessorFamily.get(1), False, self.factory.makePerson(),
            supports_virtualized=True)
        recipe = self.makeRecipe()

        browser = self.getViewBrowser(recipe, no_login=True)
        self.assertRaises(
            Unauthorized, browser.getLink('Request build(s)').click)

    def test_request_builds_archive(self):
        recipe = self.factory.makeSourcePackageRecipe()
        ppa2 = self.factory.makeArchive(
            displayname='Secret PPA', owner=self.chef, name='ppa2')
        view = SourcePackageRecipeRequestBuildsView(recipe, None)
        self.assertIs(None, view.initial_values.get('archive'))
        self.factory.makeSourcePackageRecipeBuild(recipe=recipe, archive=ppa2)
        self.assertEqual(ppa2, view.initial_values.get('archive'))

    def test_request_build_rejects_over_quota(self):
        """Over-quota build requests cause validation failures."""
        woody = self.factory.makeDistroSeries(
            name='woody', displayname='Woody',
            distribution=self.ppa.distribution)
        naked_woody = remove_security_proxy_and_shout_at_engineer(woody)
        naked_woody.nominatedarchindep = woody.newArch(
            'i386', ProcessorFamily.get(1), False, self.factory.makePerson(),
            supports_virtualized=True)

        recipe = self.makeRecipe()
        for x in range(5):
            build = recipe.requestBuild(
                self.ppa, self.chef, woody, PackagePublishingPocket.RELEASE)
            removeSecurityProxy(build).status = BuildStatus.FULLYBUILT

        browser = self.getViewBrowser(recipe, '+request-builds')
        browser.getControl('Woody').click()
        browser.getControl('Request builds').click()
        self.assertIn("You have exceeded today's quota for ubuntu woody.",
                extract_text(find_main_content(browser.contents)))

    def test_request_builds_rejects_duplicate(self):
        """Over-quota build requests cause validation failures."""
        woody = self.factory.makeDistroSeries(
            name='woody', displayname='Woody',
            distribution=self.ppa.distribution)
        naked_woody = remove_security_proxy_and_shout_at_engineer(woody)
        naked_woody.nominatedarchindep = woody.newArch(
            'i386', ProcessorFamily.get(1), False, self.factory.makePerson(),
            supports_virtualized=True)

        recipe = self.makeRecipe()
        recipe.requestBuild(
            self.ppa, self.chef, woody, PackagePublishingPocket.RELEASE)

        browser = self.getViewBrowser(recipe, '+request-builds')
        browser.getControl('Woody').click()
        browser.getControl('Request builds').click()
        self.assertIn(
            "An identical build is already pending for ubuntu woody.",
            extract_text(find_main_content(browser.contents)))

    def makeRecipeWithUploadIssues(self):
        """Make a recipe where the owner can't upload to the PPA."""
        # This occurs when the PPA that the recipe is being built daily into
        # is owned by a team, and the owner of the recipe isn't in the team
        # that owns the PPA.
        registrant = self.factory.makePerson()
        owner_team = self.factory.makeTeam(members=[registrant], name='team1')
        ppa_team = self.factory.makeTeam(members=[registrant], name='team2')
        ppa = self.factory.makeArchive(owner=ppa_team, name='ppa')
        return self.factory.makeSourcePackageRecipe(
            registrant=registrant, owner=owner_team, daily_build_archive=ppa,
            build_daily=True)

    def test_owner_with_no_ppa_upload_permission(self):
        # Daily build with upload issues are a problem.
        recipe = self.makeRecipeWithUploadIssues()
        view = create_initialized_view(recipe, '+index')
        self.assertTrue(view.dailyBuildWithoutUploadPermission())

    def test_owner_with_no_ppa_upload_permission_non_daily(self):
        # Non-daily builds with upload issues are not so much of an issue.
        recipe = self.makeRecipeWithUploadIssues()
        with person_logged_in(recipe.registrant):
            recipe.build_daily = False
        view = create_initialized_view(recipe, '+index')
        self.assertFalse(view.dailyBuildWithoutUploadPermission())

    def test_owner_with_no_ppa_upload_permission_message(self):
        # If there is an issue, a message is shown.
        recipe = self.makeRecipeWithUploadIssues()
        browser = self.getViewBrowser(recipe, '+index')
        messages = get_feedback_messages(browser.contents)
        self.assertEqual(
            "Daily builds for this recipe will not occur.\n"
            "The owner of the recipe (Team1) does not have permission to "
            "upload packages into the daily build PPA (PPA for Team2)",
            messages[-1])

    def test_view_with_disabled_archive(self):
        # When a PPA is disabled, it is only viewable to the owner. This
        # case is handled with the view not showing builds into a disabled
        # archive, rather than giving an Unauthorized error to the user.
        recipe = self.factory.makeSourcePackageRecipe(build_daily=True)
        recipe.requestBuild(
            recipe.daily_build_archive, recipe.owner, self.squirrel,
            PackagePublishingPocket.RELEASE)
        with person_logged_in(recipe.owner):
            recipe.daily_build_archive.disable()
        browser = self.getUserBrowser(canonical_url(recipe))
        self.assertIn(
            "This recipe has not been built yet.",
            extract_text(find_main_content(browser.contents)))


class TestSourcePackageRecipeBuildView(BrowserTestCase):
    """Test behaviour of SourcePackageRecipeBuildView."""

    layer = LaunchpadFunctionalLayer

    def setUp(self):
        """Provide useful defaults."""
        super(TestSourcePackageRecipeBuildView, self).setUp()
        self.user = self.factory.makePerson(
            displayname='Owner', name='build-owner', password='test')

    def makeBuild(self):
        """Make a build suitabe for testing."""
        archive = self.factory.makeArchive(name='build',
            owner=self.user)
        recipe = self.factory.makeSourcePackageRecipe(
            owner=self.user, name=u'my-recipe')
        distro_series = self.factory.makeDistroSeries(
            name='squirrel', distribution=archive.distribution)
        build = self.factory.makeSourcePackageRecipeBuild(
            requester=self.user, archive=archive, recipe=recipe,
            distroseries=distro_series)
        self.factory.makeSourcePackageRecipeBuildJob(recipe_build=build)
        self.factory.makeBuilder()
        return build

    def makeBuildView(self):
        """Return a view of a build suitable for testing."""
        return SourcePackageRecipeBuildView(self.makeBuild(), None)

    def test_estimate(self):
        """Time should be estimated until the job is completed."""
        view = self.makeBuildView()
        self.assertTrue(view.estimate)
        view.context.buildqueue_record.job.start()
        clear_property_cache(view)
        self.assertTrue(view.estimate)
        removeSecurityProxy(view.context).date_finished = datetime.now(UTC)
        clear_property_cache(view)
        self.assertFalse(view.estimate)

    def test_eta(self):
        """ETA should be reasonable.

        It should be None if there is no builder or queue entry.
        It should be getEstimatedJobStartTime + estimated duration for jobs
        that have not started.
        It should be job.date_started + estimated duration for jobs that have
        started.
        """
        build = self.factory.makeSourcePackageRecipeBuild()
        view = SourcePackageRecipeBuildView(build, None)
        self.assertIs(None, view.eta)
        queue_entry = self.factory.makeSourcePackageRecipeBuildJob(
            recipe_build=build)
        queue_entry._now = lambda: datetime(1970, 1, 1, 0, 0, 0, 0, UTC)
        self.factory.makeBuilder()
        clear_property_cache(view)
        self.assertIsNot(None, view.eta)
        self.assertEqual(
            queue_entry.getEstimatedJobStartTime() +
            queue_entry.estimated_duration, view.eta)
        queue_entry.job.start()
        clear_property_cache(view)
        self.assertEqual(
            queue_entry.job.date_started + queue_entry.estimated_duration,
            view.eta)

    def getBuildBrowser(self, build, view_name=None):
        """Return a browser for the specified build, opened as owner."""
        login(ANONYMOUS)
        url = canonical_url(build, view_name=view_name)
        return self.getUserBrowser(url, self.build_owner)

    def test_render_index(self):
        """Test the basic index page."""
        main_text = self.getMainText(self.makeBuild(), '+index')
        self.assertTextMatchesExpressionIgnoreWhitespace("""\
            Owner PPA named build for Owner
            created .*
            Build status
            Needs building
            Start in .* \\(9876\\) What's this?.*
            Estimated finish in .*
            Build details
            Recipe:        Recipe my-recipe for Owner
            Archive:       PPA named build for Owner
            Series:        Squirrel
            Pocket:        Release
            Binary builds: None""", main_text)

    def test_render_index_completed(self):
        """Test the index page of a completed build."""
        release = self.makeBuildAndRelease()
        self.makeBinaryBuild(release, 'itanic')
        naked_build = removeSecurityProxy(release.source_package_recipe_build)
        naked_build.status = BuildStatus.FULLYBUILT
        naked_build.date_finished = datetime(2009, 1, 1, tzinfo=UTC)
        naked_build.date_started = (
            naked_build.date_finished - timedelta(minutes=1))
        naked_build.buildqueue_record.destroySelf()
        naked_build.log = self.factory.makeLibraryFileAlias(
            content='buildlog')
        naked_build.upload_log = self.factory.makeLibraryFileAlias(
            content='upload_log')
        main_text = self.getMainText(
            release.source_package_recipe_build, '+index')
        self.assertTextMatchesExpressionIgnoreWhitespace("""\
            Owner PPA named build for Owner
            created .*
            Build status
            Successfully built
            Started on .*
            Finished on .*
            \(took 1 minute, 0.0 seconds\)
            buildlog \(8 bytes\)
            uploadlog \(10 bytes\)
            Build details
            Recipe:        Recipe my-recipe for Owner
            Archive:       PPA named build for Owner
            Series:        Squirrel
            Pocket:        Release
            Binary builds:
            itanic build of .* 3.14 in ubuntu squirrel RELEASE""",
            main_text)

    def makeBuildAndRelease(self):
        """Make a build and release suitable for testing."""
        build = self.makeBuild()
        multiverse = self.factory.makeComponent(name='multiverse')
        return self.factory.makeSourcePackageRelease(
            source_package_recipe_build=build, version='3.14',
            component=multiverse)

    def makeBinaryBuild(self, release, architecturetag):
        """Make a binary build with specified release and architecturetag."""
        distroarchseries = self.factory.makeDistroArchSeries(
            architecturetag=architecturetag,
            distroseries=release.upload_distroseries,
            processorfamily=self.factory.makeProcessorFamily())
        return self.factory.makeBinaryPackageBuild(
            source_package_release=release, distroarchseries=distroarchseries)

    def test_render_binary_builds(self):
        """BinaryBuilds for this source build are shown if they exist."""
        release = self.makeBuildAndRelease()
        self.makeBinaryBuild(release, 'itanic')
        self.makeBinaryBuild(release, 'x87-64')
        main_text = self.getMainText(
            release.source_package_recipe_build, '+index')
        self.assertTextMatchesExpressionIgnoreWhitespace("""\
            Binary builds:
            itanic build of .* 3.14 in ubuntu squirrel RELEASE
            x87-64 build of .* 3.14 in ubuntu squirrel RELEASE$""",
            main_text)

    def test_logtail(self):
        """Logtail is shown for BUILDING builds."""
        build = self.makeBuild()
        build.buildqueue_record.logtail = 'Logs have no tails!'
        build.buildqueue_record.builder = self.factory.makeBuilder()
        main_text = self.getMainText(build, '+index')
        self.assertNotIn('Logs have no tails!', main_text)
        removeSecurityProxy(build).status = BuildStatus.BUILDING
        main_text = self.getMainText(build, '+index')
        self.assertIn('Logs have no tails!', main_text)
        removeSecurityProxy(build).status = BuildStatus.FULLYBUILT
        self.assertIn('Logs have no tails!', main_text)

    def getMainText(self, build, view_name=None):
        """Return the main text of a view's web page."""
        browser = self.getViewBrowser(build, '+index')
        return extract_text(find_main_content(browser.contents))

    def test_buildlog(self):
        """A link to the build log is shown if available."""
        build = self.makeBuild()
        removeSecurityProxy(build).log = (
            self.factory.makeLibraryFileAlias())
        build_log_url = build.log_url
        browser = self.getViewBrowser(build)
        link = browser.getLink('buildlog')
        self.assertEqual(build_log_url, link.url)

    def test_uploadlog(self):
        """A link to the upload log is shown if available."""
        build = self.makeBuild()
        removeSecurityProxy(build).upload_log = (
            self.factory.makeLibraryFileAlias())
        upload_log_url = build.upload_log_url
        browser = self.getViewBrowser(build)
        link = browser.getLink('uploadlog')
        self.assertEqual(upload_log_url, link.url)


class TestSourcePackageRecipeDeleteView(TestCaseForRecipe):

    layer = DatabaseFunctionalLayer

    def test_delete_recipe(self):
        recipe = self.factory.makeSourcePackageRecipe(owner=self.chef)

        browser = self.getUserBrowser(
            canonical_url(recipe), user=self.chef)

        browser.getLink('Delete recipe').click()
        browser.getControl('Delete recipe').click()

        self.assertEqual(
            'http://code.launchpad.dev/~chef',
            browser.url)

    def test_delete_recipe_no_permissions(self):
        recipe = self.factory.makeSourcePackageRecipe(owner=self.chef)
        nopriv_person = self.factory.makePerson()
        recipe_url = canonical_url(recipe)

        browser = self.getUserBrowser(
            recipe_url, user=nopriv_person)

        self.assertRaises(
            LinkNotFoundError,
            browser.getLink, 'Delete recipe')

        self.assertRaises(
            Unauthorized,
            self.getUserBrowser, recipe_url + '/+delete', user=nopriv_person)


class TestBrokenExistingRecipes(BrowserTestCase):
    """Existing recipes broken by builder updates need to be editable.

    This happened with a 0.2 -> 0.3 release where the nest command was no
    longer allowed to refer the '.'.  There were already existing recipes that
    had this text that were not viewable or editable.  This test case captures
    that and makes sure the views stay visible.
    """

    layer = LaunchpadFunctionalLayer

    RECIPE_FIRST_LINE = (
        "# bzr-builder format 0.2 deb-version {debupstream}+{revno}")

    def makeBrokenRecipe(self):
        """Make a valid recipe, then break it."""
        product = self.factory.makeProduct()
        b1 = self.factory.makeProductBranch(product=product)
        b2 = self.factory.makeProductBranch(product=product)
        recipe_text = dedent("""\
            %s
            %s
            nest name %s foo
            """ % (self.RECIPE_FIRST_LINE, b1.bzr_identity, b2.bzr_identity))
        recipe = self.factory.makeSourcePackageRecipe(recipe=recipe_text)
        naked_data = removeSecurityProxy(recipe)._recipe_data
        nest_instruction = list(naked_data.instructions)[0]
        nest_instruction.directory = u'.'
        return recipe

    def test_recipe_is_broken(self):
        recipe = self.makeBrokenRecipe()
        self.assertRaises(Exception, str, recipe.builder_recipe)

    def assertRecipeInText(self, text):
        """If the first line is shown, that's good enough for us."""
        self.assertTrue(self.RECIPE_FIRST_LINE in text)

    def test_recipe_index_renderable(self):
        recipe = self.makeBrokenRecipe()
        main_text = self.getMainText(recipe, '+index')
        self.assertRecipeInText(main_text)

    def test_recipe_edit_renderable(self):
        recipe = self.makeBrokenRecipe()
        main_text = self.getMainText(recipe, '+edit', user=recipe.owner)
        self.assertRecipeInText(main_text)