Esempio n. 1
0
    def test_serialize_class_based_validators(self):
        """
        Ticket #22943: Test serialization of class-based validators, including
        compiled regexes.
        """
        validator = RegexValidator(message="hello")
        string = MigrationWriter.serialize(validator)[0]
        self.assertEqual(string, "django.core.validators.RegexValidator(message='hello')")
        self.serialize_round_trip(validator)

        # Test with a compiled regex.
        validator = RegexValidator(regex=re.compile(r'^\w+$'))
        string = MigrationWriter.serialize(validator)[0]
        self.assertEqual(string, "django.core.validators.RegexValidator(regex=re.compile('^\\\\w+$'))")
        self.serialize_round_trip(validator)

        # Test a string regex with flag
        validator = RegexValidator(r'^[0-9]+$', flags=re.S)
        string = MigrationWriter.serialize(validator)[0]
        if PY36:
            self.assertEqual(string, "django.core.validators.RegexValidator('^[0-9]+$', flags=re.RegexFlag(16))")
        else:
            self.assertEqual(string, "django.core.validators.RegexValidator('^[0-9]+$', flags=16)")
        self.serialize_round_trip(validator)

        # Test message and code
        validator = RegexValidator('^[-a-zA-Z0-9_]+$', 'Invalid', 'invalid')
        string = MigrationWriter.serialize(validator)[0]
        self.assertEqual(string, "django.core.validators.RegexValidator('^[-a-zA-Z0-9_]+$', 'Invalid', 'invalid')")
        self.serialize_round_trip(validator)

        # Test with a subclass.
        validator = EmailValidator(message="hello")
        string = MigrationWriter.serialize(validator)[0]
        self.assertEqual(string, "django.core.validators.EmailValidator(message='hello')")
        self.serialize_round_trip(validator)

        validator = deconstructible(path="migrations.test_writer.EmailValidator")(EmailValidator)(message="hello")
        string = MigrationWriter.serialize(validator)[0]
        self.assertEqual(string, "migrations.test_writer.EmailValidator(message='hello')")

        validator = deconstructible(path="custom.EmailValidator")(EmailValidator)(message="hello")
        with self.assertRaisesMessage(ImportError, "No module named 'custom'"):
            MigrationWriter.serialize(validator)

        validator = deconstructible(path="django.core.validators.EmailValidator2")(EmailValidator)(message="hello")
        with self.assertRaisesMessage(ValueError, "Could not find object EmailValidator2 in django.core.validators."):
            MigrationWriter.serialize(validator)
Esempio n. 2
0
 def test_serialize(self):
     """
     Tests various different forms of the serializer.
     This does not care about formatting, just that the parsed result is
     correct, so we always exec() the result and check that.
     """
     # Basic values
     self.assertSerializedEqual(1)
     self.assertSerializedEqual(None)
     self.assertSerializedEqual(b"foobar")
     self.assertSerializedEqual("föobár")
     self.assertSerializedEqual({1: 2})
     self.assertSerializedEqual(["a", 2, True, None])
     self.assertSerializedEqual(set([2, 3, "eighty"]))
     self.assertSerializedEqual({"lalalala": ["yeah", "no", "maybe"]})
     self.assertSerializedEqual(_('Hello'))
     # Functions
     with six.assertRaisesRegex(self, ValueError, 'Cannot serialize function: lambda'):
         self.assertSerializedEqual(lambda x: 42)
     self.assertSerializedEqual(models.SET_NULL)
     string, imports = MigrationWriter.serialize(models.SET(42))
     self.assertEqual(string, 'models.SET(42)')
     self.serialize_round_trip(models.SET(42))
     # Datetime stuff
     self.assertSerializedEqual(datetime.datetime.utcnow())
     self.assertSerializedEqual(datetime.datetime.utcnow)
     self.assertSerializedEqual(datetime.datetime.today())
     self.assertSerializedEqual(datetime.datetime.today)
     self.assertSerializedEqual(datetime.date.today())
     self.assertSerializedEqual(datetime.date.today)
     # Classes
     validator = RegexValidator(message="hello")
     string, imports = MigrationWriter.serialize(validator)
     self.assertEqual(string, "django.core.validators.RegexValidator(message=%s)" % repr("hello"))
     self.serialize_round_trip(validator)
     validator = EmailValidator(message="hello")  # Test with a subclass.
     string, imports = MigrationWriter.serialize(validator)
     self.assertEqual(string, "django.core.validators.EmailValidator(message=%s)" % repr("hello"))
     self.serialize_round_trip(validator)
     validator = deconstructible(path="custom.EmailValidator")(EmailValidator)(message="hello")
     string, imports = MigrationWriter.serialize(validator)
     self.assertEqual(string, "custom.EmailValidator(message=%s)" % repr("hello"))
     # Django fields
     self.assertSerializedFieldEqual(models.CharField(max_length=255))
     self.assertSerializedFieldEqual(models.TextField(null=True, blank=True))
     # Setting references
     self.assertSerializedEqual(SettingsReference(settings.AUTH_USER_MODEL, "AUTH_USER_MODEL"))
     self.assertSerializedResultEqual(
         SettingsReference("someapp.model", "AUTH_USER_MODEL"),
         (
             "settings.AUTH_USER_MODEL",
             set(["from django.conf import settings"]),
         )
     )
Esempio n. 3
0
def create_minio_client_from_settings(*, minio_kwargs=dict()):
    endpoint = get_setting("MINIO_STORAGE_ENDPOINT")
    access_key = get_setting("MINIO_STORAGE_ACCESS_KEY")
    secret_key = get_setting("MINIO_STORAGE_SECRET_KEY")
    secure = get_setting("MINIO_STORAGE_USE_HTTPS", True)
    # Making this client deconstructible allows it to be passed directly as
    # an argument to MinioStorage, since Django needs to be able to
    # deconstruct all Storage constructor arguments for Storages referenced in
    # migrations (e.g. when using a custom storage on a FileField).
    client = deconstructible(minio.Minio)(
        endpoint,
        access_key=access_key,
        secret_key=secret_key,
        secure=secure,
        **minio_kwargs,
    )
    return client
Esempio n. 4
0
    def test_serialize_class_based_validators(self):
        """
        Ticket #22943: Test serialization of class-based validators, including
        compiled regexes.
        """
        validator = RegexValidator(message="hello")
        string = MigrationWriter.serialize(validator)[0]
        self.assertEqual(string, "django.core.validators.RegexValidator(message='hello')")
        self.serialize_round_trip(validator)

        # Test with a compiled regex.
        validator = RegexValidator(regex=re.compile(r'^\w+$', re.U))
        string = MigrationWriter.serialize(validator)[0]
        self.assertEqual(string, "django.core.validators.RegexValidator(regex=re.compile('^\\\\w+$', 32))")
        self.serialize_round_trip(validator)

        # Test a string regex with flag
        validator = RegexValidator(r'^[0-9]+$', flags=re.U)
        string = MigrationWriter.serialize(validator)[0]
        self.assertEqual(string, "django.core.validators.RegexValidator('^[0-9]+$', flags=32)")
        self.serialize_round_trip(validator)

        # Test message and code
        validator = RegexValidator('^[-a-zA-Z0-9_]+$', 'Invalid', 'invalid')
        string = MigrationWriter.serialize(validator)[0]
        self.assertEqual(string, "django.core.validators.RegexValidator('^[-a-zA-Z0-9_]+$', 'Invalid', 'invalid')")
        self.serialize_round_trip(validator)

        # Test with a subclass.
        validator = EmailValidator(message="hello")
        string = MigrationWriter.serialize(validator)[0]
        self.assertEqual(string, "django.core.validators.EmailValidator(message='hello')")
        self.serialize_round_trip(validator)

        validator = deconstructible(path="custom.EmailValidator")(EmailValidator)(message="hello")
        string = MigrationWriter.serialize(validator)[0]
        self.assertEqual(string, "custom.EmailValidator(message='hello')")
        Returns the last modified time (as datetime object) of the file
        specified by name.

        :param name: file name
        :type name: str
        :rtype: :class:`~python:datetime.datetime`
        """

        return self.get_storage(name).get_modified_time(name)

    def generate_filename(self, filename):
        return self.get_storage(filename).generate_filename(filename)


if version.parse(DJANGO_VERSION) <= version.parse('1.7'):
    QueuedStorage = deconstructible(QueuedStorage)


class QueuedFileSystemStorage(QueuedStorage):
    """d
    A :class:`~queued_storage.backends.QueuedStorage` subclass which
    conveniently uses
    :class:`~django:django.core.files.storage.FileSystemStorage` as the local
    storage.
    """
    def __init__(self,
                 local='django.core.files.storage.FileSystemStorage',
                 *args,
                 **kwargs):
        super(QueuedFileSystemStorage, self).__init__(local=local,
                                                      *args,
        :rtype: :class:`~python:datetime.datetime`
        """
        return self.get_storage(name).created_time(name)

    def modified_time(self, name):
        """
        Returns the last modified time (as datetime object) of the file
        specified by name.

        :param name: file name
        :type name: str
        :rtype: :class:`~python:datetime.datetime`
        """
        return self.get_storage(name).modified_time(name)
if django_version()[1] >= 7:
    QueuedStorage = deconstructible(QueuedStorage)


class QueuedFileSystemStorage(QueuedStorage):
    """
    A :class:`~queued_storage.backends.QueuedStorage` subclass which
    conveniently uses
    :class:`~django:django.core.files.storage.FileSystemStorage` as the local
    storage.
    """
    def __init__(self, local='django.core.files.storage.FileSystemStorage', *args, **kwargs):
        super(QueuedFileSystemStorage, self).__init__(local=local, *args, **kwargs)


class QueuedS3BotoStorage(QueuedFileSystemStorage):
    """
Esempio n. 7
0
        filepath = os.path.basename(filename)
        filename, extension = os.path.splitext(filepath)
        filename = slugify(filename)

        path = "/".join([
            self.prefix,
            str(today.year),
            str(today.month),
            str(today.day), filename + extension
        ])
        return path


try:
    from django.utils.deconstruct import deconstructible
    FilenameGenerator = deconstructible(FilenameGenerator)
except ImportError:
    pass


def normalize_phone(number):
    number = number[1:] if number[:1] == '0' else number
    parse_phone_number = phonenumbers.parse(number, 'ID')
    phone_number = phonenumbers.format_number(
        parse_phone_number, phonenumbers.PhoneNumberFormat.E164)
    return phone_number


def force_login(request, user):
    user.backend = 'django.contrib.auth.backends.ModelBackend'
    login(request, user)
Esempio n. 8
0
from django.db import models
from django.contrib.auth.models import Group
from django.contrib.auth import get_user_model
from django.conf import settings
from django.core import mail

from . import workflows
from django_xworkflows import models as xwf_models
import xworkflows

from django.utils.deconstruct import deconstructible
xwf_models.Workflow = deconstructible(xwf_models.Workflow)
xwf_models.WorkflowEnabled = xwf_models.WorkflowEnabledMeta(str('WorkflowEnabled'), (xwf_models.BaseWorkflowEnabled,), {'__module__':'django_xworkflows.models'})
class StateField(xwf_models.StateField):
    def deconstruct(self):
        name, path, args, kwargs = super(StateField, self).deconstruct()
        kwargs['workflow'] = self.workflow
        return name, path, args, kwargs

class LendablesOwner(models.Model):
    name = models.CharField(max_length=64, null=False, blank=False)
    slug = models.SlugField(null=False, blank=False)
    owning_group = models.ForeignKey(Group, null=False)

    def __unicode__(self):
        return self.name

class LendableType(models.Model):
    name = models.CharField(max_length=64, null=False, blank=False)
    slug = models.SlugField(null=False, blank=False)
Esempio n. 9
0
    # datetime.timedelta, which loses information.  We then parse it
    # ourselves in convert_relativedeltafield_value().
    #
    # We make it easier for ourselves by doing some formatting here,
    # so that we don't need to rely on weird detection logic for the
    # current value of IntervalStyle (PsycoPg2 actually gets this
    # wrong; it only checks / sets DateStyle, but not IntervalStyle)
    #
    # We can't simply replace or remove PsycoPg2's parser, because
    # that would mess with any existing Django DurationFields, since
    # Django assumes PsycoPg2 returns pre-parsed datetime.timedeltas.
    def select_format(self, compiler, sql, params):
        fmt = 'to_char(%s, \'PYYYY"Y"MM"M"DD"DT"HH24"H"MI"M"SS.US"S"\')' % sql
        return fmt, params

    def from_db_value(self, value, expression, connection, context=None):
        if value is not None:
            return parse_relativedelta(value)

    def value_to_string(self, obj):
        val = self.value_from_object(obj)
        return '' if val is None else format_relativedelta(val)

    def formfield(self, *args, **kwargs):
        kwargs.setdefault('choices_form_class',
                          relativedeltafield.forms.RelativeDeltaChoiceField)
        return super().formfield(*args, **kwargs)


deconstructible(relativedelta)