Skip to content

Commit cf54719

Browse files
committed
Add JSON schema validation to JSONConfig and update dependencies
1 parent c244641 commit cf54719

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

config/config/config.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,10 @@
55
"""
66

77
from json import loads, dumps
8+
from jsonschema import validate, ValidationError
89
from abc import ABC, abstractmethod
910
from datetime import datetime
11+
import requests
1012
import re
1113
import os
1214
import tomlkit
@@ -323,6 +325,10 @@ class JSONConfig(FileConfig):
323325
JSON configuration management class.
324326
This class provides methods to load, save, and manage configuration settings in JSON format.
325327
"""
328+
329+
def __init__(self, file_path: str):
330+
super().__init__(file_path)
331+
self.__validate()
326332

327333
def _to_string(self) -> str:
328334
"""
@@ -341,6 +347,28 @@ def _from_string(self, config_string: str) -> None:
341347
if not isinstance(self._config, dict):
342348
raise ValueError("Invalid JSON format: expected a dictionary.")
343349

350+
def __validate(self):
351+
"""
352+
Validate the configuration against a JSON schema if provided in the config.
353+
The url to the schema must be provided in the "$schema" key of the config (https://json-schema.org/)
354+
"""
355+
if "$schema" in self._config:
356+
schema_url = self._config["$schema"]
357+
try:
358+
response = requests.get(schema_url)
359+
response.raise_for_status()
360+
schema = response.json()
361+
validate(instance=self._config, schema=schema)
362+
except requests.RequestException as e:
363+
raise ValueError(f"Failed to fetch JSON schema from {schema_url}: {e}") from None
364+
except ValidationError as e:
365+
raise ValueError(f"Configuration validation against schema failed: {e.message}") from None
366+
except Exception as e:
367+
raise ValueError(f"An error occurred during schema validation: {e}") from None
368+
_trace("Configuration validated successfully against schema.")
369+
else:
370+
_trace("No JSON schema provided for validation.")
371+
344372
class TOMLConfig(FileConfig):
345373
"""
346374
TOML configuration management class.

config/pyproject.toml

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@ authors = [
1111
]
1212
requires-python = ">=3.10"
1313
dependencies = [
14-
"tomlkit==0.13.2"
14+
"tomlkit==0.13.2",
15+
"jsonschema==4.25.1",
16+
"requests==2.32.5"
1517
]
1618

1719
[tool.setuptools.packages.find]

0 commit comments

Comments
 (0)