Format and lint code

This commit is contained in:
Alexandru Arnautu 2020-03-10 09:33:34 +02:00
parent 5e1d46669c
commit 8968b0c7a8
No known key found for this signature in database
GPG Key ID: FED865E45FD7208B
4 changed files with 59 additions and 61 deletions

View File

@ -2,10 +2,10 @@ from .autoslug_field import LocalizedAutoSlugField
from .char_field import LocalizedCharField from .char_field import LocalizedCharField
from .field import LocalizedField from .field import LocalizedField
from .file_field import LocalizedFileField from .file_field import LocalizedFileField
from .float_field import LocalizedFloatField
from .integer_field import LocalizedIntegerField from .integer_field import LocalizedIntegerField
from .text_field import LocalizedTextField from .text_field import LocalizedTextField
from .uniqueslug_field import LocalizedUniqueSlugField from .uniqueslug_field import LocalizedUniqueSlugField
from .float_field import LocalizedFloatField
__all__ = [ __all__ = [
"LocalizedField", "LocalizedField",
@ -15,7 +15,7 @@ __all__ = [
"LocalizedTextField", "LocalizedTextField",
"LocalizedFileField", "LocalizedFileField",
"LocalizedIntegerField", "LocalizedIntegerField",
"LocalizedFloatField" "LocalizedFloatField",
] ]
try: try:

View File

@ -1,11 +1,11 @@
from typing import Optional, Union, Dict from typing import Dict, Optional, Union
from django.conf import settings from django.conf import settings
from django.db.utils import IntegrityError from django.db.utils import IntegrityError
from .field import LocalizedField
from ..value import LocalizedValue, LocalizedFloatValue
from ..forms import LocalizedIntegerFieldForm from ..forms import LocalizedIntegerFieldForm
from ..value import LocalizedFloatValue, LocalizedValue
from .field import LocalizedField
class LocalizedFloatField(LocalizedField): class LocalizedFloatField(LocalizedField):
@ -27,7 +27,9 @@ class LocalizedFloatField(LocalizedField):
return cls._convert_localized_value(db_value) return cls._convert_localized_value(db_value)
def to_python(self, value: Union[Dict[str, int], int, None]) -> LocalizedFloatValue: def to_python(
self, value: Union[Dict[str, int], int, None]
) -> LocalizedFloatValue:
"""Converts the value from a database value into a Python value.""" """Converts the value from a database value into a Python value."""
db_value = super().to_python(value) db_value = super().to_python(value)
@ -55,20 +57,22 @@ class LocalizedFloatField(LocalizedField):
if local_value is not None: if local_value is not None:
float(local_value) float(local_value)
except (TypeError, ValueError): except (TypeError, ValueError):
raise IntegrityError('non-float value in column "%s.%s" violates ' raise IntegrityError(
'float constraint' % (self.name, lang_code)) 'non-float value in column "%s.%s" violates '
"float constraint" % (self.name, lang_code)
)
# convert to a string before saving because the underlying # convert to a string before saving because the underlying
# type is hstore, which only accept strings # type is hstore, which only accept strings
prepped_value[lang_code] = str(local_value) if local_value is not None else None prepped_value[lang_code] = (
str(local_value) if local_value is not None else None
)
return prepped_value return prepped_value
def formfield(self, **kwargs): def formfield(self, **kwargs):
"""Gets the form field associated with this field.""" """Gets the form field associated with this field."""
defaults = { defaults = {"form_class": LocalizedIntegerFieldForm}
'form_class': LocalizedIntegerFieldForm
}
defaults.update(kwargs) defaults.update(kwargs)
return super().formfield(**defaults) return super().formfield(**defaults)
@ -80,7 +84,7 @@ class LocalizedFloatField(LocalizedField):
float_values = {} float_values = {}
for lang_code, _ in settings.LANGUAGES: for lang_code, _ in settings.LANGUAGES:
local_value = value.get(lang_code, None) local_value = value.get(lang_code, None)
if local_value is None or local_value.strip() == '': if local_value is None or local_value.strip() == "":
local_value = None local_value = None
try: try:

View File

@ -242,10 +242,10 @@ class LocalizedNumericValue(LocalizedValue):
"""Returns string representation of value.""" """Returns string representation of value."""
value = self.translate() value = self.translate()
return str(value) if value is not None else '' return str(value) if value is not None else ""
def __float__(self): def __float__(self):
"""Gets the value in the current language as a float""" """Gets the value in the current language as a float."""
value = self.translate() value = self.translate()
if value is None: if value is None:
return self.default_value return self.default_value
@ -259,28 +259,26 @@ class LocalizedIntegerValue(LocalizedNumericValue):
default_value = None default_value = None
def translate(self): def translate(self):
"""Gets the value in the current language, or """Gets the value in the current language, or in the configured fallbck
in the configured fallbck language.""" language."""
value = super().translate() value = super().translate()
if value is None or (isinstance(value, str) and value.strip() == ''): if value is None or (isinstance(value, str) and value.strip() == ""):
return None return None
return int(value) return int(value)
class LocalizedFloatValue(LocalizedNumericValue): class LocalizedFloatValue(LocalizedNumericValue):
"""All values are floats""" """All values are floats."""
default_value = None default_value = None
def translate(self): def translate(self):
""" """Gets the value in the current language, or in the configured
Gets the value in the current language, or in the configured fallback language."""
fallback language.
"""
value = super().translate() value = super().translate()
if value is None or (isinstance(value, str) and value.strip() == ''): if value is None or (isinstance(value, str) and value.strip() == ""):
return None return None
return float(value) return float(value)

View File

@ -1,7 +1,7 @@
from django.test import TestCase
from django.db.utils import IntegrityError
from django.conf import settings from django.conf import settings
from django.db import connection from django.db import connection
from django.db.utils import IntegrityError
from django.test import TestCase
from django.utils import translation from django.utils import translation
from localized_fields.fields import LocalizedFloatField from localized_fields.fields import LocalizedFloatField
@ -10,8 +10,8 @@ from .fake_model import get_fake_model
class LocalizedFloatFieldTestCase(TestCase): class LocalizedFloatFieldTestCase(TestCase):
"""Tests whether the :see:LocalizedFloatField """Tests whether the :see:LocalizedFloatField and :see:LocalizedFloatValue
and :see:LocalizedFloatValue works properly.""" works properly."""
TestModel = None TestModel = None
@ -19,9 +19,7 @@ class LocalizedFloatFieldTestCase(TestCase):
def setUpClass(cls): def setUpClass(cls):
super().setUpClass() super().setUpClass()
cls.TestModel = get_fake_model({ cls.TestModel = get_fake_model({"score": LocalizedFloatField()})
'score': LocalizedFloatField()
})
def test_basic(self): def test_basic(self):
"""Tests the basics of storing float values.""" """Tests the basics of storing float values."""
@ -36,8 +34,8 @@ class LocalizedFloatFieldTestCase(TestCase):
assert obj.score.get(lang_code) == index + 1.0 assert obj.score.get(lang_code) == index + 1.0
def test_primary_language_required(self): def test_primary_language_required(self):
"""Tests whether the primary language is required by """Tests whether the primary language is required by default and all
default and all other languages are optiona.""" other languages are optiona."""
# not filling in anything should raise IntegrityError, # not filling in anything should raise IntegrityError,
# the primary language is required # the primary language is required
@ -56,8 +54,8 @@ class LocalizedFloatFieldTestCase(TestCase):
obj.save() obj.save()
def test_default_value_none(self): def test_default_value_none(self):
"""Tests whether the default value for optional languages """Tests whether the default value for optional languages is
is NoneType.""" NoneType."""
obj = self.TestModel() obj = self.TestModel()
obj.score.set(settings.LANGUAGE_CODE, 1234.0) obj.score.set(settings.LANGUAGE_CODE, 1234.0)
@ -70,9 +68,8 @@ class LocalizedFloatFieldTestCase(TestCase):
assert obj.score.get(lang_code) is None assert obj.score.get(lang_code) is None
def test_translate(self): def test_translate(self):
"""Tests whether casting the value to an float """Tests whether casting the value to an float results in the value
results in the value being returned in the currently being returned in the currently active language as an float."""
active language as an float."""
obj = self.TestModel() obj = self.TestModel()
for index, (lang_code, _) in enumerate(settings.LANGUAGES): for index, (lang_code, _) in enumerate(settings.LANGUAGES):
@ -86,10 +83,9 @@ class LocalizedFloatFieldTestCase(TestCase):
assert obj.score.translate() == index + 1.0 assert obj.score.translate() == index + 1.0
def test_translate_primary_fallback(self): def test_translate_primary_fallback(self):
"""Tests whether casting the value to an float """Tests whether casting the value to an float results in the value
results in the value begin returned in the active begin returned in the active language and falls back to the primary
language and falls back to the primary language language if there is no value in that language."""
if there is no value in that language."""
obj = self.TestModel() obj = self.TestModel()
obj.score.set(settings.LANGUAGE_CODE, 25.0) obj.score.set(settings.LANGUAGE_CODE, 25.0)
@ -102,9 +98,8 @@ class LocalizedFloatFieldTestCase(TestCase):
assert float(obj.score) == 25.0 assert float(obj.score) == 25.0
def test_get_default_value(self): def test_get_default_value(self):
"""Tests whether getting the value in a specific """Tests whether getting the value in a specific language properly
language properly returns the specified default returns the specified default in case it is not available."""
in case it is not available."""
obj = self.TestModel() obj = self.TestModel()
obj.score.set(settings.LANGUAGE_CODE, 25.0) obj.score.set(settings.LANGUAGE_CODE, 25.0)
@ -114,12 +109,11 @@ class LocalizedFloatFieldTestCase(TestCase):
assert obj.score.get(secondary_language, 1337.0) == 1337.0 assert obj.score.get(secondary_language, 1337.0) == 1337.0
def test_completely_optional(self): def test_completely_optional(self):
"""Tests whether having all languages optional """Tests whether having all languages optional works properly."""
works properly."""
model = get_fake_model({ model = get_fake_model(
'score': LocalizedFloatField(null=True, required=[], blank=True) {"score": LocalizedFloatField(null=True, required=[], blank=True)}
}) )
obj = model() obj = model()
obj.save() obj.save()
@ -128,19 +122,18 @@ class LocalizedFloatFieldTestCase(TestCase):
assert getattr(obj.score, lang_code) is None assert getattr(obj.score, lang_code) is None
def test_store_string(self): def test_store_string(self):
"""Tests whether the field properly raises """Tests whether the field properly raises an error when trying to
an error when trying to store a non-float.""" store a non-float."""
for lang_code, _ in settings.LANGUAGES: for lang_code, _ in settings.LANGUAGES:
obj = self.TestModel() obj = self.TestModel()
with self.assertRaises(IntegrityError): with self.assertRaises(IntegrityError):
obj.score.set(lang_code, 'haha') obj.score.set(lang_code, "haha")
obj.save() obj.save()
def test_none_if_illegal_value_stored(self): def test_none_if_illegal_value_stored(self):
"""Tests whether None is returned for a language """Tests whether None is returned for a language if the value stored in
if the value stored in the database is not an the database is not an float."""
float."""
obj = self.TestModel() obj = self.TestModel()
obj.score.set(settings.LANGUAGE_CODE, 25.0) obj.score.set(settings.LANGUAGE_CODE, 25.0)
@ -154,12 +147,15 @@ class LocalizedFloatFieldTestCase(TestCase):
assert obj.score.get(settings.LANGUAGE_CODE) is None assert obj.score.get(settings.LANGUAGE_CODE) is None
def test_default_value(self): def test_default_value(self):
"""Tests whether a default is properly set """Tests whether a default is properly set when specified."""
when specified."""
model = get_fake_model({ model = get_fake_model(
'score': LocalizedFloatField(default={settings.LANGUAGE_CODE: 75.0}) {
}) "score": LocalizedFloatField(
default={settings.LANGUAGE_CODE: 75.0}
)
}
)
obj = model.objects.create() obj = model.objects.create()
assert obj.score.get(settings.LANGUAGE_CODE) == 75.0 assert obj.score.get(settings.LANGUAGE_CODE) == 75.0