diff --git a/docs/release-notes/6.2.28.md b/docs/release-notes/6.2.28.md index 341f6cf1..35abea96 100644 --- a/docs/release-notes/6.2.28.md +++ b/docs/release-notes/6.2.28.md @@ -50,3 +50,38 @@ the figures were measured. See [Counts: not measured, and whose population](../output-formats-and-report-specs.md#counts-not-measured-and-whose-population). + +- **Dr.Egeria link and detach commands that reported success without sending anything.** Before + 6.2.28, the 21 command phrasings below matched no handler in the Collection link processor. They + sent **no request to Egeria** and still reported success: "Operation completed" for a detach, and a + success header for a link. The relationship was **not** removed, or **not** created. If you ran + any of them on 6.2.27 or earlier, re-run that document on 6.2.28. + - Removing a collection member (12): `Detach`, `Remove` or `Unlink`, each followed by `Member from + Collection`, `Member from Folder`, `Member->Collection` or `Member`. + - Linking a collection to a resource (6): `Add`, `Attach` or `Link`, each followed by `Collection + to Resource` or `Collection from Resource`. + - Detaching a collection from a resource (3): `Detach`, `Remove` or `Unlink` followed by + `Collection from Resource`. + + **Already failed, unchanged (10).** These phrasings also matched no handler, but they were never + false successes: `Link Product-Product`, and `Detach`, `Remove` or `Unlink` followed by `Digital + Product from Digital Product`, `Business Capability from Digital Service` or `Business Capability + from Supporting Capability`. They have no command specification, so they fail with "No + specification found" before anything runs, and they still do. Nothing to re-run. + + Commands now pick their handler from the relationship type in their command specification. A + command that matches no handler fails with "nothing was sent to Egeria". +- **Collection to Resource sent no resource.** These commands read a `Resource Id` attribute, but + the command specification names that end `Element Id`. Both names are now accepted. +- **Detach refuses an end that did not resolve.** Every Dr.Egeria detach in this family now fails, + naming the attribute, when an end did not resolve to a GUID. That covers Member, Collection to + Resource, Data Description, Digital Subscriber, Business Capability Dependency, Digital Support, + Product Dependency, Agreement Item and Agreement Actor. Before, a detach sent `None` to Egeria; for + example, `Collection Id` and `Subscription Id` are optional in their specifications. +- **Detach Agreement Actor.** A detach without an explicit relationship `GUID` failed with an + `AttributeError`, because the relationship lookup it needs was missing from the link processor. + Now: + - It fails when `Actors` resolved to nothing, or when no AgreementActor relationship exists for + any listed actor, instead of reporting "Operation completed". + - If only some listed actors have no relationship, it detaches the others and warns about the + rest. diff --git a/md_processing/v2/collection_manager_processor.py b/md_processing/v2/collection_manager_processor.py index 9dee76e0..94a10168 100644 --- a/md_processing/v2/collection_manager_processor.py +++ b/md_processing/v2/collection_manager_processor.py @@ -261,6 +261,32 @@ async def apply_changes(self) -> str: return self.command.raw_block +# Relationship types CollectionLinkProcessor knows how to link and detach, +# keyed by the compact spec's OM_TYPE. +_COLLECTION_LINK_TYPES = frozenset({ + "AgreementItem", "AgreementActor", "CollectionMembership", "DigitalProductDependency", + "BusinessCapabilityDependency", "DigitalSupport", "ResourceList", "DataDescription", + "DigitalSubscriber", +}) + +# Phrase fallbacks for when no compact spec resolved (so there is no OM_TYPE), +# checked in order against the object type. Every command phrasing that +# reaches this processor must land on exactly one relationship type here or +# via OM_TYPE -- a miss raises rather than reporting a no-op as success. +_COLLECTION_LINK_PHRASES = ( + (("Agreement Item", "Agreement to Item", "Agreement from Item"), "AgreementItem"), + (("Agreement Actor", "Agreement to Actor", "Agreement from Actor"), "AgreementActor"), + (("Business Capability Dependency", "Supporting Capability"), "BusinessCapabilityDependency"), + (("Digital Support", "Digital Service"), "DigitalSupport"), + (("Product Dependency", "Digital Product", "Product-Product"), "DigitalProductDependency"), + (("Attach Collection", "Resource List", "Collection to Resource", "Collection from Resource", + "Collection->Resource"), "ResourceList"), + (("Data Description",), "DataDescription"), + (("Subscriber",), "DigitalSubscriber"), + (("Collection Member", "Member"), "CollectionMembership"), +) + + class CollectionLinkProcessor(AsyncBaseCommandProcessor): """ Processor for Agreement Items, Collection Membership, product dependencies, etc. @@ -270,16 +296,72 @@ class CollectionLinkProcessor(AsyncBaseCommandProcessor): async def fetch_as_is(self) -> Optional[Dict[str, Any]]: return None + # The Agreement Actor detach below calls this, but it was only defined on + # CollectionManagerProcessor, so a detach without an explicit relationship + # GUID died with AttributeError. It uses nothing but self.client. + _async_resolve_agreement_actor_relationship_guid = ( + CollectionManagerProcessor._async_resolve_agreement_actor_relationship_guid) + + def _relationship_type(self, object_type: str) -> str: + """Which relationship this command links/detaches, or raise if none. + + The compact spec's OM_TYPE is authoritative: every phrasing of a + command (``Detach Member from Collection``, ``Remove Member``, ...) + resolves to the same spec, whose canonical object type ("Member to + Collection") need not contain the words a substring test looks for. + The phrase table is only a fallback for phrasings no spec resolves. + """ + om_type = getattr(self, "egeria_type_name", None) + if om_type in _COLLECTION_LINK_TYPES: + return om_type + names = [object_type or "", self.command.object_type or ""] + for phrases, rel_type in _COLLECTION_LINK_PHRASES: + if any(p in name for name in names for p in phrases): + return rel_type + raise ValueError( + f"{self.command.verb} {self.command.object_type}: no relationship handler for object type " + f"'{object_type}' (OM_TYPE {om_type!r}); nothing was sent to Egeria") + + def _require_guids(self, attributes: dict, *names: str) -> tuple: + """GUIDs of the named reference attributes, in order, or raise. + + A detach whose end did not resolve must refuse with words, not send + ``None`` to Egeria and not report "Operation completed". + """ + guids = tuple((attributes.get(n) or {}).get('guid') for n in names) + missing = [f"{n} ({(attributes.get(n) or {}).get('value')!r})" for n, g in zip(names, guids) if not g] + if missing: + raise ValueError(f"{self.command.verb} {self.command.object_type}: did not resolve to a GUID: " + f"{', '.join(missing)}; nothing was sent to Egeria") + return guids + + def _resource_list_ends(self, attributes: dict) -> tuple[str, str]: + """(resource guid, collection guid) for a ResourceList link/detach, or raise. + + The compact spec names the resource end "Element Id"; older markdown + used "Resource Id". Accept either, and never send a request with an + unresolved end. + """ + guid_res = ((attributes.get('Resource Id') or {}).get('guid') + or (attributes.get('Element Id') or {}).get('guid')) + guid_coll = (attributes.get('Collection Id') or {}).get('guid') + if not guid_res or not guid_coll: + raise ValueError(f"{self.command.verb} {self.command.object_type}: Collection Id and Element Id " + f"(or Resource Id) must both resolve to a GUID (got {guid_coll!r}, {guid_res!r}); " + f"nothing was sent to Egeria") + return guid_res, guid_coll + async def apply_changes(self) -> str: verb = self.command.verb object_type = self.canonical_object_type attributes = self.parsed_output["attributes"] + rel_type = self._relationship_type(object_type) self.last_body = body = set_rel_request_body(object_type, attributes) new_rel_guids: list[str] = [] if verb in ["Link", "Attach", "Add"]: - if "Agreement Item" in object_type or "Agreement to Item" in object_type: + if rel_type == "AgreementItem": guid1 = attributes.get('Agreement Name', {}).get('guid') guid2 = attributes.get('Item Name', {}).get('guid') body['properties'] = { @@ -312,7 +394,7 @@ async def apply_changes(self) -> str: self.parsed_output["guid"] = rel_guid new_rel_guids.append(rel_guid) - elif "Agreement Actor" in object_type or "Agreement to Actor" in object_type: + elif rel_type == "AgreementActor": guid_ag = attributes.get('Agreement Name', {}).get('guid') actor_data = attributes.get('Actors', {}) actor_guids = actor_data.get('guid_list') or ([actor_data.get('guid')] if actor_data.get('guid') else []) @@ -347,7 +429,7 @@ async def apply_changes(self) -> str: if len(new_rel_guids) == 1: self.parsed_output["guid"] = new_rel_guids[0] - elif "Collection Member" in object_type or "Member to Collection" in object_type: + elif rel_type == "CollectionMembership": guid_coll = attributes.get('Collection Id', {}).get('guid') guid_el = attributes.get('Element Id', {}).get('guid') body['properties'] = { @@ -367,7 +449,7 @@ async def apply_changes(self) -> str: } await self.client._async_add_to_collection(guid_coll, guid_el, body_slimmer(body)) - elif "Product Dependency" in object_type: + elif rel_type == "DigitalProductDependency": guid1 = attributes.get('Digital Product 1', {}).get('guid') guid2 = attributes.get('Digital Product 2', {}).get('guid') body['properties'] = { @@ -398,7 +480,7 @@ async def apply_changes(self) -> str: self.parsed_output["guid"] = rel_guid new_rel_guids.append(rel_guid) - elif "Business Capability Dependency" in object_type: + elif rel_type == "BusinessCapabilityDependency": # BusinessCapabilityDependency is UNI_LINK, so attach is an upsert. body['properties'] = { "class": "BusinessCapabilityDependencyProperties", @@ -409,7 +491,7 @@ async def apply_changes(self) -> str: attributes.get('Dependent Capability', {}).get('guid'), attributes.get('Supporting Capability', {}).get('guid'), body) - elif "Digital Support" in object_type: + elif rel_type == "DigitalSupport": # DigitalSupport is UNI_LINK, so attach is an upsert. body['properties'] = { "class": "DigitalSupportProperties", @@ -420,9 +502,8 @@ async def apply_changes(self) -> str: attributes.get('Supported Capability', {}).get('guid'), attributes.get('Digital Service', {}).get('guid'), body) - elif "Attach Collection" in object_type: - guid_coll = attributes.get('Collection Id', {}).get('guid') - guid_res = attributes.get('Resource Id', {}).get('guid') + elif rel_type == "ResourceList": + guid_res, guid_coll = self._resource_list_ends(attributes) body['properties'] = { "class": "ResourceListProperties", "typeName": "ResourceList", @@ -435,7 +516,7 @@ async def apply_changes(self) -> str: } await self.client._async_attach_collection(guid_res, guid_coll, body) - elif "Data Description" in object_type: + elif rel_type == "DataDescription": guid_coll = attributes.get('Collection Id', {}).get('guid') guid_el = attributes.get('Element Id', {}).get('guid') body['properties'] = { @@ -443,7 +524,7 @@ async def apply_changes(self) -> str: } await self.client._async_attach_data_description(guid_el, guid_coll, body) - elif "Subscriber" in object_type: + elif rel_type == "DigitalSubscriber": guid_sub = attributes.get('Subscriber Id', {}).get('guid') guid_sn = attributes.get('Subscription Id', {}).get('guid') body['properties'] = { @@ -454,6 +535,8 @@ async def apply_changes(self) -> str: "effectiveTo": attributes.get('Effective To', {}).get('value'), } await self.client._async_link_subscriber(guid_sub, guid_sn, body) + else: # _relationship_type() returned a type with no link branch + raise ValueError(f"{verb} {object_type}: no link handler for {rel_type}; nothing was sent to Egeria") logger.success(f"Linked {object_type}") @@ -468,7 +551,7 @@ async def apply_changes(self) -> str: # "GUID" attribute on Detach. label = "Relationship GUID" if len(new_rel_guids) == 1 else "Relationship GUIDs" header += f"### {label}\n" + "\n".join(f"- `{g}`" for g in new_rel_guids) + "\n\n" - if "Member to Collection" in object_type or "Collection Member" in object_type: + if rel_type == "CollectionMembership": header += "### Associated Elements\n" header += f"- **Collection Id**: `{attributes.get('Collection Id', {}).get('value')}`\n" header += f"- **Element Id**: `{attributes.get('Element Id', {}).get('value')}`\n\n" @@ -496,48 +579,65 @@ async def apply_changes(self) -> str: # compatibility with markdown written before this attribute # existed and for the common single-instance case. explicit_rel_guid = (attributes.get("GUID") or {}).get("guid") or (attributes.get("GUID") or {}).get("value") - if "Agreement Item" in object_type or "Agreement to Item" in object_type: + if rel_type == "AgreementItem": if explicit_rel_guid: await self.client._async_detach_agreement_item_by_id(explicit_rel_guid, body) else: - await self.client._async_detach_agreement_item(attributes.get('Agreement Name', {}).get('guid'), attributes.get('Item Name', {}).get('guid'), body) - elif "Agreement Actor" in object_type or "Agreement to Actor" in object_type: - guid_ag = attributes.get('Agreement Name', {}).get('guid') - actor_data = attributes.get('Actors', {}) - actor_guids = actor_data.get('guid_list') or ([actor_data.get('guid')] if actor_data.get('guid') else []) + await self.client._async_detach_agreement_item( + *self._require_guids(attributes, 'Agreement Name', 'Item Name'), body) + elif rel_type == "AgreementActor": if explicit_rel_guid: await self.client._async_detach_agreement_actor(explicit_rel_guid, body) else: + (guid_ag,) = self._require_guids(attributes, 'Agreement Name') + actor_data = attributes.get('Actors') or {} + actor_guids = [g for g in (actor_data.get('guid_list') + or ([actor_data.get('guid')] if actor_data.get('guid') else [])) if g] + if not actor_guids: + raise ValueError(f"{verb} {object_type}: Actors did not resolve to any GUID " + f"({actor_data.get('value')!r}); nothing was sent to Egeria") + detached, not_linked = 0, [] for guid_ac in actor_guids: - if guid_ac: - rel_guid = await self._async_resolve_agreement_actor_relationship_guid(guid_ag, guid_ac) - if rel_guid: - await self.client._async_detach_agreement_actor(rel_guid, body) - else: - logger.warning( - f"No AgreementActor relationship found between agreement {guid_ag} and actor {guid_ac} - skipping detach") - elif "Collection Membership" in object_type or "Collection Member" in object_type: - await self.client._async_remove_from_collection(attributes.get('Collection Id', {}).get('guid'), attributes.get('Element Id', {}).get('guid'), body) - elif "Product Dependency" in object_type: + rel_guid = await self._async_resolve_agreement_actor_relationship_guid(guid_ag, guid_ac) + if rel_guid: + await self.client._async_detach_agreement_actor(rel_guid, body) + detached += 1 + else: + not_linked.append(guid_ac) + logger.warning( + f"No AgreementActor relationship found between agreement {guid_ag} and actor {guid_ac} - skipping detach") + if not detached: + raise ValueError(f"{verb} {object_type}: no AgreementActor relationship found between agreement " + f"{guid_ag} and actor(s) {', '.join(not_linked)}; nothing was sent to Egeria") + if not_linked: + self._add_warning(f"No AgreementActor relationship for actor(s) {', '.join(not_linked)}; " + f"those were not detached") + elif rel_type == "CollectionMembership": + await self.client._async_remove_from_collection( + *self._require_guids(attributes, 'Collection Id', 'Element Id'), body) + elif rel_type == "DigitalProductDependency": if explicit_rel_guid: await self.client._async_detach_digital_product_dependency_by_id(explicit_rel_guid, body) else: - await self.client._async_detach_digital_product_dependency(attributes.get('Digital Product 1', {}).get('guid'), attributes.get('Digital Product 2', {}).get('guid'), body) - elif "Business Capability Dependency" in object_type: + await self.client._async_detach_digital_product_dependency( + *self._require_guids(attributes, 'Digital Product 1', 'Digital Product 2'), body) + elif rel_type == "BusinessCapabilityDependency": await self.client._async_detach_business_capability_dependency( - attributes.get('Dependent Capability', {}).get('guid'), - attributes.get('Supporting Capability', {}).get('guid'), body) - elif "Digital Support" in object_type: + *self._require_guids(attributes, 'Dependent Capability', 'Supporting Capability'), body) + elif rel_type == "DigitalSupport": await self.client._async_detach_digital_support( - attributes.get('Supported Capability', {}).get('guid'), - attributes.get('Digital Service', {}).get('guid'), body) - elif "Attach Collection" in object_type or "Resource List" in object_type: - await self.client._async_detach_collection(attributes.get('Resource Id', {}).get('guid'), attributes.get('Collection Id', {}).get('guid'), body) - elif "Data Description" in object_type: - await self.client._async_detach_data_description(attributes.get('Element Id', {}).get('guid'), attributes.get('Collection Id', {}).get('guid'), body) - elif "Subscriber" in object_type: - await self.client._async_detach_subscriber(attributes.get('Subscriber Id', {}).get('guid'), attributes.get('Subscription Id', {}).get('guid'), body) - + *self._require_guids(attributes, 'Supported Capability', 'Digital Service'), body) + elif rel_type == "ResourceList": + await self.client._async_detach_collection(*self._resource_list_ends(attributes), body) + elif rel_type == "DataDescription": + await self.client._async_detach_data_description( + *self._require_guids(attributes, 'Element Id', 'Collection Id'), body) + elif rel_type == "DigitalSubscriber": + await self.client._async_detach_subscriber( + *self._require_guids(attributes, 'Subscriber Id', 'Subscription Id'), body) + else: # _relationship_type() returned a type with no detach branch + raise ValueError(f"{verb} {object_type}: no detach handler for {rel_type}; nothing was sent to Egeria") + logger.success(f"Detached {object_type}") return f"\n\n## {verb} {object_type}\n\nOperation completed." diff --git a/tests/micro-tests/test_collection_link_detach_dispatch.py b/tests/micro-tests/test_collection_link_detach_dispatch.py new file mode 100644 index 00000000..d0f7bab0 --- /dev/null +++ b/tests/micro-tests/test_collection_link_detach_dispatch.py @@ -0,0 +1,280 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright Contributors to the ODPi Egeria project. +""" +CollectionLinkProcessor must route every command phrasing to a real +relationship call, and must never report "Operation completed" when it sent +nothing. + +Seen live with pyegeria 6.2.27: ``## Detach Member from Collection`` resolves +(via its compact spec's alternate names) to the canonical command "Add Member +to Collection", so the processor's object type is "Member to Collection". The +Detach branch picked its call by substring ("Collection Membership" / +"Collection Member"), matched nothing, sent no request, and still returned +"Operation completed" -- the membership stayed in place. + +These tests go through the real ``setup_dispatcher()`` registry and +``V2Dispatcher.dispatch()`` with a fake client, so command-name resolution, +canonical object type and OM_TYPE are all the production ones. +""" +import uuid +from typing import Any, Dict +from unittest.mock import MagicMock + +import pytest + +from md_processing.dr_egeria import setup_dispatcher +from md_processing.v2.collection_manager_processor import CollectionLinkProcessor +from md_processing.v2.extraction import DrECommand + +COLLECTION_GUID = str(uuid.UUID(int=1)) +ELEMENT_GUID = str(uuid.UUID(int=2)) +RESOURCE_GUID = str(uuid.UUID(int=3)) + + +class _FakeClient: + """Records the relationship calls the processor makes; nothing else.""" + + def __init__(self): + self.calls: list[tuple] = [] + + def __getattr__(self, name): + # Any other client method (lookups during validation) -> AttributeError + # is what a missing method looks like; keep unknown _async_ calls + # visible instead of silently succeeding. + raise AttributeError(name) + + async def _async_remove_from_collection(self, collection_guid, element_guid, body=None): + self.calls.append(("remove_from_collection", collection_guid, element_guid)) + + async def _async_add_to_collection(self, collection_guid, element_guid, body=None): + self.calls.append(("add_to_collection", collection_guid, element_guid)) + + async def _async_attach_collection(self, resource_guid, collection_guid, body=None): + self.calls.append(("attach_collection", resource_guid, collection_guid)) + + async def _async_detach_collection(self, resource_guid, collection_guid, body=None): + self.calls.append(("detach_collection", resource_guid, collection_guid)) + + +def _command(verb: str, object_type: str, attributes: Dict[str, str]) -> DrECommand: + raw = f"## {verb} {object_type}\n" + "".join(f"### {k}\n{v}\n" for k, v in attributes.items()) + return DrECommand(verb=verb, object_type=object_type, attributes=attributes, raw_block=raw) + + +async def _dispatch(client, verb, object_type, attributes): + dispatcher = setup_dispatcher(client) + context: Dict[str, Any] = {"directive": "process"} + return await dispatcher.dispatch(_command(verb, object_type, attributes), context) + + +MEMBER_ATTRS = {"Collection Id": COLLECTION_GUID, "Element Id": ELEMENT_GUID} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("verb,object_type", [ + ("Detach", "Member from Collection"), # the live failure + ("Remove", "Member from Collection"), + ("Unlink", "Member"), + ("Detach", "Member from Folder"), +]) +async def test_detach_member_sends_exactly_one_remove(verb, object_type): + client = _FakeClient() + result = await _dispatch(client, verb, object_type, MEMBER_ATTRS) + + assert client.calls == [("remove_from_collection", COLLECTION_GUID, ELEMENT_GUID)], result + assert result["status"] == "success", result + + +@pytest.mark.asyncio +async def test_add_member_still_sends_one_add(): + client = _FakeClient() + result = await _dispatch(client, "Add", "Member to Collection", MEMBER_ATTRS) + + assert client.calls == [("add_to_collection", COLLECTION_GUID, ELEMENT_GUID)], result + assert result["status"] == "success", result + + +@pytest.mark.asyncio +@pytest.mark.parametrize("verb,expected", [ + ("Attach", "attach_collection"), + ("Detach", "detach_collection"), +]) +async def test_collection_to_resource_phrasings_route(verb, expected): + # Same shape as the member bug: "Attach Collection to Resource" resolves + # to object type "Collection to Resource", which neither the old Link + # test ("Attach Collection") nor the old Detach test matched. + client = _FakeClient() + attrs = {"Collection Id": COLLECTION_GUID, "Element Id": RESOURCE_GUID} # spec names the resource end "Element Id" + noun = "Collection to Resource" if verb == "Attach" else "Collection from Resource" + result = await _dispatch(client, verb, noun, attrs) + + assert client.calls == [(expected, RESOURCE_GUID, COLLECTION_GUID)], result + assert result["status"] == "success", result + + +@pytest.mark.asyncio +@pytest.mark.parametrize("verb", ["Detach", "Link"]) +async def test_unmatched_object_type_fails_loudly(verb): + """A relationship type no branch handles must fail, never 'Operation completed'.""" + client = _FakeClient() + command = _command(verb, "Gizmo Widget", {}) + p = CollectionLinkProcessor(client=client, command=command, context={}) + p.canonical_object_type = "Gizmo Widget" + p.egeria_type_name = "GizmoWidget" + p.parsed_output = {"qualified_name": "", "attributes": {}} + + with pytest.raises(ValueError, match="nothing was sent to Egeria"): + await p.apply_changes() + assert client.calls == [] + + +@pytest.mark.asyncio +async def test_detach_member_without_guids_fails(): + client = _FakeClient() + command = _command("Detach", "Member from Collection", {}) + p = CollectionLinkProcessor(client=client, command=command, context={}) + p.parsed_output = {"qualified_name": "", "attributes": {"Collection Id": {"value": "x"}}} + + with pytest.raises(ValueError, match="did not resolve to a GUID"): + await p.apply_changes() + assert client.calls == [] + + +def test_every_registered_phrasing_resolves_to_a_relationship(): + """Every Link/Detach phrasing routed to CollectionLinkProcessor lands on a handler.""" + dispatcher = setup_dispatcher(MagicMock()) + misses = [] + for key, cls in dispatcher.processors.items(): + if cls is not CollectionLinkProcessor: + continue + verb, _, noun = key.partition(" ") + if verb not in ("Link", "Attach", "Add", "Detach", "Unlink", "Remove"): + continue + p = CollectionLinkProcessor(client=MagicMock(), command=_command(verb, noun, {}), context={}) + try: + p._relationship_type(p.canonical_object_type) + except ValueError: + misses.append(key) + assert misses == [] + + +# --- Every detach branch refuses an unresolved end (read-back P3) --------------- + +G1, G2 = COLLECTION_GUID, ELEMENT_GUID + + +class _RecordingClient: + """Records every _async_detach_* / _async_remove_* call; other lookups fail.""" + + def __init__(self, relationships=None): + self.calls: list[tuple] = [] + self.relationships = relationships if relationships is not None else [] + + async def _async_get_relationships(self, *args, **kwargs): + return self.relationships + + def __getattr__(self, name): + if name.startswith(("_async_detach", "_async_remove")): + async def _record(*args, **kwargs): + self.calls.append((name, args[:-1])) + return _record + raise AttributeError(name) + + +# (object type, both ends resolved, expected call, the end left out) +DETACH_CASES = [ + ("Data Description", {"Element Id": G1, "Collection Id": G2}, + ("_async_detach_data_description", (G1, G2)), "Collection Id"), + ("Digital Subscriber", {"Subscriber Id": G1, "Subscription Id": G2}, + ("_async_detach_subscriber", (G1, G2)), "Subscription Id"), + ("Member from Collection", {"Collection Id": G1, "Element Id": G2}, + ("_async_remove_from_collection", (G1, G2)), "Collection Id"), + ("Business Capability Dependency", {"Dependent Capability": G1, "Supporting Capability": G2}, + ("_async_detach_business_capability_dependency", (G1, G2)), "Supporting Capability"), + ("Digital Support", {"Supported Capability": G1, "Digital Service": G2}, + ("_async_detach_digital_support", (G1, G2)), "Digital Service"), + ("Product Dependency", {"Digital Product 1": G1, "Digital Product 2": G2}, + ("_async_detach_digital_product_dependency", (G1, G2)), "Digital Product 2"), + ("Agreement Item", {"Agreement Name": G1, "Item Name": G2}, + ("_async_detach_agreement_item", (G1, G2)), "Item Name"), +] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("object_type,attrs,expected,_missing", DETACH_CASES, + ids=[c[0] for c in DETACH_CASES]) +async def test_detach_with_both_ends_sends_one_call(object_type, attrs, expected, _missing): + client = _RecordingClient() + result = await _dispatch(client, "Detach", object_type, attrs) + + assert client.calls == [expected], result + assert result["status"] == "success", result + + +@pytest.mark.asyncio +@pytest.mark.parametrize("object_type,attrs,_expected,missing", DETACH_CASES, + ids=[c[0] for c in DETACH_CASES]) +async def test_detach_with_an_end_left_out_fails_and_sends_nothing(object_type, attrs, _expected, missing): + """Through the real dispatcher: an omitted end never reaches Egeria as None. + + Optional ends (Collection Id, Subscription Id) pass validation and are + refused by the processor; required ends are refused by validation first. + Either way: failure, no call, no "Operation completed". + """ + client = _RecordingClient() + attrs = {k: v for k, v in attrs.items() if k != missing} + result = await _dispatch(client, "Detach", object_type, attrs) + + assert client.calls == [], result + assert result["status"] == "failure", result + assert "Operation completed" not in str(result.get("output", "")), result + assert missing in result["message"], result + + +@pytest.mark.asyncio +@pytest.mark.parametrize("object_type,attrs,_expected,missing", DETACH_CASES, + ids=[c[0] for c in DETACH_CASES]) +async def test_detach_backstop_refuses_unresolved_end(object_type, attrs, _expected, missing): + """The processor itself refuses, even when validation let an end through unresolved.""" + client = _RecordingClient() + command = _command("Detach", object_type, {}) + p = CollectionLinkProcessor(client=client, command=command, context={}) + parsed = {k: {"value": v, "guid": v} for k, v in attrs.items()} + parsed[missing] = {"value": "Unresolved Name", "guid": None} + p.parsed_output = {"qualified_name": "", "attributes": parsed} + + with pytest.raises(ValueError, match=f"did not resolve to a GUID: {missing}"): + await p.apply_changes() + assert client.calls == [] + + +@pytest.mark.asyncio +async def test_detach_agreement_actor_without_actors_fails(): + client = _RecordingClient() + result = await _dispatch(client, "Detach", "Agreement Actor", {"Agreement Name": G1}) + + assert client.calls == [], result + assert result["status"] == "failure", result + assert "Actors did not resolve" in result["message"], result + + +@pytest.mark.asyncio +async def test_detach_agreement_actor_not_linked_fails(): + """No AgreementActor relationship between the pair: refuse, don't report success.""" + client = _RecordingClient(relationships=[]) + result = await _dispatch(client, "Detach", "Agreement Actor", {"Agreement Name": G1, "Actors": G2}) + + assert client.calls == [], result + assert result["status"] == "failure", result + assert "no AgreementActor relationship found" in result["message"], result + + +@pytest.mark.asyncio +async def test_detach_agreement_actor_by_pair_detaches_the_found_relationship(): + """The pair lookup is reachable from CollectionLinkProcessor (was AttributeError).""" + client = _RecordingClient(relationships=[ + {"relationshipGUID": "rel-1", "elementGUIDAtEnd1": G1, "elementGUIDAtEnd2": G2}]) + result = await _dispatch(client, "Detach", "Agreement Actor", {"Agreement Name": G1, "Actors": G2}) + + assert client.calls == [("_async_detach_agreement_actor", ("rel-1",))], result + assert result["status"] == "success", result