def test_proprietary_product_milestone(self):
        # Proprietary projects are not listed for people without access to
        # them.
        owner = self.factory.makePerson()
        public_product = self.factory.makeProduct(
            information_type=InformationType.PUBLIC,
            project=self.project_group, owner=owner)
        public_milestone = self.factory.makeMilestone(product=public_product)
        product = self.factory.makeProduct(
            information_type=InformationType.PROPRIETARY,
            project=self.project_group, owner=owner)
        milestone = self.factory.makeMilestone(product=product,
                                               name=public_milestone.name)
        (group_milestone,) = self.project_group.milestones
        self.factory.makeSpecification(milestone=public_milestone)
        with person_logged_in(owner):
            self.factory.makeSpecification(milestone=milestone)
            product_name = product.displayname
        with person_logged_in(None):
            owner_browser = self.getViewBrowser(group_milestone, user=owner)
            browser = self.getViewBrowser(group_milestone)

        self.assertIn(product_name, owner_browser.contents)
        self.assertIn(public_product.displayname, owner_browser.contents)
        self.assertNotIn(product_name, browser.contents)
        self.assertIn(public_product.displayname, browser.contents)
    def setUp(self):
        super(TestTeamLimitedViewAccess, self).setUp()

        # Make a private team.
        team_owner = self.factory.makePerson()
        db_team = self.factory.makeTeam(
            name='private-team', owner=team_owner,
            visibility=PersonVisibility.PRIVATE,
            membership_policy=TeamMembershipPolicy.RESTRICTED)
        # Create a P3A for the team.
        with person_logged_in(team_owner):
            self.factory.makeArchive(
                owner=db_team, private=True, name='private-ppa')
        # Create an authorised user with limitedView permission on the team.
        # We do that by subscribing the team and the user to the same
        # private bug.
        self.bug_owner = self.factory.makePerson()
        bug = self.factory.makeBug(
            owner=self.bug_owner, information_type=InformationType.USERDATA)
        self.authorised_person = self.factory.makePerson()
        with person_logged_in(self.bug_owner):
            bug.subscribe(db_team, self.bug_owner)
            bug.subscribe(self.authorised_person, self.bug_owner)
            self.bug_id = bug.id
        self.factory.makeProduct(name='some-product', bug_supervisor=db_team)
        transaction.commit()
    def test_mixed_product_projectgroup_milestone(self):
        # If a milestone is mixed between public and proprietary products,
        # only the public is shown to people without access.
        owner = self.factory.makePerson()
        teammember = self.factory.makePerson()
        owning_team = self.factory.makeTeam(owner=owner,
                membership_policy=TeamMembershipPolicy.RESTRICTED)
        with person_logged_in(owner):
            owning_team.addMember(teammember, owner)
        group = self.factory.makeProject(owner=owning_team)
        private = self.factory.makeProduct(
            project=group, owner=owner,
            information_type=InformationType.PROPRIETARY, name='private')
        public = self.factory.makeProduct(
            project=group, owner=owner, name='public')
        private_milestone = self.factory.makeMilestone(
            product=private, name='1.0')
        public_milestone = self.factory.makeMilestone(
            product=public, name='1.0')
        with person_logged_in(owner):
            self.factory.makeBug(
                target=private, owner=owner, milestone=private_milestone,
                title='This is the private bug')
            self.factory.makeBug(
                target=public, owner=owner, milestone=public_milestone,
                title='This is the public bug')

        group_milestone = group.milestones[0]
        browser = self.getViewBrowser(
            group_milestone, user=self.factory.makePerson())
        self.assertTrue("This is the public bug" in browser.contents)
        self.assertFalse("This is the private bug" in browser.contents)
 def test_user_without_launchpad_view(self):
     # When the user does not have launchpad.View on the context,
     user = self.factory.makePerson()
     owner = self.factory.makePerson()
     with person_logged_in(owner):
         team = self.factory.makeTeam(
             displayname='Waffles', owner=owner,
             visibility=PersonVisibility.PRIVATE)
         archive = self.factory.makeArchive(private=True, owner=team)
         archive.newSubscription(user, registrant=owner)
     with person_logged_in(user):
         for rootsite, view_name in [
             (None, '+index'), ('code', '+branches'), ('bugs', '+bugs'),
             ('blueprints', '+specs'), ('answers', '+questions'),
             ('translations', '+translations')]:
             view = create_initialized_view(
                 team, name=view_name, path_info='', principal=user,
                 server_url=canonical_url(team, rootsite=rootsite),
                 rootsite=rootsite)
             document = find_tag_by_id(view(), 'document')
             self.assertIsNone(document.find(True, id='side-portlets'))
             self.assertIsNone(document.find(True, id='registration'))
             self.assertEndsWith(
                 extract_text(document.find(True, id='maincontent')),
                 'The information in this page is not shared with you.')
    def test_data_subscription_lp_admin(self):
        # For a subscription, answercontact_data_js has can_edit
        # set to true for a Launchpad admin.
        question = self.factory.makeQuestion()
        member = self.factory.makePerson()
        contact = self.factory.makePerson(
            name='user', displayname='Contact Name')
        contact.addLanguage(getUtility(ILanguageSet)['en'])
        with person_logged_in(member):
            question.target.addAnswerContact(contact, contact)
        view = create_view(question.target, '+portlet-answercontacts-details')
        api_request = IWebServiceClientRequest(view.request)

        expected_result = {
            'subscriber': {
                'name': 'user',
                'display_name': 'Contact Name',
                'is_team': False,
                'can_edit': True,
                'web_link': canonical_url(contact),
                'self_link': absoluteURL(contact, api_request)
                }
            }

        # Login as admin
        admin = getUtility(IPersonSet).find(ADMIN_EMAIL).any()
        with person_logged_in(admin):
            self.assertEqual(
                dumps([expected_result]), view.answercontact_data_js)
 def test_referenced_oops_in_urls_bug_663249(self):
     # Sometimes OOPS ids appears as part of an URL. These should could as
     # a reference even though they are not formatted specially - this
     # requires somewhat special handling in the reference calculation
     # function.
     oopsid_old = "OOPS-abcdef1234"
     oopsid_new = "OOPS-4321"
     bug_old = self.factory.makeBug()
     bug_new = self.factory.makeBug()
     with person_logged_in(bug_old.owner):
         bug_old.description = (
             "foo https://lp-oops.canonical.com/oops.py?oopsid=%s bar"
             % oopsid_old)
     with person_logged_in(bug_new.owner):
         bug_new.description = (
             "foo https://oops.canonical.com/oops.py?oopsid=%s bar"
             % oopsid_new)
     self.store.flush()
     now = datetime.now(tz=utc)
     day = timedelta(days=1)
     self.failUnlessEqual(
         set([oopsid_old, oopsid_new]),
         referenced_oops(now - day, now, "product=1", {}))
     self.failUnlessEqual(
         set([]),
         referenced_oops(now + day, now + day, "product=1", {}))
    def test_access_to_timeline_of_proprietary_product(self):
        # ITestTimelineProductSeries instances related to proprietary
        # products are visible only for person with a policy grant for
        # the product.
        owner = self.factory.makePerson()
        user_with_policy_grant = self.factory.makePerson()
        product = self.factory.makeProduct(
            owner=owner, information_type=InformationType.PROPRIETARY)
        series = self.factory.makeProductSeries(product=product)
        with person_logged_in(owner):
            timeline = series.getTimeline()
            getUtility(IService, 'sharing').sharePillarInformation(
                product, user_with_policy_grant, owner,
                {InformationType.PROPRIETARY: SharingPermission.ALL})

        # Anonymous users do not have access.
        with person_logged_in(ANONYMOUS):
            for name in (
                'name', 'status', 'is_development_focus', 'uri', 'landmarks',
                'product'):
                self.assertRaises(Unauthorized, getattr, timeline, name)
        # Ordinary users do not have access.
        with person_logged_in(self.factory.makePerson()):
            for name in (
                'name', 'status', 'is_development_focus', 'uri', 'landmarks',
                'product'):
                self.assertRaises(Unauthorized, getattr, timeline, name)
        # Users with a policy grant have access.
        with person_logged_in(user_with_policy_grant):
            for name in (
                'name', 'status', 'is_development_focus', 'uri', 'landmarks',
                'product'):
                # No exception is raised when attributes of timeline
                # are accessed.
                getattr(timeline, name)
    def test_data_team_subscription_member_looks(self):
        # For a team subscription, answercontact_data_js has can_edit
        # set to true for team member.
        question = self.factory.makeQuestion()
        member = self.factory.makePerson()
        teamowner = self.factory.makePerson(
            name="team-owner", displayname="Team Owner")
        contact = self.factory.makeTeam(
            name='team', displayname='Team Name', owner=teamowner,
            members=[member])
        contact.addLanguage(getUtility(ILanguageSet)['en'])
        with person_logged_in(contact.teamowner):
            question.target.addAnswerContact(contact, contact.teamowner)
        view = create_view(question.target, '+portlet-answercontacts-details')
        api_request = IWebServiceClientRequest(view.request)

        expected_result = {
            'subscriber': {
                'name': 'team',
                'display_name': 'Team Name',
                'is_team': True,
                'can_edit': True,
                'web_link': canonical_url(contact),
                'self_link': absoluteURL(contact, api_request)
                }
            }
        with person_logged_in(contact.teamowner):
            self.assertEqual(
                dumps([expected_result]), view.answercontact_data_js)
 def test_binary_query_counts(self):
     query_baseline = 40
     # Assess the baseline.
     collector = QueryCollector()
     collector.register()
     self.addCleanup(collector.unregister)
     ppa = self.factory.makeArchive()
     viewer = self.factory.makePerson()
     browser = self.getUserBrowser(user=viewer)
     with person_logged_in(viewer):
         # The baseline has one package, because otherwise the
         # short-circuit prevents the packages iteration happening at
         # all and we're not actually measuring scaling
         # appropriately.
         pkg = self.factory.makeBinaryPackagePublishingHistory(
             archive=ppa)
         url = canonical_url(ppa) + "/+packages"
     browser.open(url)
     self.assertThat(collector, HasQueryCount(LessThan(query_baseline)))
     expected_count = collector.count
     # Use all new objects - avoids caching issues invalidating the
     # gathered metrics.
     login(ADMIN_EMAIL)
     ppa = self.factory.makeArchive()
     viewer = self.factory.makePerson()
     browser = self.getUserBrowser(user=viewer)
     with person_logged_in(viewer):
         for i in range(3):
             pkg = self.factory.makeBinaryPackagePublishingHistory(
                 archive=ppa, distroarchseries=pkg.distroarchseries)
         url = canonical_url(ppa) + "/+packages"
     browser.open(url)
     self.assertThat(collector, HasQueryCount(Equals(expected_count)))
    def test_goal_propose_decline_and_clear(self):
        # Webservice clients can decline and clear spec series goals.
        db_spec = self.factory.makeBlueprint(product=self.product,
                                             owner=self.proposer)
        # Propose for series goal
        with person_logged_in(self.proposer):
            launchpad = self.factory.makeLaunchpadService(person=self.proposer)
            spec = ws_object(launchpad, db_spec)
            series = ws_object(launchpad, self.series)
            spec.proposeGoal(goal=series)
            transaction.commit()
            self.assertEqual(db_spec.goal, self.series)
            self.assertFalse(spec.has_accepted_goal)

        with person_logged_in(self.driver):
            # Decline series goal
            launchpad = self.factory.makeLaunchpadService(person=self.driver)
            spec = ws_object(launchpad, db_spec)
            spec.declineGoal()
            transaction.commit()
            self.assertFalse(spec.has_accepted_goal)
            self.assertEqual(db_spec.goal, self.series)

            # Clear series goal as a driver
            spec.proposeGoal(goal=None)
            transaction.commit()
            self.assertIsNone(db_spec.goal)
    def test_deptree_filters_blocked(self):
        # dep tree's blocked_specs and dependencies attributes filter
        # blueprints the user can't see.
        sharing_policy = SpecificationSharingPolicy.PUBLIC_OR_PROPRIETARY
        owner = self.factory.makePerson()
        product = self.factory.makeProduct(
            owner=owner, specification_sharing_policy=sharing_policy)
        root = self.factory.makeBlueprint(product=product)
        proprietary_blocked = self.factory.makeBlueprint(
            product=product, information_type=InformationType.PROPRIETARY)
        public_blocked = self.factory.makeBlueprint(product=product)
        proprietary_blocked.createDependency(root)
        public_blocked.createDependency(root)

        # Anonymous can see only the public
        with anonymous_logged_in():
            view = create_view(root, name="+deptree")
            self.assertEqual([public_blocked], view.all_blocked)
            self.assertEqual([public_blocked], view.blocked_specs)

        # The owner can see everything.
        with person_logged_in(owner):
            view = create_view(root, name="+deptree")
            self.assertEqual(
                [proprietary_blocked, public_blocked], view.all_blocked)
            self.assertEqual(
                [proprietary_blocked, public_blocked], view.blocked_specs)

        # A random person cannot see the propriety dep.
        with person_logged_in(self.factory.makePerson()):
            view = create_view(root, name="+deptree")
            self.assertEqual([public_blocked], view.all_blocked)
            self.assertEqual([public_blocked], view.blocked_specs)
 def test_mute_subscription_link_shown_for_team_subscription(self):
     # If the person belongs to a team with a structural subscription,
     # then the mute link will be displayed to them.
     person = self.factory.makePerson(name="a-person")
     team_owner = self.factory.makePerson(name="team-owner")
     team = self.factory.makeTeam(owner=team_owner, name="subscribed-team")
     with person_logged_in(team_owner):
         team.addMember(person, team_owner)
         self.target.addBugSubscription(team, team_owner)
     with person_logged_in(person):
         self.assertFalse(self.bug.isMuted(person))
         self.assertTrue(
             self.bug.personIsAlsoNotifiedSubscriber(
                 person), "Person should be a notified subscriber")
         view = create_initialized_view(
             self.bug, name="+portlet-subscription")
         self.assertTrue(view.user_should_see_mute_link,
                         "User should see mute link.")
         contents = view.render()
         self.assertTrue('mute_subscription' in contents,
                         "'mute_subscription' not in contents.")
         self.assertFalse(
             self._hasCSSClass(
                 contents, 'mute-link-container', 'hidden'))
         create_initialized_view(
             self.bug.default_bugtask, name="+mute",
             form={'field.actions.mute': 'Mute bug mail'})
         self.assertTrue(self.bug.isMuted(person))
    def test_access_for_user_with_grant_for_private_product(self):
        # Users with a policy grant for a private product have access
        # to most attributes of the private product.
        user = self.factory.makePerson()
        with person_logged_in(self.proprietary_product_owner):
            bug = self.factory.makeBug(
                target=self.proprietary_product,
                owner=self.proprietary_product_owner)
            bug.subscribe(user, subscribed_by=self.proprietary_product_owner)

        with person_logged_in(user):
            self.assertAccessAuthorized(
                self.expected_get_permissions[CheckerPublic],
                self.proprietary_milestone)

            # They have access to attributes requiring the permission
            # launchpad.LimitedView of milestones for the private
            # product.
            self.assertAccessAuthorized(
                self.expected_get_permissions['launchpad.LimitedView'],
                self.proprietary_milestone)

            # They cannot access other attributes.
            for permission, names in self.expected_get_permissions.items():
                if permission in (
                    CheckerPublic, 'launchpad.LimitedView'):
                    continue
                self.assertAccessUnauthorized(
                    names, self.proprietary_milestone)

            # They cannot change attributes.
            for names in self.expected_set_permissions.values():
                self.assertChangeUnauthorized(
                    names, self.proprietary_milestone)
 def test_user_without_launchpad_view(self):
     # When the user does not have launchpad.View on the context,
     # base-layout does not render the main slot and side slot.
     owner = self.factory.makePerson()
     with person_logged_in(owner):
         team = self.factory.makeTeam(
             displayname='Waffles', owner=owner,
             visibility=PersonVisibility.PRIVATE)
         archive = self.factory.makeArchive(private=True, owner=team)
         archive.newSubscription(self.user, registrant=owner)
     with person_logged_in(self.user):
         view = self.makeTemplateView('main_side', context=team)
         content = BeautifulSoup(view())
     self.assertIs(None, content.find(text=' Extra head content '))
     self.verify_base_layout_html_element(content)
     self.verify_base_layout_head_parts(view, content)
     document = find_tag_by_id(content, 'document')
     self.verify_base_layout_body_parts(document)
     self.verify_watermark(document)
     # These parts are unique to the case without launchpad.View.
     self.assertIsNone(document.find(True, id='side-portlets'))
     self.assertIsNone(document.find(True, id='registration'))
     self.assertEndsWith(
         extract_text(document.find(True, id='maincontent')),
         'The information in this page is not shared with you.')
 def test_new_security_bug(self):
     # Structural subscribers are not notified of security bugs.
     maintainer = self.factory.makePerson(name='maintainer')
     project = self.factory.makeProduct(name='fnord', owner=maintainer)
     subscriber = self.factory.makePerson(name='subscriber')
     with person_logged_in(subscriber):
         project.addBugSubscription(subscriber, subscriber)
     transaction.commit()
     handler = MaloneHandler()
     with person_logged_in(project.owner):
         msg = self.factory.makeSignedMessage(
             body='bad thing\n security yes\n affects fnord',
             subject='security issue',
             to_address='*****@*****.**')
         handler.process(msg, msg['To'])
     notification = self.getLatestBugNotification()
     bug = notification.bug
     self.assertEqual('security issue', bug.title)
     self.assertTrue(bug.security_related)
     self.assertEqual(1, len(bug.bugtasks))
     self.assertEqual(project, bug.bugtasks[0].target)
     recipients = set()
     for notification in BugNotification.select():
         for recipient in notification.recipients:
             recipients.add(recipient.person)
     self.assertContentEqual([maintainer], recipients)
    def test_contact_is_possible(self):
        # The contact_is_possible property checks has_valid_email_address
        # and contact_is_allowed.
        team = self.factory.makeTeam()
        sender = self.factory.makePerson()
        with person_logged_in(sender):
            view = create_initialized_view(team, '+contactuser')
        self.assertTrue(view.has_valid_email_address)
        self.assertTrue(view.contact_is_allowed)
        self.assertTrue(view.contact_is_possible)

        other_sender = self.makeThrottledSender()
        with person_logged_in(other_sender):
            view = create_initialized_view(team, '+contactuser')
        self.assertTrue(view.has_valid_email_address)
        self.assertFalse(view.contact_is_allowed)
        self.assertFalse(view.contact_is_possible)

        with person_logged_in(team.teamowner):
            team.teamowner.leave(team)
        with person_logged_in(sender):
            view = create_initialized_view(team, '+contactuser')
        self.assertTrue(view.contact_is_allowed)
        self.assertFalse(view.has_valid_email_address)
        self.assertFalse(view.contact_is_possible)
    def test_data_subscription_lp_admin(self):
        # For a subscription, subscriber_data_js has can_edit
        # set to true for a Launchpad admin.
        question = self._makeQuestionWithNoSubscribers()
        member = self.factory.makePerson()
        subscriber = self.factory.makePerson(
            name='user', displayname='Subscriber Name')
        with person_logged_in(member):
            question.subscribe(subscriber, subscriber)
        view = create_view(question, '+portlet-subscribers-details')
        api_request = IWebServiceClientRequest(view.request)

        expected_result = {
            'subscriber': {
                'name': 'user',
                'display_name': 'Subscriber Name',
                'is_team': False,
                'can_edit': True,
                'web_link': canonical_url(subscriber),
                'self_link': absoluteURL(subscriber, api_request)
                },
            'subscription_level': "Direct",
            }

        # Login as admin
        admin = getUtility(IPersonSet).find(ADMIN_EMAIL).any()
        with person_logged_in(admin):
            self.assertEqual(
                dumps([expected_result]), view.subscriber_data_js)
 def setUp(self):
     super(TestBuildPrivacy, self).setUp()
     # Add everything we need to create builds.
     self.admin = getUtility(IPersonSet).getByEmail(ADMIN_EMAIL)
     processor = self.factory.makeProcessor()
     distroseries = self.factory.makeDistroSeries()
     das = self.factory.makeDistroArchSeries(
         distroseries=distroseries, processor=processor,
         supports_virtualized=True)
     with person_logged_in(self.admin):
         publisher = SoyuzTestPublisher()
         publisher.prepareBreezyAutotest()
         distroseries.nominatedarchindep = das
         publisher.addFakeChroots(distroseries=distroseries)
         self.factory.makeBuilder(processor=processor)
     self.public_archive = self.factory.makeArchive()
     self.private_archive = self.factory.makeArchive(private=True)
     # Create one public and one private build.
     public_spph = publisher.getPubSource(
         sourcename=self.factory.getUniqueString(),
         version="%s.1" % self.factory.getUniqueInteger(),
         distroseries=distroseries, archive=self.public_archive)
     [public_build] = public_spph.createMissingBuilds()
     private_spph = publisher.getPubSource(
         sourcename=self.factory.getUniqueString(),
         version="%s.1" % self.factory.getUniqueInteger(),
         distroseries=distroseries, archive=self.private_archive)
     with person_logged_in(self.admin):
         [private_build] = private_spph.createMissingBuilds()
     self.expected_title = '%s build of %s %s in %s %s RELEASE' % (
         das.architecturetag, private_spph.source_package_name,
         private_spph.source_package_version,
         distroseries.distribution.name, distroseries.name)
    def test_expose_user_subscriptions_to_js__uses_cached_teams(self):
        # The function expose_user_subscriptions_to_js() uses a
        # cached list of administrated teams.
        user = self.factory.makePerson()
        target = self.factory.makeProduct()
        request = LaunchpadTestRequest()
        with person_logged_in(user):
            sub = target.addBugSubscription(user, user)

        # The first call requires one query to retrieve the administrated
        # teams.
        with StormStatementRecorder() as recorder:
            expose_user_subscriptions_to_js(user, [sub], request)
        statements_for_admininstrated_teams = [
            statement for statement in recorder.statements
            if statement.startswith("SELECT *")]
        self.assertEqual(1, len(statements_for_admininstrated_teams))

        # Calling the function a second time does not require an
        # SQL call to retrieve the administrated teams.
        with person_logged_in(user):
            with StormStatementRecorder() as recorder:
                expose_user_subscriptions_to_js(user, [sub], request)
        statements_for_admininstrated_teams = [
            statement for statement in recorder.statements
            if statement.startswith("SELECT *")]
        self.assertEqual(0, len(statements_for_admininstrated_teams))
    def test_data_person_subscription_subscriber(self):
        # For a subscription, subscriber_data_js has can_edit
        # set to true for the subscriber.
        bug = self._makeBugWithNoSubscribers()
        subscriber = self.factory.makePerson(
            name='user', displayname='Subscriber Name')
        subscribed_by = self.factory.makePerson(
            name='someone', displayname='Someone')
        with person_logged_in(subscriber):
            bug.subscribe(subscriber, subscribed_by,
                          level=BugNotificationLevel.LIFECYCLE)
        harness = LaunchpadFormHarness(bug, BugPortletSubscribersWithDetails)
        api_request = IWebServiceClientRequest(harness.request)

        expected_result = {
            'subscriber': {
                'name': 'user',
                'display_name': 'Subscriber Name',
                'is_team': False,
                'can_edit': True,
                'web_link': canonical_url(subscriber),
                'self_link': absoluteURL(subscriber, api_request),
                'display_subscribed_by': 'Subscribed by Someone (someone)',
                },
            'subscription_level': "Lifecycle",
            }
        with person_logged_in(subscribed_by):
            self.assertEqual(
                dumps([expected_result]), harness.view.subscriber_data_js)
    def test_data_subscription_lp_admin(self):
        # For a subscription, subscriber_data_js has can_edit
        # set to true for a Launchpad admin.
        bug = self._makeBugWithNoSubscribers()
        member = self.factory.makePerson()
        subscriber = self.factory.makePerson(
            name='user', displayname='Subscriber Name')
        with person_logged_in(member):
            bug.subscribe(subscriber, subscriber,
                          level=BugNotificationLevel.LIFECYCLE)
        harness = LaunchpadFormHarness(
            bug, BugPortletSubscribersWithDetails)
        api_request = IWebServiceClientRequest(harness.request)

        expected_result = {
            'subscriber': {
                'name': 'user',
                'display_name': 'Subscriber Name',
                'is_team': False,
                'can_edit': True,
                'web_link': canonical_url(subscriber),
                'self_link': absoluteURL(subscriber, api_request),
                'display_subscribed_by': 'Self-subscribed',
                },
            'subscription_level': "Lifecycle",
            }

        # Login as admin
        admin = getUtility(IPersonSet).find(ADMIN_EMAIL).any()
        with person_logged_in(admin):
            self.assertEqual(
                dumps([expected_result]), harness.view.subscriber_data_js)
    def test_subscribe_uses_bug_notification_level(self):
        # When a user subscribes to a bug using the advanced features on
        # the Bug +subscribe page, the bug notification level they
        # choose is taken into account.
        bug = self.factory.makeBug()
        # We unsubscribe the bug's owner because if we don't there will
        # be two COMMENTS-level subscribers.
        with person_logged_in(bug.owner):
            bug.unsubscribe(bug.owner, bug.owner)

        displayed_levels = [
            level for level in BugNotificationLevel.items]
        for level in displayed_levels:
            person = self.factory.makePerson()
            with person_logged_in(person):
                harness = LaunchpadFormHarness(
                    bug.default_bugtask, BugSubscriptionSubscribeSelfView)
                form_data = {
                    'field.subscription': person.name,
                    'field.bug_notification_level': level.title,
                    }
                harness.submit('continue', form_data)

            subscription = bug.getSubscriptionForPerson(person)
            self.assertEqual(
                level, subscription.bug_notification_level,
                "Bug notification level of subscription should be %s, is "
                "actually %s." % (
                    level.title,
                    subscription.bug_notification_level.title))
    def test_data_team_subscription_member_looks(self):
        # For a team subscription, subscriber_data_js has can_edit
        # set to true for team member.
        bug = self._makeBugWithNoSubscribers()
        member = self.factory.makePerson()
        teamowner = self.factory.makePerson(
            name="team-owner", displayname="Team Owner")
        subscriber = self.factory.makeTeam(
            name='team', displayname='Team Name', owner=teamowner,
            members=[member])
        with person_logged_in(subscriber.teamowner):
            bug.subscribe(subscriber, subscriber.teamowner,
                          level=BugNotificationLevel.LIFECYCLE)
        harness = LaunchpadFormHarness(
            bug, BugPortletSubscribersWithDetails)
        api_request = IWebServiceClientRequest(harness.request)

        expected_result = {
            'subscriber': {
                'name': 'team',
                'display_name': 'Team Name',
                'is_team': True,
                'can_edit': True,
                'web_link': canonical_url(subscriber),
                'self_link': absoluteURL(subscriber, api_request),
                'display_subscribed_by': \
                    'Subscribed by Team Owner (team-owner)',
                },
            'subscription_level': "Lifecycle",
            }
        with person_logged_in(subscriber.teamowner):
            self.assertEqual(
                dumps([expected_result]), harness.view.subscriber_data_js)
    def test_data_team_subscription_member_looks(self):
        # For a team subscription, subscriber_data_js has can_edit
        # set to true for team member.
        question = self._makeQuestionWithNoSubscribers()
        member = self.factory.makePerson()
        teamowner = self.factory.makePerson(
            name="team-owner", displayname="Team Owner")
        subscriber = self.factory.makeTeam(
            name='team', displayname='Team Name', owner=teamowner,
            members=[member])
        with person_logged_in(subscriber.teamowner):
            question.subscribe(subscriber, subscriber.teamowner)
        view = create_view(question, '+portlet-subscribers-details')
        api_request = IWebServiceClientRequest(view.request)

        expected_result = {
            'subscriber': {
                'name': 'team',
                'display_name': 'Team Name',
                'is_team': True,
                'can_edit': True,
                'web_link': canonical_url(subscriber),
                'self_link': absoluteURL(subscriber, api_request)
                },
            'subscription_level': "Direct",
            }
        with person_logged_in(subscriber.teamowner):
            self.assertEqual(
                dumps([expected_result]), view.subscriber_data_js)
    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_redeem_twice_causes_error(self):
        # If a voucher is redeemed twice, the second attempt is rejected.
        commercial_admin = login_celebrity('commercial_admin')
        voucher_id_1, voucher_id_2 = self.makeVouchers(commercial_admin, 2)
        project_1 = self.factory.makeProduct(name='p1')
        project_2 = self.factory.makeProduct(name='p2')
        url = canonical_url(commercial_admin, view_name='+vouchers')
        browser = self.getUserBrowser(url, commercial_admin)
        # A second browser opens the +vouchers page before the first browser
        # attempts to redeem the voucher.
        browser2 = self.getUserBrowser(url, commercial_admin)
        browser.getControl(
            'Select the project you wish to subscribe').value = 'p1'
        browser.getControl(
            'Select a voucher').getControl(voucher_id_1).selected = True
        browser.getControl('Redeem').click()
        with person_logged_in(commercial_admin):
            self.assertIsNotNone(project_1.commercial_subscription)

        browser2.getControl(
            'Select the project you wish to subscribe').value = 'p2'
        browser2.getControl(
            'Select a voucher').getControl(voucher_id_1).selected = True
        browser2.getControl('Redeem').click()
        with person_logged_in(commercial_admin):
            self.assertIsNone(project_2.commercial_subscription)
        error_messages = find_tags_by_class(browser2.contents, 'message')
        self.assertEqual(extract_text(error_messages[1]), 'Invalid value')
 def test_update_dependancies_respects_component(self):
     # Since main can only utilise packages that are published in main,
     # dependencies are not satisfied if they are not in main.
     spph = self.publisher.getPubSource(
         sourcename=self.factory.getUniqueString(),
         version="%s.1" % self.factory.getUniqueInteger(),
         distroseries=self.distroseries, archive=self.archive)
     [build] = spph.createMissingBuilds()
     spn = self.factory.getUniqueString()
     version = "%s.1" % self.factory.getUniqueInteger()
     with person_logged_in(self.admin):
         build.updateStatus(
             BuildStatus.MANUALDEPWAIT,
             slave_status={'dependencies': unicode(spn)})
         [bpph] = self.publisher.getPubBinaries(
             binaryname=spn, distroseries=self.distroseries,
             version=version, builder=self.builder, archive=self.archive,
             status=PackagePublishingStatus.PUBLISHED,
             component='universe')
         # Commit to make sure stuff hits the database.
         transaction.commit()
     build.updateDependencies()
     # Since the dependency is in universe, we still can't see it.
     self.assertEquals(unicode(spn), build.dependencies)
     with person_logged_in(self.admin):
         bpph.component = getUtility(IComponentSet)['main']
         transaction.commit()
     # Now that we have moved it main, we can see it.
     build.updateDependencies()
     self.assertEquals(u'', build.dependencies)
    def test_data_target_owner_answercontact_looks(self):
        # Answercontact_data_js has can_edit set to true for target owner.
        distro = self.factory.makeDistribution()
        question = self.factory.makeQuestion(target=distro)
        contact = self.factory.makePerson(
            name='user', displayname='Contact Name')
        contact.addLanguage(getUtility(ILanguageSet)['en'])
        with person_logged_in(contact):
            question.target.addAnswerContact(contact, contact)
        view = create_view(question.target, '+portlet-answercontacts-details')
        api_request = IWebServiceClientRequest(view.request)

        expected_result = {
            'subscriber': {
                'name': 'user',
                'display_name': 'Contact Name',
                'is_team': False,
                'can_edit': True,
                'web_link': canonical_url(contact),
                'self_link': absoluteURL(contact, api_request)
                }
            }
        with person_logged_in(distro.owner):
            self.assertEqual(
                dumps([expected_result]), view.answercontact_data_js)
 def _make_subscription(self, proprietary_subscription=False):
     subscriber = self.factory.makePerson()
     subscribed_by = self.factory.makePerson()
     policy = SpecificationSharingPolicy.PUBLIC_OR_PROPRIETARY
     product_owner = self.factory.makePerson()
     product = self.factory.makeProduct(specification_sharing_policy=policy, owner=product_owner)
     if proprietary_subscription:
         info_type = InformationType.PROPRIETARY
         with person_logged_in(product_owner):
             permissions = {InformationType.PROPRIETARY: SharingPermission.ALL}
             getUtility(IService, "sharing").sharePillarInformation(
                 product, subscribed_by, product_owner, permissions
             )
     else:
         info_type = InformationType.PUBLIC
     if proprietary_subscription:
         # If the spec is proprietary, subscribed_by must have the
         # permission launchpad.Edit on the spec in order to
         # subscribe someone. This permission requires to have a
         # special role for the specificaiton, like the assignee.
         assignee = subscribed_by
     else:
         assignee = None
     spec = self.factory.makeSpecification(product=product, information_type=info_type, assignee=assignee)
     with person_logged_in(subscribed_by):
         subscription = spec.subscribe(subscriber, subscribed_by)
     return spec, subscriber, subscribed_by, subscription
    def test_access_for_user_with_artifact_grant(self):
        # Users with an artifact grant related to the parent product
        # can access properties requring the permission launchpad.LimitedView
        # of a series.
        user = self.factory.makePerson()
        with person_logged_in(self.proprietary_product_owner):
            bug = self.factory.makeBug(
                target=self.proprietary_product,
                owner=self.proprietary_product_owner)
            bug.subscribe(user, subscribed_by=self.proprietary_product_owner)

        with person_logged_in(user):
            self.assertAccessAuthorized(
                self.expected_get_permissions['launchpad.LimitedView'],
                self.proprietary_series)

            # The cannot access other attributes of a series for
            # private products.
            for permission, names in self.expected_get_permissions.items():
                if permission in (CheckerPublic, 'launchpad.LimitedView'):
                    continue
                self.assertAccessUnauthorized(names, self.proprietary_series)

            # They cannot change any attributes.
            for permission, names in self.expected_set_permissions.items():
                self.assertChangeUnauthorized(names, self.proprietary_series)
Beispiel #31
0
 def test_target_owner_can_edit(self):
     with person_logged_in(self.bug.default_bugtask.target.owner):
         self.assertTrue(checkPermission('launchpad.Edit', self.bug))
Beispiel #32
0
 def test_bug_reporter_can_edit(self):
     with person_logged_in(self.bug.owner):
         self.assertTrue(checkPermission('launchpad.Edit', self.bug))
Beispiel #33
0
 def test_user_with_karma_can_edit(self):
     person = self.factory.makePerson()
     self._makeKarmaTotalCache(person, 10)
     with person_logged_in(person):
         self.assertTrue(checkPermission('launchpad.Edit', self.bug))
Beispiel #34
0
 def test_private_bug_non_subscriber_cannot_edit(self):
     with admin_logged_in() as admin:
         self.bug.setPrivate(True, admin)
     with person_logged_in(self.factory.makePerson()):
         self.assertFalse(checkPermission('launchpad.Edit', self.bug))
Beispiel #35
0
 def test_person_logged_in(self):
     # The person_logged_in context manager runs with a person logged in.
     person = self.factory.makePerson()
     with person_logged_in(person):
         self.assertLoggedIn(person)
Beispiel #36
0
 def test_is_muted_returns_false_for_non_subscribers(self):
     # Bug.isMuted() will return False if the user has no
     # subscription.
     with person_logged_in(self.person):
         self.assertEqual(False, self.bug.isMuted(self.person))
Beispiel #37
0
 def test_create_packageset_as_user(self):
     # Normal users can't create packagesets
     with person_logged_in(self.factory.makePerson()):
         self.assertRaises(Unauthorized, getattr, self.ps_set, 'new')
Beispiel #38
0
 def test_new_untouched(self):
     bugtask = self.factory.makeBugTask(status=BugTaskStatus.NEW)
     with person_logged_in(bugtask.owner):
         bugtask.bug.linkMessage(self.factory.makeMessage())
     self.assertEqual(BugTaskStatus.NEW, bugtask.status)
Beispiel #39
0
 def test_team_logged_in(self):
     # person_logged_in also works when given teams.
     team = self.factory.makeTeam()
     with person_logged_in(team):
         person = self.getLoggedInPerson()
     self.assertTrue(person.inTeam(team))
Beispiel #40
0
 def test_target_bug_supervisor_can_edit(self):
     person = self.factory.makePerson()
     removeSecurityProxy(self.bug.default_bugtask.target).bug_supervisor = (
         person)
     with person_logged_in(person):
         self.assertTrue(checkPermission('launchpad.Edit', self.bug))
Beispiel #41
0
 def test_is_muted_returns_true_for_muted_users(self):
     # Bug.isMuted() will return True if the person passed to it is muted.
     with person_logged_in(self.person):
         self.bug.mute(self.person, self.person)
         self.assertEqual(True, self.bug.isMuted(self.person))
Beispiel #42
0
 def test_checkSubmitConditions_requires_lock_timestamp(self):
     with person_logged_in(self.factory.makePerson()):
         view = self._makeView()
         view.lock_timestamp = None
         self.assertRaises(UnexpectedFormData, view._checkSubmitConditions)
Beispiel #43
0
 def test_mute_team_fails(self):
     # Muting a subscription for an entire team doesn't work.
     with person_logged_in(self.person):
         team = self.factory.makeTeam(owner=self.person)
         self.assertRaises(AssertionError,
                           self.bug.mute, team, team)
Beispiel #44
0
 def setUp(self):
     super(TestFAQPermissions, self).setUp()
     target = self.factory.makeProduct()
     self.owner = target.owner
     with person_logged_in(self.owner):
         self.faq = self.factory.makeFAQ(target=target)
Beispiel #45
0
 def test_new_user_cannot_edit(self):
     with person_logged_in(self.factory.makePerson()):
         self.assertFalse(checkPermission('launchpad.Edit', self.bug))
Beispiel #46
0
 def getViewContent(view):
     with person_logged_in(view.request.principal):
         return view()
Beispiel #47
0
 def test_disables_current_translation(self):
     # Resetting the current translation clears its "current" flag.
     self.assertTrue(self.current_translation.is_current_ubuntu)
     with person_logged_in(self.factory.makePerson()):
         self.submitForcedEmptySuggestion()
     self.assertFalse(self.current_translation.is_current_ubuntu)
Beispiel #48
0
 def test_checkSubmitConditions_passes(self):
     with person_logged_in(self.factory.makePerson()):
         view = self._makeView()
         view._checkSubmitConditions()
Beispiel #49
0
 def setup_team(team):
     super_team = self.factory.makeTeam(
         owner=team.teamowner,
         membership_policy=TeamMembershipPolicy.RESTRICTED)
     with person_logged_in(team.teamowner):
         super_team.addMember(team, team.teamowner, force_team_add=True)
Beispiel #50
0
 def setup_team(team):
     bug = self.factory.makeBug(
         owner=team.teamowner,
         information_type=InformationType.USERDATA)
     with person_logged_in(team.teamowner):
         bug.default_bugtask.transitionToAssignee(team)
Beispiel #51
0
 def test_random_person_is_unauthorized(self):
     dsp = self.factory.makeDistroSeriesParent()
     person = self.factory.makePerson()
     with person_logged_in(person):
         self.assertRaises(Unauthorized, setattr, dsp, "derived_series",
                           dsp.parent_series)
Beispiel #52
0
 def setup_team(team):
     with person_logged_in(team.teamowner):
         team.createPPA()
 def makeProductFocus(template):
     with person_logged_in(template.productseries.product.owner):
         template.productseries.product.translation_focus = (
             template.productseries)
Beispiel #54
0
 def setupLoggedInRequest(self, user, request, when=None):
     """Test helper to login a user for a request."""
     with person_logged_in(user):
         view = OpenIDCallbackView(user, request)
         view.login(user, when)
 def _create_items(self, num, factory, **kwargs):
     items = []
     with person_logged_in(self.owner):
         for n in range(num):
             items.append(factory(**kwargs))
     return items
Beispiel #56
0
 def test_registry_can_delete(self):
     # A member of ~registry can delete any FAQ.
     expert = self.factory.makePerson(
         member_of=[getUtility(IPersonSet).getByName('registry')])
     with person_logged_in(expert):
         self.assertTrue(check_permission('launchpad.Delete', self.faq))
Beispiel #57
0
 def test_transitionToInformationType_forbidden(self):
     """Raise if specified type is not supported."""
     spec = self.factory.makeSpecification()
     with person_logged_in(spec.owner):
         with ExpectedException(CannotChangeInformationType, '.*'):
             spec.transitionToInformationType(None, spec.owner)
 def assertBuildViewRetryIsExpected(self, build, person, expected):
     with person_logged_in(person):
         build_view = getMultiAdapter(
             (build, self.empty_request), name="+index")
         self.assertEquals(build_view.user_can_retry_build, expected)
Beispiel #59
0
 def test_owner_modify_packageset(self):
     # Packageset owners can modify their packagesets
     with person_logged_in(self.person):
         self.modifyPackageset()
 def add_structural_subscriber(self):
     subscriber = self.factory.makePerson()
     with person_logged_in(subscriber):
         self.target.addSubscription(subscriber, subscriber)