validate.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import os
  2. from os import listdir
  3. from os.path import isfile
  4. import json
  5. from jsonschema import validate
  6. from jsonschema.exceptions import ValidationError
  7. def validate_configs(schemata_and_configs):
  8. for schema_loc, configs in schemata_and_configs.items():
  9. with open(schema_loc, mode="r") as schema_file:
  10. schema = json.load(schema_file)
  11. for config_loc in configs:
  12. with open(config_loc, mode="r") as config_file:
  13. config = json.load(config_file)
  14. try:
  15. validate(instance=config, schema=schema)
  16. print("{} is valid with respect to {}.".format(config_loc, schema_loc))
  17. except ValidationError as verr:
  18. print("{} is not valid with respect to {}.".format(config_loc, schema_loc))
  19. print(str(verr))
  20. def get_files_from_directory(directory, filter_proc):
  21. return [os.path.join(directory, f)
  22. for f in listdir(directory)
  23. if all([
  24. isfile(os.path.join(directory, f)),
  25. filter_proc(os.path.join(directory, f))])]
  26. def main():
  27. config_dir = os.path.join("config")
  28. schema_dir = os.path.join(config_dir, "schema")
  29. # define a schema to use for validating a list of json files
  30. schemata_and_configs = {
  31. os.path.join(schema_dir, "player-schema.json"):
  32. get_files_from_directory(
  33. os.path.join(config_dir, "player"),
  34. filter_proc=lambda fname: fname.endswith("json")),
  35. os.path.join(schema_dir, "transportation-schema.json"):
  36. get_files_from_directory(
  37. os.path.join(config_dir, "transportation"),
  38. filter_proc=lambda fname: fname.endswith("json")),
  39. os.path.join(schema_dir, "general-schema.json"): [
  40. os.path.join(config_dir, "general.json")]
  41. }
  42. validate_configs(schemata_and_configs)
  43. if __name__ == "__main__":
  44. main()