Debian Codegraph @

tests/test_features.py

raw symbols SCIP
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"])
219 def test_feature_id(id):
220 """Test if a string stays a string and if an int stays an int."""
221 feature = Feature(**test_feature, id=id)
222 assert feature.id == id
223
224
225 @pytest.mark.parametrize("id", [True, 1.0])
226 def test_bad_feature_id(id):
227 """make sure it raises error."""
228 with pytest.raises(ValidationError):
229 Feature(**test_feature, id=id)
230
231
232 def test_feature_validation():
233 """Test default."""
234 assert Feature(type="Feature", properties=None, geometry=None)
235 assert Feature(type="Feature", properties=None, geometry=None, bbox=None)
236
237 with pytest.raises(ValidationError):
238 # should be type=Feature
239 Feature(type="feature", properties=None, geometry=None)
240
241 with pytest.raises(ValidationError):
242 # missing type
243 Feature(properties=None, geometry=None)
244
245 with pytest.raises(ValidationError):
246 # missing properties
247 Feature(type="Feature", geometry=None)
248
249 with pytest.raises(ValidationError):
250 # missing geometry
251 Feature(type="Feature", properties=None)
252
253 assert Feature(
254 type="Feature", properties=None, bbox=(0, 0, 100, 100), geometry=None
255 )
256 assert Feature(
257 type="Feature", properties=None, bbox=(0, 0, 0, 100, 100, 100), geometry=None
258 )
259
260 with pytest.raises(ValidationError):
261 # bad bbox2d
262 Feature(type="Feature", properties=None, bbox=(0, 100, 100, 0), geometry=None)
263
264 with pytest.raises(ValidationError):
265 # bad bbox3d
266 Feature(
267 type="Feature",
268 properties=None,
269 bbox=(0, 100, 100, 100, 0, 0),
270 geometry=None,
271 )
272
273 # Antimeridian
274 with pytest.warns(UserWarning):
275 Feature(type="Feature", properties=None, bbox=(100, 0, 0, 100), geometry=None)
276
277 with pytest.warns(UserWarning):
278 Feature(
279 type="Feature",
280 properties=None,
281 bbox=(100, 0, 0, 0, 100, 100),
282 geometry=None,
283 )
284
285
286 def test_bbox_validation():
287 # Some attempts at generic validation did not validate the types within
288 # bbox before passing them to the function and resulted in TypeErrors.
289 # This test exists to ensure that doesn't happen in the future.
290 with pytest.raises(ValidationError):
291 Feature(
292 type="Feature",
293 properties=None,
294 bbox=(0, "a", 0, 1, 1, 1),
295 geometry=None,
296 )
297
298
299 def test_feature_validation_error_count():
300 # Tests that validation does not include irrelevant errors to make them
301 # easier to read. The input below used to raise 18 errors.
302 # See #93 for more details.
303 with pytest.raises(ValidationError):
304 try:
305 Feature(
306 type="Feature",
307 geometry=Polygon(
308 type="Polygon",
309 coordinates=[
310 [
311 (-55.9947406591177, -9.26104045526505),
312 (-55.9976752102375, -9.266589696568962),
313 (-56.00200328975916, -9.264041751931352),
314 (-55.99899921566248, -9.257935213034594),
315 (-55.99477406591177, -9.26103945526505),
316 ]
317 ],
318 ),
319 properties={},
320 )
321 except ValidationError as e:
322 assert e.error_count() == 1
323 raise
324
325
326 def test_feature_serializer():
327 f = Feature(
328 **{
329 "type": "Feature",
330 "geometry": {
331 "type": "Polygon",
332 "coordinates": coordinates,
333 },
334 "properties": {},
335 "id": "Yo",
336 "bbox": [13.38272, 52.46385, 13.42786, 52.48445],
337 }
338 )
339 assert "bbox" in f.model_dump()
340 assert "id" in f.model_dump()
341
342 # Exclude
343 assert "bbox" not in f.model_dump(exclude={"bbox"})
344 assert "bbox" not in list(json.loads(f.model_dump_json(exclude={"bbox"})).keys())
345
346 # Include
347 assert ["bbox"] == list(f.model_dump(include={"bbox"}).keys())
348 assert ["bbox"] == list(json.loads(f.model_dump_json(include={"bbox"})).keys())
349
350 feat_ser = json.loads(f.model_dump_json())
351 assert "bbox" in feat_ser
352 assert "id" in feat_ser
353 assert "bbox" not in feat_ser["geometry"]
354
355 f = Feature(
356 **{
357 "type": "Feature",
358 "geometry": {
359 "type": "Polygon",
360 "coordinates": coordinates,
361 },
362 "properties": {},
363 }
364 )
365 # BBOX Should'nt be present if `None`
366 # https://github.com/developmentseed/geojson-pydantic/issues/125
367 assert "bbox" in f.model_dump()
368
369 feat_ser = json.loads(f.model_dump_json())
370 assert "bbox" not in feat_ser
371 assert "id" not in feat_ser
372 assert "bbox" not in feat_ser["geometry"]
373
374 f = Feature(
375 **{
376 "type": "Feature",
377 "geometry": {
378 "type": "Polygon",
379 "coordinates": coordinates,
380 "bbox": [13.38272, 52.46385, 13.42786, 52.48445],
381 },
382 "properties": {},
383 }
384 )
385 feat_ser = json.loads(f.model_dump_json())
386 assert "bbox" not in feat_ser
387 assert "id" not in feat_ser
388 assert "bbox" in feat_ser["geometry"]
389
390
391 def test_feature_collection_serializer():
392 fc = FeatureCollection(
393 **{
394 "type": "FeatureCollection",
395 "features": [
396 {
397 "type": "Feature",
398 "geometry": {
399 "type": "Polygon",
400 "coordinates": coordinates,
401 "bbox": [13.38272, 52.46385, 13.42786, 52.48445],
402 },
403 "properties": {},
404 "bbox": [13.38272, 52.46385, 13.42786, 52.48445],
405 }
406 ],
407 "bbox": [13.38272, 52.46385, 13.42786, 52.48445],
408 }
409 )
410 assert "bbox" in fc.model_dump()
411
412 # Exclude
413 assert "bbox" not in fc.model_dump(exclude={"bbox"})
414 assert "bbox" not in list(json.loads(fc.model_dump_json(exclude={"bbox"})).keys())
415
416 # Include
417 assert ["bbox"] == list(fc.model_dump(include={"bbox"}).keys())
418 assert ["bbox"] == list(json.loads(fc.model_dump_json(include={"bbox"})).keys())
419
420 featcoll_ser = json.loads(fc.model_dump_json())
421 assert "bbox" in featcoll_ser
422 assert "bbox" in featcoll_ser["features"][0]
423 assert "bbox" in featcoll_ser["features"][0]["geometry"]
424
425 fc = FeatureCollection(
426 **{
427 "type": "FeatureCollection",
428 "features": [
429 {
430 "type": "Feature",
431 "geometry": {
432 "type": "Polygon",
433 "coordinates": coordinates,
434 },
435 "properties": {},
436 }
437 ],
438 }
439 )
440 assert "bbox" in fc.model_dump()
441
442 featcoll_ser = json.loads(fc.model_dump_json())
443 assert "bbox" not in featcoll_ser
444 assert "bbox" not in featcoll_ser["features"][0]
445 assert "bbox" not in featcoll_ser["features"][0]["geometry"]