From a9865f5ef72d3810dcebaa50c9bdff8fc1f29020 Mon Sep 17 00:00:00 2001 From: Ralf Grubenmann Date: Mon, 22 May 2023 11:12:17 +0200 Subject: [PATCH] fix: raise proper error on mismatched schema, use string representation as fallback --- calamus/fields.py | 13 +++++++++---- calamus/utils.py | 17 +++++++++++++++++ 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/calamus/fields.py b/calamus/fields.py index 9c3b9f0..e8f8bd2 100644 --- a/calamus/fields.py +++ b/calamus/fields.py @@ -29,7 +29,7 @@ from marshmallow.exceptions import ValidationError from calamus.schema import JsonLDSchema -from calamus.utils import ONTOLOGY_QUERY, Proxy, normalize_type, normalize_value +from calamus.utils import ONTOLOGY_QUERY, Proxy, normalize_type, normalize_value, get_type_name logger = logging.getLogger("calamus") @@ -457,6 +457,7 @@ def schema(self): _schema._visited = self.root._visited self._schema["from"][rdf_type] = _schema self._schema["to"][model] = _schema + self._schema["to"][get_type_name(model)] = _schema else: if isinstance(nest, type) and issubclass(nest, SchemaABC): schema_class = nest @@ -488,6 +489,7 @@ def schema(self): _top_level=False, ) self._schema["to"][model] = self._schema["from"][rdf_type] + self._schema["to"][get_type_name(model)] = self._schema["from"][rdf_type] return self._schema def _serialize_single_obj(self, obj, **kwargs): @@ -505,10 +507,13 @@ def _serialize_single_obj(self, obj, **kwargs): # resolve Proxy object obj = obj.__wrapped__ - if type(obj) not in self.schema["to"]: - ValueError("Type {} not found in field {}.{}".format(type(obj), type(self.parent), self.name)) + if type(obj) in self.schema["to"]: + schema = self.schema["to"][type(obj)] + elif get_type_name(obj) in self.schema["to"]: + schema = self.schema["to"][get_type_name(obj)] + else: + raise ValueError("Type {} not found in field {}.{}".format(type(obj), type(self.parent), self.name)) - schema = self.schema["to"][type(obj)] schema._top_level = False return schema.dump(obj) diff --git a/calamus/utils.py b/calamus/utils.py index 9faa501..67355fe 100644 --- a/calamus/utils.py +++ b/calamus/utils.py @@ -192,3 +192,20 @@ def __getattr__(self, name): raise AttributeError(name) else: return getattr(self.__wrapped__, name) + + +def get_type_name(object) -> str: + """Return fully-qualified object's type name. + + Args: + object: The object to get the type name for. + + Returns: + Optional[str]: The fully qualified type name. + + """ + if object is None: + raise ValueError("Cannot get type name for None.") + + object_type = object if isinstance(object, type) else type(object) + return f"{object_type.__module__}.{object_type.__qualname__}"