From 8d81507a602725fcbe1afca3ac7ddb959e0e7aa5 Mon Sep 17 00:00:00 2001 From: Anton Soloviev Date: Sat, 24 Oct 2026 15:13:25 -0700 Subject: [PATCH 1/2] Accept empty feature collections and vector datasets --- src/rasterstats/io.py | 38 +++++++++++++++++++------------------- tests/test_io.py | 28 ++++++++++++++++++++++++++-- 2 files changed, 45 insertions(+), 21 deletions(-) diff --git a/src/rasterstats/io.py b/src/rasterstats/io.py index a07d698..f495732 100644 --- a/src/rasterstats/io.py +++ b/src/rasterstats/io.py @@ -175,39 +175,39 @@ def parse_feature(obj): def _is_vector_file(path, layer): - """Return True if ``path`` is a readable vector file with at least one feature. + """Return True if ``path`` is a readable vector file. Uses pyogrio.read_info for the probe — no fiona required. - Returns False for invalid paths, non-vector files, and genuinely empty sources. - A feature count of -1 (unknown, e.g. some GeoJSON drivers) is treated as - non-empty (True). + Returns False for invalid paths and non-vector files. + Empty sources and sources with unknown feature counts are readable. """ try: - info = pyogrio.read_info(path, layer=layer) + pyogrio.read_info(path, layer=layer) # important: don't catch DataLayerErrors, let those bubble up directly except pyogrio.errors.DataSourceError: return False - return info["features"] != 0 + return True def read_features(obj, layer=0, engine=None, chunk_size=DEFAULT_CHUNK_SIZE): features_iter = None if isinstance(obj, (str, PathLike)): obj = str(obj) - if _is_vector_file(obj, layer): - features_iter = feature_generator( - obj, layer, engine=engine, chunk_size=chunk_size - ) - else: - try: - mapping = json.loads(obj) - if "type" in mapping and mapping["type"] == "FeatureCollection": - features_iter = mapping["features"] - elif mapping["type"] in geom_types + ["Feature"]: - features_iter = [parse_feature(mapping)] - except (ValueError, JSONDecodeError): + try: + mapping = json.loads(obj) + except (ValueError, JSONDecodeError): + if _is_vector_file(obj, layer): + features_iter = feature_generator( + obj, layer, engine=engine, chunk_size=chunk_size + ) + else: # Single feature-like string features_iter = [parse_feature(obj)] + else: + if "type" in mapping and mapping["type"] == "FeatureCollection": + features_iter = mapping["features"] + elif mapping["type"] in geom_types + ["Feature"]: + features_iter = [parse_feature(mapping)] elif isinstance(obj, Mapping): if "type" in obj and obj["type"] == "FeatureCollection": features_iter = obj["features"] @@ -226,7 +226,7 @@ def read_features(obj, layer=0, engine=None, chunk_size=DEFAULT_CHUNK_SIZE): # Iterable of feature-like objects features_iter = (parse_feature(x) for x in obj) - if not features_iter: + if features_iter is None: raise ValueError("Object is not a recognized source of Features") return features_iter diff --git a/tests/test_io.py b/tests/test_io.py index e2327aa..5544def 100644 --- a/tests/test_io.py +++ b/tests/test_io.py @@ -158,8 +158,8 @@ def test_jsonstr_collection(): def test_jsonstr_collection_without_features(): indata = {"type": "FeatureCollection", "features": []} indata = json.dumps(indata) - with pytest.raises(ValueError): - _test_read_features(indata) + # RFC 7946 section 3.3 permits an empty features array. + assert list(read_features(indata)) == [] def test_invalid_jsonstr(): @@ -535,6 +535,30 @@ def test_geodataframe(): assert list(read_features(df)) +@pytest.mark.parametrize("as_text", [False, True]) +def test_empty_featurecollection(as_text): + collection = {"type": "FeatureCollection", "features": []} + source = json.dumps(collection) if as_text else collection + assert list(read_features(source)) == [] + + +def test_empty_geodataframe(): + gpd = pytest.importorskip("geopandas") + + frame = gpd.read_file(polygons).iloc[:0] + assert list(read_features(frame)) == [] + + +@pytest.mark.parametrize("engine", ["pyogrio", "fiona"]) +def test_empty_vector_file(tmp_path, engine): + if engine == "fiona": + pytest.importorskip("fiona") + path = tmp_path / "empty.geojson" + path.write_text(json.dumps({"type": "FeatureCollection", "features": []})) + assert _is_vector_file(path, 0) + assert list(read_features(path, engine=engine)) == [] + + def test_feature_generator_chunk_size(tmp_path): """Reading with default engine vs alternative chunk sizes, all result in equivalent feature dicts.""" From bb4b397e3cdae048e32378fa45b6612833dfb9ab Mon Sep 17 00:00:00 2001 From: Anton Soloviev Date: Sat, 24 Oct 2026 15:47:26 -0700 Subject: [PATCH 2/2] Keep existing vector filenames ahead of inline JSON parsing --- src/rasterstats/io.py | 11 ++++++++--- tests/test_io.py | 12 ++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/rasterstats/io.py b/src/rasterstats/io.py index f495732..702b36d 100644 --- a/src/rasterstats/io.py +++ b/src/rasterstats/io.py @@ -4,6 +4,7 @@ from collections.abc import Iterable, Mapping from json import JSONDecodeError from os import PathLike +from os.path import exists import numpy as np import pyogrio @@ -193,9 +194,13 @@ def read_features(obj, layer=0, engine=None, chunk_size=DEFAULT_CHUNK_SIZE): features_iter = None if isinstance(obj, (str, PathLike)): obj = str(obj) - try: - mapping = json.loads(obj) - except (ValueError, JSONDecodeError): + mapping = None + if not exists(obj): + try: + mapping = json.loads(obj) + except (ValueError, JSONDecodeError): + pass + if mapping is None: if _is_vector_file(obj, layer): features_iter = feature_generator( obj, layer, engine=engine, chunk_size=chunk_size diff --git a/tests/test_io.py b/tests/test_io.py index 5544def..68ad9ce 100644 --- a/tests/test_io.py +++ b/tests/test_io.py @@ -559,6 +559,18 @@ def test_empty_vector_file(tmp_path, engine): assert list(read_features(path, engine=engine)) == [] +@pytest.mark.parametrize("filename", ["123", "{}"]) +@pytest.mark.parametrize("as_path", [False, True]) +def test_json_like_filename(tmp_path, monkeypatch, filename, as_path): + collection = read_featurecollection(polygons) + monkeypatch.chdir(tmp_path) + path = Path(filename) + path.write_text(json.dumps(collection)) + features = list(read_features(path if as_path else filename)) + assert len(features) == len(target_geoms) + _compare_geomlists([shape(f["geometry"]) for f in features], target_geoms) + + def test_feature_generator_chunk_size(tmp_path): """Reading with default engine vs alternative chunk sizes, all result in equivalent feature dicts."""