mirror of
https://github.com/SectorLabs/django-localized-fields.git
synced 2025-10-29 18:18:57 +03:00
Re-format all files
This commit is contained in:
@@ -2,12 +2,11 @@ from django.conf import settings
|
||||
|
||||
|
||||
def get_init_values() -> dict:
|
||||
"""Gets a test dictionary containing a key
|
||||
for every language."""
|
||||
"""Gets a test dictionary containing a key for every language."""
|
||||
|
||||
keys = {}
|
||||
|
||||
for lang_code, lang_name in settings.LANGUAGES:
|
||||
keys[lang_code] = 'value in %s' % lang_name
|
||||
keys[lang_code] = "value in %s" % lang_name
|
||||
|
||||
return keys
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
import uuid
|
||||
|
||||
from django.contrib.postgres.operations import HStoreExtension
|
||||
from django.db import connection, migrations
|
||||
from django.db.migrations.executor import MigrationExecutor
|
||||
from django.contrib.postgres.operations import HStoreExtension
|
||||
|
||||
from localized_fields.models import LocalizedModel
|
||||
|
||||
|
||||
def define_fake_model(fields=None, model_base=LocalizedModel, meta_options={}):
|
||||
name = str(uuid.uuid4()).replace('-', '')[:8]
|
||||
name = str(uuid.uuid4()).replace("-", "")[:8]
|
||||
|
||||
attributes = {
|
||||
'app_label': 'tests',
|
||||
'__module__': __name__,
|
||||
'__name__': name,
|
||||
'Meta': type('Meta', (object,), meta_options)
|
||||
"app_label": "tests",
|
||||
"__module__": __name__,
|
||||
"__name__": name,
|
||||
"Meta": type("Meta", (object,), meta_options),
|
||||
}
|
||||
|
||||
if fields:
|
||||
@@ -30,7 +30,6 @@ def get_fake_model(fields=None, model_base=LocalizedModel, meta_options={}):
|
||||
model = define_fake_model(fields, model_base, meta_options)
|
||||
|
||||
class TestProject:
|
||||
|
||||
def clone(self, *_args, **_kwargs):
|
||||
return self
|
||||
|
||||
@@ -44,7 +43,8 @@ def get_fake_model(fields=None, model_base=LocalizedModel, meta_options={}):
|
||||
with connection.schema_editor() as schema_editor:
|
||||
migration_executor = MigrationExecutor(schema_editor.connection)
|
||||
migration_executor.apply_migration(
|
||||
TestProject(), TestMigration('eh', 'postgres_extra'))
|
||||
TestProject(), TestMigration("eh", "postgres_extra")
|
||||
)
|
||||
|
||||
schema_editor.create_model(model)
|
||||
|
||||
|
||||
@@ -4,9 +4,8 @@ from django.contrib.admin.checks import check_admin_app
|
||||
from django.db import models
|
||||
from django.test import TestCase
|
||||
|
||||
from localized_fields.fields import LocalizedField
|
||||
from localized_fields.admin import LocalizedFieldsAdminMixin
|
||||
|
||||
from localized_fields.fields import LocalizedField
|
||||
from tests.fake_model import get_fake_model
|
||||
|
||||
|
||||
@@ -22,16 +21,13 @@ class LocalizedFieldsAdminMixinTestCase(TestCase):
|
||||
|
||||
super(LocalizedFieldsAdminMixinTestCase, cls).setUpClass()
|
||||
|
||||
cls.TestRelModel = get_fake_model(
|
||||
{
|
||||
'description': LocalizedField()
|
||||
}
|
||||
)
|
||||
cls.TestRelModel = get_fake_model({"description": LocalizedField()})
|
||||
cls.TestModel = get_fake_model(
|
||||
{
|
||||
'title': LocalizedField(),
|
||||
'rel': models.ForeignKey(cls.TestRelModel,
|
||||
on_delete=models.CASCADE)
|
||||
"title": LocalizedField(),
|
||||
"rel": models.ForeignKey(
|
||||
cls.TestRelModel, on_delete=models.CASCADE
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
@@ -43,8 +39,8 @@ class LocalizedFieldsAdminMixinTestCase(TestCase):
|
||||
|
||||
@classmethod
|
||||
def test_model_admin(cls):
|
||||
"""Tests whether :see:LocalizedFieldsAdminMixin
|
||||
mixin are works with admin.ModelAdmin"""
|
||||
"""Tests whether :see:LocalizedFieldsAdminMixin mixin are works with
|
||||
admin.ModelAdmin."""
|
||||
|
||||
@admin.register(cls.TestModel)
|
||||
class TestModelAdmin(LocalizedFieldsAdminMixin, admin.ModelAdmin):
|
||||
@@ -54,34 +50,32 @@ class LocalizedFieldsAdminMixinTestCase(TestCase):
|
||||
|
||||
@classmethod
|
||||
def test_stackedmodel_admin(cls):
|
||||
"""Tests whether :see:LocalizedFieldsAdminMixin mixin are works
|
||||
with admin.StackedInline"""
|
||||
"""Tests whether :see:LocalizedFieldsAdminMixin mixin are works with
|
||||
admin.StackedInline."""
|
||||
|
||||
class TestModelStackedInline(LocalizedFieldsAdminMixin,
|
||||
admin.StackedInline):
|
||||
class TestModelStackedInline(
|
||||
LocalizedFieldsAdminMixin, admin.StackedInline
|
||||
):
|
||||
model = cls.TestModel
|
||||
|
||||
@admin.register(cls.TestRelModel)
|
||||
class TestRelModelAdmin(admin.ModelAdmin):
|
||||
inlines = [
|
||||
TestModelStackedInline,
|
||||
]
|
||||
inlines = [TestModelStackedInline]
|
||||
|
||||
assert len(check_admin_app(apps.get_app_configs())) == 0
|
||||
|
||||
@classmethod
|
||||
def test_tabularmodel_admin(cls):
|
||||
"""Tests whether :see:LocalizedFieldsAdminMixin mixin are works
|
||||
with admin.TabularInline"""
|
||||
"""Tests whether :see:LocalizedFieldsAdminMixin mixin are works with
|
||||
admin.TabularInline."""
|
||||
|
||||
class TestModelTabularInline(LocalizedFieldsAdminMixin,
|
||||
admin.TabularInline):
|
||||
class TestModelTabularInline(
|
||||
LocalizedFieldsAdminMixin, admin.TabularInline
|
||||
):
|
||||
model = cls.TestModel
|
||||
|
||||
@admin.register(cls.TestRelModel)
|
||||
class TestRelModelAdmin(admin.ModelAdmin):
|
||||
inlines = [
|
||||
TestModelTabularInline,
|
||||
]
|
||||
inlines = [TestModelTabularInline]
|
||||
|
||||
assert len(check_admin_app(apps.get_app_configs())) == 0
|
||||
|
||||
@@ -25,8 +25,8 @@ class LocalizedBleachFieldTestCase(TestCase):
|
||||
"""Tests the :see:LocalizedBleachField class."""
|
||||
|
||||
def test_pre_save(self):
|
||||
"""Tests whether the :see:pre_save function
|
||||
bleaches all values in a :see:LocalizedValue."""
|
||||
"""Tests whether the :see:pre_save function bleaches all values in a
|
||||
:see:LocalizedValue."""
|
||||
|
||||
value = self._get_test_value()
|
||||
model, field = self._get_test_model(value)
|
||||
@@ -35,8 +35,8 @@ class LocalizedBleachFieldTestCase(TestCase):
|
||||
self._validate(value, bleached_value)
|
||||
|
||||
def test_pre_save_none(self):
|
||||
"""Tests whether the :see:pre_save function
|
||||
works properly when specifying :see:None."""
|
||||
"""Tests whether the :see:pre_save function works properly when
|
||||
specifying :see:None."""
|
||||
|
||||
model, field = self._get_test_model(None)
|
||||
|
||||
@@ -44,9 +44,8 @@ class LocalizedBleachFieldTestCase(TestCase):
|
||||
assert not bleached_value
|
||||
|
||||
def test_pre_save_none_values(self):
|
||||
"""Tests whether the :see:pre_save function
|
||||
works properly when one of the languages has
|
||||
no text and is None."""
|
||||
"""Tests whether the :see:pre_save function works properly when one of
|
||||
the languages has no text and is None."""
|
||||
|
||||
value = self._get_test_value()
|
||||
value.set(settings.LANGUAGE_CODE, None)
|
||||
@@ -58,14 +57,13 @@ class LocalizedBleachFieldTestCase(TestCase):
|
||||
|
||||
@staticmethod
|
||||
def _get_test_model(value):
|
||||
"""Gets a test model and a artifically
|
||||
constructed :see:LocalizedBleachField
|
||||
instance to test with."""
|
||||
"""Gets a test model and a artifically constructed
|
||||
:see:LocalizedBleachField instance to test with."""
|
||||
|
||||
model = TestModel(value)
|
||||
|
||||
field = LocalizedBleachField()
|
||||
field.attname = 'value'
|
||||
field.attname = "value"
|
||||
return model, field
|
||||
|
||||
@staticmethod
|
||||
@@ -75,14 +73,14 @@ class LocalizedBleachFieldTestCase(TestCase):
|
||||
value = LocalizedValue()
|
||||
|
||||
for lang_code, lang_name in settings.LANGUAGES:
|
||||
value.set(lang_code, '<script>%s</script>' % lang_name)
|
||||
value.set(lang_code, "<script>%s</script>" % lang_name)
|
||||
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _validate(non_bleached_value, bleached_value):
|
||||
"""Validates whether the specified non-bleached
|
||||
value ended up being correctly bleached.
|
||||
"""Validates whether the specified non-bleached value ended up being
|
||||
correctly bleached.
|
||||
|
||||
Arguments:
|
||||
non_bleached_value:
|
||||
@@ -98,8 +96,7 @@ class LocalizedBleachFieldTestCase(TestCase):
|
||||
continue
|
||||
|
||||
expected_value = bleach.clean(
|
||||
non_bleached_value.get(lang_code),
|
||||
get_bleach_default_options()
|
||||
non_bleached_value.get(lang_code), get_bleach_default_options()
|
||||
)
|
||||
|
||||
assert bleached_value.get(lang_code) == expected_value
|
||||
|
||||
@@ -7,26 +7,34 @@ from .fake_model import get_fake_model
|
||||
|
||||
|
||||
class LocalizedBulkTestCase(TestCase):
|
||||
"""Tests bulk operations with data structures provided
|
||||
by the django-localized-fields library."""
|
||||
"""Tests bulk operations with data structures provided by the django-
|
||||
localized-fields library."""
|
||||
|
||||
@staticmethod
|
||||
def test_localized_bulk_insert():
|
||||
"""Tests whether bulk inserts work properly when using
|
||||
a :see:LocalizedUniqueSlugField in the model."""
|
||||
"""Tests whether bulk inserts work properly when using a
|
||||
:see:LocalizedUniqueSlugField in the model."""
|
||||
|
||||
model = get_fake_model(
|
||||
{
|
||||
'name': LocalizedField(),
|
||||
'slug': LocalizedUniqueSlugField(populate_from='name', include_time=True),
|
||||
'score': models.IntegerField()
|
||||
"name": LocalizedField(),
|
||||
"slug": LocalizedUniqueSlugField(
|
||||
populate_from="name", include_time=True
|
||||
),
|
||||
"score": models.IntegerField(),
|
||||
}
|
||||
)
|
||||
|
||||
to_create = [
|
||||
model(name={'en': 'english name 1', 'ro': 'romanian name 1'}, score=1),
|
||||
model(name={'en': 'english name 2', 'ro': 'romanian name 2'}, score=2),
|
||||
model(name={'en': 'english name 3', 'ro': 'romanian name 3'}, score=3)
|
||||
model(
|
||||
name={"en": "english name 1", "ro": "romanian name 1"}, score=1
|
||||
),
|
||||
model(
|
||||
name={"en": "english name 2", "ro": "romanian name 2"}, score=2
|
||||
),
|
||||
model(
|
||||
name={"en": "english name 3", "ro": "romanian name 3"}, score=3
|
||||
),
|
||||
]
|
||||
|
||||
model.objects.bulk_create(to_create)
|
||||
@@ -34,9 +42,7 @@ class LocalizedBulkTestCase(TestCase):
|
||||
|
||||
for obj in to_create:
|
||||
obj_db = model.objects.filter(
|
||||
name__en=obj.name.en,
|
||||
name__ro=obj.name.ro,
|
||||
score=obj.score
|
||||
name__en=obj.name.en, name__ro=obj.name.ro, score=obj.score
|
||||
).first()
|
||||
|
||||
assert obj_db
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
from django.test import TestCase
|
||||
from django.db import models
|
||||
from django.utils import translation
|
||||
from django.conf import settings
|
||||
from django.contrib.postgres.aggregates import ArrayAgg
|
||||
from django.db import models
|
||||
from django.test import TestCase
|
||||
from django.utils import translation
|
||||
|
||||
from localized_fields.expressions import LocalizedRef
|
||||
from localized_fields.fields import LocalizedField
|
||||
from localized_fields.value import LocalizedValue
|
||||
from localized_fields.expressions import LocalizedRef
|
||||
|
||||
from .fake_model import get_fake_model
|
||||
|
||||
@@ -24,15 +24,17 @@ class LocalizedExpressionsTestCase(TestCase):
|
||||
super(LocalizedExpressionsTestCase, cls).setUpClass()
|
||||
|
||||
cls.TestModel1 = get_fake_model(
|
||||
{
|
||||
'name': models.CharField(null=False, blank=False, max_length=255),
|
||||
}
|
||||
{"name": models.CharField(null=False, blank=False, max_length=255)}
|
||||
)
|
||||
|
||||
cls.TestModel2 = get_fake_model(
|
||||
{
|
||||
'text': LocalizedField(),
|
||||
'other': models.ForeignKey(cls.TestModel1, related_name='features', on_delete=models.CASCADE)
|
||||
"text": LocalizedField(),
|
||||
"other": models.ForeignKey(
|
||||
cls.TestModel1,
|
||||
related_name="features",
|
||||
on_delete=models.CASCADE,
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
@@ -40,24 +42,28 @@ class LocalizedExpressionsTestCase(TestCase):
|
||||
def test_localized_ref(cls):
|
||||
"""Tests whether the :see:LocalizedRef expression properly works."""
|
||||
|
||||
obj = cls.TestModel1.objects.create(name='bla bla')
|
||||
obj = cls.TestModel1.objects.create(name="bla bla")
|
||||
for i in range(0, 10):
|
||||
cls.TestModel2.objects.create(
|
||||
text=LocalizedValue(dict(en='text_%d_en' % i, ro='text_%d_ro' % i, nl='text_%d_nl' % i)),
|
||||
other=obj
|
||||
text=LocalizedValue(
|
||||
dict(
|
||||
en="text_%d_en" % i,
|
||||
ro="text_%d_ro" % i,
|
||||
nl="text_%d_nl" % i,
|
||||
)
|
||||
),
|
||||
other=obj,
|
||||
)
|
||||
|
||||
def create_queryset(ref):
|
||||
return (
|
||||
cls.TestModel1.objects
|
||||
.annotate(mytexts=ref)
|
||||
.values_list('mytexts', flat=True)
|
||||
return cls.TestModel1.objects.annotate(mytexts=ref).values_list(
|
||||
"mytexts", flat=True
|
||||
)
|
||||
|
||||
# assert that it properly selects the currently active language
|
||||
for lang_code, _ in settings.LANGUAGES:
|
||||
translation.activate(lang_code)
|
||||
queryset = create_queryset(LocalizedRef('features__text'))
|
||||
queryset = create_queryset(LocalizedRef("features__text"))
|
||||
|
||||
for index, value in enumerate(queryset):
|
||||
assert translation.get_language() in value
|
||||
@@ -66,19 +72,21 @@ class LocalizedExpressionsTestCase(TestCase):
|
||||
# ensure that the default language is used in case no
|
||||
# language is active at all
|
||||
translation.deactivate_all()
|
||||
queryset = create_queryset(LocalizedRef('features__text'))
|
||||
queryset = create_queryset(LocalizedRef("features__text"))
|
||||
for index, value in enumerate(queryset):
|
||||
assert settings.LANGUAGE_CODE in value
|
||||
assert str(index) in value
|
||||
|
||||
# ensures that overriding the language works properly
|
||||
queryset = create_queryset(LocalizedRef('features__text', 'ro'))
|
||||
queryset = create_queryset(LocalizedRef("features__text", "ro"))
|
||||
for index, value in enumerate(queryset):
|
||||
assert 'ro' in value
|
||||
assert "ro" in value
|
||||
assert str(index) in value
|
||||
|
||||
# ensures that using this in combination with ArrayAgg works properly
|
||||
queryset = create_queryset(ArrayAgg(LocalizedRef('features__text', 'ro'))).first()
|
||||
queryset = create_queryset(
|
||||
ArrayAgg(LocalizedRef("features__text", "ro"))
|
||||
).first()
|
||||
assert isinstance(queryset, list)
|
||||
for value in queryset:
|
||||
assert 'ro' in value
|
||||
assert "ro" in value
|
||||
|
||||
@@ -18,8 +18,8 @@ class LocalizedFieldTestCase(TestCase):
|
||||
|
||||
@staticmethod
|
||||
def test_init():
|
||||
"""Tests whether the :see:__init__ function
|
||||
correctly handles parameters"""
|
||||
"""Tests whether the :see:__init__ function correctly handles
|
||||
parameters."""
|
||||
|
||||
field = LocalizedField(blank=True)
|
||||
assert field.required == []
|
||||
@@ -28,16 +28,17 @@ class LocalizedFieldTestCase(TestCase):
|
||||
assert field.required == [settings.LANGUAGE_CODE]
|
||||
|
||||
field = LocalizedField(required=True)
|
||||
assert field.required == [lang_code for lang_code, _ in
|
||||
settings.LANGUAGES]
|
||||
assert field.required == [
|
||||
lang_code for lang_code, _ in settings.LANGUAGES
|
||||
]
|
||||
|
||||
field = LocalizedField(required=False)
|
||||
assert field.required == []
|
||||
|
||||
@staticmethod
|
||||
def test_from_db_value():
|
||||
"""Tests whether the :see:from_db_value function
|
||||
produces the expected :see:LocalizedValue."""
|
||||
"""Tests whether the :see:from_db_value function produces the expected
|
||||
:see:LocalizedValue."""
|
||||
|
||||
input_data = get_init_values()
|
||||
localized_value = LocalizedField().from_db_value(input_data)
|
||||
@@ -47,8 +48,8 @@ class LocalizedFieldTestCase(TestCase):
|
||||
|
||||
@staticmethod
|
||||
def test_from_db_value_none():
|
||||
"""Tests whether the :see:from_db_value function
|
||||
correctly handles None values."""
|
||||
"""Tests whether the :see:from_db_value function correctly handles None
|
||||
values."""
|
||||
|
||||
localized_value = LocalizedField().from_db_value(None)
|
||||
|
||||
@@ -56,9 +57,8 @@ class LocalizedFieldTestCase(TestCase):
|
||||
assert localized_value.get(lang_code) is None
|
||||
|
||||
def test_from_db_value_none_return_none(self):
|
||||
"""Tests whether the :see:from_db_value function
|
||||
correctly handles None values when LOCALIZED_FIELDS_EXPERIMENTAL
|
||||
is set to True."""
|
||||
"""Tests whether the :see:from_db_value function correctly handles None
|
||||
values when LOCALIZED_FIELDS_EXPERIMENTAL is set to True."""
|
||||
|
||||
with self.settings(LOCALIZED_FIELDS_EXPERIMENTAL=True):
|
||||
localized_value = LocalizedField.from_db_value(None)
|
||||
@@ -67,8 +67,8 @@ class LocalizedFieldTestCase(TestCase):
|
||||
|
||||
@staticmethod
|
||||
def test_to_python():
|
||||
"""Tests whether the :see:to_python function
|
||||
produces the expected :see:LocalizedValue."""
|
||||
"""Tests whether the :see:to_python function produces the expected
|
||||
:see:LocalizedValue."""
|
||||
|
||||
input_data = get_init_values()
|
||||
localized_value = LocalizedField().to_python(input_data)
|
||||
@@ -78,17 +78,16 @@ class LocalizedFieldTestCase(TestCase):
|
||||
|
||||
@staticmethod
|
||||
def test_to_python_non_json():
|
||||
"""Tests whether the :see:to_python function
|
||||
properly handles a string that is not JSON."""
|
||||
"""Tests whether the :see:to_python function properly handles a string
|
||||
that is not JSON."""
|
||||
|
||||
localized_value = LocalizedField().to_python('my value')
|
||||
assert localized_value.get() == 'my value'
|
||||
localized_value = LocalizedField().to_python("my value")
|
||||
assert localized_value.get() == "my value"
|
||||
|
||||
@staticmethod
|
||||
def test_to_python_none():
|
||||
"""Tests whether the :see:to_python function
|
||||
produces the expected :see:LocalizedValue
|
||||
instance when it is passes None."""
|
||||
"""Tests whether the :see:to_python function produces the expected
|
||||
:see:LocalizedValue instance when it is passes None."""
|
||||
|
||||
localized_value = LocalizedField().to_python(None)
|
||||
assert localized_value
|
||||
@@ -98,9 +97,8 @@ class LocalizedFieldTestCase(TestCase):
|
||||
|
||||
@staticmethod
|
||||
def test_to_python_non_dict():
|
||||
"""Tests whether the :see:to_python function produces
|
||||
the expected :see:LocalizedValue when it is
|
||||
passed a non-dictionary value."""
|
||||
"""Tests whether the :see:to_python function produces the expected
|
||||
:see:LocalizedValue when it is passed a non-dictionary value."""
|
||||
|
||||
localized_value = LocalizedField().to_python(list())
|
||||
assert localized_value
|
||||
@@ -110,9 +108,8 @@ class LocalizedFieldTestCase(TestCase):
|
||||
|
||||
@staticmethod
|
||||
def test_to_python_str():
|
||||
"""Tests whether the :see:to_python function produces
|
||||
the expected :see:LocalizedValue when it is
|
||||
passed serialized string value."""
|
||||
"""Tests whether the :see:to_python function produces the expected
|
||||
:see:LocalizedValue when it is passed serialized string value."""
|
||||
|
||||
serialized_str = json.dumps(get_init_values())
|
||||
localized_value = LocalizedField().to_python(serialized_str)
|
||||
@@ -124,8 +121,8 @@ class LocalizedFieldTestCase(TestCase):
|
||||
|
||||
@staticmethod
|
||||
def test_get_prep_value():
|
||||
""""Tests whether the :see:get_prep_value function
|
||||
produces the expected dictionary."""
|
||||
""""Tests whether the :see:get_prep_value function produces the
|
||||
expected dictionary."""
|
||||
|
||||
input_data = get_init_values()
|
||||
localized_value = LocalizedValue(input_data)
|
||||
@@ -138,25 +135,24 @@ class LocalizedFieldTestCase(TestCase):
|
||||
|
||||
@staticmethod
|
||||
def test_get_prep_value_none():
|
||||
"""Tests whether the :see:get_prep_value function
|
||||
produces the expected output when it is passed None."""
|
||||
"""Tests whether the :see:get_prep_value function produces the expected
|
||||
output when it is passed None."""
|
||||
|
||||
output_data = LocalizedField().get_prep_value(None)
|
||||
assert not output_data
|
||||
|
||||
@staticmethod
|
||||
def test_get_prep_value_no_localized_value():
|
||||
"""Tests whether the :see:get_prep_value function
|
||||
produces the expected output when it is passed a
|
||||
non-LocalizedValue value."""
|
||||
"""Tests whether the :see:get_prep_value function produces the expected
|
||||
output when it is passed a non-LocalizedValue value."""
|
||||
|
||||
output_data = LocalizedField().get_prep_value(['huh'])
|
||||
output_data = LocalizedField().get_prep_value(["huh"])
|
||||
assert not output_data
|
||||
|
||||
def test_get_prep_value_clean(self):
|
||||
"""Tests whether the :see:get_prep_value produces
|
||||
None as the output when it is passed an empty, but
|
||||
valid LocalizedValue value but, only when null=True."""
|
||||
"""Tests whether the :see:get_prep_value produces None as the output
|
||||
when it is passed an empty, but valid LocalizedValue value but, only
|
||||
when null=True."""
|
||||
|
||||
localized_value = LocalizedValue()
|
||||
|
||||
@@ -165,17 +161,14 @@ class LocalizedFieldTestCase(TestCase):
|
||||
|
||||
assert not LocalizedField(null=True).get_prep_value(localized_value)
|
||||
assert not LocalizedField().clean(None)
|
||||
assert not LocalizedField().clean(['huh'])
|
||||
assert not LocalizedField().clean(["huh"])
|
||||
|
||||
@staticmethod
|
||||
def test_formfield():
|
||||
"""Tests whether the :see:formfield function
|
||||
correctly returns a valid form."""
|
||||
"""Tests whether the :see:formfield function correctly returns a valid
|
||||
form."""
|
||||
|
||||
assert isinstance(
|
||||
LocalizedField().formfield(),
|
||||
LocalizedFieldForm
|
||||
)
|
||||
assert isinstance(LocalizedField().formfield(), LocalizedFieldForm)
|
||||
|
||||
# case optional filling
|
||||
field = LocalizedField(blank=True, required=[])
|
||||
@@ -190,7 +183,7 @@ class LocalizedFieldTestCase(TestCase):
|
||||
assert not field.required
|
||||
|
||||
# case required for specific languages
|
||||
required_langs = ['ro', 'nl']
|
||||
required_langs = ["ro", "nl"]
|
||||
field = LocalizedField(blank=False, required=required_langs)
|
||||
assert field.formfield().required
|
||||
for field in field.formfield().fields:
|
||||
@@ -206,31 +199,31 @@ class LocalizedFieldTestCase(TestCase):
|
||||
assert field.required
|
||||
|
||||
def test_descriptor_user_defined_primary_key(self):
|
||||
"""Tests that descriptor works even when primary key is user defined."""
|
||||
model = get_fake_model(dict(
|
||||
slug=models.SlugField(primary_key=True),
|
||||
title=LocalizedField()
|
||||
))
|
||||
"""Tests that descriptor works even when primary key is user
|
||||
defined."""
|
||||
model = get_fake_model(
|
||||
dict(
|
||||
slug=models.SlugField(primary_key=True), title=LocalizedField()
|
||||
)
|
||||
)
|
||||
|
||||
obj = model.objects.create(slug='test', title='test')
|
||||
assert obj.title == 'test'
|
||||
obj = model.objects.create(slug="test", title="test")
|
||||
assert obj.title == "test"
|
||||
|
||||
def test_required_all(self):
|
||||
"""Tests whether passing required=True properly validates
|
||||
that all languages are filled in."""
|
||||
"""Tests whether passing required=True properly validates that all
|
||||
languages are filled in."""
|
||||
|
||||
model = get_fake_model(dict(
|
||||
title=LocalizedField(required=True)
|
||||
))
|
||||
model = get_fake_model(dict(title=LocalizedField(required=True)))
|
||||
|
||||
with self.assertRaises(IntegrityError):
|
||||
model.objects.create(title=dict(ro='romanian', nl='dutch'))
|
||||
model.objects.create(title=dict(ro="romanian", nl="dutch"))
|
||||
|
||||
with self.assertRaises(IntegrityError):
|
||||
model.objects.create(title=dict(nl='dutch'))
|
||||
model.objects.create(title=dict(nl="dutch"))
|
||||
|
||||
with self.assertRaises(IntegrityError):
|
||||
model.objects.create(title=dict(random='random'))
|
||||
model.objects.create(title=dict(random="random"))
|
||||
|
||||
with self.assertRaises(IntegrityError):
|
||||
model.objects.create(title=dict())
|
||||
@@ -239,28 +232,27 @@ class LocalizedFieldTestCase(TestCase):
|
||||
model.objects.create(title=None)
|
||||
|
||||
with self.assertRaises(IntegrityError):
|
||||
model.objects.create(title='')
|
||||
model.objects.create(title="")
|
||||
|
||||
with self.assertRaises(IntegrityError):
|
||||
model.objects.create(title=' ')
|
||||
model.objects.create(title=" ")
|
||||
|
||||
def test_required_some(self):
|
||||
"""Tests whether passing an array to required,
|
||||
properly validates whether the specified languages
|
||||
are marked as required."""
|
||||
"""Tests whether passing an array to required, properly validates
|
||||
whether the specified languages are marked as required."""
|
||||
|
||||
model = get_fake_model(dict(
|
||||
title=LocalizedField(required=['nl', 'ro'])
|
||||
))
|
||||
model = get_fake_model(
|
||||
dict(title=LocalizedField(required=["nl", "ro"]))
|
||||
)
|
||||
|
||||
with self.assertRaises(IntegrityError):
|
||||
model.objects.create(title=dict(ro='romanian', nl='dutch'))
|
||||
model.objects.create(title=dict(ro="romanian", nl="dutch"))
|
||||
|
||||
with self.assertRaises(IntegrityError):
|
||||
model.objects.create(title=dict(nl='dutch'))
|
||||
model.objects.create(title=dict(nl="dutch"))
|
||||
|
||||
with self.assertRaises(IntegrityError):
|
||||
model.objects.create(title=dict(random='random'))
|
||||
model.objects.create(title=dict(random="random"))
|
||||
|
||||
with self.assertRaises(IntegrityError):
|
||||
model.objects.create(title=dict())
|
||||
@@ -269,7 +261,7 @@ class LocalizedFieldTestCase(TestCase):
|
||||
model.objects.create(title=None)
|
||||
|
||||
with self.assertRaises(IntegrityError):
|
||||
model.objects.create(title='')
|
||||
model.objects.create(title="")
|
||||
|
||||
with self.assertRaises(IntegrityError):
|
||||
model.objects.create(title=' ')
|
||||
model.objects.create(title=" ")
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
import json
|
||||
import os
|
||||
import pickle
|
||||
import shutil
|
||||
import tempfile as sys_tempfile
|
||||
import pickle
|
||||
import json
|
||||
|
||||
from django import forms
|
||||
from django.test import TestCase, override_settings
|
||||
from django.core.files.base import File, ContentFile
|
||||
from django.core.files import temp as tempfile
|
||||
from django.core.files.base import ContentFile, File
|
||||
from django.test import TestCase, override_settings
|
||||
|
||||
from localized_fields.fields import LocalizedFileField
|
||||
from localized_fields.value import LocalizedValue
|
||||
from localized_fields.fields.file_field import LocalizedFieldFile
|
||||
from localized_fields.forms import LocalizedFileFieldForm
|
||||
from localized_fields.value import LocalizedFileValue
|
||||
from localized_fields.value import LocalizedFileValue, LocalizedValue
|
||||
from localized_fields.widgets import LocalizedFileWidget
|
||||
from .fake_model import get_fake_model
|
||||
|
||||
from .fake_model import get_fake_model
|
||||
|
||||
MEDIA_ROOT = sys_tempfile.mkdtemp()
|
||||
|
||||
@@ -30,11 +30,7 @@ class LocalizedFileFieldTestCase(TestCase):
|
||||
|
||||
super().setUpClass()
|
||||
|
||||
cls.FileFieldModel = get_fake_model(
|
||||
{
|
||||
'file': LocalizedFileField(),
|
||||
}
|
||||
)
|
||||
cls.FileFieldModel = get_fake_model({"file": LocalizedFileField()})
|
||||
if not os.path.isdir(MEDIA_ROOT):
|
||||
os.makedirs(MEDIA_ROOT)
|
||||
|
||||
@@ -45,48 +41,49 @@ class LocalizedFileFieldTestCase(TestCase):
|
||||
|
||||
@classmethod
|
||||
def test_assign(cls):
|
||||
"""Tests whether the :see:LocalizedFileValueDescriptor works properly"""
|
||||
"""Tests whether the :see:LocalizedFileValueDescriptor works
|
||||
properly."""
|
||||
|
||||
temp_file = tempfile.NamedTemporaryFile(dir=MEDIA_ROOT)
|
||||
instance = cls.FileFieldModel()
|
||||
instance.file = {'en': temp_file.name}
|
||||
instance.file = {"en": temp_file.name}
|
||||
assert isinstance(instance.file.en, LocalizedFieldFile)
|
||||
assert instance.file.en.name == temp_file.name
|
||||
|
||||
field_dump = pickle.dumps(instance.file)
|
||||
instance = cls.FileFieldModel()
|
||||
instance.file = pickle.loads(field_dump)
|
||||
assert instance.file.en.field == instance._meta.get_field('file')
|
||||
assert instance.file.en.field == instance._meta.get_field("file")
|
||||
assert instance.file.en.instance == instance
|
||||
assert isinstance(instance.file.en, LocalizedFieldFile)
|
||||
|
||||
instance = cls.FileFieldModel()
|
||||
instance.file = {'en': ContentFile("test", "testfilename")}
|
||||
instance.file = {"en": ContentFile("test", "testfilename")}
|
||||
assert isinstance(instance.file.en, LocalizedFieldFile)
|
||||
assert instance.file.en.name == "testfilename"
|
||||
|
||||
another_instance = cls.FileFieldModel()
|
||||
another_instance.file = {'ro': instance.file.en}
|
||||
another_instance.file = {"ro": instance.file.en}
|
||||
assert another_instance == another_instance.file.ro.instance
|
||||
assert another_instance.file.ro.lang == 'ro'
|
||||
assert another_instance.file.ro.lang == "ro"
|
||||
|
||||
@classmethod
|
||||
def test_save_form_data(cls):
|
||||
"""Tests whether the :see:save_form_data function correctly set
|
||||
a valid value."""
|
||||
"""Tests whether the :see:save_form_data function correctly set a valid
|
||||
value."""
|
||||
|
||||
instance = cls.FileFieldModel()
|
||||
data = LocalizedFileValue({'en': False})
|
||||
instance._meta.get_field('file').save_form_data(instance, data)
|
||||
assert instance.file.en == ''
|
||||
data = LocalizedFileValue({"en": False})
|
||||
instance._meta.get_field("file").save_form_data(instance, data)
|
||||
assert instance.file.en == ""
|
||||
|
||||
@classmethod
|
||||
def test_pre_save(cls):
|
||||
"""Tests whether the :see:pre_save function works properly."""
|
||||
|
||||
instance = cls.FileFieldModel()
|
||||
instance.file = {'en': ContentFile("test", "testfilename")}
|
||||
instance._meta.get_field('file').pre_save(instance, False)
|
||||
instance.file = {"en": ContentFile("test", "testfilename")}
|
||||
instance._meta.get_field("file").pre_save(instance, False)
|
||||
assert instance.file.en._committed is True
|
||||
|
||||
@classmethod
|
||||
@@ -99,8 +96,8 @@ class LocalizedFileFieldTestCase(TestCase):
|
||||
# Calling delete on an unset FileField should not call the file deletion
|
||||
# process, but fail silently
|
||||
instance.file.en.delete()
|
||||
instance.file.en.save('testfilename', temp_file)
|
||||
assert instance.file.en.name == 'testfilename'
|
||||
instance.file.en.save("testfilename", temp_file)
|
||||
assert instance.file.en.name == "testfilename"
|
||||
instance.file.en.delete()
|
||||
assert instance.file.en.name is None
|
||||
|
||||
@@ -110,27 +107,29 @@ class LocalizedFileFieldTestCase(TestCase):
|
||||
works correctly."""
|
||||
|
||||
instance = cls.FileFieldModel()
|
||||
field = instance._meta.get_field('file')
|
||||
field.upload_to = '{lang}/'
|
||||
filename = field.generate_filename(instance, 'test', 'en')
|
||||
assert filename == 'en/test'
|
||||
field.upload_to = lambda instance, filename, lang: \
|
||||
'%s_%s' % (lang, filename)
|
||||
filename = field.generate_filename(instance, 'test', 'en')
|
||||
assert filename == 'en_test'
|
||||
field = instance._meta.get_field("file")
|
||||
field.upload_to = "{lang}/"
|
||||
filename = field.generate_filename(instance, "test", "en")
|
||||
assert filename == "en/test"
|
||||
field.upload_to = lambda instance, filename, lang: "%s_%s" % (
|
||||
lang,
|
||||
filename,
|
||||
)
|
||||
filename = field.generate_filename(instance, "test", "en")
|
||||
assert filename == "en_test"
|
||||
|
||||
@classmethod
|
||||
@override_settings(LANGUAGES=(('en', 'English'),))
|
||||
@override_settings(LANGUAGES=(("en", "English"),))
|
||||
def test_value_to_string(cls):
|
||||
"""Tests whether the :see:LocalizedFileField
|
||||
class's :see:value_to_string function works properly."""
|
||||
"""Tests whether the :see:LocalizedFileField class's
|
||||
:see:value_to_string function works properly."""
|
||||
|
||||
temp_file = File(tempfile.NamedTemporaryFile())
|
||||
instance = cls.FileFieldModel()
|
||||
field = cls.FileFieldModel._meta.get_field('file')
|
||||
field.upload_to = ''
|
||||
instance.file.en.save('testfilename', temp_file)
|
||||
expected_value_to_string = json.dumps({'en': 'testfilename'})
|
||||
field = cls.FileFieldModel._meta.get_field("file")
|
||||
field.upload_to = ""
|
||||
instance.file.en.save("testfilename", temp_file)
|
||||
expected_value_to_string = json.dumps({"en": "testfilename"})
|
||||
assert field.value_to_string(instance) == expected_value_to_string
|
||||
|
||||
@staticmethod
|
||||
@@ -138,15 +137,15 @@ class LocalizedFileFieldTestCase(TestCase):
|
||||
"""Tests whether the :see:get_prep_value function returns correctly
|
||||
value."""
|
||||
|
||||
value = LocalizedValue({'en': None})
|
||||
value = LocalizedValue({"en": None})
|
||||
assert LocalizedFileField().get_prep_value(None) is None
|
||||
assert isinstance(LocalizedFileField().get_prep_value(value), dict)
|
||||
assert LocalizedFileField().get_prep_value(value)['en'] == ''
|
||||
assert LocalizedFileField().get_prep_value(value)["en"] == ""
|
||||
|
||||
@staticmethod
|
||||
def test_formfield():
|
||||
"""Tests whether the :see:formfield function correctly returns
|
||||
a valid form."""
|
||||
"""Tests whether the :see:formfield function correctly returns a valid
|
||||
form."""
|
||||
|
||||
form_field = LocalizedFileField().formfield()
|
||||
assert isinstance(form_field, LocalizedFileFieldForm)
|
||||
@@ -155,11 +154,13 @@ class LocalizedFileFieldTestCase(TestCase):
|
||||
|
||||
@staticmethod
|
||||
def test_deconstruct():
|
||||
"""Tests whether the :see:LocalizedFileField
|
||||
class's :see:deconstruct function works properly."""
|
||||
"""Tests whether the :see:LocalizedFileField class's :see:deconstruct
|
||||
function works properly."""
|
||||
|
||||
name, path, args, kwargs = LocalizedFileField().deconstruct()
|
||||
assert 'upload_to' in kwargs
|
||||
assert 'storage' not in kwargs
|
||||
name, path, args, kwargs = LocalizedFileField(storage='test').deconstruct()
|
||||
assert 'storage' in kwargs
|
||||
assert "upload_to" in kwargs
|
||||
assert "storage" not in kwargs
|
||||
name, path, args, kwargs = LocalizedFileField(
|
||||
storage="test"
|
||||
).deconstruct()
|
||||
assert "storage" in kwargs
|
||||
|
||||
@@ -16,7 +16,7 @@ class LocalizedFileFieldFormTestCase(TestCase):
|
||||
with self.assertRaises(ValidationError):
|
||||
formfield.clean([])
|
||||
with self.assertRaises(ValidationError):
|
||||
formfield.clean([], {'en': None})
|
||||
formfield.clean([], {"en": None})
|
||||
with self.assertRaises(ValidationError):
|
||||
formfield.clean("badvalue")
|
||||
with self.assertRaises(ValidationError):
|
||||
@@ -24,17 +24,17 @@ class LocalizedFileFieldFormTestCase(TestCase):
|
||||
formfield.clean(value)
|
||||
|
||||
formfield = LocalizedFileFieldForm(required=False)
|
||||
formfield.clean([''] * len(settings.LANGUAGES))
|
||||
formfield.clean(['', ''], ['', ''])
|
||||
formfield.clean([""] * len(settings.LANGUAGES))
|
||||
formfield.clean(["", ""], ["", ""])
|
||||
|
||||
def test_bound_data(self):
|
||||
"""Tests whether the :see:bound_data function is returns correctly
|
||||
value"""
|
||||
value."""
|
||||
|
||||
formfield = LocalizedFileFieldForm()
|
||||
assert formfield.bound_data([''], None) == ['']
|
||||
assert formfield.bound_data([""], None) == [""]
|
||||
|
||||
initial = dict([(lang, '') for lang, _ in settings.LANGUAGES])
|
||||
initial = dict([(lang, "") for lang, _ in settings.LANGUAGES])
|
||||
value = [None] * len(settings.LANGUAGES)
|
||||
expected_value = [''] * len(settings.LANGUAGES)
|
||||
expected_value = [""] * len(settings.LANGUAGES)
|
||||
assert formfield.bound_data(value, initial) == expected_value
|
||||
|
||||
@@ -9,16 +9,18 @@ class LocalizedFileWidgetTestCase(TestCase):
|
||||
|
||||
@staticmethod
|
||||
def test_get_context():
|
||||
"""Tests whether the :see:get_context correctly
|
||||
handles 'required' attribute, separately for each subwidget."""
|
||||
"""Tests whether the :see:get_context correctly handles 'required'
|
||||
attribute, separately for each subwidget."""
|
||||
|
||||
widget = LocalizedFileWidget()
|
||||
widget.widgets[0].is_required = True
|
||||
widget.widgets[1].is_required = True
|
||||
widget.widgets[2].is_required = False
|
||||
context = widget.get_context(name='test',
|
||||
value=LocalizedFileValue(dict(en='test')),
|
||||
attrs=dict(required=True))
|
||||
assert 'required' not in context['widget']['subwidgets'][0]['attrs']
|
||||
assert context['widget']['subwidgets'][1]['attrs']['required']
|
||||
assert 'required' not in context['widget']['subwidgets'][2]['attrs']
|
||||
context = widget.get_context(
|
||||
name="test",
|
||||
value=LocalizedFileValue(dict(en="test")),
|
||||
attrs=dict(required=True),
|
||||
)
|
||||
assert "required" not in context["widget"]["subwidgets"][0]["attrs"]
|
||||
assert context["widget"]["subwidgets"][1]["attrs"]["required"]
|
||||
assert "required" not in context["widget"]["subwidgets"][2]["attrs"]
|
||||
|
||||
@@ -9,8 +9,8 @@ class LocalizedFieldFormTestCase(TestCase):
|
||||
|
||||
@staticmethod
|
||||
def test_init():
|
||||
"""Tests whether the constructor correctly
|
||||
creates a field for every language."""
|
||||
"""Tests whether the constructor correctly creates a field for every
|
||||
language."""
|
||||
# case required for specific language
|
||||
form = LocalizedFieldForm(required=[settings.LANGUAGE_CODE])
|
||||
|
||||
@@ -42,8 +42,7 @@ class LocalizedFieldFormTestCase(TestCase):
|
||||
|
||||
@staticmethod
|
||||
def test_compress():
|
||||
"""Tests whether the :see:compress function
|
||||
is working properly."""
|
||||
"""Tests whether the :see:compress function is working properly."""
|
||||
|
||||
input_value = [lang_name for _, lang_name in settings.LANGUAGES]
|
||||
output_value = LocalizedFieldForm().compress(input_value)
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
from django.test import TestCase
|
||||
from django.db.utils import IntegrityError
|
||||
from django.conf import settings
|
||||
from django.db import connection
|
||||
from django.db.utils import IntegrityError
|
||||
from django.test import TestCase
|
||||
from django.utils import translation
|
||||
|
||||
from localized_fields.value import LocalizedIntegerValue
|
||||
from localized_fields.fields import LocalizedIntegerField
|
||||
from localized_fields.value import LocalizedIntegerValue
|
||||
|
||||
from .fake_model import get_fake_model
|
||||
|
||||
|
||||
class LocalizedIntegerFieldTestCase(TestCase):
|
||||
"""Tests whether the :see:LocalizedIntegerField
|
||||
and :see:LocalizedIntegerValue works properly."""
|
||||
"""Tests whether the :see:LocalizedIntegerField and
|
||||
:see:LocalizedIntegerValue works properly."""
|
||||
|
||||
TestModel = None
|
||||
|
||||
@@ -20,9 +20,7 @@ class LocalizedIntegerFieldTestCase(TestCase):
|
||||
def setUpClass(cls):
|
||||
super().setUpClass()
|
||||
|
||||
cls.TestModel = get_fake_model({
|
||||
'score': LocalizedIntegerField()
|
||||
})
|
||||
cls.TestModel = get_fake_model({"score": LocalizedIntegerField()})
|
||||
|
||||
def test_basic(self):
|
||||
"""Tests the basics of storing integer values."""
|
||||
@@ -37,8 +35,8 @@ class LocalizedIntegerFieldTestCase(TestCase):
|
||||
assert obj.score.get(lang_code) == index + 1
|
||||
|
||||
def test_primary_language_required(self):
|
||||
"""Tests whether the primary language is required by
|
||||
default and all other languages are optiona."""
|
||||
"""Tests whether the primary language is required by default and all
|
||||
other languages are optiona."""
|
||||
|
||||
# not filling in anything should raise IntegrityError,
|
||||
# the primary language is required
|
||||
@@ -57,8 +55,8 @@ class LocalizedIntegerFieldTestCase(TestCase):
|
||||
obj.save()
|
||||
|
||||
def test_default_value_none(self):
|
||||
"""Tests whether the default value for optional languages
|
||||
is NoneType."""
|
||||
"""Tests whether the default value for optional languages is
|
||||
NoneType."""
|
||||
|
||||
obj = self.TestModel()
|
||||
obj.score.set(settings.LANGUAGE_CODE, 1234)
|
||||
@@ -71,9 +69,8 @@ class LocalizedIntegerFieldTestCase(TestCase):
|
||||
assert obj.score.get(lang_code) is None
|
||||
|
||||
def test_translate(self):
|
||||
"""Tests whether casting the value to an integer
|
||||
results in the value being returned in the currently
|
||||
active language as an integer."""
|
||||
"""Tests whether casting the value to an integer results in the value
|
||||
being returned in the currently active language as an integer."""
|
||||
|
||||
obj = self.TestModel()
|
||||
for index, (lang_code, _) in enumerate(settings.LANGUAGES):
|
||||
@@ -87,10 +84,9 @@ class LocalizedIntegerFieldTestCase(TestCase):
|
||||
assert obj.score.translate() == index + 1
|
||||
|
||||
def test_translate_primary_fallback(self):
|
||||
"""Tests whether casting the value to an integer
|
||||
results in the value begin returned in the active
|
||||
language and falls back to the primary language
|
||||
if there is no value in that language."""
|
||||
"""Tests whether casting the value to an integer results in the value
|
||||
begin returned in the active language and falls back to the primary
|
||||
language if there is no value in that language."""
|
||||
|
||||
obj = self.TestModel()
|
||||
obj.score.set(settings.LANGUAGE_CODE, 25)
|
||||
@@ -103,9 +99,8 @@ class LocalizedIntegerFieldTestCase(TestCase):
|
||||
assert int(obj.score) == 25
|
||||
|
||||
def test_get_default_value(self):
|
||||
"""Tests whether getting the value in a specific
|
||||
language properly returns the specified default
|
||||
in case it is not available."""
|
||||
"""Tests whether getting the value in a specific language properly
|
||||
returns the specified default in case it is not available."""
|
||||
|
||||
obj = self.TestModel()
|
||||
obj.score.set(settings.LANGUAGE_CODE, 25)
|
||||
@@ -115,12 +110,11 @@ class LocalizedIntegerFieldTestCase(TestCase):
|
||||
assert obj.score.get(secondary_language, 1337) == 1337
|
||||
|
||||
def test_completely_optional(self):
|
||||
"""Tests whether having all languages optional
|
||||
works properly."""
|
||||
"""Tests whether having all languages optional works properly."""
|
||||
|
||||
model = get_fake_model({
|
||||
'score': LocalizedIntegerField(null=True, required=[], blank=True)
|
||||
})
|
||||
model = get_fake_model(
|
||||
{"score": LocalizedIntegerField(null=True, required=[], blank=True)}
|
||||
)
|
||||
|
||||
obj = model()
|
||||
obj.save()
|
||||
@@ -129,19 +123,18 @@ class LocalizedIntegerFieldTestCase(TestCase):
|
||||
assert getattr(obj.score, lang_code) is None
|
||||
|
||||
def test_store_string(self):
|
||||
"""Tests whether the field properly raises
|
||||
an error when trying to store a non-integer."""
|
||||
"""Tests whether the field properly raises an error when trying to
|
||||
store a non-integer."""
|
||||
|
||||
for lang_code, _ in settings.LANGUAGES:
|
||||
obj = self.TestModel()
|
||||
with self.assertRaises(IntegrityError):
|
||||
obj.score.set(lang_code, 'haha')
|
||||
obj.score.set(lang_code, "haha")
|
||||
obj.save()
|
||||
|
||||
def test_none_if_illegal_value_stored(self):
|
||||
"""Tests whether None is returned for a language
|
||||
if the value stored in the database is not an
|
||||
integer."""
|
||||
"""Tests whether None is returned for a language if the value stored in
|
||||
the database is not an integer."""
|
||||
|
||||
obj = self.TestModel()
|
||||
obj.score.set(settings.LANGUAGE_CODE, 25)
|
||||
@@ -155,12 +148,15 @@ class LocalizedIntegerFieldTestCase(TestCase):
|
||||
assert obj.score.get(settings.LANGUAGE_CODE) is None
|
||||
|
||||
def test_default_value(self):
|
||||
"""Tests whether a default is properly set
|
||||
when specified."""
|
||||
"""Tests whether a default is properly set when specified."""
|
||||
|
||||
model = get_fake_model({
|
||||
'score': LocalizedIntegerField(default={settings.LANGUAGE_CODE: 75})
|
||||
})
|
||||
model = get_fake_model(
|
||||
{
|
||||
"score": LocalizedIntegerField(
|
||||
default={settings.LANGUAGE_CODE: 75}
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
obj = model.objects.create()
|
||||
assert obj.score.get(settings.LANGUAGE_CODE) == 75
|
||||
@@ -177,16 +173,24 @@ class LocalizedIntegerFieldTestCase(TestCase):
|
||||
assert obj.score.get(lang_code) is None
|
||||
|
||||
def test_default_value_update(self):
|
||||
"""Tests whether a default is properly set
|
||||
when specified during updates."""
|
||||
"""Tests whether a default is properly set when specified during
|
||||
updates."""
|
||||
|
||||
model = get_fake_model({
|
||||
'score': LocalizedIntegerField(default={settings.LANGUAGE_CODE: 75}, null=True)
|
||||
})
|
||||
model = get_fake_model(
|
||||
{
|
||||
"score": LocalizedIntegerField(
|
||||
default={settings.LANGUAGE_CODE: 75}, null=True
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
obj = model.objects.create(score=LocalizedIntegerValue({settings.LANGUAGE_CODE: 35}))
|
||||
obj = model.objects.create(
|
||||
score=LocalizedIntegerValue({settings.LANGUAGE_CODE: 35})
|
||||
)
|
||||
assert obj.score.get(settings.LANGUAGE_CODE) == 35
|
||||
|
||||
model.objects.update(score=LocalizedIntegerValue({settings.LANGUAGE_CODE: None}))
|
||||
model.objects.update(
|
||||
score=LocalizedIntegerValue({settings.LANGUAGE_CODE: None})
|
||||
)
|
||||
obj.refresh_from_db()
|
||||
assert obj.score.get(settings.LANGUAGE_CODE) == 75
|
||||
|
||||
@@ -12,6 +12,7 @@ from .fake_model import get_fake_model
|
||||
@override_settings(LOCALIZED_FIELDS_EXPERIMENTAL=True)
|
||||
class LocalizedLookupsTestCase(TestCase):
|
||||
"""Tests whether localized lookups properly work with."""
|
||||
|
||||
TestModel1 = None
|
||||
|
||||
@classmethod
|
||||
@@ -21,31 +22,29 @@ class LocalizedLookupsTestCase(TestCase):
|
||||
super(LocalizedLookupsTestCase, cls).setUpClass()
|
||||
|
||||
# reload app as setting has changed
|
||||
config = apps.get_app_config('localized_fields')
|
||||
config = apps.get_app_config("localized_fields")
|
||||
config.ready()
|
||||
|
||||
cls.TestModel = get_fake_model(
|
||||
{
|
||||
'text': LocalizedField(),
|
||||
}
|
||||
)
|
||||
cls.TestModel = get_fake_model({"text": LocalizedField()})
|
||||
|
||||
def test_localized_lookup(self):
|
||||
"""Tests whether localized lookup properly works."""
|
||||
|
||||
self.TestModel.objects.create(
|
||||
text=LocalizedValue(dict(en='text_en', ro='text_ro', nl='text_nl')),
|
||||
text=LocalizedValue(dict(en="text_en", ro="text_ro", nl="text_nl"))
|
||||
)
|
||||
|
||||
# assert that it properly lookups the currently active language
|
||||
for lang_code, _ in settings.LANGUAGES:
|
||||
translation.activate(lang_code)
|
||||
assert self.TestModel.objects.filter(text='text_' + lang_code).exists()
|
||||
assert self.TestModel.objects.filter(
|
||||
text="text_" + lang_code
|
||||
).exists()
|
||||
|
||||
# ensure that the default language is used in case no
|
||||
# language is active at all
|
||||
translation.deactivate_all()
|
||||
assert self.TestModel.objects.filter(text='text_en').exists()
|
||||
assert self.TestModel.objects.filter(text="text_en").exists()
|
||||
|
||||
# ensure that hstore lookups still work
|
||||
assert self.TestModel.objects.filter(text__ro='text_ro').exists()
|
||||
assert self.TestModel.objects.filter(text__ro="text_ro").exists()
|
||||
|
||||
@@ -17,17 +17,12 @@ class LocalizedModelTestCase(TestCase):
|
||||
|
||||
super(LocalizedModelTestCase, cls).setUpClass()
|
||||
|
||||
cls.TestModel = get_fake_model(
|
||||
{
|
||||
'title': LocalizedField()
|
||||
}
|
||||
)
|
||||
cls.TestModel = get_fake_model({"title": LocalizedField()})
|
||||
|
||||
@classmethod
|
||||
def test_defaults(cls):
|
||||
"""Tests whether all :see:LocalizedField
|
||||
fields are assigned an empty :see:LocalizedValue
|
||||
instance when the model is instanitiated."""
|
||||
"""Tests whether all :see:LocalizedField fields are assigned an empty
|
||||
:see:LocalizedValue instance when the model is instanitiated."""
|
||||
|
||||
obj = cls.TestModel()
|
||||
|
||||
@@ -35,19 +30,18 @@ class LocalizedModelTestCase(TestCase):
|
||||
|
||||
@classmethod
|
||||
def test_model_init_kwargs(cls):
|
||||
"""Tests whether all :see:LocalizedField
|
||||
fields are assigned an empty :see:LocalizedValue
|
||||
instance when the model is instanitiated."""
|
||||
"""Tests whether all :see:LocalizedField fields are assigned an empty
|
||||
:see:LocalizedValue instance when the model is instanitiated."""
|
||||
data = {
|
||||
'title': {
|
||||
'en': 'english_title',
|
||||
'ro': 'romanian_title',
|
||||
'nl': 'dutch_title'
|
||||
"title": {
|
||||
"en": "english_title",
|
||||
"ro": "romanian_title",
|
||||
"nl": "dutch_title",
|
||||
}
|
||||
}
|
||||
obj = cls.TestModel(**data)
|
||||
|
||||
assert isinstance(obj.title, LocalizedValue)
|
||||
assert obj.title.en == 'english_title'
|
||||
assert obj.title.ro == 'romanian_title'
|
||||
assert obj.title.nl == 'dutch_title'
|
||||
assert obj.title.en == "english_title"
|
||||
assert obj.title.ro == "romanian_title"
|
||||
assert obj.title.nl == "dutch_title"
|
||||
|
||||
@@ -16,30 +16,24 @@ class LocalizedQuerySetTestCase(TestCase):
|
||||
|
||||
super(LocalizedQuerySetTestCase, cls).setUpClass()
|
||||
|
||||
cls.Model = get_fake_model(
|
||||
{
|
||||
'title': LocalizedField(),
|
||||
}
|
||||
)
|
||||
cls.Model = get_fake_model({"title": LocalizedField()})
|
||||
|
||||
@classmethod
|
||||
def test_assign_raw_dict(cls):
|
||||
inst = cls.Model()
|
||||
inst.title = dict(en='Bread', ro='Paine')
|
||||
inst.title = dict(en="Bread", ro="Paine")
|
||||
inst.save()
|
||||
|
||||
inst = cls.Model.objects.get(pk=inst.pk)
|
||||
assert inst.title.en == 'Bread'
|
||||
assert inst.title.ro == 'Paine'
|
||||
assert inst.title.en == "Bread"
|
||||
assert inst.title.ro == "Paine"
|
||||
|
||||
@classmethod
|
||||
def test_assign_raw_dict_update(cls):
|
||||
inst = cls.Model.objects.create(
|
||||
title=dict(en='Bread', ro='Paine'))
|
||||
inst = cls.Model.objects.create(title=dict(en="Bread", ro="Paine"))
|
||||
|
||||
cls.Model.objects.update(
|
||||
title=dict(en='Beer', ro='Bere'))
|
||||
cls.Model.objects.update(title=dict(en="Beer", ro="Bere"))
|
||||
|
||||
inst = cls.Model.objects.get(pk=inst.pk)
|
||||
assert inst.title.en == 'Beer'
|
||||
assert inst.title.ro == 'Bere'
|
||||
assert inst.title.en == "Beer"
|
||||
assert inst.title.ro == "Bere"
|
||||
|
||||
@@ -1,16 +1,13 @@
|
||||
import copy
|
||||
|
||||
from django import forms
|
||||
from django.db import models
|
||||
from django.conf import settings
|
||||
from django.test import TestCase
|
||||
from django.db import models
|
||||
from django.db.utils import IntegrityError
|
||||
from django.test import TestCase
|
||||
from django.utils.text import slugify
|
||||
|
||||
from localized_fields.fields import (
|
||||
LocalizedField,
|
||||
LocalizedUniqueSlugField
|
||||
)
|
||||
from localized_fields.fields import LocalizedField, LocalizedUniqueSlugField
|
||||
|
||||
from .fake_model import get_fake_model
|
||||
|
||||
@@ -29,23 +26,25 @@ class LocalizedSlugFieldTestCase(TestCase):
|
||||
|
||||
cls.Model = get_fake_model(
|
||||
{
|
||||
'title': LocalizedField(),
|
||||
'name': models.CharField(max_length=255),
|
||||
'slug': LocalizedUniqueSlugField(populate_from='title')
|
||||
"title": LocalizedField(),
|
||||
"name": models.CharField(max_length=255),
|
||||
"slug": LocalizedUniqueSlugField(populate_from="title"),
|
||||
}
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def test_unique_slug_with_time():
|
||||
"""Tests whether the primary key is included in
|
||||
the slug when the 'use_pk' option is enabled."""
|
||||
"""Tests whether the primary key is included in the slug when the
|
||||
'use_pk' option is enabled."""
|
||||
|
||||
title = 'myuniquetitle'
|
||||
title = "myuniquetitle"
|
||||
|
||||
PkModel = get_fake_model(
|
||||
{
|
||||
'title': LocalizedField(),
|
||||
'slug': LocalizedUniqueSlugField(populate_from='title', include_time=True)
|
||||
"title": LocalizedField(),
|
||||
"slug": LocalizedUniqueSlugField(
|
||||
populate_from="title", include_time=True
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
@@ -53,7 +52,7 @@ class LocalizedSlugFieldTestCase(TestCase):
|
||||
obj.title.en = title
|
||||
obj.save()
|
||||
|
||||
assert obj.slug.en.startswith('%s-' % title)
|
||||
assert obj.slug.en.startswith("%s-" % title)
|
||||
|
||||
@classmethod
|
||||
def test_uniue_slug_no_change(cls):
|
||||
@@ -61,12 +60,14 @@ class LocalizedSlugFieldTestCase(TestCase):
|
||||
|
||||
NoChangeSlugModel = get_fake_model(
|
||||
{
|
||||
'title': LocalizedField(),
|
||||
'slug': LocalizedUniqueSlugField(populate_from='title', include_time=True)
|
||||
"title": LocalizedField(),
|
||||
"slug": LocalizedUniqueSlugField(
|
||||
populate_from="title", include_time=True
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
title = 'myuniquetitle'
|
||||
title = "myuniquetitle"
|
||||
|
||||
obj = NoChangeSlugModel()
|
||||
obj.title.en = title
|
||||
@@ -75,7 +76,7 @@ class LocalizedSlugFieldTestCase(TestCase):
|
||||
|
||||
old_slug_en = copy.deepcopy(obj.slug.en)
|
||||
old_slug_nl = copy.deepcopy(obj.slug.nl)
|
||||
obj.title.nl += 'beer'
|
||||
obj.title.nl += "beer"
|
||||
obj.save()
|
||||
|
||||
assert old_slug_en == obj.slug.en
|
||||
@@ -83,18 +84,20 @@ class LocalizedSlugFieldTestCase(TestCase):
|
||||
|
||||
@classmethod
|
||||
def test_unique_slug_update(cls):
|
||||
obj = cls.Model.objects.create(title={settings.LANGUAGE_CODE: 'mytitle'})
|
||||
assert obj.slug.get() == 'mytitle'
|
||||
obj.title.set(settings.LANGUAGE_CODE, 'othertitle')
|
||||
obj = cls.Model.objects.create(
|
||||
title={settings.LANGUAGE_CODE: "mytitle"}
|
||||
)
|
||||
assert obj.slug.get() == "mytitle"
|
||||
obj.title.set(settings.LANGUAGE_CODE, "othertitle")
|
||||
obj.save()
|
||||
assert obj.slug.get() == 'othertitle'
|
||||
assert obj.slug.get() == "othertitle"
|
||||
|
||||
@classmethod
|
||||
def test_unique_slug_unique_max_retries(cls):
|
||||
"""Tests whether the unique slug implementation doesn't
|
||||
try to find a slug forever and gives up after a while."""
|
||||
"""Tests whether the unique slug implementation doesn't try to find a
|
||||
slug forever and gives up after a while."""
|
||||
|
||||
title = 'myuniquetitle'
|
||||
title = "myuniquetitle"
|
||||
|
||||
obj = cls.Model()
|
||||
obj.title.en = title
|
||||
@@ -111,106 +114,112 @@ class LocalizedSlugFieldTestCase(TestCase):
|
||||
"""Tests whether the populating feature works correctly."""
|
||||
|
||||
obj = cls.Model()
|
||||
obj.title.en = 'this is my title'
|
||||
obj.title.en = "this is my title"
|
||||
obj.save()
|
||||
|
||||
assert obj.slug.get('en') == slugify(obj.title)
|
||||
assert obj.slug.get("en") == slugify(obj.title)
|
||||
|
||||
@classmethod
|
||||
def test_populate_callable(cls):
|
||||
"""Tests whether the populating feature works correctly
|
||||
when you specify a callable."""
|
||||
"""Tests whether the populating feature works correctly when you
|
||||
specify a callable."""
|
||||
|
||||
def generate_slug(instance):
|
||||
return instance.title
|
||||
|
||||
get_fake_model({
|
||||
'title': LocalizedField(),
|
||||
'slug': LocalizedUniqueSlugField(populate_from=generate_slug)
|
||||
})
|
||||
get_fake_model(
|
||||
{
|
||||
"title": LocalizedField(),
|
||||
"slug": LocalizedUniqueSlugField(populate_from=generate_slug),
|
||||
}
|
||||
)
|
||||
|
||||
obj = cls.Model()
|
||||
for lang_code, lang_name in settings.LANGUAGES:
|
||||
obj.title.set(lang_code, 'title %s' % lang_name)
|
||||
obj.title.set(lang_code, "title %s" % lang_name)
|
||||
|
||||
obj.save()
|
||||
|
||||
for lang_code, lang_name in settings.LANGUAGES:
|
||||
assert obj.slug.get(lang_code) == 'title-%s' % lang_name.lower()
|
||||
assert obj.slug.get(lang_code) == "title-%s" % lang_name.lower()
|
||||
|
||||
@staticmethod
|
||||
def test_populate_multiple_from_fields():
|
||||
"""Tests whether populating the slug from multiple
|
||||
fields works correctly."""
|
||||
"""Tests whether populating the slug from multiple fields works
|
||||
correctly."""
|
||||
|
||||
model = get_fake_model(
|
||||
{
|
||||
'title': LocalizedField(),
|
||||
'name': models.CharField(max_length=255),
|
||||
'slug': LocalizedUniqueSlugField(populate_from=('title', 'name'))
|
||||
"title": LocalizedField(),
|
||||
"name": models.CharField(max_length=255),
|
||||
"slug": LocalizedUniqueSlugField(
|
||||
populate_from=("title", "name")
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
obj = model()
|
||||
for lang_code, lang_name in settings.LANGUAGES:
|
||||
obj.name = 'swen'
|
||||
obj.title.set(lang_code, 'title %s' % lang_name)
|
||||
obj.name = "swen"
|
||||
obj.title.set(lang_code, "title %s" % lang_name)
|
||||
|
||||
obj.save()
|
||||
|
||||
for lang_code, lang_name in settings.LANGUAGES:
|
||||
assert obj.slug.get(lang_code) == 'title-%s-swen' % lang_name.lower()
|
||||
assert (
|
||||
obj.slug.get(lang_code) == "title-%s-swen" % lang_name.lower()
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def test_populate_multiple_from_fields_fk():
|
||||
"""Tests whether populating the slug from multiple
|
||||
fields works correctly."""
|
||||
"""Tests whether populating the slug from multiple fields works
|
||||
correctly."""
|
||||
|
||||
model_fk = get_fake_model(
|
||||
{
|
||||
'name': LocalizedField(),
|
||||
}
|
||||
)
|
||||
model_fk = get_fake_model({"name": LocalizedField()})
|
||||
|
||||
model = get_fake_model(
|
||||
{
|
||||
'title': LocalizedField(),
|
||||
'other': models.ForeignKey(model_fk, on_delete=models.CASCADE),
|
||||
'slug': LocalizedUniqueSlugField(populate_from=('title', 'other.name'))
|
||||
"title": LocalizedField(),
|
||||
"other": models.ForeignKey(model_fk, on_delete=models.CASCADE),
|
||||
"slug": LocalizedUniqueSlugField(
|
||||
populate_from=("title", "other.name")
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
other = model_fk.objects.create(name={settings.LANGUAGE_CODE: 'swen'})
|
||||
other = model_fk.objects.create(name={settings.LANGUAGE_CODE: "swen"})
|
||||
|
||||
obj = model()
|
||||
for lang_code, lang_name in settings.LANGUAGES:
|
||||
obj.other_id = other.id
|
||||
obj.title.set(lang_code, 'title %s' % lang_name)
|
||||
obj.title.set(lang_code, "title %s" % lang_name)
|
||||
|
||||
obj.save()
|
||||
|
||||
for lang_code, lang_name in settings.LANGUAGES:
|
||||
assert obj.slug.get(lang_code) == 'title-%s-swen' % lang_name.lower()
|
||||
assert (
|
||||
obj.slug.get(lang_code) == "title-%s-swen" % lang_name.lower()
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def test_populate_multiple_languages(cls):
|
||||
"""Tests whether the populating feature correctly
|
||||
works for all languages."""
|
||||
"""Tests whether the populating feature correctly works for all
|
||||
languages."""
|
||||
|
||||
obj = cls.Model()
|
||||
for lang_code, lang_name in settings.LANGUAGES:
|
||||
obj.title.set(lang_code, 'title %s' % lang_name)
|
||||
obj.title.set(lang_code, "title %s" % lang_name)
|
||||
|
||||
obj.save()
|
||||
|
||||
for lang_code, lang_name in settings.LANGUAGES:
|
||||
assert obj.slug.get(lang_code) == 'title-%s' % lang_name.lower()
|
||||
assert obj.slug.get(lang_code) == "title-%s" % lang_name.lower()
|
||||
|
||||
@classmethod
|
||||
def test_unique_slug(cls):
|
||||
"""Tests whether unique slugs are properly generated."""
|
||||
|
||||
title = 'myuniquetitle'
|
||||
title = "myuniquetitle"
|
||||
|
||||
obj = cls.Model()
|
||||
obj.title.en = title
|
||||
@@ -221,38 +230,36 @@ class LocalizedSlugFieldTestCase(TestCase):
|
||||
another_obj.title.en = title
|
||||
another_obj.save()
|
||||
|
||||
assert another_obj.slug.en == '%s-%d' % (title, i)
|
||||
assert another_obj.slug.en == "%s-%d" % (title, i)
|
||||
|
||||
@classmethod
|
||||
def test_unique_slug_utf(cls):
|
||||
"""Tests whether generating a slug works
|
||||
when the value consists completely out
|
||||
of non-ASCII characters."""
|
||||
"""Tests whether generating a slug works when the value consists
|
||||
completely out of non-ASCII characters."""
|
||||
|
||||
obj = cls.Model()
|
||||
obj.title.en = 'مكاتب للايجار بشارع بورسعيد'
|
||||
obj.title.en = "مكاتب للايجار بشارع بورسعيد"
|
||||
obj.save()
|
||||
|
||||
assert obj.slug.en == 'مكاتب-للايجار-بشارع-بورسعيد'
|
||||
assert obj.slug.en == "مكاتب-للايجار-بشارع-بورسعيد"
|
||||
|
||||
@staticmethod
|
||||
def test_deconstruct():
|
||||
"""Tests whether the :see:deconstruct
|
||||
function properly retains options
|
||||
"""Tests whether the :see:deconstruct function properly retains options
|
||||
specified in the constructor."""
|
||||
|
||||
field = LocalizedUniqueSlugField(populate_from='title')
|
||||
field = LocalizedUniqueSlugField(populate_from="title")
|
||||
_, _, _, kwargs = field.deconstruct()
|
||||
|
||||
assert 'populate_from' in kwargs
|
||||
assert kwargs['populate_from'] == field.populate_from
|
||||
assert "populate_from" in kwargs
|
||||
assert kwargs["populate_from"] == field.populate_from
|
||||
|
||||
@staticmethod
|
||||
def test_formfield():
|
||||
"""Tests whether the :see:formfield method
|
||||
returns a valid form field that is hidden."""
|
||||
"""Tests whether the :see:formfield method returns a valid form field
|
||||
that is hidden."""
|
||||
|
||||
form_field = LocalizedUniqueSlugField(populate_from='title').formfield()
|
||||
form_field = LocalizedUniqueSlugField(populate_from="title").formfield()
|
||||
|
||||
assert isinstance(form_field, forms.CharField)
|
||||
assert isinstance(form_field.widget, forms.HiddenInput)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from django.db.models import F
|
||||
from django.conf import settings
|
||||
from django.utils import translation
|
||||
from django.db.models import F
|
||||
from django.test import TestCase, override_settings
|
||||
from django.utils import translation
|
||||
|
||||
from localized_fields.value import LocalizedValue
|
||||
|
||||
@@ -13,16 +13,14 @@ class LocalizedValueTestCase(TestCase):
|
||||
|
||||
@staticmethod
|
||||
def tearDown():
|
||||
"""Assures that the current language
|
||||
is set back to the default."""
|
||||
"""Assures that the current language is set back to the default."""
|
||||
|
||||
translation.activate(settings.LANGUAGE_CODE)
|
||||
|
||||
@staticmethod
|
||||
def test_init():
|
||||
"""Tests whether the __init__ function
|
||||
of the :see:LocalizedValue class works
|
||||
as expected."""
|
||||
"""Tests whether the __init__ function of the :see:LocalizedValue class
|
||||
works as expected."""
|
||||
|
||||
keys = get_init_values()
|
||||
value = LocalizedValue(keys)
|
||||
@@ -32,9 +30,8 @@ class LocalizedValueTestCase(TestCase):
|
||||
|
||||
@staticmethod
|
||||
def test_init_default_values():
|
||||
"""Tests whether the __init__ function
|
||||
of the :see:LocalizedValue accepts the
|
||||
default value or an empty dict properly."""
|
||||
"""Tests whether the __init__ function of the :see:LocalizedValue
|
||||
accepts the default value or an empty dict properly."""
|
||||
|
||||
value = LocalizedValue()
|
||||
|
||||
@@ -43,21 +40,20 @@ class LocalizedValueTestCase(TestCase):
|
||||
|
||||
@staticmethod
|
||||
def test_init_array():
|
||||
"""Tests whether the __init__ function
|
||||
of :see:LocalizedValue properly handles an
|
||||
array.
|
||||
"""Tests whether the __init__ function of :see:LocalizedValue properly
|
||||
handles an array.
|
||||
|
||||
Arrays can be passed to LocalizedValue as
|
||||
a result of a ArrayAgg operation."""
|
||||
Arrays can be passed to LocalizedValue as a result of a ArrayAgg
|
||||
operation.
|
||||
"""
|
||||
|
||||
value = LocalizedValue(['my value'])
|
||||
assert value.get(settings.LANGUAGE_CODE) == 'my value'
|
||||
value = LocalizedValue(["my value"])
|
||||
assert value.get(settings.LANGUAGE_CODE) == "my value"
|
||||
|
||||
@staticmethod
|
||||
def test_get_explicit():
|
||||
"""Tests whether the the :see:LocalizedValue
|
||||
class's :see:get function works properly
|
||||
when specifying an explicit value."""
|
||||
"""Tests whether the the :see:LocalizedValue class's :see:get function
|
||||
works properly when specifying an explicit value."""
|
||||
|
||||
keys = get_init_values()
|
||||
localized_value = LocalizedValue(keys)
|
||||
@@ -67,9 +63,8 @@ class LocalizedValueTestCase(TestCase):
|
||||
|
||||
@staticmethod
|
||||
def test_get_default_language():
|
||||
"""Tests whether the :see:LocalizedValue
|
||||
class's see:get function properly
|
||||
gets the value in the default language."""
|
||||
"""Tests whether the :see:LocalizedValue class's see:get function
|
||||
properly gets the value in the default language."""
|
||||
|
||||
keys = get_init_values()
|
||||
localized_value = LocalizedValue(keys)
|
||||
@@ -80,8 +75,8 @@ class LocalizedValueTestCase(TestCase):
|
||||
|
||||
@staticmethod
|
||||
def test_set():
|
||||
"""Tests whether the :see:LocalizedValue
|
||||
class's see:set function works properly."""
|
||||
"""Tests whether the :see:LocalizedValue class's see:set function works
|
||||
properly."""
|
||||
|
||||
localized_value = LocalizedValue()
|
||||
|
||||
@@ -92,21 +87,21 @@ class LocalizedValueTestCase(TestCase):
|
||||
|
||||
@staticmethod
|
||||
def test_eq():
|
||||
"""Tests whether the __eq__ operator
|
||||
of :see:LocalizedValue works properly."""
|
||||
"""Tests whether the __eq__ operator of :see:LocalizedValue works
|
||||
properly."""
|
||||
|
||||
a = LocalizedValue({'en': 'a', 'ar': 'b'})
|
||||
b = LocalizedValue({'en': 'a', 'ar': 'b'})
|
||||
a = LocalizedValue({"en": "a", "ar": "b"})
|
||||
b = LocalizedValue({"en": "a", "ar": "b"})
|
||||
|
||||
assert a == b
|
||||
|
||||
b.en = 'b'
|
||||
b.en = "b"
|
||||
assert a != b
|
||||
|
||||
@staticmethod
|
||||
def test_translate():
|
||||
"""Tests whether the :see:LocalizedValue
|
||||
class's __str__ works properly."""
|
||||
"""Tests whether the :see:LocalizedValue class's __str__ works
|
||||
properly."""
|
||||
|
||||
keys = get_init_values()
|
||||
localized_value = LocalizedValue(keys)
|
||||
@@ -117,15 +112,12 @@ class LocalizedValueTestCase(TestCase):
|
||||
|
||||
@staticmethod
|
||||
def test_translate_fallback():
|
||||
"""Tests whether the :see:LocalizedValue
|
||||
class's translate()'s fallback functionality
|
||||
works properly."""
|
||||
"""Tests whether the :see:LocalizedValue class's translate()'s fallback
|
||||
functionality works properly."""
|
||||
|
||||
test_value = 'myvalue'
|
||||
test_value = "myvalue"
|
||||
|
||||
localized_value = LocalizedValue({
|
||||
settings.LANGUAGE_CODE: test_value
|
||||
})
|
||||
localized_value = LocalizedValue({settings.LANGUAGE_CODE: test_value})
|
||||
|
||||
other_language = settings.LANGUAGES[-1][0]
|
||||
|
||||
@@ -146,50 +138,44 @@ class LocalizedValueTestCase(TestCase):
|
||||
|
||||
@staticmethod
|
||||
def test_translate_none():
|
||||
"""Tests whether the :see:LocalizedValue
|
||||
class's translate() method properly returns
|
||||
None when there is no value."""
|
||||
"""Tests whether the :see:LocalizedValue class's translate() method
|
||||
properly returns None when there is no value."""
|
||||
|
||||
# with no value, we always expect it to return None
|
||||
localized_value = LocalizedValue()
|
||||
assert localized_value.translate() is None
|
||||
assert str(localized_value) == ''
|
||||
assert str(localized_value) == ""
|
||||
|
||||
# with no value for the default language, the default
|
||||
# behavior is to return None, unless a custom fallback
|
||||
# chain is configured, which there is not for this test
|
||||
other_language = settings.LANGUAGES[-1][0]
|
||||
localized_value = LocalizedValue({
|
||||
other_language: 'hey'
|
||||
})
|
||||
localized_value = LocalizedValue({other_language: "hey"})
|
||||
|
||||
translation.activate(settings.LANGUAGE_CODE)
|
||||
assert localized_value.translate() is None
|
||||
assert str(localized_value) == ''
|
||||
assert str(localized_value) == ""
|
||||
|
||||
@staticmethod
|
||||
def test_translate_fallback_custom_fallback():
|
||||
"""Tests whether the :see:LocalizedValue class's
|
||||
translate()'s fallback functionality properly respects
|
||||
the LOCALIZED_FIELDS_FALLBACKS setting."""
|
||||
"""Tests whether the :see:LocalizedValue class's translate()'s fallback
|
||||
functionality properly respects the LOCALIZED_FIELDS_FALLBACKS
|
||||
setting."""
|
||||
|
||||
fallbacks = {
|
||||
'nl': ['ro']
|
||||
}
|
||||
fallbacks = {"nl": ["ro"]}
|
||||
|
||||
localized_value = LocalizedValue({
|
||||
settings.LANGUAGE_CODE: settings.LANGUAGE_CODE,
|
||||
'ro': 'ro'
|
||||
})
|
||||
localized_value = LocalizedValue(
|
||||
{settings.LANGUAGE_CODE: settings.LANGUAGE_CODE, "ro": "ro"}
|
||||
)
|
||||
|
||||
with override_settings(LOCALIZED_FIELDS_FALLBACKS=fallbacks):
|
||||
with translation.override('nl'):
|
||||
assert localized_value.translate() == 'ro'
|
||||
with translation.override("nl"):
|
||||
assert localized_value.translate() == "ro"
|
||||
|
||||
@staticmethod
|
||||
def test_deconstruct():
|
||||
"""Tests whether the :see:LocalizedValue
|
||||
class's :see:deconstruct function works properly."""
|
||||
"""Tests whether the :see:LocalizedValue class's :see:deconstruct
|
||||
function works properly."""
|
||||
|
||||
keys = get_init_values()
|
||||
value = LocalizedValue(keys)
|
||||
@@ -200,16 +186,16 @@ class LocalizedValueTestCase(TestCase):
|
||||
|
||||
@staticmethod
|
||||
def test_construct_string():
|
||||
"""Tests whether the :see:LocalizedValue's constructor
|
||||
assumes the primary language when passing a single string."""
|
||||
"""Tests whether the :see:LocalizedValue's constructor assumes the
|
||||
primary language when passing a single string."""
|
||||
|
||||
value = LocalizedValue('beer')
|
||||
assert value.get(settings.LANGUAGE_CODE) == 'beer'
|
||||
value = LocalizedValue("beer")
|
||||
assert value.get(settings.LANGUAGE_CODE) == "beer"
|
||||
|
||||
@staticmethod
|
||||
def test_construct_expression():
|
||||
"""Tests whether passing expressions as values
|
||||
works properly and are not converted to string."""
|
||||
"""Tests whether passing expressions as values works properly and are
|
||||
not converted to string."""
|
||||
|
||||
value = LocalizedValue(dict(en=F('other')))
|
||||
value = LocalizedValue(dict(en=F("other")))
|
||||
assert isinstance(value.en, F)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import re
|
||||
|
||||
from django.conf import settings
|
||||
from django.test import TestCase
|
||||
|
||||
@@ -11,8 +12,7 @@ class LocalizedFieldWidgetTestCase(TestCase):
|
||||
|
||||
@staticmethod
|
||||
def test_widget_creation():
|
||||
"""Tests whether a widget is created for every
|
||||
language correctly."""
|
||||
"""Tests whether a widget is created for every language correctly."""
|
||||
|
||||
widget = LocalizedFieldWidget()
|
||||
assert len(widget.widgets) == len(settings.LANGUAGES)
|
||||
@@ -20,9 +20,8 @@ class LocalizedFieldWidgetTestCase(TestCase):
|
||||
|
||||
@staticmethod
|
||||
def test_decompress():
|
||||
"""Tests whether a :see:LocalizedValue instance
|
||||
can correctly be "decompressed" over the available
|
||||
widgets."""
|
||||
"""Tests whether a :see:LocalizedValue instance can correctly be
|
||||
"decompressed" over the available widgets."""
|
||||
|
||||
localized_value = LocalizedValue()
|
||||
for lang_code, lang_name in settings.LANGUAGES:
|
||||
@@ -31,13 +30,15 @@ class LocalizedFieldWidgetTestCase(TestCase):
|
||||
widget = LocalizedFieldWidget()
|
||||
decompressed_values = widget.decompress(localized_value)
|
||||
|
||||
for (lang_code, _), value in zip(settings.LANGUAGES, decompressed_values):
|
||||
for (lang_code, _), value in zip(
|
||||
settings.LANGUAGES, decompressed_values
|
||||
):
|
||||
assert localized_value.get(lang_code) == value
|
||||
|
||||
@staticmethod
|
||||
def test_decompress_none():
|
||||
"""Tests whether the :see:LocalizedFieldWidget correctly
|
||||
handles :see:None."""
|
||||
"""Tests whether the :see:LocalizedFieldWidget correctly handles
|
||||
:see:None."""
|
||||
|
||||
widget = LocalizedFieldWidget()
|
||||
decompressed_values = widget.decompress(None)
|
||||
@@ -47,16 +48,17 @@ class LocalizedFieldWidgetTestCase(TestCase):
|
||||
|
||||
@staticmethod
|
||||
def test_get_context_required():
|
||||
"""Tests whether the :see:get_context correctly
|
||||
handles 'required' attribute, separately for each subwidget."""
|
||||
"""Tests whether the :see:get_context correctly handles 'required'
|
||||
attribute, separately for each subwidget."""
|
||||
|
||||
widget = LocalizedFieldWidget()
|
||||
widget.widgets[0].is_required = True
|
||||
widget.widgets[1].is_required = False
|
||||
context = widget.get_context(name='test', value=LocalizedValue(),
|
||||
attrs=dict(required=True))
|
||||
assert context['widget']['subwidgets'][0]['attrs']['required']
|
||||
assert 'required' not in context['widget']['subwidgets'][1]['attrs']
|
||||
context = widget.get_context(
|
||||
name="test", value=LocalizedValue(), attrs=dict(required=True)
|
||||
)
|
||||
assert context["widget"]["subwidgets"][0]["attrs"]["required"]
|
||||
assert "required" not in context["widget"]["subwidgets"][1]["attrs"]
|
||||
|
||||
@staticmethod
|
||||
def test_get_context_langs():
|
||||
@@ -64,20 +66,20 @@ class LocalizedFieldWidgetTestCase(TestCase):
|
||||
'lang_name' attribute for each subwidget."""
|
||||
|
||||
widget = LocalizedFieldWidget()
|
||||
context = widget.get_context(name='test', value=LocalizedValue(),
|
||||
attrs=dict())
|
||||
subwidgets_context = context['widget']['subwidgets']
|
||||
context = widget.get_context(
|
||||
name="test", value=LocalizedValue(), attrs=dict()
|
||||
)
|
||||
subwidgets_context = context["widget"]["subwidgets"]
|
||||
for widget, context in zip(widget.widgets, subwidgets_context):
|
||||
assert 'lang_code' in context
|
||||
assert 'lang_name' in context
|
||||
assert widget.lang_code == context['lang_code']
|
||||
assert widget.lang_name == context['lang_name']
|
||||
assert "lang_code" in context
|
||||
assert "lang_name" in context
|
||||
assert widget.lang_code == context["lang_code"]
|
||||
assert widget.lang_name == context["lang_name"]
|
||||
|
||||
@staticmethod
|
||||
def test_render():
|
||||
"""Tests whether the :see:LocalizedFieldWidget correctly
|
||||
render."""
|
||||
"""Tests whether the :see:LocalizedFieldWidget correctly render."""
|
||||
|
||||
widget = LocalizedFieldWidget()
|
||||
output = widget.render(name='title', value=None)
|
||||
assert bool(re.search('<label (.|\n|\t)*>\w+<\/label>', output))
|
||||
output = widget.render(name="title", value=None)
|
||||
assert bool(re.search("<label (.|\n|\t)*>\w+<\/label>", output))
|
||||
|
||||
Reference in New Issue
Block a user