Beispiel #1
0
 def test_IPAddressField(self):
     lazy_func = lazy(lambda: '127.0.0.1', str)
     self.assertIsInstance(IPAddressField().get_prep_value(lazy_func()),
                           str)
     lazy_func = lazy(lambda: 0, int)
     self.assertIsInstance(IPAddressField().get_prep_value(lazy_func()),
                           str)
Beispiel #2
0
    def test_lazy_equality(self):
        """
        == and != work correctly for Promises.
        """
        lazy_a = lazy(lambda: 4, int)
        lazy_b = lazy(lambda: 4, int)
        lazy_c = lazy(lambda: 5, int)

        self.assertEqual(lazy_a(), lazy_b())
        self.assertNotEqual(lazy_b(), lazy_c())
Beispiel #3
0
 def test_lazy_strings_not_evaluated(self):
     lazy_func = lazy(lambda x: 0 / 0,
                      int)  # raises ZeroDivisionError if evaluated.
     f = models.CharField(choices=[(lazy_func('group'), (('a', 'A'),
                                                         ('b', 'B')))])
     self.assertEqual(
         f.get_choices(include_blank=True)[0], ('', '---------'))
Beispiel #4
0
 def test_defaults_not_evaluated_unless_needed(self):
     """`defaults` aren't evaluated if the instance isn't created."""
     def raise_exception():
         raise AssertionError
     obj, created = Person.objects.get_or_create(
         first_name='John', defaults=lazy(raise_exception, object)(),
     )
     self.assertFalse(created)
Beispiel #5
0
 def test_invalid_generic_ip_raises_error(self):
     giptm = GenericIPAddressTestModel(generic_ip="294.4.2.1")
     self.assertFailsValidation(giptm.full_clean, ['generic_ip'])
     giptm = GenericIPAddressTestModel(generic_ip="1:2")
     self.assertFailsValidation(giptm.full_clean, ['generic_ip'])
     giptm = GenericIPAddressTestModel(generic_ip=1)
     self.assertFailsValidation(giptm.full_clean, ['generic_ip'])
     giptm = GenericIPAddressTestModel(generic_ip=lazy(lambda: 1, int))
     self.assertFailsValidation(giptm.full_clean, ['generic_ip'])
Beispiel #6
0
    def test_mark_safe_decorator_does_not_affect_promises(self):
        """
        mark_safe doesn't affect lazy strings (Promise objects).
        """
        def html_str():
            return '<html></html>'

        lazy_str = lazy(html_str, str)()
        self.assertEqual(mark_safe(lazy_str), html_str())
Beispiel #7
0
    def test_lazy_base_class(self):
        """lazy also finds base class methods in the proxy object"""
        class Base:
            def base_method(self):
                pass

        class Klazz(Base):
            pass

        t = lazy(lambda: Klazz(), Klazz)()
        self.assertIn('base_method', dir(t))
Beispiel #8
0
    def test_lazy_base_class_override(self):
        """lazy finds the correct (overridden) method implementation"""
        class Base:
            def method(self):
                return 'Base'

        class Klazz(Base):
            def method(self):
                return 'Klazz'

        t = lazy(lambda: Klazz(), Base)()
        self.assertEqual(t.method(), 'Klazz')
Beispiel #9
0
    def test_lazy_object_to_string(self):
        class Klazz:
            def __str__(self):
                return "Î am ā Ǩlâzz."

            def __bytes__(self):
                return b"\xc3\x8e am \xc4\x81 binary \xc7\xa8l\xc3\xa2zz."

        t = lazy(lambda: Klazz(), Klazz)()
        self.assertEqual(str(t), "Î am ā Ǩlâzz.")
        self.assertEqual(bytes(t),
                         b"\xc3\x8e am \xc4\x81 binary \xc7\xa8l\xc3\xa2zz.")
Beispiel #10
0
def lazy_number(func, resultclass, number=None, **kwargs):
    if isinstance(number, int):
        kwargs['number'] = number
        proxy = lazy(func, resultclass)(**kwargs)
    else:
        original_kwargs = kwargs.copy()

        class NumberAwareString(resultclass):
            def __bool__(self):
                return bool(kwargs['singular'])

            def __mod__(self, rhs):
                if isinstance(rhs, dict) and number:
                    try:
                        number_value = rhs[number]
                    except KeyError:
                        raise KeyError(
                            "Your dictionary lacks key '%s\'. Please provide "
                            "it, because it is required to determine whether "
                            "string is singular or plural." % number)
                else:
                    number_value = rhs
                kwargs['number'] = number_value
                translated = func(**kwargs)
                try:
                    translated = translated % rhs
                except TypeError:
                    # String doesn't contain a placeholder for the number.
                    pass
                return translated

        proxy = lazy(lambda **kwargs: NumberAwareString(),
                     NumberAwareString)(**kwargs)
        proxy.__reduce__ = lambda: (_lazy_number_unpickle, (
            func, resultclass, number, original_kwargs))
    return proxy
Beispiel #11
0
 def test_DecimalField(self):
     lazy_func = lazy(lambda: Decimal('1.2'), Decimal)
     self.assertIsInstance(DecimalField().get_prep_value(lazy_func()),
                           Decimal)
Beispiel #12
0
    """
    Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens.
    Remove characters that aren't alphanumerics, underscores, or hyphens.
    Convert to lowercase. Also strip leading and trailing whitespace.
    """
    value = str(value)
    if allow_unicode:
        value = unicodedata.normalize('NFKC', value)
    else:
        value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
    value = re.sub(r'[^\w\s-]', '', value).strip().lower()
    return re.sub(r'[-\s]+', '-', value)


def camel_case_to_spaces(value):
    """
    Split CamelCase and convert to lower case. Strip surrounding whitespace.
    """
    return re_camel_case.sub(r' \1', value).strip().lower()


def _format_lazy(format_string, *args, **kwargs):
    """
    Apply str.format() on 'format_string' where format_string, args,
    and/or kwargs might be lazy.
    """
    return format_string.format(*args, **kwargs)


format_lazy = lazy(_format_lazy, str)
Beispiel #13
0
 class Model(models.Model):
     field = models.CharField(max_length=10,
                              choices=lazy(lambda: [[1, '1'], [2, '2']],
                                           tuple)())
Beispiel #14
0
 def test_URLField(self):
     lazy_func = lazy(lambda: 'http://domain.com', str)
     self.assertIsInstance(URLField().get_prep_value(lazy_func()), str)
Beispiel #15
0
 def test_IntegerField(self):
     lazy_func = lazy(lambda: 1, int)
     self.assertIsInstance(IntegerField().get_prep_value(lazy_func()), int)
Beispiel #16
0
    return _trans.ngettext(singular, plural, number)


# An alias since Django 2.0
ungettext = ngettext


def pgettext(context, message):
    return _trans.pgettext(context, message)


def npgettext(context, singular, plural, number):
    return _trans.npgettext(context, singular, plural, number)


gettext_lazy = ugettext_lazy = lazy(gettext, str)
pgettext_lazy = lazy(pgettext, str)


def lazy_number(func, resultclass, number=None, **kwargs):
    if isinstance(number, int):
        kwargs['number'] = number
        proxy = lazy(func, resultclass)(**kwargs)
    else:
        original_kwargs = kwargs.copy()

        class NumberAwareString(resultclass):
            def __bool__(self):
                return bool(kwargs['singular'])

            def __mod__(self, rhs):
Beispiel #17
0
 def test_AutoField(self):
     lazy_func = lazy(lambda: 1, int)
     self.assertIsInstance(
         AutoField(primary_key=True).get_prep_value(lazy_func()), int)
Beispiel #18
0
 def test_BinaryField(self):
     lazy_func = lazy(lambda: b'', bytes)
     self.assertIsInstance(BinaryField().get_prep_value(lazy_func()), bytes)
Beispiel #19
0
 def test_lazy_repr_int(self):
     original_object = 15
     lazy_obj = lazy(lambda: original_object, int)
     self.assertEqual(repr(original_object), repr(lazy_obj()))
Beispiel #20
0
 def test_DateTimeField(self):
     lazy_func = lazy(lambda: datetime.datetime.now(), datetime.datetime)
     self.assertIsInstance(DateTimeField().get_prep_value(lazy_func()),
                           datetime.datetime)
Beispiel #21
0
 def test_CharField(self):
     lazy_func = lazy(lambda: '', str)
     self.assertIsInstance(CharField().get_prep_value(lazy_func()), str)
     lazy_func = lazy(lambda: 0, int)
     self.assertIsInstance(CharField().get_prep_value(lazy_func()), str)
Beispiel #22
0
 def test_BooleanField(self):
     lazy_func = lazy(lambda: True, bool)
     self.assertIsInstance(BooleanField().get_prep_value(lazy_func()), bool)
Beispiel #23
0
 def test_lazy_repr_bytes(self):
     original_object = b'J\xc3\xbcst a str\xc3\xadng'
     lazy_obj = lazy(lambda: original_object, bytes)
     self.assertEqual(repr(original_object), repr(lazy_obj()))
Beispiel #24
0
 def test_EmailField(self):
     lazy_func = lazy(lambda: '*****@*****.**', str)
     self.assertIsInstance(EmailField().get_prep_value(lazy_func()), str)
Beispiel #25
0
 def test_FilePathField(self):
     lazy_func = lazy(lambda: 'tests.py', str)
     self.assertIsInstance(FilePathField().get_prep_value(lazy_func()), str)
     lazy_func = lazy(lambda: 0, int)
     self.assertIsInstance(FilePathField().get_prep_value(lazy_func()), str)
Beispiel #26
0
 def test_FloatField(self):
     lazy_func = lazy(lambda: 1.2, float)
     self.assertIsInstance(FloatField().get_prep_value(lazy_func()), float)
Beispiel #27
0
 def test_lazy(self):
     t = lazy(lambda: tuple(range(3)), list, tuple)
     for a, b in zip(t(), range(3)):
         self.assertEqual(a, b)
Beispiel #28
0
 def test_ImageField(self):
     lazy_func = lazy(lambda: 'filename.ext', str)
     self.assertIsInstance(ImageField().get_prep_value(lazy_func()), str)
Beispiel #29
0
 def test_lazy_repr_text(self):
     original_object = 'Lazy translation text'
     lazy_obj = lazy(lambda: original_object, str)
     self.assertEqual(repr(original_object), repr(lazy_obj()))
Beispiel #30
0
    if val is None:
        if format_type not in FORMAT_SETTINGS:
            return format_type
        val = getattr(settings, format_type)
    elif format_type in ISO_INPUT_FORMATS:
        # If a list of input formats from one of the format_modules was
        # retrieved, make sure the ISO_INPUT_FORMATS are in this list.
        val = list(val)
        for iso_input in ISO_INPUT_FORMATS.get(format_type, ()):
            if iso_input not in val:
                val.append(iso_input)
    _format_cache[cache_key] = val
    return val


get_format_lazy = lazy(get_format, str, list, tuple)


def date_format(value, format=None, use_l10n=None):
    """
    Format a datetime.date or datetime.datetime object using a
    localizable format.

    If use_l10n is provided and is not None, that will force the value to
    be localized (or not), overriding the value of settings.USE_L10N.
    """
    return dateformat.format(value, get_format(format or 'DATE_FORMAT', use_l10n=use_l10n))


def time_format(value, format=None, use_l10n=None):
    """