Просмотр исходного кода

Started with validators for users.

Rafał Pitoń 11 лет назад
Родитель
Сommit
28a323b2a8

+ 1 - 1
misago/users/models/usermodel.py

@@ -11,7 +11,7 @@ from misago.users.utils import hash_email
 class UserManager(BaseUserManager):
     def create_user(self, username, email, password=None, **extra_fields):
         if not email:
-            raise ValueError(_('User must have an email address.'))
+            raise ValueError(_("User must have an email address."))
 
         now = timezone.now()
         user = self.model(is_staff=False, is_active=True, is_superuser=False,

+ 28 - 0
misago/users/tests/test_validators.py

@@ -0,0 +1,28 @@
+#-*- coding: utf-8 -*-
+from django.core.exceptions import ValidationError
+from django.test import TestCase
+from misago.users.validators import (validate_username_available,
+                                     validate_username_content,
+                                     validate_username_length,
+                                     validate_username)
+
+
+class ValidateContentTests(TestCase):
+    def test_valid_names(self):
+        """validate_username_content allows valid names"""
+        validate_username_content('123')
+        validate_username_content('Bob')
+        validate_username_content('Bob123')
+
+    def test_invalid_names(self):
+        """validate_username_content disallows invalid names"""
+        with self.assertRaises(ValidationError):
+            validate_username_content('!')
+        with self.assertRaises(ValidationError):
+            validate_username_content('Bob!')
+        with self.assertRaises(ValidationError):
+            validate_username_content('Bob Boberson')
+        with self.assertRaises(ValidationError):
+            validate_username_content(u'Rafał')
+        with self.assertRaises(ValidationError):
+            validate_username_content(u'初音 ミク')

+ 27 - 0
misago/users/validators.py

@@ -0,0 +1,27 @@
+import re
+from django.core.exceptions import ValidationError
+from django.utils.translation import ugettext_lazy as _
+from django.contrib.auth import get_user_model
+
+
+username_regex = re.compile(r'^[0-9A-Z]+$', re.IGNORECASE)
+
+
+def validate_username_available(value):
+    User = get_user_model()
+
+
+def validate_username_content(value):
+    if not username_regex.match(value):
+        raise ValidationError(
+            _("Username can only contain latin alphabet letters and digits."))
+
+
+def validate_username_length(value):
+    pass
+
+
+def validate_username(value):
+    validate_username_available(value)
+    validate_username_content(value)
+    validate_username_length(value)