示例#1
0
    def testPBProxy(self):
        """Checks that PBProxy wraps protobuf objects as expected."""
        # check that protobuf fields are accessible in ".attribute" form
        pbe = pbproxy_test_pb2.PBProxyExample()
        pbe.foo = 'foo'
        pbe.bar = False
        pbep = template_helpers.PBProxy(pbe)
        self.assertEqual(pbep.foo, 'foo')
        # _bool suffix converts protobuf field 'bar' to None (EZT boolean false)
        self.assertEqual(pbep.bar_bool, None)

        # check that a new field can be added to the PBProxy
        pbep.baz = 'bif'
        self.assertEqual(pbep.baz, 'bif')

        # check that a PBProxy-local field can hide a protobuf field
        pbep.foo = 'local foo'
        self.assertEqual(pbep.foo, 'local foo')

        # check that a nested protobuf is recursively wrapped with a PBProxy
        pbn = pbproxy_test_pb2.PBProxyNested()
        pbn.nested = pbproxy_test_pb2.PBProxyExample()
        pbn.nested.foo = 'bar'
        pbn.nested.bar = True
        pbnp = template_helpers.PBProxy(pbn)
        self.assertEqual(pbnp.nested.foo, 'bar')
        # _bool suffix converts protobuf field 'bar' to 'yes' (EZT boolean true)
        self.assertEqual(pbnp.nested.bar_bool, 'yes')

        # check that 'repeated' lists of items produce a list of strings
        pbn.multiple_strings.append('1')
        pbn.multiple_strings.append('2')
        self.assertEqual(pbnp.multiple_strings, ['1', '2'])

        # check that 'repeated' messages produce lists of PBProxy instances
        pbe1 = pbproxy_test_pb2.PBProxyExample()
        pbn.multiple_pbes.append(pbe1)
        pbe1.foo = '1'
        pbe1.bar = True
        pbe2 = pbproxy_test_pb2.PBProxyExample()
        pbn.multiple_pbes.append(pbe2)
        pbe2.foo = '2'
        pbe2.bar = False
        self.assertEqual(pbnp.multiple_pbes[0].foo, '1')
        self.assertEqual(pbnp.multiple_pbes[0].bar_bool, 'yes')
        self.assertEqual(pbnp.multiple_pbes[1].foo, '2')
        self.assertEqual(pbnp.multiple_pbes[1].bar_bool, None)
示例#2
0
 def GatherPageData(self, mr):
     """Build up a dictionary of data values to use when rendering the page."""
     page_data = {
         'user_tab_mode': 'st3',
         'logged_in_user_pb': template_helpers.PBProxy(mr.auth.user_pb),
         # When on /hosting/settings, the logged-in user is the viewed user.
         'viewed_user': mr.auth.user_view,
         'offer_saved_queries_subtab': ezt.boolean(True),
         'viewing_self': ezt.boolean(True),
     }
     page_data.update(
         framework_helpers.UserSettings.GatherUnifiedSettingsPageData(
             mr.auth.user_id, mr.auth.user_view, mr.auth.user_pb))
     return page_data
示例#3
0
    def testGatherPageData(self):
        self.mox.StubOutWithMock(framework_helpers.UserSettings,
                                 'GatherUnifiedSettingsPageData')
        framework_helpers.UserSettings.GatherUnifiedSettingsPageData(
            0L, None, mox.IsA(user_pb2.User)).AndReturn({'unified': None})
        self.mox.ReplayAll()

        mr = testing_helpers.MakeMonorailRequest()
        page_data = self.servlet.GatherPageData(mr)

        self.assertItemsEqual([
            'logged_in_user_pb', 'unified', 'user_tab_mode', 'viewed_user',
            'offer_saved_queries_subtab', 'viewing_self'
        ], page_data.keys())
        self.assertEqual(template_helpers.PBProxy(mr.auth.user_pb),
                         page_data['logged_in_user_pb'])

        self.mox.VerifyAll()
示例#4
0
    def GatherUnifiedSettingsPageData(cls, logged_in_user_id,
                                      settings_user_view, settings_user,
                                      settings_user_prefs):
        """Gather EZT variables needed for the unified user settings form.

    Args:
      logged_in_user_id: The user ID of the acting user.
      settings_user_view: The UserView of the target user.
      settings_user: The User PB of the target user.
      settings_user_prefs: UserPrefs object for the view user.

    Returns:
      A dictionary giving the names and values of all the variables to
      be exported to EZT to support the unified user settings form template.
    """

        settings_user_prefs_view = template_helpers.EZTItem(
            **{name: None
               for name in framework_bizobj.USER_PREF_DEFS})
        if settings_user_prefs:
            for upv in settings_user_prefs.prefs:
                if upv.value == 'true':
                    setattr(settings_user_prefs_view, upv.name, True)
                elif upv.value == 'false':
                    setattr(settings_user_prefs_view, upv.name, None)

        logging.info('settings_user_prefs_view is %r' %
                     settings_user_prefs_view)
        return {
            'settings_user': settings_user_view,
            'settings_user_pb': template_helpers.PBProxy(settings_user),
            'settings_user_is_banned': ezt.boolean(settings_user.banned),
            'self':
            ezt.boolean(logged_in_user_id == settings_user_view.user_id),
            'profile_url_fragment':
            (settings_user_view.profile_url[len('/u/'):]),
            'preview_on_hover': ezt.boolean(settings_user.preview_on_hover),
            'settings_user_prefs': settings_user_prefs_view,
        }
示例#5
0
    def GatherBaseData(self, mr, nonce):
        """Return a dict of info used on almost all pages."""
        project = mr.project

        project_summary = ''
        project_alert = None
        project_read_only = False
        project_home_page = ''
        project_thumbnail_url = ''
        if project:
            project_summary = project.summary
            project_alert = _CalcProjectAlert(project)
            project_read_only = project.read_only_reason
            project_home_page = project.home_page
            project_thumbnail_url = tracker_views.LogoView(
                project).thumbnail_url

        with work_env.WorkEnv(mr, self.services) as we:
            is_project_starred = False
            project_view = None
            if mr.project:
                if permissions.UserCanViewProject(mr.auth.user_pb,
                                                  mr.auth.effective_ids,
                                                  mr.project):
                    is_project_starred = we.IsProjectStarred(mr.project_id)
                    # TODO(jrobbins): should this be a ProjectView?
                    project_view = template_helpers.PBProxy(mr.project)

        grid_x_attr = None
        grid_y_attr = None
        hotlist_view = None
        if mr.hotlist:
            users_by_id = framework_views.MakeAllUserViews(
                mr.cnxn, self.services.user,
                features_bizobj.UsersInvolvedInHotlists([mr.hotlist]))
            hotlist_view = hotlist_views.HotlistView(
                mr.hotlist, mr.perms, mr.auth, mr.viewed_user_auth.user_id,
                users_by_id,
                self.services.hotlist_star.IsItemStarredBy(
                    mr.cnxn, mr.hotlist.hotlist_id, mr.auth.user_id))
            grid_x_attr = mr.x.lower()
            grid_y_attr = mr.y.lower()

        app_version = os.environ.get('CURRENT_VERSION_ID')

        viewed_username = None
        if mr.viewed_user_auth.user_view:
            viewed_username = mr.viewed_user_auth.user_view.username

        issue_entry_url = 'entry'
        config = None
        if mr.project_id and self.services.config:
            with mr.profiler.Phase('getting config'):
                config = self.services.config.GetProjectConfig(
                    mr.cnxn, mr.project_id)
            grid_x_attr = (mr.x or config.default_x_attr).lower()
            grid_y_attr = (mr.y or config.default_y_attr).lower()
            issue_entry_url = _LoginOrIssueEntryURL(mr, config)

        viewing_self = mr.auth.user_id == mr.viewed_user_auth.user_id
        offer_saved_queries_subtab = (viewing_self or mr.auth.user_pb
                                      and mr.auth.user_pb.is_site_admin)

        login_url = _SafeCreateLoginURL(mr)
        logout_url = _SafeCreateLogoutURL(mr)
        logout_url_goto_home = users.create_logout_url('/')
        version_base = _VersionBaseURL(mr.request)

        base_data = {
            # EZT does not have constants for True and False, so we pass them in.
            'True':
            ezt.boolean(True),
            'False':
            ezt.boolean(False),
            'local_mode':
            ezt.boolean(settings.local_mode),
            'site_name':
            settings.site_name,
            'show_search_metadata':
            ezt.boolean(False),
            'page_template':
            self._PAGE_TEMPLATE,
            'main_tab_mode':
            self._MAIN_TAB_MODE,
            'project_summary':
            project_summary,
            'project_home_page':
            project_home_page,
            'project_thumbnail_url':
            project_thumbnail_url,
            'hotlist_id':
            mr.hotlist_id,
            'hotlist':
            hotlist_view,
            'hostport':
            mr.request.host,
            'absolute_base_url':
            '%s://%s' % (mr.request.scheme, mr.request.host),
            'project_home_url':
            None,
            'link_rel_canonical':
            None,  # For specifying <link rel="canonical">
            'projectname':
            mr.project_name,
            'project':
            project_view,
            'project_is_restricted':
            ezt.boolean(_ProjectIsRestricted(mr)),
            'offer_contributor_list':
            ezt.boolean(permissions.CanViewContributorList(mr, mr.project)),
            'logged_in_user':
            mr.auth.user_view,
            'form_token':
            None,  # Set to a value below iff the user is logged in.
            'form_token_path':
            None,
            'token_expires_sec':
            None,
            'xhr_token':
            None,  # Set to a value below iff the user is logged in.
            'flag_spam_token':
            None,
            'nonce':
            nonce,
            'perms':
            mr.perms,
            'warnings':
            mr.warnings,
            'errors':
            mr.errors,
            'viewed_username':
            viewed_username,
            'viewed_user':
            mr.viewed_user_auth.user_view,
            'viewed_user_pb':
            template_helpers.PBProxy(mr.viewed_user_auth.user_pb),
            'viewing_self':
            ezt.boolean(viewing_self),
            'viewed_user_id':
            mr.viewed_user_auth.user_id,
            'offer_saved_queries_subtab':
            ezt.boolean(offer_saved_queries_subtab),
            'currentPageURL':
            mr.current_page_url,
            'currentPageURLEncoded':
            mr.current_page_url_encoded,
            'login_url':
            login_url,
            'logout_url':
            logout_url,
            'logout_url_goto_home':
            logout_url_goto_home,
            'continue_issue_id':
            mr.continue_issue_id,
            'feedback_email':
            settings.feedback_email,
            'category_css':
            None,  # Used to specify a category of stylesheet
            'category2_css':
            None,  # specify a 2nd category of stylesheet if needed.
            'page_css':
            None,  # Used to add a stylesheet to a specific page.
            'can':
            mr.can,
            'query':
            mr.query,
            'colspec':
            None,
            'sortspec':
            mr.sort_spec,

            # Options for issuelist display
            'grid_x_attr':
            grid_x_attr,
            'grid_y_attr':
            grid_y_attr,
            'grid_cell_mode':
            mr.cells,
            'grid_mode':
            None,
            'list_mode':
            None,
            'chart_mode':
            None,
            'issue_entry_url':
            issue_entry_url,
            'is_cross_project':
            ezt.boolean(False),

            # for project search (some also used in issue search)
            'start':
            mr.start,
            'num':
            mr.num,
            'groupby':
            mr.group_by_spec,
            'q_field_size': (min(
                framework_constants.MAX_ARTIFACT_SEARCH_FIELD_SIZE,
                max(framework_constants.MIN_ARTIFACT_SEARCH_FIELD_SIZE,
                    len(mr.query) + framework_constants.AUTOSIZE_STEP))),
            'mode':
            None,  # Display mode, e.g., grid mode.
            'ajah':
            mr.ajah,
            'table_title':
            mr.table_title,
            'alerts':
            alerts.AlertsView(mr),  # For alert.ezt
            'project_alert':
            project_alert,
            'title':
            None,  # First part of page title
            'title_summary':
            None,  # Appended to title on artifact detail pages

            # TODO(jrobbins): make sure that the templates use
            # project_read_only for project-mutative actions and if any
            # uses of read_only remain.
            'project_read_only':
            ezt.boolean(project_read_only),
            'site_read_only':
            ezt.boolean(settings.read_only),
            'banner_time':
            servlet_helpers.GetBannerTime(settings.banner_time),
            'read_only':
            ezt.boolean(settings.read_only or project_read_only),
            'site_banner_message':
            settings.banner_message,
            'robots_no_index':
            None,
            'analytics_id':
            settings.analytics_id,
            'is_project_starred':
            ezt.boolean(is_project_starred),
            'version_base':
            version_base,
            'app_version':
            app_version,
            'gapi_client_id':
            settings.gapi_client_id,
            'viewing_user_page':
            ezt.boolean(False),
            'old_ui_url':
            None,
            'is_member':
            ezt.boolean(False),
        }

        if mr.project:
            base_data['project_home_url'] = '/p/%s' % mr.project_name

        # Always add xhr-xsrf token because even anon users need some
        # pRPC methods, e.g., autocomplete, flipper, and charts.
        base_data['token_expires_sec'] = xsrf.TokenExpiresSec()
        base_data['xhr_token'] = xsrf.GenerateToken(mr.auth.user_id,
                                                    xsrf.XHR_SERVLET_PATH)
        # Always add other anti-xsrf tokens when the user is logged in.
        if mr.auth.user_id:
            form_token_path = self._FormHandlerURL(mr.request.path)
            base_data['form_token'] = xsrf.GenerateToken(
                mr.auth.user_id, form_token_path)
            base_data['form_token_path'] = form_token_path

        return base_data
    def GatherUnifiedSettingsPageData(cls, logged_in_user_id,
                                      settings_user_view, settings_user):
        """Gather EZT variables needed for the unified user settings form.

    Args:
      logged_in_user_id: The user ID of the acting user.
      settings_user_view: The UserView of the target user.
      settings_user: The User PB of the target user.

    Returns:
      A dictionary giving the names and values of all the variables to
      be exported to EZT to support the unified user settings form template.
    """
        def ActionLastReset(action_limit):
            """Return a formatted time string for the last action limit reset."""
            if action_limit:
                return time.asctime(
                    time.localtime(action_limit.reset_timestamp))
            return 'Never'

        def DefaultLifetimeLimit(action_type):
            """Return the deault lifetime limit for the give type of action."""
            return actionlimit.ACTION_LIMITS[action_type][3]

        def DefaultPeriodSoftLimit(action_type):
            """Return the deault period soft limit for the give type of action."""
            return actionlimit.ACTION_LIMITS[action_type][1]

        def DefaultPeriodHardLimit(action_type):
            """Return the deault period jard limit for the give type of action."""
            return actionlimit.ACTION_LIMITS[action_type][2]

        project_creation_lifetime_limit = (
            (settings_user.project_creation_limit
             and settings_user.project_creation_limit.lifetime_limit)
            or DefaultLifetimeLimit(actionlimit.PROJECT_CREATION))
        project_creation_soft_limit = (
            (settings_user.project_creation_limit
             and settings_user.project_creation_limit.period_soft_limit)
            or DefaultPeriodSoftLimit(actionlimit.PROJECT_CREATION))
        project_creation_hard_limit = (
            (settings_user.project_creation_limit
             and settings_user.project_creation_limit.period_hard_limit)
            or DefaultPeriodHardLimit(actionlimit.PROJECT_CREATION))
        issue_comment_lifetime_limit = (
            (settings_user.issue_comment_limit
             and settings_user.issue_comment_limit.lifetime_limit)
            or DefaultLifetimeLimit(actionlimit.ISSUE_COMMENT))
        issue_comment_soft_limit = (
            (settings_user.issue_comment_limit
             and settings_user.issue_comment_limit.period_soft_limit)
            or DefaultPeriodSoftLimit(actionlimit.ISSUE_COMMENT))
        issue_comment_hard_limit = (
            (settings_user.issue_comment_limit
             and settings_user.issue_comment_limit.period_hard_limit)
            or DefaultPeriodHardLimit(actionlimit.ISSUE_COMMENT))
        issue_attachment_lifetime_limit = (
            (settings_user.issue_attachment_limit
             and settings_user.issue_attachment_limit.lifetime_limit)
            or DefaultLifetimeLimit(actionlimit.ISSUE_ATTACHMENT))
        issue_attachment_soft_limit = (
            (settings_user.issue_attachment_limit
             and settings_user.issue_attachment_limit.period_soft_limit)
            or DefaultPeriodSoftLimit(actionlimit.ISSUE_ATTACHMENT))
        issue_attachment_hard_limit = (
            (settings_user.issue_attachment_limit
             and settings_user.issue_attachment_limit.period_hard_limit)
            or DefaultPeriodHardLimit(actionlimit.ISSUE_ATTACHMENT))
        issue_bulk_edit_lifetime_limit = (
            (settings_user.issue_bulk_edit_limit
             and settings_user.issue_bulk_edit_limit.lifetime_limit)
            or DefaultLifetimeLimit(actionlimit.ISSUE_BULK_EDIT))
        issue_bulk_edit_soft_limit = (
            (settings_user.issue_bulk_edit_limit
             and settings_user.issue_bulk_edit_limit.period_soft_limit)
            or DefaultPeriodSoftLimit(actionlimit.ISSUE_BULK_EDIT))
        issue_bulk_edit_hard_limit = (
            (settings_user.issue_bulk_edit_limit
             and settings_user.issue_bulk_edit_limit.period_hard_limit)
            or DefaultPeriodHardLimit(actionlimit.ISSUE_BULK_EDIT))
        api_request_lifetime_limit = (
            (settings_user.api_request_limit
             and settings_user.api_request_limit.lifetime_limit)
            or DefaultLifetimeLimit(actionlimit.API_REQUEST))
        api_request_soft_limit = (
            (settings_user.api_request_limit
             and settings_user.api_request_limit.period_soft_limit)
            or DefaultPeriodSoftLimit(actionlimit.API_REQUEST))
        api_request_hard_limit = (
            (settings_user.api_request_limit
             and settings_user.api_request_limit.period_hard_limit)
            or DefaultPeriodHardLimit(actionlimit.API_REQUEST))

        return {
            'settings_user':
            settings_user_view,
            'settings_user_pb':
            template_helpers.PBProxy(settings_user),
            'settings_user_is_banned':
            ezt.boolean(settings_user.banned),
            'settings_user_ignore_action_limits':
            (ezt.boolean(settings_user.ignore_action_limits)),
            'self':
            ezt.boolean(logged_in_user_id == settings_user_view.user_id),
            'project_creation_reset':
            (ActionLastReset(settings_user.project_creation_limit)),
            'issue_comment_reset':
            (ActionLastReset(settings_user.issue_comment_limit)),
            'issue_attachment_reset':
            (ActionLastReset(settings_user.issue_attachment_limit)),
            'issue_bulk_edit_reset':
            (ActionLastReset(settings_user.issue_bulk_edit_limit)),
            'api_request_reset':
            (ActionLastReset(settings_user.api_request_limit)),
            'project_creation_lifetime_limit':
            project_creation_lifetime_limit,
            'project_creation_soft_limit':
            project_creation_soft_limit,
            'project_creation_hard_limit':
            project_creation_hard_limit,
            'issue_comment_lifetime_limit':
            issue_comment_lifetime_limit,
            'issue_comment_soft_limit':
            issue_comment_soft_limit,
            'issue_comment_hard_limit':
            issue_comment_hard_limit,
            'issue_attachment_lifetime_limit':
            issue_attachment_lifetime_limit,
            'issue_attachment_soft_limit':
            issue_attachment_soft_limit,
            'issue_attachment_hard_limit':
            issue_attachment_hard_limit,
            'issue_bulk_edit_lifetime_limit':
            issue_bulk_edit_lifetime_limit,
            'issue_bulk_edit_soft_limit':
            issue_bulk_edit_soft_limit,
            'issue_bulk_edit_hard_limit':
            issue_bulk_edit_hard_limit,
            'api_request_lifetime_limit':
            api_request_lifetime_limit,
            'api_request_soft_limit':
            api_request_soft_limit,
            'api_request_hard_limit':
            api_request_hard_limit,
            'profile_url_fragment':
            (settings_user_view.profile_url[len('/u/'):]),
            'preview_on_hover':
            ezt.boolean(settings_user.preview_on_hover),
        }