diff --git a/pyegeria/models/__init__.py b/pyegeria/models/__init__.py index a8f02477..8b4e821c 100644 --- a/pyegeria/models/__init__.py +++ b/pyegeria/models/__init__.py @@ -11,6 +11,16 @@ GovernanceControlProperties, MonitoredResourceProperties, NotificationSubscriberProperties, + DataValueSpecificationProperties, + MeasurementSpecificationProperties, + DataSetProperties, + ReportProperties, + DashboardProperties, + LabeledRelationshipProperties, + BasisDataFieldProperties, + AsOfDataFieldProperties, + ReportTypeInstanceProperties, + ReportRunOfProperties, RequestBody, NewRelationshipRequestBody, NewAttachmentRequestBody, @@ -120,6 +130,16 @@ "GovernanceControlProperties", "MonitoredResourceProperties", "NotificationSubscriberProperties", + "DataValueSpecificationProperties", + "MeasurementSpecificationProperties", + "DataSetProperties", + "ReportProperties", + "DashboardProperties", + "LabeledRelationshipProperties", + "BasisDataFieldProperties", + "AsOfDataFieldProperties", + "ReportTypeInstanceProperties", + "ReportRunOfProperties", "RequestBody", "NewRelationshipRequestBody", "NewAttachmentRequestBody", diff --git a/pyegeria/models/models.py b/pyegeria/models/models.py index 5789c6b3..5de31da9 100644 --- a/pyegeria/models/models.py +++ b/pyegeria/models/models.py @@ -362,6 +362,118 @@ class NotificationSubscriberProperties(PyegeriaModel): effective_to: datetime | None = None +# +# Report specifications, measurements and dashboards (Egeria 6.3, odpi/egeria#9432, area 0582). +# Each `class_` is the Java bean name exactly: Egeria resolves the polymorphic "class" against its +# known `*Properties` subtypes, so sending a type name ("Dashboard") is an HTTP 400 +# "Could not resolve type id" (the ScopedBy lesson, pyegeria #537). +# + +class DataValueSpecificationProperties(AuthoredReferenceableProperties): + """Properties of a DataValueSpecification (and the base of DataClass, DataGrain, MeasurementSpecification).""" + class_: Annotated[Literal["DataValueSpecificationProperties"], Field(alias="class")] + match_property_names: list[str] | None = None + namespace_path: str | None = None + match_threshold: int | None = None + specification: str | None = None + specification_details: dict[str, str] | None = None + data_type: str | None = None + units: str | None = None + absolute_uncertainty: int | None = None + relative_uncertainty: int | None = None + + +class MeasurementSpecificationProperties(DataValueSpecificationProperties): + """How a measured value is to be read: completeness, confidence form, uncertainty form and the sentences + to show in place of a value when there isn't one. Created through DataDesigner.create_data_value_specification. + + completenessDeclared: complete | lower_bound | unknown + confidenceForm: measured | estimated | inferred | judged | generated + uncertaintyForm: plus_minus | low_high | band + absenceSentences: map keyed by absence state (nothing_found, not_measured, not_permitted, not_applicable) + + The state set is not a property: it is a ValidValuesAssignment from the specification. The basis and + as-of fields are the BasisDataField / AsOfDataField relationships, not strings. + """ + class_: Annotated[Literal["MeasurementSpecificationProperties"], Field(alias="class")] + completeness_declared: str | None = None + confidence_form: str | None = None + uncertainty_form: str | None = None + absence_sentences: dict[str, str] | None = None + + +class DataSetProperties(ReferenceableProperties): + """Partial model of Egeria's DataSetProperties (a DataAsset). Only the DataSet-level fields are declared; + other Asset fields a caller supplies are kept (extra='allow') rather than silently dropped.""" + model_config = ConfigDict(extra='allow') + class_: Annotated[Literal["DataSetProperties"], Field(alias="class")] + formula: str | None = None + formula_type: str | None = None + + @model_validator(mode='after') + def _drop_injected_metadata(self): + # OpenMetadataRootProperties.preprocess_data adds an empty 'metadata' key; with extra='allow' it + # would otherwise be serialized and sent to Egeria. + if self.__pydantic_extra__ and self.__pydantic_extra__.get('metadata') == {}: + self.__pydantic_extra__.pop('metadata') + return self + + +class ReportProperties(DataSetProperties): + """A Report asset. outputFormat and reportParameters (a JSON string) are new in Egeria 6.3.""" + class_: Annotated[Literal["ReportProperties"], Field(alias="class")] + purpose: str | None = None + start_time: datetime | None = None + completion_time: datetime | None = None + completion_message: str | None = None + created_time: datetime | None = None + last_modified_time: datetime | None = None + last_modifier: str | None = None + output_format: str | None = None + report_parameters: str | None = None + + +class DashboardProperties(DataSetProperties): + """A Dashboard asset (a DataSet, sibling of Report). refreshTimeInterval is a long, in minutes + (Egeria's existing REFRESH_TIME_INTERVAL property: "how frequently the processing should run - in minutes").""" + class_: Annotated[Literal["DashboardProperties"], Field(alias="class")] + aliases: list[str] | None = None + refresh_time_interval: int | None = None + layout_style: str | None = None + + +class LabeledRelationshipProperties(PyegeriaModel): + """Egeria's LabeledRelationshipProperties: the base of the relationship properties below.""" + class_: Annotated[Literal["LabeledRelationshipProperties"], Field(alias="class")] + label: str | None = None + description: str | None = None + effective_from: datetime | None = None + effective_to: datetime | None = None + + +class BasisDataFieldProperties(LabeledRelationshipProperties): + """BasisDataField: MeasurementSpecification (end 1) -> the DataField giving the measurement's basis.""" + class_: Annotated[Literal["BasisDataFieldProperties"], Field(alias="class")] + + +class AsOfDataFieldProperties(LabeledRelationshipProperties): + """AsOfDataField: MeasurementSpecification (end 1) -> the DataField giving the time of the measurement.""" + class_: Annotated[Literal["AsOfDataFieldProperties"], Field(alias="class")] + + +class ReportTypeInstanceProperties(LabeledRelationshipProperties): + """ReportTypeInstance: ReportType (end 1, e.g. a ReportSpec) -> a Report generated from it.""" + class_: Annotated[Literal["ReportTypeInstanceProperties"], Field(alias="class")] + + +class ReportRunOfProperties(LabeledRelationshipProperties): + """ReportRunOf: ResultsSet (end 1) -> the Report it is a run of, with the run's result state.""" + class_: Annotated[Literal["ReportRunOfProperties"], Field(alias="class")] + result_state: str | None = None + result_state_reason: str | None = None + result_location: str | None = None + + class RequestBody(PyegeriaModel): external_source_guid: str | None = None external_source_name: str | None = None diff --git a/pyegeria/omvs/collection_manager.py b/pyegeria/omvs/collection_manager.py index b8349f49..f53ad27d 100644 --- a/pyegeria/omvs/collection_manager.py +++ b/pyegeria/omvs/collection_manager.py @@ -32,7 +32,8 @@ COLLECTION_PROPERTIES_LIST = ["CollectionProperties", "DataDictionaryProperties", "DataSpecProperties", "DigitalProductProperties", "AgreementProperties","RootCollectionProperties", "HomeCollectionProperties", - "SkillSetProperties", "ReferenceListProperties",] + "SkillSetProperties", "ReferenceListProperties", + "ReportTypeProperties", "ReportSpecProperties",] AGREEMENT_PROPERTIES_LIST = ["AgreementProperties", "DigitalSubscriptionProperties",] @@ -111,6 +112,20 @@ class ReportTypeProperties(CollectionProperties): lastModifier: str | None = None +class ReportSpecProperties(ReportTypeProperties): + """A ReportSpec (Egeria 6.3, ReportType subtype): a report specification held in Egeria. + + microflow is the ordered list of stages with their parameters, as a JSON string; outputTypes the output + formats it can produce; targetTypeName the type of element it reports on. + """ + class_: Annotated[Literal["ReportSpecProperties"], Field(alias="class")] + microflow: str | None = None + target_type_name: str | None = None + aliases: list[str] | None = None + output_types: list[str] | None = None + include_preamble: bool | None = None + + class DataDictionaryProperties(CollectionProperties): class_: Annotated[Literal["DataDictionaryProperties"], Field(alias="class")] @@ -2368,6 +2383,98 @@ def create_report_type_collection(self, display_name: Optional[str] = None, desc self._async_create_report_type_collection(display_name, description,category, classification_name, body)) + @dynamic_catch + async def _async_create_report_spec(self, display_name: Optional[str] = None, + description: Optional[str] = None, category: Optional[str] = None, + microflow: Optional[str] = None, target_type_name: Optional[str] = None, + aliases: Optional[list[str]] = None, + output_types: Optional[list[str]] = None, + include_preamble: Optional[bool] = None, + body: Optional[dict | NewElementRequestBody] = None) -> str: + """ Create a ReportSpec (a ReportType collection subtype, Egeria 6.3). Async version. + + If `body` is supplied it is sent as given (its properties class should be "ReportSpecProperties") + and the other arguments are ignored. Otherwise a self-anchored ReportSpec is built from the + arguments, with the qualified name manufactured from `display_name` ("ReportSpec::..."). + + Parameters + ---------- + display_name: str, optional + The display name of the report spec; required when no body is given. + description: str, optional + category: str, optional + The family the spec belongs to. + microflow: str, optional + The ordered list of stages to run with their parameters, as a JSON string. + target_type_name: str, optional + The type of element the spec reports on. + aliases: list[str], optional + output_types: list[str], optional + The output formats the spec can produce (e.g. ["MD", "JSON"]). + include_preamble: bool, optional + body: dict | NewElementRequestBody, optional + + Returns + ------- + str - the guid of the created report spec + + Raises + ------ + PyegeriaException + ValidationError + """ + if body: + validated_body = self.validate_new_element_request(body, ["ReportSpecProperties"]) + elif display_name is not None: + qualified_name = self.__create_qualified_name__("ReportSpec", display_name) + spec_properties = ReportSpecProperties(class_="ReportSpecProperties", + qualified_name=qualified_name, + display_name=display_name, + description=description, + category=category, + microflow=microflow, + target_type_name=target_type_name, + aliases=aliases, + output_types=output_types, + include_preamble=include_preamble) + body = { + "class": "NewElementRequestBody", + "isOwnAnchor": True, + "properties": spec_properties.model_dump(exclude_none=True), + } + validated_body = NewElementRequestBody.model_validate(body) + else: + raise PyegeriaInvalidParameterException(additional_info={"reason": "Invalid input parameters"}) + + url = f"{self.collection_command_root}" + json_body = validated_body.model_dump_json(indent=2, exclude_none=True, by_alias=True) + logger.info(json_body) + resp = await self._async_make_request("POST", url, json_body, is_json=True) + logger.info(f"Create report spec with GUID: {resp.json().get('guid')}") + return resp.json().get("guid", NO_GUID_RETURNED) + + @dynamic_catch + def create_report_spec(self, display_name: Optional[str] = None, + description: Optional[str] = None, category: Optional[str] = None, + microflow: Optional[str] = None, target_type_name: Optional[str] = None, + aliases: Optional[list[str]] = None, + output_types: Optional[list[str]] = None, + include_preamble: Optional[bool] = None, + body: Optional[dict | NewElementRequestBody] = None) -> str: + """ Create a ReportSpec (a ReportType collection subtype, Egeria 6.3). + + See `_async_create_report_spec` for the parameters. Update an existing spec with + `update_collection(guid, body)` using a "ReportSpecProperties" properties class. + + Returns + ------- + str - the guid of the created report spec + """ + return run_sync( + self._async_create_report_spec(display_name, description, category, microflow, + target_type_name, aliases, output_types, + include_preamble, body)) + @dynamic_catch async def _async_create_question_spec_folder(self, display_name: Optional[str] = None, description: Optional[str] = None, diff --git a/pyegeria/omvs/data_designer.py b/pyegeria/omvs/data_designer.py index 065d81b9..127ac7f5 100644 --- a/pyegeria/omvs/data_designer.py +++ b/pyegeria/omvs/data_designer.py @@ -22,6 +22,12 @@ from typing import Any, Optional from pyegeria.core.async_runner import run_sync +# Properties classes accepted by the data-value-specifications create/update endpoints. A +# MeasurementSpecification (Egeria 6.3) is created and updated through these same endpoints with +# "class": "MeasurementSpecificationProperties" in the body's properties. +DATA_VALUE_SPECIFICATION_PROPERTIES_LIST = ["DataValueSpecificationProperties", "DataClassProperties", + "DataGrainProperties", "MeasurementSpecificationProperties"] + class DataDesigner(ServerClient): """ @@ -361,6 +367,9 @@ async def _async_create_data_value_specification(self, body: dict | NewElementRe """ Create a new data value specification. Async version. + Also creates a MeasurementSpecification (Egeria 6.3): set the properties class to + "MeasurementSpecificationProperties" (see pyegeria.models.MeasurementSpecificationProperties). + Parameters ---------- body : dict | NewElementRequestBody @@ -377,7 +386,7 @@ async def _async_create_data_value_specification(self, body: dict | NewElementRe If there are issues in communications, message format, or Egeria errors. """ url = f"{self.ref_data_designer_command_base}/data-value-specifications" - return await self._async_create_element_body_request(url, ["DataValueSpecification"], body) + return await self._async_create_element_body_request(url, DATA_VALUE_SPECIFICATION_PROPERTIES_LIST, body) @dynamic_catch def create_data_value_specification(self, body: dict | NewElementRequestBody) -> str: @@ -4883,7 +4892,7 @@ async def _async_update_data_value_specification(self, guid: str, body: dict | U None """ url = f"{self.ref_data_designer_command_base}/data-value-specifications/{guid}/update" - await self._async_update_element_body_request(url, ["DataValueSpecification"], body) + await self._async_update_element_body_request(url, DATA_VALUE_SPECIFICATION_PROPERTIES_LIST, body) @dynamic_catch def update_data_value_specification(self, guid: str, body: dict | UpdateElementRequestBody) -> None: @@ -5004,6 +5013,334 @@ def detach_schema_type_definition(self, data_structure_guid: str, schema_type_gu run_sync(self._async_detach_schema_type_definition( data_structure_guid, schema_type_guid, body, cascade_delete)) + # + # Report specifications and measurements (Egeria 6.3, odpi/egeria#9432): the BasisDataField, + # AsOfDataField, ReportTypeInstance and ReportRunOf relationships. Same shape as + # _async_link_specialized_data_value_specification above. + # + + @dynamic_catch + async def _async_link_basis_data_field(self, measurement_spec_guid: str, data_field_guid: str, + body: Optional[dict | NewRelationshipRequestBody] = None) -> str | None: + """ + Link the MeasurementSpecification to the DataField that gives the basis for the measurement (for example the denominator of a percentage) (BasisDataField relationship). Async version. + + Parameters + ---------- + measurement_spec_guid : str + The unique identifier of the MeasurementSpecification (end 1). + data_field_guid : str + The unique identifier of the DataField that gives the basis for the measurement (for example the denominator of a percentage) (end 2). + body : dict | NewRelationshipRequestBody, optional + The request body; its properties class is "BasisDataFieldProperties". If omitted, a body with no + relationship properties is sent. + + Returns + ------- + str | None + The GUID of the new relationship, or None if the server did not return one. + + Raises + ------ + PyegeriaException + If there are issues in communications, message format, or Egeria errors. + """ + url = f"{self.ref_data_designer_command_base}/data-value-specifications/{measurement_spec_guid}/basis-data-fields/{data_field_guid}/attach" + return await self._async_new_relationship_request(url, ["BasisDataFieldProperties"], body) + + @dynamic_catch + def link_basis_data_field(self, measurement_spec_guid: str, data_field_guid: str, + body: Optional[dict | NewRelationshipRequestBody] = None) -> str | None: + """ + Link the MeasurementSpecification to the DataField that gives the basis for the measurement (for example the denominator of a percentage) (BasisDataField relationship). + + See `_async_link_basis_data_field` for the parameters. + """ + return run_sync(self._async_link_basis_data_field(measurement_spec_guid, data_field_guid, body)) + + @dynamic_catch + async def _async_detach_basis_data_field(self, measurement_spec_guid: str, data_field_guid: str, + body: Optional[dict | DeleteRelationshipRequestBody] = None, + cascade_delete: bool = False) -> None: + """ + Detach the MeasurementSpecification from the DataField that gives the basis for the measurement (for example the denominator of a percentage) (BasisDataField relationship). Async version. + + Parameters + ---------- + measurement_spec_guid : str + The unique identifier of the MeasurementSpecification (end 1). + data_field_guid : str + The unique identifier of the DataField that gives the basis for the measurement (for example the denominator of a percentage) (end 2). + body : dict | DeleteRelationshipRequestBody, optional + The detach request body. + cascade_delete : bool, default=False + Whether to cascade the delete. + + Returns + ------- + None + + Raises + ------ + PyegeriaException + If there are issues in communications, message format, or Egeria errors. + """ + url = f"{self.ref_data_designer_command_base}/data-value-specifications/{measurement_spec_guid}/basis-data-fields/{data_field_guid}/detach" + await self._async_delete_relationship_request(url, body, cascade_delete) + + @dynamic_catch + def detach_basis_data_field(self, measurement_spec_guid: str, data_field_guid: str, + body: Optional[dict | DeleteRelationshipRequestBody] = None, + cascade_delete: bool = False) -> None: + """ + Detach the MeasurementSpecification from the DataField that gives the basis for the measurement (for example the denominator of a percentage) (BasisDataField relationship). + + See `_async_detach_basis_data_field` for the parameters. + """ + run_sync(self._async_detach_basis_data_field(measurement_spec_guid, data_field_guid, body, cascade_delete)) + + @dynamic_catch + async def _async_link_as_of_data_field(self, measurement_spec_guid: str, data_field_guid: str, + body: Optional[dict | NewRelationshipRequestBody] = None) -> str | None: + """ + Link the MeasurementSpecification to the DataField that gives the time of the measurement (AsOfDataField relationship). Async version. + + Parameters + ---------- + measurement_spec_guid : str + The unique identifier of the MeasurementSpecification (end 1). + data_field_guid : str + The unique identifier of the DataField that gives the time of the measurement (end 2). + body : dict | NewRelationshipRequestBody, optional + The request body; its properties class is "AsOfDataFieldProperties". If omitted, a body with no + relationship properties is sent. + + Returns + ------- + str | None + The GUID of the new relationship, or None if the server did not return one. + + Raises + ------ + PyegeriaException + If there are issues in communications, message format, or Egeria errors. + """ + url = f"{self.ref_data_designer_command_base}/data-value-specifications/{measurement_spec_guid}/as-of-data-fields/{data_field_guid}/attach" + return await self._async_new_relationship_request(url, ["AsOfDataFieldProperties"], body) + + @dynamic_catch + def link_as_of_data_field(self, measurement_spec_guid: str, data_field_guid: str, + body: Optional[dict | NewRelationshipRequestBody] = None) -> str | None: + """ + Link the MeasurementSpecification to the DataField that gives the time of the measurement (AsOfDataField relationship). + + See `_async_link_as_of_data_field` for the parameters. + """ + return run_sync(self._async_link_as_of_data_field(measurement_spec_guid, data_field_guid, body)) + + @dynamic_catch + async def _async_detach_as_of_data_field(self, measurement_spec_guid: str, data_field_guid: str, + body: Optional[dict | DeleteRelationshipRequestBody] = None, + cascade_delete: bool = False) -> None: + """ + Detach the MeasurementSpecification from the DataField that gives the time of the measurement (AsOfDataField relationship). Async version. + + Parameters + ---------- + measurement_spec_guid : str + The unique identifier of the MeasurementSpecification (end 1). + data_field_guid : str + The unique identifier of the DataField that gives the time of the measurement (end 2). + body : dict | DeleteRelationshipRequestBody, optional + The detach request body. + cascade_delete : bool, default=False + Whether to cascade the delete. + + Returns + ------- + None + + Raises + ------ + PyegeriaException + If there are issues in communications, message format, or Egeria errors. + """ + url = f"{self.ref_data_designer_command_base}/data-value-specifications/{measurement_spec_guid}/as-of-data-fields/{data_field_guid}/detach" + await self._async_delete_relationship_request(url, body, cascade_delete) + + @dynamic_catch + def detach_as_of_data_field(self, measurement_spec_guid: str, data_field_guid: str, + body: Optional[dict | DeleteRelationshipRequestBody] = None, + cascade_delete: bool = False) -> None: + """ + Detach the MeasurementSpecification from the DataField that gives the time of the measurement (AsOfDataField relationship). + + See `_async_detach_as_of_data_field` for the parameters. + """ + run_sync(self._async_detach_as_of_data_field(measurement_spec_guid, data_field_guid, body, cascade_delete)) + + @dynamic_catch + async def _async_link_report_type_instance(self, report_type_guid: str, report_guid: str, + body: Optional[dict | NewRelationshipRequestBody] = None) -> str | None: + """ + Link the ReportType (for example a ReportSpec) the report was generated from to the Report (ReportTypeInstance relationship). Async version. + + Parameters + ---------- + report_type_guid : str + The unique identifier of the ReportType (for example a ReportSpec) the report was generated from (end 1). + report_guid : str + The unique identifier of the Report (end 2). + body : dict | NewRelationshipRequestBody, optional + The request body; its properties class is "ReportTypeInstanceProperties". If omitted, a body with no + relationship properties is sent. + + Returns + ------- + str | None + The GUID of the new relationship, or None if the server did not return one. + + Raises + ------ + PyegeriaException + If there are issues in communications, message format, or Egeria errors. + """ + url = f"{self.ref_data_designer_command_base}/report-types/{report_type_guid}/report-type-instances/{report_guid}/attach" + return await self._async_new_relationship_request(url, ["ReportTypeInstanceProperties"], body) + + @dynamic_catch + def link_report_type_instance(self, report_type_guid: str, report_guid: str, + body: Optional[dict | NewRelationshipRequestBody] = None) -> str | None: + """ + Link the ReportType (for example a ReportSpec) the report was generated from to the Report (ReportTypeInstance relationship). + + See `_async_link_report_type_instance` for the parameters. + """ + return run_sync(self._async_link_report_type_instance(report_type_guid, report_guid, body)) + + @dynamic_catch + async def _async_detach_report_type_instance(self, report_type_guid: str, report_guid: str, + body: Optional[dict | DeleteRelationshipRequestBody] = None, + cascade_delete: bool = False) -> None: + """ + Detach the ReportType (for example a ReportSpec) the report was generated from from the Report (ReportTypeInstance relationship). Async version. + + Parameters + ---------- + report_type_guid : str + The unique identifier of the ReportType (for example a ReportSpec) the report was generated from (end 1). + report_guid : str + The unique identifier of the Report (end 2). + body : dict | DeleteRelationshipRequestBody, optional + The detach request body. + cascade_delete : bool, default=False + Whether to cascade the delete. + + Returns + ------- + None + + Raises + ------ + PyegeriaException + If there are issues in communications, message format, or Egeria errors. + """ + url = f"{self.ref_data_designer_command_base}/report-types/{report_type_guid}/report-type-instances/{report_guid}/detach" + await self._async_delete_relationship_request(url, body, cascade_delete) + + @dynamic_catch + def detach_report_type_instance(self, report_type_guid: str, report_guid: str, + body: Optional[dict | DeleteRelationshipRequestBody] = None, + cascade_delete: bool = False) -> None: + """ + Detach the ReportType (for example a ReportSpec) the report was generated from from the Report (ReportTypeInstance relationship). + + See `_async_detach_report_type_instance` for the parameters. + """ + run_sync(self._async_detach_report_type_instance(report_type_guid, report_guid, body, cascade_delete)) + + @dynamic_catch + async def _async_link_report_run_of(self, results_set_guid: str, report_guid: str, + body: Optional[dict | NewRelationshipRequestBody] = None) -> str | None: + """ + Link the ResultsSet holding one run's results to the Report the results set is a run of (ReportRunOf relationship). Async version. + + The relationship properties (class "ReportRunOfProperties") may carry resultState, + resultStateReason and resultLocation for the run. + Parameters + ---------- + results_set_guid : str + The unique identifier of the ResultsSet holding one run's results (end 1). + report_guid : str + The unique identifier of the Report the results set is a run of (end 2). + body : dict | NewRelationshipRequestBody, optional + The request body; its properties class is "ReportRunOfProperties". If omitted, a body with no + relationship properties is sent. + + Returns + ------- + str | None + The GUID of the new relationship, or None if the server did not return one. + + Raises + ------ + PyegeriaException + If there are issues in communications, message format, or Egeria errors. + """ + url = f"{self.ref_data_designer_command_base}/results-sets/{results_set_guid}/report-runs/{report_guid}/attach" + return await self._async_new_relationship_request(url, ["ReportRunOfProperties"], body) + + @dynamic_catch + def link_report_run_of(self, results_set_guid: str, report_guid: str, + body: Optional[dict | NewRelationshipRequestBody] = None) -> str | None: + """ + Link the ResultsSet holding one run's results to the Report the results set is a run of (ReportRunOf relationship). + + See `_async_link_report_run_of` for the parameters. + """ + return run_sync(self._async_link_report_run_of(results_set_guid, report_guid, body)) + + @dynamic_catch + async def _async_detach_report_run_of(self, results_set_guid: str, report_guid: str, + body: Optional[dict | DeleteRelationshipRequestBody] = None, + cascade_delete: bool = False) -> None: + """ + Detach the ResultsSet holding one run's results from the Report the results set is a run of (ReportRunOf relationship). Async version. + + Parameters + ---------- + results_set_guid : str + The unique identifier of the ResultsSet holding one run's results (end 1). + report_guid : str + The unique identifier of the Report the results set is a run of (end 2). + body : dict | DeleteRelationshipRequestBody, optional + The detach request body. + cascade_delete : bool, default=False + Whether to cascade the delete. + + Returns + ------- + None + + Raises + ------ + PyegeriaException + If there are issues in communications, message format, or Egeria errors. + """ + url = f"{self.ref_data_designer_command_base}/results-sets/{results_set_guid}/report-runs/{report_guid}/detach" + await self._async_delete_relationship_request(url, body, cascade_delete) + + @dynamic_catch + def detach_report_run_of(self, results_set_guid: str, report_guid: str, + body: Optional[dict | DeleteRelationshipRequestBody] = None, + cascade_delete: bool = False) -> None: + """ + Detach the ResultsSet holding one run's results from the Report the results set is a run of (ReportRunOf relationship). + + See `_async_detach_report_run_of` for the parameters. + """ + run_sync(self._async_detach_report_run_of(results_set_guid, report_guid, body, cascade_delete)) + if __name__ == "__main__": print("Data Designer") diff --git a/pyegeria/omvs/schema_maker.py b/pyegeria/omvs/schema_maker.py index c08ddc6f..57f4c266 100644 --- a/pyegeria/omvs/schema_maker.py +++ b/pyegeria/omvs/schema_maker.py @@ -55,6 +55,30 @@ class SchemaAttributeProperties(ReferenceableProperties): anchor_guid: Optional[str] = None +class DisplayDataContainerProperties(SchemaAttributeProperties): + """A DisplayDataContainer: one formatter of a report spec, or a sheet (or nested sheet) of a dashboard. + renderer, placementKind, span, presentationStyle and markdownContent are new in Egeria 6.3. Their allowed + values are Egeria valid metadata values keyed by property name. Create with create_schema_attribute.""" + class_: Annotated[Literal["DisplayDataContainerProperties"], Field(alias="class")] + renderer: Optional[str] = None + placement_kind: Optional[str] = None + span: Optional[str] = None + presentation_style: Optional[str] = None + markdown_content: Optional[str] = None + + +class DisplayDataFieldProperties(SchemaAttributeProperties): + """A DisplayDataField: one column of a formatter, or a leaf placement on a dashboard sheet. + inputField marks a form input. placementKind, span, presentationStyle and markdownContent are new in + Egeria 6.3. Create with create_schema_attribute.""" + class_: Annotated[Literal["DisplayDataFieldProperties"], Field(alias="class")] + input_field: Optional[bool] = None + placement_kind: Optional[str] = None + span: Optional[str] = None + presentation_style: Optional[str] = None + markdown_content: Optional[str] = None + + class SchemaMaker(ServerClient): """ Client for the Schema Maker View Service. diff --git a/pyegeria/view/base_report_formats.py b/pyegeria/view/base_report_formats.py index d6aea247..4a987c64 100644 --- a/pyegeria/view/base_report_formats.py +++ b/pyegeria/view/base_report_formats.py @@ -2976,6 +2976,87 @@ def _user_report_specs_dir() -> str: spec_params={}, ) ), + # Report specifications, measurements and dashboards (Egeria 6.3, odpi/egeria#9432). + "Report-Specs": FormatSet( + target_type="ReportSpec", + heading="Report Specifications", + description="Report specifications held in Egeria (ReportSpec, a ReportType collection).", + aliases=["Report Spec", "ReportSpec", "Report Specs", "ReportSpecs"], + annotations={"wikilinks": ["[[Report Spec]]"]}, + family="Views & Reports", + formats=[ + Format(types=["MD", "FORM", "DICT", "LIST", "TABLE"], attributes=COLLECTIONS_COLUMNS + [ + Column(name="Target Type", key="target_type_name"), + Column(name="Output Types", key="output_types"), + Column(name="Include Preamble", key="include_preamble"), + Column(name="Aliases", key="aliases"), + Column(name="Report Type Instances", key="report_type_instances"), + ]), + Format(types=["REPORT", "ALL"], attributes=COLLECTIONS_COLUMNS + [ + Column(name="Target Type", key="target_type_name"), + Column(name="Output Types", key="output_types"), + Column(name="Include Preamble", key="include_preamble"), + Column(name="Aliases", key="aliases"), + Column(name="Microflow", key="microflow"), + Column(name="Report Type Instances", key="report_type_instances"), + ]), + ], + action=ActionParameter( + function="CollectionManager.find_collections", + required_params=["search_string"], + optional_params=OPTIONAL_FILTER_PARAMS, + spec_params={"metadata_element_subtypes": ["ReportSpec"]}, + ), + ), + "Measurement-Specifications": FormatSet( + target_type="MeasurementSpecification", + heading="Measurement Specifications", + description="How measured values are read: units, completeness, confidence and uncertainty form, absence sentences.", + aliases=["Measurement Specification", "MeasurementSpecification", "Measurement Specs", "Measurement Spec"], + annotations={"wikilinks": ["[[Measurement Specification]]"]}, + family="Data Designer", + formats=[ + Format(types=["MD", "FORM", "DICT", "LIST", "TABLE", "REPORT", "ALL"], attributes=COMMON_COLUMNS + [ + Column(name="Units", key="units"), + Column(name="Data Type", key="data_type"), + Column(name="Completeness Declared", key="completeness_declared"), + Column(name="Confidence Form", key="confidence_form"), + Column(name="Uncertainty Form", key="uncertainty_form"), + Column(name="Absolute Uncertainty", key="absolute_uncertainty"), + Column(name="Relative Uncertainty", key="relative_uncertainty"), + Column(name="Absence Sentences", key="absence_sentences"), + Column(name="Basis Data Field", key="basis_data_field"), + Column(name="As Of Data Field", key="as_of_data_field"), + ]), + ], + action=ActionParameter( + function="DataDesigner.find_data_value_specifications", + required_params=["search_string"], + optional_params=OPTIONAL_SEARCH_PARAMS, + spec_params={"metadata_element_subtypes": ["MeasurementSpecification"]}, + ), + ), + "Dashboards": FormatSet( + target_type="Dashboard", + heading="Dashboards", + description="Dashboards held in Egeria (Dashboard, a DataSet asset).", + aliases=["Dashboard"], + annotations={"wikilinks": ["[[Dashboard]]"]}, + family="Views & Reports", + formats=[ + Format(types=["MD", "FORM", "DICT", "LIST", "TABLE", "REPORT", "ALL"], attributes=COMMON_COLUMNS + [ + Column(name="Aliases", key="aliases"), + Column(name="Refresh Time Interval (minutes)", key="refresh_time_interval"), + Column(name="Layout Style", key="layout_style"), + ]), + ], + action=ActionParameter( + function="MetadataExpert.find_metadata_elements_with_string", + required_params=["search_string"], + optional_params=OPTIONAL_SEARCH_PARAMS, + spec_params={"metadata_element_type": "Dashboard"}, + ), + ), 'External-References': FormatSet(target_type='External-Reference', heading='External-Reference Attributes', description='External References', diff --git a/tests/micro-tests/test_report_spec_types.py b/tests/micro-tests/test_report_spec_types.py new file mode 100644 index 00000000..87381e2d --- /dev/null +++ b/tests/micro-tests/test_report_spec_types.py @@ -0,0 +1,327 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright Contributors to the ODPi Egeria project. +""" +Client support for Egeria 6.3's report-spec, measurement and dashboard types (odpi/egeria#9432): +ReportSpec, MeasurementSpecification, Dashboard; the BasisDataField, AsOfDataField, ReportTypeInstance +and ReportRunOf relationships; the new Report / DisplayDataContainer / DisplayDataField attributes. + +No network: _async_make_request is replaced by a recorder. URLs and body classes are checked against +the Data Designer .http file and the Java beans in that PR. +""" +import json + +import pytest + +from pyegeria.models import ( + AsOfDataFieldProperties, + BasisDataFieldProperties, + DashboardProperties, + DataValueSpecificationProperties, + MeasurementSpecificationProperties, + ReportProperties, + ReportRunOfProperties, + ReportTypeInstanceProperties, +) +from pyegeria.omvs.asset_maker import AssetMaker +from pyegeria.omvs.collection_manager import CollectionManager, ReportSpecProperties +from pyegeria.omvs.data_designer import DataDesigner +from pyegeria.omvs.schema_maker import ( + DisplayDataContainerProperties, + DisplayDataFieldProperties, + SchemaMaker, +) + +DD_BASE = "https://localhost:1/servers/view-server/api/open-metadata/data-designer" + + +class _Response: + def json(self): + return {"class": "GUIDResponse", "guid": "new-guid"} + + +def _client(cls, sent: list, monkeypatch): + monkeypatch.setattr(cls, "check_connection", lambda self: "test") + monkeypatch.delenv("EGERIA_LOCAL_QUALIFIER", raising=False) + client = cls("view-server", "https://localhost:1", "user", "pwd") + client.local_qualifier = None + + async def fake_make_request(method, url, body=None, *args, **kwargs): + sent.append({"method": method, "url": url, + "body": json.loads(body) if isinstance(body, str) else body}) + return _Response() + + client._async_make_request = fake_make_request + return client + + +# --------------------------------------------------------------------------------------------------- +# Properties models: the "class" string must be the Java bean name (pyegeria #537) +# --------------------------------------------------------------------------------------------------- + +MODELS = [ + DataValueSpecificationProperties, MeasurementSpecificationProperties, ReportProperties, + DashboardProperties, BasisDataFieldProperties, AsOfDataFieldProperties, + ReportTypeInstanceProperties, ReportRunOfProperties, ReportSpecProperties, + DisplayDataContainerProperties, DisplayDataFieldProperties, +] + + +@pytest.mark.parametrize("model", MODELS, ids=[m.__name__ for m in MODELS]) +def test_class_string_is_java_bean_name(model): + annotation = model.model_fields["class_"].annotation + assert annotation.__args__ == (model.__name__,) + + +def test_measurement_specification_serializes_new_fields(): + props = MeasurementSpecificationProperties( + class_="MeasurementSpecificationProperties", qualified_name="MS::count", display_name="count", + units="elements", completeness_declared="lower_bound", confidence_form="measured", + uncertainty_form="plus_minus", + absence_sentences={"nothing_found": "None found.", "not_measured": "Not measured."}, + ).model_dump(exclude_none=True) + assert props["class"] == "MeasurementSpecificationProperties" + assert props["completenessDeclared"] == "lower_bound" + assert props["confidenceForm"] == "measured" + assert props["uncertaintyForm"] == "plus_minus" + assert props["absenceSentences"]["not_measured"] == "Not measured." + assert props["units"] == "elements" + # owner decision: the state set and basis/as-of fields are relationships, not properties + for gone in ("stateSet", "basisField", "asOfField"): + assert gone not in props + + +def test_dashboard_keeps_undeclared_asset_fields_and_no_injected_metadata(): + props = DashboardProperties( + class_="DashboardProperties", qualified_name="Dashboard::ops", display_name="ops", + aliases=["Ops"], refresh_time_interval=15, layout_style="grid", resourceName="ops-dash", + ).model_dump(exclude_none=True) + assert props["refreshTimeInterval"] == 15 + assert props["layoutStyle"] == "grid" + assert props["aliases"] == ["Ops"] + assert props["resourceName"] == "ops-dash" # extra='allow': not silently dropped + assert "metadata" not in props + + +def test_report_new_fields(): + props = ReportProperties( + class_="ReportProperties", qualified_name="Report::g", display_name="g", + output_format="REPORT-GRAPH", report_parameters='{"search_string": "Clinical"}', + ).model_dump(exclude_none=True) + assert props["outputFormat"] == "REPORT-GRAPH" + assert json.loads(props["reportParameters"]) == {"search_string": "Clinical"} + + +def test_display_data_models_new_fields(): + container = DisplayDataContainerProperties( + class_="DisplayDataContainerProperties", qualified_name="DDC::sheet", display_name="sheet", + renderer="table", placement_kind="inline", span="2", presentation_style="card", + markdown_content="# Summary", + ).model_dump(exclude_none=True) + assert {k: container[k] for k in ("renderer", "placementKind", "span", "presentationStyle", + "markdownContent")} == { + "renderer": "table", "placementKind": "inline", "span": "2", "presentationStyle": "card", + "markdownContent": "# Summary"} + + field = DisplayDataFieldProperties( + class_="DisplayDataFieldProperties", qualified_name="DDF::tile", display_name="tile", + input_field=False, placement_kind="report", span="1", presentation_style="kpi", + ).model_dump(exclude_none=True) + assert field["inputField"] is False + assert field["presentationStyle"] == "kpi" + assert "renderer" not in DisplayDataFieldProperties.model_fields + + +# --------------------------------------------------------------------------------------------------- +# The four relationships: URL, verb and default properties class +# --------------------------------------------------------------------------------------------------- + +LINKS = [ + ("basis_data_field", "data-value-specifications/ms-1/basis-data-fields/df-2", "BasisDataFieldProperties"), + ("as_of_data_field", "data-value-specifications/ms-1/as-of-data-fields/df-2", "AsOfDataFieldProperties"), + ("report_type_instance", "report-types/ms-1/report-type-instances/df-2", "ReportTypeInstanceProperties"), + ("report_run_of", "results-sets/ms-1/report-runs/df-2", "ReportRunOfProperties"), +] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("name, path, props_class", LINKS, ids=[l[0] for l in LINKS]) +async def test_link_default_body(name, path, props_class, monkeypatch): + sent: list = [] + client = _client(DataDesigner, sent, monkeypatch) + + guid = await getattr(client, f"_async_link_{name}")("ms-1", "df-2") + + assert guid == "new-guid" + assert sent[0]["method"] == "POST" + assert sent[0]["url"] == f"{DD_BASE}/{path}/attach" + assert sent[0]["body"]["class"] == "NewRelationshipRequestBody" + assert sent[0]["body"]["properties"]["class"] == props_class + + +@pytest.mark.asyncio +@pytest.mark.parametrize("name, path, props_class", LINKS, ids=[l[0] for l in LINKS]) +async def test_detach(name, path, props_class, monkeypatch): + sent: list = [] + client = _client(DataDesigner, sent, monkeypatch) + + await getattr(client, f"_async_detach_{name}")("ms-1", "df-2") + + assert sent[0]["method"] == "POST" + assert sent[0]["url"] == f"{DD_BASE}/{path}/detach" + + +@pytest.mark.parametrize("name", [l[0] for l in LINKS]) +def test_sync_wrappers_exist(name): + assert callable(getattr(DataDesigner, f"link_{name}")) + assert callable(getattr(DataDesigner, f"detach_{name}")) + + +@pytest.mark.asyncio +async def test_report_run_of_carries_result_state(monkeypatch): + sent: list = [] + client = _client(DataDesigner, sent, monkeypatch) + body = { + "class": "NewRelationshipRequestBody", + "properties": ReportRunOfProperties( + class_="ReportRunOfProperties", label="run 1", result_state="nothing_found", + result_state_reason="no glossaries", result_location="file:///tmp/r.json", + ).model_dump(exclude_none=True), + } + + await client._async_link_report_run_of("rs-1", "report-2", body) + + props = sent[0]["body"]["properties"] + assert sent[0]["url"] == f"{DD_BASE}/results-sets/rs-1/report-runs/report-2/attach" + assert props == {"class": "ReportRunOfProperties", "label": "run 1", "resultState": "nothing_found", + "resultStateReason": "no glossaries", "resultLocation": "file:///tmp/r.json"} + + +# --------------------------------------------------------------------------------------------------- +# Create / update paths +# --------------------------------------------------------------------------------------------------- + +@pytest.mark.asyncio +async def test_measurement_specification_created_through_data_value_specifications(monkeypatch): + sent: list = [] + client = _client(DataDesigner, sent, monkeypatch) + body = { + "class": "NewElementRequestBody", + "properties": { + "class": "MeasurementSpecificationProperties", + "qualifiedName": "MeasurementSpecification::term-count", + "displayName": "term count", + "completenessDeclared": "complete", + "absenceSentences": {"nothing_found": "No terms."}, + }, + } + + guid = await client._async_create_data_value_specification(body) + + assert guid == "new-guid" + assert sent[0]["url"] == f"{DD_BASE}/data-value-specifications" + props = sent[0]["body"]["properties"] + assert props["class"] == "MeasurementSpecificationProperties" + assert props["completenessDeclared"] == "complete" + assert props["absenceSentences"] == {"nothing_found": "No terms."} + + +@pytest.mark.asyncio +async def test_measurement_specification_update(monkeypatch): + sent: list = [] + client = _client(DataDesigner, sent, monkeypatch) + body = {"class": "UpdateElementRequestBody", "mergeUpdate": True, + "properties": {"class": "MeasurementSpecificationProperties", "confidenceForm": "estimated"}} + + await client._async_update_data_value_specification("ms-1", body) + + assert sent[0]["url"] == f"{DD_BASE}/data-value-specifications/ms-1/update" + assert sent[0]["body"]["properties"]["confidenceForm"] == "estimated" + + +@pytest.mark.asyncio +async def test_create_report_spec_from_arguments(monkeypatch): + sent: list = [] + client = _client(CollectionManager, sent, monkeypatch) + microflow = json.dumps([{"function": "find_glossaries", "params": {"search_string": "*"}}]) + + guid = await client._async_create_report_spec( + display_name="Glossaries", description="All glossaries", category="Glossary", + microflow=microflow, target_type_name="Glossary", aliases=["Glossary List"], + output_types=["MD", "JSON"], include_preamble=False) + + assert guid == "new-guid" + assert sent[0]["method"] == "POST" + assert sent[0]["url"].endswith("/api/open-metadata/collection-manager/collections") + body = sent[0]["body"] + assert body["isOwnAnchor"] is True + props = body["properties"] + assert props["class"] == "ReportSpecProperties" + assert props["qualifiedName"] == "ReportSpec::Glossaries" + assert props["microflow"] == microflow + assert props["targetTypeName"] == "Glossary" + assert props["outputTypes"] == ["MD", "JSON"] + assert props["includePreamble"] is False # an explicit False is sent, not dropped + assert props["aliases"] == ["Glossary List"] + + +@pytest.mark.asyncio +async def test_create_report_spec_from_body(monkeypatch): + sent: list = [] + client = _client(CollectionManager, sent, monkeypatch) + body = {"class": "NewElementRequestBody", "isOwnAnchor": True, + "properties": {"class": "ReportSpecProperties", "qualifiedName": "ReportSpec::x", + "displayName": "x", "microflow": "[]"}} + + await client._async_create_report_spec(body=body) + + assert sent[0]["body"]["properties"] == body["properties"] + + +@pytest.mark.asyncio +async def test_dashboard_created_through_asset_maker(monkeypatch): + sent: list = [] + client = _client(AssetMaker, sent, monkeypatch) + props = DashboardProperties(class_="DashboardProperties", qualified_name="Dashboard::ops", + display_name="ops", refresh_time_interval=60, layout_style="grid") + body = {"class": "NewElementRequestBody", "isOwnAnchor": True, + "properties": props.model_dump(exclude_none=True)} + + await client._async_create_asset(["DashboardProperties"], body) + + assert sent[0]["url"].endswith("/api/open-metadata/asset-maker/assets") + assert sent[0]["body"]["properties"] == {"class": "DashboardProperties", "qualifiedName": "Dashboard::ops", + "displayName": "ops", "refreshTimeInterval": 60, + "layoutStyle": "grid"} + + +@pytest.mark.asyncio +async def test_display_data_container_through_schema_maker(monkeypatch): + sent: list = [] + client = _client(SchemaMaker, sent, monkeypatch) + props = DisplayDataContainerProperties(class_="DisplayDataContainerProperties", qualified_name="DDC::t", + display_name="TABLE", renderer="table", placement_kind="inline") + body = {"class": "NewElementRequestBody", "properties": props.model_dump(exclude_none=True)} + + await client._async_create_schema_attribute(body) + + assert sent[0]["url"].endswith("/api/open-metadata/schema-maker/schema-attributes") + assert sent[0]["body"]["properties"]["renderer"] == "table" + assert sent[0]["body"]["properties"]["placementKind"] == "inline" + + +# --------------------------------------------------------------------------------------------------- +# Report specs so run_report / Dr.Egeria Display can show the new types +# --------------------------------------------------------------------------------------------------- + +@pytest.mark.parametrize("label, function, spec_params", [ + ("Report-Specs", "CollectionManager.find_collections", {"metadata_element_subtypes": ["ReportSpec"]}), + ("Measurement-Specifications", "DataDesigner.find_data_value_specifications", + {"metadata_element_subtypes": ["MeasurementSpecification"]}), + ("Dashboards", "MetadataExpert.find_metadata_elements_with_string", {"metadata_element_type": "Dashboard"}), +]) +def test_report_specs_registered(label, function, spec_params): + from pyegeria.view.base_report_formats import base_report_specs + + fs = base_report_specs[label] + assert fs.action.function == function + assert fs.action.spec_params == spec_params