stac-validator 3.5.0__tar.gz → 3.6.0__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: stac_validator
3
- Version: 3.5.0
3
+ Version: 3.6.0
4
4
  Summary: A package to validate STAC files
5
5
  Home-page: https://github.com/stac-utils/stac-validator
6
6
  Author: James Banting, Jonathan Healy
@@ -110,34 +110,38 @@ stac-validator --help
110
110
  Usage: stac-validator [OPTIONS] STAC_FILE
111
111
 
112
112
  Options:
113
- --core Validate core stac object only without extensions.
114
- --extensions Validate extensions only.
115
- --links Additionally validate links. Only works with
116
- default mode.
117
- --assets Additionally validate assets. Only works with
118
- default mode.
119
- -c, --custom TEXT Validate against a custom schema (local filepath or
120
- remote schema).
121
- -r, --recursive Recursively validate all related stac objects.
122
- -m, --max-depth INTEGER Maximum depth to traverse when recursing. Omit this
123
- argument to get full recursion. Ignored if
124
- `recursive == False`.
125
- --collections Validate /collections response.
126
- --item-collection Validate item collection response. Can be combined
127
- with --pages. Defaults to one page.
128
- --no-assets-urls Disables the opening of href links when validating
129
- assets (enabled by default).
130
- --header KEY VALUE HTTP header to include in the requests. Can be used
131
- multiple times.
132
- -p, --pages INTEGER Maximum number of pages to validate via --item-
133
- collection. Defaults to one page.
134
- -v, --verbose Enables verbose output for recursive mode.
135
- --no_output Do not print output to console.
136
- --log_file TEXT Save full recursive output to log file (local
137
- filepath).
138
- --version Show the version and exit.
139
- --help Show this message and exit.
140
- ```
113
+ --core Validate core stac object only without
114
+ extensions.
115
+ --extensions Validate extensions only.
116
+ --links Additionally validate links. Only works with
117
+ default mode.
118
+ --assets Additionally validate assets. Only works
119
+ with default mode.
120
+ -c, --custom TEXT Validate against a custom schema (local
121
+ filepath or remote schema).
122
+ -s, --schema-map <TEXT TEXT>...
123
+ Schema path to replaced by (local) schema
124
+ path during validation. Can be used multiple
125
+ times.
126
+ -r, --recursive Recursively validate all related stac
127
+ objects.
128
+ -m, --max-depth INTEGER Maximum depth to traverse when recursing.
129
+ Omit this argument to get full recursion.
130
+ Ignored if `recursive == False`.
131
+ --collections Validate /collections response.
132
+ --item-collection Validate item collection response. Can be
133
+ combined with --pages. Defaults to one page.
134
+ --no-assets-urls Disables the opening of href links when
135
+ validating assets (enabled by default).
136
+ --header <TEXT TEXT>... HTTP header to include in the requests. Can
137
+ be used multiple times.
138
+ -p, --pages INTEGER Maximum number of pages to validate via
139
+ --item-collection. Defaults to one page.
140
+ -v, --verbose Enables verbose output for recursive mode.
141
+ --no_output Do not print output to console.
142
+ --log_file TEXT Save full recursive output to log file
143
+ (local filepath).
144
+ --help Show this message and exit.```
141
145
 
142
146
  ---
143
147
 
@@ -359,3 +363,47 @@ stac-validator https://earth-search.aws.element84.com/v0/collections/sentinel-s2
359
363
  ```bash
360
364
  stac-validator https://stac-catalog.eu/collections/sentinel-s2-l2a/items --header x-api-key $MY_API_KEY --header foo bar
361
365
  ```
366
+
367
+ **--schema-map**
368
+ Schema map allows stac-validator to replace a schema in a STAC json by a schema from another URL or local schema file.
369
+ This is especially useful when developing a schema and testing validation against your local copy of the schema.
370
+
371
+ ``` bash
372
+ stac-validator https://raw.githubusercontent.com/radiantearth/stac-spec/master/examples/extended-item.json --extensions --schema-map https://stac-extensions.github.io/projection/v1.0.0/schema.json stac-validator https://raw.githubusercontent.com/radiantearth/stac-spec/v1.0.0/examples/extended-item.json --extensions --schema-map https://stac-extensions.github.io/projection/v1.0.0/schema.json "tests/test_data/schema/v1.0.0/projection.json"
373
+ [
374
+ {
375
+ "version": "1.0.0",
376
+ "path": "https://raw.githubusercontent.com/radiantearth/stac-spec/v1.0.0/examples/extended-item.json",
377
+ "schema": [
378
+ "https://stac-extensions.github.io/eo/v1.0.0/schema.json",
379
+ "tests/test_data/schema/v1.0.0/projection.json",
380
+ "https://stac-extensions.github.io/scientific/v1.0.0/schema.json",
381
+ "https://stac-extensions.github.io/view/v1.0.0/schema.json",
382
+ "https://stac-extensions.github.io/remote-data/v1.0.0/schema.json"
383
+ ],
384
+ "valid_stac": true,
385
+ "asset_type": "ITEM",
386
+ "validation_method": "extensions"
387
+ }
388
+ ]
389
+ ```
390
+
391
+ This option is also capable of replacing URLs to subschemas:
392
+
393
+ ```bash
394
+ stac-validator tests/test_data/v100/extended-item-local.json --custom tests/test_data/schema/v1.0.0/item_with_unreachable_url.json --schema-map https://geojson-wrong-url.org/schema/Feature.json https://geojson.org/schema/Feature.json --schema-map https://geojson-wrong-url.org/schema/Geometry.json https://geojson.org/schema/Geometry.json
395
+ [
396
+ {
397
+ "version": "1.0.0",
398
+ "path": "tests/test_data/v100/extended-item-local.json",
399
+ "schema": [
400
+ "tests/test_data/schema/v1.0.0/item_with_unreachable_url.json"
401
+ ],
402
+ "valid_stac": true,
403
+ "asset_type": "ITEM",
404
+ "validation_method": "custom"
405
+ }
406
+ ]
407
+ ```
408
+
409
+
@@ -91,34 +91,38 @@ stac-validator --help
91
91
  Usage: stac-validator [OPTIONS] STAC_FILE
92
92
 
93
93
  Options:
94
- --core Validate core stac object only without extensions.
95
- --extensions Validate extensions only.
96
- --links Additionally validate links. Only works with
97
- default mode.
98
- --assets Additionally validate assets. Only works with
99
- default mode.
100
- -c, --custom TEXT Validate against a custom schema (local filepath or
101
- remote schema).
102
- -r, --recursive Recursively validate all related stac objects.
103
- -m, --max-depth INTEGER Maximum depth to traverse when recursing. Omit this
104
- argument to get full recursion. Ignored if
105
- `recursive == False`.
106
- --collections Validate /collections response.
107
- --item-collection Validate item collection response. Can be combined
108
- with --pages. Defaults to one page.
109
- --no-assets-urls Disables the opening of href links when validating
110
- assets (enabled by default).
111
- --header KEY VALUE HTTP header to include in the requests. Can be used
112
- multiple times.
113
- -p, --pages INTEGER Maximum number of pages to validate via --item-
114
- collection. Defaults to one page.
115
- -v, --verbose Enables verbose output for recursive mode.
116
- --no_output Do not print output to console.
117
- --log_file TEXT Save full recursive output to log file (local
118
- filepath).
119
- --version Show the version and exit.
120
- --help Show this message and exit.
121
- ```
94
+ --core Validate core stac object only without
95
+ extensions.
96
+ --extensions Validate extensions only.
97
+ --links Additionally validate links. Only works with
98
+ default mode.
99
+ --assets Additionally validate assets. Only works
100
+ with default mode.
101
+ -c, --custom TEXT Validate against a custom schema (local
102
+ filepath or remote schema).
103
+ -s, --schema-map <TEXT TEXT>...
104
+ Schema path to replaced by (local) schema
105
+ path during validation. Can be used multiple
106
+ times.
107
+ -r, --recursive Recursively validate all related stac
108
+ objects.
109
+ -m, --max-depth INTEGER Maximum depth to traverse when recursing.
110
+ Omit this argument to get full recursion.
111
+ Ignored if `recursive == False`.
112
+ --collections Validate /collections response.
113
+ --item-collection Validate item collection response. Can be
114
+ combined with --pages. Defaults to one page.
115
+ --no-assets-urls Disables the opening of href links when
116
+ validating assets (enabled by default).
117
+ --header <TEXT TEXT>... HTTP header to include in the requests. Can
118
+ be used multiple times.
119
+ -p, --pages INTEGER Maximum number of pages to validate via
120
+ --item-collection. Defaults to one page.
121
+ -v, --verbose Enables verbose output for recursive mode.
122
+ --no_output Do not print output to console.
123
+ --log_file TEXT Save full recursive output to log file
124
+ (local filepath).
125
+ --help Show this message and exit.```
122
126
 
123
127
  ---
124
128
 
@@ -340,3 +344,47 @@ stac-validator https://earth-search.aws.element84.com/v0/collections/sentinel-s2
340
344
  ```bash
341
345
  stac-validator https://stac-catalog.eu/collections/sentinel-s2-l2a/items --header x-api-key $MY_API_KEY --header foo bar
342
346
  ```
347
+
348
+ **--schema-map**
349
+ Schema map allows stac-validator to replace a schema in a STAC json by a schema from another URL or local schema file.
350
+ This is especially useful when developing a schema and testing validation against your local copy of the schema.
351
+
352
+ ``` bash
353
+ stac-validator https://raw.githubusercontent.com/radiantearth/stac-spec/master/examples/extended-item.json --extensions --schema-map https://stac-extensions.github.io/projection/v1.0.0/schema.json stac-validator https://raw.githubusercontent.com/radiantearth/stac-spec/v1.0.0/examples/extended-item.json --extensions --schema-map https://stac-extensions.github.io/projection/v1.0.0/schema.json "tests/test_data/schema/v1.0.0/projection.json"
354
+ [
355
+ {
356
+ "version": "1.0.0",
357
+ "path": "https://raw.githubusercontent.com/radiantearth/stac-spec/v1.0.0/examples/extended-item.json",
358
+ "schema": [
359
+ "https://stac-extensions.github.io/eo/v1.0.0/schema.json",
360
+ "tests/test_data/schema/v1.0.0/projection.json",
361
+ "https://stac-extensions.github.io/scientific/v1.0.0/schema.json",
362
+ "https://stac-extensions.github.io/view/v1.0.0/schema.json",
363
+ "https://stac-extensions.github.io/remote-data/v1.0.0/schema.json"
364
+ ],
365
+ "valid_stac": true,
366
+ "asset_type": "ITEM",
367
+ "validation_method": "extensions"
368
+ }
369
+ ]
370
+ ```
371
+
372
+ This option is also capable of replacing URLs to subschemas:
373
+
374
+ ```bash
375
+ stac-validator tests/test_data/v100/extended-item-local.json --custom tests/test_data/schema/v1.0.0/item_with_unreachable_url.json --schema-map https://geojson-wrong-url.org/schema/Feature.json https://geojson.org/schema/Feature.json --schema-map https://geojson-wrong-url.org/schema/Geometry.json https://geojson.org/schema/Geometry.json
376
+ [
377
+ {
378
+ "version": "1.0.0",
379
+ "path": "tests/test_data/v100/extended-item-local.json",
380
+ "schema": [
381
+ "tests/test_data/schema/v1.0.0/item_with_unreachable_url.json"
382
+ ],
383
+ "valid_stac": true,
384
+ "asset_type": "ITEM",
385
+ "validation_method": "custom"
386
+ }
387
+ ]
388
+ ```
389
+
390
+
@@ -2,7 +2,7 @@
2
2
 
3
3
  from setuptools import setup
4
4
 
5
- __version__ = "3.5.0"
5
+ __version__ = "3.6.0"
6
6
 
7
7
  with open("README.md", "r") as fh:
8
8
  long_description = fh.read()
@@ -1,6 +1,6 @@
1
1
  import json
2
2
  import sys
3
- from typing import Any, Dict, List
3
+ from typing import Any, Dict, List, Optional, Tuple
4
4
 
5
5
  import click # type: ignore
6
6
 
@@ -87,6 +87,13 @@ def collections_summary(message: List[Dict[str, Any]]) -> None:
87
87
  default="",
88
88
  help="Validate against a custom schema (local filepath or remote schema).",
89
89
  )
90
+ @click.option(
91
+ "--schema-map",
92
+ "-s",
93
+ type=(str, str),
94
+ multiple=True,
95
+ help="Schema path to replaced by (local) schema path during validation. Can be used multiple times.",
96
+ )
90
97
  @click.option(
91
98
  "--recursive",
92
99
  "-r",
@@ -149,6 +156,7 @@ def main(
149
156
  links: bool,
150
157
  assets: bool,
151
158
  custom: str,
159
+ schema_map: List[Tuple],
152
160
  verbose: bool,
153
161
  no_output: bool,
154
162
  log_file: str,
@@ -170,6 +178,7 @@ def main(
170
178
  links (bool): Whether to additionally validate links. Only works with default mode.
171
179
  assets (bool): Whether to additionally validate assets. Only works with default mode.
172
180
  custom (str): Path to a custom schema file to validate against.
181
+ schema_map (list(tuple)): List of tuples each having two elememts. First element is the schema path to be replaced by the path in the second element.
173
182
  verbose (bool): Whether to enable verbose output for recursive mode.
174
183
  no_output (bool): Whether to print output to console.
175
184
  log_file (str): Path to a log file to save full recursive output.
@@ -182,6 +191,10 @@ def main(
182
191
  or 1 if it is invalid.
183
192
  """
184
193
  valid = True
194
+ if schema_map == ():
195
+ schema_map_dict: Optional[Dict[str, str]] = None
196
+ else:
197
+ schema_map_dict = dict(schema_map)
185
198
  stac = StacValidate(
186
199
  stac_file=stac_file,
187
200
  collections=collections,
@@ -196,6 +209,7 @@ def main(
196
209
  headers=dict(header),
197
210
  extensions=extensions,
198
211
  custom=custom,
212
+ schema_map=schema_map_dict,
199
213
  verbose=verbose,
200
214
  log=log_file,
201
215
  )
@@ -5,12 +5,10 @@ from typing import Dict, Optional
5
5
  from urllib.parse import urlparse
6
6
  from urllib.request import Request, urlopen
7
7
 
8
- import jsonschema
9
8
  import requests # type: ignore
10
9
  from jsonschema import Draft202012Validator
11
10
  from referencing import Registry, Resource
12
11
  from referencing.jsonschema import DRAFT202012
13
- from referencing.retrieval import to_cached_resource
14
12
  from referencing.typing import URI
15
13
 
16
14
  NEW_VERSIONS = [
@@ -192,60 +190,58 @@ def link_request(
192
190
  initial_message["format_invalid"].append(link["href"])
193
191
 
194
192
 
195
- def fetch_remote_schema(uri: str) -> dict:
193
+ def cached_retrieve(uri: URI, schema_map: Optional[Dict] = None) -> Resource[Dict]:
196
194
  """
197
- Fetch a remote schema from a URI.
195
+ Retrieve and cache a remote schema.
198
196
 
199
197
  Args:
200
- uri (str): The URI of the schema to fetch.
198
+ uri (str): The URI of the schema.
199
+ schema_map_keys: Override schema location to validate against local versions of a schema
201
200
 
202
201
  Returns:
203
- dict: The fetched schema content as a dictionary.
202
+ dict: The parsed JSON dict of the schema.
204
203
 
205
204
  Raises:
206
205
  requests.RequestException: If the request to fetch the schema fails.
206
+ Exception: For any other unexpected errors.
207
207
  """
208
- response = requests.get(uri)
209
- response.raise_for_status()
210
- return response.json()
208
+ return Resource.from_contents(
209
+ fetch_schema_with_override(uri, schema_map=schema_map)
210
+ )
211
211
 
212
212
 
213
- @to_cached_resource() # type: ignore
214
- def cached_retrieve(uri: URI) -> str:
213
+ def fetch_schema_with_override(
214
+ schema_path: str, schema_map: Optional[Dict] = None
215
+ ) -> Dict:
215
216
  """
216
217
  Retrieve and cache a remote schema.
217
218
 
218
219
  Args:
219
- uri (str): The URI of the schema.
220
+ schema_path (str): Path or URI of the schema.
221
+ schema_map (dict): Override schema location to validate against local versions of a schema
220
222
 
221
223
  Returns:
222
- str: The raw JSON string of the schema.
223
-
224
- Raises:
225
- requests.RequestException: If the request to fetch the schema fails.
226
- Exception: For any other unexpected errors.
224
+ dict: The parsed JSON dict of the schema.
227
225
  """
228
- try:
229
- response = requests.get(uri, timeout=10) # Set a timeout for robustness
230
- response.raise_for_status() # Raise an error for HTTP response codes >= 400
231
- return response.text
232
- except requests.exceptions.RequestException as e:
233
- raise requests.RequestException(
234
- f"Failed to fetch schema from {uri}: {str(e)}"
235
- ) from e
236
- except Exception as e:
237
- raise Exception(
238
- f"Unexpected error while retrieving schema from {uri}: {str(e)}"
239
- ) from e
240
-
241
-
242
- def validate_with_ref_resolver(schema_path: str, content: dict) -> None:
226
+
227
+ if schema_map:
228
+ if schema_path in schema_map:
229
+ schema_path = schema_map[schema_path]
230
+
231
+ # Load the schema
232
+ return fetch_and_parse_schema(schema_path)
233
+
234
+
235
+ def validate_with_ref_resolver(
236
+ schema_path: str, content: Dict, schema_map: Optional[Dict] = None
237
+ ) -> None:
243
238
  """
244
239
  Validate a JSON document against a JSON Schema with dynamic reference resolution.
245
240
 
246
241
  Args:
247
242
  schema_path (str): Path or URI of the JSON Schema.
248
243
  content (dict): JSON content to validate.
244
+ schema_map (dict): Override schema location to validate against local versions of a schema
249
245
 
250
246
  Raises:
251
247
  jsonschema.exceptions.ValidationError: If validation fails.
@@ -253,27 +249,16 @@ def validate_with_ref_resolver(schema_path: str, content: dict) -> None:
253
249
  FileNotFoundError: If a local schema file is not found.
254
250
  Exception: If any other error occurs during validation.
255
251
  """
256
- # Load the schema
257
- if schema_path.startswith("http"):
258
- schema = fetch_remote_schema(schema_path)
259
- else:
260
- try:
261
- with open(schema_path, "r") as f:
262
- schema = json.load(f)
263
- except FileNotFoundError as e:
264
- raise FileNotFoundError(f"Schema file not found: {schema_path}") from e
265
-
252
+ schema = fetch_schema_with_override(schema_path, schema_map=schema_map)
266
253
  # Set up the resource and registry for schema resolution
254
+ cached_retrieve_with_schema_map = functools.partial(
255
+ cached_retrieve, schema_map=schema_map
256
+ )
267
257
  resource: Resource = Resource(contents=schema, specification=DRAFT202012) # type: ignore
268
- registry: Registry = Registry(retrieve=cached_retrieve).with_resource( # type: ignore
258
+ registry: Registry = Registry(retrieve=cached_retrieve_with_schema_map).with_resource( # type: ignore
269
259
  uri=schema_path, resource=resource
270
260
  ) # type: ignore
271
261
 
272
262
  # Validate the content against the schema
273
- try:
274
- validator = Draft202012Validator(schema, registry=registry)
275
- validator.validate(content)
276
- except jsonschema.exceptions.ValidationError as e:
277
- raise jsonschema.exceptions.ValidationError(f"{e.message}") from e
278
- except Exception as e:
279
- raise Exception(f"Unexpected error during validation: {str(e)}") from e
263
+ validator = Draft202012Validator(schema, registry=registry)
264
+ validator.validate(content)
@@ -6,6 +6,7 @@ from urllib.error import HTTPError, URLError
6
6
 
7
7
  import click # type: ignore
8
8
  import jsonschema # type: ignore
9
+ from jsonschema.exceptions import best_match
9
10
  from requests import exceptions # type: ignore
10
11
 
11
12
  from .utilities import (
@@ -60,6 +61,7 @@ class StacValidate:
60
61
  headers: dict = {},
61
62
  extensions: bool = False,
62
63
  custom: str = "",
64
+ schema_map: Optional[Dict[str, str]] = None,
63
65
  verbose: bool = False,
64
66
  log: str = "",
65
67
  ):
@@ -68,7 +70,8 @@ class StacValidate:
68
70
  self.item_collection = item_collection
69
71
  self.pages = pages
70
72
  self.message: List = []
71
- self.schema = custom
73
+ self._schema = custom
74
+ self.schema_map = schema_map
72
75
  self.links = links
73
76
  self.assets = assets
74
77
  self.assets_open_urls = assets_open_urls
@@ -85,6 +88,17 @@ class StacValidate:
85
88
  self.valid = False
86
89
  self.log = log
87
90
 
91
+ @property
92
+ def schema(self) -> str:
93
+ return self._schema
94
+
95
+ @schema.setter
96
+ def schema(self, schema_path: str):
97
+ if self.schema_map:
98
+ if schema_path in self.schema_map:
99
+ schema_path = self.schema_map[schema_path]
100
+ self._schema = schema_path
101
+
88
102
  def create_err_msg(self, err_type: str, err_msg: str) -> Dict:
89
103
  """
90
104
  Create a standardized error message dictionary and mark validation as failed.
@@ -197,14 +211,20 @@ class StacValidate:
197
211
  None
198
212
  """
199
213
  if is_valid_url(self.schema):
200
- validate_with_ref_resolver(self.schema, self.stac_content)
214
+ validate_with_ref_resolver(
215
+ self.schema, self.stac_content, schema_map=self.schema_map
216
+ )
201
217
  elif os.path.exists(self.schema):
202
- validate_with_ref_resolver(self.schema, self.stac_content)
218
+ validate_with_ref_resolver(
219
+ self.schema, self.stac_content, schema_map=self.schema_map
220
+ )
203
221
  else:
204
222
  file_directory = os.path.dirname(os.path.abspath(str(self.stac_file)))
205
- self.schema = os.path.join(file_directory, self.schema)
206
- self.schema = os.path.abspath(os.path.realpath(self.schema))
207
- validate_with_ref_resolver(self.schema, self.stac_content)
223
+ schema = os.path.join(file_directory, self.schema)
224
+ schema = os.path.abspath(os.path.realpath(schema))
225
+ validate_with_ref_resolver(
226
+ schema, self.stac_content, schema_map=self.schema_map
227
+ )
208
228
 
209
229
  def core_validator(self, stac_type: str) -> None:
210
230
  """
@@ -215,7 +235,9 @@ class StacValidate:
215
235
  """
216
236
  stac_type = stac_type.lower()
217
237
  self.schema = set_schema_addr(self.version, stac_type)
218
- validate_with_ref_resolver(self.schema, self.stac_content)
238
+ validate_with_ref_resolver(
239
+ self.schema, self.stac_content, schema_map=self.schema_map
240
+ )
219
241
 
220
242
  def extensions_validator(self, stac_type: str) -> Dict:
221
243
  """
@@ -231,49 +253,58 @@ class StacValidate:
231
253
  message["schema"] = []
232
254
  valid = True
233
255
 
234
- if stac_type == "ITEM":
235
- try:
236
- if "stac_extensions" in self.stac_content:
237
- # Handle legacy "proj" to "projection" mapping
238
- if "proj" in self.stac_content["stac_extensions"]:
239
- index = self.stac_content["stac_extensions"].index("proj")
240
- self.stac_content["stac_extensions"][index] = "projection"
241
-
242
- schemas = self.stac_content["stac_extensions"]
243
- for extension in schemas:
244
- if not (is_valid_url(extension) or extension.endswith(".json")):
245
- if self.version == "1.0.0-beta.2":
246
- self.stac_content["stac_version"] = "1.0.0-beta.1"
247
- self.version = self.stac_content["stac_version"]
248
- extension = (
249
- f"https://cdn.staclint.com/v{self.version}/extension/"
250
- f"{extension}.json"
251
- )
252
- self.schema = extension
253
- self.custom_validator()
254
- message["schema"].append(extension)
256
+ try:
257
+ if (
258
+ "stac_extensions" in self.stac_content
259
+ and len(self.stac_content["stac_extensions"]) > 0
260
+ ):
261
+ # Handle legacy "proj" to "projection" mapping
262
+ if "proj" in self.stac_content["stac_extensions"]:
263
+ index = self.stac_content["stac_extensions"].index("proj")
264
+ self.stac_content["stac_extensions"][index] = "projection"
265
+
266
+ schemas = self.stac_content["stac_extensions"]
267
+ for extension in schemas:
268
+ if not (is_valid_url(extension) or extension.endswith(".json")):
269
+ if self.version == "1.0.0-beta.2":
270
+ self.stac_content["stac_version"] = "1.0.0-beta.1"
271
+ self.version = self.stac_content["stac_version"]
272
+ extension = (
273
+ f"https://cdn.staclint.com/v{self.version}/extension/"
274
+ f"{extension}.json"
275
+ )
276
+ self.schema = extension
277
+ self.custom_validator()
278
+ message["schema"].append(self.schema)
279
+ else:
280
+ self.core_validator(stac_type)
281
+ message["schema"] = [self.schema]
255
282
 
256
- except jsonschema.exceptions.ValidationError as e:
257
- valid = False
258
- if e.absolute_path:
259
- err_msg = (
260
- f"{e.message}. Error is in "
261
- f"{' -> '.join(map(str, e.absolute_path))}"
262
- )
263
- else:
264
- err_msg = f"{e.message}"
265
- message = self.create_err_msg("JSONSchemaValidationError", err_msg)
266
- return message
283
+ except jsonschema.exceptions.ValidationError as e:
284
+ if self.recursive:
285
+ raise
286
+ if e.context:
287
+ e = best_match(e.context) # type: ignore
288
+ valid = False
289
+ if e.absolute_path:
290
+ err_msg = (
291
+ f"{e.message}. Error is in "
292
+ f"{' -> '.join(map(str, e.absolute_path))}"
293
+ )
294
+ else:
295
+ err_msg = f"{e.message}"
296
+ message = self.create_err_msg("JSONSchemaValidationError", err_msg)
297
+ return message
267
298
 
268
- except Exception as e:
269
- valid = False
270
- err_msg = f"{e}. Error in Extensions."
271
- return self.create_err_msg("Exception", err_msg)
272
- else:
273
- self.core_validator(stac_type)
274
- message["schema"] = [self.schema]
299
+ except Exception as e:
300
+ if self.recursive:
301
+ raise
302
+ valid = False
303
+ err_msg = f"{e}. Error in Extensions."
304
+ return self.create_err_msg("Exception", err_msg)
275
305
 
276
306
  self.valid = valid
307
+ message["valid_stac"] = valid
277
308
  return message
278
309
 
279
310
  def default_validator(self, stac_type: str) -> Dict:
@@ -292,14 +323,16 @@ class StacValidate:
292
323
  # Validate core
293
324
  self.core_validator(stac_type)
294
325
  core_schema = self.schema
295
- message["schema"].append(core_schema)
326
+ if core_schema not in message["schema"]:
327
+ message["schema"].append(core_schema)
296
328
  stac_upper = stac_type.upper()
297
329
 
298
330
  # Validate extensions if ITEM
299
- if stac_upper == "ITEM":
331
+ if stac_upper == "ITEM" or stac_upper == "COLLECTION":
300
332
  message = self.extensions_validator(stac_upper)
301
333
  message["validation_method"] = "default"
302
- message["schema"].append(core_schema)
334
+ if core_schema not in message["schema"]:
335
+ message["schema"].append(core_schema)
303
336
 
304
337
  # Optionally validate links
305
338
  if self.links:
@@ -323,14 +356,19 @@ class StacValidate:
323
356
  Returns:
324
357
  bool: True if all validations are successful, False otherwise.
325
358
  """
359
+ valid = False
326
360
  if not self.skip_val:
327
361
  self.schema = set_schema_addr(self.version, stac_type.lower())
328
362
  message = self.create_message(stac_type, "recursive")
329
363
  message["valid_stac"] = False
330
364
 
331
365
  try:
332
- _ = self.default_validator(stac_type)
366
+ msg = self.default_validator(stac_type)
367
+ message["schema"] = msg["schema"]
368
+
333
369
  except jsonschema.exceptions.ValidationError as e:
370
+ if e.context:
371
+ e = best_match(e.context) # type: ignore
334
372
  if e.absolute_path:
335
373
  err_msg = (
336
374
  f"{e.message}. Error is in "
@@ -344,9 +382,10 @@ class StacValidate:
344
382
  self.message.append(message)
345
383
  if self.verbose:
346
384
  click.echo(json.dumps(message, indent=4))
347
- return False
385
+ return valid
348
386
 
349
- message["valid_stac"] = True
387
+ valid = True
388
+ message["valid_stac"] = valid
350
389
  self.message.append(message)
351
390
  if self.verbose:
352
391
  click.echo(json.dumps(message, indent=4))
@@ -357,6 +396,7 @@ class StacValidate:
357
396
 
358
397
  base_url = self.stac_file
359
398
 
399
+ child_validity = []
360
400
  for link in self.stac_content["links"]:
361
401
  if link["rel"] in ("child", "item"):
362
402
  address = link["href"]
@@ -377,7 +417,9 @@ class StacValidate:
377
417
  stac_type = get_stac_type(self.stac_content).lower()
378
418
 
379
419
  if link["rel"] == "child":
380
- self.recursive_validator(stac_type)
420
+ if not self.skip_val:
421
+ valid_child = self.recursive_validator(stac_type)
422
+ child_validity.append(valid_child)
381
423
 
382
424
  if link["rel"] == "item":
383
425
  self.schema = set_schema_addr(self.version, stac_type.lower())
@@ -396,8 +438,11 @@ class StacValidate:
396
438
  self.message.append(message)
397
439
  if not self.max_depth or self.max_depth < 5:
398
440
  self.message.append(message)
399
-
400
- return True
441
+ if all(child_validity):
442
+ valid = True
443
+ else:
444
+ valid = False
445
+ return valid
401
446
 
402
447
  def validate_dict(self, stac_content: Dict) -> bool:
403
448
  """
@@ -558,4 +603,12 @@ class StacValidate:
558
603
  with open(self.log, "w") as f:
559
604
  f.write(json.dumps(self.message, indent=4))
560
605
 
606
+ # filter message to only show errors if valid is False unless verbose mode is on
607
+ if self.recursive and not self.valid and not self.verbose:
608
+ filtered_messages = []
609
+ for message in self.message:
610
+ if not message["valid_stac"]:
611
+ filtered_messages.append(message)
612
+ self.message = filtered_messages
613
+
561
614
  return self.valid
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: stac-validator
3
- Version: 3.5.0
3
+ Version: 3.6.0
4
4
  Summary: A package to validate STAC files
5
5
  Home-page: https://github.com/stac-utils/stac-validator
6
6
  Author: James Banting, Jonathan Healy
@@ -110,34 +110,38 @@ stac-validator --help
110
110
  Usage: stac-validator [OPTIONS] STAC_FILE
111
111
 
112
112
  Options:
113
- --core Validate core stac object only without extensions.
114
- --extensions Validate extensions only.
115
- --links Additionally validate links. Only works with
116
- default mode.
117
- --assets Additionally validate assets. Only works with
118
- default mode.
119
- -c, --custom TEXT Validate against a custom schema (local filepath or
120
- remote schema).
121
- -r, --recursive Recursively validate all related stac objects.
122
- -m, --max-depth INTEGER Maximum depth to traverse when recursing. Omit this
123
- argument to get full recursion. Ignored if
124
- `recursive == False`.
125
- --collections Validate /collections response.
126
- --item-collection Validate item collection response. Can be combined
127
- with --pages. Defaults to one page.
128
- --no-assets-urls Disables the opening of href links when validating
129
- assets (enabled by default).
130
- --header KEY VALUE HTTP header to include in the requests. Can be used
131
- multiple times.
132
- -p, --pages INTEGER Maximum number of pages to validate via --item-
133
- collection. Defaults to one page.
134
- -v, --verbose Enables verbose output for recursive mode.
135
- --no_output Do not print output to console.
136
- --log_file TEXT Save full recursive output to log file (local
137
- filepath).
138
- --version Show the version and exit.
139
- --help Show this message and exit.
140
- ```
113
+ --core Validate core stac object only without
114
+ extensions.
115
+ --extensions Validate extensions only.
116
+ --links Additionally validate links. Only works with
117
+ default mode.
118
+ --assets Additionally validate assets. Only works
119
+ with default mode.
120
+ -c, --custom TEXT Validate against a custom schema (local
121
+ filepath or remote schema).
122
+ -s, --schema-map <TEXT TEXT>...
123
+ Schema path to replaced by (local) schema
124
+ path during validation. Can be used multiple
125
+ times.
126
+ -r, --recursive Recursively validate all related stac
127
+ objects.
128
+ -m, --max-depth INTEGER Maximum depth to traverse when recursing.
129
+ Omit this argument to get full recursion.
130
+ Ignored if `recursive == False`.
131
+ --collections Validate /collections response.
132
+ --item-collection Validate item collection response. Can be
133
+ combined with --pages. Defaults to one page.
134
+ --no-assets-urls Disables the opening of href links when
135
+ validating assets (enabled by default).
136
+ --header <TEXT TEXT>... HTTP header to include in the requests. Can
137
+ be used multiple times.
138
+ -p, --pages INTEGER Maximum number of pages to validate via
139
+ --item-collection. Defaults to one page.
140
+ -v, --verbose Enables verbose output for recursive mode.
141
+ --no_output Do not print output to console.
142
+ --log_file TEXT Save full recursive output to log file
143
+ (local filepath).
144
+ --help Show this message and exit.```
141
145
 
142
146
  ---
143
147
 
@@ -359,3 +363,47 @@ stac-validator https://earth-search.aws.element84.com/v0/collections/sentinel-s2
359
363
  ```bash
360
364
  stac-validator https://stac-catalog.eu/collections/sentinel-s2-l2a/items --header x-api-key $MY_API_KEY --header foo bar
361
365
  ```
366
+
367
+ **--schema-map**
368
+ Schema map allows stac-validator to replace a schema in a STAC json by a schema from another URL or local schema file.
369
+ This is especially useful when developing a schema and testing validation against your local copy of the schema.
370
+
371
+ ``` bash
372
+ stac-validator https://raw.githubusercontent.com/radiantearth/stac-spec/master/examples/extended-item.json --extensions --schema-map https://stac-extensions.github.io/projection/v1.0.0/schema.json stac-validator https://raw.githubusercontent.com/radiantearth/stac-spec/v1.0.0/examples/extended-item.json --extensions --schema-map https://stac-extensions.github.io/projection/v1.0.0/schema.json "tests/test_data/schema/v1.0.0/projection.json"
373
+ [
374
+ {
375
+ "version": "1.0.0",
376
+ "path": "https://raw.githubusercontent.com/radiantearth/stac-spec/v1.0.0/examples/extended-item.json",
377
+ "schema": [
378
+ "https://stac-extensions.github.io/eo/v1.0.0/schema.json",
379
+ "tests/test_data/schema/v1.0.0/projection.json",
380
+ "https://stac-extensions.github.io/scientific/v1.0.0/schema.json",
381
+ "https://stac-extensions.github.io/view/v1.0.0/schema.json",
382
+ "https://stac-extensions.github.io/remote-data/v1.0.0/schema.json"
383
+ ],
384
+ "valid_stac": true,
385
+ "asset_type": "ITEM",
386
+ "validation_method": "extensions"
387
+ }
388
+ ]
389
+ ```
390
+
391
+ This option is also capable of replacing URLs to subschemas:
392
+
393
+ ```bash
394
+ stac-validator tests/test_data/v100/extended-item-local.json --custom tests/test_data/schema/v1.0.0/item_with_unreachable_url.json --schema-map https://geojson-wrong-url.org/schema/Feature.json https://geojson.org/schema/Feature.json --schema-map https://geojson-wrong-url.org/schema/Geometry.json https://geojson.org/schema/Geometry.json
395
+ [
396
+ {
397
+ "version": "1.0.0",
398
+ "path": "tests/test_data/v100/extended-item-local.json",
399
+ "schema": [
400
+ "tests/test_data/schema/v1.0.0/item_with_unreachable_url.json"
401
+ ],
402
+ "valid_stac": true,
403
+ "asset_type": "ITEM",
404
+ "validation_method": "custom"
405
+ }
406
+ ]
407
+ ```
408
+
409
+
File without changes
File without changes