cedarkit-query 0.2.1__tar.gz → 0.2.3__tar.gz

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.
Files changed (48) hide show
  1. {cedarkit_query-0.2.1/src/cedarkit_query.egg-info → cedarkit_query-0.2.3}/PKG-INFO +1 -1
  2. cedarkit_query-0.2.3/docs/using-v1.md +11 -0
  3. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/pyproject.toml +1 -1
  4. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/src/cedarkit_query/__init__.py +4 -1
  5. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/src/cedarkit_query/model.py +39 -12
  6. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/src/cedarkit_query/resources.py +91 -18
  7. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3/src/cedarkit_query.egg-info}/PKG-INFO +1 -1
  8. cedarkit_query-0.2.3/tests/test_resources.py +346 -0
  9. cedarkit_query-0.2.1/docs/using-v1.md +0 -5
  10. cedarkit_query-0.2.1/tests/test_resources.py +0 -151
  11. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/LICENSE +0 -0
  12. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/MANIFEST.in +0 -0
  13. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/README.md +0 -0
  14. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/docs/normalization-v1.md +0 -0
  15. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/docs/protocol-v1.md +0 -0
  16. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/examples/catalog.json +0 -0
  17. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/examples/request.json +0 -0
  18. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/scripts/build_schemas.py +0 -0
  19. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/scripts/check_dist.py +0 -0
  20. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/setup.cfg +0 -0
  21. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/src/cedarkit_query/_json.py +0 -0
  22. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/src/cedarkit_query/errors.py +0 -0
  23. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/src/cedarkit_query/normalize.py +0 -0
  24. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/src/cedarkit_query/parameters.py +0 -0
  25. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/src/cedarkit_query/schemas/catalog-v1.schema.json +0 -0
  26. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/src/cedarkit_query/schemas/common-v1.schema.json +0 -0
  27. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/src/cedarkit_query/schemas/context-v1.schema.json +0 -0
  28. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/src/cedarkit_query/schemas/error-v1.schema.json +0 -0
  29. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/src/cedarkit_query/schemas/explanation-v1.schema.json +0 -0
  30. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/src/cedarkit_query/schemas/mappings-v1.schema.json +0 -0
  31. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/src/cedarkit_query/schemas/parameters-v1.schema.json +0 -0
  32. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/src/cedarkit_query/schemas/query-v1.schema.json +0 -0
  33. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/src/cedarkit_query/schemas/report-v1.schema.json +0 -0
  34. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/src/cedarkit_query/schemas/request-v1.schema.json +0 -0
  35. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/src/cedarkit_query/validation.py +0 -0
  36. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/src/cedarkit_query.egg-info/SOURCES.txt +0 -0
  37. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/src/cedarkit_query.egg-info/dependency_links.txt +0 -0
  38. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/src/cedarkit_query.egg-info/requires.txt +0 -0
  39. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/src/cedarkit_query.egg-info/top_level.txt +0 -0
  40. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/tests/conftest.py +0 -0
  41. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/tests/test_normalize.py +0 -0
  42. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/tests/test_parameters.py +0 -0
  43. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/tests/test_protocol.py +0 -0
  44. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/tests/test_scopes.py +0 -0
  45. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/tests/test_vectors.py +0 -0
  46. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/tests/vectors/v1/invalid.json +0 -0
  47. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/tests/vectors/v1/normalization.json +0 -0
  48. {cedarkit_query-0.2.1 → cedarkit_query-0.2.3}/tests/vectors/v1/valid.json +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cedarkit-query
3
- Version: 0.2.1
3
+ Version: 0.2.3
4
4
  Summary: Language-neutral CedarKit query value models and schemas
5
5
  License-Expression: Apache-2.0
6
6
  Requires-Python: >=3.11
@@ -0,0 +1,11 @@
1
+ # Use a native request
2
+
3
+ Load the request with `Request.load(path)` or build it from a mapping. Use `Query` to set native predicates and optional coordinate constraints. Use `reki.from_source(request.source, context=request.context)` and `source.sel(request.queries)` to execute the selection.
4
+
5
+ See [the native protocol](protocol-v1.md) and [the example request](../examples/request.json).
6
+
7
+ ## Validate GRIB2 definitions for a file source
8
+
9
+ `validate_standalone_grib2(parameters, mappings)` accepts a parameter registry and a single GRIB2 mapping resource as dictionaries or validated models. It returns effective definitions by stable ID for `prepare_queries`. Each name and alias must resolve within the registry. Mapping and table `applies_to` scopes must be empty. Use `when` for query conditions and `native.match` for GRIB2 header predicates. Two rules may coexist when their effective query conditions or their native predicates are disjoint.
10
+
11
+ Use `validate_resource_set(parameters, mappings, catalog, dataset_id)` to validate mappings selected by a catalog product.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "cedarkit-query"
7
- version = "0.2.1"
7
+ version = "0.2.3"
8
8
  description = "Language-neutral CedarKit query value models and schemas"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -13,6 +13,7 @@ from .model import (
13
13
  Request,
14
14
  dump_value,
15
15
  get_schema,
16
+ load_prevalidated_resource,
16
17
  load_request,
17
18
  load_value,
18
19
  validate_value,
@@ -28,7 +29,7 @@ from .normalize import (
28
29
  query_identity,
29
30
  )
30
31
  from .parameters import prepare_queries
31
- from .resources import validate_resource_set
32
+ from .resources import validate_resource_set, validate_standalone_grib2
32
33
 
33
34
  __all__ = [
34
35
  "Query",
@@ -43,8 +44,10 @@ __all__ = [
43
44
  "Parameters",
44
45
  "Mappings",
45
46
  "validate_resource_set",
47
+ "validate_standalone_grib2",
46
48
  "Context",
47
49
  "load_value",
50
+ "load_prevalidated_resource",
48
51
  "load_request",
49
52
  "dump_value",
50
53
  "get_schema",
@@ -332,20 +332,24 @@ def _format(path):
332
332
  return "json" if suffix == ".json" else "yaml"
333
333
 
334
334
 
335
+ def _parse_text(text, kind, format):
336
+ try:
337
+ return parse(text, format)
338
+ except (ValueError, YAMLError) as exc:
339
+ raise QueryError(
340
+ "invalid_request"
341
+ if kind == "request"
342
+ else "invalid_query"
343
+ if kind == "query"
344
+ else "invalid_config",
345
+ "",
346
+ str(exc),
347
+ ) from exc
348
+
349
+
335
350
  def load_value(value, kind, *, format=None, base_dir=None):
336
351
  if isinstance(value, str):
337
- try:
338
- value = parse(value, format)
339
- except (ValueError, YAMLError) as exc:
340
- raise QueryError(
341
- "invalid_request"
342
- if kind == "request"
343
- else "invalid_query"
344
- if kind == "query"
345
- else "invalid_config",
346
- "",
347
- str(exc),
348
- ) from exc
352
+ value = _parse_text(value, kind, format)
349
353
  elif format is not None:
350
354
  raise ValueError("format is only valid for text input")
351
355
  return (
@@ -355,6 +359,29 @@ def load_value(value, kind, *, format=None, base_dir=None):
355
359
  )
356
360
 
357
361
 
362
+ def load_prevalidated_resource(text, kind):
363
+ """Load packaged resource JSON previously validated with `load_value`.
364
+
365
+ The caller selects a trusted catalog, parameter registry, or mapping
366
+ resource validated against this protocol version. Return the same immutable
367
+ model as `load_value`, with JSON parsing and the protocol version check.
368
+ """
369
+ if kind not in {"catalog", "parameters", "mappings"}:
370
+ raise ValueError(f"unknown resource kind: {kind}")
371
+ if not isinstance(text, str):
372
+ raise TypeError("prevalidated resource requires JSON text")
373
+ value = _parse_text(text, kind, "json")
374
+ if not isinstance(value, dict):
375
+ raise QueryError("invalid_config", "", "resource must be a JSON object")
376
+ if value.get("api_version") != VERSIONS[kind]:
377
+ raise QueryError(
378
+ "unsupported_version", "/api_version", "unsupported format version"
379
+ )
380
+ result = object.__new__(MODELS[kind])
381
+ object.__setattr__(result, "_value", freeze(value))
382
+ return result
383
+
384
+
358
385
  def load_request(value, *, format=None, base_dir=None):
359
386
  return load_value(value, "request", format=format, base_dir=base_dir)
360
387
 
@@ -1,8 +1,14 @@
1
1
  """Pure validation for definitions, mappings and catalog resource combinations."""
2
2
 
3
- from ._json import canonical, plain
3
+ from ._json import canonical, plain, pointer
4
4
  from .errors import QueryError
5
- from .normalize import _normal_selector, _normalize, constrain_query, intersect_scopes
5
+ from .normalize import (
6
+ _intersection,
7
+ _normal_selector,
8
+ _normalize,
9
+ constrain_query,
10
+ intersect_scopes,
11
+ )
6
12
 
7
13
 
8
14
  def _error(path, message):
@@ -141,12 +147,85 @@ def validate_resource(data, kind):
141
147
  ) from exc
142
148
 
143
149
 
150
+ def _mapping_conditions(row, definition, path):
151
+ fixed = {
152
+ key: value
153
+ for key, value in definition["fixed_conditions"].items()
154
+ if key != "statistics"
155
+ }
156
+ try:
157
+ return constrain_query(row["when"], fixed).to_dict()
158
+ except QueryError as exc:
159
+ raise QueryError(
160
+ "invalid_config", path + "/when", "mapping conflicts with parameter conditions"
161
+ ) from exc
162
+
163
+
164
+ def _native_overlap(left, right):
165
+ for key in left.keys() & right.keys():
166
+ a, b = left[key], right[key]
167
+ if isinstance(b, dict):
168
+ a, b = b, a
169
+ kind = "number" if isinstance(a, dict) else "literal"
170
+ if kind == "number" and not isinstance(b, dict):
171
+ values = b if isinstance(b, list) else [b]
172
+ b = [value for value in values if type(value) in (int, float)]
173
+ if _intersection(a, b, kind) is None:
174
+ return False
175
+ return True
176
+
177
+
178
+ def validate_standalone_grib2(parameters, mappings):
179
+ """Validate an independent GRIB2 mapping resource and return effective definitions."""
180
+ from .model import Mappings
181
+
182
+ effective = effective_parameters(parameters)
183
+ names = {}
184
+ for pid, definition in effective.items():
185
+ for name in (definition["name"], *definition.get("aliases", ())):
186
+ if names.setdefault(name, pid) != pid:
187
+ _error(
188
+ pointer(("parameters", pid, "aliases")),
189
+ f"ambiguous parameter name or alias {name!r}",
190
+ )
191
+
192
+ mappings = mappings if type(mappings) is Mappings else Mappings(mappings)
193
+ resource = mappings.to_dict()
194
+ if resource["backend"] != "grib2":
195
+ _error("/backend", "standalone mappings require the grib2 backend")
196
+ for index, table in enumerate(resource["tables"]):
197
+ if table["applies_to"]:
198
+ _error(
199
+ f"/tables/{index}/applies_to", "standalone tables require an empty scope"
200
+ )
201
+
202
+ applicable = []
203
+ for index, row in enumerate(resource["mappings"]):
204
+ pid = row["parameter_id"]
205
+ path = f"/mappings/{index}"
206
+ if pid not in effective:
207
+ _error(path + "/parameter_id", "unknown mapped parameter ID")
208
+ if row["applies_to"]:
209
+ _error(path + "/applies_to", "standalone mappings require an empty scope")
210
+ bound = _mapping_conditions(row, effective[pid], path)
211
+ native = row["native"]["match"]
212
+ for other_id, other_native, other_bound in applicable:
213
+ if (
214
+ _native_overlap(native, other_native)
215
+ and intersect_scopes(bound, other_bound) is not None
216
+ ):
217
+ _error(path + "/native/match", f"overlapping standalone mapping {other_id!r}")
218
+ applicable.append((row["id"], native, bound))
219
+ return effective
220
+
221
+
144
222
  def validate_resource_set(parameters, mappings, catalog, dataset_id):
145
223
  """Validate the selected dataset's resource references and return effective definitions."""
146
224
  from .model import Catalog, Mappings
147
225
 
148
226
  effective = effective_parameters(parameters)
149
- datasets = {row["id"]: row for row in Catalog(catalog).to_dict()["datasets"]}
227
+ catalog = catalog if type(catalog) is Catalog else Catalog(catalog)
228
+ datasets = {row["id"]: row for row in catalog.to_dict()["datasets"]}
150
229
  if dataset_id not in datasets:
151
230
  _error("/datasets", "dataset is absent from catalog")
152
231
  products = {
@@ -167,7 +246,12 @@ def validate_resource_set(parameters, mappings, catalog, dataset_id):
167
246
  _error(f"/datasets/products/{key}", "unknown catalog parameter ID")
168
247
 
169
248
  resources = _index(
170
- [Mappings(value).to_dict() for value in mappings], "backend", "/mappings"
249
+ [
250
+ (value if type(value) is Mappings else Mappings(value)).to_dict()
251
+ for value in mappings
252
+ ],
253
+ "backend",
254
+ "/mappings",
171
255
  )
172
256
  applicable = {identity: [] for identity in products}
173
257
  for resource in resources.values():
@@ -190,19 +274,7 @@ def validate_resource_set(parameters, mappings, catalog, dataset_id):
190
274
  path + "/applies_to",
191
275
  "mapping refers to an unavailable product or version",
192
276
  )
193
- fixed = {
194
- k: v
195
- for k, v in effective[pid]["fixed_conditions"].items()
196
- if k != "statistics"
197
- }
198
- try:
199
- bound = constrain_query(row["when"], fixed).to_dict()
200
- except QueryError as exc:
201
- raise QueryError(
202
- "invalid_config",
203
- path + "/when",
204
- "mapping conflicts with parameter conditions",
205
- ) from exc
277
+ bound = _mapping_conditions(row, effective[pid], path)
206
278
  backend = resource["backend"]
207
279
  native = canonical(row["native"]["match"])
208
280
  time_scope = {"time": applies["time"]} if "time" in applies else {}
@@ -265,4 +337,5 @@ def effective_parameters(parameters):
265
337
  """Expand validated parameter definitions for binding."""
266
338
  from .model import Parameters
267
339
 
268
- return _effective(Parameters(parameters).to_dict())
340
+ parameters = parameters if type(parameters) is Parameters else Parameters(parameters)
341
+ return _effective(parameters.to_dict())
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cedarkit-query
3
- Version: 0.2.1
3
+ Version: 0.2.3
4
4
  Summary: Language-neutral CedarKit query value models and schemas
5
5
  License-Expression: Apache-2.0
6
6
  Requires-Python: >=3.11
@@ -0,0 +1,346 @@
1
+ import json
2
+
3
+ import pytest
4
+ from cedarkit_query import (
5
+ Catalog,
6
+ Mappings,
7
+ Parameters,
8
+ QueryError,
9
+ load_prevalidated_resource,
10
+ load_value,
11
+ prepare_queries,
12
+ validate_resource_set,
13
+ validate_standalone_grib2,
14
+ )
15
+ from cedarkit_query import model
16
+ from cedarkit_query.resources import effective_parameters
17
+
18
+ BASE = {"parameter_id": "cedarkit.t", "name": "t", "unit": "K"}
19
+ HEIGHT = {"level_type": "height_above_ground", "level": 2, "level_unit": "m"}
20
+ VARIANT = {
21
+ "parameter_id": "cedarkit.t2m",
22
+ "name": "t2m",
23
+ "parent": "cedarkit.t",
24
+ "fixed_conditions": HEIGHT,
25
+ }
26
+
27
+
28
+ def snapshot(rows):
29
+ return {
30
+ "api_version": "cedarkit.parameters/v1",
31
+ "id": "test.parameters",
32
+ "version": "1",
33
+ "parameters": rows,
34
+ }
35
+
36
+
37
+ def test_prevalidated_resources_match_validated_models(catalog, monkeypatch):
38
+ resources = {
39
+ "catalog": catalog,
40
+ "parameters": snapshot([BASE, VARIANT]),
41
+ "mappings": {
42
+ "api_version": "cedarkit.mappings/v1",
43
+ "id": "test.grib2",
44
+ "version": "1",
45
+ "backend": "grib2",
46
+ "tables": [],
47
+ "mappings": [],
48
+ },
49
+ }
50
+ expected = {kind: load_value(value, kind) for kind, value in resources.items()}
51
+
52
+ def reject_validation(*args):
53
+ pytest.fail("prevalidated resource ran the full validator")
54
+
55
+ monkeypatch.setattr(model, "validate_value", reject_validation)
56
+ for kind, value in resources.items():
57
+ resource = load_prevalidated_resource(json.dumps(value), kind)
58
+ assert resource == expected[kind]
59
+ loaded = resource.to_dict()
60
+ loaded["id"] = "changed"
61
+ assert resource == expected[kind]
62
+ with pytest.raises(AttributeError):
63
+ resource.id = "changed"
64
+
65
+
66
+ @pytest.mark.parametrize(
67
+ "text,code",
68
+ [
69
+ ("[]", "invalid_config"),
70
+ ('{"api_version":"cedarkit.catalog/v2"}', "unsupported_version"),
71
+ (
72
+ '{"api_version":"cedarkit.catalog/v1","api_version":"cedarkit.catalog/v1"}',
73
+ "invalid_config",
74
+ ),
75
+ ],
76
+ )
77
+ def test_prevalidated_resource_checks_json_and_protocol_version(text, code):
78
+ with pytest.raises(QueryError) as caught:
79
+ load_prevalidated_resource(text, "catalog")
80
+ assert caught.value.code == code
81
+
82
+
83
+ def test_parameters_inherit_without_depending_on_record_order():
84
+ parameters = Parameters(snapshot([VARIANT, BASE]))
85
+ index = effective_parameters(parameters)
86
+ assert index["cedarkit.t2m"]["unit"] == "K"
87
+ (query,) = prepare_queries([{"parameter": "t2m"}], index)
88
+ assert query.to_dict() == {"parameter": "cedarkit.t2m", **HEIGHT}
89
+
90
+
91
+ def test_resource_set_reuses_validated_models(monkeypatch):
92
+ parameters = Parameters(snapshot([BASE, VARIANT]))
93
+ product = {
94
+ "id": "original",
95
+ "version": "1",
96
+ "scope": {},
97
+ "provides": [{"parameter": "cedarkit.t2m"}],
98
+ "populations": [],
99
+ "methods": [],
100
+ "evidence": [],
101
+ "sources": [{"id": "file", "kind": "file"}],
102
+ }
103
+ catalog = Catalog(
104
+ {
105
+ "api_version": "cedarkit.catalog/v1",
106
+ "id": "test.catalog",
107
+ "version": "1",
108
+ "datasets": [{"id": "test", "products": [product]}],
109
+ }
110
+ )
111
+ mapping = {
112
+ "id": "t2m",
113
+ "parameter_id": "cedarkit.t2m",
114
+ "backend": "grib2",
115
+ "applies_to": {},
116
+ "when": {},
117
+ "evidence": [],
118
+ "native": {"match": {"shortName": "2t"}},
119
+ }
120
+ mappings = Mappings(
121
+ {
122
+ "api_version": "cedarkit.mappings/v1",
123
+ "id": "test.grib2",
124
+ "version": "1",
125
+ "backend": "grib2",
126
+ "tables": [],
127
+ "mappings": [mapping],
128
+ }
129
+ )
130
+ expected = validate_resource_set(
131
+ parameters.to_dict(), [mappings.to_dict()], catalog.to_dict(), "test"
132
+ )
133
+ validate_value = model.validate_value
134
+
135
+ def reject_revalidation(value, kind):
136
+ assert kind not in {"parameters", "catalog", "mappings"}
137
+ return validate_value(value, kind)
138
+
139
+ monkeypatch.setattr(model, "validate_value", reject_revalidation)
140
+ assert validate_resource_set(parameters, [mappings], catalog, "test") == expected
141
+ with pytest.raises(QueryError, match="dataset is absent"):
142
+ validate_resource_set(parameters, [mappings], catalog, "missing")
143
+
144
+
145
+ @pytest.fixture
146
+ def standalone():
147
+ parameters = snapshot([BASE, {**VARIANT, "aliases": ["2t"]}])
148
+ mappings = {
149
+ "api_version": "cedarkit.mappings/v1",
150
+ "id": "test.generic.grib2",
151
+ "version": "1",
152
+ "backend": "grib2",
153
+ "tables": [],
154
+ "mappings": [
155
+ {
156
+ "id": "t2m",
157
+ "parameter_id": "cedarkit.t2m",
158
+ "backend": "grib2",
159
+ "applies_to": {},
160
+ "when": {},
161
+ "evidence": [],
162
+ "native": {"match": {"tablesVersion": {"range": {"start": 1, "end": 37}}}},
163
+ }
164
+ ],
165
+ }
166
+ return parameters, mappings
167
+
168
+
169
+ def test_standalone_resolves_public_alias_and_inherits_conditions(standalone):
170
+ parameters, mappings = standalone
171
+ effective = validate_standalone_grib2(Parameters(parameters), Mappings(mappings))
172
+ assert effective["cedarkit.t2m"]["unit"] == "K"
173
+ for token in ("cedarkit.t2m", "t2m", "2t"):
174
+ (selected,) = prepare_queries([{"parameter": token}], effective)
175
+ assert selected.to_dict() == {"parameter": "cedarkit.t2m", **HEIGHT}
176
+
177
+
178
+ def test_standalone_rejects_ambiguous_alias(standalone):
179
+ parameters, mappings = standalone
180
+ parameters["parameters"][0] = {**BASE, "aliases": ["2t"]}
181
+ with pytest.raises(QueryError, match="ambiguous parameter name or alias"):
182
+ validate_standalone_grib2(parameters, mappings)
183
+
184
+
185
+ @pytest.mark.parametrize(
186
+ "changes, path",
187
+ [
188
+ ({"parameter_id": "unregistered"}, "/parameter_id"),
189
+ ({"applies_to": {"dataset": "example"}}, "/applies_to"),
190
+ ({"applies_to": {"product": "orig"}}, "/applies_to"),
191
+ ({"applies_to": {"product_version": "current"}}, "/applies_to"),
192
+ ({"applies_to": {"time": "2026-11-02T12:00:00Z"}}, "/applies_to"),
193
+ ({"when": {"level": 10}}, "/when"),
194
+ ],
195
+ )
196
+ def test_standalone_requires_compatible_and_independent_rows(standalone, changes, path):
197
+ parameters, mappings = standalone
198
+ mappings["mappings"][0].update(changes)
199
+ with pytest.raises(QueryError) as caught:
200
+ validate_standalone_grib2(parameters, mappings)
201
+ assert (caught.value.code, caught.value.path) == ("invalid_config", "/mappings/0" + path)
202
+
203
+
204
+ @pytest.mark.parametrize(
205
+ "selector, when, overlaps",
206
+ [
207
+ (4, {}, True),
208
+ ({"range": {"start": 32, "end": 40}}, HEIGHT, True),
209
+ ({"range": {"start": 38, "end": 40}}, {}, False),
210
+ (["32", 38], {}, False),
211
+ (4, {"level_type": "pressure", "level": 850}, False),
212
+ ],
213
+ )
214
+ def test_standalone_checks_native_and_effective_conditions(standalone, selector, when, overlaps):
215
+ parameters, mappings = standalone
216
+ mappings["mappings"].append({
217
+ **mappings["mappings"][0],
218
+ "id": "other",
219
+ "parameter_id": "cedarkit.t",
220
+ "when": when,
221
+ "native": {"match": {"tablesVersion": selector}},
222
+ })
223
+ if overlaps:
224
+ with pytest.raises(QueryError, match="overlapping standalone mapping"):
225
+ validate_standalone_grib2(parameters, mappings)
226
+ else:
227
+ validate_standalone_grib2(parameters, mappings)
228
+
229
+
230
+ @pytest.mark.parametrize(
231
+ "rows,path",
232
+ [
233
+ ([VARIANT], "/parent"),
234
+ ([{**BASE, "parent": "cedarkit.t2m"}, VARIANT], "/parent"),
235
+ ([BASE, BASE], "/parameter_id"),
236
+ (
237
+ [{**BASE, "fixed_conditions": {**HEIGHT, "level": 10}}, VARIANT],
238
+ "/fixed_conditions/level",
239
+ ),
240
+ ],
241
+ )
242
+ def test_invalid_parameter_inheritance_is_rejected(rows, path):
243
+ with pytest.raises(QueryError) as caught:
244
+ Parameters(snapshot(rows))
245
+ assert caught.value.code == "invalid_config"
246
+ assert caught.value.path.endswith(path)
247
+
248
+
249
+ def test_ensemble_statistic_is_a_named_product_not_an_individual_member():
250
+ statistic = {
251
+ "parameter_id": "test.ensemble_temperature",
252
+ "name": "ensemble_temperature",
253
+ "unit": "K",
254
+ "fixed_conditions": {
255
+ "statistics": {
256
+ "over": "ensemble",
257
+ "operation": "mean",
258
+ "of": {"parameter_id": "cedarkit.t"},
259
+ },
260
+ },
261
+ }
262
+ index = effective_parameters(snapshot([BASE, statistic]))
263
+ (query,) = prepare_queries([{"parameter": statistic["name"]}], index)
264
+ assert query.to_dict() == {"parameter": statistic["parameter_id"]}
265
+ with pytest.raises(QueryError) as caught:
266
+ prepare_queries([{"parameter": statistic["name"], "member": 0}], index)
267
+ assert (caught.value.code, caught.value.path) == ("constraint_conflict", "/member")
268
+
269
+
270
+ def test_time_statistic_can_inherit_operation_and_refine_period():
271
+ rain = {
272
+ "parameter_id": "test.rain",
273
+ "name": "rain",
274
+ "unit": "mm",
275
+ "fixed_conditions": {
276
+ "statistics": {"over": "time", "operation": "accumulation"}
277
+ },
278
+ }
279
+ since_initialization = {
280
+ "parameter_id": "test.rain.since-init",
281
+ "name": "rain-since-init",
282
+ "parent": "test.rain",
283
+ "fixed_conditions": {
284
+ "statistics": {"period": {"kind": "since_initialization"}}
285
+ },
286
+ }
287
+ params = effective_parameters(snapshot([since_initialization, rain]))
288
+ assert params["test.rain.since-init"]["fixed_conditions"]["statistics"] == {
289
+ "over": "time",
290
+ "operation": "accumulation",
291
+ "period": {"kind": "since_initialization"},
292
+ }
293
+ since_initialization["fixed_conditions"]["statistics"]["operation"] = "maximum"
294
+ with pytest.raises(QueryError, match="conflicting inherited statistic"):
295
+ Parameters(snapshot([since_initialization, rain]))
296
+
297
+
298
+ @pytest.mark.parametrize(
299
+ "config",
300
+ [
301
+ {},
302
+ {"operation": "accumulation", "period": {"kind": "since_initialization"}},
303
+ {
304
+ "period": {"kind": "trailing", "duration": "PT3H"},
305
+ "response_profile": "derived_grid",
306
+ },
307
+ ],
308
+ )
309
+ def test_service_statistics_config_has_the_same_three_resource_forms(config):
310
+ import yaml
311
+
312
+ resource = {
313
+ "api_version": "cedarkit.mappings/v1",
314
+ "id": "test.service",
315
+ "version": "1",
316
+ "backend": "cmadaas",
317
+ "tables": [],
318
+ "mappings": [
319
+ {
320
+ "id": "rain",
321
+ "backend": "cmadaas",
322
+ "parameter_id": "test.rain",
323
+ "applies_to": {},
324
+ "when": {},
325
+ "native": {
326
+ "match": {"fcstEle": "TPE03"},
327
+ "translate": {
328
+ "statistics": {
329
+ "rule": "cmadaas.statistics_fields",
330
+ "config": config,
331
+ }
332
+ },
333
+ },
334
+ "evidence": ["reviewed service contract"],
335
+ }
336
+ ],
337
+ }
338
+ expected = Mappings(resource)
339
+ assert load_value(json.dumps(resource), "mappings") == expected
340
+ assert load_value(yaml.safe_dump(resource), "mappings", format="yaml") == expected
341
+ if config:
342
+ resource["mappings"][0]["native"]["translate"]["statistics"]["config"][
343
+ "period"
344
+ ] = {"kind": "trailing"}
345
+ with pytest.raises(QueryError):
346
+ Mappings(resource)
@@ -1,5 +0,0 @@
1
- # Use a native request
2
-
3
- Load the request with `Request.load(path)` or build it from a mapping. Use `Query` to set native predicates and optional coordinate constraints. Use `reki.from_source(request.source, context=request.context)` and `source.sel(request.queries)` to execute the selection.
4
-
5
- See [the native protocol](protocol-v1.md) and [the example request](../examples/request.json).
@@ -1,151 +0,0 @@
1
- import pytest
2
- from cedarkit_query import Parameters, QueryError, prepare_queries
3
- from cedarkit_query.resources import effective_parameters
4
-
5
- BASE = {"parameter_id": "cedarkit.t", "name": "t", "unit": "K"}
6
- HEIGHT = {"level_type": "height_above_ground", "level": 2, "level_unit": "m"}
7
- VARIANT = {
8
- "parameter_id": "cedarkit.t2m",
9
- "name": "t2m",
10
- "parent": "cedarkit.t",
11
- "fixed_conditions": HEIGHT,
12
- }
13
-
14
-
15
- def snapshot(rows):
16
- return {
17
- "api_version": "cedarkit.parameters/v1",
18
- "id": "test.parameters",
19
- "version": "1",
20
- "parameters": rows,
21
- }
22
-
23
-
24
- def test_parameters_inherit_without_depending_on_record_order():
25
- parameters = Parameters(snapshot([VARIANT, BASE]))
26
- index = effective_parameters(parameters)
27
- assert index["cedarkit.t2m"]["unit"] == "K"
28
- (query,) = prepare_queries([{"parameter": "t2m"}], index)
29
- assert query.to_dict() == {"parameter": "cedarkit.t2m", **HEIGHT}
30
-
31
-
32
- @pytest.mark.parametrize(
33
- "rows,path",
34
- [
35
- ([VARIANT], "/parent"),
36
- ([{**BASE, "parent": "cedarkit.t2m"}, VARIANT], "/parent"),
37
- ([BASE, BASE], "/parameter_id"),
38
- (
39
- [{**BASE, "fixed_conditions": {**HEIGHT, "level": 10}}, VARIANT],
40
- "/fixed_conditions/level",
41
- ),
42
- ],
43
- )
44
- def test_invalid_parameter_inheritance_is_rejected(rows, path):
45
- with pytest.raises(QueryError) as caught:
46
- Parameters(snapshot(rows))
47
- assert caught.value.code == "invalid_config"
48
- assert caught.value.path.endswith(path)
49
-
50
-
51
- def test_ensemble_statistic_is_a_named_product_not_an_individual_member():
52
- statistic = {
53
- "parameter_id": "test.ensemble_temperature",
54
- "name": "ensemble_temperature",
55
- "unit": "K",
56
- "fixed_conditions": {
57
- "statistics": {
58
- "over": "ensemble",
59
- "operation": "mean",
60
- "of": {"parameter_id": "cedarkit.t"},
61
- },
62
- },
63
- }
64
- index = effective_parameters(snapshot([BASE, statistic]))
65
- (query,) = prepare_queries([{"parameter": statistic["name"]}], index)
66
- assert query.to_dict() == {"parameter": statistic["parameter_id"]}
67
- with pytest.raises(QueryError) as caught:
68
- prepare_queries([{"parameter": statistic["name"], "member": 0}], index)
69
- assert (caught.value.code, caught.value.path) == ("constraint_conflict", "/member")
70
-
71
-
72
- def test_time_statistic_can_inherit_operation_and_refine_period():
73
- rain = {
74
- "parameter_id": "test.rain",
75
- "name": "rain",
76
- "unit": "mm",
77
- "fixed_conditions": {
78
- "statistics": {"over": "time", "operation": "accumulation"}
79
- },
80
- }
81
- since_initialization = {
82
- "parameter_id": "test.rain.since-init",
83
- "name": "rain-since-init",
84
- "parent": "test.rain",
85
- "fixed_conditions": {
86
- "statistics": {"period": {"kind": "since_initialization"}}
87
- },
88
- }
89
- params = effective_parameters(snapshot([since_initialization, rain]))
90
- assert params["test.rain.since-init"]["fixed_conditions"]["statistics"] == {
91
- "over": "time",
92
- "operation": "accumulation",
93
- "period": {"kind": "since_initialization"},
94
- }
95
- since_initialization["fixed_conditions"]["statistics"]["operation"] = "maximum"
96
- with pytest.raises(QueryError, match="conflicting inherited statistic"):
97
- Parameters(snapshot([since_initialization, rain]))
98
-
99
-
100
- @pytest.mark.parametrize(
101
- "config",
102
- [
103
- {},
104
- {"operation": "accumulation", "period": {"kind": "since_initialization"}},
105
- {
106
- "period": {"kind": "trailing", "duration": "PT3H"},
107
- "response_profile": "derived_grid",
108
- },
109
- ],
110
- )
111
- def test_service_statistics_config_has_the_same_three_resource_forms(config):
112
- import json
113
-
114
- import yaml
115
- from cedarkit_query import Mappings, load_value
116
-
117
- resource = {
118
- "api_version": "cedarkit.mappings/v1",
119
- "id": "test.service",
120
- "version": "1",
121
- "backend": "cmadaas",
122
- "tables": [],
123
- "mappings": [
124
- {
125
- "id": "rain",
126
- "backend": "cmadaas",
127
- "parameter_id": "test.rain",
128
- "applies_to": {},
129
- "when": {},
130
- "native": {
131
- "match": {"fcstEle": "TPE03"},
132
- "translate": {
133
- "statistics": {
134
- "rule": "cmadaas.statistics_fields",
135
- "config": config,
136
- }
137
- },
138
- },
139
- "evidence": ["reviewed service contract"],
140
- }
141
- ],
142
- }
143
- expected = Mappings(resource)
144
- assert load_value(json.dumps(resource), "mappings") == expected
145
- assert load_value(yaml.safe_dump(resource), "mappings", format="yaml") == expected
146
- if config:
147
- resource["mappings"][0]["native"]["translate"]["statistics"]["config"][
148
- "period"
149
- ] = {"kind": "trailing"}
150
- with pytest.raises(QueryError):
151
- Mappings(resource)
File without changes
File without changes
File without changes