Commit 492081b4 authored by Laurent Peuch's avatar Laurent Peuch
Browse files

refactor: rename _subject_relations to subject_relations

Making those attributes privates didn't made that much sens.
parent be1a5a9429bc
......@@ -168,7 +168,7 @@ class SchemaLoaderTC(TestCase):
self.assertEqual(entity_schema.description, "")
self.assertEqual(entity_schema.final, False)
self.assertListEqual(
sorted(entity_schema.subject_relations()),
sorted(list(entity_schema.subject_relations.values())),
[
"ad1",
"ad2",
......@@ -194,7 +194,7 @@ class SchemaLoaderTC(TestCase):
)
self.assertEqual(entity_schema.final, False)
self.assertListEqual(
sorted(str(r) for r in entity_schema.subject_relations()),
sorted(str(r) for r in entity_schema.subject_relations.values()),
["description", "final", "initial_state", "meta", "name", "subj_wildcard"],
)
self.assertListEqual(
......@@ -204,7 +204,7 @@ class SchemaLoaderTC(TestCase):
entity_schema = self.schema.entity_schema_for("Boolean")
self.assertEqual(entity_schema.description, "")
self.assertEqual(entity_schema.final, True)
self.assertListEqual(sorted(entity_schema.subject_relations()), [])
self.assertListEqual(sorted(list(entity_schema.subject_relations.values())), [])
self.assertListEqual(sorted(entity_schema.object_relations()), ["final", "meta", "test"])
# test base entity type's subject relation properties #####################
......
......@@ -273,7 +273,9 @@ class EntitySchemaTC(BaseSchemaTC):
self.assertFalse(eperson is schema["Person"])
self.assertEqual(eperson, schema["Person"])
self.assertEqual("Person", schema["Person"])
self.assertCountEqual(eperson.subject_relations(), schema["Person"].subject_relations())
self.assertCountEqual(
list(eperson.subject_relations.values()), schema["Person"].subject_relations()
)
self.assertCountEqual(eperson.object_relations(), schema["Person"].object_relations())
self.assertEqual(schema.entity_schema_for("Person").final, False)
self.assertEqual(schema.entity_schema_for("String").final, True)
......@@ -300,9 +302,9 @@ class EntitySchemaTC(BaseSchemaTC):
self.assertEqual(enote.final, False)
self.assertEqual(estring.final, True)
self.assertEqual(eint.final, True)
self.assertEqual(eperson._subject_relations["nom"].final, True)
self.assertEqual(eperson.subject_relations["nom"].final, True)
# self.assertEqual(eperson.is_final('concerne'), False)
self.assertEqual(eperson._subject_relations["concerne"].final, False)
self.assertEqual(eperson.subject_relations["concerne"].final, False)
def test_is_metadata(self):
self.assertEqual(eperson.is_metadata("promo"), None)
......
......@@ -165,7 +165,7 @@ class SpecializationTC(TestCase):
)
self.assertEqual(len(set(expected) - done), 0, "missing %s" % (set(expected) - done))
self.assertIn("custom_attr", self.schema["Student"]._subject_relations)
self.assertIn("custom_attr", self.schema["Student"].subject_relations)
self.assertEqual(
self.schema["custom_attr"].relation_definitions[("Student", "String")].permissions,
{"read": ("managers",), "add": ("managers",), "update": ("managers",)},
......
......@@ -19,6 +19,11 @@
"""Classes to define generic Entities/Relations schemas."""
from logilab.common.logging_ext import set_log_methods
from logilab.common.deprecation import (
send_warning,
DeprecationWarningKind,
TargetRemovedDeprecationWarning,
)
import logging
......@@ -107,7 +112,7 @@ def rehash(dictionary: Dict) -> dict:
>>> 'Folder' in d
True
"""
return dict(item for item in dictionary.items())
return _RetroCompatRelationsDict(item for item in dictionary.items())
class ERSchema:
......@@ -224,7 +229,44 @@ class PermissionMixIn:
# Schema objects definition ###################################################
@deprecation.attribute_renamed(old_name="subjrels", new_name="_subject_relations")
class TargetInlinedDeprecationWarning(TargetRemovedDeprecationWarning):
def __init__(self, reason: str, kind: DeprecationWarningKind, name: str):
super().__init__(reason=reason, kind=kind, name=name)
self.operation = "inlined" # type: ignore
def render_result(self, old_name):
return f"list({old_name}.values())"
class _RetroCompatRelationsDict(dict):
def __init__(self, *args, **kwargs):
self.old_name = None
if "old_name" in kwargs:
self.old_name = kwargs["old_name"]
del kwargs["old_name"]
super().__init__(*args, **kwargs)
def __call__(self):
if self.old_name:
send_warning(
(
f"schema.{self.old_name}() method has been remove and is deprecated, use "
f"list(schema.{self.old_name}.values()) instead"
),
TargetInlinedDeprecationWarning,
deprecation_class_kwargs={
"kind": DeprecationWarningKind.CALLABLE,
"name": self.old_name,
},
stacklevel=3,
version="0.46.2",
module_name="yams.schema",
)
return list(self.values())
@deprecation.attribute_renamed(old_name="subjrels", new_name="subject_relations")
@deprecation.attribute_renamed(old_name="objrels", new_name="_object_relations")
class EntitySchema(PermissionMixIn, ERSchema):
"""An entity has a type, a set of subject and or object relations
......@@ -255,7 +297,9 @@ class EntitySchema(PermissionMixIn, ERSchema):
if relation_definition is not None:
# quick access to bounded relation schemas
self._subject_relations: Dict["RelationSchema", "RelationSchema"] = {}
self.subject_relations: Dict[
"RelationSchema", "RelationSchema"
] = _RetroCompatRelationsDict(old_name="subject_relations")
self._object_relations: Dict["RelationSchema", "RelationSchema"] = {}
self._specialized_type = relation_definition.specialized_type
self._specialized_by = relation_definition.specialized_by
......@@ -292,12 +336,12 @@ class EntitySchema(PermissionMixIn, ERSchema):
def __repr__(self) -> str:
return "<%s %s - %s>" % (
self.type,
[subject_relation.type for subject_relation in self.subject_relations()],
[subject_relation.type for subject_relation in self.subject_relations.values()],
[object_relation.type for object_relation in self.object_relations()],
)
def _rehash(self) -> None:
self._subject_relations = rehash(self._subject_relations)
self.subject_relations = rehash(self.subject_relations)
self._object_relations = rehash(self._object_relations)
def advertise_new_add_permission(self) -> None:
......@@ -308,7 +352,7 @@ class EntitySchema(PermissionMixIn, ERSchema):
@deprecation.argument_renamed(old_name="rschema", new_name="relation_schema")
def add_subject_relation(self, relation_schema: "RelationSchema") -> None:
"""register the relation schema as possible subject relation"""
self._subject_relations[relation_schema] = relation_schema
self.subject_relations[relation_schema] = relation_schema
clear_cache(self, "ordered_relations")
clear_cache(self, "meta_attributes")
......@@ -321,7 +365,7 @@ class EntitySchema(PermissionMixIn, ERSchema):
@deprecation.argument_renamed(old_name="rtype", new_name="relation_schema")
def del_subject_relation(self, relation_schema: "RelationSchema") -> None:
try:
del self._subject_relations[relation_schema]
del self.subject_relations[relation_schema]
clear_cache(self, "ordered_relations")
clear_cache(self, "meta_attributes")
except KeyError:
......@@ -367,16 +411,10 @@ class EntitySchema(PermissionMixIn, ERSchema):
@deprecation.argument_renamed(old_name="rtype", new_name="relation_type")
def has_relation(self, relation_type: yams_types.RelationType, role: str) -> bool:
if role == "subject":
return relation_type in self._subject_relations
return relation_type in self.subject_relations
return relation_type in self._object_relations
def subject_relations(self) -> List["RelationSchema"]:
"""return a list of relations that may have this type of entity as
subject
"""
return list(self._subject_relations.values())
def object_relations(self) -> List["RelationSchema"]:
"""return a list of relations that may have this type of entity as
object
......@@ -430,7 +468,7 @@ class EntitySchema(PermissionMixIn, ERSchema):
# mypy: "RelationDefinitionSchema" has no attribute "order"
# this is a dynamically setted attribue using self.__dict__.update(some_dict)
return sorted(
self._subject_relations.values(),
self.subject_relations.values(),
key=lambda x: x.relation_definition(self, x.objects(self)[0]).order, # type: ignore
)
......@@ -462,7 +500,7 @@ class EntitySchema(PermissionMixIn, ERSchema):
`relation_schema` is expected to be a non ambiguous relation
"""
relation_schema = self._subject_relations[relation_schema]
relation_schema = self.subject_relations[relation_schema]
object_types = relation_schema.objects(self.type)
assert len(object_types) == 1, (
......@@ -505,7 +543,7 @@ class EntitySchema(PermissionMixIn, ERSchema):
def defaults(self) -> Generator[Tuple["RelationSchema", Any], Any, None]:
"""return an iterator on (attribute name, default value)"""
for relation_schema in self.subject_relations():
for relation_schema in self.subject_relations.values():
if relation_schema.final:
value = self.default(relation_schema.type)
......@@ -560,7 +598,7 @@ class EntitySchema(PermissionMixIn, ERSchema):
except ValueError:
continue
if meta in KNOWN_METAATTRIBUTES and attribute in self._subject_relations:
if meta in KNOWN_METAATTRIBUTES and attribute in self.subject_relations:
meta_attributes[relation_schema] = (meta, attribute)
return meta_attributes
......@@ -570,7 +608,7 @@ class EntitySchema(PermissionMixIn, ERSchema):
"""return metadata's relation schema if this entity has the given
`metadata` field for the given `attribute` attribute
"""
return self._subject_relations.get("%s_%s" % (attribute, metadata))
return self.subject_relations.get("%s_%s" % (attribute, metadata))
@deprecation.argument_renamed(old_name="attr", new_name="attribute")
def is_metadata(self, attribute) -> Optional[Tuple[str, str]]:
......@@ -580,7 +618,7 @@ class EntitySchema(PermissionMixIn, ERSchema):
except ValueError:
return None
if metadata in KNOWN_METAATTRIBUTES and attribute in self._subject_relations:
if metadata in KNOWN_METAATTRIBUTES and attribute in self.subject_relations:
return (attribute, metadata)
return None
......@@ -589,7 +627,7 @@ class EntitySchema(PermissionMixIn, ERSchema):
def indexable_attributes(self) -> Generator["RelationSchema", Any, None]:
"""return the relation schema of attribtues to index"""
for relation_schema in self.subject_relations():
for relation_schema in self.subject_relations.values():
if relation_schema.final:
try:
# mypy: "RelationDefinitionSchema" has no attribute "fulltextindexed"
......@@ -602,7 +640,7 @@ class EntitySchema(PermissionMixIn, ERSchema):
def fulltext_relations(self) -> Generator[Tuple["RelationSchema", str], Any, None]:
"""return the (name, role) of relations to index"""
for relation_schema in self.subject_relations():
for relation_schema in self.subject_relations.values():
if not relation_schema.final and relation_schema.fulltext_container == "subject":
yield relation_schema, "subject"
......@@ -614,7 +652,7 @@ class EntitySchema(PermissionMixIn, ERSchema):
"""return relations whose extremity points to an entity that should
contains the full text index content of entities of this type
"""
for relation_schema in self.subject_relations():
for relation_schema in self.subject_relations.values():
if relation_schema.fulltext_container == "object":
yield relation_schema, "object"
......@@ -648,7 +686,7 @@ class EntitySchema(PermissionMixIn, ERSchema):
if not strict or relation_definition.cardinality[1] in "1+": # type: ignore
return True
for relation_schema in self.subject_relations():
for relation_schema in self.subject_relations.values():
if (relation_schema, "subject") in skip_relations:
continue
......@@ -693,7 +731,7 @@ class EntitySchema(PermissionMixIn, ERSchema):
errors: Dict[str, str] = {}
message_arguments: Dict[str, Any] = {}
i18nvalues: List[str] = []
relations = relations or self.subject_relations()
relations = relations or list(self.subject_relations.values())
for relation_schema in relations:
if not relation_schema.final:
......@@ -1588,7 +1626,7 @@ class Schema:
def del_entity_type(self, entity_type: str) -> None:
entity_schema = self._entities[entity_type]
for relation_schema in list(entity_schema._subject_relations.values()):
for relation_schema in list(entity_schema.subject_relations.values()):
for object_type in relation_schema.objects(entity_type):
self.del_relation_def(entity_schema, relation_schema, object_type)
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment