Skip to content

Commit

Permalink
Decimal for this is 💰
Browse files Browse the repository at this point in the history
  • Loading branch information
regiscamimura committed Oct 13, 2023
1 parent 832deac commit 32f422d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
9 changes: 9 additions & 0 deletions tests/test_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,15 @@ def test_validate_bundle_raises_invalid_fields(profile_view):
assert "invalid_field is not editable" in str(e.value)


def test_validate_bundle_raises_invalid_decimal(profile_view):
profile_view.set_bundle(dict(decimal="money"))

with pytest.raises(ValidationError) as e:
profile_view.validate_bundle("decimal")

assert "Field decimal accepts a decimal" in str(e.value)


def test_validate_bundle_raises_read_only_fields(profile_view):
with pytest.raises(ValidationError) as e:
profile_view.validate_bundle("recovery_phone")
Expand Down
13 changes: 7 additions & 6 deletions worf/validators.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from datetime import datetime, time
from decimal import Decimal, InvalidOperation
from uuid import UUID

from django.core.exceptions import ValidationError
Expand Down Expand Up @@ -118,17 +119,17 @@ def _validate_positive_int(self, key):
)

return integer

def _validate_decimal(self, key):
value = self.bundle[key]

if value is None or value == "":
return None

try:
decimal = float(value)
except (TypeError, ValueError):
raise ValidationError(f"Field {self.keymap[key]} accepts an decimal")
decimal = Decimal(value)
except InvalidOperation:
raise ValidationError(f"Field {self.keymap[key]} accepts a decimal")

return decimal

Expand Down Expand Up @@ -240,7 +241,7 @@ def validate_bundle(self, key): # noqa: C901
elif isinstance(field, (models.IntegerField, models.SmallIntegerField)):
self.bundle[key] = self._validate_int(key)
return

elif isinstance(field, (models.DecimalField)):
self.bundle[key] = self._validate_decimal(key)
return
Expand Down

0 comments on commit 32f422d

Please sign in to comment.