/validator.py

https://gitlab.com/rajul/ovl · Python · 98 lines · 68 code · 29 blank · 1 comment · 13 complexity · d2180495ba93ef92f0c96436ffe63a7b MD5 · raw file

  1. #!/usr/bin/python
  2. import re
  3. import json
  4. class OvlUserCSVRecordValidator:
  5. NUMBER_OF_FIELDS_IN_CSV = 5
  6. EXPECTED_FIELDS = ("email", "name", "phone", "organisation", "group")
  7. EMAIL_REGEX = re.compile(r'[^@]+@[^@]+\.[^@]+')
  8. NAME_REGEX = re.compile(r'[a-zA-Z\-\'\s]+')
  9. def __init__(self):
  10. self.csv_data = []
  11. self.data = {}
  12. def validate_record_number_of_fields(self):
  13. return len(self.csv_data) == self.NUMBER_OF_FIELDS_IN_CSV
  14. def create_data_map(self):
  15. for i in range(self.NUMBER_OF_FIELDS_IN_CSV):
  16. self.data[self.EXPECTED_FIELDS[i]] = self.csv_data[i]
  17. def validate_required_fields(self):
  18. return True
  19. def validate_record_email_address(self):
  20. print self.EMAIL_REGEX.match(self.data['email'])
  21. if not self.EMAIL_REGEX.match(self.data['email']):
  22. return False
  23. return True
  24. def validate_real_name(self):
  25. if not self.NAME_REGEX.match(self.data['name']):
  26. return False
  27. return True
  28. def validate_phone_number(self):
  29. return True
  30. def validate_organisation(self):
  31. return True
  32. def validate_group(self):
  33. return True
  34. def validate_record(self, csv_line):
  35. self.csv_data = csv_line.strip().split(',')
  36. print self.csv_data
  37. print self.validate_record_number_of_fields()
  38. if self.validate_record_number_of_fields():
  39. self.create_data_map()
  40. else:
  41. return False
  42. if not self.validate_record_email_address():
  43. return False
  44. if not self.validate_real_name():
  45. return False
  46. if not self.validate_phone_number():
  47. return False
  48. if not self.validate_group():
  49. return False
  50. if not self.validate_organisation():
  51. return False
  52. return True
  53. class OvlUserCSVFileValidator:
  54. def __init__(self, filepath):
  55. self.file = open(filepath, 'r')
  56. self.good_records = []
  57. self.bad_records = []
  58. self.good_records_count = 0
  59. self.bad_records_count = 0
  60. self.record_validator = OvlUserCSVRecordValidator()
  61. def validate_file(self):
  62. for line in self.file:
  63. if self.record_validator.validate_record(line):
  64. self.good_records.append(line)
  65. self.good_records_count = self.good_records_count + 1
  66. else:
  67. self.bad_records.append(line)
  68. self.bad_records_count = self.bad_records_count + 1
  69. return True