~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
# Copyright 2009, 2011 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

"""Unit tests for ISourcePackage implementations."""

__metaclass__ = type

from lazr.lifecycle.event import (
    ObjectCreatedEvent,
    ObjectDeletedEvent,
    )
from storm.locals import Store
import transaction
from zope.component import getUtility
from zope.security.checker import canAccess
from zope.security.interfaces import Unauthorized
from zope.security.management import checkPermission

from lp.app.interfaces.launchpad import ILaunchpadCelebrities
from lp.code.model.seriessourcepackagebranch import (
    SeriesSourcePackageBranchSet,
    )
from lp.registry.interfaces.distribution import NoPartnerArchive
from lp.registry.interfaces.pocket import PackagePublishingPocket
from lp.registry.interfaces.series import SeriesStatus
from lp.registry.model.distributionsourcepackage import (
    DistributionSourcePackage,
    )
from lp.registry.model.packaging import Packaging
from lp.soyuz.enums import (
    ArchivePurpose,
    PackagePublishingStatus,
    )
from lp.soyuz.interfaces.component import IComponentSet
from lp.testing import (
    EventRecorder,
    person_logged_in,
    TestCaseWithFactory,
    WebServiceTestCase,
    )
from lp.testing.layers import DatabaseFunctionalLayer
from lp.testing.views import create_initialized_view


class TestSourcePackage(TestCaseWithFactory):

    layer = DatabaseFunctionalLayer

    def test_path(self):
        sourcepackage = self.factory.makeSourcePackage()
        self.assertEqual(
            '%s/%s/%s' % (
                sourcepackage.distribution.name,
                sourcepackage.distroseries.name,
                sourcepackage.sourcepackagename.name),
            sourcepackage.path)

    def test_getBranch_no_branch(self):
        # If there's no official branch for that pocket of a source package,
        # getBranch returns None.
        sourcepackage = self.factory.makeSourcePackage()
        branch = sourcepackage.getBranch(PackagePublishingPocket.RELEASE)
        self.assertIs(None, branch)

    def test_getBranch_exists(self):
        # If there is a SeriesSourcePackageBranch entry for that source
        # package and pocket, then return the branch.
        sourcepackage = self.factory.makeSourcePackage()
        registrant = self.factory.makePerson()
        branch = self.factory.makePackageBranch(sourcepackage=sourcepackage)
        SeriesSourcePackageBranchSet.new(
            sourcepackage.distroseries, PackagePublishingPocket.RELEASE,
            sourcepackage.sourcepackagename, branch, registrant)
        official_branch = sourcepackage.getBranch(
            PackagePublishingPocket.RELEASE)
        self.assertEqual(branch, official_branch)

    def test_setBranch(self):
        # We can set the official branch for a pocket of a source package.
        sourcepackage = self.factory.makeSourcePackage()
        pocket = PackagePublishingPocket.RELEASE
        registrant = self.factory.makePerson()
        branch = self.factory.makePackageBranch(sourcepackage=sourcepackage)
        with person_logged_in(sourcepackage.distribution.owner):
            sourcepackage.setBranch(pocket, branch, registrant)
        self.assertEqual(branch, sourcepackage.getBranch(pocket))
        # A DSP was created for the official branch.
        new_dsp = DistributionSourcePackage._get(
            sourcepackage.distribution, sourcepackage.sourcepackagename)
        self.assertIsNot(None, new_dsp)

    def test_change_branch_once_set(self):
        # We can change the official branch for a a pocket of a source package
        # even after it has already been set.
        sourcepackage = self.factory.makeSourcePackage()
        pocket = PackagePublishingPocket.RELEASE
        registrant = self.factory.makePerson()
        branch = self.factory.makePackageBranch(sourcepackage=sourcepackage)
        new_branch = self.factory.makePackageBranch(
            sourcepackage=sourcepackage)
        with person_logged_in(sourcepackage.distribution.owner):
            sourcepackage.setBranch(pocket, branch, registrant)
            sourcepackage.setBranch(pocket, new_branch, registrant)
        self.assertEqual(new_branch, sourcepackage.getBranch(pocket))

    def test_unsetBranch(self):
        # Setting the official branch for a pocket to 'None' breaks the link
        # between the branch and pocket.
        sourcepackage = self.factory.makeSourcePackage()
        pocket = PackagePublishingPocket.RELEASE
        registrant = self.factory.makePerson()
        branch = self.factory.makePackageBranch(sourcepackage=sourcepackage)
        with person_logged_in(sourcepackage.distribution.owner):
            sourcepackage.setBranch(pocket, branch, registrant)
            sourcepackage.setBranch(pocket, None, registrant)
        self.assertIs(None, sourcepackage.getBranch(pocket))

    def test_unsetBranch_delete_unpublished_dsp(self):
        # Setting the official branch for a pocket to 'None' deletes the
        # official DSP record if there is no SPPH.
        sourcepackage = self.factory.makeSourcePackage()
        pocket = PackagePublishingPocket.RELEASE
        registrant = self.factory.makePerson()
        branch = self.factory.makePackageBranch(sourcepackage=sourcepackage)
        with person_logged_in(sourcepackage.distribution.owner):
            sourcepackage.setBranch(pocket, branch, registrant)
            sourcepackage.setBranch(pocket, None, registrant)
        new_dsp = DistributionSourcePackage._get(
            sourcepackage.distribution, sourcepackage.sourcepackagename)
        self.assertIs(None, new_dsp)

    def test_linked_branches(self):
        # ISourcePackage.linked_branches is a mapping of pockets to branches.
        sourcepackage = self.factory.makeSourcePackage()
        pocket = PackagePublishingPocket.RELEASE
        registrant = self.factory.makePerson()
        branch = self.factory.makePackageBranch(sourcepackage=sourcepackage)
        with person_logged_in(sourcepackage.distribution.owner):
            sourcepackage.setBranch(pocket, branch, registrant)
        self.assertEqual(
            [(pocket, branch)], list(sourcepackage.linked_branches))

    def test_getSuiteSourcePackage(self):
        # ISourcePackage.getSuiteSourcePackage returns the suite source
        # package object for the given pocket.
        sourcepackage = self.factory.makeSourcePackage()
        pocket = PackagePublishingPocket.RELEASE
        ssp = sourcepackage.getSuiteSourcePackage(pocket)
        self.assertEqual(sourcepackage, ssp.sourcepackage)
        self.assertEqual(pocket, ssp.pocket)

    def test_path_to_release_pocket(self):
        # ISourcePackage.getPocketPath returns the path to a pocket. For the
        # RELEASE pocket, it's the same as the package path.
        sourcepackage = self.factory.makeSourcePackage()
        pocket = PackagePublishingPocket.RELEASE
        self.assertEqual(
            sourcepackage.path, sourcepackage.getPocketPath(pocket))

    def test_path_to_non_release_pocket(self):
        # ISourcePackage.getPocketPath returns the path to a pocket. For a
        # non-RELEASE pocket, it's the same as the package path, except with
        # series-pocket for the middle component.
        sourcepackage = self.factory.makeSourcePackage()
        pocket = PackagePublishingPocket.SECURITY
        path = '%s/%s-%s/%s' % (
            sourcepackage.distribution.name,
            sourcepackage.distroseries.name,
            pocket.name.lower(),
            sourcepackage.name)
        self.assertEqual(path, sourcepackage.getPocketPath(pocket))

    def test_development_version(self):
        # ISourcePackage.development_version gets the development version of
        # the source package.
        distribution = self.factory.makeDistribution()
        dev_series = self.factory.makeDistroSeries(
            distribution=distribution, status=SeriesStatus.DEVELOPMENT)
        other_series = self.factory.makeDistroSeries(
            distribution=distribution, status=SeriesStatus.OBSOLETE)
        self.assertEqual(dev_series, distribution.currentseries)
        dev_sourcepackage = self.factory.makeSourcePackage(
            distroseries=dev_series)
        other_sourcepackage = self.factory.makeSourcePackage(
            distroseries=other_series,
            sourcepackagename=dev_sourcepackage.sourcepackagename)
        self.assertEqual(
            dev_sourcepackage, other_sourcepackage.development_version)
        self.assertEqual(
            dev_sourcepackage, dev_sourcepackage.development_version)

    def test_distribution_sourcepackage(self):
        # ISourcePackage.distribution_sourcepackage is the distribution source
        # package for the ISourcePackage.
        sourcepackage = self.factory.makeSourcePackage()
        distribution = sourcepackage.distribution
        distribution_sourcepackage = distribution.getSourcePackage(
            sourcepackage.sourcepackagename)
        self.assertEqual(
            distribution_sourcepackage,
            sourcepackage.distribution_sourcepackage)

    def test_default_archive(self):
        # The default archive of a source package is the primary archive of
        # its distribution.
        sourcepackage = self.factory.makeSourcePackage()
        distribution = sourcepackage.distribution
        self.assertEqual(
            distribution.main_archive, sourcepackage.get_default_archive())

    def test_default_archive_partner(self):
        # If the source package was most recently uploaded to a partner
        # component, then its default archive is the partner archive for the
        # distribution.
        sourcepackage = self.factory.makeSourcePackage()
        partner = getUtility(IComponentSet)['partner']
        self.factory.makeSourcePackagePublishingHistory(
            sourcepackagename=sourcepackage.sourcepackagename,
            distroseries=sourcepackage.distroseries,
            component=partner,
            status=PackagePublishingStatus.PUBLISHED)
        distribution = sourcepackage.distribution
        expected_archive = self.factory.makeArchive(
            distribution=distribution,
            purpose=ArchivePurpose.PARTNER)
        self.assertEqual(
            expected_archive, sourcepackage.get_default_archive())

    def test_default_archive_specified_component(self):
        # If the component is explicitly specified as partner, then we return
        # the partner archive.
        sourcepackage = self.factory.makeSourcePackage()
        partner = getUtility(IComponentSet)['partner']
        distribution = sourcepackage.distribution
        expected_archive = self.factory.makeArchive(
            distribution=distribution,
            purpose=ArchivePurpose.PARTNER)
        self.assertEqual(
            expected_archive,
            sourcepackage.get_default_archive(component=partner))

    def test_default_archive_partner_doesnt_exist(self):
        # If the default archive ought to be the partner archive (because the
        # last published upload was to a partner component) then
        # default_archive will raise an exception.
        sourcepackage = self.factory.makeSourcePackage()
        partner = getUtility(IComponentSet)['partner']
        self.factory.makeSourcePackagePublishingHistory(
            sourcepackagename=sourcepackage.sourcepackagename,
            distroseries=sourcepackage.distroseries,
            component=partner,
            status=PackagePublishingStatus.PUBLISHED)
        self.assertRaises(
            NoPartnerArchive, sourcepackage.get_default_archive)

    def test_source_package_summary_no_releases_returns_None(self):
        sourcepackage = self.factory.makeSourcePackage()
        self.assertEqual(sourcepackage.summary, None)

    def test_source_package_summary_with_releases_returns_None(self):
        sourcepackage = self.factory.makeSourcePackage()
        self.factory.makeSourcePackageRelease(
            sourcepackagename=sourcepackage.sourcepackagename)
        self.assertEqual(sourcepackage.summary, None)

    def test_source_package_summary_with_binaries_returns_list(self):
        sp = getUtility(
            ILaunchpadCelebrities).ubuntu['warty'].getSourcePackage(
            'mozilla-firefox')

        expected_summary = (
            u'mozilla-firefox: Mozilla Firefox Web Browser\n'
            u'mozilla-firefox-data: No summary available for '
            u'mozilla-firefox-data in ubuntu warty.')
        self.assertEqual(''.join(expected_summary), sp.summary)

    def test_deletePackaging(self):
        """Ensure deletePackaging completely removes packaging."""
        packaging = self.factory.makePackagingLink()
        packaging_id = packaging.id
        store = Store.of(packaging)
        with person_logged_in(packaging.owner):
            packaging.sourcepackage.deletePackaging()
        result = store.find(Packaging, Packaging.id == packaging_id)
        self.assertIs(None, result.one())

    def test_setPackaging__new(self):
        """setPackaging() creates a Packaging link."""
        sourcepackage = self.factory.makeSourcePackage()
        productseries = self.factory.makeProductSeries()
        sourcepackage.setPackaging(
            productseries, owner=self.factory.makePerson())
        packaging = sourcepackage.direct_packaging
        self.assertEqual(packaging.productseries, productseries)

    def test_setPackaging__change_existing_entry(self):
        """setPackaging() changes existing Packaging links."""
        sourcepackage = self.factory.makeSourcePackage()
        productseries = self.factory.makeProductSeries()
        other_series = self.factory.makeProductSeries()
        owner = self.factory.makePerson()
        with EventRecorder() as recorder:
            with person_logged_in(owner):
                sourcepackage.setPackaging(productseries, owner=owner)
                sourcepackage.setPackaging(other_series, owner=owner)
                packaging = sourcepackage.direct_packaging
                self.assertEqual(packaging.productseries, other_series)
        # The first call of setPackaging() created an ObjectCreatedEvent;
        # the second call created an ObjectDeletedEvent for the deletion
        # of the old packaging link, and another ObjectCreatedEvent
        # for the new Packaging.
        event1, event2, event3 = recorder.events
        self.assertIsInstance(event1, ObjectCreatedEvent)
        self.assertIsInstance(event2, ObjectDeletedEvent)
        self.assertIsInstance(event3, ObjectCreatedEvent)

    def test_setPackaging__change_existing_entry_different_users(self):
        """An ordinary user cannot change a Packaging defined by
        somebody else.
        """
        sourcepackage = self.factory.makeSourcePackage()
        productseries = self.factory.makeProductSeries()
        other_series = self.factory.makeProductSeries()
        owner = self.factory.makePerson()
        other_user = self.factory.makePerson()
        sourcepackage.setPackaging(productseries, owner=owner)
        with person_logged_in(other_user):
            self.assertRaises(
                Unauthorized, sourcepackage.setPackaging,
                other_series, owner=other_user)

    def test_setPackagingReturnSharingDetailPermissions__ordinary_user(self):
        """An ordinary user can create a packaging link but he cannot
        set the series' branch or translation syncronisation settings,
        or the translation usage settings of the product.
        """
        sourcepackage = self.factory.makeSourcePackage()
        productseries = self.factory.makeProductSeries()
        packaging_owner = self.factory.makePerson()
        with person_logged_in(packaging_owner):
            permissions = (
                sourcepackage.setPackagingReturnSharingDetailPermissions(
                    productseries, packaging_owner))
            self.assertEqual(productseries, sourcepackage.productseries)
            self.assertFalse(
                packaging_owner.canWrite(productseries, 'branch'))
            self.assertFalse(
                packaging_owner.canWrite(
                    productseries, 'translations_autoimport_mode'))
            self.assertFalse(
                packaging_owner.canWrite(
                    productseries.product, 'translations_usage'))
            expected = {
                'user_can_change_product_series': True,
                'user_can_change_branch': False,
                'user_can_change_translation_usage': False,
                'user_can_change_translations_autoimport_mode': False,
                }
            self.assertEqual(expected, permissions)

    def test_getSharingDetailPermissions__ordinary_user(self):
        """An ordinary user cannot set the series' branch or translation
        synchronisation settings, or the translation usage settings of the
        product.
        """
        packaging = self.factory.makePackagingLink()
        sourcepackage = packaging.sourcepackage
        productseries = packaging.productseries
        with person_logged_in(packaging.owner):
            permissions = sourcepackage.getSharingDetailPermissions()
            self.assertEqual(productseries, sourcepackage.productseries)
            self.assertFalse(
                packaging.owner.canWrite(productseries, 'branch'))
            self.assertFalse(
                packaging.owner.canWrite(
                    productseries, 'translations_autoimport_mode'))
            self.assertFalse(
                packaging.owner.canWrite(
                    productseries.product, 'translations_usage'))
            expected = {
                'user_can_change_product_series': True,
                'user_can_change_branch': False,
                'user_can_change_translation_usage': False,
                'user_can_change_translations_autoimport_mode': False,
                }
            self.assertEqual(expected, permissions)

    def makeDistinctOwnerProductSeries(self):
        # Ensure productseries owner is distinct from product owner.
        return self.factory.makeProductSeries(
            owner=self.factory.makePerson())

    def test_getSharingDetailPermissions__series_owner(self):
        """A product series owner can create a packaging link, and he can
        set the series' branch or translation syncronisation settings,
        but he cannot set the translation usage settings of the product.
        """
        productseries = self.makeDistinctOwnerProductSeries()
        series_owner = productseries.owner
        # Ensure productseries owner is distinct from product owner.
        productseries = self.factory.makeProductSeries(
            owner=series_owner)
        with person_logged_in(series_owner):
            packaging = self.factory.makePackagingLink(
                productseries=productseries, owner=series_owner)
            sourcepackage = packaging.sourcepackage
            permissions = sourcepackage.getSharingDetailPermissions()
            self.assertEqual(productseries, sourcepackage.productseries)
            self.assertTrue(series_owner.canWrite(productseries, 'branch'))
            self.assertTrue(
                series_owner.canWrite(
                    productseries, 'translations_autoimport_mode'))
            self.assertFalse(
                series_owner.canWrite(
                    productseries.product, 'translations_usage'))
            expected = {
                'user_can_change_product_series': True,
                'user_can_change_branch': True,
                'user_can_change_translation_usage': False,
                'user_can_change_translations_autoimport_mode': True,
                }
            self.assertEqual(expected, permissions)

    def test_getSharingDetailPermissions__product_owner(self):
        """A product owner can create a packaging link, and he can set the
        series' branch and the translation syncronisation settings, and the
        translation usage settings of the product.
        """
        productseries = self.makeDistinctOwnerProductSeries()
        product = productseries.product
        with person_logged_in(product.owner):
            packaging = self.factory.makePackagingLink(
                productseries=productseries, owner=product.owner)
            sourcepackage = packaging.sourcepackage
            permissions = sourcepackage.getSharingDetailPermissions()
            self.assertEqual(productseries, sourcepackage.productseries)
            self.assertTrue(product.owner.canWrite(productseries, 'branch'))
            self.assertTrue(
                product.owner.canWrite(
                    productseries, 'translations_autoimport_mode'))
            self.assertTrue(
                product.owner.canWrite(
                    productseries.product, 'translations_usage'))
            expected = {
                'user_can_change_product_series': True,
                'user_can_change_branch': True,
                'user_can_change_translation_usage': True,
                'user_can_change_translations_autoimport_mode': True,
                }
            self.assertEqual(expected, permissions)

    def test_getSharingDetailPermissions_change_product(self):
        """Test user_can_change_product_series.

        Until a Packaging is created, anyone can change product series.
        Afterward, random people cannot change product series.
        """
        sourcepackage = self.factory.makeSourcePackage()
        person1 = self.factory.makePerson()
        person2 = self.factory.makePerson()

        def can_change_product_series():
            return sourcepackage.getSharingDetailPermissions()[
                    'user_can_change_product_series']
        with person_logged_in(person1):
            self.assertTrue(can_change_product_series())
        with person_logged_in(person2):
            self.assertTrue(can_change_product_series())
        self.factory.makePackagingLink(
            sourcepackage=sourcepackage, owner=person1)
        with person_logged_in(person1):
            self.assertTrue(can_change_product_series())
        with person_logged_in(person2):
            self.assertFalse(can_change_product_series())

    def test_getSharingDetailPermissions_no_product_series(self):
        sourcepackage = self.factory.makeSourcePackage()
        expected = {
            'user_can_change_product_series': True,
            'user_can_change_branch': False,
            'user_can_change_translation_usage': False,
            'user_can_change_translations_autoimport_mode': False}
        with person_logged_in(self.factory.makePerson()):
            self.assertEqual(
                expected, sourcepackage.getSharingDetailPermissions())

    def test_getSharingDetailPermissions_no_user(self):
        sourcepackage = self.factory.makeSourcePackage()
        expected = {
            'user_can_change_product_series': False,
            'user_can_change_branch': False,
            'user_can_change_translation_usage': False,
            'user_can_change_translations_autoimport_mode': False}
        self.assertEqual(
            expected, sourcepackage.getSharingDetailPermissions())

    def test_drivers_are_distroseries(self):
        # SP.drivers returns the drivers for the distroseries.
        distroseries = self.factory.makeDistroSeries()
        sourcepackage = self.factory.makeSourcePackage(
            distroseries=distroseries)
        self.assertNotEqual([], distroseries.drivers)
        self.assertEqual(sourcepackage.drivers, distroseries.drivers)

    def test_personHasDriverRights_true(self):
        # A distroseries driver has driver permissions on source packages.
        distroseries = self.factory.makeDistroSeries()
        sourcepackage = self.factory.makeSourcePackage(
            distroseries=distroseries)
        driver = distroseries.drivers[0]
        self.assertTrue(sourcepackage.personHasDriverRights(driver))

    def test_personHasDriverRights_false(self):
        # A non-owner/driver/admin does not have driver rights.
        distroseries = self.factory.makeDistroSeries()
        sourcepackage = self.factory.makeSourcePackage(
            distroseries=distroseries)
        non_priv_user = self.factory.makePerson()
        self.assertFalse(sourcepackage.personHasDriverRights(non_priv_user))

    def test_owner_is_distroseries_owner(self):
        # The source package owner differs to the ditroseries owner.
        distroseries = self.factory.makeDistroSeries()
        sourcepackage = self.factory.makeSourcePackage(
            distroseries=distroseries)
        self.assertIsNot(None, sourcepackage.owner)
        self.assertEqual(distroseries.owner, sourcepackage.owner)
        self.assertTrue(
            sourcepackage.personHasDriverRights(distroseries.owner))


class TestSourcePackageWebService(WebServiceTestCase):

    def test_setPackaging(self):
        """setPackaging is accessible and works."""
        sourcepackage = self.factory.makeSourcePackage()
        self.assertIs(None, sourcepackage.direct_packaging)
        productseries = self.factory.makeProductSeries()
        transaction.commit()
        ws_sourcepackage = self.wsObject(sourcepackage)
        ws_productseries = self.wsObject(productseries)
        ws_sourcepackage.setPackaging(productseries=ws_productseries)
        transaction.commit()
        self.assertEqual(
            productseries, sourcepackage.direct_packaging.productseries)

    def test_deletePackaging(self):
        """Deleting a packaging should work."""
        packaging = self.factory.makePackagingLink()
        sourcepackage = packaging.sourcepackage
        transaction.commit()
        self.wsObject(sourcepackage, user=packaging.owner).deletePackaging()
        transaction.commit()
        self.assertIs(None, sourcepackage.direct_packaging)

    def test_deletePackaging_with_no_packaging(self):
        """Deleting when there's no packaging should be a no-op."""
        sourcepackage = self.factory.makeSourcePackage()
        transaction.commit()
        self.wsObject(sourcepackage).deletePackaging()
        transaction.commit()
        self.assertIs(None, sourcepackage.direct_packaging)


class TestSourcePackageSecurity(TestCaseWithFactory):
    """Tests for source package security."""

    layer = DatabaseFunctionalLayer

    def test_admins_have_launchpad_Edit(self):
        admin = self.factory.makeAdministrator()
        sourcepackage = self.factory.makeSourcePackage()
        with person_logged_in(admin):
            self.assertTrue(
                checkPermission('launchpad.Edit', sourcepackage),
                "Administrators should have launchpad.Edit on source "
                "packages.")

    def test_distro_owner_have_launchpad_Edit(self):
        sourcepackage = self.factory.makeSourcePackage()
        with person_logged_in(sourcepackage.distribution.owner):
            self.assertTrue(
                checkPermission('launchpad.Edit', sourcepackage),
                "Distribution owner should have launchpad.Edit on source "
                "packages.")

    def test_uploader_has_launchpad_edit(self):
        sourcepackage = self.factory.makeSourcePackage()
        uploader = self.factory.makePerson()
        archive = sourcepackage.get_default_archive()
        with person_logged_in(sourcepackage.distribution.main_archive.owner):
            archive.newPackageUploader(uploader, sourcepackage.name)
        with person_logged_in(uploader):
            self.assertTrue(
                checkPermission('launchpad.Edit', sourcepackage),
                "Uploader to the package should have launchpad.Edit on "
                "source packages.")

    def test_uploader_has_launchpad_edit_on_obsolete_series(self):
        obsolete_series = self.factory.makeDistroSeries(
            status=SeriesStatus.OBSOLETE)
        sourcepackage = self.factory.makeSourcePackage(
            distroseries=obsolete_series)
        uploader = self.factory.makePerson()
        archive = sourcepackage.get_default_archive()
        with person_logged_in(sourcepackage.distribution.main_archive.owner):
            archive.newPackageUploader(uploader, sourcepackage.name)
        with person_logged_in(uploader):
            self.assertTrue(
                checkPermission('launchpad.Edit', sourcepackage),
                "Uploader to the package should have launchpad.Edit on "
                "source packages in an OBSOLETE series.")

    def test_uploader_have_launchpad_edit_on_current_series(self):
        current_series = self.factory.makeDistroSeries(
            status=SeriesStatus.CURRENT)
        sourcepackage = self.factory.makeSourcePackage(
            distroseries=current_series)
        uploader = self.factory.makePerson()
        archive = sourcepackage.get_default_archive()
        with person_logged_in(sourcepackage.distribution.main_archive.owner):
            archive.newPackageUploader(uploader, sourcepackage.name)
        with person_logged_in(uploader):
            self.assertTrue(
                checkPermission('launchpad.Edit', sourcepackage),
                "Uploader to the package should have launchpad.Edit on "
                "source packages in a CURRENT series.")

    def test_uploader_have_launchpad_edit_on_supported_series(self):
        supported_series = self.factory.makeDistroSeries(
            status=SeriesStatus.SUPPORTED)
        sourcepackage = self.factory.makeSourcePackage(
            distroseries=supported_series)
        uploader = self.factory.makePerson()
        archive = sourcepackage.get_default_archive()
        with person_logged_in(sourcepackage.distribution.main_archive.owner):
            archive.newPackageUploader(uploader, sourcepackage.name)
        with person_logged_in(uploader):
            self.assertTrue(
                checkPermission('launchpad.Edit', sourcepackage),
                "Uploader to the package should have launchpad.Edit on "
                "source packages in a SUPPORTED series.")

    def test_john_doe_cannot_edit(self):
        sourcepackage = self.factory.makeSourcePackage()
        john_doe = self.factory.makePerson()
        with person_logged_in(john_doe):
            self.failIf(
                checkPermission('launchpad.Edit', sourcepackage),
                "Random user shouldn't have launchpad.Edit on source "
                "packages.")

    def test_cannot_setBranch(self):
        sourcepackage = self.factory.makeSourcePackage()
        self.failIf(
            canAccess(sourcepackage, 'setBranch'),
            "setBranch should only be available to admins and uploaders")


class TestSourcePackageViews(TestCaseWithFactory):
    """Tests for source package view classes."""

    layer = DatabaseFunctionalLayer

    def setUp(self):
        TestCaseWithFactory.setUp(self)
        self.owner = self.factory.makePerson()
        self.product = self.factory.makeProduct(
            name='bonkers', displayname='Bonkers', owner=self.owner)

        self.obsolete_productseries = self.factory.makeProductSeries(
            name='obsolete', product=self.product)
        with person_logged_in(self.product.owner):
            self.obsolete_productseries.status = SeriesStatus.OBSOLETE

        self.dev_productseries = self.factory.makeProductSeries(
            name='current', product=self.product)
        with person_logged_in(self.product.owner):
            self.dev_productseries.status = SeriesStatus.DEVELOPMENT

        self.distribution = self.factory.makeDistribution(
            name='youbuntu', displayname='Youbuntu', owner=self.owner)
        self.distroseries = self.factory.makeDistroSeries(
            name='busy', distribution=self.distribution)
        self.sourcepackagename = self.factory.makeSourcePackageName(
            name='bonkers')
        self.package = self.factory.makeSourcePackage(
            sourcepackagename=self.sourcepackagename,
            distroseries=self.distroseries)

    def test_editpackaging_obsolete_series_in_vocabulary(self):
        # The sourcepackage's current product series is included in
        # the vocabulary even if it is obsolete.
        self.package.setPackaging(self.obsolete_productseries, self.owner)
        form = {
            'field.product': 'bonkers',
            'field.actions.continue': 'Continue',
            'field.__visited_steps__': 'sourcepackage_change_upstream_step1',
            }
        view = create_initialized_view(
            self.package, name='+edit-packaging', form=form,
            principal=self.owner)
        self.assertEqual([], view.view.errors)
        self.assertEqual(
            self.obsolete_productseries,
            view.view.form_fields['productseries'].field.default,
            "The form's default productseries must be the current one.")
        options = [term.token
                   for term in view.view.widgets['productseries'].vocabulary]
        self.assertEqual(
            ['trunk', 'current', 'obsolete'], options,
            "The obsolete series must be in the vocabulary.")

    def test_editpackaging_obsolete_series_not_in_vocabulary(self):
        # Obsolete productseries are normally not in the vocabulary.
        form = {
            'field.product': 'bonkers',
            'field.actions.continue': 'Continue',
            'field.__visited_steps__': 'sourcepackage_change_upstream_step1',
            }
        view = create_initialized_view(
            self.package, name='+edit-packaging', form=form,
            principal=self.owner)
        self.assertEqual([], view.view.errors)
        self.assertEqual(
            None,
            view.view.form_fields['productseries'].field.default,
            "The form's default productseries must be None.")
        options = [term.token
                   for term in view.view.widgets['productseries'].vocabulary]
        self.assertEqual(
            ['trunk', 'current'], options,
            "The obsolete series must NOT be in the vocabulary.")