forked from DOI-USGS/dataretrieval-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwaterdata_test.py
More file actions
755 lines (638 loc) · 25.9 KB
/
Copy pathwaterdata_test.py
File metadata and controls
755 lines (638 loc) · 25.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
import datetime
import json
import sys
from unittest import mock
import pandas as pd
import pytest
from pandas import DataFrame
if sys.version_info < (3, 10):
pytest.skip("Skip entire module on Python < 3.10", allow_module_level=True)
from dataretrieval.waterdata import (
get_channel,
get_combined_metadata,
get_continuous,
get_daily,
get_field_measurements,
get_field_measurements_metadata,
get_latest_continuous,
get_latest_daily,
get_monitoring_locations,
get_peaks,
get_reference_table,
get_samples,
get_samples_summary,
get_stats_date_range,
get_stats_por,
get_time_series_metadata,
)
from dataretrieval.waterdata.utils import (
_check_monitoring_location_id,
_check_profiles,
_construct_api_requests,
_normalize_str_iterable,
)
# Most tests in this module call the live USGS Water Data API. After
# PR #273, transient upstream errors (5xx / 429 / connection drops)
# propagate instead of silently truncating, which makes CI susceptible
# to flaking on a brief upstream blip. Auto-retry such failures, but
# only for the narrow set of transient-error trace patterns below —
# library bugs raising other exception types still fail on the first
# try. The marker is attached to every test in the module, but the
# patterns match only traces produced by real network round-trips
# (``_raise_for_non_200`` output, ``requests`` exceptions), so tests
# using ``httpx_mock`` or ``mock.patch`` are no-ops for the rerun.
pytestmark = pytest.mark.flaky(
reruns=2,
reruns_delay=5,
only_rerun=[
r"(?:RateLimited|RuntimeError):\s*(?:429|5\d\d):", # _raise_for_non_200 output
r"Connect(ion)?Error", # requests' ConnectionError + httpx' ConnectError
r"ReadTimeout|ConnectTimeout|Timeout",
],
)
def mock_request(httpx_mock, request_url, file_path):
"""Mock request code"""
with open(file_path) as text:
httpx_mock.add_response(
method="GET",
url=request_url,
text=text.read(),
headers={"mock_header": "value"},
)
def test_mock_get_samples(httpx_mock):
"""Tests USGS Samples query"""
request_url = (
"https://api.waterdata.usgs.gov/samples-data/results/fullphyschem?"
"activityMediaName=Water&activityStartDateLower=2020-01-01"
"&activityStartDateUpper=2024-12-31&monitoringLocationIdentifier=USGS-05406500&mimeType=text%2Fcsv"
)
response_file_path = "tests/data/samples_results.txt"
mock_request(httpx_mock, request_url, response_file_path)
df, md = get_samples(
service="results",
profile="fullphyschem",
activityMediaName="Water",
activityStartDateLower="2020-01-01",
activityStartDateUpper="2024-12-31",
monitoringLocationIdentifier="USGS-05406500",
)
assert type(df) is DataFrame
# 181 source columns + 6 derived <prefix>DateTime columns
assert df.shape == (67, 187)
assert md.url == request_url
assert isinstance(md.query_time, datetime.timedelta)
assert md.header.get("mock_header") == "value"
assert md.comment is None
assert df["Activity_StartDateTime"].notna().any()
def test_mock_get_samples_summary(httpx_mock):
"""Tests USGS Samples summary query"""
request_url = (
"https://api.waterdata.usgs.gov/samples-data/summary/USGS-04183500"
"?mimeType=text%2Fcsv"
)
response_file_path = "tests/data/samples_summary.txt"
mock_request(httpx_mock, request_url, response_file_path)
df, md = get_samples_summary(monitoringLocationIdentifier="USGS-04183500")
assert type(df) is DataFrame
expected_columns = {
"monitoringLocationIdentifier",
"characteristicGroup",
"characteristic",
"characteristicUserSupplied",
"resultCount",
"activityCount",
"firstActivity",
"mostRecentActivity",
}
assert expected_columns.issubset(df.columns)
assert (df["monitoringLocationIdentifier"] == "USGS-04183500").all()
assert md.url == request_url
assert isinstance(md.query_time, datetime.timedelta)
assert md.header.get("mock_header") == "value"
assert md.comment is None
def test_get_samples_summary_rejects_list():
"""The summary endpoint accepts only one site; a list must raise TypeError."""
with pytest.raises(TypeError, match="exactly one monitoring location"):
get_samples_summary(monitoringLocationIdentifier=["USGS-04183500"])
def test_check_profiles():
"""Tests that correct errors are raised for invalid profiles."""
with pytest.raises(ValueError):
_check_profiles(service="foo", profile="bar")
with pytest.raises(ValueError):
_check_profiles(service="results", profile="foo")
def test_construct_api_requests_multivalue_get():
"""Multi-value params use GET with comma-separated values for daily service."""
req = _construct_api_requests(
"daily",
monitoring_location_id=["USGS-05427718", "USGS-05427719"],
parameter_code=["00060", "00065"],
)
assert req.method == "GET"
assert "monitoring_location_id=USGS-05427718%2CUSGS-05427719" in str(req.url)
assert "parameter_code=00060%2C00065" in str(req.url)
def test_construct_api_requests_monitoring_locations_post():
"""monitoring-locations uses POST+CQL2 for multi-value params (API limitation)."""
req = _construct_api_requests(
"monitoring-locations",
hydrologic_unit_code=["010802050102", "010802050103"],
)
assert req.method == "POST"
assert req.headers["Content-Type"] == "application/query-cql-json"
# Body is serialized compactly (tight separators, no whitespace): the
# body counts against the server's ~8 KB request-size cap and the
# chunk planner's byte budget, so pretty-printing would needlessly
# halve how many ids fit per sub-request and double the chunk count.
raw = req.content.decode()
assert "\n" not in raw and ", " not in raw and ": " not in raw
body = json.loads(req.content)
# Top-level shape: AND over a list of per-param predicates.
assert body["op"] == "and"
assert isinstance(body["args"], list) and len(body["args"]) == 1
# The single predicate is an IN over hydrologic_unit_code with both values.
predicate = body["args"][0]
assert predicate["op"] == "in"
assert predicate["args"][0] == {"property": "hydrologic_unit_code"}
assert predicate["args"][1] == ["010802050102", "010802050103"]
def test_construct_api_requests_single_value_stays_get():
"""A length-1 list (or scalar) reaches the URL as a plain value, not a
comma-separated form, so existing single-site callers see no change."""
req = _construct_api_requests(
"daily",
monitoring_location_id="USGS-05427718",
parameter_code="00060",
)
assert req.method == "GET"
assert "monitoring_location_id=USGS-05427718" in str(req.url)
assert "%2C" not in str(req.url) # no comma-encoded multi-value
def test_construct_api_requests_numeric_list_joins_with_str():
"""Numeric-list params (e.g. ``water_year=[2020, 2021]`` on get_peaks)
must reach the URL as a comma-joined string, not crash on ``",".join``
of ints. The generator-of-``str(x)`` exists exactly for this case."""
req = _construct_api_requests(
"peaks",
monitoring_location_id="USGS-05427718",
water_year=[2020, 2021],
)
assert req.method == "GET"
assert "water_year=2020%2C2021" in str(req.url)
def test_construct_api_requests_two_element_date_list_becomes_interval():
"""A two-element date list is interpreted as start/end of an OGC datetime
interval (joined with '/'), NOT as two discrete dates. The OGC `datetime`
parameter does not support "these N specific dates" — that would require
a CQL filter. Verifying so this contract is locked in."""
req = _construct_api_requests(
"daily",
monitoring_location_id="USGS-05427718",
time=["2024-01-01", "2024-01-31"],
)
assert req.method == "GET"
# `/` URL-encodes to %2F. Confirms _format_api_dates ran before the join.
assert "time=2024-01-01%2F2024-01-31" in str(req.url)
def test_samples_results():
"""Test results call for proper columns"""
df, _ = get_samples(
service="results",
profile="narrow",
monitoringLocationIdentifier="USGS-05288705",
activityStartDateLower="2024-10-01",
activityStartDateUpper="2025-04-24",
)
assert all(
col in df.columns
for col in ["Location_Identifier", "Activity_ActivityIdentifier"]
)
assert len(df) > 0
def test_samples_activity():
"""Test activity call for proper columns"""
df, _ = get_samples(
service="activities",
profile="sampact",
monitoringLocationIdentifier="USGS-06719505",
)
assert len(df) > 0
assert len(df.columns) == 97
assert "Location_HUCTwelveDigitCode" in df.columns
def test_samples_locations():
"""Test locations call for proper columns"""
df, _ = get_samples(
service="locations",
profile="site",
stateFips="US:55",
activityStartDateLower="2024-10-01",
activityStartDateUpper="2025-04-24",
usgsPCode="00010",
)
assert all(
col in df.columns for col in ["Location_Identifier", "Location_Latitude"]
)
assert len(df) > 0
def test_samples_projects():
"""Test projects call for proper columns"""
df, _ = get_samples(
service="projects",
profile="project",
stateFips="US:15",
activityStartDateLower="2024-10-01",
activityStartDateUpper="2025-04-24",
)
assert all(col in df.columns for col in ["Org_Identifier", "Project_Identifier"])
assert len(df) > 0
def test_samples_organizations():
"""Test organizations call for proper columns"""
df, _ = get_samples(service="organizations", profile="count", stateFips="US:01")
assert len(df) == 1
assert df.size == 3
def test_get_daily():
df, md = get_daily(
monitoring_location_id="USGS-05427718",
parameter_code="00060",
time="2025-01-01/..",
)
assert "daily_id" in df.columns
assert "geometry" in df.columns
assert df.columns[-1] == "daily_id"
assert df.shape[1] == 12
assert df.parameter_code.unique().tolist() == ["00060"]
assert df.monitoring_location_id.unique().tolist() == ["USGS-05427718"]
assert df["time"].apply(lambda x: isinstance(x, datetime.date)).all()
assert df["time"].iloc[0] < df["time"].iloc[-1]
assert hasattr(md, "url")
assert hasattr(md, "query_time")
assert df["value"].dtype == "float64"
def test_get_daily_properties():
df, _ = get_daily(
monitoring_location_id="USGS-05427718",
parameter_code="00060",
time="2025-01-01/..",
properties=[
"daily_id",
"monitoring_location_id",
"parameter_code",
"time",
"value",
"geometry",
],
)
assert df.columns[0] == "daily_id"
assert df.columns[-1] == "geometry"
assert df.shape[1] == 6
assert df.parameter_code.unique().tolist() == ["00060"]
def test_get_daily_properties_id():
df, _ = get_daily(
monitoring_location_id="USGS-05427718",
parameter_code="00060",
time="2025-01-01/..",
properties=[
"monitoring_location_id",
"id",
"parameter_code",
"time",
"value",
"geometry",
],
)
assert df.columns[1] == "daily_id"
def test_get_daily_no_geometry():
df, _ = get_daily(
monitoring_location_id="USGS-05427718",
parameter_code="00060",
time="2025-01-01/..",
skip_geometry=True,
)
assert "geometry" not in df.columns
assert df.shape[1] == 11
assert isinstance(df, DataFrame)
def test_get_continuous():
df, _ = get_continuous(
monitoring_location_id="USGS-06904500",
parameter_code="00065",
time="2025-01-01/2025-12-31",
)
assert isinstance(df, DataFrame)
assert "geometry" not in df.columns
assert (
df["time"].dtype.name.startswith("datetime64[")
and "UTC" in df["time"].dtype.name
)
assert "continuous_id" in df.columns
def test_get_monitoring_locations():
df, md = get_monitoring_locations(state_name="Connecticut", site_type_code="GW")
assert df.site_type_code.unique().tolist() == ["GW"]
assert hasattr(md, "url")
assert hasattr(md, "query_time")
def test_get_monitoring_locations_hucs():
df, _ = get_monitoring_locations(
hydrologic_unit_code=["010802050102", "010802050103"]
)
assert set(df.hydrologic_unit_code.unique().tolist()) == {
"010802050102",
"010802050103",
}
def test_get_latest_continuous():
df, md = get_latest_continuous(
monitoring_location_id=["USGS-05427718", "USGS-05427719"],
parameter_code=["00060", "00065"],
)
assert df.columns[-1] == "latest_continuous_id"
assert df.shape[0] <= 4
assert df.statistic_id.unique().tolist() == ["00011"]
assert hasattr(md, "url")
assert (
df["time"].dtype.name.startswith("datetime64[")
and "UTC" in df["time"].dtype.name
)
def test_get_latest_daily():
df, md = get_latest_daily(
monitoring_location_id=["USGS-05427718", "USGS-05427719"],
parameter_code=["00060", "00065"],
)
assert "latest_daily_id" in df.columns
assert df.shape[1] == 12
assert hasattr(md, "url")
assert hasattr(md, "query_time")
def test_get_latest_daily_properties_geometry():
df, _md = get_latest_daily(
monitoring_location_id=["USGS-05427718", "USGS-05427719"],
parameter_code=["00060", "00065"],
properties=[
"monitoring_location_id",
"parameter_code",
"time",
"value",
"unit_of_measure",
],
)
assert "geometry" in df.columns
assert df.shape[1] == 6
def test_get_field_measurements():
df, md = get_field_measurements(
monitoring_location_id="USGS-05427718",
unit_of_measure="ft^3/s",
time="2025-01-01/2025-10-01",
skip_geometry=True,
)
assert "field_measurement_id" in df.columns
assert "geometry" not in df.columns
assert df.unit_of_measure.unique().tolist() == ["ft^3/s"]
assert hasattr(md, "url")
assert hasattr(md, "query_time")
def test_get_time_series_metadata():
df, md = get_time_series_metadata(
bbox=[-89.840355, 42.853411, -88.818626, 43.422598],
parameter_code=["00060", "00065", "72019"],
skip_geometry=True,
)
assert set(df["parameter_name"].unique().tolist()) == {
"Gage height",
"Water level, depth LSD",
"Discharge",
}
assert hasattr(md, "url")
assert hasattr(md, "query_time")
def test_get_combined_metadata():
df, md = get_combined_metadata(
monitoring_location_id="USGS-05407000",
skip_geometry=True,
)
assert "monitoring_location_id" in df.columns
assert "parameter_code" in df.columns
assert "data_type" in df.columns
assert "drainage_area" in df.columns
assert (df["monitoring_location_id"] == "USGS-05407000").all()
assert hasattr(md, "url")
assert hasattr(md, "query_time")
def test_get_combined_metadata_multi_site_post():
df, _ = get_combined_metadata(
monitoring_location_id=[
"USGS-07069000",
"USGS-07064000",
"USGS-07068000",
],
parameter_code="00060",
skip_geometry=True,
)
assert set(df["monitoring_location_id"].unique()) == {
"USGS-07069000",
"USGS-07064000",
"USGS-07068000",
}
assert (df["parameter_code"] == "00060").all()
def test_get_field_measurements_metadata():
df, md = get_field_measurements_metadata(
monitoring_location_id="USGS-02238500", skip_geometry=True
)
assert "field_series_id" in df.columns
assert "begin" in df.columns
assert "end" in df.columns
assert (df["monitoring_location_id"] == "USGS-02238500").all()
assert hasattr(md, "url")
assert hasattr(md, "query_time")
def test_get_field_measurements_metadata_multi_site():
df, _ = get_field_measurements_metadata(
monitoring_location_id=[
"USGS-07069000",
"USGS-07064000",
"USGS-07068000",
],
parameter_code="00060",
skip_geometry=True,
)
assert (df["parameter_code"] == "00060").all()
assert set(df["monitoring_location_id"].unique()) == {
"USGS-07069000",
"USGS-07064000",
"USGS-07068000",
}
def test_get_peaks():
df, md = get_peaks(monitoring_location_id="USGS-02238500", skip_geometry=True)
assert "peak_id" in df.columns
assert "value" in df.columns
assert "water_year" in df.columns
assert (df["monitoring_location_id"] == "USGS-02238500").all()
assert set(df["parameter_code"].unique()).issubset({"00060", "00065"})
assert hasattr(md, "url")
assert hasattr(md, "query_time")
def test_get_peaks_water_year_filter():
df, _ = get_peaks(
monitoring_location_id="USGS-02238500",
parameter_code="00060",
water_year=[2020, 2021, 2022],
skip_geometry=True,
)
assert (df["parameter_code"] == "00060").all()
assert set(df["water_year"].unique()).issubset({2020, 2021, 2022})
def test_get_reference_table():
df, md = get_reference_table("agency-codes")
assert "agency_code" in df.columns
assert df.shape[0] > 0
assert hasattr(md, "url")
assert hasattr(md, "query_time")
def test_get_reference_table_with_query():
query = {"id": "AK001,AK008"}
df, md = get_reference_table("agency-codes", query=query)
assert "agency_code" in df.columns
assert df.shape[0] == 2
assert hasattr(md, "url")
assert hasattr(md, "query_time")
def test_get_reference_table_wrong_name():
with pytest.raises(ValueError):
get_reference_table("agency-cod")
def test_get_stats_por():
df, _ = get_stats_por(
monitoring_location_id="USGS-12451000",
parameter_code="00060",
start_date="01-01",
end_date="01-01",
)
assert (
df["computation"]
.isin(["median", "maximum", "minimum", "arithmetic_mean", "percentile"])
.all()
)
assert df["time_of_year"].isin(["01-01", "01"]).all()
assert df.loc[df["computation"] == "minimum", "percentile"].unique().tolist() == [
0.0
]
assert df.loc[df["computation"] == "arithmetic_mean", "percentile"].isnull().all()
def test_get_stats_por_expanded_false():
df, _ = get_stats_por(
monitoring_location_id="USGS-12451000",
parameter_code="00060",
start_date="01-01",
end_date="01-01",
expand_percentiles=False,
computation_type=["minimum", "percentile"],
)
assert df.shape[0] == 4
assert df.shape[1] == 20 # if geopandas installed, 21 columns if not
assert "percentile" not in df.columns
assert "percentiles" in df.columns
assert type(df["percentiles"][2]) is list
assert df.loc[~df["percentiles"].isna(), "value"].isnull().all()
def test_get_stats_date_range():
df, _ = get_stats_date_range(
monitoring_location_id="USGS-12451000",
parameter_code="00060",
start_date="2025-01-01",
end_date="2025-01-01",
computation_type="maximum",
)
assert df.shape[0] == 3
assert df.shape[1] == 20 # if geopandas installed, 21 columns if not
assert "interval_type" in df.columns
assert "percentile" in df.columns
assert df["interval_type"].isin(["month", "calendar_year", "water_year"]).all()
def test_get_channel():
df, _ = get_channel(monitoring_location_id="USGS-02238500")
assert df.shape[0] > 470
assert df.shape[1] == 27 # if geopandas installed, 21 columns if not
assert "channel_measurements_id" in df.columns
class TestCheckMonitoringLocationId:
"""Tests for the AGENCY-ID-specific layer over ``_normalize_str_iterable``.
Generic type/iterable normalization is covered by
``TestNormalizeStrIterable`` below; this suite holds only the format
check (``AGENCY-NUMBER`` shape) and the public-API integration smokes.
Regression tests for GitHub issue #188.
"""
def test_valid_string(self):
"""Happy-path smoke: the wrapper still routes through normalization
for a well-formed AGENCY-ID string."""
assert _check_monitoring_location_id("USGS-01646500") == "USGS-01646500"
def test_integer_raises_type_error(self):
"""An integer ID raises TypeError with a helpful AGENCY-ID hint."""
with pytest.raises(TypeError, match="not int") as exc_info:
_check_monitoring_location_id(5129115)
# The wrapper appends the AGENCY-ID format hint that the generic
# helper alone doesn't carry.
assert "USGS-01646500" in str(exc_info.value)
def test_missing_agency_prefix_raises_value_error(self):
"""A string without the AGENCY- prefix raises ValueError."""
with pytest.raises(ValueError, match="Invalid monitoring_location_id"):
_check_monitoring_location_id("dog")
def test_bare_site_number_raises_value_error(self):
"""A bare site number string (no agency prefix) raises ValueError."""
with pytest.raises(ValueError, match="Invalid monitoring_location_id"):
_check_monitoring_location_id("01646500")
def test_get_daily_integer_id_raises(self):
"""get_daily raises TypeError before making any network call."""
with pytest.raises(TypeError):
get_daily(monitoring_location_id=5129115, parameter_code="00060")
def test_get_daily_malformed_id_raises(self):
"""get_daily raises ValueError for a malformed string ID."""
with pytest.raises(ValueError):
get_daily(monitoring_location_id="dog", parameter_code="00060")
def test_per_item_format_check_in_list(self):
"""The AGENCY-ID format check runs on EVERY element of an
iterable, not just the first. Regression guard against a
future ``_check_id_format`` loop that bails after one valid
item or only checks the head."""
with pytest.raises(ValueError, match="Invalid monitoring_location_id"):
_check_monitoring_location_id(["USGS-01646500", "badformat"])
class TestNormalizeStrIterable:
"""Tests for the generic _normalize_str_iterable helper.
Mirrors TestCheckMonitoringLocationId for the type/iterable contract;
the AGENCY-ID format check is monitoring_location_id-specific and lives
only in the _check_monitoring_location_id wrapper.
"""
def test_none_passes(self):
assert _normalize_str_iterable(None, "p") is None
def test_string_returned_unchanged(self):
assert _normalize_str_iterable("00060", "parameter_code") == "00060"
# Note: no hyphen requirement here — that's monitoring_location_id-specific.
assert _normalize_str_iterable("dog", "parameter_code") == "dog"
def test_list_returned_unchanged(self):
assert _normalize_str_iterable(["00060", "00010"], "p") == ["00060", "00010"]
def test_tuple_normalizes_to_list(self):
result = _normalize_str_iterable(("00060", "00010"), "p")
assert result == ["00060", "00010"]
assert isinstance(result, list)
def test_pandas_series_normalizes_to_list(self):
result = _normalize_str_iterable(pd.Series(["00060", "00010"]), "p")
assert result == ["00060", "00010"]
assert isinstance(result, list)
def test_numpy_array_normalizes_to_list(self):
import numpy as np
result = _normalize_str_iterable(np.array(["00060", "00010"]), "p")
assert result == ["00060", "00010"]
assert isinstance(result, list)
def test_int_raises_type_error(self):
with pytest.raises(TypeError, match="parameter_code must be a string"):
_normalize_str_iterable(5129115, "parameter_code")
def test_int_in_iterable_raises_type_error(self):
with pytest.raises(TypeError, match="parameter_code elements must be strings"):
_normalize_str_iterable(["00060", 5129115], "parameter_code")
def test_dict_raises_type_error(self):
with pytest.raises(TypeError, match="not dict"):
_normalize_str_iterable({"00060": "discharge"}, "parameter_code")
def test_get_daily_parameter_code_as_series(self):
"""Wiring check: pd.Series for ``parameter_code`` arrives at the inner
call as a list.
Regression for the gap PR #229 originally left on every multi-value
parameter other than ``monitoring_location_id``. Pre-fix, the Series
was passed through to ``requests`` which str-serialized it into the
URL (or POST body). Post-fix, ``_normalize_str_iterable`` materializes
it to ``list`` at the function boundary.
"""
with mock.patch("dataretrieval.waterdata.api.get_ogc_data") as fake:
fake.return_value = (pd.DataFrame(), mock.MagicMock(spec=[]))
get_daily(
monitoring_location_id="USGS-05427718",
parameter_code=pd.Series(["00060", "00010"]),
)
# _get_args(locals()) packs kwargs and passes them as `args` to
# get_ogc_data; the first positional argument is the args dict.
args_dict = fake.call_args[0][0]
assert args_dict["parameter_code"] == ["00060", "00010"]
assert isinstance(args_dict["parameter_code"], list)
def test_list_of_ints_rejected_at_boundary(self):
"""List-of-non-strings must be caught client-side, not silently sent.
Regression: an earlier pass through ``_get_args`` had a
``list-of-non-str`` fast-path that bypassed normalization, so
``parameter_code=[60, 65]`` would reach the OGC API and surface as
a confusing JSONDecodeError on the malformed response.
"""
with pytest.raises(TypeError, match="parameter_code elements must be strings"):
get_daily(
monitoring_location_id="USGS-05427718",
parameter_code=[60, 65],
)