diff --git a/README.md b/README.md index 89d71d2..0c5f8df 100644 --- a/README.md +++ b/README.md @@ -138,8 +138,8 @@ Easiest way to learn about it, is starting with an existing transformation using E.g. you could start with the following to example transformations (which might not exactly reflect the latest code version of this project): -* https://try.jsonata.org/Gk5r-kLek: Mapping DATEX3.7LiteJSON to DATEX2MostlyFlatGeoJSON (Current JSONata expression is in datex2_xml2json/transform/jsonata_transformer.py) -* https://try.jsonata.org/QEnqmItyF: Mapping DATEX2MostlyFlatGeoJSON to (mostly) WAZE CIFS (Current JSONata expression is in datex2_xml2json/transform/cifs_transformer.py) +* https://try.jsonata.org/Gk5r-kLek: Mapping DATEX3.7LiteJSON to DATEX2MostlyFlatGeoJSON (Current JSONata expression is in `src/datex2_xml2json/transform/jsonata_transformer.py`) +* https://try.jsonata.org/QEnqmItyF: Mapping DATEX2MostlyFlatGeoJSON to (mostly) WAZE CIFS (Current JSONata expression is in `src/datex2_xml2json/transform/cifs_transformer.py`) ### Running tests diff --git a/pyproject.toml b/pyproject.toml index dead5d1..9e94a4e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,7 +1,10 @@ [build-system] -requires = ["uv_build >= 0.12.19"] +requires = ["uv_build >= 0.12.19, <1"] build-backend = "uv_build" +[tool.uv.build-backend] +source-exclude = [".DS_Store"] + [project] name = "datex2-xml2json" # The version is bumped from the git tag in CI via `uv version` on release; see .github/workflows/test_build_and_publish.yml @@ -24,23 +27,21 @@ license = "EUPL-1.2" license-files = ["LICENSE.md"] dependencies = [ - "jsonschema>=4.26.0", - "check-jsonschema>=0.38.2", - "jsonata-python>=0.7.0", - "geoparquet-io>=1.6.0", - "pyarrow>=26.0.0", - "rs-xml2json>=0.2.0" + "jsonschema>=4.26,<5", + "check-jsonschema>=0.38,<1", + "jsonata-python>=0.7.0,<1", + "geoparquet-io>=1.7,<2", + "pyarrow>=26,<27", + "rs-xml2json~=0.2.0" ] # Development and test dependencies (PEP 735 dependency group, installed by `uv sync`). [dependency-groups] dev = [ - "pytest~=9.1.1", + "pytest>=9.1.1,<10", "ruff~=0.17.2", "mypy~=2.3.1", - "pre-commit>=4.3.0", - "types-shapely~=2.1.0.20260728", - "pyarrow-stubs~=20.0.0.20260819", + "pre-commit>=4.3.0,<5" ] [project.urls] @@ -130,6 +131,7 @@ testpaths = ["tests"] [tool.mypy] python_version = "3.12" +strict = true [[tool.mypy.overrides]] module = [ @@ -144,6 +146,6 @@ module = [ "geoparquet_io", "rs_xml2json", "pyarrow", - "shapely.geometry", + "pyarrow.parquet", ] ignore_missing_imports = true diff --git a/src/datex2_xml2json/json_validator.py b/src/datex2_xml2json/json_validator.py index 727fd6d..d2a1594 100644 --- a/src/datex2_xml2json/json_validator.py +++ b/src/datex2_xml2json/json_validator.py @@ -1,3 +1,5 @@ +from pathlib import Path + from check_jsonschema.checker import SchemaChecker from check_jsonschema.file_wrapper import BinaryFileInput from check_jsonschema.formats import FormatOptions @@ -8,7 +10,7 @@ class JsonValidator: - def __init__(self, schema_path): + def __init__(self, schema_path: str) -> None: self.schema_loader = SchemaLoader( schema_path, disable_cache=False, @@ -20,7 +22,7 @@ def build_reporter(self, output_format: str, verbosity: int) -> Reporter: cls = REPORTER_BY_NAME[output_format] return cls(verbosity=verbosity) - def validate(self, filename): + def validate(self, filename: str | Path) -> int: checker = SchemaChecker( schema_loader=self.schema_loader, instance_loader=InstanceLoader([BinaryFileInput(filename)]), @@ -33,4 +35,5 @@ def validate(self, filename): regex_impl=RegexImplementation(RegexVariantName.default), ) - return checker.run() + result: int = checker.run() + return result diff --git a/src/datex2_xml2json/py.typed b/src/datex2_xml2json/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/src/datex2_xml2json/transform/__init__.py b/src/datex2_xml2json/transform/__init__.py index 93ec6ba..7bdd34f 100644 --- a/src/datex2_xml2json/transform/__init__.py +++ b/src/datex2_xml2json/transform/__init__.py @@ -1,4 +1,5 @@ from .base import ( + AbstractTransformer as AbstractTransformer, TransformerPipeline as TransformerPipeline, RulesTransformer as RulesTransformer, ) @@ -9,5 +10,5 @@ GeoJSONGeometryTransformer as GeoJSONGeometryTransformer, ) from .geoparquet_transformer import GeoparquetRenderer as GeoparquetRenderer -from .cifs_transformer import CifsTransformer -from .source_setter import SourceSetter +from .cifs_transformer import CifsTransformer as CifsTransformer +from .source_setter import SourceSetter as SourceSetter diff --git a/src/datex2_xml2json/transform/base.py b/src/datex2_xml2json/transform/base.py index 743ab45..8781b79 100644 --- a/src/datex2_xml2json/transform/base.py +++ b/src/datex2_xml2json/transform/base.py @@ -1,22 +1,24 @@ -from datex2_xml2json.util import replace, xpath_dict +from typing import Self + +from datex2_xml2json.util import JsonDict, replace, xpath_dict from .transformation_rules import TransformationRules class AbstractTransformer: - def transform(self, a_dict: dict) -> dict: + def transform(self, a_dict: JsonDict) -> JsonDict: return a_dict class TransformerPipeline(AbstractTransformer): - def __init__(self, transformers: list[AbstractTransformer]): + def __init__(self, transformers: list[AbstractTransformer]) -> None: self.transformers = list(transformers) - def add_transformer(self, transformer: AbstractTransformer): + def add_transformer(self, transformer: AbstractTransformer) -> Self: self.transformers.append(transformer) return self - def transform(self, a_dict: dict) -> dict: + def transform(self, a_dict: JsonDict) -> JsonDict: result = a_dict for t in self.transformers: result = t.transform(result) @@ -28,7 +30,7 @@ class RulesTransformer(AbstractTransformer): def __init__(self, rules: TransformationRules): self.rules = rules - def transform(self, a_dict: dict) -> dict: + def transform(self, a_dict: JsonDict) -> JsonDict: # Transforms the result of xml2json transformation into DATEXIIv3 json. # This includes: # * renamings of certain properties according to v2 to v3 name changes @@ -36,7 +38,7 @@ def transform(self, a_dict: dict) -> dict: # * casts values of certain properties to intended types # * ... - return replace( + result: JsonDict = replace( a_dict, None, self.rules.renamings, @@ -46,29 +48,31 @@ def transform(self, a_dict: dict) -> dict: self.rules.keys_to_pull_up, ) + return result + class ProcessingTransformer(AbstractTransformer): - def __init__(self, xpath: str): + def __init__(self, xpath: str) -> None: self.xpath = xpath - def transform(self, a_dict: dict) -> dict: + def transform(self, a_dict: JsonDict) -> JsonDict: for elem in xpath_dict(a_dict, self.xpath): self.process(elem) return a_dict - def process(self, a_dict: dict): + def process(self, a_dict: JsonDict) -> None: pass class SituationRecordTransformer(ProcessingTransformer): - def __init__(self, xpath: str): + def __init__(self, xpath: str) -> None: super().__init__(xpath) - def process_situation_record(self, situation_record: dict) -> None: + def process_situation_record(self, situation_record: JsonDict) -> None: pass - def process(self, situation_record_wrapper: dict) -> None: + def process(self, situation_record_wrapper: JsonDict) -> None: if isinstance(situation_record_wrapper, dict) and len(situation_record_wrapper) == 1: situation_record = situation_record_wrapper.get(next(iter(situation_record_wrapper.keys()))) else: diff --git a/src/datex2_xml2json/transform/cifs_transformer.py b/src/datex2_xml2json/transform/cifs_transformer.py index c4df529..7e61d45 100644 --- a/src/datex2_xml2json/transform/cifs_transformer.py +++ b/src/datex2_xml2json/transform/cifs_transformer.py @@ -2,6 +2,8 @@ import logging import re +from datex2_xml2json.util import JsonDict + from .jsonata_transformer import JsonataTransformer logger = logging.getLogger(__name__) @@ -58,7 +60,7 @@ "DisturbanceActivity": "CHIT_CHAT", "TransitInformation": "CHIT_CHAT" }; - $lookup($typeBySubtypeLookup , properties.situationRecordSubtype)?:$lookup($typeLookup , properties.type)?:"TODO"), + $lookup($typeBySubtypeLookup , properties.situationRecordSubtype)?:$lookup($typeLookup , properties.type)?:"HAZARD"), "subtype": ( $subtypeByTypeLookup := { /* Accident (no subtypes, as DATEXII does not provide accident severity) */ @@ -134,6 +136,12 @@ } """ +# In case multiple incidents describe the same situation, usually because of an caused/effect relation, +# we pick the incident, whose type/subtype are ranked highest (most informative/important) +DEFAULT_INCIDENT_PRIORITY = 1 +TYPE_PRIORITIES = {'ROAD_CLOSED': 10, 'ACCIDENT': 9, 'JAM': 8, 'HAZARD': 7, 'POLICE': 2, 'CHIT_CHAT': 1} +SUBTYPE_PRIORITIES = {'ROAD_CLOSED': 10, 'ACCIDENT': 9, 'JAM': 8, 'HAZARD': 7, 'POLICE': 2, 'CHIT_CHAT': 1} + class CifsTransformer(JsonataTransformer): # This pattern is used to exract the common ID prefix of all situation records which @@ -143,11 +151,11 @@ class CifsTransformer(JsonataTransformer): # 2. Any string/char prefix followed by dot + number situation_record_group_prefix_regexp = r'^(\d+-\d\d\d\dV\d+)$|^(\d+-\d+-\d+-\d+-gegen).*|^(\d+-\d+-\d+-\d+).*|^(.*)\.\d+$' - def __init__(self, **kwargs): + def __init__(self) -> None: super().__init__(cifs_expression) - def _group_by_common_situation_record_id_substring(self, incidents, pattern): - grouped_incidents = {} + def _group_by_common_situation_record_id_substring(self, incidents: list[JsonDict], pattern: str) -> dict[str, list[JsonDict]]: + grouped_incidents: dict[str, list[JsonDict]] = {} p = re.compile(pattern) for incident in incidents: @@ -163,19 +171,13 @@ def _group_by_common_situation_record_id_substring(self, incidents, pattern): return grouped_incidents - def _get_type_sub_type_prio(self, incident): - if incident.get('type') == 'ROAD_CLOSED': - return 10 - if incident.get('subtype') == 'HAZARD_ON_ROAD_LANE_CLOSED': - return 4 - if incident.get('subtype') == 'HAZARD_ON_ROAD_CONSTRUCTION': - return 3 - if incident.get('subtype') == 'HAZARD_ON_ROAD' or incident.get('type') in ['CHIT_CHAT']: - return 1 - else: - return 2 + def _get_type_sub_type_prio(self, incident: JsonDict) -> int: + return max( + TYPE_PRIORITIES.get(str(incident.get('type')), DEFAULT_INCIDENT_PRIORITY), + SUBTYPE_PRIORITIES.get(str(incident.get('subtype')), DEFAULT_INCIDENT_PRIORITY), + ) - def _merge_incident_group(self, incident_group): + def _merge_incident_group(self, incident_group: list[JsonDict]) -> JsonDict: # Assumptions: besides type and subtype, all properties are assumed to be equals # (TODO: we might check this explicitly) # @@ -184,30 +186,33 @@ def _merge_incident_group(self, incident_group): # * highest priority subtype/type wins # TODO: subtype for road_closed to be set according to other incidents # TODO: should jam be communicated in addition? + if not incident_group: + raise ValueError('incident_group must not be empty') + highest_prio = None highest_prio_type = None highest_prio_subtype = None - highest_prio_incident = None + highest_prio_incident: JsonDict = incident_group[0] for incident in incident_group: current_prio = self._get_type_sub_type_prio(incident) if highest_prio is None or current_prio > highest_prio: logger.debug( f'For {incident["id"]}, replace {highest_prio} {highest_prio_type} {highest_prio_subtype}' - f' by {incident["type"]} {incident.get("subtype")}' + f' by {incident.get("type")} {incident.get("subtype")}' ) highest_prio = current_prio - highest_prio_type = incident['type'] + highest_prio_type = incident.get('type') highest_prio_subtype = incident.get('subtype') highest_prio_incident = incident else: logger.debug( f'For {incident["id"]}, do not replace {highest_prio} {highest_prio_type} {highest_prio_subtype}' - f' by {incident["type"]} {incident.get("subtype")}' + f' by {incident.get("type")} {incident.get("subtype")}' ) return highest_prio_incident - def _transform_polyline_geom(self, linestring_coordinates) -> str: + def _transform_polyline_geom(self, linestring_coordinates: list[list[float]]) -> str: """ Converts GeoJSON linestring coordinates array into CIFS polyline string. The list of lon/lat coords (like [[10.0, 49.0], [11.0, 49.0]]) is converted into a @@ -215,7 +220,7 @@ def _transform_polyline_geom(self, linestring_coordinates) -> str: """ return ' '.join([f'{coords[1]} {coords[0]}' for coords in linestring_coordinates]) - def _transform_incident_geometry(self, incident: dict) -> list[dict]: + def _transform_incident_geometry(self, incident: JsonDict) -> list[JsonDict]: """ Converts GeoJSON geometry of incident into a CIFS polyline. As the GeoJSON geometry might be a MultiLineString, we return an array @@ -248,7 +253,7 @@ def _transform_incident_geometry(self, incident: dict) -> list[dict]: return [incident] - def _merge_grouped_incidents_and_handle_geometry(self, grouped_incidents): + def _merge_grouped_incidents_and_handle_geometry(self, grouped_incidents: dict[str, list[JsonDict]]) -> list[JsonDict]: incidents = [] for key in grouped_incidents: try: @@ -260,7 +265,7 @@ def _merge_grouped_incidents_and_handle_geometry(self, grouped_incidents): return incidents - def post_transform(self, a_dict: dict) -> dict: + def post_transform(self, a_dict: JsonDict) -> JsonDict: """ Retains the most expressive incident of a group of incidents describing the same situation. diff --git a/src/datex2_xml2json/transform/geojson_geometry_transformer.py b/src/datex2_xml2json/transform/geojson_geometry_transformer.py index f64cca6..ed84087 100644 --- a/src/datex2_xml2json/transform/geojson_geometry_transformer.py +++ b/src/datex2_xml2json/transform/geojson_geometry_transformer.py @@ -1,5 +1,7 @@ import logging +from datex2_xml2json.util import JsonDict + from .base import SituationRecordTransformer logger = logging.getLogger(__name__) @@ -14,7 +16,7 @@ def __init__( super().__init__(situation_record_json_pointer) self.geom_container_element_json_point = geom_container_element_json_point - def _extract_coordinates_from_gmlLineString(self, gmlLineString: dict) -> list: + def _extract_coordinates_from_gmlLineString(self, gmlLineString: JsonDict) -> list[list[float]]: # Coordinate Order Confusion # There is often some confusion regarding the correct ordering of coordinate values. # While EPSG:4326 usually uses lat,lon ordering, and CRS84 (and GeoJSON) use lon/lat, @@ -38,7 +40,7 @@ def _extract_coordinates_from_gmlLineString(self, gmlLineString: dict) -> list: else: return [[lon, lat] for lon, lat in zipped_coords] - def _extract_line_geom(self, linearExtended: dict) -> None | dict: + def _extract_line_geom(self, linearExtended: JsonDict) -> None | JsonDict: gmlLineString = linearExtended.get('gmlLineString') if gmlLineString is None: logger.warning('No linearExtended/gmlLineString') @@ -50,7 +52,7 @@ def _extract_line_geom(self, linearExtended: dict) -> None | dict: } return geometry - def _extract_point_geom(self, pointCoordinates: dict | None) -> dict | None: + def _extract_point_geom(self, pointCoordinates: JsonDict | None) -> JsonDict | None: if pointCoordinates is None: logger.warning('No pointCoordinates') return None @@ -64,7 +66,7 @@ def _extract_point_geom(self, pointCoordinates: dict | None) -> dict | None: } return geometry - def _extract_multi_line_string(self, locationReference: dict) -> dict: + def _extract_multi_line_string(self, locationReference: JsonDict) -> JsonDict: locations = locationReference.get('locationContainedInGroup', {}) lineStrings = [] @@ -82,7 +84,7 @@ def _extract_multi_line_string(self, locationReference: dict) -> dict: return {'type': 'MultiLineString', 'coordinates': lineStrings} - def _extract_extendedLinear_geom(self, locationReference: dict) -> dict: + def _extract_extendedLinear_geom(self, locationReference: JsonDict) -> JsonDict: """ Some publications use a custom extension extendedLinear to provide linear geometries using a verbose xml encoding. @@ -119,7 +121,7 @@ def _extract_extendedLinear_geom(self, locationReference: dict) -> dict: return {'type': 'LineString', 'coordinates': coordinates} - def process_situation_record(self, situation_record: dict) -> None: + def process_situation_record(self, situation_record: JsonDict) -> None: locationReference = situation_record.get('locationReference') if locationReference is None: return @@ -147,7 +149,7 @@ def process_situation_record(self, situation_record: dict) -> None: class GeoJSONGeometryTransformer_DATEXII_3_7(GeoJSONGeometryTransformer): - def __init__(self): + def __init__(self) -> None: super().__init__( 'payload/sitSituationPublication/situation/situationRecord', 'linearExtended', @@ -155,5 +157,5 @@ def __init__(self): class GeoJSONGeometryTransformer_Simplified(GeoJSONGeometryTransformer): - def __init__(self): + def __init__(self) -> None: super().__init__('payload/situation/situationRecord', None) diff --git a/src/datex2_xml2json/transform/geoparquet_transformer.py b/src/datex2_xml2json/transform/geoparquet_transformer.py index 9a5b8f6..e53d5b6 100644 --- a/src/datex2_xml2json/transform/geoparquet_transformer.py +++ b/src/datex2_xml2json/transform/geoparquet_transformer.py @@ -1,11 +1,15 @@ import json import logging from datetime import datetime, timezone +from pathlib import Path from tempfile import NamedTemporaryFile +from typing import Any import geoparquet_io as gpio import pyarrow as pa +from datex2_xml2json.util import JsonDict + logger = logging.getLogger(__name__) fields: list[tuple[str, pa.DataType]] = [ @@ -88,10 +92,10 @@ class GeoparquetRenderer: happend in situ, no deep copy of the GeoJSON dict is created. """ - def __init__(self, target_schema=MOSTLY_FLAT_SITUATION_RECORD_TARGET_SCHEMA): + def __init__(self, target_schema: pa.Schema = MOSTLY_FLAT_SITUATION_RECORD_TARGET_SCHEMA) -> None: self.target_schema = target_schema - def _get_timestamp_fieldnames(self): + def _get_timestamp_fieldnames(self) -> list[str]: """ Return a list of all fieldnames of self.target_schema, whose type is pyarrow.TimestampType. """ @@ -101,7 +105,7 @@ def _get_timestamp_fieldnames(self): fieldnames.append(self.target_schema.names[index]) return fieldnames - def _set_timestamps_to_UTC(self, a_geojson_dict: dict): + def _set_timestamps_to_UTC(self, a_geojson_dict: JsonDict) -> None: """ Adds/subtracts optional timezone offset for all timestamp properties to assure they are in UTC. @@ -115,14 +119,21 @@ def _set_timestamps_to_UTC(self, a_geojson_dict: dict): for feature in a_geojson_dict['features']: props = feature['properties'] for ts_property in ts_fieldnames: - if ts_property in props: - dt = datetime.fromisoformat(props[ts_property]) - # Assume datetime was given in UTC if no timezone was specified - if not dt.tzinfo: - dt.replace(tzinfo=timezone.utc) - props[ts_property] = dt.astimezone(timezone.utc).isoformat() + value = props.get(ts_property) + if value is None: + continue + try: + dt = datetime.fromisoformat(value) + except (TypeError, ValueError): + logger.warning('Replacing invalid timestamp %r of property %s by null', value, ts_property) + props[ts_property] = None + continue + # Assume datetime was given in UTC if no timezone was specified + if not dt.tzinfo: + dt = dt.replace(tzinfo=timezone.utc) + props[ts_property] = dt.astimezone(timezone.utc).isoformat() - def _cast_fields_and_add_missing(self, table) -> None: + def _cast_fields_and_add_missing(self, table: Any) -> None: """ Replaces table's pyarrow table by a new one which has expected columns in expected order and type. @@ -139,11 +150,13 @@ def _cast_fields_and_add_missing(self, table) -> None: arrays.append(pa.nulls(len(patable), type=field.type)) except Exception: logger.exception(f'Exception handling field {field}') + # Create null column of the correct type + arrays.append(pa.nulls(len(patable), type=field.type)) patable = pa.Table.from_arrays(arrays, schema=self.target_schema) table._table = patable - def _as_table(self, a_geojson_dict: dict): + def _as_table(self, a_geojson_dict: JsonDict) -> Any: """ Writes a_geojson_dict to a tempory file which is then read via geoparquet-io as pyarrow table. @@ -153,8 +166,11 @@ def _as_table(self, a_geojson_dict: dict): f.close() return gpio.convert(f.name) - def render(self, filename, a_geojson_dict: dict) -> None: - self._set_timestamps_to_UTC(a_geojson_dict) - table = self._as_table(a_geojson_dict) + def render(self, filename: str | Path, a_geojson_dict: JsonDict) -> None: + # Only properties are modified, so a copy of them suffices to leave a_geojson_dict untouched + features = [{**feature, 'properties': dict(feature['properties'])} for feature in a_geojson_dict['features']] + geojson_copy = {**a_geojson_dict, 'features': features} + self._set_timestamps_to_UTC(geojson_copy) + table = self._as_table(geojson_copy) self._cast_fields_and_add_missing(table) table.write(filename) diff --git a/src/datex2_xml2json/transform/jsonata_transformer.py b/src/datex2_xml2json/transform/jsonata_transformer.py index 42cd3f6..3b305b6 100644 --- a/src/datex2_xml2json/transform/jsonata_transformer.py +++ b/src/datex2_xml2json/transform/jsonata_transformer.py @@ -1,5 +1,7 @@ import jsonata +from datex2_xml2json.util import JsonDict + from .base import AbstractTransformer # ruff: noqa: E501 (JSONata expressions are long...) @@ -88,13 +90,13 @@ class JsonataTransformer(AbstractTransformer): - def __init__(self, jsonata_expression=mostly_flat_geojson_expression): + def __init__(self, jsonata_expression: str = mostly_flat_geojson_expression) -> None: self.jsonata_expr = jsonata.Jsonata(jsonata_expression) - def transform(self, a_dict: dict) -> dict: + def transform(self, a_dict: JsonDict) -> JsonDict: result = self.jsonata_expr.evaluate(a_dict) return self.post_transform(result) - def post_transform(self, a_dict: dict) -> dict: + def post_transform(self, a_dict: JsonDict) -> JsonDict: return a_dict diff --git a/src/datex2_xml2json/transform/roads_regio_transformer.py b/src/datex2_xml2json/transform/roads_regio_transformer.py index fc1ce43..6165b0a 100644 --- a/src/datex2_xml2json/transform/roads_regio_transformer.py +++ b/src/datex2_xml2json/transform/roads_regio_transformer.py @@ -1,15 +1,17 @@ import logging +from datex2_xml2json.util import JsonDict + from .base import SituationRecordTransformer logger = logging.getLogger(__name__) class RoadsRegioTransformer(SituationRecordTransformer): - def __init__(self, path: str = 'payload/sitSituationPublication/situation/situationRecord'): + def __init__(self, path: str = 'payload/sitSituationPublication/situation/situationRecord') -> None: super().__init__(path) - def _filter_empty_comments(self, situation_record: dict): + def _filter_empty_comments(self, situation_record: JsonDict) -> None: # Remove comments without value if 'generalPublicComment' in situation_record: comments = [ @@ -19,14 +21,14 @@ def _filter_empty_comments(self, situation_record: dict): ] situation_record['generalPublicComment'] = comments - def _handle_originalNumberOfLanes(self, situation_record: dict): + def _handle_originalNumberOfLanes(self, situation_record: JsonDict) -> None: # Removes originalNumberOfLanes from impact. if 'impact' in situation_record: # TODO originalNumberOfLanes probably should they be added elsewhere situation_record['impact'].pop('originalNumberOfLanes', None) - def _handle_bemas_locations(self, situation_record: dict): + def _handle_bemas_locations(self, situation_record: JsonDict) -> None: # Removes originalNumberOfLanes from impact. # BEMaS @@ -62,7 +64,7 @@ def _handle_bemas_locations(self, situation_record: dict): linearElement['locLinearElementByLineString'] = locLinearElementByLineString linearWithinLinearElements[0]['linearElement'] = linearElement - def _fix_missing_linearElement(self, situation_record: dict): + def _fix_missing_linearElement(self, situation_record: JsonDict) -> None: # Removes originalNumberOfLanes from impact. # BEMaS @@ -81,7 +83,7 @@ def _fix_missing_linearElement(self, situation_record: dict): if 'linearElement' not in linearWithinLinearElements[0]: linearWithinLinearElements[0]['linearElement'] = {} - def process_situation_record(self, situation_record: dict) -> None: + def process_situation_record(self, situation_record: JsonDict) -> None: # self._handle_bemas_locations(situation_record) self._fix_missing_linearElement(situation_record) self._handle_originalNumberOfLanes(situation_record) diff --git a/src/datex2_xml2json/transform/source_setter.py b/src/datex2_xml2json/transform/source_setter.py index 37674b7..cc777be 100644 --- a/src/datex2_xml2json/transform/source_setter.py +++ b/src/datex2_xml2json/transform/source_setter.py @@ -1,30 +1,31 @@ from datex2_xml2json.transform.base import SituationRecordTransformer +from datex2_xml2json.util import JsonDict class SourceSetter(SituationRecordTransformer): """ This Transformer sets situationRecord/source/sourceIdentification and the - custom extension payload/payloadPublicationExtension/publicationIdentifier, + custom extension payloadPublication/payloadPublicationExtension/publicationIdentifier, if they are specified in the constructor call. """ sourceIdentification: str | None = None publicationIdentifier: str | None = None - def __init__(self, publicationIdentifier: str | None, sourceIdentification: str | None): - super().__init__('d2LogicalModel/payload/situation/situationRecord') + def __init__(self, publicationIdentifier: str | None, sourceIdentification: str | None) -> None: + super().__init__('d2LogicalModel/payloadPublication/situation/situationRecord') self.publicationIdentifier = publicationIdentifier self.sourceIdentification = sourceIdentification - def process_situation_record(self, situation_record: dict) -> None: - situation_record['source'] = {'sourceIdentification': self.sourceIdentification} + def process_situation_record(self, situation_record: JsonDict) -> None: + situation_record.setdefault('source', {})['sourceIdentification'] = self.sourceIdentification - def transform(self, publication: dict) -> dict: + def transform(self, publication: JsonDict) -> JsonDict: if self.sourceIdentification is not None: publication = super().transform(publication) if self.publicationIdentifier is not None: - publication['d2LogicalModel']['payload'].setdefault('payloadPublicationExtension', {})['publicationIdentifier'] = ( + publication['d2LogicalModel']['payloadPublication'].setdefault('payloadPublicationExtension', {})['publicationIdentifier'] = ( self.publicationIdentifier ) diff --git a/src/datex2_xml2json/transform/transformation_rules.py b/src/datex2_xml2json/transform/transformation_rules.py index ec1f202..6daa21b 100644 --- a/src/datex2_xml2json/transform/transformation_rules.py +++ b/src/datex2_xml2json/transform/transformation_rules.py @@ -1,6 +1,8 @@ import logging from dataclasses import dataclass -from typing import Callable +from typing import Any + +from datex2_xml2json.util import JsonDict, ValueTransform logger = logging.getLogger(__name__) @@ -8,13 +10,13 @@ @dataclass class TransformationRules: renamings: dict[str, str] - value_transforms: dict[str, Callable] + value_transforms: ValueTransform keys_to_drop: dict[str, list[str]] type_mappings: dict[str, str] keys_to_pull_up: dict[str, None | list[str]] -def push_down_vms_configuration(vms: dict) -> dict: +def push_down_vms_configuration(vms: JsonDict) -> JsonDict: vmsConfiguration = {} if 'numberOfPictogramDisplayAreas' in vms: vmsConfiguration['numberOfDisplayAreas'] = vms.pop('numberOfPictogramDisplayAreas') @@ -67,7 +69,7 @@ def push_down_vms_configuration(vms: dict) -> dict: } -def transform_supplementaryPositionalDescription(v: dict): +def transform_supplementaryPositionalDescription(v: JsonDict) -> JsonDict: # locationDescriptior needs to be split in multiple properties if 'locationDescriptor' in v: locationDescriptors = v.pop('locationDescriptor') @@ -109,7 +111,7 @@ def transform_supplementaryPositionalDescription(v: dict): return v -def wrap_lroffset(lr_dict: dict): +def wrap_lroffset(lr_dict: JsonDict) -> JsonDict: new_dict = {} for k in lr_dict: if k == 'openlrPositiveOffset': @@ -119,7 +121,7 @@ def wrap_lroffset(lr_dict: dict): return new_dict -def transform_alertc(v: dict, shouldWrapWithValue: bool): +def transform_alertc(v: JsonDict, shouldWrapWithValue: bool) -> JsonDict: """ In v2, alertCDirection did not distinguish between encoding and affected direction. We assume, as apparently NDW mandated explictly, that for encoding matches affected direction and, @@ -234,10 +236,10 @@ class TransformationRuleFactory: 'PlaceStatus': 'prkPlaceStatus', } - def __init__(self): + def __init__(self) -> None: pass - def xmlv2_to_json(self): + def xmlv2_to_json(self) -> TransformationRules: renamings = { # xml2json artifact '$': 'value', @@ -277,11 +279,11 @@ def xmlv2_to_json(self): '@extensionVersion': 'extensionVersionG', } - def add_def_lang_if_missing(v): + def add_def_lang_if_missing(v: Any) -> JsonDict: return v if isinstance(v, dict) else {'lang': DEFAULT_LANGUAGE, 'value': v} # TODO move value wrapping down to datex transform, here we should use them unwrapped - value_transforms = { + value_transforms: ValueTransform = { # type transformations 'offsetDistance': lambda v: int(v) if not isinstance(v, dict) else v, # value transformations @@ -336,10 +338,10 @@ def add_def_lang_if_missing(v): 'carParkIdentity': [], } - geojson_drops = {'situationExtension': []} + geojson_drops: dict[str, list[str]] = {'situationExtension': []} # keys_to_pull_up convert { ..., '': { } } in { ..., } - keys_to_pull_up = { + keys_to_pull_up: dict[str, list[str] | None] = { 'linearExtension': None, 'linearExtended': None, 'linearLineStringExtension': None, @@ -360,7 +362,7 @@ def add_def_lang_if_missing(v): keys_to_pull_up, ) - def xmlv3_to_json3_7(self): + def xmlv3_to_json3_7(self) -> TransformationRules: datex_json_renamings = { # Assumed DATEXII JSON Schema Artifacts '@modelBaseVersion': 'modelBaseVersionG', @@ -373,17 +375,17 @@ def xmlv3_to_json3_7(self): '@extensionVersion': 'extensionVersionG', } - def wrap_with_value(v): + def wrap_with_value(v: Any) -> JsonDict: return {'value': v} - value_transforms = { + value_transforms: ValueTransform = { # Value wrapping for parking ... 'status': wrap_with_value, 'operationStatus': wrap_with_value, 'informationStatus': wrap_with_value, 'confidentiality': wrap_with_value, } - keys_to_drop = { + keys_to_drop: dict[str, list[str]] = { '@xsi:schemaLocation': [], '@xmlns': [], '@xmlns:d2': [], @@ -394,7 +396,8 @@ def wrap_with_value(v): '@xmlns:xsi': [], '@xsi:type': [], } - keys_to_pull_up = {'modelBaseVersion': None} + keys_to_pull_up: dict[str, list[str] | None] = {'modelBaseVersion': None} + return TransformationRules( datex_json_renamings, value_transforms, @@ -403,7 +406,7 @@ def wrap_with_value(v): keys_to_pull_up, ) - def xmlv2_to_json3_7(self): + def xmlv2_to_json3_7(self) -> TransformationRules: datex_json_renamings = { # Assumed DATEXII JSON Schema Artifacts '@modelBaseVersion': 'modelBaseVersionG', @@ -432,7 +435,7 @@ def xmlv2_to_json3_7(self): } # A couple of text properties are wrapped in an object, presumably for extendability - def wrap_with_value(v): + def wrap_with_value(v: Any) -> JsonDict: return {'value': v} value_transforms = { @@ -510,7 +513,7 @@ def wrap_with_value(v): 'lane': lambda v: {'laneNumber': int(v[4:])} if v.startswith('lane') else {'laneUsage': {'value': v}}, } - keys_to_drop = { + keys_to_drop: dict[str, list[str]] = { '@xsi:schemaLocation': [], '@xmlns:xsd': [], '@xsi:type': [], diff --git a/src/datex2_xml2json/transformer.py b/src/datex2_xml2json/transformer.py index 56bc3e0..d7f152e 100644 --- a/src/datex2_xml2json/transformer.py +++ b/src/datex2_xml2json/transformer.py @@ -16,7 +16,7 @@ TransformationRuleFactory, TransformerPipeline, ) -from .util import load_as_json_using_schema, schema_path +from .util import JsonDict, load_as_json_using_schema, schema_path logger = logging.getLogger(__name__) @@ -55,7 +55,7 @@ class OutputFormat(StrEnum): } -def build_transformer(input_format: InputFormat, output_format: OutputFormat): +def build_transformer(input_format: InputFormat, output_format: OutputFormat) -> TransformerPipeline: if input_format == InputFormat.DATEX2_2_2_XML: if output_format == OutputFormat.DATEX2_3_7_JSON: return TransformerPipeline( @@ -78,12 +78,40 @@ def build_transformer(input_format: InputFormat, output_format: OutputFormat): return build_transformer(input_format, OutputFormat.GEOJSON).add_transformer(CifsTransformer()) elif output_format == OutputFormat.RAW: return TransformerPipeline([]) + else: + raise ValueError(f'Unsupported output format {output_format}') else: - return TransformerPipeline([RulesTransformer(TransformationRuleFactory().xmlv3_to_json3_7())]) + if output_format == OutputFormat.DATEX2_3_7_JSON: + return TransformerPipeline([RulesTransformer(TransformationRuleFactory().xmlv3_to_json3_7())]) + elif output_format == OutputFormat.RAW: + return TransformerPipeline([]) + else: + raise ValueError(f'Unsupported output format {output_format} for input format {input_format}') + + +class UnsupportedOptionsError(ValueError): + """Raised if the requested combination of options is not supported.""" + + +def check_options( + input_format: InputFormat, + output_format: OutputFormat | None, + validate: bool, + sourceIdentification: str | None, + publicationIdentifier: str | None, +) -> None: + if validate and output_format is not None and output_format not in OUTPUT_SCHEMAS: + raise UnsupportedOptionsError(f'Validation is not supported for format {output_format}') + if input_format != InputFormat.DATEX2_2_2_XML: + if output_format not in (OutputFormat.DATEX2_3_7_JSON, OutputFormat.RAW): + raise UnsupportedOptionsError(f'Input format {input_format} only supports output formats datex2_3_7_json and raw') + if sourceIdentification or publicationIdentifier: + raise UnsupportedOptionsError(f'Setting source or publication identifiers is not supported for input format {input_format}') -def write(stem: str, json_result: dict, output_format: OutputFormat, outDir: str, validate: bool = False): + +def write(stem: str, json_result: JsonDict, output_format: OutputFormat, outDir: str, validate: bool = False) -> None: suffix = FILE_SUFFIXES_PER_FORMAT[output_format] outfile_name = Path(outDir) / (stem + suffix) outfile_name.parent.mkdir(parents=True, exist_ok=True) @@ -92,13 +120,14 @@ def write(stem: str, json_result: dict, output_format: OutputFormat, outDir: str with open(outfile_name, 'w') as f: json.dump(json_result, f, indent=2) if validate: - exit(JsonValidator(schema_path(OUTPUT_SCHEMAS[output_format])).validate(outfile_name)) + with schema_path(OUTPUT_SCHEMAS[output_format]) as schema: + result = JsonValidator(schema).validate(outfile_name) + exit(result) else: GeoparquetRenderer().render(outfile_name, json_result) -def generate_all(stem: str, json_input: dict, outDir: str, validate: bool): - write(stem, json_input, OutputFormat.RAW, outDir) +def generate_all(stem: str, json_input: JsonDict, outDir: str, validate: bool) -> None: jsonLiteTransformer = build_transformer(InputFormat.DATEX2_2_2_XML, OutputFormat.DATEX2_3_7_JSON_LITE) jsonLite_output = jsonLiteTransformer.transform(json_input) write(stem, jsonLite_output, OutputFormat.DATEX2_3_7_JSON_LITE, outDir) @@ -113,13 +142,22 @@ def transform( filename: str, outDir: str, input_format: InputFormat, - output_format: OutputFormat, + output_format: OutputFormat | None, validate: bool, - sourceIdentification: str, - publicationIdentifier: str, -): + sourceIdentification: str | None, + publicationIdentifier: str | None, +) -> None: + check_options(input_format, output_format, validate, sourceIdentification, publicationIdentifier) + stem = Path(filename).stem - json_input = load_as_json_using_schema(filename, schema_path(DEFAULT_SCHEMAS[input_format])) + with schema_path(DEFAULT_SCHEMAS[input_format]) as schema: + json_input = load_as_json_using_schema(filename, schema) + + # RAW reflects the input, so it is written before source information is set + if output_format is None or output_format == OutputFormat.RAW: + write(stem, json_input, OutputFormat.RAW, outDir) + if output_format == OutputFormat.RAW: + return if sourceIdentification or publicationIdentifier: SourceSetter(publicationIdentifier, sourceIdentification).transform(json_input) @@ -182,16 +220,16 @@ def transform( args = parser.parse_args() - if args.validate and args.output_format is not None and args.output_format not in OUTPUT_SCHEMAS: - logger.error('Validation is not supported for format %s', args.output_format) + try: + transform( + args.filename, + args.outputDir, + args.input_format, + args.output_format, + args.validate, + args.sourceIdentification, + args.publicationIdentifier, + ) + except UnsupportedOptionsError as e: + logger.error('%s', e) exit(1) - - transform( - args.filename, - args.outputDir, - args.input_format, - args.output_format, - args.validate, - args.sourceIdentification, - args.publicationIdentifier, - ) diff --git a/src/datex2_xml2json/util.py b/src/datex2_xml2json/util.py index d6671fb..b574d39 100644 --- a/src/datex2_xml2json/util.py +++ b/src/datex2_xml2json/util.py @@ -1,27 +1,42 @@ import json +from collections.abc import Callable, Iterator +from contextlib import contextmanager from importlib.resources import as_file, files +from pathlib import Path from typing import Any from rs_xml2json import convert +JsonDict = dict[str, Any] +ValueTransform = dict[str, Callable[[Any], Any]] -def schema_path(schema): - with as_file(files('datex2_xml2json').joinpath(schema)) as fspath: - return str(fspath.resolve()) +@contextmanager +def schema_path(schema: str) -> Iterator[str]: + """ + Yields a filesystem path to schema (given relative to the package, e.g. schema/cifs_schema.json). + + The path is only valid inside the with block. If the package is imported from a zip file, the whole + schema directory is extracted temporarily, as schemas reference sibling files via relative paths. + """ + with as_file(files('datex2_xml2json').joinpath('schema')) as schema_dir: + yield str(schema_dir / Path(schema).relative_to('schema')) -def load_as_json_using_schema(filename: str, schemafile: str) -> dict: + +def load_as_json_using_schema(filename: str, schemafile: str) -> JsonDict: if filename.endswith('.xml'): json_string = convert(filename, schemafile) - json_input = json.loads(json_string) + json_input: JsonDict = json.loads(json_string) + return json_input elif filename.endswith('.json'): with open(filename) as f: - json_input = json.load(f) - - return json_input + json_from_file: JsonDict = json.load(f) + return json_from_file + else: + raise ValueError(f'Unsupported input file: {filename}') -def find(a_dict: dict[Any, Any], simplified_xpath: str, default_value: Any = None) -> Any: +def find(a_dict: JsonDict, simplified_xpath: str, default_value: Any = None) -> Any: paths = simplified_xpath.split('/') elem: Any = a_dict for path in paths: @@ -32,7 +47,7 @@ def find(a_dict: dict[Any, Any], simplified_xpath: str, default_value: Any = Non return elem -def xpath_dict(data, path: str) -> Any: +def xpath_dict(data: JsonDict, path: str) -> Any: """ Simple XPath-like lookup for nested dict/list structures. @@ -42,7 +57,7 @@ def xpath_dict(data, path: str) -> Any: parts = [p for p in path.strip('/').split('/') if p] - def _search(current: Any, remaining: list) -> Any: + def _search(current: Any, remaining: list[str]) -> Any: if not remaining: if isinstance(current, list): return current @@ -75,11 +90,11 @@ def replace( value: Any, current_key: str | None, renamings: dict[str, str], - value_transforms: dict, + value_transforms: ValueTransform, keys_to_drop: dict[str, list[str]], type_mappings: dict[str, str], keys_to_pull_up: dict[str, None | list[str]], -): +) -> Any: # renamings: dict of old keys which shall be replaced by new keys # keys_to_drop: dict of keys which should be removed from dicts, if their parent key equals keys_to_drop[key]'s value (or value is None) # type_mappings: dict of type values which, if present as 'type': type_mapping_key will result in an object {type_mapping_value: {} } diff --git a/tests/integration/test_xml_to_json_3_7.py b/tests/integration/test_xml_to_json_3_7.py index ae3bf0e..80d9963 100644 --- a/tests/integration/test_xml_to_json_3_7.py +++ b/tests/integration/test_xml_to_json_3_7.py @@ -3,6 +3,7 @@ from datex2_xml2json.json_validator import JsonValidator from datex2_xml2json.transform import ( + AbstractTransformer, GeoJSONGeometryTransformer, JsonataTransformer, RoadsRegioTransformer, @@ -10,15 +11,16 @@ TransformationRuleFactory, TransformerPipeline, ) -from datex2_xml2json.util import load_as_json_using_schema, schema_path +from datex2_xml2json.util import JsonDict, load_as_json_using_schema, schema_path DATEX2_XSD_2_2_0_SCHEMA = 'schema/DATEXIISchema_2_2_3.xsd' DATEX2_3_7_JSON_SCHEMA = 'schema/DATEXII_3.7_Profile/DATEXII_3_D2Payload.json' FIXTURES_DIR = 'tests/integration/data/' -def load_and_transform(FIXTURE_NAME: str, overwrite: bool, transformer, suffix: str): - json_input = load_as_json_using_schema(FIXTURES_DIR + FIXTURE_NAME + '.xml', schema_path(DATEX2_XSD_2_2_0_SCHEMA)) +def load_and_transform(FIXTURE_NAME: str, overwrite: bool, transformer: AbstractTransformer, suffix: str) -> JsonDict: + with schema_path(DATEX2_XSD_2_2_0_SCHEMA) as schema: + json_input = load_as_json_using_schema(FIXTURES_DIR + FIXTURE_NAME + '.xml', schema) if overwrite: with open(FIXTURES_DIR + FIXTURE_NAME + '.json', 'w') as f: json.dump(json_input, f, indent=2) @@ -39,18 +41,19 @@ def load_and_transform(FIXTURE_NAME: str, overwrite: bool, transformer, suffix: return json_output -def transform_validate(FIXTURE_NAME: str, overwrite: bool, transformer, suffix: str): +def transform_validate(FIXTURE_NAME: str, overwrite: bool, transformer: AbstractTransformer, suffix: str) -> None: json_output = load_and_transform(FIXTURE_NAME, overwrite, transformer, suffix) with tempfile.NamedTemporaryFile(mode='w', delete_on_close=False) as fp: json.dump(json_output, fp) fp.close() - res = JsonValidator(schema_path(DATEX2_3_7_JSON_SCHEMA)).validate(fp.name) + with schema_path(DATEX2_3_7_JSON_SCHEMA) as schema: + res = JsonValidator(schema).validate(fp.name) if res != 0: raise Exception('Failed validation') -def transform_to_3_7_validate(inputfile: str, overwrite: bool): +def transform_to_3_7_validate(inputfile: str, overwrite: bool) -> None: transform_validate( inputfile, overwrite, @@ -59,7 +62,7 @@ def transform_to_3_7_validate(inputfile: str, overwrite: bool): ) -def transform_to_flat_geojson(inputfile: str, overwrite: bool): +def transform_to_flat_geojson(inputfile: str, overwrite: bool) -> None: transformer = TransformerPipeline( [ RulesTransformer(TransformationRuleFactory().xmlv2_to_json()), @@ -72,66 +75,66 @@ def transform_to_flat_geojson(inputfile: str, overwrite: bool): # ---------- -def test_sitpub_comments_to_json3_7(): +def test_sitpub_comments_to_json3_7() -> None: transform_to_3_7_validate('sitpub_comments', False) -def test_sitpub_linearExtension_to_json3_7(): +def test_sitpub_linearExtension_to_json3_7() -> None: transform_to_3_7_validate('sitpub_linearExtension', False) -def test_sitpub_linearExtension_to_flat_geojson(): +def test_sitpub_linearExtension_to_flat_geojson() -> None: transform_to_flat_geojson('sitpub_linearExtension', False) -def test_sitpub_linearExtended_to_json3_7(): +def test_sitpub_linearExtended_to_json3_7() -> None: transform_to_3_7_validate('sitpub_linearExtended', False) -def test_sitpub_linearExtended_to_flat_geojson(): +def test_sitpub_linearExtended_to_flat_geojson() -> None: transform_to_flat_geojson('sitpub_linearExtended', False) -def test_sitpub_pointCoordinate_to_3_7(): +def test_sitpub_pointCoordinate_to_3_7() -> None: transform_to_3_7_validate('sitpub_pointCoordinate', False) -def test_sitpub_pointCoordinate_to_flat_geojson(): +def test_sitpub_pointCoordinate_to_flat_geojson() -> None: transform_to_flat_geojson('sitpub_pointCoordinate', False) -def test_sitpub_sitpub_multi_linearExtended_to_flat_geojson(): +def test_sitpub_sitpub_multi_linearExtended_to_flat_geojson() -> None: transform_to_flat_geojson('sitpub_multi_linearExtended', False) -def test_sitpub_linearByCoordinates_to_flat_geojson(): +def test_sitpub_linearByCoordinates_to_flat_geojson() -> None: transform_to_flat_geojson('sitpub_linearByCoordinates', False) -def test_sitpub_only_coordinatesForDisplay_to_flat_geojson(): +def test_sitpub_only_coordinatesForDisplay_to_flat_geojson() -> None: transform_to_flat_geojson('sitpub_only_coordinatesForDisplay', False) -def test_sitpub_multiple_lanerestrictions_to_flat_geojson(): +def test_sitpub_multiple_lanerestrictions_to_flat_geojson() -> None: transform_to_flat_geojson('sitpub_multiple_lanerestrictions', False) -def test_sitpub_empty_linearElement_to_json3_7(): +def test_sitpub_empty_linearElement_to_json3_7() -> None: transform_to_3_7_validate('sitpub_empty_linearElement', False) -def test_sitpub_point_along_linearElement(): +def test_sitpub_point_along_linearElement() -> None: transform_to_3_7_validate('sitpub_point_along_linearElement', False) -def test_sitpub_source_to_json3_7(): +def test_sitpub_source_to_json3_7() -> None: """ Tests, if a DATEXII 2.2 with source and custom publicationId will converted to valid 3.7 JSON. """ transform_to_3_7_validate('sitpub_source', False) -def test_sitpub_source_to_flat_geojson(): +def test_sitpub_source_to_flat_geojson() -> None: """ Tests, if a DATEXII 2.2 with source and custom publicationId will converted to valid 3.7 JSON. """ diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/unit/test_cifs_transformer.py b/tests/unit/test_cifs_transformer.py index 05f7d57..dafae3e 100644 --- a/tests/unit/test_cifs_transformer.py +++ b/tests/unit/test_cifs_transformer.py @@ -1,7 +1,11 @@ +from typing import Any + +import pytest + from datex2_xml2json.transform import CifsTransformer -def test_post_transform(): +def test_post_transform() -> None: transformer = CifsTransformer() incidents = { 'incidents': [ @@ -24,3 +28,45 @@ def test_post_transform(): } actual = transformer.post_transform(incidents) assert expected == actual + + +testdata = [ + (['HAZARD', None], ['ROAD_CLOSED', None], ['ROAD_CLOSED', None]), + (['HAZARD', 'HAZARD_ON_ROAD_CONSTRUCTION'], ['HAZARD', None], ['HAZARD', 'HAZARD_ON_ROAD_CONSTRUCTION']), + (['ACCIDENT', 'ACCIDENT_MINOR'], ['CHIT_CHAT', None], ['ACCIDENT', 'ACCIDENT_MINOR']), + (['JAM', 'JAM_HEAVY_TRAFFIC'], ['CHIT_CHAT', None], ['JAM', 'JAM_HEAVY_TRAFFIC']), +] + + +@pytest.mark.parametrize( + 'type_subtype_first_situation_record,type_subtype_second_situation_record,expected_type_subtype_after_merge', testdata +) +def test_most_specific_type_and_subtype_is_retained_on_merge( + type_subtype_first_situation_record: list[Any], + type_subtype_second_situation_record: list[Any], + expected_type_subtype_after_merge: list[Any], +) -> None: + transformer = CifsTransformer() + + first_sr = { + 'id': '1487640-1487641-1487644-3508083', + 'type': type_subtype_first_situation_record[0], + 'subtype': type_subtype_first_situation_record[1], + 'geometry': {'type': 'LineString', 'coordinates': [[8.110721, 47.606249], [8.110684, 47.60628]]}, + } + second_sr = { + 'id': '1487640-1487641-1487644-3508083-sperrung', + 'type': type_subtype_second_situation_record[0], + 'subtype': type_subtype_second_situation_record[1], + 'geometry': {'type': 'LineString', 'coordinates': [[8.110721, 47.606249], [8.110684, 47.60628]]}, + } + incidents = { + 'incidents': [ + first_sr, + second_sr, + ] + } + actual = transformer.post_transform(incidents) + retained_sr = actual['incidents'][0] + + assert expected_type_subtype_after_merge == [retained_sr['type'], retained_sr.get('subtype')] diff --git a/tests/unit/test_geoparquet_transformer.py b/tests/unit/test_geoparquet_transformer.py new file mode 100644 index 0000000..02e6b03 --- /dev/null +++ b/tests/unit/test_geoparquet_transformer.py @@ -0,0 +1,39 @@ +from datetime import datetime +from pathlib import Path + +import pyarrow.parquet as pq + +from datex2_xml2json.transform import GeoparquetRenderer + + +def test_timezones(tmp_path: Path) -> None: + geojson = { + 'type': 'FeatureCollection', + 'features': [ + { + 'type': 'Feature', + 'properties': { + 'situationRecordCreationTime': '2026-01-01T00:00:00+01:00', + }, + 'geometry': {'type': 'Point', 'coordinates': [9.0, 49.0]}, + }, + { + 'type': 'Feature', + 'properties': { + 'situationRecordCreationTime': '2026-01-01T00:00:00', + }, + 'geometry': {'type': 'Point', 'coordinates': [9.0, 49.0]}, + }, + ], + } + + renderer = GeoparquetRenderer() + filename = tmp_path / 'test_timezones.parquet' + renderer.render(filename, geojson) + + with pq.ParquetFile(str(filename)) as reader: + table = reader.read() + + features = table.to_pylist() + assert features[0]['situationRecordCreationTime'].timestamp() == datetime.fromisoformat('2026-01-01T00:00:00+01:00').timestamp() + assert features[1]['situationRecordCreationTime'].timestamp() == datetime.fromisoformat('2026-01-01T00:00:00+00:00').timestamp() diff --git a/tests/unit/test_replacements.py b/tests/unit/test_replacements.py index 67769c4..e343c15 100644 --- a/tests/unit/test_replacements.py +++ b/tests/unit/test_replacements.py @@ -1,15 +1,15 @@ -from datex2_xml2json.util import replace +from datex2_xml2json.util import JsonDict, ValueTransform, replace def replace_and_check( - value, - expected, - renamings={}, - value_transforms={}, - keys_to_drop={}, - type_mappings={}, - keys_to_pull_up={}, -): + value: JsonDict, + expected: JsonDict, + renamings: dict[str, str] = {}, + value_transforms: ValueTransform = {}, + keys_to_drop: dict[str, list[str]] = {}, + type_mappings: dict[str, str] = {}, + keys_to_pull_up: dict[str, None | list[str]] = {}, +) -> None: # Helper function which performs replacements and asserts the result is as expected actual = replace( value, @@ -23,7 +23,7 @@ def replace_and_check( assert actual == expected -def test_renamings(): +def test_renamings() -> None: # Some properties need to be renamed renamings = { 'd2LogicalModel': 'payload', @@ -39,7 +39,7 @@ def test_renamings(): ) -def test_value_transforms(): +def test_value_transforms() -> None: # Some properties require specific transfomations value_transforms = {'key': lambda v: int(v)} @@ -47,9 +47,9 @@ def test_value_transforms(): replace_and_check({'key': '1'}, {'key': 1}, value_transforms=value_transforms) -def test_keys_to_drop_from_any_parent(): +def test_keys_to_drop_from_any_parent() -> None: # Some properties need to be dropped, either in general, or only if appearing under a specific parent - keys_to_drop = {'unwanted_key': []} + keys_to_drop: dict[str, list[str]] = {'unwanted_key': []} replace_and_check( {'parent': {'unwanted_key': '1', 'wanted_key': '2'}}, @@ -58,10 +58,10 @@ def test_keys_to_drop_from_any_parent(): ) -def test_keys_to_drop_from_specific_parent(): +def test_keys_to_drop_from_specific_parent() -> None: # Some properties need to be dropped, either in general, or only if appearing under a specific parent - keys_to_drop = {'unwanted_key': 'parent'} + keys_to_drop: dict[str, list[str]] = {'unwanted_key': ['parent']} replace_and_check( {'parent': {'unwanted_key': '1', 'wanted_key': '2'}}, @@ -75,7 +75,7 @@ def test_keys_to_drop_from_specific_parent(): ) -def test_type_mappings(): +def test_type_mappings() -> None: # Instead of having the objects type indicated by e.g. @xsitype, # a wrapping type object is inserted by DATEXII Part 15. @@ -90,10 +90,10 @@ def test_type_mappings(): ) -def test_keys_to_pull_up_all_children(): +def test_keys_to_pull_up_all_children() -> None: # For some objects, all or some of their properties need to be pulled one level up - keys_to_pull_up = {'openlrExtendedPoint': None} + keys_to_pull_up: dict[str, None | list[str]] = {'openlrExtendedPoint': None} replace_and_check( {'openlrExtendedPoint': {'a': 'value', 'b': 'value'}}, @@ -102,9 +102,9 @@ def test_keys_to_pull_up_all_children(): ) -def test_keys_to_pull_up_specified_children(): +def test_keys_to_pull_up_specified_children() -> None: # For some objects, all or some of their properties need to be pulled one level up - keys_to_pull_up = {'openlrExtendedPoint': ['a']} + keys_to_pull_up: dict[str, None | list[str]] = {'openlrExtendedPoint': ['a']} replace_and_check( {'openlrExtendedPoint': {'a': 'value', 'b': 'value'}}, diff --git a/tests/unit/test_source_transformer.py b/tests/unit/test_source_transformer.py index 7f3bada..ed71738 100644 --- a/tests/unit/test_source_transformer.py +++ b/tests/unit/test_source_transformer.py @@ -1,33 +1,29 @@ -from datex2_xml2json.transform.base import SituationRecordTransformer +from datex2_xml2json.transform.source_setter import SourceSetter +from datex2_xml2json.util import JsonDict -class SourceTransformer(SituationRecordTransformer): - sourceIdentification: str | None = None - publicationId: str | None = None - - def __init__(self, publicationId: str | None, sourceIdentification: str | None): - super().__init__('payload/situation/situationRecord') - self.publicationId = publicationId - self.sourceIdentification = sourceIdentification - - def process_situation_record(self, situation_record: dict) -> None: - situation_record['source'] = {'sourceIdentification': self.sourceIdentification} - - def transform(self, publication: dict) -> dict: - publication = super().transform(publication) - - publication['payload']['publicationId'] = self.publicationId - return publication - - -def test_source_added(): - transformer = SourceTransformer('https://xyz.xyz/dataset-id', 'roadworks_source') - payload = {'payload': {'situation': [{'situationRecord': [{}]}]}} +def test_source_added() -> None: + transformer = SourceSetter('https://xyz.xyz/dataset-id', 'roadworks_source') + payload: JsonDict = {'d2LogicalModel': {'payloadPublication': {'situation': [{'situationRecord': [{}]}]}}} expected = { - 'payload': { - 'publicationId': 'https://xyz.xyz/dataset-id', - 'situation': [{'situationRecord': [{'source': {'sourceIdentification': 'roadworks_source'}}]}], + 'd2LogicalModel': { + 'payloadPublication': { + 'situation': [{'situationRecord': [{'source': {'sourceIdentification': 'roadworks_source'}}]}], + 'payloadPublicationExtension': { + 'publicationIdentifier': 'https://xyz.xyz/dataset-id', + }, + } } } actual = transformer.transform(payload) assert expected == actual + + +def test_existing_source_properties_are_retained() -> None: + transformer = SourceSetter(None, 'roadworks_source') + record = {'id': 'a', 'source': {'sourceCountry': 'de', 'sourceIdentification': 'old'}} + payload: JsonDict = {'d2LogicalModel': {'payloadPublication': {'situation': [{'situationRecord': [record]}]}}} + + transformer.transform(payload) + + assert record['source'] == {'sourceCountry': 'de', 'sourceIdentification': 'roadworks_source'} diff --git a/tests/unit/test_transformer.py b/tests/unit/test_transformer.py new file mode 100644 index 0000000..e4927a5 --- /dev/null +++ b/tests/unit/test_transformer.py @@ -0,0 +1,57 @@ +from pathlib import Path + +import pytest + +from datex2_xml2json.transformer import ( + InputFormat, + OutputFormat, + UnsupportedOptionsError, + build_transformer, + check_options, + transform, +) + +XML_FIXTURE = str(Path(__file__).parents[1] / 'integration' / 'data' / 'sitpub_pointCoordinate.xml') + + +@pytest.mark.parametrize( + 'output_format', [OutputFormat.GEOJSON, OutputFormat.RAW, OutputFormat.DATEX2_3_7_JSON_LITE, OutputFormat.GEOPARQUET] +) +def test_validation_of_unsupported_format_is_rejected_before_writing(tmp_path: Path, output_format: OutputFormat) -> None: + with pytest.raises(UnsupportedOptionsError): + transform(XML_FIXTURE, str(tmp_path), InputFormat.DATEX2_2_2_XML, output_format, True, None, None) + + assert list(tmp_path.iterdir()) == [] + + +@pytest.mark.parametrize( + 'output_format', + [None, OutputFormat.GEOJSON, OutputFormat.CIFS, OutputFormat.DATEX2_3_7_JSON_LITE, OutputFormat.GEOPARQUET], +) +def test_unsupported_output_formats_for_3_7_input_are_rejected(output_format: OutputFormat | None) -> None: + with pytest.raises(UnsupportedOptionsError): + check_options(InputFormat.DATEX2_3_7_XML, output_format, False, None, None) + + +@pytest.mark.parametrize('source,publication', [('source', None), (None, 'publication')]) +def test_source_options_for_3_7_input_are_rejected(source: str | None, publication: str | None) -> None: + with pytest.raises(UnsupportedOptionsError): + check_options(InputFormat.DATEX2_3_7_XML, OutputFormat.DATEX2_3_7_JSON, False, source, publication) + + +@pytest.mark.parametrize('output_format', [OutputFormat.DATEX2_3_7_JSON, OutputFormat.RAW]) +def test_supported_output_formats_for_3_7_input_are_accepted(output_format: OutputFormat) -> None: + check_options(InputFormat.DATEX2_3_7_XML, output_format, False, None, None) + + +def test_build_transformer_rejects_unsupported_output_format_for_3_7_input() -> None: + with pytest.raises(ValueError, match='Unsupported output format'): + build_transformer(InputFormat.DATEX2_3_7_XML, OutputFormat.GEOJSON) + + +def test_raw_output_does_not_contain_source_options(tmp_path: Path) -> None: + transform(XML_FIXTURE, str(tmp_path), InputFormat.DATEX2_2_2_XML, None, False, 'MY_SOURCE_ID', 'MY_PUBLICATION_ID') + + assert 'MY_SOURCE_ID' not in (tmp_path / 'sitpub_pointCoordinate.raw.json').read_text() + assert 'MY_SOURCE_ID' in (tmp_path / 'sitpub_pointCoordinate.lite.json').read_text() + assert 'MY_PUBLICATION_ID' in (tmp_path / 'sitpub_pointCoordinate.lite.json').read_text() diff --git a/uv.lock b/uv.lock index bdcb21c..fd5c8e8 100644 --- a/uv.lock +++ b/uv.lock @@ -516,30 +516,26 @@ dependencies = [ dev = [ { name = "mypy" }, { name = "pre-commit" }, - { name = "pyarrow-stubs" }, { name = "pytest" }, { name = "ruff" }, - { name = "types-shapely" }, ] [package.metadata] requires-dist = [ - { name = "check-jsonschema", specifier = ">=0.38.2" }, - { name = "geoparquet-io", specifier = ">=1.6.0" }, - { name = "jsonata-python", specifier = ">=0.7.0" }, - { name = "jsonschema", specifier = ">=4.26.0" }, - { name = "pyarrow", specifier = ">=26.0.0" }, - { name = "rs-xml2json", specifier = ">=0.2.0" }, + { name = "check-jsonschema", specifier = ">=0.38,<1" }, + { name = "geoparquet-io", specifier = ">=1.7,<2" }, + { name = "jsonata-python", specifier = ">=0.7.0,<1" }, + { name = "jsonschema", specifier = ">=4.26,<5" }, + { name = "pyarrow", specifier = ">=26,<27" }, + { name = "rs-xml2json", specifier = "~=0.2.0" }, ] [package.metadata.requires-dev] dev = [ { name = "mypy", specifier = "~=2.3.1" }, - { name = "pre-commit", specifier = ">=4.3.0" }, - { name = "pyarrow-stubs", specifier = "~=20.0.0.20260819" }, - { name = "pytest", specifier = "~=9.1.1" }, + { name = "pre-commit", specifier = ">=4.3.0,<5" }, + { name = "pytest", specifier = ">=9.1.1,<10" }, { name = "ruff", specifier = "~=0.17.2" }, - { name = "types-shapely", specifier = "~=2.1.0.20260728" }, ] [[package]] @@ -1901,18 +1897,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/96/be/7b81a44d6a8e70581dcc1d6f01541f9000a973b1e5d75394aec91e7b179a/pyarrow-26.0.0-cp315-cp315t-win_amd64.whl", hash = "sha256:68cd662e9e2b00876a131950cf32336ace2d0865e1f9418763e3d3be8481dfa4", size = 29389953, upload-time = "2026-10-09T08:26:18.277Z" }, ] -[[package]] -name = "pyarrow-stubs" -version = "20.0.0.20260819" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyarrow" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/12/a7/8a2ca91ffe4c6576207f932de655d7d8a36485c520dccce70ce7d492b256/pyarrow_stubs-20.0.0.20260819.tar.gz", hash = "sha256:150710a72248bc834bf048d3092713f070904a4af76d40289c43afb3ee189823", size = 238222, upload-time = "2026-08-19T05:52:53.618Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/65/6c/eea1d03e475217aea95b1d52aee09c97575d05bbc592c39c085b71dab89f/pyarrow_stubs-20.0.0.20260819-py3-none-any.whl", hash = "sha256:297e60b6e5314739c082b4757d090d8be6047465510eb0684ca954ef7ea58be3", size = 235949, upload-time = "2026-08-19T05:52:54.711Z" }, -] - [[package]] name = "pygments" version = "2.21.0" @@ -2705,18 +2689,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, ] -[[package]] -name = "types-shapely" -version = "2.1.0.20260728" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "numpy" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/be/cf/1ea740a3532b6e4cdeae8ba121618eb58a543eba2721016d358e4c0992e3/types_shapely-2.1.0.20260728.tar.gz", hash = "sha256:8ec23a5aa484c1ec7bbc56aa353cc230ae63e38e0f35a6e4b79a011d99bcfcc2", size = 27501, upload-time = "2026-07-28T04:51:41.724Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/79/8d/2e6c38118cc6b20075ccd1609840314aa8a694a255a09149b185d8a608e1/types_shapely-2.1.0.20260728-py3-none-any.whl", hash = "sha256:7299a62025528b3f0cc5af37095f05fbe7d76d399bdc8d7ea9b3d395e988f547", size = 38539, upload-time = "2026-07-28T04:51:40.638Z" }, -] - [[package]] name = "typing-extensions" version = "4.16.0"