Exemplo n.º 1
0
    def traverse(self, path, first_segment, use_default_referer=True):
        """Traverse to 'path' using a 'LaunchpadRootNavigation' object.

        Using the Zope traversal machinery, traverse to the path given by
        'segments', starting at a `LaunchpadRootNavigation` object.

        CAUTION: Prefer test_traverse to this method, because it correctly
        establishes the global request.

        :param path: A slash-delimited path.
        :param use_default_referer: If True, set the referer attribute in the
            request header to DEFAULT_REFERER = "http://launchpad.dev"
            (otherwise it remains as None)
        :return: The object found.
        """
        # XXX: What's the difference between first_segment and path? -- mbp
        # 2011-06-27.
        extra = {'PATH_INFO': urlappend('/%s' % first_segment, path)}
        if use_default_referer:
            extra['HTTP_REFERER'] = DEFAULT_REFERER
        request = LaunchpadTestRequest(**extra)
        segments = reversed(path.split('/'))
        request.setTraversalStack(segments)
        traverser = LaunchpadRootNavigation(getUtility(ILaunchpadRoot),
                                            request=request)
        return traverser.publishTraverse(request, first_segment)
Exemplo n.º 2
0
 def test_pageid_scope_empty(self):
     request = LaunchpadTestRequest()
     scopes = webapp.ScopesFromRequest(request)
     request.setInWSGIEnvironment('launchpad.pageid', '')
     self.assertTrue(scopes.lookup('pageid:'))
     self.assertFalse(scopes.lookup('pageid:foo'))
     self.assertFalse(scopes.lookup('pageid:foo:bar'))
    def traverse(self, path, first_segment, use_default_referer=True):
        """Traverse to 'path' using a 'LaunchpadRootNavigation' object.

        Using the Zope traversal machinery, traverse to the path given by
        'segments', starting at a `LaunchpadRootNavigation` object.

        CAUTION: Prefer test_traverse to this method, because it correctly
        establishes the global request.

        :param path: A slash-delimited path.
        :param use_default_referer: If True, set the referer attribute in the
            request header to DEFAULT_REFERER = "http://launchpad.dev"
            (otherwise it remains as None)
        :return: The object found.
        """
        # XXX: What's the difference between first_segment and path? -- mbp
        # 2011-06-27.
        extra = {'PATH_INFO': urlappend('/%s' % first_segment, path)}
        if use_default_referer:
            extra['HTTP_REFERER'] = DEFAULT_REFERER
        request = LaunchpadTestRequest(**extra)
        segments = reversed(path.split('/'))
        request.setTraversalStack(segments)
        traverser = LaunchpadRootNavigation(
            getUtility(ILaunchpadRoot), request=request)
        return traverser.publishTraverse(request, first_segment)
Exemplo n.º 4
0
 def test_pageid_scope_empty(self):
     request = LaunchpadTestRequest()
     scopes = webapp.ScopesFromRequest(request)
     request.setInWSGIEnvironment('launchpad.pageid', '')
     self.assertTrue(scopes.lookup('pageid:'))
     self.assertFalse(scopes.lookup('pageid:foo'))
     self.assertFalse(scopes.lookup('pageid:foo:bar'))
Exemplo n.º 5
0
 def setUp(self):
     super(TestBaseLayout, self).setUp()
     self.user = self.factory.makePerson(name='waffles')
     self.request = LaunchpadTestRequest(SERVER_URL='http://launchpad.dev',
                                         PATH_INFO='/~waffles/+layout')
     self.request.setPrincipal(self.user)
     self.context = None
Exemplo n.º 6
0
 def test_navigation(self):
     request = LaunchpadTestRequest()
     request.setTraversalStack([unicode(self.subscription_filter.id)])
     navigation = StructuralSubscriptionNavigation(self.subscription,
                                                   request)
     view = navigation.publishTraverse(request, '+filter')
     self.assertIsNot(None, view)
Exemplo n.º 7
0
 def test_macaroon_extension_added_with_macaroon_query(self):
     # We can signal that we need to acquire a discharge macaroon via a
     # macaroon_caveat_id form parameter, which should add the macaroon
     # extension.
     caveat_id = 'ask SSO'
     form = {
         'macaroon_caveat_id': caveat_id,
         'discharge_macaroon_action': 'field.actions.complete',
         'discharge_macaroon_field': 'field.discharge_macaroon',
     }
     request = LaunchpadTestRequest(form=form, method='POST')
     request.processInputs()
     # This is a hack to make the request.getURL(1) call issued by the view
     # not raise an IndexError.
     request._app_names = ['foo']
     view = StubbedOpenIDLogin(object(), request)
     view()
     extensions = view.openid_request.extensions
     self.assertIsNot(None, extensions)
     macaroon_extension = extensions[1]
     self.assertIsInstance(macaroon_extension, MacaroonRequest)
     self.assertEqual(caveat_id, macaroon_extension.caveat_id)
     return_to_args = dict(
         urlparse.parse_qsl(
             urlparse.urlsplit(view.openid_request.return_to).query))
     self.assertEqual('field.actions.complete',
                      return_to_args['discharge_macaroon_action'])
     self.assertEqual('field.discharge_macaroon',
                      return_to_args['discharge_macaroon_field'])
 def test_navigation(self):
     request = LaunchpadTestRequest()
     request.setTraversalStack([unicode(self.subscription_filter.id)])
     navigation = StructuralSubscriptionNavigation(
         self.subscription, request)
     view = navigation.publishTraverse(request, '+filter')
     self.assertIsNot(None, view)
    def testDefaultToUserAgentSeries(self):
        # The distroseries version found in the user-agent header will
        # be selected by default.

        # Ubuntu version 10.09 in the user-agent should display as getsy
        view = SourcesListEntriesView(
            self.entries,
            LaunchpadTestRequest(HTTP_USER_AGENT='Mozilla/5.0 '
                                 '(X11; U; Linux i686; en-US; rv:1.9.0.10) '
                                 'Gecko/2009042523 Ubuntu/10.09 (whatever) '
                                 'Firefox/3.0.10'))
        view.initialize()

        self.assertEqual(u'getsy', view.default_series_name)

        # Ubuntu version 9.04 in the user-agent should display as feasty
        view = SourcesListEntriesView(
            self.entries,
            LaunchpadTestRequest(HTTP_USER_AGENT='Mozilla/5.0 '
                                 '(X11; U; Linux i686; en-US; rv:1.9.0.10) '
                                 'Gecko/2009042523 Ubuntu/9.04 (whatever) '
                                 'Firefox/3.0.10'))
        view.initialize()

        self.assertEqual(u'feasty', view.default_series_name)
Exemplo n.º 10
0
 def test_with_oops_id(self):
     request = LaunchpadTestRequest()
     request.oopsid = 'OOPS-1X1'
     SystemErrorView(Exception(), request)
     self.assertEquals(500, request.response.getStatus())
     self.assertEquals(
         'OOPS-1X1',
         request.response.getHeader('X-Lazr-OopsId', literal=True))
Exemplo n.º 11
0
 def test_traversal_to_lfa_of_bug_attachment(self):
     # Traversing to the URL provided by a ProxiedLibraryFileAlias of a
     # bug attachament returns a RedirectionView.
     request = LaunchpadTestRequest()
     request.setTraversalStack(['foo.txt'])
     navigation = BugAttachmentFileNavigation(self.bugattachment, request)
     view = navigation.publishTraverse(request, '+files')
     self.assertIsInstance(view, RedirectionView)
Exemplo n.º 12
0
 def test_access_to_unrestricted_file(self):
     # Requests of unrestricted files are redirected to Librarian URLs.
     request = LaunchpadTestRequest()
     request.setTraversalStack(['foo.txt'])
     navigation = BugAttachmentFileNavigation(self.bugattachment, request)
     view = navigation.publishTraverse(request, '+files')
     mo = re.match('^http://.*/\d+/foo.txt$', view.target)
     self.assertIsNot(None, mo)
Exemplo n.º 13
0
 def test_traversal_to_lfa_of_bug_attachment_wrong_filename(self):
     # If the filename provided in the URL does not match the
     # filename of the LibraryFileAlias, a NotFound error is raised.
     request = LaunchpadTestRequest()
     request.setTraversalStack(['nonsense'])
     navigation = BugAttachmentFileNavigation(self.bugattachment, request)
     self.assertRaises(
         NotFound, navigation.publishTraverse, request, '+files')
 def test_traversal_to_lfa_of_bug_attachment_wrong_filename(self):
     # If the filename provided in the URL does not match the
     # filename of the LibraryFileAlias, a NotFound error is raised.
     request = LaunchpadTestRequest()
     request.setTraversalStack(['nonsense'])
     navigation = BugAttachmentFileNavigation(self.bugattachment, request)
     self.assertRaises(
         NotFound, navigation.publishTraverse, request, '+files')
Exemplo n.º 15
0
 def test_pageid_scope_collection(self):
     request = LaunchpadTestRequest()
     scopes = webapp.ScopesFromRequest(request)
     request.setInWSGIEnvironment('launchpad.pageid', 'scoped:thing:#type')
     self.assertTrue(scopes.lookup('pageid:'))
     self.assertTrue(scopes.lookup('pageid:scoped'))
     self.assertTrue(scopes.lookup('pageid:scoped:thing'))
     self.assertTrue(scopes.lookup('pageid:scoped:thing:#type'))
     self.assertFalse(scopes.lookup('pageid:scoped:thing:#type:other'))
 def test_access_to_unrestricted_file(self):
     # Requests of unrestricted files are redirected to Librarian URLs.
     request = LaunchpadTestRequest()
     request.setTraversalStack(['foo.txt'])
     navigation = BugAttachmentFileNavigation(
         self.bugattachment, request)
     view = navigation.publishTraverse(request, '+files')
     mo = re.match('^http://.*/\d+/foo.txt$', view.target)
     self.assertIsNot(None, mo)
 def test_traversal_to_lfa_of_bug_attachment(self):
     # Traversing to the URL provided by a ProxiedLibraryFileAlias of a
     # bug attachament returns a RedirectionView.
     request = LaunchpadTestRequest()
     request.setTraversalStack(['foo.txt'])
     navigation = BugAttachmentFileNavigation(
         self.bugattachment, request)
     view = navigation.publishTraverse(request, '+files')
     self.assertIsInstance(view, RedirectionView)
Exemplo n.º 18
0
 def test_pageid_scope_collection(self):
     request = LaunchpadTestRequest()
     scopes = webapp.ScopesFromRequest(request)
     request.setInWSGIEnvironment('launchpad.pageid', 'scoped:thing:#type')
     self.assertTrue(scopes.lookup('pageid:'))
     self.assertTrue(scopes.lookup('pageid:scoped'))
     self.assertTrue(scopes.lookup('pageid:scoped:thing'))
     self.assertTrue(scopes.lookup('pageid:scoped:thing:#type'))
     self.assertFalse(scopes.lookup('pageid:scoped:thing:#type:other'))
 def _createView(self, pofile, form=None):
     # All exports can be requested by an unprivileged user.
     login_person(self.factory.makePerson())
     if form is None:
         request = LaunchpadTestRequest()
     else:
         request = LaunchpadTestRequest(method='POST', form=form)
     view = POExportView(pofile, request)
     view.initialize()
     return view
Exemplo n.º 20
0
    def test_admin_can_accept_partner_upload(self):
        # An admin can always accept packages, even for the
        # partner archive (note, this is *not* an archive admin).
        login('*****@*****.**')

        package_upload_id = self.partner_spr.package_upload.id
        self.form['QUEUE_ID'] = [package_upload_id]
        request = LaunchpadTestRequest(form=self.form)
        request.method = 'POST'
        self.setupQueueView(request)
        self.assertStatus(package_upload_id, PackageUploadStatus.DONE)
Exemplo n.º 21
0
 def test_cannot_reject_without_comment(self):
     login_person(self.proposed_queue_admin)
     package_upload_id = self.proposed_spr.package_upload.id
     form = {
         'Reject': 'Reject',
         'QUEUE_ID': [package_upload_id]}
     request = LaunchpadTestRequest(form=form)
     request.method = 'POST'
     view = self.setupQueueView(request)
     self.assertEqual('Rejection comment required.', view.error)
     self.assertStatus(package_upload_id, PackageUploadStatus.NEW)
Exemplo n.º 22
0
 def test_reject_with_comment(self):
    login_person(self.proposed_queue_admin)
    package_upload_id = self.proposed_spr.package_upload.id
    form = {
        'Reject': 'Reject',
        'rejection_comment': 'Because I can.',
        'QUEUE_ID': [package_upload_id]}
    request = LaunchpadTestRequest(form=form)
    request.method = 'POST'
    self.setupQueueView(request)
    self.assertStatus(package_upload_id, PackageUploadStatus.REJECTED)
Exemplo n.º 23
0
 def match(self, query_string):
     args = dict(urlparse.parse_qsl(query_string))
     request = LaunchpadTestRequest(form=args)
     # This is a hack to make the request.getURL(1) call issued by the view
     # not raise an IndexError.
     request._app_names = ['foo']
     view = StubbedOpenIDLogin(object(), request)
     view()
     escaped_args = tuple(map(urllib.quote, args.items()[0]))
     expected_fragment = urllib.quote('%s=%s' % escaped_args)
     return Contains(
         expected_fragment).match(view.openid_request.return_to)
 def test_mute_help_available(self):
     # There is a help link available next to the mute/unmute button.
     person = self.factory.makePerson()
     with feature_flags():
         with person_logged_in(person):
             self.bug.subscribe(person, person, level=BugNotificationLevel.METADATA)
             self.bug.mute(person, person)
             request = LaunchpadTestRequest()
             request.features = get_relevant_feature_controller()
             view = create_initialized_view(self.bug, name="+portlet-subscription", request=request)
             html = view.render()
     self.assertTrue('class="sprite maybe action-icon mute-help"' in html)
Exemplo n.º 25
0
    def test_is_browser(self):
        # No User-Agent: header.
        request = LaunchpadTestRequest()
        self.assertFalse(is_browser(request))

        # Browser User-Agent: header.
        request = LaunchpadTestRequest(
            environ={'USER_AGENT': 'Mozilla/42 Extreme Edition'})
        self.assertTrue(is_browser(request))

        # Robot User-Agent: header.
        request = LaunchpadTestRequest(environ={'USER_AGENT': 'BottyBot'})
        self.assertFalse(is_browser(request))
Exemplo n.º 26
0
 def setUp(self):
     TestCaseWithFactory.setUp(self)
     self.request = LaunchpadTestRequest()
     # We create an account without a Person here just to make sure the
     # person and account created later don't end up with the same IDs,
     # which could happen since they're both sequential.
     # We need them to be different for one of our tests here.
     getUtility(IAccountSet).new(
         AccountCreationRationale.UNKNOWN, 'Dummy name')
     person = self.factory.makePerson('*****@*****.**')
     self.assertNotEqual(person.id, person.account.id)
     self.principal = LaunchpadPrincipal(
         person.account.id, person.displayname,
         person.displayname, person)
Exemplo n.º 27
0
    def test_partner_admin_can_accept_partner_upload(self):
        # A person with queue admin access for partner
        # can accept uploads to the partner archive.
        login_person(self.partner_queue_admin)
        self.assertTrue(
            self.partner_archive.canAdministerQueue(
                self.partner_queue_admin, self.partner_spr.component))

        package_upload_id = self.partner_spr.package_upload.id
        self.form['QUEUE_ID'] = [package_upload_id]
        request = LaunchpadTestRequest(form=self.form)
        request.method = 'POST'
        self.setupQueueView(request)
        self.assertStatus(package_upload_id, PackageUploadStatus.DONE)
Exemplo n.º 28
0
 def test_pape_extension_added_with_reauth_query(self):
     # We can signal that a request should be reauthenticated via
     # a reauth URL parameter, which should add PAPE extension's
     # max_auth_age paramter.
     request = LaunchpadTestRequest(QUERY_STRING='reauth=1')
     # This is a hack to make the request.getURL(1) call issued by the view
     # not raise an IndexError.
     request._app_names = ['foo']
     view = StubbedOpenIDLogin(object(), request)
     view()
     extensions = view.openid_request.extensions
     self.assertIsNot(None, extensions)
     pape_extension = extensions[1]
     self.assertIsInstance(pape_extension, pape.Request)
     self.assertEqual(0, pape_extension.max_auth_age)
Exemplo n.º 29
0
 def test_zope_i18n_Messages_are_interpolated(self):
     # Views can use zope.i18nmessageid.Message as their title when they
     # want to i18n it, but when that's the case we need to
     # translate/interpolate the string.
     class TestView:
         """A test view that uses a Message as its page_title."""
         page_title = Message(
             '${name} test', mapping={'name': 'breadcrumb'})
         __name__ = 'test-page'
     test_view = TestView()
     request = LaunchpadTestRequest()
     request.traversed_objects = [self.product, test_view]
     hierarchy_view = Hierarchy(self.product, request)
     breadcrumb = hierarchy_view.makeBreadcrumbForRequestedPage()
     self.assertEquals(breadcrumb.text, 'breadcrumb test')
Exemplo n.º 30
0
 def test_logs_to_timeline(self):
     # Beginning an OpenID association makes an HTTP request to the
     # OP, so it's a potentially long action. It is logged to the
     # request timeline.
     request = LaunchpadTestRequest()
     # This is a hack to make the request.getURL(1) call issued by the view
     # not raise an IndexError.
     request._app_names = ['foo']
     view = StubbedOpenIDLogin(object(), request)
     view()
     start, stop = get_request_timeline(request).actions[-2:]
     self.assertEqual(start.category, 'openid-association-begin-start')
     self.assertEqual(start.detail, 'http://testopenid.dev/')
     self.assertEqual(stop.category, 'openid-association-begin-stop')
     self.assertEqual(stop.detail, 'http://testopenid.dev/')
Exemplo n.º 31
0
def create_view(context, name, form=None, layer=None, server_url=None,
                method='GET', principal=None, query_string='', cookie='',
                request=None, path_info='/', current_request=False,
                rootsite=None, **kwargs):
    """Return a view based on the given arguments.

    :param context: The context for the view.
    :param name: The web page the view should handle.
    :param form: A dictionary with the form keys.
    :param layer: The layer where the page we are interested in is located.
    :param server_url: The URL from where this request was done.
    :param method: The method used in the request. Defaults to 'GET'.
    :param principal: The principal for the request, default to the
        unauthenticated principal.
    :param query_string: The query string for the request.
    :param cookie: The HTTP_COOKIE value for the request.
    :param request: Use this request instead of creating a new one.
    :param path_info: The PATH_INFO value for the request.
    :param current_request: If True, the request will be set as the current
        interaction.
    :param **kwargs: Any other parameter for the request.
    :return: The view class for the given context and the name.
    """
    if request is None:
        request = LaunchpadTestRequest(
            form=form, SERVER_URL=server_url, QUERY_STRING=query_string,
            HTTP_COOKIE=cookie, method=method, PATH_INFO=path_info, **kwargs)
    if principal is not None:
        request.setPrincipal(principal)
    else:
        request.setPrincipal(
            getUtility(IPlacelessAuthUtility).unauthenticatedPrincipal())
    if layer is None:
        # If a layer hasn't been specified, try to get the layer for the
        # rootsite.
        if rootsite is None:
            # If we haven't been told a site, try to get it from the canonical
            # url data of the object.
            obj_urldata = ICanonicalUrlData(context, None)
            if obj_urldata is not None:
                rootsite = obj_urldata.rootsite
        layer = layer_for_rootsite(rootsite)
    if layer is not None:
        setFirstLayer(request, layer)
    if current_request:
        endInteraction()
        newInteraction(request)
    return getMultiAdapter((context, request), name=name)
Exemplo n.º 32
0
    def test_proposed_series_admin_can_accept_that_series_upload(self):
        # A person with queue admin access for proposed for one series can
        # accept uploads to that series.
        login_person(self.proposed_series_queue_admin)
        self.assertTrue(
            self.main_archive.canAdministerQueue(
                self.proposed_series_queue_admin,
                pocket=PackagePublishingPocket.PROPOSED,
                distroseries=self.second_series))

        package_upload_id = self.proposed_series_spr.package_upload.id
        self.form['QUEUE_ID'] = [package_upload_id]
        request = LaunchpadTestRequest(form=self.form)
        request.method = 'POST'
        self.setupQueueView(request, series=self.second_series)
        self.assertStatus(package_upload_id, PackageUploadStatus.DONE)
Exemplo n.º 33
0
    def test_json_cache_collects_related_features_from_all_views(self):
        # A typical page includes data from more than one view,
        # for example, from macros. Related features from these sub-views
        # are included in the JSON cache.
        class TestView(LaunchpadView):
            related_features = {'test_feature': False}

        class TestView2(LaunchpadView):
            related_features = {'test_feature_2': False}

        self.useFixture(
            FeatureFixture({},
                           self.makeFeatureFlagDictionaries(u'', u'on'),
                           override_scope_lookup=lambda scope_name: True))
        request = LaunchpadTestRequest()
        view = TestView(object(), request)
        TestView2(object(), request)
        with person_logged_in(self.factory.makePerson()):
            self.assertEqual(
                '{"related_features": '
                '{"test_feature_2": {"url": "http://wiki.lp.dev/LEP/sample2",'
                ' "is_beta": true, "value": "on", "title": "title"}, '
                '"test_feature": {"url": "http://wiki.lp.dev/LEP/sample", '
                '"is_beta": true, "value": "on", "title": "title"}}}',
                view.getCacheJSON())
 def getViewContentXmlHttpRequest(self, context, view_name, person):
     # Helper method to request a view via an XMLHttpRequest.
     with person_logged_in(person):
         request = LaunchpadTestRequest(
             HTTP_X_REQUESTED_WITH='XMLHttpRequest')
         view = create_initialized_view(context, view_name, request=request)
         return view()
Exemplo n.º 35
0
 def test_access_to_restricted_file(self):
     # Requests of restricted files are redirected to librarian URLs
     # with tokens.
     lfa_with_parent = getMultiAdapter(
         (self.bugattachment.libraryfile, self.bugattachment),
         ILibraryFileAliasWithParent)
     lfa_with_parent.restricted = True
     self.bug.setPrivate(True, self.bug_owner)
     transaction.commit()
     request = LaunchpadTestRequest()
     request.setTraversalStack(['foo.txt'])
     navigation = BugAttachmentFileNavigation(self.bugattachment, request)
     view = navigation.publishTraverse(request, '+files')
     mo = re.match(
         '^https://.*.restricted.*/\d+/foo.txt\?token=.*$', view.target)
     self.assertIsNot(None, mo)
Exemplo n.º 36
0
 def test_getCacheJSON_context_overrides_objects(self):
     request = LaunchpadTestRequest()
     view = LaunchpadView(self.getCanada(), request)
     IJSONRequestCache(request).objects['context'] = True
     with person_logged_in(self.factory.makePerson()):
         json_dict = simplejson.loads(view.getCacheJSON())['context']
     self.assertIsCanada(json_dict)
 def test_access_to_restricted_file(self):
     # Requests of restricted files are redirected to librarian URLs
     # with tokens.
     lfa_with_parent = getMultiAdapter(
         (self.bugattachment.libraryfile, self.bugattachment),
         ILibraryFileAliasWithParent)
     lfa_with_parent.restricted = True
     self.bug.setPrivate(True, self.bug_owner)
     transaction.commit()
     request = LaunchpadTestRequest()
     request.setTraversalStack(['foo.txt'])
     navigation = BugAttachmentFileNavigation(self.bugattachment, request)
     view = navigation.publishTraverse(request, '+files')
     mo = re.match(
         '^https://.*.restricted.*/\d+/foo.txt\?token=.*$', view.target)
     self.assertIsNot(None, mo)
Exemplo n.º 38
0
 def test_getCacheJSON_non_resource_object(self):
     request = LaunchpadTestRequest()
     view = LaunchpadView(object(), request)
     IJSONRequestCache(request).objects['my_bool'] = True
     with person_logged_in(self.factory.makePerson()):
         self.assertEqual('{"related_features": {}, "my_bool": true}',
                          view.getCacheJSON())
Exemplo n.º 39
0
 def setUp(self):
     super(TestVocabularyPickerWidget, self).setUp()
     self.context = self.factory.makeTeam()
     self.vocabulary_registry = getVocabularyRegistry()
     self.vocabulary = self.vocabulary_registry.get(self.context,
                                                    'ValidTeamOwner')
     self.request = LaunchpadTestRequest()
Exemplo n.º 40
0
 def _createFeed(self):
     """Create and return a RevisionListingFeed instance."""
     # The FeedBase class determins the feed type by the end of the
     # requested URL, so forcing .atom here.
     return RevisionListingFeed(
         None,
         LaunchpadTestRequest(SERVER_URL="http://example.com/fake.atom"))
Exemplo n.º 41
0
 def test_getCacheJSON_resource_object(self):
     request = LaunchpadTestRequest()
     view = LaunchpadView(object(), request)
     IJSONRequestCache(request).objects['country'] = self.getCanada()
     with person_logged_in(self.factory.makePerson()):
         json_dict = simplejson.loads(view.getCacheJSON())['country']
     self.assertIsCanada(json_dict)
 def setUp(self):
     super(TestBaseLayout, self).setUp()
     self.user = self.factory.makePerson(name='waffles')
     self.request = LaunchpadTestRequest(
         SERVER_URL='http://launchpad.dev',
         PATH_INFO='/~waffles/+layout')
     self.request.setPrincipal(self.user)
     self.context = None
 def test_access_to_restricted_file_unauthorized(self):
     # If a user cannot access the bug attachment itself, he can neither
     # access the restricted Librarian file.
     lfa_with_parent = getMultiAdapter(
         (self.bugattachment.libraryfile, self.bugattachment),
         ILibraryFileAliasWithParent)
     lfa_with_parent.restricted = True
     self.bug.setPrivate(True, self.bug_owner)
     transaction.commit()
     user = self.factory.makePerson()
     login_person(user)
     self.assertRaises(Unauthorized, getattr, self.bugattachment, 'title')
     request = LaunchpadTestRequest()
     request.setTraversalStack(['foo.txt'])
     navigation = BugAttachmentFileNavigation(self.bugattachment, request)
     self.assertRaises(
         Unauthorized, navigation.publishTraverse, request, '+files')
Exemplo n.º 44
0
 def test_sreg_fields(self):
     # We request the user's email address and Full Name (through the SREG
     # extension) to the OpenID provider so that we can automatically
     # register unseen OpenID identities.
     request = LaunchpadTestRequest()
     # This is a hack to make the request.getURL(1) call issued by the view
     # not raise an IndexError.
     request._app_names = ['foo']
     view = StubbedOpenIDLogin(object(), request)
     view()
     extensions = view.openid_request.extensions
     self.assertIsNot(None, extensions)
     sreg_extension = extensions[0]
     self.assertIsInstance(sreg_extension, sreg.SRegRequest)
     self.assertEquals(['email', 'fullname'],
                       sorted(sreg_extension.allRequestedFields()))
     self.assertEquals(sorted(sreg_extension.required),
                       sorted(sreg_extension.allRequestedFields()))
 def test_help_links_render(self):
     # The values in a view's help_links dictionary are rendered in the
     # default generic-edit template.
     user = self.factory.makePerson()
     request = LaunchpadTestRequest(PATH_INFO="/")
     request.setPrincipal(user)
     view = TestHelpLinksView(user, request)
     view.initialize()
     root = html.fromstring(view.render())
     [nickname_help_link] = root.cssselect(
         "label[for$=nickname] ~ a[target=help]")
     self.assertEqual(
         u"http://widget.example.com/name",
         nickname_help_link.get("href"))
     [displayname_help_link] = root.cssselect(
         "label[for$=displayname] ~ a[target=help]")
     self.assertEqual(
         u"http://widget.example.com/displayname",
         displayname_help_link.get("href"))
Exemplo n.º 46
0
    def test_proposed_series_admin_cannot_accept_other_series_upload(self):
        # A person with queue admin access for proposed for one series
        # cannot necessarily accept uploads to other series.
        login_person(self.proposed_series_queue_admin)
        self.assertFalse(
            self.main_archive.canAdministerQueue(
                self.proposed_series_queue_admin,
                pocket=PackagePublishingPocket.PROPOSED,
                distroseries=self.test_publisher.distroseries))

        package_upload_id = self.proposed_spr.package_upload.id
        self.form['QUEUE_ID'] = [package_upload_id]
        request = LaunchpadTestRequest(form=self.form)
        request.method = 'POST'
        view = self.setupQueueView(request)

        self.assertEqual(
            "You do not have permission to act on queue items.", view.error)
        self.assertStatus(package_upload_id, PackageUploadStatus.NEW)
Exemplo n.º 47
0
def make_fake_request(url, traversed_objects=None):
    """Return a fake request object for menu testing.

    :param traversed_objects: A list of objects that becomes the request's
        traversed_objects attribute.
    """
    url_parts = urlsplit(url)
    server_url = '://'.join(url_parts[0:2])
    path_info = url_parts[2]
    request = LaunchpadTestRequest(
        SERVER_URL=server_url,
        PATH_INFO=path_info)
    request._traversed_names = path_info.split('/')[1:]
    if traversed_objects is not None:
        request.traversed_objects = traversed_objects[:]
    # After making the request, setup a new interaction.
    endInteraction()
    newInteraction(request)
    return request
Exemplo n.º 48
0
    def test_partner_admin_cannot_accept_main_upload(self):
        # A person with queue admin access for partner cannot necessarily
        # accept uploads to main.
        login_person(self.partner_queue_admin)
        self.assertFalse(
            self.main_archive.canAdministerQueue(
                self.partner_queue_admin, self.main_spr.component))

        package_upload_id = self.main_spr.package_upload.id
        self.form['QUEUE_ID'] = [package_upload_id]
        request = LaunchpadTestRequest(form=self.form)
        request.method = 'POST'
        view = self.setupQueueView(request)

        self.assertEquals(
            html_escape(
                "FAILED: main-upload (You have no rights to accept "
                "component(s) 'main')"),
            view.request.response.notifications[0].message)
        self.assertStatus(package_upload_id, PackageUploadStatus.NEW)
Exemplo n.º 49
0
    def test_proposed_admin_cannot_accept_release_upload(self):
        # A person with queue admin access for proposed cannot necessarly
        # accept uploads to the release pocket.
        login_person(self.proposed_queue_admin)
        self.assertFalse(
            self.main_archive.canAdministerQueue(
                self.proposed_queue_admin,
                pocket=PackagePublishingPocket.RELEASE))

        package_upload_id = self.main_spr.package_upload.id
        self.form['QUEUE_ID'] = [package_upload_id]
        request = LaunchpadTestRequest(form=self.form)
        request.method = 'POST'
        view = self.setupQueueView(request)

        self.assertEqual(
            html_escape(
                "FAILED: main-upload (You have no rights to accept "
                "component(s) 'main')"),
            view.request.response.notifications[0].message)
        self.assertStatus(package_upload_id, PackageUploadStatus.NEW)
Exemplo n.º 50
0
 def test_WebServiceRequest_uses_LaunchpadDatabasePolicy(self):
     """WebService requests with a session cookie will use the
     standard LaunchpadDatabasePolicy so their database queries
     can be outsourced to a slave database when possible.
     """
     api_prefix = getUtility(IWebServiceConfiguration).active_versions[0]
     server_url = "http://api.launchpad.dev/%s" % api_prefix
     request = LaunchpadTestRequest(SERVER_URL=server_url)
     newInteraction(request)
     try:
         # First, generate a valid session cookie.
         ISession(request)["whatever"]["whatever"] = "whatever"
         # Then stuff it into the request where we expect to
         # find it. The database policy is only interested if
         # a session cookie was sent with the request, not it
         # one has subsequently been set in the response.
         request._cookies = request.response._cookies
         setFirstLayer(request, WebServiceLayer)
         policy = IDatabasePolicy(request)
         self.assertIsInstance(policy, LaunchpadDatabasePolicy)
     finally:
         endInteraction()
Exemplo n.º 51
0
    def test_proposed_admin_can_accept_proposed_upload(self):
        # A person with queue admin access for proposed can accept uploads
        # to the proposed pocket for any series.
        login_person(self.proposed_queue_admin)
        self.assertTrue(
            self.main_archive.canAdministerQueue(
                self.proposed_queue_admin,
                pocket=PackagePublishingPocket.PROPOSED))
        for distroseries in self.test_publisher.distroseries.distribution:
            self.assertTrue(
                self.main_archive.canAdministerQueue(
                    self.proposed_queue_admin,
                    pocket=PackagePublishingPocket.PROPOSED,
                    distroseries=distroseries))

        for spr in (self.proposed_spr, self.proposed_series_spr):
            package_upload_id = spr.package_upload.id
            self.form['QUEUE_ID'] = [package_upload_id]
            request = LaunchpadTestRequest(form=self.form)
            request.method = 'POST'
            self.setupQueueView(request, series=spr.upload_distroseries)
            self.assertStatus(package_upload_id, PackageUploadStatus.DONE)
 def setUp(self):
     TestCaseWithFactory.setUp(self)
     self.request = LaunchpadTestRequest()
     # We create an account without a Person here just to make sure the
     # person and account created later don't end up with the same IDs,
     # which could happen since they're both sequential.
     # We need them to be different for one of our tests here.
     getUtility(IAccountSet).new(
         AccountCreationRationale.UNKNOWN, 'Dummy name')
     person = self.factory.makePerson('*****@*****.**')
     self.failIfEqual(person.id, person.account.id)
     self.principal = LaunchpadPrincipal(
         person.account.id, person.displayname,
         person.displayname, person)