Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 21 additions & 16 deletions src/rasterstats/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -175,39 +176,43 @@ 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:
mapping = None
if not exists(obj):
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):
pass
if mapping is None:
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"]
Expand All @@ -226,7 +231,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

Expand Down
40 changes: 38 additions & 2 deletions tests/test_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down Expand Up @@ -535,6 +535,42 @@ 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)) == []


@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."""
Expand Down