diff --git a/src/curies/api.py b/src/curies/api.py index 684433f..4970757 100644 --- a/src/curies/api.py +++ b/src/curies/api.py @@ -210,6 +210,18 @@ def __str__(self) -> str: # noqa:D105 return f"Duplicate prefixes:\n{self._str()}" +class ConversionError(ValueError): + """An error raised on conversion.""" + + +class ExpansionError(ConversionError): + """An error raised on expansion if the prefix can't be looked up.""" + + +class CompressionError(ConversionError): + """An error raised on expansion if the URI prefix can't be matched.""" + + def _get_duplicate_uri_prefixes(records: List[Record]) -> List[Tuple[Record, Record, str]]: return [ (record_1, record_2, uri_prefix) @@ -684,6 +696,13 @@ def format_curie(self, prefix: str, identifier: str) -> str: """Format a prefix and identifier into a CURIE string.""" return f"{prefix}{self.delimiter}{identifier}" + def compress_strict(self, uri: str) -> str: + """Compress a URI to a CURIE, and raise an error of not possible.""" + rv = self.compress(uri) + if rv is None: + raise CompressionError(uri) + return rv + def compress(self, uri: str) -> Optional[str]: """Compress a URI to a CURIE, if possible. @@ -733,6 +752,13 @@ def parse_uri(self, uri: str) -> Union[ReferenceTuple, Tuple[None, None]]: else: return ReferenceTuple(prefix, uri[len(value) :]) + def expand_strict(self, curie: str) -> str: + """Expand a CURIE to a URI, and raise an error of not possible.""" + rv = self.expand(curie) + if rv is None: + raise ExpansionError(curie) + return rv + def expand(self, curie: str) -> Optional[str]: """Expand a CURIE to a URI, if possible. diff --git a/tests/test_api.py b/tests/test_api.py index 92a449c..9ad8e2c 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -13,9 +13,11 @@ from bioregistry.export.prefix_maps import EXTENDED_PREFIX_MAP_PATH from curies.api import ( + CompressionError, Converter, DuplicatePrefixes, DuplicateURIPrefixes, + ExpansionError, Record, Reference, ReferenceTuple, @@ -113,10 +115,17 @@ def _assert_convert(self, converter: Converter): ("OBO:unnamespaced", "http://purl.obolibrary.org/obo/unnamespaced"), ]: self.assertEqual(curie, converter.compress(uri)) + self.assertEqual(curie, converter.compress_strict(uri)) self.assertEqual(uri, converter.expand(curie)) + self.assertEqual(uri, converter.expand_strict(curie)) self.assertIsNone(converter.compress("http://example.org/missing:00000")) + with self.assertRaises(CompressionError): + converter.compress_strict("http://example.org/missing:00000") + self.assertIsNone(converter.expand("missing:00000")) + with self.assertRaises(ExpansionError): + converter.expand_strict("missing:00000") self.assertLess(0, len(converter.records), msg="converter has no records") self.assertIsNone(converter.get_record("nope"))