-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig_schema_validator.py
More file actions
62 lines (52 loc) · 1.93 KB
/
Copy pathconfig_schema_validator.py
File metadata and controls
62 lines (52 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import json
import yaml
class Config_Schema_Validator:
def __init__(self):
self.config_data = None
def load_data(self, config):
if config.endswith(".json"):
with open(config, 'r') as file:
self.config_data = json.load(file)
elif config.endswith(".yaml"):
with open(config, 'r') as file:
self.config_data = yaml.safe_load(file)
else:
raise ValueError("invalid file format")
return self.config_data
def validate(self, config, schema, path=""):
errors = []
for key, value in schema.items():
full_key = f"{path}.{key}" if path else key
if key not in config:
errors.append(f"Missing key: {full_key}")
else:
actual_value = config[key]
if isinstance(value, dict):
if isinstance(actual_value, dict):
errors.extend(self.validate(actual_value, value, full_key))
else:
errors.append(f"Type Mismath: {full_key} - Expected {type(value).__name__}, got {type(actual_value).__name__}")
else:
if not isinstance(actual_value, value):
errors.append(f"Type Mismath: {full_key} - Expected {type(value).__name__}, got {type(actual_value).__name__}")
return errors
if __name__ == "__main__":
schema = {
"app_name": str,
"version": str,
"debug": bool,
"database": {
"host": str,
"port": int
}
}
csv = Config_Schema_Validator()
config_data = csv.load_data('config.json')
print(config_data)
validation_errors = csv.validate(config_data, schema)
if validation_errors:
print("Validation Errprs:")
for err in validation_errors:
print(" -", err)
else:
print("Config is valid as per schema")