diff --git a/src/mapillary/models/geojson.py b/src/mapillary/models/geojson.py index 1730f2d..453f7a2 100644 --- a/src/mapillary/models/geojson.py +++ b/src/mapillary/models/geojson.py @@ -207,6 +207,11 @@ def __init__(self, geometry: dict) -> None: options=["dict"], ) + if not geometry: + self.type = None + self.coordinates = None + return + # Setting the type of the selected geometry self.type: str = geometry["type"] @@ -218,7 +223,10 @@ def __init__(self, geometry: dict) -> None: def to_dict(self): """Return dictionary representation of the geometry""" - return {"type": self.type, "coordinates": self.coordinates.to_list()} + return { + "type": self.type, + "coordinates": self.coordinates.to_list() if self.coordinates else None, + } def __str__(self): """Return the informal string representation of the Geometry""" @@ -267,7 +275,8 @@ def __init__(self, feature: dict) -> None: self.type = "Feature" # Setting the `geometry` property - self.geometry = Geometry(feature["geometry"]) + geom = feature.get("geometry") + self.geometry = Geometry(geom) if geom else None # Setting the `properties` property self.properties = Properties(feature["properties"]) @@ -277,7 +286,7 @@ def to_dict(self) -> dict: return { "type": self.type, - "geometry": self.geometry.to_dict(), + "geometry": self.geometry.to_dict() if self.geometry else None, "properties": self.properties.to_dict(), } diff --git a/tests/models/test_geojson.py b/tests/models/test_geojson.py new file mode 100644 index 0000000..2391bcd --- /dev/null +++ b/tests/models/test_geojson.py @@ -0,0 +1,60 @@ +# Copyright (c) 2022 Facebook, Inc. and its affiliates. (http://www.facebook.com) +# -*- coding: utf-8 -*- + +""" +tests.models.test_geojson + +This module tests the GeoJSON model classes defined in src/mapillary/models/geojson.py. +""" + +from mapillary.models.geojson import Feature, GeoJSON, Geometry + + +def test_geometry_empty_dict_does_not_raise_key_error(): + geom = Geometry({}) + assert geom.type is None + assert geom.coordinates is None + assert geom.to_dict() == { + "type": None, + "coordinates": None, + } + + +def test_geometry_none_sets_none_fields(): + geom = Geometry(None) + assert geom.type is None + assert geom.coordinates is None + assert geom.to_dict() == { + "type": None, + "coordinates": None, + } + + +def test_feature_with_empty_geometry(): + feature = Feature( + { + "type": "Feature", + "geometry": {}, + "properties": {"id": "123"}, + } + ) + assert feature.geometry is None + assert feature.to_dict()["geometry"] is None + + +def test_geojson_with_empty_feature_geometry(): + geojson = GeoJSON( + { + "type": "FeatureCollection", + "features": [ + { + "type": "Feature", + "geometry": {}, + "properties": {}, + } + ], + } + ) + assert len(geojson.features) == 1 + assert geojson.features[0].geometry is None + assert geojson.to_dict()["features"][0]["geometry"] is None