Debian Codegraph @

tests/test_features.py

raw
1 import json
2 from random import randint
3 from typing import Any, Dict
4 from uuid import uuid4
5
6 import pytest
7 from pydantic import BaseModel, ValidationError
8
9 from geojson_pydantic.features import Feature, FeatureCollection
10 from geojson_pydantic.geometries import (
11 Geometry,
12 GeometryCollection,
13 MultiPolygon,
14 Polygon,
15 )
16
17
18 class GenericProperties(BaseModel):
19 id: str
20 description: str
21 size: int
22
23
24 properties: Dict[str, Any] = {
25 "id": str(uuid4()),
26 "description": str(uuid4()),
27 "size": randint(0, 1000),
28 }
29
30 coordinates = [
31 [
32 [13.38272, 52.46385],
33 [13.42786, 52.46385],
34 [13.42786, 52.48445],
35 [13.38272, 52.48445],
36 [13.38272, 52.46385],
37 ]
38 ]
39
40 polygon: Dict[str, Any] = {
41 "type": "Polygon",
42 "coordinates": coordinates,
43 }
44
45 multipolygon: Dict[str, Any] = {
46 "type": "MultiPolygon",
47 "coordinates": [coordinates],
48 }
49
50 geom_collection: Dict[str, Any] = {
51 "type": "GeometryCollection",
52 "geometries": [polygon, multipolygon],
53 }
54
55 test_feature: Dict[str, Any] = {
56 "type": "Feature",
57 "geometry": polygon,
58 "properties": properties,
59 "bbox": [13.38272, 52.46385, 13.42786, 52.48445],
60 }
61
62 test_feature_geom_null: Dict[str, Any] = {
63 "type": "Feature",
64 "geometry": None,
65 "properties": properties,
66 }
67
68 test_feature_geometry_collection: Dict[str, Any] = {
69 "type": "Feature",
70 "geometry": geom_collection,
71 "properties": properties,
72 }
73
74
75 @pytest.mark.parametrize(
76 "obj",
77 [
78 FeatureCollection,
79 Feature,
80 ],
81 )
82 def test_pydantic_schema(obj):
83 """Test schema for Pydantic Object."""
84 assert obj.model_json_schema()
85
86
87 def test_feature_collection_iteration():
88 """test if feature collection is iterable"""
89 gc = FeatureCollection(
90 type="FeatureCollection", features=[test_feature, test_feature]
91 )
92 assert hasattr(gc, "__geo_interface__")
93 assert list(iter(gc))
94 assert len(list(gc.iter())) == 2
95 assert dict(gc)
96
97
98 def test_geometry_collection_iteration():
99 """test if feature collection is iterable"""
100 gc = FeatureCollection(
101 type="FeatureCollection", features=[test_feature_geometry_collection]
102 )
103 assert hasattr(gc, "__geo_interface__")
104 assert list(iter(gc))
105 assert len(list(gc.iter())) == 1
106 assert dict(gc)
107
108
109 def test_generic_properties_is_dict():
110 feature = Feature(**test_feature)
111 assert hasattr(feature, "__geo_interface__")
112 assert feature.properties["id"] == test_feature["properties"]["id"]
113 assert isinstance(feature.properties, dict)
114 assert not hasattr(feature.properties, "id")
115
116
117 def test_generic_properties_is_dict_collection():
118 feature = Feature(**test_feature_geometry_collection)
119 assert hasattr(feature, "__geo_interface__")
120 assert (
121 feature.properties["id"] == test_feature_geometry_collection["properties"]["id"]
122 )
123 assert isinstance(feature.properties, dict)
124 assert not hasattr(feature.properties, "id")
125
126
127 def test_generic_properties_is_object():
128 feature = Feature[Geometry, GenericProperties](**test_feature)
129 assert feature.properties.id == test_feature["properties"]["id"]
130 assert isinstance(feature.properties, GenericProperties)
131 assert hasattr(feature.properties, "id")
132
133
134 def test_generic_geometry():
135 feature = Feature[Polygon, GenericProperties](**test_feature)
136 assert feature.properties.id == test_feature_geometry_collection["properties"]["id"]
137 assert isinstance(feature.geometry, Polygon)
138 assert isinstance(feature.properties, GenericProperties)
139 assert hasattr(feature.properties, "id")
140
141 feature = Feature[Polygon, Dict](**test_feature)
142 assert isinstance(feature.geometry, Polygon)
143 assert feature.properties["id"] == test_feature["properties"]["id"]
144 assert isinstance(feature.properties, dict)
145 assert not hasattr(feature.properties, "id")
146
147 with pytest.raises(ValidationError):
148 Feature[MultiPolygon, Dict](**({"type": "Feature", "geometry": polygon}))
149
150
151 def test_generic_geometry_collection():
152 feature = Feature[GeometryCollection, GenericProperties](
153 **test_feature_geometry_collection
154 )
155 assert feature.properties.id == test_feature_geometry_collection["properties"]["id"]
156 assert isinstance(feature.geometry, GeometryCollection)
157 assert feature.geometry.wkt.startswith("GEOMETRYCOLLECTION (POLYGON ")
158 assert isinstance(feature.properties, GenericProperties)
159 assert hasattr(feature.properties, "id")
160
161 feature = Feature[GeometryCollection, Dict](**test_feature_geometry_collection)
162 assert isinstance(feature.geometry, GeometryCollection)
163 assert (
164 feature.properties["id"] == test_feature_geometry_collection["properties"]["id"]
165 )
166 assert isinstance(feature.properties, dict)
167 assert not hasattr(feature.properties, "id")
168
169 with pytest.raises(ValidationError):
170 Feature[MultiPolygon, Dict](**({"type": "Feature", "geometry": polygon}))
171
172
173 def test_generic_properties_should_raise_for_string():
174 with pytest.raises(ValidationError):
175 Feature(
176 **({"type": "Feature", "geometry": polygon, "properties": "should raise"})
177 )
178
179
180 def test_feature_collection_generic():
181 fc = FeatureCollection[Feature[Polygon, GenericProperties]](
182 type="FeatureCollection", features=[test_feature, test_feature]
183 )
184 assert fc.length == 2
185 assert len(list(fc.iter())) == 2
186 assert isinstance(fc.features[0].properties, GenericProperties)
187 assert isinstance(fc.features[0].geometry, Polygon)
188 assert dict(fc)
189
190
191 def test_geo_interface_protocol():
192 class Pointy:
193 __geo_interface__ = {"type": "Point", "coordinates": (0.0, 0.0)}
194
195 feat = Feature(type="Feature", geometry=Pointy(), properties={})
196 assert feat.geometry.model_dump(exclude_unset=True) == Pointy.__geo_interface__
197
198
199 def test_feature_with_null_geometry():
200 feature = Feature(**test_feature_geom_null)
201 assert feature.geometry is None
202
203
204 def test_feature_geo_interface_with_null_geometry():
205 feature = Feature(**test_feature_geom_null)
206 assert "bbox" not in feature.__geo_interface__
207
208
209 def test_feature_collection_geo_interface_with_null_geometry():
210 fc = FeatureCollection(
211 type="FeatureCollection", features=[test_feature_geom_null, test_feature]
212 )
213 assert "bbox" not in fc.__geo_interface__
214 assert "bbox" not in fc.__geo_interface__["features"][0]
215 assert "bbox" in fc.__geo_interface__["features"][1]
216
217
218 @pytest.mark.parametrize("id", ["a", 1, "1", 9007199254740993, 1.0, 1.25, -1.25, 0.0])
219 @pytest.mark.parametrize("from_json", [False, True])
220 def test_feature_id(id, from_json):
221 """Identifiers retain their values and types during validation and serialization."""
222 data = dict(test_feature, id=id)
223 feature = (
224 Feature.model_validate_json(json.dumps(data)) if from_json else Feature(**data)
225 )
226 assert feature.id == id
227 assert type(feature.id) is type(id)
228 serialized = json.loads(feature.model_dump_json())
229 assert serialized["id"] == id
230 assert type(serialized["id"]) is type(id)
231 assert feature.__geo_interface__["id"] == id
232
233
234 @pytest.mark.parametrize(
235 "id", [True, False, [], {}, float("nan"), float("inf"), -float("inf")]
236 )
237 @pytest.mark.parametrize("from_json", [False, True])
238 def test_bad_feature_id(id, from_json):
239 """make sure it raises error."""
240 with pytest.raises(ValidationError):
241 data = dict(test_feature, id=id)
242 if from_json:
243 Feature.model_validate_json(json.dumps(data))
244 else:
245 Feature(**data)
246
247
248 def test_feature_id_schema():
249 """The identifier schema accepts JSON numbers as well as strings."""
250 schema = Feature.model_json_schema()["properties"]["id"]
251 assert {choice["type"] for choice in schema["anyOf"]} == {
252 "integer",
253 "number",
254 "string",
255 "null",
256 }
257
258
259 def test_feature_validation():
260 """Test default."""
261 assert Feature(type="Feature", properties=None, geometry=None)
262 assert Feature(type="Feature", properties=None, geometry=None, bbox=None)
263
264 with pytest.raises(ValidationError):
265 # should be type=Feature
266 Feature(type="feature", properties=None, geometry=None)
267
268 with pytest.raises(ValidationError):
269 # missing type
270 Feature(properties=None, geometry=None)
271
272 with pytest.raises(ValidationError):
273 # missing properties
274 Feature(type="Feature", geometry=None)
275
276 with pytest.raises(ValidationError):
277 # missing geometry
278 Feature(type="Feature", properties=None)
279
280 assert Feature(
281 type="Feature", properties=None, bbox=(0, 0, 100, 100), geometry=None
282 )
283 assert Feature(
284 type="Feature", properties=None, bbox=(0, 0, 0, 100, 100, 100), geometry=None
285 )
286
287 with pytest.raises(ValidationError):
288 # bad bbox2d
289 Feature(type="Feature", properties=None, bbox=(0, 100, 100, 0), geometry=None)
290
291 with pytest.raises(ValidationError):
292 # bad bbox3d
293 Feature(
294 type="Feature",
295 properties=None,
296 bbox=(0, 100, 100, 100, 0, 0),
297 geometry=None,
298 )
299
300 # Antimeridian
301 with pytest.warns(UserWarning):
302 Feature(type="Feature", properties=None, bbox=(100, 0, 0, 100), geometry=None)
303
304 with pytest.warns(UserWarning):
305 Feature(
306 type="Feature",
307 properties=None,
308 bbox=(100, 0, 0, 0, 100, 100),
309 geometry=None,
310 )
311
312
313 def test_bbox_validation():
314 # Some attempts at generic validation did not validate the types within
315 # bbox before passing them to the function and resulted in TypeErrors.
316 # This test exists to ensure that doesn't happen in the future.
317 with pytest.raises(ValidationError):
318 Feature(
319 type="Feature",
320 properties=None,
321 bbox=(0, "a", 0, 1, 1, 1),
322 geometry=None,
323 )
324
325
326 def test_feature_validation_error_count():
327 # Tests that validation does not include irrelevant errors to make them
328 # easier to read. The input below used to raise 18 errors.
329 # See #93 for more details.
330 with pytest.raises(ValidationError):
331 try:
332 Feature(
333 type="Feature",
334 geometry=Polygon(
335 type="Polygon",
336 coordinates=[
337 [
338 (-55.9947406591177, -9.26104045526505),
339 (-55.9976752102375, -9.266589696568962),
340 (-56.00200328975916, -9.264041751931352),
341 (-55.99899921566248, -9.257935213034594),
342 (-55.99477406591177, -9.26103945526505),
343 ]
344 ],
345 ),
346 properties={},
347 )
348 except ValidationError as e:
349 assert e.error_count() == 1
350 raise
351
352
353 def test_feature_serializer():
354 f = Feature(
355 **{
356 "type": "Feature",
357 "geometry": {
358 "type": "Polygon",
359 "coordinates": coordinates,
360 },
361 "properties": {},
362 "id": "Yo",
363 "bbox": [13.38272, 52.46385, 13.42786, 52.48445],
364 }
365 )
366 assert "bbox" in f.model_dump()
367 assert "id" in f.model_dump()
368
369 # Exclude
370 assert "bbox" not in f.model_dump(exclude={"bbox"})
371 assert "bbox" not in list(json.loads(f.model_dump_json(exclude={"bbox"})).keys())
372
373 # Include
374 assert ["bbox"] == list(f.model_dump(include={"bbox"}).keys())
375 assert ["bbox"] == list(json.loads(f.model_dump_json(include={"bbox"})).keys())
376
377 feat_ser = json.loads(f.model_dump_json())
378 assert "bbox" in feat_ser
379 assert "id" in feat_ser
380 assert "bbox" not in feat_ser["geometry"]
381
382 f = Feature(
383 **{
384 "type": "Feature",
385 "geometry": {
386 "type": "Polygon",
387 "coordinates": coordinates,
388 },
389 "properties": {},
390 }
391 )
392 # BBOX Should'nt be present if `None`
393 # https://github.com/developmentseed/geojson-pydantic/issues/125
394 assert "bbox" in f.model_dump()
395
396 feat_ser = json.loads(f.model_dump_json())
397 assert "bbox" not in feat_ser
398 assert "id" not in feat_ser
399 assert "bbox" not in feat_ser["geometry"]
400
401 f = Feature(
402 **{
403 "type": "Feature",
404 "geometry": {
405 "type": "Polygon",
406 "coordinates": coordinates,
407 "bbox": [13.38272, 52.46385, 13.42786, 52.48445],
408 },
409 "properties": {},
410 }
411 )
412 feat_ser = json.loads(f.model_dump_json())
413 assert "bbox" not in feat_ser
414 assert "id" not in feat_ser
415 assert "bbox" in feat_ser["geometry"]
416
417
418 def test_feature_collection_serializer():
419 fc = FeatureCollection(
420 **{
421 "type": "FeatureCollection",
422 "features": [
423 {
424 "type": "Feature",
425 "geometry": {
426 "type": "Polygon",
427 "coordinates": coordinates,
428 "bbox": [13.38272, 52.46385, 13.42786, 52.48445],
429 },
430 "properties": {},
431 "bbox": [13.38272, 52.46385, 13.42786, 52.48445],
432 }
433 ],
434 "bbox": [13.38272, 52.46385, 13.42786, 52.48445],
435 }
436 )
437 assert "bbox" in fc.model_dump()
438
439 # Exclude
440 assert "bbox" not in fc.model_dump(exclude={"bbox"})
441 assert "bbox" not in list(json.loads(fc.model_dump_json(exclude={"bbox"})).keys())
442
443 # Include
444 assert ["bbox"] == list(fc.model_dump(include={"bbox"}).keys())
445 assert ["bbox"] == list(json.loads(fc.model_dump_json(include={"bbox"})).keys())
446
447 featcoll_ser = json.loads(fc.model_dump_json())
448 assert "bbox" in featcoll_ser
449 assert "bbox" in featcoll_ser["features"][0]
450 assert "bbox" in featcoll_ser["features"][0]["geometry"]
451
452 fc = FeatureCollection(
453 **{
454 "type": "FeatureCollection",
455 "features": [
456 {
457 "type": "Feature",
458 "geometry": {
459 "type": "Polygon",
460 "coordinates": coordinates,
461 },
462 "properties": {},
463 }
464 ],
465 }
466 )
467 assert "bbox" in fc.model_dump()
468
469 featcoll_ser = json.loads(fc.model_dump_json())
470 assert "bbox" not in featcoll_ser
471 assert "bbox" not in featcoll_ser["features"][0]
472 assert "bbox" not in featcoll_ser["features"][0]["geometry"]