Exemplo n.º 1
0
    def _set_attr_name_map(self):
        """ build a map for attributes names and display names

    Dict containing all display_name to attr_name mappings
    for all objects used in the current query
    Example:
        { Program: {"Program URL": "url", "Code": "slug", ...} ...}
    """
        self.attr_name_map = {}
        for object_query in self.query:
            object_name = object_query["object_name"]
            object_class = self.object_map[object_name]
            aliases = AttributeInfo.gather_aliases(object_class)
            self.attr_name_map[object_class] = {}
            for key, value in aliases.items():
                filter_by = None
                if isinstance(value, dict):
                    filter_name = value.get("filter_by", None)
                    if filter_name is not None:
                        filter_by = getattr(object_class, filter_name, None)
                    name = value["display_name"]
                else:
                    name = value
                if name:
                    self.attr_name_map[object_class][name.lower()] = (
                        key.lower(), filter_by)
Exemplo n.º 2
0
  def _set_attr_name_map(self):
    """ build a map for attributes names and display names

    Dict containing all display_name to attr_name mappings
    for all objects used in the current query
    Example:
        { Program: {"Program URL": "url", "Code": "slug", ...} ...}
    """
    self.attr_name_map = {}
    for object_query in self.query:
      object_name = object_query["object_name"]
      object_class = self.object_map[object_name]
      tgt_class = object_class
      if object_name == "Snapshot":
        child_type = self._get_snapshot_child_type(object_query)
        tgt_class = getattr(models.all_models, child_type, object_class)
      aliases = AttributeInfo.gather_aliases(tgt_class)
      self.attr_name_map[tgt_class] = {}
      for key, value in aliases.items():
        filter_by = None
        if isinstance(value, dict):
          filter_name = value.get("filter_by", None)
          if filter_name is not None:
            filter_by = getattr(tgt_class, filter_name, None)
          name = value["display_name"]
        else:
          name = value
        if name:
          self.attr_name_map[tgt_class][name.lower()] = (key.lower(),
                                                         filter_by)
Exemplo n.º 3
0
    def _get_reserved_names(cls, definition_type):
        """Get a list of all attribute names in all objects.

    On first call this function computes all possible names that can be used by
    any model and stores them in a static frozen set. All later calls just get
    this set.

    Returns:
      frozen set containing all reserved attribute names for the current
      object.
    """
        with benchmark("Generate a list of all reserved attribute names"):
            if not cls._reserved_names.get(definition_type):
                definition_map = {
                    model._inflector.table_singular: model
                    for model in ggrc.models.all_models.all_models
                }
                definition_model = definition_map.get(definition_type)
                if not definition_model:
                    raise ValueError("Invalid definition type")

                aliases = AttributeInfo.gather_aliases(definition_model)
                cls._reserved_names[definition_type] = frozenset(
                    (value["display_name"] if isinstance(value, dict
                                                         ) else value).lower()
                    for value in aliases.values() if value)
            return cls._reserved_names[definition_type]
Exemplo n.º 4
0
  def _get_reserved_names(cls, definition_type):
    """Get a list of all attribute names in all objects.

    On first call this function computes all possible names that can be used by
    any model and stores them in a static frozen set. All later calls just get
    this set.

    Returns:
      frozen set containing all reserved attribute names for the current
      object.
    """
    # pylint: disable=protected-access
    # The _inflector is a false positive in our app.
    with benchmark("Generate a list of all reserved attribute names"):
      if not cls._reserved_names.get(definition_type):
        definition_map = {model._inflector.table_singular: model
                          for model in ggrc.models.all_models.all_models}
        definition_map.update({model._inflector.model_singular: model
                              for model in ggrc.models.all_models.all_models})

        definition_model = definition_map.get(definition_type)
        if not definition_model:
          raise ValueError("Invalid definition type")

        aliases = AttributeInfo.gather_aliases(definition_model)
        cls._reserved_names[definition_type] = frozenset(
            (value["display_name"] if isinstance(
                value, dict) else value).lower()
            for value in aliases.values() if value
        )
      return cls._reserved_names[definition_type]
Exemplo n.º 5
0
  def test_gather_aliases(self):
    """Test gather all aliases."""
    class Child(object):
      # pylint: disable=too-few-public-methods
      _aliases = {
          "child_normal": "normal",
          "child_extended": {
              "display_name": "Extended",
          },
          "child_filter_only": {
              "display_name": "Extended",
              "filter_only": True,
          },
      }

    class Parent(Child):
      # pylint: disable=too-few-public-methods
      _aliases = {
          "parent_normal": "normal",
          "parent_extended": {
              "display_name": "Extended",
          },
          "parent_filter_only": {
              "display_name": "Extended",
              "filter_only": True,
          },
      }

    self.assertEqual(
        AttributeInfo.gather_aliases(Parent),
        {
            "parent_normal": "normal",
            "parent_extended": {
                "display_name": "Extended",
            },
            "parent_filter_only": {
                "display_name": "Extended",
                "filter_only": True,
            },
            "child_normal": "normal",
            "child_extended": {
                "display_name": "Extended",
            },
            "child_filter_only": {
                "display_name": "Extended",
                "filter_only": True,
            },
        }
    )
Exemplo n.º 6
0
  def test_gather_aliases(self):
    """Test gather all aliases."""
    class Child(object):
      # pylint: disable=too-few-public-methods
      _aliases = {
          "child_normal": "normal",
          "child_extended": {
              "display_name": "Extended",
          },
          "child_filter_only": {
              "display_name": "Extended",
              "filter_only": True,
          },
      }

    class Parent(Child):
      # pylint: disable=too-few-public-methods
      _aliases = {
          "parent_normal": "normal",
          "parent_extended": {
              "display_name": "Extended",
          },
          "parent_filter_only": {
              "display_name": "Extended",
              "filter_only": True,
          },
      }

    self.assertEqual(
        AttributeInfo.gather_aliases(Parent),
        {
            "parent_normal": "normal",
            "parent_extended": {
                "display_name": "Extended",
            },
            "parent_filter_only": {
                "display_name": "Extended",
                "filter_only": True,
            },
            "child_normal": "normal",
            "child_extended": {
                "display_name": "Extended",
            },
            "child_filter_only": {
                "display_name": "Extended",
                "filter_only": True,
            },
        }
    )
Exemplo n.º 7
0
    def _get_model_names(cls, model):
        """Get tuple of all attribute names for model.

    Args:
        model: Model class.

    Returns:
        Tuple of all attributes for provided model.
    """
        if not model:
            raise ValueError("Invalid definition type")
        aliases = AttributeInfo.gather_aliases(model)
        return ((value["display_name"]
                 if isinstance(value, dict) else value).lower()
                for value in aliases.values() if value)
Exemplo n.º 8
0
  def _get_model_names(cls, model):
    """Get tuple of all attribute names for model.

    Args:
        model: Model class.

    Returns:
        Tuple of all attributes for provided model.
    """
    if not model:
      raise ValueError("Invalid definition type")
    aliases = AttributeInfo.gather_aliases(model)
    return (
        (value["display_name"] if isinstance(value, dict) else value).lower()
        for value in aliases.values() if value
    )
Exemplo n.º 9
0
    def _set_attr_name_map(self):
        """ build a map for attributes names and display names

    Dict containing all display_name to attr_name mappings
    for all objects used in the current query
    Example:
        { Program: {"Program URL": "url", "Code": "slug", ...} ...}
    """
        self.attr_name_map = {}
        for object_query in self.query:
            object_name = object_query["object_name"]
            object_class = self.object_map[object_name]
            aliases = AttributeInfo.gather_aliases(object_class)
            self.attr_name_map[object_class] = {}
            for key, value in aliases.items():
                filter_by = None
                if isinstance(value, dict):
                    filter_name = value.get("filter_by", None)
                    if filter_name is not None:
                        filter_by = getattr(object_class, filter_name, None)
                    value = value["display_name"]
                if value:
                    self.attr_name_map[object_class][value.lower()] = (
                        key.lower(), filter_by)
            if not self.ca_disabled:
                custom_attrs = AttributeInfo.get_custom_attr_definitions(
                    object_class)
            else:
                custom_attrs = {}

            for key, definition in custom_attrs.items():
                if not key.startswith("__custom__:") or \
                   "display_name" not in definition:
                    continue
                try:
                    # Global custom attribute definition can only have a single id on
                    # their name, so it is safe for that. Currently the filters do not
                    # work with object level custom attributes.
                    attr_id = definition["definition_ids"][0]
                except KeyError:
                    continue
                filter_by = CustomAttributeValue.mk_filter_by_custom(
                    object_class, attr_id)
                name = definition["display_name"].lower()
                self.attr_name_map[object_class][name] = (name, filter_by)
Exemplo n.º 10
0
 def attributes_map(cls):
     if cls.CACHED_ATTRIBUTE_MAP:
         return cls.CACHED_ATTRIBUTE_MAP
     aliases = AttributeInfo.gather_aliases(cls)
     cls.CACHED_ATTRIBUTE_MAP = {}
     for key, value in aliases.items():
         if isinstance(value, dict):
             name = value["display_name"]
             filter_by = None
             if value.get("filter_by"):
                 filter_by = getattr(cls, value["filter_by"], None)
         else:
             name = value
             filter_by = None
         if not name:
             continue
         cls.CACHED_ATTRIBUTE_MAP[name.lower()] = (key.lower(), filter_by)
     return cls.CACHED_ATTRIBUTE_MAP
Exemplo n.º 11
0
 def attributes_map(cls):
   if cls.CACHED_ATTRIBUTE_MAP:
     return cls.CACHED_ATTRIBUTE_MAP
   aliases = AttributeInfo.gather_aliases(cls)
   cls.CACHED_ATTRIBUTE_MAP = {}
   for key, value in aliases.items():
     if isinstance(value, dict):
       name = value["display_name"]
       filter_by = None
       if value.get("filter_by"):
         filter_by = getattr(cls, value["filter_by"], None)
     else:
       name = value
       filter_by = None
     if not name:
       continue
     tmp = getattr(cls, "PROPERTY_TEMPLATE", "{}")
     name = tmp.format(name)
     key = tmp.format(key)
     cls.CACHED_ATTRIBUTE_MAP[name.lower()] = (key.lower(), filter_by)
   return cls.CACHED_ATTRIBUTE_MAP
Exemplo n.º 12
0
 def attributes_map(cls):
   """Get class attributes map"""
   if cls.CACHED_ATTRIBUTE_MAP:
     return cls.CACHED_ATTRIBUTE_MAP
   aliases = AttributeInfo.gather_aliases(cls)
   cls.CACHED_ATTRIBUTE_MAP = {}
   for key, value in aliases.items():
     if isinstance(value, dict):
       name = value["display_name"]
       filter_by = None
       if value.get("filter_by"):
         filter_by = getattr(cls, value["filter_by"], None)
     else:
       name = value
       filter_by = None
     if not name:
       continue
     tmp = getattr(cls, "PROPERTY_TEMPLATE", "{}")
     name = tmp.format(name)
     key = tmp.format(key)
     cls.CACHED_ATTRIBUTE_MAP[name.lower()] = (key.lower(), filter_by)
   return cls.CACHED_ATTRIBUTE_MAP