import datetime
def verify_user_records(user_records):
"""
Verifies the integrity of user records for scheduled runs.
Performs basic sanity checks.
Args:
user_records (list): A list of dictionaries, where each dictionary
represents a user record. Example:
[{'user_id': 1, 'username': 'john_doe', 'email': 'john.doe@example.com', 'scheduled_run_time': '2024-01-01T10:00:00'}]
Returns:
list: A list of error messages. Empty if all records are valid.
"""
errors = []
for record in user_records:
# Check for required fields
required_fields = ['user_id', 'username', 'email', 'scheduled_run_time']
for field in required_fields:
if field not in record:
errors.append(f"Missing required field: {field}")
continue # Skip to next field if one is missing
# Validate user_id (must be an integer)
if not isinstance(record.get('user_id'), int):
errors.append("user_id must be an integer.")
# Validate username (must be a string)
if not isinstance(record.get('username'), str):
errors.append("username must be a string.")
# Validate email (basic format check)
email = record.get('email')
if not isinstance(email, str) or "@" not in email or "." not in email:
errors.append("Invalid email format.")
# Validate scheduled_run_time (must be a valid datetime string)
try:
datetime.datetime.fromisoformat(record.get('scheduled_run_time'))
except ValueError:
errors.append("Invalid scheduled_run_time format. Must be ISO format (YYYY-MM-DDTHH:MM:SS).")
return errors
if __name__ == '__main__':
user_records = [
{'user_id': 1, 'username': 'john_doe', 'email': 'john.doe@example.com', 'scheduled_run_time': '2024-01-01T10:00:00'},
{'user_id': 'two', 'username': 'jane_doe', 'email': 'jane.doe@example.com', 'scheduled_run_time': '2024-01-02T12:00:00'}, #invalid user_id
{'username': 'peter_pan', 'email': 'peter.pan@example.com', 'scheduled_run_time': '2024-01-03T14:00:00'}, #missing user_id
{'user_id': 4, 'username': 123, 'email': 'invalid_email', 'scheduled_run_time': '2024-01-04T16:00:00'}, #invalid username and email
{'user_id': 5, 'username': 'alice', 'email': 'alice@example.com', 'scheduled_run_time': '2024/01/05 18:00:00'} #incorrect date format
]
errors = verify_user_records(user_records)
if errors:
print("User record validation errors:")
for error in errors:
print(error)
else:
print("User records are valid.")
Add your comment