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
7 changes: 7 additions & 0 deletions dataretrieval/nwis.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,13 @@ def preformat_peaks_response(df: pd.DataFrame) -> pd.DataFrame:
The formatted data frame

"""
if "peak_dt" not in df.columns:
# An empty peaks response (e.g. "No sites found") parses to a
# column-less frame, so there is no peak_dt to reformat. Return it
# unchanged and let format_response's empty-frame path handle it,
# matching how the other services treat empty results (issue #171).
return df

df["datetime"] = pd.to_datetime(df.pop("peak_dt"), errors="coerce")
df.dropna(subset=["datetime"], inplace=True)
return df
Expand Down
21 changes: 21 additions & 0 deletions tests/nwis_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from dataretrieval.nwis import (
NWIS_Metadata,
_read_rdb,
format_response,
get_discharge_measurements,
get_gwlevels,
get_iv,
Expand All @@ -19,6 +20,7 @@
get_record,
get_water_use,
preformat_peaks_response,
read_rdb,
)

START_DATE = "2018-01-24"
Expand Down Expand Up @@ -303,3 +305,22 @@ def test_no_sites_flows_through_format_response(self):
df = _read_rdb(no_sites_rdb)
assert isinstance(df, pd.DataFrame)
assert df.empty

def test_no_peaks_flows_through_format_response(self):
"""The 'peaks' service takes an extra formatting step
(preformat_peaks_response) before the empty-frame check, so an empty
peaks response has to survive that too. Previously this raised
KeyError('peak_dt'); now it returns an empty frame like the other
services (same empty-result contract as issue #171).
"""
no_peaks_rdb = (
"# //Output-Format: RDB\n"
"# //Response-Status: OK\n"
"# //Response-Message: No sites found matching all criteria\n"
)
# Mirror get_discharge_peaks: raw read_rdb, then the peaks-specific
# format_response (not _read_rdb, which formats with service=None).
df = read_rdb(no_peaks_rdb)
df = format_response(df, service="peaks")
assert isinstance(df, pd.DataFrame)
assert df.empty