envlib-api 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- envlib_api/__init__.py +3 -0
- envlib_api/__main__.py +3 -0
- envlib_api/api/__init__.py +7 -0
- envlib_api/api/app.py +435 -0
- envlib_api/api/compress.py +52 -0
- envlib_api/api/cost.py +107 -0
- envlib_api/api/edr.py +343 -0
- envlib_api/api/encode.py +285 -0
- envlib_api/api/errors.py +23 -0
- envlib_api/api/grid.py +317 -0
- envlib_api/api/params.py +71 -0
- envlib_api/api/read.py +65 -0
- envlib_api/api/resolve.py +191 -0
- envlib_api/api/server.py +35 -0
- envlib_api/api/stations.py +96 -0
- envlib_api/api/timesel.py +97 -0
- envlib_api/cli.py +179 -0
- envlib_api/config.py +158 -0
- envlib_api/healthcheck.py +38 -0
- envlib_api/mirror.py +353 -0
- envlib_api/refresher.py +265 -0
- envlib_api/tests/__init__.py +0 -0
- envlib_api/tests/api_support.py +307 -0
- envlib_api/tests/conftest.py +12 -0
- envlib_api/tests/grid_support.py +217 -0
- envlib_api/tests/schemas/README.md +12 -0
- envlib_api/tests/schemas/coveragejson/coveragejson.json +1794 -0
- envlib_api/tests/schemas/edr/schemas/collections/DataQuery.yaml +38 -0
- envlib_api/tests/schemas/edr/schemas/collections/areaDataQuery.yaml +10 -0
- envlib_api/tests/schemas/edr/schemas/collections/areaLink.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/collections/collection.yaml +137 -0
- envlib_api/tests/schemas/edr/schemas/collections/collections.yaml +26 -0
- envlib_api/tests/schemas/edr/schemas/collections/corridorDataQuery.yaml +29 -0
- envlib_api/tests/schemas/edr/schemas/collections/corridorLink.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/collections/crsObject.yaml +15 -0
- envlib_api/tests/schemas/edr/schemas/collections/cubeDataQuery.yaml +20 -0
- envlib_api/tests/schemas/edr/schemas/collections/cubeLink.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/collections/extent.yaml +311 -0
- envlib_api/tests/schemas/edr/schemas/collections/instancesDataQuery.yaml +21 -0
- envlib_api/tests/schemas/edr/schemas/collections/instancesLink.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/collections/itemsDataQuery.yaml +21 -0
- envlib_api/tests/schemas/edr/schemas/collections/itemsLink.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/collections/locationsDataQuery.yaml +10 -0
- envlib_api/tests/schemas/edr/schemas/collections/locationsLink.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/collections/observedPropertyCollection.yaml +51 -0
- envlib_api/tests/schemas/edr/schemas/collections/parameterNames.yaml +70 -0
- envlib_api/tests/schemas/edr/schemas/collections/positionDataQuery.yaml +12 -0
- envlib_api/tests/schemas/edr/schemas/collections/positionLink.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/collections/radiusDataQuery.yaml +18 -0
- envlib_api/tests/schemas/edr/schemas/collections/radiusLink.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/collections/trajectoryDataQuery.yaml +10 -0
- envlib_api/tests/schemas/edr/schemas/collections/trajectoryLink.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/collections/units.yaml +42 -0
- envlib_api/tests/schemas/edr/schemas/core/confClasses.yaml +8 -0
- envlib_api/tests/schemas/edr/schemas/core/exception.yaml +8 -0
- envlib_api/tests/schemas/edr/schemas/core/landingPage.yaml +76 -0
- envlib_api/tests/schemas/edr/schemas/core/link.yaml +31 -0
- envlib_api/tests/schemas/edr/schemas/covjson/anyAxis.yaml +11 -0
- envlib_api/tests/schemas/edr/schemas/covjson/coverage.yaml +14 -0
- envlib_api/tests/schemas/edr/schemas/covjson/coverageBase.yaml +68 -0
- envlib_api/tests/schemas/edr/schemas/covjson/coverageCollection.yaml +58 -0
- envlib_api/tests/schemas/edr/schemas/covjson/coverageJSON.yaml +46 -0
- envlib_api/tests/schemas/edr/schemas/covjson/covjsonI18n.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/covjson/covjsonObservedProperty.yaml +29 -0
- envlib_api/tests/schemas/edr/schemas/covjson/covjsonParameter.yaml +32 -0
- envlib_api/tests/schemas/edr/schemas/covjson/covjsonParameterGroup.yaml +31 -0
- envlib_api/tests/schemas/edr/schemas/covjson/covjsonUnit.yaml +31 -0
- envlib_api/tests/schemas/edr/schemas/covjson/domain.yaml +7 -0
- envlib_api/tests/schemas/edr/schemas/covjson/domainBase.yaml +337 -0
- envlib_api/tests/schemas/edr/schemas/covjson/ndArray.yaml +88 -0
- envlib_api/tests/schemas/edr/schemas/covjson/numericAxis.yaml +11 -0
- envlib_api/tests/schemas/edr/schemas/covjson/numericRegularlySpacedAxis.yaml +17 -0
- envlib_api/tests/schemas/edr/schemas/covjson/numericSingleValueAxis.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/covjson/numericValuesAxis.yaml +14 -0
- envlib_api/tests/schemas/edr/schemas/covjson/polygonValuesAxis.yaml +29 -0
- envlib_api/tests/schemas/edr/schemas/covjson/primitiveValuesAxis.yaml +22 -0
- envlib_api/tests/schemas/edr/schemas/covjson/referenceSystem.yaml +48 -0
- envlib_api/tests/schemas/edr/schemas/covjson/referenceSystemConnection.yaml +16 -0
- envlib_api/tests/schemas/edr/schemas/covjson/stringSingleValueAxis.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/covjson/stringValuesAxis.yaml +14 -0
- envlib_api/tests/schemas/edr/schemas/covjson/targetConcept.yaml +13 -0
- envlib_api/tests/schemas/edr/schemas/covjson/tiledNdArray.yaml +50 -0
- envlib_api/tests/schemas/edr/schemas/covjson/tupleValuesAxis.yaml +24 -0
- envlib_api/tests/schemas/edr/schemas/covjson/valuesAxis.yaml +27 -0
- envlib_api/tests/schemas/edr/schemas/covjson/valuesAxisBase.yaml +24 -0
- envlib_api/tests/schemas/edr/schemas/edr-geojson/edrFeatureCollectionGeoJSON.yaml +32 -0
- envlib_api/tests/schemas/edr/schemas/edr-geojson/edrProperties.yaml +49 -0
- envlib_api/tests/schemas/edr/schemas/edr-geojson/observedProperty.yaml +26 -0
- envlib_api/tests/schemas/edr/schemas/edr-geojson/parameter.yaml +28 -0
- envlib_api/tests/schemas/edr/schemas/edr-geojson/unit.yaml +24 -0
- envlib_api/tests/schemas/edr/schemas/geojson/featureGeoJSON.yaml +29 -0
- envlib_api/tests/schemas/edr/schemas/geojson/geometrycollectionGeoJSON.yaml +19 -0
- envlib_api/tests/schemas/edr/schemas/geojson/linestringGeoJSON.yaml +23 -0
- envlib_api/tests/schemas/edr/schemas/geojson/multilinestringGeoJSON.yaml +19 -0
- envlib_api/tests/schemas/edr/schemas/geojson/multipointGeoJSON.yaml +16 -0
- envlib_api/tests/schemas/edr/schemas/geojson/multipolygonGeoJSON.yaml +21 -0
- envlib_api/tests/schemas/edr/schemas/geojson/pointGeoJSON.yaml +14 -0
- envlib_api/tests/schemas/edr/schemas/geojson/polygonGeoJSON.yaml +19 -0
- envlib_api/tests/schemas/edr/schemas/i18n.yaml +4 -0
- envlib_api/tests/schemas/edr/schemas/numberMatched.yaml +7 -0
- envlib_api/tests/schemas/edr/schemas/numberReturned.yaml +12 -0
- envlib_api/tests/schemas/edr/schemas/parameterGroup.yaml +30 -0
- envlib_api/tests/schemas/edr/schemas/queries/instances.yaml +26 -0
- envlib_api/tests/support.py +320 -0
- envlib_api/tests/test_alerting_and_guards.py +325 -0
- envlib_api/tests/test_api.py +808 -0
- envlib_api/tests/test_api_review.py +428 -0
- envlib_api/tests/test_grid.py +1075 -0
- envlib_api/tests/test_ops.py +358 -0
- envlib_api/tests/test_refresher.py +354 -0
- envlib_api/tests/test_schemas.py +91 -0
- envlib_api-0.3.0.dist-info/METADATA +408 -0
- envlib_api-0.3.0.dist-info/RECORD +116 -0
- envlib_api-0.3.0.dist-info/WHEEL +4 -0
- envlib_api-0.3.0.dist-info/entry_points.txt +3 -0
- envlib_api-0.3.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Tests added from code review `edr-api-code-3`: each guards a finding or kills a surviving mutant
|
|
3
|
+
(the synthesis is planning/edr-api-code-3-review-synthesis.md).
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import csv
|
|
7
|
+
import io
|
|
8
|
+
import json
|
|
9
|
+
import logging
|
|
10
|
+
import math
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
import textwrap
|
|
14
|
+
import time
|
|
15
|
+
|
|
16
|
+
import cfdb
|
|
17
|
+
import numpy as np
|
|
18
|
+
import pymongo
|
|
19
|
+
import pytest
|
|
20
|
+
import urllib3
|
|
21
|
+
from ebooklet.mongo import CHUNKS, DATASETS, MongoStore
|
|
22
|
+
from fastapi.testclient import TestClient
|
|
23
|
+
|
|
24
|
+
from envlib_api.api import app as app_mod
|
|
25
|
+
from envlib_api.api import edr, read, timesel
|
|
26
|
+
from envlib_api.api.app import create_app
|
|
27
|
+
from envlib_api.tests.api_support import POLY_EDGE, STATIONS, api_config, refresh_into
|
|
28
|
+
from envlib_api.tests.test_api import IDENTITY, _sf_url, cid, client, station_id
|
|
29
|
+
|
|
30
|
+
# ── the zstd crash (finding 1) ─────────────────────────────────────────────────────────────────
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def test_concurrent_zstd_compression_neither_crashes_nor_corrupts():
|
|
34
|
+
"""
|
|
35
|
+
Many threads compressing at once through the real compress.encode. A compressor shared between
|
|
36
|
+
threads segfaulted here, so it runs in a subprocess: a crash is a failed return code, not a dead
|
|
37
|
+
test run.
|
|
38
|
+
"""
|
|
39
|
+
code = textwrap.dedent("""
|
|
40
|
+
import threading, numpy as np, zstandard
|
|
41
|
+
from envlib_api.api import compress
|
|
42
|
+
rng = np.random.default_rng(0)
|
|
43
|
+
bodies = [rng.integers(0, 10, 2_000_000, dtype=np.uint8).tobytes() for _ in range(8)]
|
|
44
|
+
bad = []
|
|
45
|
+
def work(i):
|
|
46
|
+
for _ in range(12):
|
|
47
|
+
out = compress.encode(bodies[i], 'zstd')
|
|
48
|
+
if zstandard.ZstdDecompressor().decompress(out, max_output_size=len(bodies[i])) != bodies[i]:
|
|
49
|
+
bad.append(i)
|
|
50
|
+
ts = [threading.Thread(target=work, args=(i,)) for i in range(8)]
|
|
51
|
+
[t.start() for t in ts]; [t.join() for t in ts]
|
|
52
|
+
print('bad', len(bad))
|
|
53
|
+
""")
|
|
54
|
+
r = subprocess.run([sys.executable, '-c', code], capture_output=True, text=True, timeout=120)
|
|
55
|
+
assert r.returncode == 0, f'exit {r.returncode}: {r.stderr[-500:]}'
|
|
56
|
+
assert r.stdout.strip() == 'bad 0'
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
# ── client-triggered 500s and the error shape (finding 2) ──────────────────────────────────────
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@pytest.mark.parametrize(
|
|
63
|
+
'path,params',
|
|
64
|
+
[
|
|
65
|
+
('locations/{A}', {'datetime': '0001-01-01T00:00:00+14:00'}),
|
|
66
|
+
('locations/{A}', {'datetime': '9999-12-31T23:00:00-14:00'}),
|
|
67
|
+
('area', {'coords': 'CURVEPOLYGON(CIRCULARSTRING(0 0,1 1,2 0,1 -1,0 0))'}),
|
|
68
|
+
('radius', {'coords': 'POINT(172 100)', 'within': '5', 'within-units': 'km'}),
|
|
69
|
+
('radius', {'coords': 'POINT(nan nan)', 'within': '5', 'within-units': 'km'}),
|
|
70
|
+
],
|
|
71
|
+
)
|
|
72
|
+
def test_hostile_inputs_answer_400_in_the_ogc_shape(mirror, path, params):
|
|
73
|
+
url = f'/collections/{cid(mirror, "sf")}/' + path.format(A=station_id(mirror, 'sf', 'A'))
|
|
74
|
+
r = client(mirror).get(url, params=params)
|
|
75
|
+
assert r.status_code == 400 and r.headers['content-type'] == 'application/json', (r.status_code, r.text)
|
|
76
|
+
assert set(r.json()) >= {'code', 'description'}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def test_an_unexpected_error_is_a_json_500(mirror, monkeypatch):
|
|
80
|
+
def boom(*a, **kw):
|
|
81
|
+
raise RuntimeError('planted')
|
|
82
|
+
|
|
83
|
+
monkeypatch.setattr(app_mod.encode, 'coverage_json', boom)
|
|
84
|
+
c = TestClient(create_app(api_config(), db=mirror.adb), headers=IDENTITY, raise_server_exceptions=False)
|
|
85
|
+
r = c.get(_sf_url(mirror), params={'datetime': '2020-01-01T00:00Z'})
|
|
86
|
+
assert r.status_code == 500 and r.json()['code'] == 'InternalError'
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def test_framework_errors_use_the_ogc_shape(mirror):
|
|
90
|
+
c = client(mirror)
|
|
91
|
+
r404 = c.get('/no/such/route')
|
|
92
|
+
r405 = c.post('/collections')
|
|
93
|
+
assert r404.status_code == 404 and r404.json()['code'] == 'NotFound'
|
|
94
|
+
assert r405.status_code == 405 and r405.json()['code'] == 'MethodNotAllowed'
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@pytest.mark.parametrize('route', ['/', '/conformance', '/collections', '/collections/{sf}'])
|
|
98
|
+
def test_metadata_routes_validate_f(mirror, route):
|
|
99
|
+
c = client(mirror)
|
|
100
|
+
url = route.format(sf=cid(mirror, 'sf'))
|
|
101
|
+
assert c.get(url, params={'f': 'html'}).status_code == 400
|
|
102
|
+
assert c.get(url, params={'f': 'json'}).status_code == 200
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
# ── MongoDB trouble (findings 3, 5, 8) ─────────────────────────────────────────────────────────
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def test_a_dead_mongodb_answers_503_on_every_route():
|
|
109
|
+
dead = pymongo.MongoClient('mongodb://127.0.0.1:1', serverSelectionTimeoutMS=100, connectTimeoutMS=100)['x']
|
|
110
|
+
c = TestClient(create_app(api_config(), db=dead), headers=IDENTITY)
|
|
111
|
+
for path in ('/collections', '/collections/abc', '/collections/abc/locations'):
|
|
112
|
+
r = c.get(path)
|
|
113
|
+
assert r.status_code == 503 and r.headers['retry-after'] == '60', (path, r.status_code, r.text)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def test_the_api_mongodb_client_has_a_short_selection_timeout():
|
|
117
|
+
db = app_mod.connect(api_config(mongo_uri='mongodb://127.0.0.1:1'))
|
|
118
|
+
assert db.client.options.server_selection_timeout == app_mod.MONGO_TIMEOUT_MS / 1000 <= 5
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def test_a_mongodb_error_inside_the_missing_handler_answers_503(fresh_mirror, monkeypatch):
|
|
122
|
+
m = fresh_mirror
|
|
123
|
+
m.admin[DATASETS].update_one({'_id': m.world.dvid['sf']}, {'$set': {'missing': True}})
|
|
124
|
+
real = app_mod.resolve.latest
|
|
125
|
+
calls = []
|
|
126
|
+
|
|
127
|
+
def flaky(db, dataset_id):
|
|
128
|
+
calls.append(1)
|
|
129
|
+
if len(calls) > 1: # the re-resolve inside the RemoteMissingError handler
|
|
130
|
+
raise pymongo.errors.AutoReconnect('planted')
|
|
131
|
+
return real(db, dataset_id)
|
|
132
|
+
|
|
133
|
+
monkeypatch.setattr(app_mod.resolve, 'latest', flaky)
|
|
134
|
+
r = client(m).get(_sf_url(m))
|
|
135
|
+
assert r.status_code == 503 and len(calls) == 2
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def test_a_mongodb_error_mid_read_answers_503(fresh_mirror, monkeypatch):
|
|
139
|
+
def fail(self, keys):
|
|
140
|
+
raise pymongo.errors.AutoReconnect('planted')
|
|
141
|
+
|
|
142
|
+
monkeypatch.setattr(MongoStore, '_read_entries', fail)
|
|
143
|
+
assert client(fresh_mirror).get(_sf_url(fresh_mirror), params={'datetime': '2020-01-01T00:00Z'}).status_code == 503
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def test_a_b2_failure_answers_502(fresh_mirror, monkeypatch):
|
|
147
|
+
def fail(self, entries):
|
|
148
|
+
raise urllib3.exceptions.HTTPError('planted')
|
|
149
|
+
|
|
150
|
+
monkeypatch.setattr(MongoStore, '_fetch', fail)
|
|
151
|
+
r = client(fresh_mirror).get(_sf_url(fresh_mirror), params={'datetime': '2020-01-01T00:00Z'})
|
|
152
|
+
assert r.status_code == 502 and r.json()['code'] == 'UpstreamError'
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def test_the_deadline_is_checked_after_the_batched_fetch(fresh_mirror, monkeypatch):
|
|
156
|
+
"""The batched fetch (the first load_items) overruns a 0.2 s deadline; the check after it fires."""
|
|
157
|
+
real = MongoStore.load_items
|
|
158
|
+
calls = []
|
|
159
|
+
|
|
160
|
+
def slow_first(store, keys=None):
|
|
161
|
+
calls.append(1)
|
|
162
|
+
if len(calls) == 1:
|
|
163
|
+
time.sleep(0.3)
|
|
164
|
+
return real(store, keys)
|
|
165
|
+
|
|
166
|
+
monkeypatch.setattr(MongoStore, 'load_items', slow_first)
|
|
167
|
+
r = client(fresh_mirror, request_deadline_seconds=0.2).get(
|
|
168
|
+
_sf_url(fresh_mirror), params={'datetime': '2020-01-01T00:00Z'}
|
|
169
|
+
)
|
|
170
|
+
assert r.status_code == 503 and r.json()['code'] == 'Deadline'
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def test_the_deadline_503_carries_retry_after(fresh_mirror):
|
|
174
|
+
r = client(fresh_mirror, request_deadline_seconds=0).get(_sf_url(fresh_mirror))
|
|
175
|
+
assert r.status_code == 503 and r.headers['retry-after'] == '60'
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
# ── one bad catalogue entry (finding 4), unserved types, conventions ───────────────────────────
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def test_an_unparsable_created_at_neither_fails_the_listing_nor_its_collection(fresh_mirror, caplog):
|
|
182
|
+
m = fresh_mirror
|
|
183
|
+
m.admin['catalogue'].update_one({'_id': m.world.dvid['sf']}, {'$set': {'user_meta.created_at': 'not a date'}})
|
|
184
|
+
c = client(m)
|
|
185
|
+
with caplog.at_level('WARNING'):
|
|
186
|
+
ids = [col['id'] for col in c.get('/collections').json()['collections']]
|
|
187
|
+
assert sorted(ids) == sorted({cid(m, n) for n in ('sf', 'gh', 'pv1')})
|
|
188
|
+
assert c.get(f'/collections/{cid(m, "sf")}').status_code == 200
|
|
189
|
+
assert any('unparsable user_meta.created_at' in rec.getMessage() for rec in caplog.records)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def test_a_dataset_type_that_is_not_served_is_neither_listed_nor_answered(fresh_mirror):
|
|
193
|
+
"""A forecast grid (plan 4 serves `ts_ortho` and `grid` only)."""
|
|
194
|
+
m = fresh_mirror
|
|
195
|
+
forecast = 'ab' * 12
|
|
196
|
+
m.admin['catalogue'].insert_one(
|
|
197
|
+
{
|
|
198
|
+
'_id': forecast,
|
|
199
|
+
'dataset_id': 'cd' * 12,
|
|
200
|
+
'ts': 1,
|
|
201
|
+
'user_meta': {
|
|
202
|
+
'dataset_type': 'grid_forecast',
|
|
203
|
+
'dataset_id': 'cd' * 12,
|
|
204
|
+
'created_at': '2026-01-01T00:00:00Z',
|
|
205
|
+
},
|
|
206
|
+
'remote_conn': {'db_url': m.world.conn('sf').db_url},
|
|
207
|
+
'type': None,
|
|
208
|
+
}
|
|
209
|
+
)
|
|
210
|
+
c = client(m)
|
|
211
|
+
assert 'cd' * 12 not in [col['id'] for col in c.get('/collections').json()['collections']]
|
|
212
|
+
assert c.get(f'/collections/{"cd" * 12}').status_code == 404
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def test_a_collection_off_the_station_conventions_answers_404_not_served(mirror, monkeypatch):
|
|
216
|
+
monkeypatch.setattr(edr, 'STATION_VARS', (*edr.STATION_VARS, 'station_altitude'))
|
|
217
|
+
c = client(mirror)
|
|
218
|
+
r = c.get(f'/collections/{cid(mirror, "sf")}')
|
|
219
|
+
assert r.status_code == 404 and r.json()['code'] == 'NotServed'
|
|
220
|
+
assert c.get('/collections').json()['collections'] == []
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
# ── the reader and the 413 come from the datasets document (kills R2, R3) ──────────────────────
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def test_the_reader_and_the_413_use_the_datasets_document_not_the_catalogue(fresh_mirror):
|
|
227
|
+
"""
|
|
228
|
+
The mirror lists a catalogue document only after refreshing its member, so during a re-point the
|
|
229
|
+
two documents' db_urls differ. Planted here: the catalogue document names a remote that does not
|
|
230
|
+
exist. A cold read must still come from the datasets document's remote.
|
|
231
|
+
"""
|
|
232
|
+
m = fresh_mirror
|
|
233
|
+
dvid = m.world.dvid['sf']
|
|
234
|
+
m.admin['catalogue'].update_one({'_id': dvid}, {'$set': {'remote_conn.db_url': 'http://127.0.0.1:1/nowhere/sf'}})
|
|
235
|
+
real_url = m.admin[DATASETS].find_one({'_id': dvid})['db_url']
|
|
236
|
+
c = client(m)
|
|
237
|
+
r = c.get(_sf_url(m), params={'datetime': '2020-01-01T00:00Z/2020-01-02T00:00Z'})
|
|
238
|
+
assert r.status_code == 200, r.text
|
|
239
|
+
big = client(m, max_values=1).get(_sf_url(m))
|
|
240
|
+
assert big.status_code == 413 and big.json()['db_url'] == real_url
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def test_the_etag_is_the_dataset_version_and_its_applied_commit(mirror):
|
|
244
|
+
dvid = mirror.world.dvid['sf']
|
|
245
|
+
applied = mirror.admin[DATASETS].find_one({'_id': dvid})['applied']
|
|
246
|
+
want = f'"{dvid}-{applied["uuid"]}-{applied["ts"]}"'
|
|
247
|
+
c = client(mirror)
|
|
248
|
+
assert c.get(f'/collections/{cid(mirror, "sf")}').headers['etag'] == want
|
|
249
|
+
assert c.get(f'/collections/{cid(mirror, "sf")}/locations').headers['etag'] == want
|
|
250
|
+
assert c.get(_sf_url(mirror), params={'datetime': '2020-01-01T00:00Z'}).headers['etag'] == want
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
# ── caps and parameters ────────────────────────────────────────────────────────────────────────
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def test_the_values_cap_counts_every_parameter(mirror):
|
|
257
|
+
"""gh has gage_height and quality_code: D alone over 10 steps is 20 values."""
|
|
258
|
+
url = f'/collections/{cid(mirror, "gh")}/area'
|
|
259
|
+
params = {'coords': POLY_EDGE, 'datetime': '2020-01-01T00:00Z/2020-01-01T09:00Z'}
|
|
260
|
+
assert client(mirror, max_values=20).get(url, params=params).status_code == 200
|
|
261
|
+
r = client(mirror, max_values=19).get(url, params=params)
|
|
262
|
+
assert r.status_code == 413 and r.json()['limits'][0]['requested'] == 20
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def test_parameters_come_in_the_order_requested(mirror):
|
|
266
|
+
url = f'/collections/{cid(mirror, "gh")}/locations/{station_id(mirror, "gh", "A")}'
|
|
267
|
+
for order in (['quality_code', 'gage_height'], ['gage_height', 'quality_code']):
|
|
268
|
+
r = client(mirror).get(url, params={'datetime': '2020-01-01T00:00Z', 'parameter-name': ','.join(order)})
|
|
269
|
+
assert list(r.json()['parameters']) == order and list(r.json()['ranges']) == order
|
|
270
|
+
csvr = client(mirror).get(
|
|
271
|
+
url, params={'datetime': '2020-01-01T00:00Z', 'parameter-name': ','.join(order), 'f': 'CSV'}
|
|
272
|
+
)
|
|
273
|
+
assert csvr.text.split('\n')[0].split(',')[-2:] == order
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def test_an_empty_area_reads_no_time_chunk(mirror, monkeypatch):
|
|
277
|
+
loaded = []
|
|
278
|
+
real = MongoStore._fill
|
|
279
|
+
|
|
280
|
+
def spy(store, keys):
|
|
281
|
+
loaded.extend(keys)
|
|
282
|
+
return real(store, keys)
|
|
283
|
+
|
|
284
|
+
monkeypatch.setattr(MongoStore, '_fill', spy)
|
|
285
|
+
r = client(mirror).get(f'/collections/{cid(mirror, "sf")}/area', params={'coords': 'POLYGON((0 0,1 0,1 1,0 0))'})
|
|
286
|
+
assert r.status_code == 204
|
|
287
|
+
assert not [k for k in loaded if k.startswith('time!')], loaded
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
# ── the CSV quotes hostile names ───────────────────────────────────────────────────────────────
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def test_csv_quotes_a_station_name_with_a_comma_a_quote_and_a_newline(mirror):
|
|
294
|
+
url = f'/collections/{cid(mirror, "sf")}/locations/{station_id(mirror, "sf", "D")}'
|
|
295
|
+
rows = list(
|
|
296
|
+
csv.reader(
|
|
297
|
+
io.StringIO(
|
|
298
|
+
client(mirror).get(url, params={'datetime': '2020-01-01T00:00Z/2020-01-01T01:00Z', 'f': 'CSV'}).text
|
|
299
|
+
)
|
|
300
|
+
)
|
|
301
|
+
)
|
|
302
|
+
assert [row[2] for row in rows[1:]] == [STATIONS['D']['name']] * 2
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
# ── time selection before 1970 (kills the truncating floor) ────────────────────────────────────
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
@pytest.mark.parametrize('unit,step', [('h', 1), ('m', 15), ('D', 1)])
|
|
309
|
+
def test_off_step_bounds_resolve_by_label_containment_across_the_epoch(unit, step):
|
|
310
|
+
rng = np.random.default_rng(3)
|
|
311
|
+
start = np.datetime64('1969-12-20T00:00', 'm').astype(f'datetime64[{unit}]')
|
|
312
|
+
axis = np.arange(start, start + np.timedelta64(step, unit) * 400, np.timedelta64(step, unit))
|
|
313
|
+
t_us = axis.astype('datetime64[us]').astype('int64')
|
|
314
|
+
span = int(t_us[-1] - t_us[0])
|
|
315
|
+
for _ in range(200):
|
|
316
|
+
lo, hi = sorted(int(t_us[0] - span // 20 + rng.integers(0, span + span // 10)) for _ in range(2))
|
|
317
|
+
lo_dt, hi_dt = np.datetime64(lo, 'us'), np.datetime64(hi, 'us')
|
|
318
|
+
a, b = timesel.resolve(('interval', lo_dt, hi_dt), axis)
|
|
319
|
+
want = np.nonzero((t_us >= lo) & (t_us <= hi))[0]
|
|
320
|
+
got = np.arange(a, b)
|
|
321
|
+
assert type(a) is int and type(b) is int
|
|
322
|
+
assert np.array_equal(got, want), (unit, str(lo_dt), str(hi_dt), a, b, want[:3])
|
|
323
|
+
k = int(rng.integers(0, len(axis)))
|
|
324
|
+
assert timesel.resolve(('instant', axis[k].astype('datetime64[us]')), axis) == (k, k + 1)
|
|
325
|
+
off = axis[k].astype('datetime64[us]') + np.timedelta64(7, 'us')
|
|
326
|
+
a, b = timesel.resolve(('instant', off), axis)
|
|
327
|
+
assert a == b
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
# ── radius by an independent geodesic (kills a spherical distance) ─────────────────────────────
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _vincenty_m(lon1, lat1, lon2, lat2):
|
|
334
|
+
"""Vincenty's inverse on WGS84, written here so the oracle shares no code with pyproj."""
|
|
335
|
+
a, f = 6378137.0, 1 / 298.257223563
|
|
336
|
+
b = (1 - f) * a
|
|
337
|
+
L = math.radians(lon2 - lon1)
|
|
338
|
+
U1, U2 = math.atan((1 - f) * math.tan(math.radians(lat1))), math.atan((1 - f) * math.tan(math.radians(lat2)))
|
|
339
|
+
sinU1, cosU1, sinU2, cosU2 = math.sin(U1), math.cos(U1), math.sin(U2), math.cos(U2)
|
|
340
|
+
lam = L
|
|
341
|
+
for _ in range(200):
|
|
342
|
+
sinl, cosl = math.sin(lam), math.cos(lam)
|
|
343
|
+
sins = math.hypot(cosU2 * sinl, cosU1 * sinU2 - sinU1 * cosU2 * cosl)
|
|
344
|
+
coss = sinU1 * sinU2 + cosU1 * cosU2 * cosl
|
|
345
|
+
sig = math.atan2(sins, coss)
|
|
346
|
+
sina = cosU1 * cosU2 * sinl / sins
|
|
347
|
+
cos2a = 1 - sina**2
|
|
348
|
+
cos2sm = coss - 2 * sinU1 * sinU2 / cos2a
|
|
349
|
+
C = f / 16 * cos2a * (4 + f * (4 - 3 * cos2a))
|
|
350
|
+
prev, lam = lam, L + (1 - C) * f * sina * (sig + C * sins * (cos2sm + C * coss * (-1 + 2 * cos2sm**2)))
|
|
351
|
+
if abs(lam - prev) < 1e-12:
|
|
352
|
+
break
|
|
353
|
+
u2 = cos2a * (a**2 - b**2) / b**2
|
|
354
|
+
A = 1 + u2 / 16384 * (4096 + u2 * (-768 + u2 * (320 - 175 * u2)))
|
|
355
|
+
B = u2 / 1024 * (256 + u2 * (-128 + u2 * (74 - 47 * u2)))
|
|
356
|
+
ds = (
|
|
357
|
+
B
|
|
358
|
+
* sins
|
|
359
|
+
* (cos2sm + B / 4 * (coss * (-1 + 2 * cos2sm**2) - B / 6 * cos2sm * (-3 + 4 * sins**2) * (-3 + 4 * cos2sm**2)))
|
|
360
|
+
)
|
|
361
|
+
return b * A * (sig - ds)
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def _sphere_m(lon1, lat1, lon2, lat2, r=6371008.8):
|
|
365
|
+
p1, p2, dl = math.radians(lat1), math.radians(lat2), math.radians(lon2 - lon1)
|
|
366
|
+
return (
|
|
367
|
+
2 * r * math.asin(math.sqrt(math.sin((p2 - p1) / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2))
|
|
368
|
+
)
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def test_radius_uses_the_wgs84_geodesic(mirror):
|
|
372
|
+
"""A radius set between the sphere's and the ellipsoid's distance to one station decides which is used."""
|
|
373
|
+
centre = (172.5, -43.5)
|
|
374
|
+
ref = 'E'
|
|
375
|
+
d_ell = _vincenty_m(*centre, STATIONS[ref]['lon'], STATIONS[ref]['lat'])
|
|
376
|
+
d_sph = _sphere_m(*centre, STATIONS[ref]['lon'], STATIONS[ref]['lat'])
|
|
377
|
+
assert abs(d_ell - d_sph) > 50, 'the fixture cannot separate the two distances'
|
|
378
|
+
within = (d_ell + d_sph) / 2
|
|
379
|
+
r = client(mirror).get(
|
|
380
|
+
f'/collections/{cid(mirror, "sf")}/radius',
|
|
381
|
+
params={
|
|
382
|
+
'coords': f'POINT({centre[0]} {centre[1]})',
|
|
383
|
+
'within': str(within),
|
|
384
|
+
'within-units': 'm',
|
|
385
|
+
'datetime': '2020-01-01T00:00Z',
|
|
386
|
+
},
|
|
387
|
+
)
|
|
388
|
+
ids = [cov['id'] for cov in r.json()['coverages']] if r.status_code == 200 else []
|
|
389
|
+
assert (station_id(mirror, 'sf', ref) in ids) == (d_ell <= within)
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
# ── a refused cache insert is reported at ERROR (finding 6) ────────────────────────────────────
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def test_a_cache_that_refuses_inserts_is_reported_at_error(fresh_mirror, monkeypatch, caplog):
|
|
396
|
+
m = fresh_mirror
|
|
397
|
+
m.admin.command('collMod', CHUNKS, validator={'$jsonSchema': {'required': ['zzz']}})
|
|
398
|
+
monkeypatch.setattr(app_mod.CACHE_ALARM, 'fired', False)
|
|
399
|
+
with caplog.at_level('WARNING'):
|
|
400
|
+
r = client(m).get(_sf_url(m), params={'datetime': '2020-01-01T00:00Z/2020-01-02T00:00Z'})
|
|
401
|
+
assert r.status_code == 200
|
|
402
|
+
errors = [rec.getMessage() for rec in caplog.records if rec.levelno == logging.ERROR]
|
|
403
|
+
assert any('refused an insert' in e for e in errors), errors
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
# ── a real commit applied during a request (the retry re-reads the data) ───────────────────────
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def test_a_real_commit_applied_mid_request_is_answered_from_the_new_commit(small_mirror, monkeypatch):
|
|
410
|
+
m = small_mirror
|
|
411
|
+
w = m.world
|
|
412
|
+
real = read.read_values
|
|
413
|
+
calls = []
|
|
414
|
+
|
|
415
|
+
def push_then_read(attempt, *args, **kwargs):
|
|
416
|
+
calls.append(1)
|
|
417
|
+
if len(calls) == 1:
|
|
418
|
+
with cfdb.open_edataset(w.conn('sf'), w.tmp / 'sf.cfdb', flag='w') as ds:
|
|
419
|
+
ds['streamflow'][0, 0:24] = np.full((1, 24), 3.25)
|
|
420
|
+
assert ds.push()
|
|
421
|
+
refresh_into(w, m.rdb)
|
|
422
|
+
return real(attempt, *args, **kwargs)
|
|
423
|
+
|
|
424
|
+
monkeypatch.setattr(read, 'read_values', push_then_read)
|
|
425
|
+
r = client(m).get(_sf_url(m), params={'datetime': '2020-01-01T00:00Z/2020-01-01T05:00Z'})
|
|
426
|
+
assert r.status_code == 200 and len(calls) == 2
|
|
427
|
+
assert r.json()['ranges']['streamflow']['values'] == [3.25] * 6
|
|
428
|
+
assert json.loads(r.content)['id'] == station_id(m, 'sf', 'A')
|