From 084e5669cdebe4eebac4c3c8ae9c94758841b92d Mon Sep 17 00:00:00 2001 From: David McKee Date: Mon, 2 Dec 2024 17:55:51 +0000 Subject: [PATCH] Validate UUIDs make sense on save --- src/caselawclient/models/identifiers/__init__.py | 12 +++++++++++- tests/models/documents/test_document_identifiers.py | 7 +++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/caselawclient/models/identifiers/__init__.py b/src/caselawclient/models/identifiers/__init__.py index 16d30212..5f6d5b72 100644 --- a/src/caselawclient/models/identifiers/__init__.py +++ b/src/caselawclient/models/identifiers/__init__.py @@ -20,6 +20,10 @@ class InvalidIdentifierXMLRepresentationException(Exception): pass +class UUIDMismatchError(Exception): + pass + + class IdentifierSchema(ABC): """ A base class which describes what an identifier schema should look like. @@ -99,6 +103,12 @@ def url_slug(self) -> str: class Identifiers(dict[str, Identifier]): + def validate(self) -> None: + for uuid, identifier in self.items(): + if uuid != identifier.uuid: + msg = "Key of {identifier} in Identifiers is {uuid} not {identifier.uuid}" + raise UUIDMismatchError(msg) + def add(self, identifier: Identifier) -> None: self[identifier.uuid] = identifier @@ -120,5 +130,5 @@ def as_etree(self) -> etree._Element: def save(self, document) -> None: # type: ignore[no-untyped-def, unused-ignore] """Save the current state of this Document's identifiers to MarkLogic.""" - + self.validate() document.api_client.set_property_as_node(document.uri, "identifiers", self.as_etree) diff --git a/tests/models/documents/test_document_identifiers.py b/tests/models/documents/test_document_identifiers.py index 8c90f7c5..9e6875d1 100644 --- a/tests/models/documents/test_document_identifiers.py +++ b/tests/models/documents/test_document_identifiers.py @@ -1,6 +1,8 @@ +import pytest from lxml import etree from caselawclient.factories import DocumentFactory +from caselawclient.models.identifiers import Identifiers, UUIDMismatchError from tests.models.identifiers.test_identifiers import TestIdentifier @@ -18,6 +20,11 @@ def test_add_identifiers(self): "id-2": identifier_2, } + def test_validate(self): + identifiers = Identifiers({"id-1": TestIdentifier(uuid="id-2", value="TEST-123")}) + with pytest.raises(UUIDMismatchError): + identifiers.validate() + def test_identifiers_as_etree(self): document = DocumentFactory.build()