1. import datetime
  2. def verify_user_records(user_records):
  3. """
  4. Verifies the integrity of user records for scheduled runs.
  5. Performs basic sanity checks.
  6. Args:
  7. user_records (list): A list of dictionaries, where each dictionary
  8. represents a user record. Example:
  9. [{'user_id': 1, 'username': 'john_doe', 'email': 'john.doe@example.com', 'scheduled_run_time': '2024-01-01T10:00:00'}]
  10. Returns:
  11. list: A list of error messages. Empty if all records are valid.
  12. """
  13. errors = []
  14. for record in user_records:
  15. # Check for required fields
  16. required_fields = ['user_id', 'username', 'email', 'scheduled_run_time']
  17. for field in required_fields:
  18. if field not in record:
  19. errors.append(f"Missing required field: {field}")
  20. continue # Skip to next field if one is missing
  21. # Validate user_id (must be an integer)
  22. if not isinstance(record.get('user_id'), int):
  23. errors.append("user_id must be an integer.")
  24. # Validate username (must be a string)
  25. if not isinstance(record.get('username'), str):
  26. errors.append("username must be a string.")
  27. # Validate email (basic format check)
  28. email = record.get('email')
  29. if not isinstance(email, str) or "@" not in email or "." not in email:
  30. errors.append("Invalid email format.")
  31. # Validate scheduled_run_time (must be a valid datetime string)
  32. try:
  33. datetime.datetime.fromisoformat(record.get('scheduled_run_time'))
  34. except ValueError:
  35. errors.append("Invalid scheduled_run_time format. Must be ISO format (YYYY-MM-DDTHH:MM:SS).")
  36. return errors
  37. if __name__ == '__main__':
  38. user_records = [
  39. {'user_id': 1, 'username': 'john_doe', 'email': 'john.doe@example.com', 'scheduled_run_time': '2024-01-01T10:00:00'},
  40. {'user_id': 'two', 'username': 'jane_doe', 'email': 'jane.doe@example.com', 'scheduled_run_time': '2024-01-02T12:00:00'}, #invalid user_id
  41. {'username': 'peter_pan', 'email': 'peter.pan@example.com', 'scheduled_run_time': '2024-01-03T14:00:00'}, #missing user_id
  42. {'user_id': 4, 'username': 123, 'email': 'invalid_email', 'scheduled_run_time': '2024-01-04T16:00:00'}, #invalid username and email
  43. {'user_id': 5, 'username': 'alice', 'email': 'alice@example.com', 'scheduled_run_time': '2024/01/05 18:00:00'} #incorrect date format
  44. ]
  45. errors = verify_user_records(user_records)
  46. if errors:
  47. print("User record validation errors:")
  48. for error in errors:
  49. print(error)
  50. else:
  51. print("User records are valid.")

Add your comment