tests.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/usr/bin/env python3
  2. """Checks that the peering details in this repo conform to a few basic rules."""
  3. import json
  4. import os
  5. import sys
  6. REQUIRED_FIELDS = ['publicKey', 'password', 'contact', 'peerName']
  7. RECOMMENDED_FIELDS = ['gpg', 'login']
  8. RED = '\x1b[01;31m'
  9. GREEN = '\x1b[01;32m'
  10. YELLOW = '\x1b[01;33m'
  11. END = '\x1b[0m'
  12. def validate(path):
  13. """Test a single set of peering creds."""
  14. print("Validating %s" % path)
  15. try:
  16. creds = open(path).read()
  17. peers = json.loads(creds)
  18. # Check formatting
  19. pretty = json.dumps(peers, sort_keys=True, indent=4, separators=(',', ':'))
  20. pretty = "%s\n" % pretty
  21. formatting = True
  22. if pretty != creds:
  23. if "--clean" in sys.argv:
  24. with open(path, 'w') as outfile:
  25. outfile.write(pretty)
  26. print(" %sJSON in %s has been fixed.%s" % (YELLOW, path, END))
  27. else:
  28. print(" %sJSON in %s is NOT properly formatted! This is really easy to fix!"
  29. " just run tests.py --clean.%s" % (YELLOW, path, END))
  30. formatting = False
  31. hosts = peers.keys()
  32. for host in hosts:
  33. for field in REQUIRED_FIELDS:
  34. if field not in peers[host]:
  35. print(" %sHost %s is missing the required field %s%s" % (RED, host,
  36. field, END))
  37. return False
  38. for field in RECOMMENDED_FIELDS:
  39. if field not in peers[host]:
  40. print(" %sHost %s is missing the recommended field %s%s" % (YELLOW, host,
  41. field, END))
  42. if formatting:
  43. return True
  44. else:
  45. return False
  46. except ValueError:
  47. print(" %sInvalid JSON!%s" % (RED, END))
  48. return False
  49. if __name__ == "__main__":
  50. success = True
  51. for directory, subdirs, files in os.walk('.'):
  52. if len(files) > 0:
  53. if directory != '.' and not directory.startswith('./.git'):
  54. for f in files:
  55. result = validate("%s/%s" % (directory, f))
  56. if not result:
  57. success = False
  58. if not success:
  59. sys.exit(1)