From b314cca0ed5aa51aa9e68c9ef3935f214806f6a3 Mon Sep 17 00:00:00 2001 From: Holger Bruch Date: Wed, 4 Nov 2026 18:11:31 +0100 Subject: [PATCH 01/16] chore: support type checking --- src/datex2_xml2json/py.typed | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 src/datex2_xml2json/py.typed diff --git a/src/datex2_xml2json/py.typed b/src/datex2_xml2json/py.typed new file mode 100644 index 0000000..e69de29 From 9c2dc16d8d475141ddf174cffd7522fd65098ce5 Mon Sep 17 00:00:00 2001 From: Holger Bruch Date: Wed, 4 Nov 2026 18:20:13 +0100 Subject: [PATCH 02/16] style: add missing types --- src/datex2_xml2json/json_validator.py | 9 ++-- src/datex2_xml2json/transform/__init__.py | 5 ++- src/datex2_xml2json/transform/base.py | 30 +++++++------ .../transform/cifs_transformer.py | 25 ++++++----- .../transform/geojson_geometry_transformer.py | 18 ++++---- .../transform/geoparquet_transformer.py | 16 ++++--- .../transform/jsonata_transformer.py | 8 ++-- .../transform/roads_regio_transformer.py | 14 +++--- .../transform/source_setter.py | 7 +-- .../transform/transformation_rules.py | 43 ++++++++++--------- src/datex2_xml2json/transformer.py | 18 ++++---- src/datex2_xml2json/util.py | 28 +++++++----- tests/integration/test_xml_to_json_3_7.py | 41 +++++++++--------- tests/unit/test_cifs_transformer.py | 2 +- tests/unit/test_replacements.py | 40 ++++++++--------- 15 files changed, 170 insertions(+), 134 deletions(-) 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/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..14b7467 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__) @@ -143,11 +145,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,7 +165,7 @@ def _group_by_common_situation_record_id_substring(self, incidents, pattern): return grouped_incidents - def _get_type_sub_type_prio(self, incident): + def _get_type_sub_type_prio(self, incident: JsonDict) -> int: if incident.get('type') == 'ROAD_CLOSED': return 10 if incident.get('subtype') == 'HAZARD_ON_ROAD_LANE_CLOSED': @@ -175,7 +177,7 @@ def _get_type_sub_type_prio(self, incident): else: return 2 - 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,10 +186,13 @@ 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) @@ -207,7 +212,7 @@ def _merge_incident_group(self, incident_group): ) 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..a349bda 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. @@ -122,7 +126,7 @@ def _set_timestamps_to_UTC(self, a_geojson_dict: dict): 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. @@ -143,7 +147,7 @@ def _cast_fields_and_add_missing(self, table) -> None: 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,7 +157,7 @@ def _as_table(self, a_geojson_dict: dict): f.close() return gpio.convert(f.name) - def render(self, filename, a_geojson_dict: dict) -> None: + def render(self, filename: str | Path, a_geojson_dict: JsonDict) -> None: self._set_timestamps_to_UTC(a_geojson_dict) table = self._as_table(a_geojson_dict) self._cast_fields_and_add_missing(table) 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..e2607aa 100644 --- a/src/datex2_xml2json/transform/source_setter.py +++ b/src/datex2_xml2json/transform/source_setter.py @@ -1,4 +1,5 @@ from datex2_xml2json.transform.base import SituationRecordTransformer +from datex2_xml2json.util import JsonDict class SourceSetter(SituationRecordTransformer): @@ -11,15 +12,15 @@ class SourceSetter(SituationRecordTransformer): sourceIdentification: str | None = None publicationIdentifier: str | None = None - def __init__(self, publicationIdentifier: str | None, sourceIdentification: str | None): + def __init__(self, publicationIdentifier: str | None, sourceIdentification: str | None) -> None: super().__init__('d2LogicalModel/payload/situation/situationRecord') self.publicationIdentifier = publicationIdentifier self.sourceIdentification = sourceIdentification - def process_situation_record(self, situation_record: dict) -> None: + def process_situation_record(self, situation_record: JsonDict) -> None: situation_record['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) 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..76ea751 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,14 @@ 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())]) -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) @@ -97,7 +99,7 @@ def write(stem: str, json_result: dict, output_format: OutputFormat, outDir: str GeoparquetRenderer().render(outfile_name, json_result) -def generate_all(stem: str, json_input: dict, outDir: str, validate: bool): +def generate_all(stem: str, json_input: JsonDict, outDir: str, validate: bool) -> None: write(stem, json_input, OutputFormat.RAW, outDir) jsonLiteTransformer = build_transformer(InputFormat.DATEX2_2_2_XML, OutputFormat.DATEX2_3_7_JSON_LITE) jsonLite_output = jsonLiteTransformer.transform(json_input) @@ -113,11 +115,11 @@ 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: stem = Path(filename).stem json_input = load_as_json_using_schema(filename, schema_path(DEFAULT_SCHEMAS[input_format])) diff --git a/src/datex2_xml2json/util.py b/src/datex2_xml2json/util.py index d6671fb..35c30fb 100644 --- a/src/datex2_xml2json/util.py +++ b/src/datex2_xml2json/util.py @@ -1,27 +1,33 @@ import json +from collections.abc import Callable from importlib.resources import as_file, files from typing import Any from rs_xml2json import convert +JsonDict = dict[str, Any] +ValueTransform = dict[str, Callable[[Any], Any]] -def schema_path(schema): + +def schema_path(schema: str) -> str: with as_file(files('datex2_xml2json').joinpath(schema)) as fspath: return str(fspath.resolve()) -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 +38,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 +48,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 +81,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..32a5939 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,14 +11,14 @@ 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): +def load_and_transform(FIXTURE_NAME: str, overwrite: bool, transformer: AbstractTransformer, suffix: str) -> JsonDict: json_input = load_as_json_using_schema(FIXTURES_DIR + FIXTURE_NAME + '.xml', schema_path(DATEX2_XSD_2_2_0_SCHEMA)) if overwrite: with open(FIXTURES_DIR + FIXTURE_NAME + '.json', 'w') as f: @@ -39,7 +40,7 @@ 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: @@ -50,7 +51,7 @@ def transform_validate(FIXTURE_NAME: str, overwrite: bool, transformer, suffix: 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 +60,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 +73,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/test_cifs_transformer.py b/tests/unit/test_cifs_transformer.py index 05f7d57..721e838 100644 --- a/tests/unit/test_cifs_transformer.py +++ b/tests/unit/test_cifs_transformer.py @@ -1,7 +1,7 @@ from datex2_xml2json.transform import CifsTransformer -def test_post_transform(): +def test_post_transform() -> None: transformer = CifsTransformer() incidents = { 'incidents': [ 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'}}, From 31137e490b236a32d9fc8e494e389c4ad240bc00 Mon Sep 17 00:00:00 2001 From: Holger Bruch Date: Wed, 4 Nov 2026 19:24:58 +0100 Subject: [PATCH 03/16] fix: better checking of incompatible parameters ... and write raw before source and publication identifiers are added --- src/datex2_xml2json/transformer.py | 61 +++++++++++++++++++++++------- tests/unit/test_transformer.py | 57 ++++++++++++++++++++++++++++ 2 files changed, 104 insertions(+), 14 deletions(-) create mode 100644 tests/unit/test_transformer.py diff --git a/src/datex2_xml2json/transformer.py b/src/datex2_xml2json/transformer.py index 76ea751..034cca3 100644 --- a/src/datex2_xml2json/transformer.py +++ b/src/datex2_xml2json/transformer.py @@ -82,7 +82,33 @@ def build_transformer(input_format: InputFormat, output_format: OutputFormat) -> 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: JsonDict, output_format: OutputFormat, outDir: str, validate: bool = False) -> None: @@ -100,7 +126,6 @@ def write(stem: str, json_result: JsonDict, output_format: OutputFormat, outDir: def generate_all(stem: str, json_input: JsonDict, outDir: str, validate: bool) -> None: - write(stem, json_input, OutputFormat.RAW, outDir) 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) @@ -120,9 +145,17 @@ def transform( 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])) + # 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) @@ -184,16 +217,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/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() From 8c41f1f273ba7aa110d36266f3b1893af6da89ea Mon Sep 17 00:00:00 2001 From: Holger Bruch Date: Wed, 4 Nov 2026 19:25:46 +0100 Subject: [PATCH 04/16] fix: handle invalid timestamps --- .../transform/geoparquet_transformer.py | 13 +++++-- tests/unit/test_geoparquet_transformer.py | 39 +++++++++++++++++++ 2 files changed, 49 insertions(+), 3 deletions(-) create mode 100644 tests/unit/test_geoparquet_transformer.py diff --git a/src/datex2_xml2json/transform/geoparquet_transformer.py b/src/datex2_xml2json/transform/geoparquet_transformer.py index a349bda..b1f7a11 100644 --- a/src/datex2_xml2json/transform/geoparquet_transformer.py +++ b/src/datex2_xml2json/transform/geoparquet_transformer.py @@ -119,11 +119,18 @@ def _set_timestamps_to_UTC(self, a_geojson_dict: JsonDict) -> None: 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]) + 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.replace(tzinfo=timezone.utc) + dt = dt.replace(tzinfo=timezone.utc) props[ts_property] = dt.astimezone(timezone.utc).isoformat() def _cast_fields_and_add_missing(self, table: Any) -> None: 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() From e556372926277ae512d98509996b9f75a33ea424 Mon Sep 17 00:00:00 2001 From: Holger Bruch Date: Wed, 4 Nov 2026 19:26:28 +0100 Subject: [PATCH 05/16] fix: handle unset type --- src/datex2_xml2json/transform/cifs_transformer.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/datex2_xml2json/transform/cifs_transformer.py b/src/datex2_xml2json/transform/cifs_transformer.py index 14b7467..32ab7dd 100644 --- a/src/datex2_xml2json/transform/cifs_transformer.py +++ b/src/datex2_xml2json/transform/cifs_transformer.py @@ -199,16 +199,16 @@ def _merge_incident_group(self, incident_group: list[JsonDict]) -> JsonDict: 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 From d747fd3ef3cdebb909fabe9014c550fad8dd648e Mon Sep 17 00:00:00 2001 From: Holger Bruch Date: Wed, 4 Nov 2026 19:27:07 +0100 Subject: [PATCH 06/16] fix: append null column in case of exception --- src/datex2_xml2json/transform/geoparquet_transformer.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/datex2_xml2json/transform/geoparquet_transformer.py b/src/datex2_xml2json/transform/geoparquet_transformer.py index b1f7a11..00eac3a 100644 --- a/src/datex2_xml2json/transform/geoparquet_transformer.py +++ b/src/datex2_xml2json/transform/geoparquet_transformer.py @@ -150,6 +150,8 @@ def _cast_fields_and_add_missing(self, table: Any) -> 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 From 83f531d0e49eb0e741928f9ccec3519bebb0237f Mon Sep 17 00:00:00 2001 From: Holger Bruch Date: Wed, 4 Nov 2026 19:28:35 +0100 Subject: [PATCH 07/16] doc: fix paths to files containing jsonata expressions --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 From 67e7ce5cdb623e094689d98d12f400da1c84f5d5 Mon Sep 17 00:00:00 2001 From: Holger Bruch Date: Wed, 4 Nov 2026 19:33:16 +0100 Subject: [PATCH 08/16] chore: fix upper version bounds for dependencies --- pyproject.toml | 25 +++++++++++++------------ uv.lock | 32 +++++++++----------------------- 2 files changed, 22 insertions(+), 35 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index dead5d1..5aee47f 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,22 @@ 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", + "pyarrow-stubs>=20.0.0.20260819", ] [project.urls] @@ -144,6 +146,5 @@ module = [ "geoparquet_io", "rs_xml2json", "pyarrow", - "shapely.geometry", ] ignore_missing_imports = true diff --git a/uv.lock b/uv.lock index bdcb21c..705c70f 100644 --- a/uv.lock +++ b/uv.lock @@ -519,27 +519,25 @@ dev = [ { 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 = "pyarrow-stubs", specifier = ">=20.0.0.20260819" }, + { name = "pytest", specifier = ">=9.1.1,<10" }, { name = "ruff", specifier = "~=0.17.2" }, - { name = "types-shapely", specifier = "~=2.1.0.20260728" }, ] [[package]] @@ -2705,18 +2703,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" From 2fa128242936fc72238f91616b0f2a910d9b6d01 Mon Sep 17 00:00:00 2001 From: Holger Bruch Date: Wed, 4 Nov 2026 22:27:00 +0100 Subject: [PATCH 09/16] chore: disable pyarrow type checking ... as it does not provide typing information for pyarrow.parquet --- pyproject.toml | 4 ++-- uv.lock | 14 -------------- 2 files changed, 2 insertions(+), 16 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 5aee47f..6fbb634 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -41,8 +41,7 @@ dev = [ "pytest>=9.1.1,<10", "ruff~=0.17.2", "mypy~=2.3.1", - "pre-commit>=4.3.0,<5", - "pyarrow-stubs>=20.0.0.20260819", + "pre-commit>=4.3.0,<5" ] [project.urls] @@ -146,5 +145,6 @@ module = [ "geoparquet_io", "rs_xml2json", "pyarrow", + "pyarrow.parquet", ] ignore_missing_imports = true diff --git a/uv.lock b/uv.lock index 705c70f..fd5c8e8 100644 --- a/uv.lock +++ b/uv.lock @@ -516,7 +516,6 @@ dependencies = [ dev = [ { name = "mypy" }, { name = "pre-commit" }, - { name = "pyarrow-stubs" }, { name = "pytest" }, { name = "ruff" }, ] @@ -535,7 +534,6 @@ requires-dist = [ dev = [ { name = "mypy", specifier = "~=2.3.1" }, { name = "pre-commit", specifier = ">=4.3.0,<5" }, - { name = "pyarrow-stubs", specifier = ">=20.0.0.20260819" }, { name = "pytest", specifier = ">=9.1.1,<10" }, { name = "ruff", specifier = "~=0.17.2" }, ] @@ -1899,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" From 5eabd248be113f8e806e673859ff9551bde77201 Mon Sep 17 00:00:00 2001 From: Holger Bruch Date: Wed, 4 Nov 2026 18:06:54 +0100 Subject: [PATCH 10/16] fix: rename payload to payloadPublication --- .../transform/source_setter.py | 6 ++-- tests/unit/__init__.py | 0 tests/unit/test_source_transformer.py | 35 ++++++------------- 3 files changed, 13 insertions(+), 28 deletions(-) create mode 100644 tests/unit/__init__.py diff --git a/src/datex2_xml2json/transform/source_setter.py b/src/datex2_xml2json/transform/source_setter.py index e2607aa..3559409 100644 --- a/src/datex2_xml2json/transform/source_setter.py +++ b/src/datex2_xml2json/transform/source_setter.py @@ -5,7 +5,7 @@ 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. """ @@ -13,7 +13,7 @@ class SourceSetter(SituationRecordTransformer): publicationIdentifier: str | None = None def __init__(self, publicationIdentifier: str | None, sourceIdentification: str | None) -> None: - super().__init__('d2LogicalModel/payload/situation/situationRecord') + super().__init__('d2LogicalModel/payloadPublication/situation/situationRecord') self.publicationIdentifier = publicationIdentifier self.sourceIdentification = sourceIdentification @@ -25,7 +25,7 @@ def transform(self, publication: JsonDict) -> JsonDict: 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/tests/unit/__init__.py b/tests/unit/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/unit/test_source_transformer.py b/tests/unit/test_source_transformer.py index 7f3bada..09f2a93 100644 --- a/tests/unit/test_source_transformer.py +++ b/tests/unit/test_source_transformer.py @@ -1,32 +1,17 @@ -from datex2_xml2json.transform.base import SituationRecordTransformer - - -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 +from datex2_xml2json.transform.source_setter import SourceSetter def test_source_added(): - transformer = SourceTransformer('https://xyz.xyz/dataset-id', 'roadworks_source') - payload = {'payload': {'situation': [{'situationRecord': [{}]}]}} + transformer = SourceSetter('https://xyz.xyz/dataset-id', 'roadworks_source') + payload = {'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) From 29c3580e7c12f1cea1c8d4fb7c047677d08477a8 Mon Sep 17 00:00:00 2001 From: Holger Bruch Date: Wed, 4 Nov 2026 23:16:28 +0100 Subject: [PATCH 11/16] fix: Use HAZARD as fallback type and prioritize more specific types --- src/datex2_xml2json/transform/cifs_transformer.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/datex2_xml2json/transform/cifs_transformer.py b/src/datex2_xml2json/transform/cifs_transformer.py index 32ab7dd..3bc1661 100644 --- a/src/datex2_xml2json/transform/cifs_transformer.py +++ b/src/datex2_xml2json/transform/cifs_transformer.py @@ -60,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) */ @@ -173,9 +173,9 @@ def _get_type_sub_type_prio(self, incident: JsonDict) -> int: 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 + else: + return 1 def _merge_incident_group(self, incident_group: list[JsonDict]) -> JsonDict: # Assumptions: besides type and subtype, all properties are assumed to be equals From cf8adcfe5153108135287bdfbd17e60f59905845 Mon Sep 17 00:00:00 2001 From: Holger Bruch Date: Wed, 4 Nov 2026 23:17:54 +0100 Subject: [PATCH 12/16] fix: retain pre-existing source information --- src/datex2_xml2json/transform/source_setter.py | 2 +- tests/unit/test_source_transformer.py | 15 +++++++++++++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/datex2_xml2json/transform/source_setter.py b/src/datex2_xml2json/transform/source_setter.py index 3559409..cc777be 100644 --- a/src/datex2_xml2json/transform/source_setter.py +++ b/src/datex2_xml2json/transform/source_setter.py @@ -18,7 +18,7 @@ def __init__(self, publicationIdentifier: str | None, sourceIdentification: str self.sourceIdentification = sourceIdentification def process_situation_record(self, situation_record: JsonDict) -> None: - situation_record['source'] = {'sourceIdentification': self.sourceIdentification} + situation_record.setdefault('source', {})['sourceIdentification'] = self.sourceIdentification def transform(self, publication: JsonDict) -> JsonDict: if self.sourceIdentification is not None: diff --git a/tests/unit/test_source_transformer.py b/tests/unit/test_source_transformer.py index 09f2a93..ed71738 100644 --- a/tests/unit/test_source_transformer.py +++ b/tests/unit/test_source_transformer.py @@ -1,9 +1,10 @@ from datex2_xml2json.transform.source_setter import SourceSetter +from datex2_xml2json.util import JsonDict -def test_source_added(): +def test_source_added() -> None: transformer = SourceSetter('https://xyz.xyz/dataset-id', 'roadworks_source') - payload = {'d2LogicalModel': {'payloadPublication': {'situation': [{'situationRecord': [{}]}]}}} + payload: JsonDict = {'d2LogicalModel': {'payloadPublication': {'situation': [{'situationRecord': [{}]}]}}} expected = { 'd2LogicalModel': { 'payloadPublication': { @@ -16,3 +17,13 @@ def test_source_added(): } 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'} From 841e5df633012da590e0328f854acdaa7cb762cb Mon Sep 17 00:00:00 2001 From: Holger Bruch Date: Wed, 4 Nov 2026 23:25:37 +0100 Subject: [PATCH 13/16] fix: create a copy of geojson before transforming --- .../transform/geoparquet_transformer.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/datex2_xml2json/transform/geoparquet_transformer.py b/src/datex2_xml2json/transform/geoparquet_transformer.py index 00eac3a..e53d5b6 100644 --- a/src/datex2_xml2json/transform/geoparquet_transformer.py +++ b/src/datex2_xml2json/transform/geoparquet_transformer.py @@ -128,10 +128,10 @@ def _set_timestamps_to_UTC(self, a_geojson_dict: JsonDict) -> None: 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() + # 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: Any) -> None: """ @@ -167,7 +167,10 @@ def _as_table(self, a_geojson_dict: JsonDict) -> Any: return gpio.convert(f.name) def render(self, filename: str | Path, a_geojson_dict: JsonDict) -> None: - self._set_timestamps_to_UTC(a_geojson_dict) - table = self._as_table(a_geojson_dict) + # 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) From 4d7625bded5ffbb21f51c4f22e13767f2b1338b6 Mon Sep 17 00:00:00 2001 From: Holger Bruch Date: Wed, 4 Nov 2026 23:26:18 +0100 Subject: [PATCH 14/16] chore: enable strict mypy checking --- pyproject.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/pyproject.toml b/pyproject.toml index 6fbb634..9e94a4e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -131,6 +131,7 @@ testpaths = ["tests"] [tool.mypy] python_version = "3.12" +strict = true [[tool.mypy.overrides]] module = [ From 68b878e90afbd5031dcb393f71f4c5efa8d5814e Mon Sep 17 00:00:00 2001 From: Holger Bruch Date: Fri, 6 Nov 2026 17:05:58 +0100 Subject: [PATCH 15/16] fix: explicitly rate all known types ... and a few specific subtypes --- .../transform/cifs_transformer.py | 20 ++++---- tests/unit/test_cifs_transformer.py | 46 +++++++++++++++++++ 2 files changed, 56 insertions(+), 10 deletions(-) diff --git a/src/datex2_xml2json/transform/cifs_transformer.py b/src/datex2_xml2json/transform/cifs_transformer.py index 3bc1661..7e61d45 100644 --- a/src/datex2_xml2json/transform/cifs_transformer.py +++ b/src/datex2_xml2json/transform/cifs_transformer.py @@ -136,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 @@ -166,16 +172,10 @@ def _group_by_common_situation_record_id_substring(self, incidents: list[JsonDic return grouped_incidents def _get_type_sub_type_prio(self, incident: JsonDict) -> int: - 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 2 - else: - return 1 + 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: list[JsonDict]) -> JsonDict: # Assumptions: besides type and subtype, all properties are assumed to be equals diff --git a/tests/unit/test_cifs_transformer.py b/tests/unit/test_cifs_transformer.py index 721e838..dafae3e 100644 --- a/tests/unit/test_cifs_transformer.py +++ b/tests/unit/test_cifs_transformer.py @@ -1,3 +1,7 @@ +from typing import Any + +import pytest + from datex2_xml2json.transform import CifsTransformer @@ -24,3 +28,45 @@ def test_post_transform() -> None: } 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')] From 43eebe7ea0b484602814825f447136621289d395 Mon Sep 17 00:00:00 2001 From: Holger Bruch Date: Sat, 7 Nov 2026 10:05:32 +0100 Subject: [PATCH 16/16] fix: use context-manager for schema access --- src/datex2_xml2json/transformer.py | 7 +++++-- src/datex2_xml2json/util.py | 17 +++++++++++++---- tests/integration/test_xml_to_json_3_7.py | 6 ++++-- 3 files changed, 22 insertions(+), 8 deletions(-) diff --git a/src/datex2_xml2json/transformer.py b/src/datex2_xml2json/transformer.py index 034cca3..d7f152e 100644 --- a/src/datex2_xml2json/transformer.py +++ b/src/datex2_xml2json/transformer.py @@ -120,7 +120,9 @@ def write(stem: str, json_result: JsonDict, output_format: OutputFormat, outDir: 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) @@ -148,7 +150,8 @@ def transform( 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: diff --git a/src/datex2_xml2json/util.py b/src/datex2_xml2json/util.py index 35c30fb..b574d39 100644 --- a/src/datex2_xml2json/util.py +++ b/src/datex2_xml2json/util.py @@ -1,6 +1,8 @@ import json -from collections.abc import Callable +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 @@ -9,9 +11,16 @@ ValueTransform = dict[str, Callable[[Any], Any]] -def schema_path(schema: str) -> str: - 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) -> JsonDict: diff --git a/tests/integration/test_xml_to_json_3_7.py b/tests/integration/test_xml_to_json_3_7.py index 32a5939..80d9963 100644 --- a/tests/integration/test_xml_to_json_3_7.py +++ b/tests/integration/test_xml_to_json_3_7.py @@ -19,7 +19,8 @@ def load_and_transform(FIXTURE_NAME: str, overwrite: bool, transformer: AbstractTransformer, suffix: str) -> JsonDict: - json_input = load_as_json_using_schema(FIXTURES_DIR + FIXTURE_NAME + '.xml', schema_path(DATEX2_XSD_2_2_0_SCHEMA)) + 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) @@ -46,7 +47,8 @@ def transform_validate(FIXTURE_NAME: str, overwrite: bool, transformer: Abstract 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')