stac-validator 3.3.2__tar.gz → 3.5.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.
Files changed (27) hide show
  1. {stac_validator-3.3.2 → stac_validator-3.5.0}/PKG-INFO +31 -25
  2. {stac_validator-3.3.2 → stac_validator-3.5.0}/README.md +26 -15
  3. {stac_validator-3.3.2 → stac_validator-3.5.0}/setup.py +11 -9
  4. {stac_validator-3.3.2 → stac_validator-3.5.0}/stac_validator/stac_validator.py +52 -4
  5. {stac_validator-3.3.2 → stac_validator-3.5.0}/stac_validator/utilities.py +115 -15
  6. {stac_validator-3.3.2 → stac_validator-3.5.0}/stac_validator/validate.py +221 -176
  7. {stac_validator-3.3.2 → stac_validator-3.5.0}/stac_validator.egg-info/PKG-INFO +31 -25
  8. {stac_validator-3.3.2 → stac_validator-3.5.0}/stac_validator.egg-info/SOURCES.txt +1 -11
  9. stac_validator-3.5.0/stac_validator.egg-info/requires.txt +9 -0
  10. stac_validator-3.3.2/stac_validator.egg-info/requires.txt +0 -7
  11. stac_validator-3.3.2/tests/test_assets.py +0 -86
  12. stac_validator-3.3.2/tests/test_core.py +0 -176
  13. stac_validator-3.3.2/tests/test_custom.py +0 -207
  14. stac_validator-3.3.2/tests/test_default.py +0 -160
  15. stac_validator-3.3.2/tests/test_extensions.py +0 -215
  16. stac_validator-3.3.2/tests/test_links.py +0 -80
  17. stac_validator-3.3.2/tests/test_recursion.py +0 -355
  18. stac_validator-3.3.2/tests/test_sys_exit.py +0 -32
  19. stac_validator-3.3.2/tests/test_validate_dict.py +0 -69
  20. stac_validator-3.3.2/tests/test_validate_item_collection.py +0 -664
  21. {stac_validator-3.3.2 → stac_validator-3.5.0}/LICENSE +0 -0
  22. {stac_validator-3.3.2 → stac_validator-3.5.0}/pyproject.toml +0 -0
  23. {stac_validator-3.3.2 → stac_validator-3.5.0}/setup.cfg +0 -0
  24. {stac_validator-3.3.2 → stac_validator-3.5.0}/stac_validator/__init__.py +0 -0
  25. {stac_validator-3.3.2 → stac_validator-3.5.0}/stac_validator.egg-info/dependency_links.txt +0 -0
  26. {stac_validator-3.3.2 → stac_validator-3.5.0}/stac_validator.egg-info/entry_points.txt +0 -0
  27. {stac_validator-3.3.2 → stac_validator-3.5.0}/stac_validator.egg-info/top_level.txt +0 -0
@@ -1,26 +1,21 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: stac_validator
3
- Version: 3.3.2
3
+ Version: 3.5.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
7
- Author-email: jhealy@sparkgeo.com
8
- License: MIT
7
+ Author-email: jonathan.d.healy@gmail.com
8
+ License: Apache-2.0
9
9
  Keywords: STAC validation raster
10
10
  Classifier: Intended Audience :: Information Technology
11
11
  Classifier: Intended Audience :: Science/Research
12
- Classifier: License :: OSI Approved :: MIT License
13
- Classifier: Programming Language :: Python :: 3.7
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python :: 3.8
14
14
  Classifier: Topic :: Scientific/Engineering :: GIS
15
15
  Requires-Python: >=3.8
16
16
  Description-Content-Type: text/markdown
17
- License-File: LICENSE
18
- Requires-Dist: requests>=2.19.1
19
- Requires-Dist: jsonschema>=3.2.0
20
- Requires-Dist: click>=8.0.0
21
17
  Provides-Extra: dev
22
- Requires-Dist: pytest; extra == "dev"
23
- Requires-Dist: types-setuptools; extra == "dev"
18
+ License-File: LICENSE
24
19
 
25
20
  # SpatioTemporal Asset Catalog (STAC) Validator
26
21
 
@@ -28,10 +23,7 @@ Requires-Dist: types-setuptools; extra == "dev"
28
23
 
29
24
  [read the docs](https://stac-validator.readthedocs.io/en/latest/)
30
25
 
31
-
32
- ## Validate STAC json files against the [STAC spec](https://github.com/radiantearth/stac-spec).
33
-
34
-
26
+ ## Validate STAC json files against the [STAC spec](https://github.com/radiantearth/stac-spec).
35
27
 
36
28
  ```bash
37
29
  stac-validator https://raw.githubusercontent.com/radiantearth/stac-spec/master/examples/extended-item.json
@@ -56,10 +48,9 @@ stac-validator https://raw.githubusercontent.com/radiantearth/stac-spec/master/e
56
48
 
57
49
  ## Requirements
58
50
 
59
- - Python 3.7+
51
+ - Python 3.8+
60
52
  - Requests
61
53
  - Click
62
- - Pytest
63
54
  - Jsonschema
64
55
 
65
56
  Note: Stac-validator is also used in stac-check which adds linting messages based on the official STAC best practices document.
@@ -85,7 +76,6 @@ or for local development
85
76
  pip install -e '.[dev]'
86
77
  ```
87
78
 
88
-
89
79
  The [Makefile](./Makefile) has convenience commands if Make is installed.
90
80
 
91
81
  ```bash
@@ -106,7 +96,8 @@ make help
106
96
  | 1.0.0-rc.3 |
107
97
  | 1.0.0-rc.4 |
108
98
  | 1.0.0 |
109
-
99
+ | 1.1.0-beta.1 |
100
+ | 1.1.0 |
110
101
 
111
102
  ---
112
103
 
@@ -131,8 +122,13 @@ Options:
131
122
  -m, --max-depth INTEGER Maximum depth to traverse when recursing. Omit this
132
123
  argument to get full recursion. Ignored if
133
124
  `recursive == False`.
125
+ --collections Validate /collections response.
134
126
  --item-collection Validate item collection response. Can be combined
135
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.
136
132
  -p, --pages INTEGER Maximum number of pages to validate via --item-
137
133
  collection. Defaults to one page.
138
134
  -v, --verbose Enables verbose output for recursive mode.
@@ -170,7 +166,9 @@ docker run stac-validator https://raw.githubusercontent.com/stac-extensions/proj
170
166
  ```
171
167
 
172
168
  ## AWS (CDK)
169
+
173
170
  An example [AWS CDK](https://aws.amazon.com/cdk/) deployment is available in [cdk-deployment](./cdk-deployment/README.md)
171
+
174
172
  ```bash
175
173
  cd cdk-deployment
176
174
  cdk diff
@@ -225,29 +223,29 @@ print(stac.message)
225
223
  ```
226
224
 
227
225
  **Dictionary**
228
-
226
+
229
227
  ```python
230
228
  from stac_validator import stac_validator
231
-
229
+
232
230
  stac = stac_validator.StacValidate()
233
231
  stac.validate_dict(dictionary)
234
232
  print(stac.message)
235
233
  ```
236
234
 
237
235
  **Item Collection**
238
-
236
+
239
237
  ```python
240
238
  from stac_validator import stac_validator
241
-
239
+
242
240
  stac = stac_validator.StacValidate()
243
241
  stac.validate_item_collection_dict(item_collection_dict)
244
242
  print(stac.message)
245
243
  ```
244
+
246
245
  ---
247
246
 
248
247
  # Testing
249
248
 
250
-
251
249
  ```bash
252
250
  make test
253
251
  # or
@@ -257,6 +255,7 @@ pytest -v
257
255
  See the [tests](./tests/test_stac_validator.py) files for examples on different usages.
258
256
 
259
257
  ---
258
+
260
259
  # Additional Examples
261
260
 
262
261
  **--core**
@@ -316,7 +315,7 @@ stac-validator https://raw.githubusercontent.com/radiantearth/stac-spec/master/e
316
315
  }
317
316
  ]
318
317
  ```
319
-
318
+
320
319
  **--recursive**
321
320
 
322
321
  ```bash
@@ -348,8 +347,15 @@ stac-validator https://spot-canada-ortho.s3.amazonaws.com/catalog.json --recursi
348
347
  }
349
348
  ]
350
349
  ```
350
+
351
351
  **--item-collection**
352
352
 
353
353
  ```bash
354
354
  stac-validator https://earth-search.aws.element84.com/v0/collections/sentinel-s2-l2a/items --item-collection --pages 2
355
355
  ```
356
+
357
+ **--header**
358
+
359
+ ```bash
360
+ stac-validator https://stac-catalog.eu/collections/sentinel-s2-l2a/items --header x-api-key $MY_API_KEY --header foo bar
361
+ ```
@@ -4,10 +4,7 @@
4
4
 
5
5
  [read the docs](https://stac-validator.readthedocs.io/en/latest/)
6
6
 
7
-
8
- ## Validate STAC json files against the [STAC spec](https://github.com/radiantearth/stac-spec).
9
-
10
-
7
+ ## Validate STAC json files against the [STAC spec](https://github.com/radiantearth/stac-spec).
11
8
 
12
9
  ```bash
13
10
  stac-validator https://raw.githubusercontent.com/radiantearth/stac-spec/master/examples/extended-item.json
@@ -32,10 +29,9 @@ stac-validator https://raw.githubusercontent.com/radiantearth/stac-spec/master/e
32
29
 
33
30
  ## Requirements
34
31
 
35
- - Python 3.7+
32
+ - Python 3.8+
36
33
  - Requests
37
34
  - Click
38
- - Pytest
39
35
  - Jsonschema
40
36
 
41
37
  Note: Stac-validator is also used in stac-check which adds linting messages based on the official STAC best practices document.
@@ -61,7 +57,6 @@ or for local development
61
57
  pip install -e '.[dev]'
62
58
  ```
63
59
 
64
-
65
60
  The [Makefile](./Makefile) has convenience commands if Make is installed.
66
61
 
67
62
  ```bash
@@ -82,7 +77,8 @@ make help
82
77
  | 1.0.0-rc.3 |
83
78
  | 1.0.0-rc.4 |
84
79
  | 1.0.0 |
85
-
80
+ | 1.1.0-beta.1 |
81
+ | 1.1.0 |
86
82
 
87
83
  ---
88
84
 
@@ -107,8 +103,13 @@ Options:
107
103
  -m, --max-depth INTEGER Maximum depth to traverse when recursing. Omit this
108
104
  argument to get full recursion. Ignored if
109
105
  `recursive == False`.
106
+ --collections Validate /collections response.
110
107
  --item-collection Validate item collection response. Can be combined
111
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.
112
113
  -p, --pages INTEGER Maximum number of pages to validate via --item-
113
114
  collection. Defaults to one page.
114
115
  -v, --verbose Enables verbose output for recursive mode.
@@ -146,7 +147,9 @@ docker run stac-validator https://raw.githubusercontent.com/stac-extensions/proj
146
147
  ```
147
148
 
148
149
  ## AWS (CDK)
150
+
149
151
  An example [AWS CDK](https://aws.amazon.com/cdk/) deployment is available in [cdk-deployment](./cdk-deployment/README.md)
152
+
150
153
  ```bash
151
154
  cd cdk-deployment
152
155
  cdk diff
@@ -201,29 +204,29 @@ print(stac.message)
201
204
  ```
202
205
 
203
206
  **Dictionary**
204
-
207
+
205
208
  ```python
206
209
  from stac_validator import stac_validator
207
-
210
+
208
211
  stac = stac_validator.StacValidate()
209
212
  stac.validate_dict(dictionary)
210
213
  print(stac.message)
211
214
  ```
212
215
 
213
216
  **Item Collection**
214
-
217
+
215
218
  ```python
216
219
  from stac_validator import stac_validator
217
-
220
+
218
221
  stac = stac_validator.StacValidate()
219
222
  stac.validate_item_collection_dict(item_collection_dict)
220
223
  print(stac.message)
221
224
  ```
225
+
222
226
  ---
223
227
 
224
228
  # Testing
225
229
 
226
-
227
230
  ```bash
228
231
  make test
229
232
  # or
@@ -233,6 +236,7 @@ pytest -v
233
236
  See the [tests](./tests/test_stac_validator.py) files for examples on different usages.
234
237
 
235
238
  ---
239
+
236
240
  # Additional Examples
237
241
 
238
242
  **--core**
@@ -292,7 +296,7 @@ stac-validator https://raw.githubusercontent.com/radiantearth/stac-spec/master/e
292
296
  }
293
297
  ]
294
298
  ```
295
-
299
+
296
300
  **--recursive**
297
301
 
298
302
  ```bash
@@ -324,8 +328,15 @@ stac-validator https://spot-canada-ortho.s3.amazonaws.com/catalog.json --recursi
324
328
  }
325
329
  ]
326
330
  ```
331
+
327
332
  **--item-collection**
328
333
 
329
334
  ```bash
330
335
  stac-validator https://earth-search.aws.element84.com/v0/collections/sentinel-s2-l2a/items --item-collection --pages 2
331
- ```
336
+ ```
337
+
338
+ **--header**
339
+
340
+ ```bash
341
+ stac-validator https://stac-catalog.eu/collections/sentinel-s2-l2a/items --header x-api-key $MY_API_KEY --header foo bar
342
+ ```
@@ -2,7 +2,7 @@
2
2
 
3
3
  from setuptools import setup
4
4
 
5
- __version__ = "3.3.2"
5
+ __version__ = "3.5.0"
6
6
 
7
7
  with open("README.md", "r") as fh:
8
8
  long_description = fh.read()
@@ -11,14 +11,14 @@ setup(
11
11
  name="stac_validator",
12
12
  version=__version__,
13
13
  author="James Banting, Jonathan Healy",
14
- author_email="jhealy@sparkgeo.com",
14
+ author_email="jonathan.d.healy@gmail.com",
15
15
  description="A package to validate STAC files",
16
- license="MIT",
16
+ license="Apache-2.0",
17
17
  classifiers=[
18
18
  "Intended Audience :: Information Technology",
19
19
  "Intended Audience :: Science/Research",
20
- "License :: OSI Approved :: MIT License",
21
- "Programming Language :: Python :: 3.7",
20
+ "License :: OSI Approved :: Apache Software License",
21
+ "Programming Language :: Python :: 3.8",
22
22
  "Topic :: Scientific/Engineering :: GIS",
23
23
  ],
24
24
  keywords="STAC validation raster",
@@ -26,13 +26,15 @@ setup(
26
26
  long_description_content_type="text/markdown",
27
27
  url="https://github.com/stac-utils/stac-validator",
28
28
  install_requires=[
29
- "requests>=2.19.1",
30
- "jsonschema>=3.2.0",
31
- "click>=8.0.0",
29
+ "requests>=2.32.3",
30
+ "jsonschema>=4.23.0",
31
+ "click>=8.1.8",
32
+ "referencing>=0.35.1",
32
33
  ],
33
34
  extras_require={
34
35
  "dev": [
35
36
  "pytest",
37
+ "requests-mock",
36
38
  "types-setuptools",
37
39
  ],
38
40
  },
@@ -41,5 +43,5 @@ setup(
41
43
  "console_scripts": ["stac-validator = stac_validator.stac_validator:main"]
42
44
  },
43
45
  python_requires=">=3.8",
44
- tests_require=["pytest"],
46
+ tests_require=["pytest", "requests-mock"],
45
47
  )
@@ -18,12 +18,12 @@ def print_update_message(version: str) -> None:
18
18
  None
19
19
  """
20
20
  click.secho()
21
- if version != "1.0.0":
21
+ if version != "1.1.0":
22
22
  click.secho(
23
- f"Please upgrade from version {version} to version 1.0.0!", fg="red"
23
+ f"Please upgrade from version {version} to version 1.1.0!", fg="red"
24
24
  )
25
25
  else:
26
- click.secho("Thanks for using STAC version 1.0.0!", fg="green")
26
+ click.secho("Thanks for using STAC version 1.1.0!", fg="green")
27
27
  click.secho()
28
28
 
29
29
 
@@ -46,6 +46,25 @@ def item_collection_summary(message: List[Dict[str, Any]]) -> None:
46
46
  click.secho(f"valid_items: {valid_count}")
47
47
 
48
48
 
49
+ def collections_summary(message: List[Dict[str, Any]]) -> None:
50
+ """Prints a summary of the validation results for an item collection response.
51
+
52
+ Args:
53
+ message (List[Dict[str, Any]]): The validation results for the item collection.
54
+
55
+ Returns:
56
+ None
57
+ """
58
+ valid_count = 0
59
+ for collection in message:
60
+ if "valid_stac" in collection and collection["valid_stac"] is True:
61
+ valid_count = valid_count + 1
62
+ click.secho()
63
+ click.secho("--collections summary", bold=True)
64
+ click.secho(f"collections_validated: {len(message)}")
65
+ click.secho(f"valid_collections: {valid_count}")
66
+
67
+
49
68
  @click.command()
50
69
  @click.argument("stac_file")
51
70
  @click.option(
@@ -80,11 +99,27 @@ def item_collection_summary(message: List[Dict[str, Any]]) -> None:
80
99
  type=int,
81
100
  help="Maximum depth to traverse when recursing. Omit this argument to get full recursion. Ignored if `recursive == False`.",
82
101
  )
102
+ @click.option(
103
+ "--collections",
104
+ is_flag=True,
105
+ help="Validate /collections response.",
106
+ )
83
107
  @click.option(
84
108
  "--item-collection",
85
109
  is_flag=True,
86
110
  help="Validate item collection response. Can be combined with --pages. Defaults to one page.",
87
111
  )
112
+ @click.option(
113
+ "--no-assets-urls",
114
+ is_flag=True,
115
+ help="Disables the opening of href links when validating assets (enabled by default).",
116
+ )
117
+ @click.option(
118
+ "--header",
119
+ type=(str, str),
120
+ multiple=True,
121
+ help="HTTP header to include in the requests. Can be used multiple times.",
122
+ )
88
123
  @click.option(
89
124
  "--pages",
90
125
  "-p",
@@ -102,7 +137,10 @@ def item_collection_summary(message: List[Dict[str, Any]]) -> None:
102
137
  )
103
138
  def main(
104
139
  stac_file: str,
140
+ collections: bool,
105
141
  item_collection: bool,
142
+ no_assets_urls: bool,
143
+ header: list,
106
144
  pages: int,
107
145
  recursive: bool,
108
146
  max_depth: int,
@@ -120,7 +158,10 @@ def main(
120
158
 
121
159
  Args:
122
160
  stac_file (str): Path to the STAC file to be validated.
161
+ collections (bool): Validate response from /collections endpoint.
123
162
  item_collection (bool): Whether to validate item collection responses.
163
+ no_assets_urls (bool): Whether to open href links when validating assets (enabled by default).
164
+ headers (dict): HTTP headers to include in the requests.
124
165
  pages (int): Maximum number of pages to validate via `item_collection`.
125
166
  recursive (bool): Whether to recursively validate all related STAC objects.
126
167
  max_depth (int): Maximum depth to traverse when recursing.
@@ -143,6 +184,7 @@ def main(
143
184
  valid = True
144
185
  stac = StacValidate(
145
186
  stac_file=stac_file,
187
+ collections=collections,
146
188
  item_collection=item_collection,
147
189
  pages=pages,
148
190
  recursive=recursive,
@@ -150,13 +192,17 @@ def main(
150
192
  core=core,
151
193
  links=links,
152
194
  assets=assets,
195
+ assets_open_urls=not no_assets_urls,
196
+ headers=dict(header),
153
197
  extensions=extensions,
154
198
  custom=custom,
155
199
  verbose=verbose,
156
200
  log=log_file,
157
201
  )
158
- if not item_collection:
202
+ if not item_collection and not collections:
159
203
  valid = stac.run()
204
+ elif collections:
205
+ stac.validate_collections()
160
206
  else:
161
207
  stac.validate_item_collection()
162
208
 
@@ -169,6 +215,8 @@ def main(
169
215
 
170
216
  if item_collection:
171
217
  item_collection_summary(message)
218
+ elif collections:
219
+ collections_summary(message)
172
220
 
173
221
  sys.exit(0 if valid else 1)
174
222
 
@@ -1,10 +1,17 @@
1
1
  import functools
2
2
  import json
3
3
  import ssl
4
+ from typing import Dict, Optional
4
5
  from urllib.parse import urlparse
5
- from urllib.request import urlopen
6
+ from urllib.request import Request, urlopen
6
7
 
8
+ import jsonschema
7
9
  import requests # type: ignore
10
+ from jsonschema import Draft202012Validator
11
+ from referencing import Registry, Resource
12
+ from referencing.jsonschema import DRAFT202012
13
+ from referencing.retrieval import to_cached_resource
14
+ from referencing.typing import URI
8
15
 
9
16
  NEW_VERSIONS = [
10
17
  "1.0.0-beta.2",
@@ -13,6 +20,8 @@ NEW_VERSIONS = [
13
20
  "1.0.0-rc.3",
14
21
  "1.0.0-rc.4",
15
22
  "1.0.0",
23
+ "1.1.0-beta.1",
24
+ "1.1.0",
16
25
  ]
17
26
 
18
27
 
@@ -44,7 +53,7 @@ def is_valid_url(url: str) -> bool:
44
53
  return urlparse(url).scheme in ["http", "https"]
45
54
 
46
55
 
47
- def get_stac_type(stac_content: dict) -> str:
56
+ def get_stac_type(stac_content: Dict) -> str:
48
57
  """Determine the type of a STAC resource.
49
58
 
50
59
  Given a dictionary representing a STAC resource, this function determines the
@@ -74,7 +83,7 @@ def get_stac_type(stac_content: dict) -> str:
74
83
  return str(e)
75
84
 
76
85
 
77
- def fetch_and_parse_file(input_path: str) -> dict:
86
+ def fetch_and_parse_file(input_path: str, headers: Optional[Dict] = None) -> Dict:
78
87
  """Fetches and parses a JSON file from a URL or local file.
79
88
 
80
89
  Given a URL or local file path to a JSON file, this function fetches the file,
@@ -84,6 +93,7 @@ def fetch_and_parse_file(input_path: str) -> dict:
84
93
 
85
94
  Args:
86
95
  input_path: A string representing the URL or local file path to the JSON file.
96
+ headers: For URLs: HTTP headers to include in the request
87
97
 
88
98
  Returns:
89
99
  A dictionary containing the parsed contents of the JSON file.
@@ -94,7 +104,7 @@ def fetch_and_parse_file(input_path: str) -> dict:
94
104
  """
95
105
  try:
96
106
  if is_url(input_path):
97
- resp = requests.get(input_path)
107
+ resp = requests.get(input_path, headers=headers)
98
108
  resp.raise_for_status()
99
109
  data = resp.json()
100
110
  else:
@@ -107,7 +117,7 @@ def fetch_and_parse_file(input_path: str) -> dict:
107
117
 
108
118
 
109
119
  @functools.lru_cache(maxsize=48)
110
- def fetch_and_parse_schema(input_path: str) -> dict:
120
+ def fetch_and_parse_schema(input_path: str) -> Dict:
111
121
  """Fetches and parses a JSON schema file from a URL or local file using a cache.
112
122
 
113
123
  Given a URL or local file path to a JSON schema file, this function fetches the file
@@ -147,8 +157,7 @@ def set_schema_addr(version: str, stac_type: str) -> str:
147
157
 
148
158
 
149
159
  def link_request(
150
- link: dict,
151
- initial_message: dict,
160
+ link: Dict, initial_message: Dict, open_urls: bool = True, headers: Dict = {}
152
161
  ) -> None:
153
162
  """Makes a request to a URL and appends it to the relevant field of the initial message.
154
163
 
@@ -156,6 +165,8 @@ def link_request(
156
165
  link: A dictionary containing a "href" key which is a string representing a URL.
157
166
  initial_message: A dictionary containing lists for "request_valid", "request_invalid",
158
167
  "format_valid", and "format_invalid" URLs.
168
+ open_urls: Whether to open link href URL
169
+ headers: HTTP headers to include in the request
159
170
 
160
171
  Returns:
161
172
  None
@@ -163,17 +174,106 @@ def link_request(
163
174
  """
164
175
  if is_url(link["href"]):
165
176
  try:
166
- if "s3" in link["href"]:
167
- context = ssl._create_unverified_context()
168
- response = urlopen(link["href"], context=context)
169
- else:
170
- response = urlopen(link["href"])
171
- status_code = response.getcode()
172
- if status_code == 200:
173
- initial_message["request_valid"].append(link["href"])
177
+ if open_urls:
178
+ request = Request(link["href"], headers=headers)
179
+ if "s3" in link["href"]:
180
+ context = ssl._create_unverified_context()
181
+ response = urlopen(request, context=context)
182
+ else:
183
+ response = urlopen(request)
184
+ status_code = response.getcode()
185
+ if status_code == 200:
186
+ initial_message["request_valid"].append(link["href"])
174
187
  except Exception:
175
188
  initial_message["request_invalid"].append(link["href"])
176
189
  initial_message["format_valid"].append(link["href"])
177
190
  else:
178
191
  initial_message["request_invalid"].append(link["href"])
179
192
  initial_message["format_invalid"].append(link["href"])
193
+
194
+
195
+ def fetch_remote_schema(uri: str) -> dict:
196
+ """
197
+ Fetch a remote schema from a URI.
198
+
199
+ Args:
200
+ uri (str): The URI of the schema to fetch.
201
+
202
+ Returns:
203
+ dict: The fetched schema content as a dictionary.
204
+
205
+ Raises:
206
+ requests.RequestException: If the request to fetch the schema fails.
207
+ """
208
+ response = requests.get(uri)
209
+ response.raise_for_status()
210
+ return response.json()
211
+
212
+
213
+ @to_cached_resource() # type: ignore
214
+ def cached_retrieve(uri: URI) -> str:
215
+ """
216
+ Retrieve and cache a remote schema.
217
+
218
+ Args:
219
+ uri (str): The URI of the schema.
220
+
221
+ 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.
227
+ """
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:
243
+ """
244
+ Validate a JSON document against a JSON Schema with dynamic reference resolution.
245
+
246
+ Args:
247
+ schema_path (str): Path or URI of the JSON Schema.
248
+ content (dict): JSON content to validate.
249
+
250
+ Raises:
251
+ jsonschema.exceptions.ValidationError: If validation fails.
252
+ requests.RequestException: If fetching a remote schema fails.
253
+ FileNotFoundError: If a local schema file is not found.
254
+ Exception: If any other error occurs during validation.
255
+ """
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
+
266
+ # Set up the resource and registry for schema resolution
267
+ resource: Resource = Resource(contents=schema, specification=DRAFT202012) # type: ignore
268
+ registry: Registry = Registry(retrieve=cached_retrieve).with_resource( # type: ignore
269
+ uri=schema_path, resource=resource
270
+ ) # type: ignore
271
+
272
+ # 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