diff --git a/pyegeria/view/dashboard_sheet_registry.py b/pyegeria/view/dashboard_sheet_registry.py index e2b847fa..281c680f 100644 --- a/pyegeria/view/dashboard_sheet_registry.py +++ b/pyegeria/view/dashboard_sheet_registry.py @@ -8,13 +8,16 @@ two stay co-elements: same env-var-driven JSON config pattern, same runtime registration API, same collision semantics. -Unlike report specs, there is no generated/built-in source here — no -Tinderbox/`refresh_specs` pipeline authors dashboard sheets as Egeria -elements (yet; see egeria-workspaces `OVERVIEW_REPORTING_MODEL.md` §10 for -the plan — Dashboard Sheet is planned to become an Egeria `Collection` -subtype). The registry is CONFIG (env-var JSON files) + RUNTIME (dynamically -registered, e.g. by the Dr.Egeria `Create Dashboard Sheet` command's -processor) only. +Unlike report specs, there is no generated/built-in source here. The tiers, +lowest first: + - EGERIA: sheets held in Egeria 6.3 as Dashboard element chains + (`pyegeria.view.dashboards`), loaded with `refresh_egeria_dashboard_sheets(client)` + or set with `set_egeria_dashboard_sheets(...)`. Never fetched implicitly: reading + the registry makes no Egeria call. + - CONFIG (env-var JSON files) and RUNTIME (registered at run time): the local + sources. Same precedence as report specs: a local sheet overrides a same-named + Egeria sheet, with one warning per name per process; never raised. +`get_dashboard_sheet_tier(name)` says which tier a sheet came from. This module is hand-written and safe to edit — unlike `base_report_formats.py`, nothing regenerates it. @@ -30,6 +33,10 @@ __all__ = [ 'DashboardSheetCollision', + 'clear_egeria_dashboard_sheets', + 'get_dashboard_sheet_tier', + 'refresh_egeria_dashboard_sheets', + 'set_egeria_dashboard_sheets', 'refresh_dashboard_sheets', 'get_dashboard_sheet_registry', 'register_dashboard_sheets', @@ -39,6 +46,9 @@ _RUNTIME_DASHBOARD_SHEETS = DashboardSheetDict() _CONFIG_DASHBOARD_SHEETS = DashboardSheetDict() +_EGERIA_DASHBOARD_SHEETS = DashboardSheetDict() +_REGISTRY_TIERS: dict = {} +_SHADOW_WARNED: set = set() class DashboardSheetCollision(ValueError): @@ -101,21 +111,72 @@ def refresh_dashboard_sheets() -> None: def get_dashboard_sheet_registry() -> DashboardSheetDict: - """Combine config-loaded and runtime dashboard sheets. Enforce no - duplicate names across sources.""" + """Combine the Egeria, config-loaded and runtime dashboard sheets. + + The local sources (CONFIG, RUNTIME) must not repeat a name between them (that raises, as before). A + local sheet overrides a same-named Egeria sheet: the Egeria one is left out, with one warning per name + per process.""" + local = DashboardSheetDict() + _add_with_collision_check(local, _CONFIG_DASHBOARD_SHEETS, source="CONFIG") + _add_with_collision_check(local, _RUNTIME_DASHBOARD_SHEETS, source="RUNTIME") + combined = DashboardSheetDict() - _add_with_collision_check(combined, _CONFIG_DASHBOARD_SHEETS, source="CONFIG") - _add_with_collision_check(combined, _RUNTIME_DASHBOARD_SHEETS, source="RUNTIME") + tiers = {} + for name, sheet in _EGERIA_DASHBOARD_SHEETS.items(): + if name in local.keys(): + if name not in _SHADOW_WARNED: + _SHADOW_WARNED.add(name) + logger.warning(f"Dashboard Sheet '{name}' is defined locally and held in Egeria; the local " + f"definition is used.") + continue + combined[name] = sheet + tiers[name] = "egeria" + for name, sheet in local.items(): + combined[name] = sheet + tiers[name] = "local" + _REGISTRY_TIERS.clear() + _REGISTRY_TIERS.update(tiers) return combined +def get_dashboard_sheet_tier(name: str): + """"egeria" or "local" for a sheet in the last registry read, else None.""" + if not _REGISTRY_TIERS: + get_dashboard_sheet_registry() + return _REGISTRY_TIERS.get(name) + + +def set_egeria_dashboard_sheets(sheets) -> None: + """Replace the EGERIA tier with these sheets (a DashboardSheetDict, a dict, or a list of sheets).""" + global _EGERIA_DASHBOARD_SHEETS + if isinstance(sheets, list): + sheets = {s.name: s for s in sheets} + _EGERIA_DASHBOARD_SHEETS = sheets if isinstance(sheets, DashboardSheetDict) else DashboardSheetDict(sheets) + + +def refresh_egeria_dashboard_sheets(client=None) -> int: + """Load the EGERIA tier from Egeria (`pyegeria.view.dashboards.list_dashboard_sheets`). Returns the + number of sheets. With no client, one is made from the environment.""" + from pyegeria.view.dashboards import list_dashboard_sheets + sheets = list_dashboard_sheets(client) + set_egeria_dashboard_sheets(sheets) + return len(sheets) + + +def clear_egeria_dashboard_sheets() -> None: + _EGERIA_DASHBOARD_SHEETS.clear() + _SHADOW_WARNED.clear() + + def register_dashboard_sheets(new_sheets: Union[DashboardSheetDict, dict], *, source: str = "runtime") -> None: """Dynamically add dashboard sheets at runtime. Raises on duplicate name.""" global _RUNTIME_DASHBOARD_SHEETS if not isinstance(new_sheets, DashboardSheetDict): new_sheets = DashboardSheetDict(new_sheets) - existing = get_dashboard_sheet_registry() - for name in new_sheets.keys(): + existing = DashboardSheetDict() + _add_with_collision_check(existing, _CONFIG_DASHBOARD_SHEETS, source="CONFIG") + _add_with_collision_check(existing, _RUNTIME_DASHBOARD_SHEETS, source="RUNTIME") + for name in new_sheets.keys(): # a runtime sheet may override an Egeria one; not another local one if name in existing.keys(): raise DashboardSheetCollision( f"Dashboard Sheet '{name}' already exists; cannot register from {source}") diff --git a/pyegeria/view/dashboards.py b/pyegeria/view/dashboards.py new file mode 100644 index 00000000..f60a9d6a --- /dev/null +++ b/pyegeria/view/dashboards.py @@ -0,0 +1,442 @@ +""" +SPDX-License-Identifier: Apache-2.0 +Copyright Contributors to the ODPi Egeria project. + +Dashboard sheets held in Egeria: the reader, and the migration from the local JSON store +(report-spec pipeline note v5.5 §8d / §10.6(c); BRIEF RS-DASH PR-2). + + load_dashboard_sheet(name) -> the sheet, read from its Egeria element chain, or None + list_dashboard_sheets() -> every sheet held in Egeria (Dashboard::* elements) + +Both return today's `DashboardSheet` / `Placement` model, so a consumer keeps its code. The objects are the +subclasses `EgeriaDashboardSheet` / `EgeriaPlacement`, which add only what an Egeria-held sheet must say: +`source` ("egeria"), a placement's `kind` ("report" / "text" / "missing") and `note`, and a sheet's `breaks`. +`as_local_model()` drops those, giving a plain `DashboardSheet` that compares equal to the JSON record it +was written from. + +Absence and drift are said in words, never as an empty value: + - a REPORT placement whose field exists but whose DataSetContent link is gone reads `kind: "missing"`, + note "report link missing in Egeria" (its `ref` is the placement's name, so it can still be shown); + - a sheet whose chain is broken (no layout schema, no sheet container) is listed with the break named + in `breaks`, not dropped; + - a placement whose stored perspective labels or drill-down name disagree with its ScopedBy / + DataDescription links (edited in Egeria directly) gets a note naming the difference. + +The chain is walked with the same primitives that write it (md_processing.v2.dashboard_sheet), so the +writer and the reader cannot disagree about its shape. Every Egeria read is bounded: page size 25, +graph_query_depth 0, paged until an empty page. + +Command line (writes are shared writes: run them only with the owner's word and the Coordinator's CLEAR): + + python -m pyegeria.view.dashboards list + python -m pyegeria.view.dashboards show NAME + python -m pyegeria.view.dashboards migrate [--sheet NAME] [--rename NEW_NAME] [--store PATH] [--dry-run] + python -m pyegeria.view.dashboards delete --sheet NAME [--dry-run] [--local] + +`migrate` reads the JSON store and writes each sheet through PR-1's writer (one implementation); it is +idempotent by qualifiedName, and `--dry-run` lists every element it would create. It never writes the +store. `delete` removes a sheet's Egeria chain (never its Reports or ReportSpecs); `--local` also removes +the store record. +""" +from __future__ import annotations + +import argparse +import os +import sys +from typing import Any, Dict, List, Literal, Optional + +from loguru import logger +from pydantic import Field + +from md_processing.v2.dashboard_sheet import ( + DASHBOARD_QN_PREFIX, DashboardSheetEgeriaWriter, _default_store_path, _load_store, dashboard_qn, + perspective_qualified_name, sheet_name_from_dashboard_qn, +) +from pyegeria.view._output_dashboard_sheet_models import DashboardSheet, DashboardSheetDict, Placement + +__all__ = [ + "EgeriaDashboardSheet", "EgeriaPlacement", "REPORT_LINK_MISSING", "as_local_model", + "async_list_dashboard_sheets", "async_load_dashboard_sheet", "async_migrate_dashboard_sheets", + "list_dashboard_sheets", "load_dashboard_sheet", "main", "read_sheet_from_chain", +] + +PAGE_SIZE = 25 +REPORT_LINK_MISSING = "report link missing in Egeria" +_SPANS = ("1", "2", "full") +_STYLES = ("kpi", "panel") + + +class EgeriaPlacement(Placement): + """A Placement read from Egeria. `kind`: "report", "text", or "missing" (a report placement whose + report link is gone); `note` says what is missing or odd, in words.""" + kind: Literal["report", "text", "missing"] = "report" + note: Optional[str] = None + source: str = "egeria" + + +class EgeriaDashboardSheet(DashboardSheet): + """A DashboardSheet read from Egeria. `breaks` names each broken link of its element chain (empty when + the chain is whole); `guid` is the Dashboard's.""" + source: str = "egeria" + guid: Optional[str] = None + breaks: List[str] = Field(default_factory=list) + + +def as_local_model(sheet: DashboardSheet) -> DashboardSheet: + """The plain DashboardSheet / Placement form of a sheet (Egeria-only fields dropped), as the JSON store + holds it. A whole Egeria sheet compares equal to the record it was written from.""" + base_fields = set(Placement.model_fields) + placements = [Placement(**{k: v for k, v in (p if isinstance(p, dict) else p.model_dump()).items() + if k in base_fields}) for p in sheet.placements] + return DashboardSheet(name=sheet.name, heading=sheet.heading, description=sheet.description, + aliases=list(sheet.aliases), family=sheet.family, placements=placements) + + +# ---------------------------------------------------------------------------- reading + +def _split_labels(value: Any) -> List[str]: + if isinstance(value, list): + return [str(v).strip() for v in value if str(v).strip()] + return [p.strip() for p in str(value or "").split(",") if p.strip()] + + +async def _scoped_by_qns(writer: DashboardSheetEgeriaWriter, field_guid: str) -> List[str]: + """qualifiedNames of the Perspectives linked to a placement by ScopedBy.""" + return [(e.get("properties") or {}).get("qualifiedName") or "" + for e in await writer._related(field_guid, "ScopedBy", start_at_end=2) + if writer._type(e) == "Perspective"] + + +async def _data_descriptions(writer: DashboardSheetEgeriaWriter, field_guid: str) -> List[Dict[str, Any]]: + return [e.get("properties") or {} for e in await writer._related(field_guid, "DataDescription", start_at_end=1)] + + +def _perspective_drift(labels: List[str], linked_qns: List[str]) -> List[str]: + """Where the stored labels and the ScopedBy links disagree (someone edited one in Egeria), in words.""" + expected = {perspective_qualified_name(label): label for label in labels} + notes = [] + unlinked = [label for qn, label in expected.items() if qn not in linked_qns] + extra = [qn for qn in linked_qns if qn not in expected] + if unlinked: + notes.append(f"stored perspective(s) {', '.join(unlinked)} have no ScopedBy link in Egeria") + if extra: + notes.append(f"ScopedBy link(s) to {', '.join(extra)} are not in the stored perspectives") + return notes + + +def _detail_drift(stored: Optional[str], linked: List[Dict[str, Any]]) -> List[str]: + """A DataDescription link that the stored drill-down name does not explain. A stored name with no link is + not drift: a spec held only in pyegeria has no element to link to.""" + names = [] + for props in linked: + qn = props.get("qualifiedName") or "" + names.append((props.get("displayName"), qn, qn.split("::", 1)[1] if "::" in qn else qn)) + if not names: + return [] + if stored and any(stored in n for n in names): + return [] + shown = ", ".join(n[1] or n[0] or "?" for n in names) + return [f"DataDescription links to {shown}, but the stored drill-down is {stored or 'none'}"] + + +async def read_sheet_from_chain(client: Any, sheet_name: str, + dashboard: Optional[Dict[str, Any]] = None) -> Optional[EgeriaDashboardSheet]: + """Read one sheet by walking its Egeria chain. None if there is no `Dashboard::`.""" + writer = DashboardSheetEgeriaWriter(client) + chain = await writer.find_chain(sheet_name) + if not chain.dashboard_guid: + return None + props = (chain.dashboard or dashboard or {}).get("properties") or {} + extra = props.get("additionalProperties") or {} + sheet = EgeriaDashboardSheet( + name=sheet_name, heading=props.get("displayName") or sheet_name, + description=props.get("description") or "", aliases=list(props.get("aliases") or []), + family=extra.get("family") or None, guid=chain.dashboard_guid) + + if not chain.schema_type_guid: + sheet.breaks.append("no layout schema: the Dashboard has no Schema link to a DisplayDataSchemaType") + return sheet + if not chain.container_guid: + sheet.breaks.append("no sheet container: the DisplayDataSchemaType has no AttributeForSchema link to a " + "DisplayDataContainer") + return sheet + + fields = await writer.list_fields(chain.container_guid) + bindings: Dict[str, Dict[str, Any]] = {} + report_qns = [f.qualified_name for f in fields if (f.properties.get("placementKind") or "report") != "text"] + if report_qns: + bindings = await client.asset_maker._async_get_placement_reports(chain.dashboard_guid, report_qns) or {} + + for f in fields: + fp = f.properties + f_extra = fp.get("additionalProperties") or {} + notes: List[str] = [] + if f.position is None: + notes.append("no position on its NestedSchemaAttribute link; shown last") + span = str(fp.get("span") or "1") + if span not in _SPANS: + notes.append(f"span '{span}' is not one of {', '.join(_SPANS)}; shown as 1") + span = "1" + style = str(fp.get("presentationStyle") or "kpi") + if style not in _STYLES: + notes.append(f"presentationStyle '{style}' is not one of {', '.join(_STYLES)}; shown as kpi") + style = "kpi" + # The labels and drill-down name stored on the field are what the author wrote; the ScopedBy / + # DataDescription links carry the graph meaning. Read both, and say where they disagree. + linked_qns = await _scoped_by_qns(writer, f.guid) + if "perspectives" in f_extra: + perspectives = _split_labels(f_extra.get("perspectives")) + notes += _perspective_drift(perspectives, linked_qns) + else: + perspectives = [qn.split("::", 1)[1] if qn.startswith("Perspective::") else qn for qn in linked_qns] + linked_specs = await _data_descriptions(writer, f.guid) + detail_spec = f_extra.get("detailSpec") or None + if "detailSpec" in f_extra or "placementName" in f_extra: + notes += _detail_drift(detail_spec, linked_specs) + if detail_spec is None and linked_specs: + detail_spec = linked_specs[0].get("displayName") or linked_specs[0].get("qualifiedName") + + kind = fp.get("placementKind") or "report" + if kind == "text": + content = fp.get("markdownContent") + if content is None: + notes.append("text placement with no markdownContent in Egeria") + content = "" + placement = EgeriaPlacement(ref=f.display_name, span=span, emphasis=style, content=content, + perspectives=perspectives, detail_spec=detail_spec, kind="text") + else: + binding = bindings.get(f.qualified_name) or {"state": "unbound", "links": []} + if binding.get("state") == "bound" and binding.get("report_name"): + placement = EgeriaPlacement(ref=binding["report_name"], span=span, emphasis=style, + perspectives=perspectives, detail_spec=detail_spec, kind="report") + else: + if binding.get("state") == "ambiguous": + notes.insert(0, f"{len(binding['links'])} reports are linked to this placement in Egeria; " + f"none is chosen") + else: + notes.insert(0, REPORT_LINK_MISSING) + placement = EgeriaPlacement(ref=f.display_name, span=span, emphasis=style, + perspectives=perspectives, detail_spec=detail_spec, kind="missing") + if notes: + placement.note = "; ".join(notes) + sheet.placements.append(placement) + return sheet + + +async def async_load_dashboard_sheet(client: Any, name: str) -> Optional[EgeriaDashboardSheet]: + """The Egeria-held sheet `name` (its Dashboard is `Dashboard::`), or None.""" + return await read_sheet_from_chain(client, name) + + +async def _dashboard_elements(client: Any) -> List[Dict[str, Any]]: + """Every Dashboard whose qualifiedName starts `Dashboard::`. Read by type in pages of 25 (Dashboard is a + small type; only an empty page ends the read) and filtered here: a starts-with search on qualifiedName + took 21 s on the live platform with no Dashboards at all, the type read 2.8 s.""" + out: List[Dict[str, Any]] = [] + start = 0 + while True: + page = await client.classification_manager._async_get_elements( + "Dashboard", start_from=start, page_size=PAGE_SIZE, graph_query_depth=0) + items = [e for e in page if isinstance(e, dict) and e.get("elementHeader")] if isinstance(page, list) else [] + if not items: + return out + out.extend(e for e in items + if ((e.get("properties") or {}).get("qualifiedName") or "").startswith(DASHBOARD_QN_PREFIX)) + start += len(items) + + +async def async_list_dashboard_sheets(client: Any) -> List[EgeriaDashboardSheet]: + """Every sheet held in Egeria, by name. A Dashboard whose chain is broken (for example one made with + plain `Create Dashboard`) is listed with its `breaks`, not dropped.""" + sheets: List[EgeriaDashboardSheet] = [] + seen = set() + for element in await _dashboard_elements(client): + name = sheet_name_from_dashboard_qn((element.get("properties") or {}).get("qualifiedName") or "") + if not name or name in seen: + continue + seen.add(name) + sheet = await read_sheet_from_chain(client, name, dashboard=element) + if sheet is not None: + sheets.append(sheet) + sheets.sort(key=lambda s: s.name.lower()) + return sheets + + +def _client_from_env() -> Any: + """An EgeriaTech client from the environment (EGERIA_VIEW_SERVER, EGERIA_VIEW_SERVER_URL or + EGERIA_PLATFORM_URL, EGERIA_USER / EGERIA_USER_PASSWORD, else pyegeria's settings), not yet signed in.""" + from pyegeria import EgeriaTech + from pyegeria.core.config import resolve_egeria_credentials, settings + server = os.environ.get("EGERIA_VIEW_SERVER") or settings.Environment.egeria_view_server + url = (os.environ.get("EGERIA_VIEW_SERVER_URL") or os.environ.get("EGERIA_PLATFORM_URL") + or settings.Environment.egeria_view_server_url) + user, pwd = resolve_egeria_credentials() + return EgeriaTech(server, url, user, pwd) + + +async def _signed_in_client() -> Any: + client = _client_from_env() + await client._async_create_egeria_bearer_token(client.user_id, client.user_pwd) + return client + + +def load_dashboard_sheet(name: str, client: Any = None) -> Optional[EgeriaDashboardSheet]: + """Sync form of async_load_dashboard_sheet. With no client, one is made from the environment.""" + from pyegeria.core.async_runner import run_sync + + async def _go(): + return await async_load_dashboard_sheet(client or await _signed_in_client(), name) + return run_sync(_go()) + + +def list_dashboard_sheets(client: Any = None) -> List[EgeriaDashboardSheet]: + """Sync form of async_list_dashboard_sheets. With no client, one is made from the environment.""" + from pyegeria.core.async_runner import run_sync + + async def _go(): + return await async_list_dashboard_sheets(client or await _signed_in_client()) + return run_sync(_go()) + + +# ---------------------------------------------------------------------------- migration + +async def async_migrate_dashboard_sheets(client: Any, sheets: DashboardSheetDict, *, + only: Optional[str] = None, rename: Optional[str] = None, + dry_run: bool = False, + owner: Optional[str] = None) -> Dict[str, DashboardSheetEgeriaWriter]: + """Write sheets from the JSON store to Egeria through the PR-1 writer, one writer per sheet (so each + sheet's actions and notes stay apart). Idempotent by qualifiedName. Never writes the store. + + `only` picks one sheet; `rename` writes it under another name (a scratch copy, e.g. for a live test). + DB-3: the sheets are shared (default zone) and owned by `owner`, by default the client's user. + """ + if rename and not only: + raise ValueError("--rename needs --sheet: it renames one sheet") + if owner is None: + owner = getattr(client, "user_id", None) + selected = [sheets[only]] if only else list(sheets.values()) + results: Dict[str, DashboardSheetEgeriaWriter] = {} + for sheet in selected: + target = sheet.model_copy(deep=True) + if rename: + target.name = rename + writer = DashboardSheetEgeriaWriter(client, dry_run=dry_run) + chain = await writer.write_sheet(target) + if owner: + await _ensure_ownership(writer, chain.dashboard_guid, dashboard_qn(target.name), owner) + results[target.name] = writer + return results + + +async def _ensure_ownership(writer: DashboardSheetEgeriaWriter, dashboard_guid: Optional[str], qn: str, + owner: str) -> None: + """DB-3: a migrated sheet is owned by the user who migrates it -- the Dashboard's Ownership + classification (owner = that userId). Left alone when the Dashboard already has an owner. No zone is + set: the sheet is shared, in the default zone.""" + current = None if writer._is_planned(dashboard_guid) else await writer._find(qn) + header = (current or {}).get("elementHeader") or {} + if header.get("ownership"): + writer.actions.append(f"unchanged Ownership {qn}") + return + writer.actions.append(f"classify Ownership {qn} (owner {owner})") + if writer.dry_run: + return + await writer.client.classification_manager._async_add_ownership_to_element( + dashboard_guid, {"class": "NewClassificationRequestBody", + "properties": {"class": "OwnershipProperties", "owner": owner, + "ownerTypeName": "UserIdentity", "ownerPropertyName": "userId"}}) + + +# ---------------------------------------------------------------------------- command line + +def _print_actions(name: str, writer: DashboardSheetEgeriaWriter, dry_run: bool) -> None: + changed = [a for a in writer.actions if not a.startswith("unchanged")] + title = "would make" if dry_run else "made" + print(f"\n== {name}: {title} {len(changed)} change(s), {len(writer.actions) - len(changed)} unchanged") + for action in writer.actions: + print(f" {'(dry run) ' if dry_run and not action.startswith('unchanged') else ''}{action}") + for note in writer.notes: + print(f" NOTE: {note}") + + +def _print_sheet(sheet: EgeriaDashboardSheet) -> None: + print(f"{sheet.name} | {sheet.heading} | {len(sheet.placements)} placement(s)" + + (f" | BROKEN: {'; '.join(sheet.breaks)}" if sheet.breaks else "")) + for i, p in enumerate(sheet.placements, start=1): + print(f" {i:>2}. [{p.kind}] {p.ref} (span {p.span}, {p.emphasis})" + + (f" perspectives={','.join(p.perspectives)}" if p.perspectives else "") + + (f" detail={p.detail_spec}" if p.detail_spec else "") + + (f" -- {p.note}" if p.note else "")) + + +async def _amain(args: argparse.Namespace) -> int: + client = await _signed_in_client() + if args.command == "list": + for sheet in await async_list_dashboard_sheets(client): + _print_sheet(sheet) + return 0 + if args.command == "show": + sheet = await async_load_dashboard_sheet(client, args.name) + if sheet is None: + print(f"No dashboard sheet '{args.name}' in Egeria (looked for {dashboard_qn(args.name)}).") + return 1 + _print_sheet(sheet) + return 0 + if args.command == "migrate": + store = args.store or _default_store_path() + sheets = _load_store(store) + if args.sheet and args.sheet not in sheets: + print(f"No sheet '{args.sheet}' in {store}.") + return 1 + print(f"Migrating from {store}{' (DRY RUN: nothing is written)' if args.dry_run else ''}") + results = await async_migrate_dashboard_sheets(client, sheets, only=args.sheet, rename=args.rename, + dry_run=args.dry_run, owner=args.owner) + for name, writer in results.items(): + _print_actions(name, writer, args.dry_run) + return 0 + if args.command == "delete": + writer = DashboardSheetEgeriaWriter(client, dry_run=args.dry_run) + found = await writer.delete_sheet(args.sheet) + if not found: + print(f"No dashboard sheet '{args.sheet}' in Egeria (looked for {dashboard_qn(args.sheet)}).") + else: + _print_actions(args.sheet, writer, args.dry_run) + if args.local and not args.dry_run: + store = args.store or _default_store_path() + sheets = _load_store(store) + if args.sheet in sheets.keys(): + del sheets[args.sheet] + sheets.save_to_json(store) + print(f"Removed '{args.sheet}' from {store}.") + return 0 if found else 1 + return 2 + + +def main(argv: Optional[List[str]] = None) -> int: + parser = argparse.ArgumentParser(prog="python -m pyegeria.view.dashboards", + description="Dashboard sheets held in Egeria: read, migrate, delete.") + sub = parser.add_subparsers(dest="command", required=True) + sub.add_parser("list", help="list the sheets held in Egeria") + show = sub.add_parser("show", help="read one sheet from Egeria") + show.add_argument("name") + mig = sub.add_parser("migrate", help="write sheets from the JSON store to Egeria (a shared write)") + mig.add_argument("--sheet", help="migrate only this sheet") + mig.add_argument("--rename", help="write the --sheet under this name instead (a scratch copy)") + mig.add_argument("--store", help="the JSON store (default PYEGERIA_DASHBOARD_SHEETS_STORE or " + "~/.pyegeria/dashboard_sheets.json)") + mig.add_argument("--dry-run", action="store_true", help="list every write; write nothing") + mig.add_argument("--owner", help="owner of the migrated Dashboards (default: the signed-in user; DB-3)") + dele = sub.add_parser("delete", help="delete a sheet's Egeria chain (never its Reports)") + dele.add_argument("--sheet", required=True) + dele.add_argument("--dry-run", action="store_true") + dele.add_argument("--local", action="store_true", help="also remove the sheet from the JSON store") + dele.add_argument("--store") + args = parser.parse_args(argv) + logger.remove() + logger.add(sys.stderr, level=os.environ.get("PYEGERIA_DASHBOARDS_LOG_LEVEL", "WARNING")) + from pyegeria.core.async_runner import run_sync + return run_sync(_amain(args)) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/micro-tests/dashboard_fake_egeria.py b/tests/micro-tests/dashboard_fake_egeria.py index 2d7ab7d1..a03f2b8a 100644 --- a/tests/micro-tests/dashboard_fake_egeria.py +++ b/tests/micro-tests/dashboard_fake_egeria.py @@ -79,8 +79,11 @@ def write_names(self) -> List[str]: def _header(self, guid: str) -> Dict[str, Any]: e = self.entities[guid] - return {"class": "ElementHeader", "guid": guid, - "type": {"typeName": e["type"], "superTypeNames": SUPERTYPES.get(e["type"], [])}} + header = {"class": "ElementHeader", "guid": guid, + "type": {"typeName": e["type"], "superTypeNames": SUPERTYPES.get(e["type"], [])}} + if e.get("ownership"): + header["ownership"] = {"classificationName": "Ownership", "classificationProperties": e["ownership"]} + return header def element(self, guid: str) -> Dict[str, Any]: e = self.entities[guid] @@ -154,6 +157,11 @@ async def _async_get_elements_by_property_value(self, property_value, property_n page = hits[start_from:start_from + page_size] if page_size else hits[start_from:] return page if page else "No elements found" + async def _async_get_elements(self, metadata_element_type="Referenceable", start_from=0, page_size=10, **kwargs): + hits = [self.element(g) for g, e in self.entities.items() if e["type"] == metadata_element_type] + page = hits[start_from:start_from + page_size] if page_size else hits[start_from:] + return page if page else "No elements found" + async def _async_get_placement_reports(self, dashboard_guid, placement_qualified_names, **kwargs): element = self.element(dashboard_guid) links = [] @@ -256,6 +264,10 @@ async def _async_detach_placement_report(self, dashboard_guid, placement_qualifi and r["props"].get("queryId") == placement_qualified_name)] return before - len(self.relationships) + async def _async_add_ownership_to_element(self, element_guid, body, timeout=None): + self.writes.append(("add_ownership", element_guid, body["properties"]["owner"])) + self.entities[element_guid]["ownership"] = {k: v for k, v in body["properties"].items() if k != "class"} + async def _async_add_scope_to_element(self, scoped_by_guid, element_guid, body=None): self.writes.append(("add_scope", scoped_by_guid, element_guid)) return self._link("ScopedBy", scoped_by_guid, element_guid) diff --git a/tests/micro-tests/data/dashboard_sheets_live_2026_11_09.json b/tests/micro-tests/data/dashboard_sheets_live_2026_11_09.json new file mode 100644 index 00000000..5b30c471 --- /dev/null +++ b/tests/micro-tests/data/dashboard_sheets_live_2026_11_09.json @@ -0,0 +1,398 @@ +{ + "local-dashboards-next-steps": { + "name": "local-dashboards-next-steps", + "heading": "Local Dashboards \u2014 Next Steps", + "description": "The open punch list for the Local Dashboards / Egeria Overview feature, tracked as a real Egeria Work Item List and browsable right here as a Dashboard Sheet.", + "aliases": [], + "family": null, + "placements": [ + { + "ref": "Next Steps Work Item List", + "span": "2", + "emphasis": "kpi", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Next Steps Membership Diagram", + "span": "full", + "emphasis": "panel", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Project Count", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Term Count", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Term Definition Completeness", + "span": "2", + "emphasis": "kpi", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Tasks", + "span": "2", + "emphasis": "kpi", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "My own mermaid", + "span": "full", + "emphasis": "panel", + "content": "This is could be a bunch of content.\n**italics?**", + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Test-MD", + "span": "full", + "emphasis": "panel", + "content": "This is a simple test.", + "perspectives": [], + "detail_spec": null + } + ] + }, + "Assets by Type and Location Demo": { + "name": "Assets by Type and Location Demo", + "heading": "Assets by Type & Location", + "description": "Demo dashboard: how many assets, of which type, are cataloged, and where they're located \u2014 a mix of live charts, KPI numbers, and a location snapshot.", + "aliases": [], + "family": "dashboard", + "placements": [ + { + "ref": "Total Cataloged Assets", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Total Locations Tracked", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Assets by Type (Pie Chart)", + "span": "2", + "emphasis": "panel", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Assets by Type (Bar Chart)", + "span": "2", + "emphasis": "panel", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Assets by Location Snapshot", + "span": "full", + "emphasis": "panel", + "content": "**Assets by Location** \u2014 snapshot as of authoring time, built from real live\n`/api/locations` data (no live \"group assets by Location\" analytic function\nexists yet, so unlike the tiles above this panel doesn't re-query on every\nview \u2014 see this step's own commentary above for what a live version would\nneed). 37 locations are tracked in Egeria; 5 currently have assets\nregistered against them, all `SoftwareServer` infrastructure, 9 assets\ntotal.\n\n```mermaid\npie title Assets by Location (SoftwareServer)\n \"Amsterdam Data Centre\" : 5\n \"Austin Data Center\" : 1\n \"New York Data Center\" : 1\n \"Sales4U\" : 1\n \"Winchester Data Centre\" : 1\n```\n\n| Location | Asset Count | Asset Type |\n|---|---|---|\n| Amsterdam Data Centre | 5 | SoftwareServer |\n| Austin Data Center | 1 | SoftwareServer |\n| New York Data Center | 1 | SoftwareServer |\n| Sales4U | 1 | SoftwareServer |\n| Winchester Data Centre | 1 | SoftwareServer |\n\nThe remaining 32 tracked locations have no assets registered against them\nyet in this demo dataset.", + "perspectives": [], + "detail_spec": null + } + ] + }, + "digital-product-portfolio": { + "name": "digital-product-portfolio", + "heading": "Digital Product Portfolio & Subscriptions", + "description": "A high-level view of our data product ecosystem and adoption metrics.", + "aliases": [], + "family": null, + "placements": [ + { + "ref": "Total Products Count", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Active Subscriptions Count", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Subscription Growth Trend", + "span": "2", + "emphasis": "panel", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Product Subscription Map", + "span": "full", + "emphasis": "panel", + "content": null, + "perspectives": [], + "detail_spec": null + } + ] + }, + "my-team-dashboard": { + "name": "my-team-dashboard", + "heading": "My Team Dashboard", + "description": "Whatever this dashboard is for.", + "aliases": [], + "family": null, + "placements": [ + { + "ref": "My Team Work Items", + "span": "full", + "emphasis": "panel", + "content": null, + "perspectives": [], + "detail_spec": null + } + ] + }, + "Chief Data Officer Dashboard": { + "name": "Chief Data Officer Dashboard", + "heading": "How the Data Governance Program is Going", + "description": "Jules Keeper's view of the data governance program at Coco Pharmaceuticals: whether the program has been built, whether the DATA domain's own metrics are moving, whether the common vocabulary is in use, whether the data hub is delivering, and where things stand against the ninety day plan and the risk register.", + "aliases": [], + "family": "dashboard", + "placements": [ + { + "ref": "Introduction", + "span": "full", + "emphasis": "panel", + "content": "**How is the data governance program going?** Every tile below is a live query against Egeria, so this page changes as the domain teams, the data hub team and the data governance team add to the catalog. The DATA domain exists in service of the domains that carry business and regulatory responsibility, so most tiles measure the shared foundation those domains depend on. Where a governance metric has no live measure yet, the dashboard says so rather than leaving it out.", + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Section 1 - Program Built", + "span": "full", + "emphasis": "panel", + "content": "**1. Has the governance program been built?** The governance definitions defined by all the governance leaders and their teams, the metrics that make them observable, and the information supply chains and blueprints that put the data in a business context.", + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Governance Definitions by Type", + "span": "2", + "emphasis": "panel", + "content": null, + "perspectives": [ + "governance" + ], + "detail_spec": null + }, + { + "ref": "Governance Metrics Defined", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [ + "governance" + ], + "detail_spec": "Governance-Metric-DrE-Basic" + }, + { + "ref": "Supply Chains and Blueprints", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [ + "governance" + ], + "detail_spec": null + }, + { + "ref": "Section 2 - DATA Metrics", + "span": "full", + "emphasis": "panel", + "content": "**2. Are the DATA domain's own metrics moving?** The data governance program defines six metrics. Three have a live measure below: *Percentage of Data Assets with Designated Owner* (Data Asset Ownership, a direct measure), *Catalog Registration Coverage* (Governance Classification Coverage and Catalog Freshness, a partial measure until discovery scanning runs) and *Lineage Coverage for Critical Data Elements* (Solution Design Context, a proxy: the first hop from an asset to the design it implements, not an end-to-end lineage path).", + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Data Asset Ownership", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [ + "governance", + "owner" + ], + "detail_spec": null + }, + { + "ref": "Governance Classification Coverage", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [ + "governance", + "steward" + ], + "detail_spec": null + }, + { + "ref": "Catalog Freshness", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [ + "governance", + "steward" + ], + "detail_spec": null + }, + { + "ref": "Solution Design Context", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [ + "governance", + "engineer" + ], + "detail_spec": null + }, + { + "ref": "Data Quality Not Yet Measured", + "span": "full", + "emphasis": "panel", + "content": "**Not yet measured: data quality.** Three of the DATA domain's metrics \u2014 *Critical Data Element Quality Expectation Coverage*, *Data Quality Rule Pass Rate* (target 98% or above) and *Open Data Quality Issues by Age* (target: nothing older than seven days on critical data) \u2014 need automated quality rule results and a record of the issues they raise. The clinical trials pipeline in `2. clinical-trials` runs quality checks, but their results are not yet recorded in the catalog in a form these tiles can count. Until they are, the honest answer to *how good is our data?* is *we cannot yet say*, and closing this gap is the next priority for Erin Overview and Peter Profile.", + "perspectives": [ + "governance", + "steward" + ], + "detail_spec": null + }, + { + "ref": "Section 3 - Vocabulary", + "span": "full", + "emphasis": "panel", + "content": "**3. Is the common vocabulary being used?** A glossary term is only useful once it is defined, and only does its job once it is attached to the data it describes. The first tile shows how many terms have a definition; the second shows how many terms are actually assigned to something in the catalog.", + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Glossary Definition Completeness", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [ + "governance", + "steward" + ], + "detail_spec": null + }, + { + "ref": "Glossary Terms in Use", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [ + "governance", + "steward" + ], + "detail_spec": null + }, + { + "ref": "Section 4 - Data Hub", + "span": "full", + "emphasis": "panel", + "content": "**4. Is the data hub delivering?** The digital products that deliver critical data between systems, how the catalog has grown over the last ninety days, and the register of strategic information supply chains the company governs and monitors at company level.", + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Digital Products Published", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [], + "detail_spec": "Digital-Products" + }, + { + "ref": "Catalog Growth - Last Ninety Days", + "span": "2", + "emphasis": "panel", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Strategic Information Supply Chain Register", + "span": "full", + "emphasis": "panel", + "content": null, + "perspectives": [], + "detail_spec": "Information-Supply-Chain-DrE-Basic" + }, + { + "ref": "Section 5 - Plan Risks Metrics", + "span": "full", + "emphasis": "panel", + "content": "**5. The plan, the risks and the metrics.** The ninety day plan with the status of each phase and task, the company risk register built by all the governance leaders, and the full governance metric register \u2014 the metrics system the Impact Phase set out to build, of which the tiles above are the first live measures.", + "perspectives": [], + "detail_spec": null + }, + { + "ref": "My Ninety Day Plan Progress", + "span": "full", + "emphasis": "panel", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Company Risk Register", + "span": "full", + "emphasis": "panel", + "content": null, + "perspectives": [ + "governance" + ], + "detail_spec": null + }, + { + "ref": "Governance Metric Register", + "span": "full", + "emphasis": "panel", + "content": null, + "perspectives": [ + "governance" + ], + "detail_spec": null + } + ] + } +} \ No newline at end of file diff --git a/tests/micro-tests/test_dashboards_reader.py b/tests/micro-tests/test_dashboards_reader.py new file mode 100644 index 00000000..be10932a --- /dev/null +++ b/tests/micro-tests/test_dashboards_reader.py @@ -0,0 +1,257 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright Contributors to the ODPi Egeria project. +""" +Dashboard sheets held in Egeria: the reader (BRIEF RS-DASH PR-2). + +Gate: a round trip on fakes. Every live sheet's JSON (the five sheets in the Portal's store, copied read +only on 2026-11-09 to data/dashboard_sheets_live_2026_11_09.json) -> Egeria elements (through the PR-1 +writer, as `migrate` does) -> DashboardSheet gives an EQUAL model: order, span, style, perspectives, text +and refs. Plus the two absence cases, worded; the registry's EGERIA tier; migrate's idempotence. +""" +import importlib.util +import json +import pathlib + +import pytest + +from md_processing.v2.dashboard_sheet import DashboardSheetEgeriaWriter +from pyegeria.view import dashboard_sheet_registry as registry +from pyegeria.view._output_dashboard_sheet_models import DashboardSheet, DashboardSheetDict +from pyegeria.view.dashboards import ( + REPORT_LINK_MISSING, EgeriaDashboardSheet, as_local_model, async_list_dashboard_sheets, + async_load_dashboard_sheet, async_migrate_dashboard_sheets, +) + +_HERE = pathlib.Path(__file__).parent +_spec = importlib.util.spec_from_file_location("dashboard_fake_egeria", _HERE / "dashboard_fake_egeria.py") +fake_egeria = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(fake_egeria) + +LIVE = json.loads((_HERE / "data" / "dashboard_sheets_live_2026_11_09.json").read_text()) + + +def _egeria_with_reports(sheets: dict): + fake = fake_egeria.FakeEgeria() + fake_egeria.seed_perspectives(fake) + for sheet in sheets.values(): + for p in sheet["placements"]: + if p.get("content") is None and not fake.by_qn(f"DeployedReport::{p['ref']}"): + fake.add_entity("Report", f"DeployedReport::{p['ref']}", p["ref"]) + return fake + + +def test_fixture_is_the_five_live_sheets(): + assert sorted(LIVE) == sorted(["Chief Data Officer Dashboard", "local-dashboards-next-steps", + "Assets by Type and Location Demo", "digital-product-portfolio", + "my-team-dashboard"]) + placements = [p for s in LIVE.values() for p in s["placements"]] + assert len(placements) == 40 + assert sum(1 for p in placements if p.get("content") is not None) == 10 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("name", sorted(LIVE)) +async def test_round_trip_every_live_sheet(name): + fake = _egeria_with_reports(LIVE) + original = DashboardSheet(**LIVE[name]) + + await DashboardSheetEgeriaWriter(fake).write_sheet(original) + loaded = await async_load_dashboard_sheet(fake, name) + + assert isinstance(loaded, EgeriaDashboardSheet) and loaded.breaks == [] + assert as_local_model(loaded) == original + assert all(p.kind in ("report", "text") and p.note is None for p in loaded.placements) + # still the base model, so consumers keep their code + assert isinstance(loaded, DashboardSheet) + + +@pytest.mark.asyncio +async def test_list_returns_all_live_sheets_and_migrate_is_idempotent(): + fake = _egeria_with_reports(LIVE) + store = DashboardSheetDict({k: DashboardSheet(**v) for k, v in LIVE.items()}) + + first = await async_migrate_dashboard_sheets(fake, store) + writes = list(fake.writes) + second = await async_migrate_dashboard_sheets(fake, store) + + assert fake.writes == writes + assert all(not [a for a in w.actions if not a.startswith("unchanged")] for w in second.values()) + sheets = await async_list_dashboard_sheets(fake) + assert [s.name for s in sheets] == sorted(LIVE, key=str.lower) + assert {s.name: as_local_model(s) for s in sheets} == {k: DashboardSheet(**v) for k, v in LIVE.items()} + # element counts: per sheet Dashboard + schema type + container, one field per placement + assert len(fake.of_type("Dashboard")) == 5 and len(fake.of_type("DisplayDataField")) == 40 + assert len(fake.rels("DataSetContent")) == 30 + assert sum(len(w.actions) for w in first.values()) > 0 + # DB-3: owned by the migrating user (the fake has none, so owner is given), set once + assert [w for w in writes if w[0] == "add_ownership"] == [] # no owner known -> not classified + + +@pytest.mark.asyncio +async def test_migrate_sets_ownership_once_db3(): + fake = _egeria_with_reports(LIVE) + store = DashboardSheetDict({k: DashboardSheet(**v) for k, v in LIVE.items()}) + await async_migrate_dashboard_sheets(fake, store, only="my-team-dashboard", owner="garygeeke") + await async_migrate_dashboard_sheets(fake, store, only="my-team-dashboard", owner="garygeeke") + owned = [w for w in fake.writes if w[0] == "add_ownership"] + assert owned == [("add_ownership", fake.by_qn("Dashboard::my-team-dashboard"), "garygeeke")] + + +@pytest.mark.asyncio +async def test_dry_run_migrate_writes_nothing(): + fake = _egeria_with_reports(LIVE) + store = DashboardSheetDict({k: DashboardSheet(**v) for k, v in LIVE.items()}) + results = await async_migrate_dashboard_sheets(fake, store, dry_run=True) + assert fake.writes == [] + creates = [a for w in results.values() for a in w.actions if a.startswith("create")] + assert len(creates) == 5 * 3 + 40 + assert not [a for w in results.values() for a in w.actions if a.startswith("classify")] # no owner known + + +@pytest.mark.asyncio +async def test_dry_run_lists_ownership(): + fake = _egeria_with_reports(LIVE) + store = DashboardSheetDict({k: DashboardSheet(**v) for k, v in LIVE.items()}) + results = await async_migrate_dashboard_sheets(fake, store, only="my-team-dashboard", dry_run=True, + owner="erinoverview") + assert "classify Ownership Dashboard::my-team-dashboard (owner erinoverview)" in results["my-team-dashboard"].actions + assert fake.writes == [] + + +@pytest.mark.asyncio +async def test_rename_writes_a_scratch_copy(): + fake = _egeria_with_reports(LIVE) + store = DashboardSheetDict({k: DashboardSheet(**v) for k, v in LIVE.items()}) + await async_migrate_dashboard_sheets(fake, store, only="my-team-dashboard", + rename="scratch-my-team-dashboard") + loaded = await async_load_dashboard_sheet(fake, "scratch-my-team-dashboard") + expected = DashboardSheet(**{**LIVE["my-team-dashboard"], "name": "scratch-my-team-dashboard"}) + assert as_local_model(loaded) == expected + assert await async_load_dashboard_sheet(fake, "my-team-dashboard") is None + + +# ---------------------------------------------------------------------------- absences, in words + +@pytest.mark.asyncio +async def test_report_link_gone_reads_missing(): + fake = _egeria_with_reports(LIVE) + name = "digital-product-portfolio" + await DashboardSheetEgeriaWriter(fake).write_sheet(DashboardSheet(**LIVE[name])) + gone = next(r for r in fake.rels("DataSetContent") if r["props"]["queryId"].endswith("::Total Products Count")) + fake.relationships.remove(gone) + + loaded = await async_load_dashboard_sheet(fake, name) + + first = loaded.placements[0] + assert (first.kind, first.ref, first.note) == ("missing", "Total Products Count", REPORT_LINK_MISSING) + assert [p.kind for p in loaded.placements[1:]] == ["report"] * 3 + + +@pytest.mark.asyncio +async def test_broken_chain_is_listed_with_the_break_named(): + fake = _egeria_with_reports(LIVE) + await DashboardSheetEgeriaWriter(fake).write_sheet(DashboardSheet(**LIVE["my-team-dashboard"])) + fake.relationships = [r for r in fake.relationships if r["type"] != "AttributeForSchema"] + fake.add_entity("Dashboard", "Dashboard::plain", "A plain Create Dashboard") # no chain at all + + sheets = {s.name: s for s in await async_list_dashboard_sheets(fake)} + + assert sheets["my-team-dashboard"].breaks == [ + "no sheet container: the DisplayDataSchemaType has no AttributeForSchema link to a DisplayDataContainer"] + assert sheets["plain"].breaks == [ + "no layout schema: the Dashboard has no Schema link to a DisplayDataSchemaType"] + assert sheets["plain"].heading == "A plain Create Dashboard" and sheets["plain"].placements == [] + + +@pytest.mark.asyncio +async def test_unknown_sheet_is_none(): + assert await async_load_dashboard_sheet(fake_egeria.FakeEgeria(), "nope") is None + + +# ---------------------------------------------------------------------------- registry tier + +@pytest.fixture +def clean_registry(monkeypatch): + monkeypatch.delenv("PYEGERIA_DASHBOARD_SHEETS_JSON", raising=False) + monkeypatch.delenv("PYEGERIA_DASHBOARD_SHEETS_MODULES", raising=False) + registry.refresh_dashboard_sheets() + registry.clear_runtime_dashboard_sheets() + registry.clear_egeria_dashboard_sheets() + yield + registry.clear_runtime_dashboard_sheets() + registry.clear_egeria_dashboard_sheets() + registry.refresh_dashboard_sheets() + + +def test_local_overrides_egeria_with_one_warning(clean_registry, tmp_path, monkeypatch): + egeria_a = EgeriaDashboardSheet(name="a", heading="A from Egeria") + egeria_b = EgeriaDashboardSheet(name="b", heading="B from Egeria") + registry.set_egeria_dashboard_sheets([egeria_a, egeria_b]) + path = tmp_path / "local.json" + path.write_text(json.dumps({"a": {"name": "a", "heading": "A local"}})) + monkeypatch.setenv("PYEGERIA_DASHBOARD_SHEETS_JSON", str(path)) + registry.refresh_dashboard_sheets() + + warnings = [] + handler = registry.logger.add(lambda m: warnings.append(m), level="WARNING") + try: + combined = registry.get_dashboard_sheet_registry() + registry.get_dashboard_sheet_registry() + finally: + registry.logger.remove(handler) + + assert combined["a"].heading == "A local" and combined["b"].heading == "B from Egeria" + assert registry.get_dashboard_sheet_tier("a") == "local" + assert registry.get_dashboard_sheet_tier("b") == "egeria" + assert len([w for w in warnings if "'a'" in w]) == 1 + + +def test_runtime_registration_may_shadow_egeria(clean_registry): + registry.set_egeria_dashboard_sheets([EgeriaDashboardSheet(name="x", heading="X from Egeria")]) + registry.register_dashboard_sheets({"x": DashboardSheet(name="x", heading="X runtime")}) + assert registry.get_dashboard_sheet_registry()["x"].heading == "X runtime" + + +# ---------------------------------------------------------------------------- drift (read-back P3, 2026-11-09) + +async def _cdo_with_link_edits(edit): + fake = _egeria_with_reports(LIVE) + name = "Chief Data Officer Dashboard" + await DashboardSheetEgeriaWriter(fake).write_sheet(DashboardSheet(**LIVE[name])) + edit(fake) + loaded = await async_load_dashboard_sheet(fake, name) + return fake, {p.ref: p for p in loaded.placements} + + +@pytest.mark.asyncio +async def test_extra_scopedby_link_is_a_note(): + def edit(fake): + field = fake.by_qn("DashboardPlacement::Chief Data Officer Dashboard::4::Governance Metrics Defined") + fake.relationships.append({"guid": "x1", "type": "ScopedBy", "end1": fake.by_qn("Perspective::Privacy"), + "end2": field, "props": {}}) + _, placements = await _cdo_with_link_edits(edit) + p = placements["Governance Metrics Defined"] + assert p.perspectives == ["governance"] # the stored labels stay the value + assert p.note == "ScopedBy link(s) to Perspective::Privacy are not in the stored perspectives" + + +@pytest.mark.asyncio +async def test_removed_scopedby_link_is_a_note(): + def edit(fake): + field = fake.by_qn("DashboardPlacement::Chief Data Officer Dashboard::7::Data Asset Ownership") + owner = fake.by_qn("Perspective::Owner") + fake.relationships = [r for r in fake.relationships + if not (r["type"] == "ScopedBy" and r["end1"] == owner and r["end2"] == field)] + _, placements = await _cdo_with_link_edits(edit) + assert placements["Data Asset Ownership"].note == "stored perspective(s) owner have no ScopedBy link in Egeria" + + +@pytest.mark.asyncio +async def test_unexplained_datadescription_link_is_a_note(): + def edit(fake): + spec = fake.add_entity("ReportSpec", "ReportSpec::Something-Else", "Something-Else") + field = fake.by_qn("DashboardPlacement::Chief Data Officer Dashboard::4::Governance Metrics Defined") + fake.relationships.append({"guid": "x2", "type": "DataDescription", "end1": field, "end2": spec, "props": {}}) + _, placements = await _cdo_with_link_edits(edit) + assert placements["Governance Metrics Defined"].note == ( + "DataDescription links to ReportSpec::Something-Else, but the stored drill-down is Governance-Metric-DrE-Basic")