Exemplo n.º 1
0
    def initialize_admin_view(self, enabled=True):
        # Initialize the admin view with the supplied params.
        method = 'POST'
        form = {
            'field.actions.update': 'update',
        }

        if enabled:
            form['field.enabled'] = 'on'
        else:
            form['field.enabled'] = 'off'

        view = DistroArchSeriesAdminView(
            self.das, LaunchpadTestRequest(method=method, form=form))
        view.initialize()
        return view
Exemplo n.º 2
0
    def test_detects_sourcepackage_and_productseries(self):
        # Detect if no source package or productseries was selected.
        potemplate = self.factory.makePOTemplate()
        sourcepackage = self.factory.makeSourcePackage()

        view = POTemplateAdminView(potemplate, LaunchpadTestRequest())
        data = self._makeData(
            potemplate,
            distroseries=sourcepackage.distroseries,
            sourcepackagename=sourcepackage.sourcepackagename,
            productseries=potemplate.productseries)
        view.validate(data)
        self.assertEqual([
            u'Choose a distribution release series or a project '
            u'release series, but not both.'
        ], view.errors)
Exemplo n.º 3
0
def setupBrowserFreshLogin(user):
    """Create a test browser with a recently logged in user.

    The request is not shared by the browser, so we create
    a session of the test request and set a cookie to reference
    the session in the test browser.
    """
    request = LaunchpadTestRequest()
    session = ISession(request)
    authdata = session['launchpad.authenticateduser']
    authdata['logintime'] = datetime.utcnow()
    namespace = config.launchpad_session.cookie
    cookie = '%s=%s' % (namespace, session.client_id)
    browser = setupBrowserForUser(user)
    browser.addHeader('Cookie', cookie)
    return browser
 def test_bugs_with_patches_count(self):
     # Bugs with patches that have the status FIXRELEASED, INVALID,
     # WONTFIX, or UNKNOWN are not counted in
     # BugListingPortletStatsView.bugs_with_patches_count, bugs
     # with all other statuses are counted.
     number_of_bugs_shown = 0
     for bugtask_status in DISPLAY_BUG_STATUS_FOR_PATCHES:
         if DISPLAY_BUG_STATUS_FOR_PATCHES[bugtask_status]:
             number_of_bugs_shown += 1
         self.makeBugWithPatch(bugtask_status)
         view = BugListingPortletStatsView(self.product,
                                           LaunchpadTestRequest())
         self.assertEqual(
             view.bugs_with_patches_count, number_of_bugs_shown,
             "Unexpected number of bugs with patches displayed for status "
             "%s" % bugtask_status)
Exemplo n.º 5
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.º 6
0
    def test_detects_domain_clash_on_productseries_change(self):
        # Detect changing to a productseries that already has a template with
        # the same translation domain.
        translation_domain = self.factory.getUniqueString()
        existing_potemplate = self.factory.makePOTemplate(
            translation_domain=translation_domain)
        new_series = existing_potemplate.productseries
        potemplate = self.factory.makePOTemplate(
            translation_domain=translation_domain)

        view = POTemplateAdminView(potemplate, LaunchpadTestRequest())
        data = self._makeData(potemplate, productseries=new_series)
        view.validate(data)
        self.assertEqual(
            [u'Series already has a template with that same domain.'],
            view.errors)
Exemplo n.º 7
0
    def test_disconnect_logs_oops(self):
        # Ensure that OOPS reports are generated for database
        # disconnections, as per Bug #373837.
        request = LaunchpadTestRequest()
        publication = WebServicePublication(None)
        dbadapter.set_request_started()
        try:
            raise DisconnectionError('Fake')
        except DisconnectionError:
            self.assertRaises(Retry, publication.handleException, None,
                              request, sys.exc_info(), True)
        dbadapter.clear_request_started()
        self.assertEqual(1, len(self.oopses))
        oops = self.oopses[0]

        # Ensure the OOPS mentions the correct exception
        self.assertEqual(oops['type'], "DisconnectionError")
 def test_setUpOptions_product_checked(self):
     # The product radio button is selected when the form is submitted
     # when the target field's value is 'product'.
     form = {
         'field.target': 'product',
     }
     self.widget.request = LaunchpadTestRequest(form=form)
     self.widget.setUpSubWidgets()
     self.widget.setUpOptions()
     self.assertEqual(
         '<input class="radioType" '
         'id="field.target.option.package" name="field.target" '
         'type="radio" value="package" />', self.widget.options['package'])
     self.assertEqual(
         '<input class="radioType" checked="checked" '
         'id="field.target.option.product" name="field.target" '
         'type="radio" value="product" />', self.widget.options['product'])
Exemplo n.º 9
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'
            context = self.product

        test_view = TestView()
        request = LaunchpadTestRequest()
        request.traversed_objects = [self.product, test_view]
        hierarchy_view = Hierarchy(test_view, request)
        [breadcrumb] = hierarchy_view.makeBreadcrumbsForRequestedPage()
        self.assertEqual(breadcrumb.text, 'breadcrumb test')
Exemplo n.º 10
0
 def assertEmptyResultSetsWorking(self, range_factory):
     # getSlice() and getSliceByIndex() return empty ShadowedLists.
     sliced = range_factory.getSlice(1)
     self.assertEqual([], sliced.values)
     self.assertEqual([], sliced.shadow_values)
     sliced = range_factory.getSliceByIndex(0, 1)
     self.assertEqual([], sliced.values)
     self.assertEqual([], sliced.shadow_values)
     # The endpoint memos are empty strings.
     request = LaunchpadTestRequest()
     batchnav = BatchNavigator(range_factory.resultset,
                               request,
                               size=3,
                               range_factory=range_factory)
     first, last = range_factory.getEndpointMemos(batchnav.batch)
     self.assertEqual('', first)
     self.assertEqual('', last)
Exemplo n.º 11
0
 def test_json_cache_populated_on_subscribe(self):
     # To aid with debugging the event_key of subscriptions are added to
     # the JSON cache.
     request = LaunchpadTestRequest()
     cache = IJSONRequestCache(request)
     event1 = FakeEvent()
     ILongPollSubscriber(request).subscribe(event1)  # Side-effects!
     self.assertThat(cache.objects, Contains("longpoll"))
     self.assertThat(cache.objects["longpoll"], Contains("key"))
     self.assertThat(cache.objects["longpoll"], Contains("subscriptions"))
     self.assertEqual([event1.event_key],
                      cache.objects["longpoll"]["subscriptions"])
     # More events can be subscribed.
     event2 = FakeEvent()
     ILongPollSubscriber(request).subscribe(event2)
     self.assertEqual([event1.event_key, event2.event_key],
                      cache.objects["longpoll"]["subscriptions"])
Exemplo n.º 12
0
 def test_setUpOptions_ppa_checked(self):
     # The ppa radio button is selected when the form is submitted when
     # the archive field's value is 'ppa'.
     form = {
         "field.archive": "ppa",
     }
     self.widget.request = LaunchpadTestRequest(form=form)
     self.widget.setUpSubWidgets()
     self.widget.setUpOptions()
     self.assertEqual(
         '<input class="radioType" ' +
         'id="field.archive.option.primary" name="field.archive" '
         'type="radio" value="primary" />', self.widget.options["primary"])
     self.assertEqual(
         '<input class="radioType" checked="checked" ' +
         'id="field.archive.option.ppa" name="field.archive" '
         'type="radio" value="ppa" />', self.widget.options["ppa"])
 def test_ajax_action_failure(self):
     # When there are errors performing the action, these are recorded.
     extra = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}
     request = LaunchpadTestRequest(method='POST',
                                    form={
                                        'field.actions.test': 'Test',
                                        'field.single_line': 'failure'
                                    },
                                    **extra)
     view = TestFormView({}, request)
     view.initialize()
     self.assertEqual(
         {
             "error_summary": "There is 1 error.",
             "errors": {},
             "form_wide_errors": ["An action error"]
         }, simplejson.loads(view.form_result))
Exemplo n.º 14
0
    def test_view_beta_features_simple(self):
        class TestView(LaunchpadView):
            related_features = {'test_feature': False}

        self.useFixture(
            FeatureFixture({},
                           self.makeFeatureFlagDictionaries(u'', u'on'),
                           override_scope_lookup=lambda scope_name: True))
        request = LaunchpadTestRequest()
        view = TestView(object(), request)
        expected_beta_features = [{
            'url': 'http://wiki.lp.dev/LEP/sample',
            'is_beta': True,
            'value': u'on',
            'title': 'title'
        }]
        self.assertEqual(expected_beta_features, view.beta_features)
Exemplo n.º 15
0
 def test_limitedView_visible_attributes(self):
     """Users with LimitedView can know identifying information like name,
     displayname, and unique_name, but cannot know other information like
     team members.
     """
     some_person = self.factory.makePerson()
     request = LaunchpadTestRequest()
     # First login as a person who has limitedView permission.
     precache_permission_for_objects(request, 'launchpad.LimitedView',
                                     [self.priv_team])
     login_person(some_person, participation=request)
     self.assertEqual('priv-team', self.priv_team.name)
     self.assertEqual('Priv Team', self.priv_team.displayname)
     self.assertEqual('Priv Team (priv-team)',
                      self.priv_team.unique_displayname)
     self.assertIsNone(self.priv_team.icon)
     self.assertRaises(Unauthorized, getattr, self.priv_team, 'allmembers')
Exemplo n.º 16
0
 def test_access_to_restricted_file_unauthorized(self):
     # If a user cannot access the bug attachment itself, they cannot
     # access the restricted Librarian file either.
     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.º 17
0
    def test_detects_name_clash_on_sourcepackage_change(self):
        # Detect changing to a source package that already has a template of
        # the same name.
        sourcepackage = self.factory.makeSourcePackage()
        existing_potemplate = self.factory.makePOTemplate(
            sourcepackage=sourcepackage)
        potemplate = self.factory.makePOTemplate(
            distroseries=sourcepackage.distroseries,
            name=existing_potemplate.name)

        view = POTemplateEditView(potemplate, LaunchpadTestRequest())
        data = self._makeData(
            potemplate, sourcepackagename=sourcepackage.sourcepackagename)
        view.validate(data)
        self.assertEqual(
            [u'Source package already has a template with that same name.'],
            view.errors)
Exemplo n.º 18
0
 def test_gather_params(self):
     # If the currently requested URL includes a query string, the
     # parameters in the query string must be included when constructing
     # the params mapping (which is then used to complete the open ID
     # response).  OpenIDCallbackView._gather_params does that gathering.
     request = LaunchpadTestRequest(
         SERVER_URL='http://example.com',
         QUERY_STRING='foo=bar',
         form={'starting_url': 'http://launchpad.dev/after-login'},
         environ={'PATH_INFO': '/'})
     view = OpenIDCallbackView(context=None, request=None)
     params = view._gather_params(request)
     expected_params = {
         'starting_url': 'http://launchpad.dev/after-login',
         'foo': 'bar',
     }
     self.assertEquals(params, expected_params)
 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"))
    def initialize_admin_view(self, private=True):
        """Initialize the admin view to set the privacy.."""
        method = 'POST'
        form = {
            'field.enabled': 'on',
            'field.actions.save': 'Save',
            }

        if private is True:
            form['field.private'] = 'on'
        else:
            form['field.private'] = 'off'

        view = ArchiveAdminView(self.ppa, LaunchpadTestRequest(
            method=method, form=form))
        view.initialize()
        return view
Exemplo n.º 21
0
 def test_self_subscription(self):
     # Make a subscription directly for the user and see what we record.
     user = self.factory.makePerson()
     target = self.factory.makeProduct()
     request = LaunchpadTestRequest()
     with person_logged_in(user):
         sub = target.addBugSubscription(user, user)
     expose_user_subscriptions_to_js(user, [sub], request)
     info = IJSONRequestCache(request).objects['subscription_info']
     filter_info = info[0]['filters'][0]
     self.assertFalse(filter_info['subscriber_is_team'])
     self.assertEqual(filter_info['subscriber_title'], user.title)
     self.assertFalse(filter_info['can_mute'])
     self.assertFalse(filter_info['is_muted'])
     self.assertEqual(filter_info['subscriber_link'],
                      absoluteURL(user, IWebServiceClientRequest(request)))
     self.assertEqual(filter_info['subscriber_url'],
                      canonical_url(user, rootsite='mainsite'))
    def test_translation_team(self):
        # Just having a group doesn't mean there's a translation
        # team as well.
        group = self.factory.makeTranslationGroup(
            self.distroseries.distribution.owner, url=None)
        self.distroseries.distribution.translationgroup = group
        self.assertIsNone(self.view.translation_team)

        # Setting a translator for this languages makes it
        # appear as the translation_team.
        team = self.factory.makeTeam()
        translator = getUtility(ITranslatorSet).new(
            group, self.language, team)
        # Recreate the view because we are using a cached property.
        self.view = DistroSeriesLanguageView(
            self.dsl, LaunchpadTestRequest())
        self.view.initialize()
        self.assertEqual(self.view.translation_team, translator)
Exemplo n.º 23
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()))
Exemplo n.º 24
0
 def test_getEndpointMemos__decorated_result_set(self):
     # getEndpointMemos() works for DecoratedResultSet
     # instances too.
     resultset = self.makeDecoratedStormResultSet()
     resultset.order_by(LibraryFileAlias.id)
     range_factory = StormRangeFactory(resultset)
     request = LaunchpadTestRequest()
     batchnav = BatchNavigator(
         resultset, request, size=3, range_factory=range_factory)
     first, last = range_factory.getEndpointMemos(batchnav.batch)
     expected_first = simplejson.dumps(
         [resultset.get_plain_result_set()[0][1].id],
         cls=DateTimeJSONEncoder)
     expected_last = simplejson.dumps(
         [resultset.get_plain_result_set()[2][1].id],
         cls=DateTimeJSONEncoder)
     self.assertEqual(expected_first, first)
     self.assertEqual(expected_last, last)
Exemplo n.º 25
0
 def test_getEndpointMemos(self):
     # getEndpointMemos() returns JSON representations of the
     # sort fields of the first and last element of a batch.
     resultset = self.makeStormResultSet()
     resultset.order_by(Person.name)
     range_factory = StormRangeFactory(resultset)
     memo_value = range_factory.getOrderValuesFor(resultset[0])
     request = LaunchpadTestRequest(
         QUERY_STRING='memo=%s' % simplejson.dumps(memo_value))
     batchnav = BatchNavigator(
         resultset, request, size=3, range_factory=range_factory)
     first, last = range_factory.getEndpointMemos(batchnav.batch)
     expected_first = simplejson.dumps(
         [resultset[1].name], cls=DateTimeJSONEncoder)
     expected_last = simplejson.dumps(
         [resultset[3].name], cls=DateTimeJSONEncoder)
     self.assertEqual(expected_first, first)
     self.assertEqual(expected_last, last)
Exemplo n.º 26
0
 def test_open_id_callback_handles_query_string(self):
     # If the currently requested URL includes a query string, the
     # parameters in the query string must be included when constructing
     # the params mapping (which is then used to complete the open ID
     # response).
     request = LaunchpadTestRequest(
         SERVER_URL='http://example.com',
         QUERY_STRING='foo=bar',
         form={'starting_url': 'http://launchpad.dev/after-login'},
         environ={'PATH_INFO': '/'})
     view = FakeConsumerOpenIDCallbackView(object(), request)
     view.initialize()
     self.assertEqual(view.fake_consumer.params, {
         'starting_url': 'http://launchpad.dev/after-login',
         'foo': 'bar',
     })
     self.assertEqual(view.fake_consumer.requested_url,
                      'http://example.com?foo=bar')
Exemplo n.º 27
0
    def _change_and_test_config(self):
        form = {
            'field.actions.save': 'save',
            'field.root_dir': self.ROOT_DIR,
            'field.base_url': self.BASE_URL,
            'field.copy_base_url': self.COPY_BASE_URL,
        }

        view = DistributionPublisherConfigView(
            self.distro, LaunchpadTestRequest(method='POST', form=form))
        view.initialize()

        config = getUtility(
            IPublisherConfigSet).getByDistribution(self.distro)

        self.assertEqual(self.ROOT_DIR, config.root_dir)
        self.assertEqual(self.BASE_URL, config.base_url)
        self.assertEqual(self.COPY_BASE_URL, config.copy_base_url)
Exemplo n.º 28
0
 def test_widget_suggestions(self):
     # The suggestions menu is shown when the input is invalid and there
     # are matches to suggest to the user.
     field = ITest['test_valid.item']
     bound_field = field.bind(self.context)
     request = LaunchpadTestRequest(form={'field.test_valid.item': 'foo'})
     picker_widget = VocabularyPickerWidget(bound_field, self.vocabulary,
                                            request)
     matches = list(picker_widget.matches)
     self.assertEqual(1, len(matches))
     self.assertEqual('Foo Bar', matches[0].title)
     markup = picker_widget()
     self.assertIn('id="field.test_valid.item-suggestions"', markup)
     self.assertIn("Y.DOM.byId('field.test_valid.item-suggestions')",
                   markup)
     self.assertTextMatchesExpressionIgnoreWhitespace(
         'Y.lp.app.picker.connect_select_menu\( '
         'select_menu, text_input\);', markup)
Exemplo n.º 29
0
 def test_setUpOptions_repository_owner_checked(self):
     # The repository owner radio button is selected when the form is
     # submitted when the grantee field's value is 'repository_owner'.
     form = {"field.grantee": "repository_owner"}
     self.widget.request = LaunchpadTestRequest(form=form)
     self.widget.setUpSubWidgets()
     self.widget.setUpOptions()
     self.assertEqual(
         '<input class="radioType" style="margin-left: 0;" '
         'checked="checked" ' + self.expected_disabled_attr +
         'id="field.grantee.option.repository_owner" name="field.grantee" '
         'type="radio" value="repository_owner" />',
         self.widget.options["repository_owner"])
     self.assertEqual(
         '<input class="radioType" style="margin-left: 0;" ' +
         self.expected_disabled_attr +
         'id="field.grantee.option.person" name="field.grantee" '
         'type="radio" value="person" />', self.widget.options["person"])
Exemplo n.º 30
0
    def test_json_cache_has_related_features(self):
        # The property related_features is copied into the JSON cache.
        class TestView(LaunchpadView):
            related_features = {'test_feature': False}

        self.useFixture(
            FeatureFixture({},
                           self.makeFeatureFlagDictionaries(u'', u'on'),
                           override_scope_lookup=lambda scope_name: True))
        request = LaunchpadTestRequest()
        view = TestView(object(), request)
        with person_logged_in(self.factory.makePerson()):
            self.assertEqual(
                '{"related_features": {"test_feature": {'
                '"url": "http://wiki.lp.dev/LEP/sample", '
                '"is_beta": true, '
                '"value": "on", '
                '"title": "title"'
                '}}}', view.getCacheJSON())