mloda-plugin-govdata 0.2.1__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.
- mloda_plugin_govdata/__init__.py +0 -0
- mloda_plugin_govdata/feature_groups/__init__.py +1 -0
- mloda_plugin_govdata/feature_groups/govdata/__init__.py +55 -0
- mloda_plugin_govdata/feature_groups/govdata/bundeswahlleiterin.py +48 -0
- mloda_plugin_govdata/feature_groups/govdata/core/__init__.py +1 -0
- mloda_plugin_govdata/feature_groups/govdata/core/cache.py +114 -0
- mloda_plugin_govdata/feature_groups/govdata/core/client.py +72 -0
- mloda_plugin_govdata/feature_groups/govdata/core/discovery.py +177 -0
- mloda_plugin_govdata/feature_groups/govdata/core/locator.py +42 -0
- mloda_plugin_govdata/feature_groups/govdata/core/parse.py +275 -0
- mloda_plugin_govdata/feature_groups/govdata/feature.py +17 -0
- mloda_plugin_govdata/feature_groups/govdata/population.py +22 -0
- mloda_plugin_govdata/feature_groups/govdata/reader.py +123 -0
- mloda_plugin_govdata/feature_groups/govdata/tests/__init__.py +0 -0
- mloda_plugin_govdata/feature_groups/govdata/tests/conftest.py +8 -0
- mloda_plugin_govdata/feature_groups/govdata/tests/test_cache.py +62 -0
- mloda_plugin_govdata/feature_groups/govdata/tests/test_client.py +49 -0
- mloda_plugin_govdata/feature_groups/govdata/tests/test_discovery.py +157 -0
- mloda_plugin_govdata/feature_groups/govdata/tests/test_parse.py +183 -0
- mloda_plugin_govdata/feature_groups/govdata/tests/test_parse_hypothesis.py +38 -0
- mloda_plugin_govdata/feature_groups/govdata/tests/test_reader.py +327 -0
- mloda_plugin_govdata/feature_groups/govdata/tests/test_uba.py +193 -0
- mloda_plugin_govdata/feature_groups/govdata/uba.py +220 -0
- mloda_plugin_govdata-0.2.1.dist-info/METADATA +29 -0
- mloda_plugin_govdata-0.2.1.dist-info/RECORD +28 -0
- mloda_plugin_govdata-0.2.1.dist-info/WHEEL +5 -0
- mloda_plugin_govdata-0.2.1.dist-info/licenses/LICENSE +201 -0
- mloda_plugin_govdata-0.2.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
"""Level 2 (recorded) and Level 3 (live) tests for the GovData reader."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any, cast
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
import pyarrow as pa
|
|
9
|
+
import pytest
|
|
10
|
+
import respx
|
|
11
|
+
from mloda.provider import FeatureSet
|
|
12
|
+
from mloda.user import Feature, Options, mloda
|
|
13
|
+
from mloda_plugins.feature_group.input_data.read_file import ReadFile
|
|
14
|
+
|
|
15
|
+
from mloda_plugin_govdata.feature_groups.govdata.bundeswahlleiterin import (
|
|
16
|
+
OPTION_WAHL_HEADER_ROWS,
|
|
17
|
+
OPTION_WAHL_LABEL_COLUMNS,
|
|
18
|
+
OPTION_WAHL_SKIPROWS,
|
|
19
|
+
OPTION_WAHL_VALUE_TYPE,
|
|
20
|
+
BundeswahlleiterinReader,
|
|
21
|
+
)
|
|
22
|
+
from mloda_plugin_govdata.feature_groups.govdata.core.discovery import ResolvedDistribution
|
|
23
|
+
from mloda_plugin_govdata.feature_groups.govdata.core.locator import GovDataLocator
|
|
24
|
+
from mloda_plugin_govdata.feature_groups.govdata.feature import GovDataFeature
|
|
25
|
+
from mloda_plugin_govdata.feature_groups.govdata.population import StuttgartPopulationReader
|
|
26
|
+
from mloda_plugin_govdata.feature_groups.govdata.reader import BaseGovDataReader, GovDataReader
|
|
27
|
+
from mloda_plugin_govdata.feature_groups.govdata.uba import UbaAirReader, uba_measures_url
|
|
28
|
+
|
|
29
|
+
SLUG = "einwohner-nach-altersgruppen-und-stadtbezirken"
|
|
30
|
+
PACKAGE_SHOW = "https://ckan.govdata.de/api/3/action/package_show"
|
|
31
|
+
KERG_URL = "https://www.bundeswahlleiterin.de/bundestagswahlen/2025/ergebnisse/opendata/btw25/csv/kerg.csv"
|
|
32
|
+
KERG_MEASURE = "Wahlberechtigte Erststimmen Endgültig"
|
|
33
|
+
BERLIN_URL = "https://www.wahlen-berlin.de/wahlen/BE2023/AFSPRAES/agh/Datenexport_AGH2023_Zweitstimme_W_BE.csv"
|
|
34
|
+
# The wahlen-berlin.de Datenexport geometry: no preamble, one header row, 12 label
|
|
35
|
+
# columns (Adresse..Zeit), then vote counts and German-decimal percentage columns.
|
|
36
|
+
BERLIN_OPTIONS: dict[str, Any] = {
|
|
37
|
+
BundeswahlleiterinReader.__name__: BERLIN_URL,
|
|
38
|
+
OPTION_WAHL_SKIPROWS: 0,
|
|
39
|
+
OPTION_WAHL_HEADER_ROWS: 1,
|
|
40
|
+
OPTION_WAHL_LABEL_COLUMNS: 12,
|
|
41
|
+
OPTION_WAHL_VALUE_TYPE: "float",
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _mock_population_endpoints(fixtures_dir: Path) -> None:
|
|
46
|
+
package_show = (fixtures_dir / "package_show.json").read_text(encoding="utf-8")
|
|
47
|
+
csv_bytes = (fixtures_dir / "population_sample.csv").read_bytes()
|
|
48
|
+
distribution_url = json.loads(package_show)["result"]["resources"][0]["url"]
|
|
49
|
+
respx.get(PACKAGE_SHOW).mock(return_value=httpx.Response(200, text=package_show))
|
|
50
|
+
respx.get(distribution_url).mock(return_value=httpx.Response(200, content=csv_bytes, headers={"ETag": '"v1"'}))
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class _FakeFeatureSet:
|
|
54
|
+
"""Just enough FeatureSet surface for load_data; mirrors the sorted-tuple contract."""
|
|
55
|
+
|
|
56
|
+
def __init__(self, names: set[str], options: Options | None = None) -> None:
|
|
57
|
+
self._names = tuple(sorted(names))
|
|
58
|
+
self.options = options # FeatureSet leaves this None until a feature is added
|
|
59
|
+
|
|
60
|
+
def get_all_names(self) -> tuple[str, ...]:
|
|
61
|
+
return self._names
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def test_feature_group_uses_base_govdata_reader() -> None:
|
|
65
|
+
assert isinstance(GovDataFeature.input_data(), BaseGovDataReader)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def test_class_options_key_normalizes_to_reader_name() -> None:
|
|
69
|
+
# The reader class works as an options key; it normalizes to the class-name string (mloda >=0.10.0).
|
|
70
|
+
# The cast bridges a 0.10.0 typing gap: the runtime accepts class keys, the hints only admit str.
|
|
71
|
+
options = Options(cast(dict[str, Any], {GovDataReader: SLUG}))
|
|
72
|
+
assert options.get(GovDataReader.__name__) == SLUG
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@respx.mock
|
|
76
|
+
def test_load_data_level2(fixtures_dir: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
77
|
+
monkeypatch.setattr(StuttgartPopulationReader, "cache_dir", str(tmp_path))
|
|
78
|
+
package_show = (fixtures_dir / "package_show.json").read_text(encoding="utf-8")
|
|
79
|
+
csv_bytes = (fixtures_dir / "population_sample.csv").read_bytes()
|
|
80
|
+
distribution_url = json.loads(package_show)["result"]["resources"][0]["url"]
|
|
81
|
+
|
|
82
|
+
respx.get(PACKAGE_SHOW).mock(return_value=httpx.Response(200, text=package_show))
|
|
83
|
+
respx.get(distribution_url).mock(return_value=httpx.Response(200, content=csv_bytes, headers={"ETag": '"v1"'}))
|
|
84
|
+
|
|
85
|
+
result = mloda.run_all(
|
|
86
|
+
[
|
|
87
|
+
Feature("Einwohner", options={StuttgartPopulationReader.__name__: SLUG}),
|
|
88
|
+
Feature("Stadtbezirk", options={StuttgartPopulationReader.__name__: SLUG}),
|
|
89
|
+
],
|
|
90
|
+
compute_frameworks=["PyArrowTable"],
|
|
91
|
+
)
|
|
92
|
+
table = result[0]
|
|
93
|
+
assert set(table.schema.names) == {"Einwohner", "Stadtbezirk"}
|
|
94
|
+
assert table.num_rows == 1000
|
|
95
|
+
assert table.schema.field("Einwohner").type == pa.int64()
|
|
96
|
+
# RunResult.plan (mloda >=0.10.0): the resolved execution steps name our group and framework.
|
|
97
|
+
compute_steps = [step for step in result.plan if step.step_kind == "compute"]
|
|
98
|
+
assert [step.feature_group_name for step in compute_steps] == ["GovDataFeature"]
|
|
99
|
+
assert compute_steps[0].compute_framework_name == "PyArrowTable"
|
|
100
|
+
assert set(compute_steps[0].requested_feature_names) == {"Einwohner", "Stadtbezirk"}
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@respx.mock
|
|
104
|
+
def test_resolves_without_explicit_compute_framework(
|
|
105
|
+
fixtures_dir: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
106
|
+
) -> None:
|
|
107
|
+
# Regression: GovDataFeature must not collide with the built-in ReadFileFeature,
|
|
108
|
+
# so a run_all call with no compute_frameworks pin still resolves to one group.
|
|
109
|
+
monkeypatch.setattr(GovDataReader, "cache_dir", str(tmp_path))
|
|
110
|
+
package_show = (fixtures_dir / "package_show.json").read_text(encoding="utf-8")
|
|
111
|
+
csv_bytes = (fixtures_dir / "population_sample.csv").read_bytes()
|
|
112
|
+
distribution_url = json.loads(package_show)["result"]["resources"][0]["url"]
|
|
113
|
+
respx.get(PACKAGE_SHOW).mock(return_value=httpx.Response(200, text=package_show))
|
|
114
|
+
respx.get(distribution_url).mock(return_value=httpx.Response(200, content=csv_bytes, headers={"ETag": '"v1"'}))
|
|
115
|
+
|
|
116
|
+
result = mloda.run_all([Feature("Einwohner", options={GovDataReader.__name__: SLUG})])
|
|
117
|
+
assert result[0].num_rows == 1000
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
@pytest.mark.live
|
|
121
|
+
def test_live_end_to_end() -> None:
|
|
122
|
+
result = mloda.run_all(
|
|
123
|
+
[Feature("Einwohner", options={StuttgartPopulationReader.__name__: SLUG})],
|
|
124
|
+
compute_frameworks=["PyArrowTable"],
|
|
125
|
+
)
|
|
126
|
+
table = result[0]
|
|
127
|
+
assert table.num_rows > 20_000
|
|
128
|
+
assert table.schema.field("Einwohner").type == pa.int64()
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
@respx.mock
|
|
132
|
+
def test_elections_reader_level2(fixtures_dir: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
133
|
+
monkeypatch.setattr(BundeswahlleiterinReader, "cache_dir", str(tmp_path))
|
|
134
|
+
kerg_bytes = (fixtures_dir / "kerg_sample.csv").read_bytes()
|
|
135
|
+
respx.get(KERG_URL).mock(return_value=httpx.Response(200, content=kerg_bytes, headers={"ETag": '"k1"'}))
|
|
136
|
+
result = mloda.run_all(
|
|
137
|
+
[
|
|
138
|
+
Feature("Gebiet", options={BundeswahlleiterinReader.__name__: KERG_URL}),
|
|
139
|
+
Feature(KERG_MEASURE, options={BundeswahlleiterinReader.__name__: KERG_URL}),
|
|
140
|
+
],
|
|
141
|
+
compute_frameworks=["PyArrowTable"],
|
|
142
|
+
)
|
|
143
|
+
table = result[0]
|
|
144
|
+
assert set(table.schema.names) == {"Gebiet", KERG_MEASURE}
|
|
145
|
+
assert table.num_rows == 16
|
|
146
|
+
assert table.column("Gebiet").to_pylist()[0] == "Flensburg – Schleswig"
|
|
147
|
+
assert table.schema.field(KERG_MEASURE).type == pa.int64()
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@pytest.mark.live
|
|
151
|
+
def test_elections_live_end_to_end() -> None:
|
|
152
|
+
result = mloda.run_all(
|
|
153
|
+
[Feature("Gebiet", options={BundeswahlleiterinReader.__name__: KERG_URL})],
|
|
154
|
+
compute_frameworks=["PyArrowTable"],
|
|
155
|
+
)
|
|
156
|
+
table = result[0]
|
|
157
|
+
assert table.num_rows > 300
|
|
158
|
+
assert table.column("Gebiet").to_pylist()[-1] == "Bundesgebiet"
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def test_berlin_url_is_a_direct_distribution() -> None:
|
|
162
|
+
locator = GovDataLocator.from_string(BERLIN_URL)
|
|
163
|
+
assert locator.distribution_url == BERLIN_URL
|
|
164
|
+
assert locator.dataset_id is None
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
@respx.mock
|
|
168
|
+
def test_berlin_wahl_reader_level2(fixtures_dir: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
169
|
+
# The Berlin single-header export needs no code change: only geometry options.
|
|
170
|
+
monkeypatch.setattr(BundeswahlleiterinReader, "cache_dir", str(tmp_path))
|
|
171
|
+
berlin_bytes = (fixtures_dir / "berlin_wahl_sample.csv").read_bytes()
|
|
172
|
+
respx.get(BERLIN_URL).mock(return_value=httpx.Response(200, content=berlin_bytes, headers={"ETag": '"b1"'}))
|
|
173
|
+
result = mloda.run_all(
|
|
174
|
+
[
|
|
175
|
+
Feature("Bezirksname", options=dict(BERLIN_OPTIONS)),
|
|
176
|
+
Feature("Gueltig", options=dict(BERLIN_OPTIONS)),
|
|
177
|
+
Feature("P02", options=dict(BERLIN_OPTIONS)),
|
|
178
|
+
],
|
|
179
|
+
compute_frameworks=["PyArrowTable"],
|
|
180
|
+
)
|
|
181
|
+
table = result[0]
|
|
182
|
+
assert set(table.schema.names) == {"Bezirksname", "Gueltig", "P02"}
|
|
183
|
+
assert table.num_rows == 12
|
|
184
|
+
assert table.column("Bezirksname").to_pylist()[0] == "Mitte"
|
|
185
|
+
assert table.schema.field("Gueltig").type == pa.float64()
|
|
186
|
+
assert table.column("Gueltig").to_pylist()[0] == 428.0
|
|
187
|
+
assert table.column("P02").to_pylist()[0] == 102.0
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
@respx.mock
|
|
191
|
+
def test_geometry_options_default_to_btw25(fixtures_dir: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
192
|
+
monkeypatch.setattr(BundeswahlleiterinReader, "cache_dir", str(tmp_path))
|
|
193
|
+
kerg_bytes = (fixtures_dir / "kerg_sample.csv").read_bytes()
|
|
194
|
+
respx.get(KERG_URL).mock(return_value=httpx.Response(200, content=kerg_bytes, headers={"ETag": '"k1"'}))
|
|
195
|
+
explicit_btw25: dict[str, Any] = {
|
|
196
|
+
BundeswahlleiterinReader.__name__: KERG_URL,
|
|
197
|
+
OPTION_WAHL_SKIPROWS: 5,
|
|
198
|
+
OPTION_WAHL_HEADER_ROWS: 3,
|
|
199
|
+
OPTION_WAHL_LABEL_COLUMNS: 4,
|
|
200
|
+
OPTION_WAHL_VALUE_TYPE: "integer",
|
|
201
|
+
}
|
|
202
|
+
defaulted = mloda.run_all(
|
|
203
|
+
[Feature("Gebiet", options={BundeswahlleiterinReader.__name__: KERG_URL})],
|
|
204
|
+
compute_frameworks=["PyArrowTable"],
|
|
205
|
+
)[0]
|
|
206
|
+
explicit = mloda.run_all(
|
|
207
|
+
[Feature("Gebiet", options=explicit_btw25)],
|
|
208
|
+
compute_frameworks=["PyArrowTable"],
|
|
209
|
+
)[0]
|
|
210
|
+
assert defaulted.equals(explicit)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def test_bad_geometry_option_raises(fixtures_dir: Path) -> None:
|
|
214
|
+
locator = GovDataLocator.from_string(KERG_URL)
|
|
215
|
+
distribution = ResolvedDistribution(url=KERG_URL, license=None, dataset=None)
|
|
216
|
+
options = Options({OPTION_WAHL_SKIPROWS: "five"})
|
|
217
|
+
with pytest.raises(ValueError):
|
|
218
|
+
BundeswahlleiterinReader._parse(fixtures_dir / "kerg_sample.csv", locator, distribution, options)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
@pytest.mark.live
|
|
222
|
+
def test_berlin_wahl_live_end_to_end() -> None:
|
|
223
|
+
result = mloda.run_all(
|
|
224
|
+
[
|
|
225
|
+
Feature("Bezirksname", options=dict(BERLIN_OPTIONS)),
|
|
226
|
+
Feature("Gueltig", options=dict(BERLIN_OPTIONS)),
|
|
227
|
+
],
|
|
228
|
+
compute_frameworks=["PyArrowTable"],
|
|
229
|
+
)
|
|
230
|
+
table = result[0]
|
|
231
|
+
assert table.num_rows > 3000
|
|
232
|
+
assert "Mitte" in table.column("Bezirksname").to_pylist()
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
@respx.mock
|
|
236
|
+
def test_peek_population_level2(fixtures_dir: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
237
|
+
monkeypatch.setattr(StuttgartPopulationReader, "cache_dir", str(tmp_path))
|
|
238
|
+
_mock_population_endpoints(fixtures_dir)
|
|
239
|
+
assert StuttgartPopulationReader.peek(SLUG) == {
|
|
240
|
+
"Stichtag": "date32[day]",
|
|
241
|
+
"Stadtbezirk": "string",
|
|
242
|
+
"Alter in 10 Gruppen": "string",
|
|
243
|
+
"Einwohner": "int64",
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
@respx.mock
|
|
248
|
+
def test_generic_reader_reads_unknown_dataset_as_strings(
|
|
249
|
+
fixtures_dir: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
250
|
+
) -> None:
|
|
251
|
+
# The generic reader carries no dataset schema; every column comes back as a string.
|
|
252
|
+
monkeypatch.setattr(GovDataReader, "cache_dir", str(tmp_path))
|
|
253
|
+
_mock_population_endpoints(fixtures_dir)
|
|
254
|
+
assert GovDataReader.peek(SLUG) == {
|
|
255
|
+
"Stichtag": "string",
|
|
256
|
+
"Stadtbezirk": "string",
|
|
257
|
+
"Alter in 10 Gruppen": "string",
|
|
258
|
+
"Einwohner": "string",
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
@respx.mock
|
|
263
|
+
def test_peek_elections_level2(fixtures_dir: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
264
|
+
monkeypatch.setattr(BundeswahlleiterinReader, "cache_dir", str(tmp_path))
|
|
265
|
+
kerg_bytes = (fixtures_dir / "kerg_sample.csv").read_bytes()
|
|
266
|
+
respx.get(KERG_URL).mock(return_value=httpx.Response(200, content=kerg_bytes, headers={"ETag": '"k1"'}))
|
|
267
|
+
columns = BundeswahlleiterinReader.peek(KERG_URL)
|
|
268
|
+
assert columns["Gebiet"] == "string"
|
|
269
|
+
assert columns[KERG_MEASURE] == "int64"
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
@respx.mock
|
|
273
|
+
def test_peek_uba_level2(fixtures_dir: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
274
|
+
monkeypatch.setattr(UbaAirReader, "cache_dir", str(tmp_path))
|
|
275
|
+
url = uba_measures_url(station=143, component=3, scope=2, date_from="2025-01-01", date_to="2025-01-01")
|
|
276
|
+
payload = (fixtures_dir / "uba_measures.json").read_bytes()
|
|
277
|
+
respx.get(url).mock(return_value=httpx.Response(200, content=payload, headers={"ETag": '"u1"'}))
|
|
278
|
+
columns = UbaAirReader.peek(url)
|
|
279
|
+
assert columns["station_id"] == "int64"
|
|
280
|
+
assert columns["value"] == "double"
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def test_peek_rejects_unusable_data_access() -> None:
|
|
284
|
+
with pytest.raises(ValueError, match="cannot handle data access"):
|
|
285
|
+
GovDataReader.peek(123)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
@pytest.mark.parametrize(
|
|
289
|
+
"reader",
|
|
290
|
+
[BaseGovDataReader, GovDataReader, StuttgartPopulationReader, BundeswahlleiterinReader, UbaAirReader],
|
|
291
|
+
)
|
|
292
|
+
def test_readers_classify_as_final_readers(reader: type[BaseGovDataReader]) -> None:
|
|
293
|
+
# mloda >=0.10.0 classifies readers structurally: overriding load_data wholesale
|
|
294
|
+
# relative to the ReadFile anchor makes each reader final; the ReadFile base is not.
|
|
295
|
+
assert reader.final_reader_anchor() is ReadFile
|
|
296
|
+
assert reader.is_final_reader() is True
|
|
297
|
+
assert ReadFile.is_final_reader() is False
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
@respx.mock
|
|
301
|
+
def test_unknown_feature_names_available_columns(
|
|
302
|
+
fixtures_dir: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
303
|
+
) -> None:
|
|
304
|
+
monkeypatch.setattr(GovDataReader, "cache_dir", str(tmp_path))
|
|
305
|
+
_mock_population_endpoints(fixtures_dir)
|
|
306
|
+
features = cast(FeatureSet, _FakeFeatureSet({"Einwohner_", "Stadtbezirk"}))
|
|
307
|
+
with pytest.raises(ValueError) as excinfo:
|
|
308
|
+
GovDataReader.load_data(SLUG, features)
|
|
309
|
+
message = str(excinfo.value)
|
|
310
|
+
assert "Unknown feature(s) 'Einwohner_'" in message
|
|
311
|
+
assert "Available: Alter in 10 Gruppen, Einwohner, Stadtbezirk, Stichtag." in message
|
|
312
|
+
assert "Did you mean 'Einwohner' instead of 'Einwohner_'?" in message
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
@respx.mock
|
|
316
|
+
def test_unknown_feature_suggestion_only_for_close_matches(
|
|
317
|
+
fixtures_dir: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
318
|
+
) -> None:
|
|
319
|
+
monkeypatch.setattr(GovDataReader, "cache_dir", str(tmp_path))
|
|
320
|
+
_mock_population_endpoints(fixtures_dir)
|
|
321
|
+
features = cast(FeatureSet, _FakeFeatureSet({"Einwohner_", "zzzzz"}))
|
|
322
|
+
with pytest.raises(ValueError) as excinfo:
|
|
323
|
+
GovDataReader.load_data(SLUG, features)
|
|
324
|
+
message = str(excinfo.value)
|
|
325
|
+
assert "Unknown feature(s) 'Einwohner_', 'zzzzz'" in message
|
|
326
|
+
assert message.count("Did you mean") == 1 # no suggestion for 'zzzzz'
|
|
327
|
+
assert "Did you mean 'Einwohner' instead of 'Einwohner_'?" in message
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""Tests for the UBA Air Data reader: Level 1 (flatten / URL), Level 2 (recorded), Level 3 (live)."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
import pyarrow as pa
|
|
9
|
+
import pytest
|
|
10
|
+
import respx
|
|
11
|
+
from hypothesis import given
|
|
12
|
+
from hypothesis import strategies as st
|
|
13
|
+
from mloda.user import Feature, mloda
|
|
14
|
+
|
|
15
|
+
from mloda_plugin_govdata.feature_groups.govdata.uba import (
|
|
16
|
+
UBA_AIR_BASE,
|
|
17
|
+
UbaAirReader,
|
|
18
|
+
parse_uba_measures_bytes,
|
|
19
|
+
uba_measures_url,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
MEASURE_COLUMNS = ["station_id", "date_start", "component_id", "scope_id", "value", "date_end", "index"]
|
|
23
|
+
INDICES = {"data": {"station id": {"date start": ["component id", "scope id", "value", "date end", "index"]}}}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _demo_url() -> str:
|
|
27
|
+
return uba_measures_url(station=143, component=3, scope=2, date_from="2025-01-01", date_to="2025-01-01")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
# --- Level 1: URL builder ---------------------------------------------------------------
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def test_uba_measures_url_is_exact_and_ordered() -> None:
|
|
34
|
+
# Assert the full string: param order is fixed, which keeps the cache key stable.
|
|
35
|
+
expected = (
|
|
36
|
+
f"{UBA_AIR_BASE}/measures/json?"
|
|
37
|
+
"date_from=2025-01-01&time_from=1&date_to=2025-01-01&time_to=24"
|
|
38
|
+
"&station=143&component=3&scope=2&lang=en"
|
|
39
|
+
)
|
|
40
|
+
assert _demo_url() == expected
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
# --- Level 1: flatten -------------------------------------------------------------------
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_flatten_real_fixture(fixtures_dir: Path) -> None:
|
|
47
|
+
table = parse_uba_measures_bytes((fixtures_dir / "uba_measures.json").read_bytes())
|
|
48
|
+
assert table.schema.names == MEASURE_COLUMNS
|
|
49
|
+
assert table.num_rows == 24
|
|
50
|
+
assert table.column("station_id").to_pylist()[0] == 143
|
|
51
|
+
assert table.column("date_start").to_pylist()[0] == "2025-01-01 00:00:00"
|
|
52
|
+
assert table.column("date_end").to_pylist()[0] == "2025-01-01 01:00:00"
|
|
53
|
+
assert table.column("component_id").to_pylist()[0] == 3
|
|
54
|
+
assert table.column("scope_id").to_pylist()[0] == 2
|
|
55
|
+
assert table.column("value").to_pylist()[0] == 37.0
|
|
56
|
+
assert table.column("index").to_pylist()[0] == 2
|
|
57
|
+
assert table.schema.field("station_id").type == pa.int64()
|
|
58
|
+
assert table.schema.field("value").type == pa.float64()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def test_flatten_multi_station() -> None:
|
|
62
|
+
payload = {
|
|
63
|
+
"indices": INDICES,
|
|
64
|
+
"data": {
|
|
65
|
+
"143": {"2025-01-01 00:00:00": [3, 2, 37, "2025-01-01 01:00:00", "2"]},
|
|
66
|
+
"144": {"2025-01-01 00:00:00": [3, 2, 40, "2025-01-01 01:00:00", "3"]},
|
|
67
|
+
},
|
|
68
|
+
}
|
|
69
|
+
table = parse_uba_measures_bytes(json.dumps(payload).encode())
|
|
70
|
+
assert table.num_rows == 2
|
|
71
|
+
assert set(table.column("station_id").to_pylist()) == {143, 144}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def test_flatten_handles_null_value_and_index() -> None:
|
|
75
|
+
payload = {"indices": INDICES, "data": {"143": {"2025-01-01 00:00:00": [3, 2, None, "2025-01-01 01:00:00", None]}}}
|
|
76
|
+
table = parse_uba_measures_bytes(json.dumps(payload).encode())
|
|
77
|
+
assert table.column("value").to_pylist() == [None]
|
|
78
|
+
assert table.column("index").to_pylist() == [None]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def test_flatten_without_indices_uses_canonical_schema() -> None:
|
|
82
|
+
# The schema is canonical and does not depend on the response self-describing its layout.
|
|
83
|
+
payload = {"data": {"143": {"2025-01-01 00:00:00": [3, 2, 37, "2025-01-01 01:00:00", "2"]}}}
|
|
84
|
+
table = parse_uba_measures_bytes(json.dumps(payload).encode())
|
|
85
|
+
assert table.schema.names == MEASURE_COLUMNS
|
|
86
|
+
assert table.column("value").to_pylist() == [37.0]
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def test_flatten_keeps_canonical_names_for_localized_labels() -> None:
|
|
90
|
+
# Even if the server sends localized labels, the public column names stay canonical.
|
|
91
|
+
localized = {"data": {"Stationskennung": {"Startdatum": ["Komponente", "Bereich", "Wert", "Enddatum", "Index"]}}}
|
|
92
|
+
payload = {"indices": localized, "data": {"143": {"2025-01-01 00:00:00": [3, 2, 37, "2025-01-01 01:00:00", "2"]}}}
|
|
93
|
+
table = parse_uba_measures_bytes(json.dumps(payload).encode())
|
|
94
|
+
assert table.schema.names == MEASURE_COLUMNS
|
|
95
|
+
assert table.schema.field("value").type == pa.float64()
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def test_flatten_rejects_changed_leaf_layout() -> None:
|
|
99
|
+
# A different leaf width would shift columns under positional mapping; reject it loudly.
|
|
100
|
+
changed = {"data": {"station id": {"date start": ["component id", "scope id", "value", "date end"]}}}
|
|
101
|
+
payload = {"indices": changed, "data": {"143": {"2025-01-01 00:00:00": [3, 2, 37, "2025-01-01 01:00:00"]}}}
|
|
102
|
+
with pytest.raises(ValueError):
|
|
103
|
+
parse_uba_measures_bytes(json.dumps(payload).encode())
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def test_flatten_rejects_payload_without_data() -> None:
|
|
107
|
+
with pytest.raises(ValueError):
|
|
108
|
+
parse_uba_measures_bytes(b'{"request": {}}')
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def test_flatten_empty_data_yields_zero_rows() -> None:
|
|
112
|
+
table = parse_uba_measures_bytes(json.dumps({"indices": INDICES, "data": {}}).encode())
|
|
113
|
+
assert table.num_rows == 0
|
|
114
|
+
assert table.schema.names == MEASURE_COLUMNS
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def test_flatten_skips_non_dict_station() -> None:
|
|
118
|
+
payload = {
|
|
119
|
+
"indices": INDICES,
|
|
120
|
+
"data": {"143": {"2025-01-01 00:00:00": [3, 2, 37, "2025-01-01 01:00:00", "2"]}, "999": None},
|
|
121
|
+
}
|
|
122
|
+
table = parse_uba_measures_bytes(json.dumps(payload).encode())
|
|
123
|
+
assert table.column("station_id").to_pylist() == [143]
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def test_flatten_pads_short_leaf() -> None:
|
|
127
|
+
payload = {"data": {"143": {"2025-01-01 00:00:00": [3, 2, 37]}}}
|
|
128
|
+
table = parse_uba_measures_bytes(json.dumps(payload).encode())
|
|
129
|
+
assert table.column("value").to_pylist() == [37.0]
|
|
130
|
+
assert table.column("date_end").to_pylist() == [None]
|
|
131
|
+
assert table.column("index").to_pylist() == [None]
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def test_flatten_rejects_non_numeric_station_id() -> None:
|
|
135
|
+
# station_id is typed integer; a non-numeric key fails loudly rather than silently mistyping.
|
|
136
|
+
payload = {"data": {"DEBW118": {"2025-01-01 00:00:00": [3, 2, 37, "2025-01-01 01:00:00", "2"]}}}
|
|
137
|
+
with pytest.raises(ValueError):
|
|
138
|
+
parse_uba_measures_bytes(json.dumps(payload).encode())
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
_LEAF = st.just([3, 2, 10, "2025-01-01 01:00:00", "1"])
|
|
142
|
+
_SERIES = st.dictionaries(
|
|
143
|
+
keys=st.integers(min_value=0, max_value=23).map(lambda h: f"2025-01-01 {h:02d}:00:00"),
|
|
144
|
+
values=_LEAF,
|
|
145
|
+
max_size=24,
|
|
146
|
+
)
|
|
147
|
+
_STATIONS = st.dictionaries(keys=st.integers(min_value=1, max_value=999).map(str), values=_SERIES, max_size=4)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@given(stations=_STATIONS)
|
|
151
|
+
def test_flatten_row_count_matches_leaves(stations: dict[str, dict[str, list[Any]]]) -> None:
|
|
152
|
+
payload = {"indices": INDICES, "data": stations}
|
|
153
|
+
table = parse_uba_measures_bytes(json.dumps(payload).encode())
|
|
154
|
+
assert table.num_rows == sum(len(series) for series in stations.values())
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
# --- Level 2: recorded reader (no network) ----------------------------------------------
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
@respx.mock
|
|
161
|
+
def test_uba_reader_level2(fixtures_dir: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
162
|
+
monkeypatch.setattr(UbaAirReader, "cache_dir", str(tmp_path))
|
|
163
|
+
measures_bytes = (fixtures_dir / "uba_measures.json").read_bytes()
|
|
164
|
+
url = _demo_url()
|
|
165
|
+
respx.get(url).mock(return_value=httpx.Response(200, content=measures_bytes))
|
|
166
|
+
|
|
167
|
+
result = mloda.run_all(
|
|
168
|
+
[
|
|
169
|
+
Feature("value", options={UbaAirReader.__name__: url}),
|
|
170
|
+
Feature("date_start", options={UbaAirReader.__name__: url}),
|
|
171
|
+
],
|
|
172
|
+
compute_frameworks=["PyArrowTable"],
|
|
173
|
+
)
|
|
174
|
+
table = result[0]
|
|
175
|
+
assert set(table.schema.names) == {"value", "date_start"}
|
|
176
|
+
assert table.num_rows == 24
|
|
177
|
+
assert table.schema.field("value").type == pa.float64()
|
|
178
|
+
assert table.column("value").to_pylist()[0] == 37.0
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
# --- Level 3: live (deselected by default) ----------------------------------------------
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
@pytest.mark.live
|
|
185
|
+
def test_uba_live_end_to_end() -> None:
|
|
186
|
+
url = _demo_url()
|
|
187
|
+
result = mloda.run_all(
|
|
188
|
+
[Feature("value", options={UbaAirReader.__name__: url})],
|
|
189
|
+
compute_frameworks=["PyArrowTable"],
|
|
190
|
+
)
|
|
191
|
+
table = result[0]
|
|
192
|
+
assert table.num_rows >= 20
|
|
193
|
+
assert table.schema.field("value").type == pa.float64()
|