Skip to content

Commit

Permalink
better performance?
Browse files Browse the repository at this point in the history
  • Loading branch information
markus-96 committed Jan 30, 2025
1 parent 8e001ea commit 39dd1ff
Show file tree
Hide file tree
Showing 9 changed files with 41 additions and 44 deletions.
4 changes: 2 additions & 2 deletions tests/fields/test_enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from tests import testmodels
from tortoise.contrib import test
from tortoise.exceptions import ConfigurationError, ValidationError
from tortoise.exceptions import ConfigurationError, IntegrityError
from tortoise.fields import CharEnumField, IntEnumField


Expand All @@ -26,7 +26,7 @@ class BadIntEnumIfGenerated(IntEnum):

class TestIntEnumFields(test.TestCase):
async def test_empty(self):
with self.assertRaises(ValidationError):
with self.assertRaises(IntegrityError):
await testmodels.EnumFields.create()

async def test_create(self):
Expand Down
3 changes: 2 additions & 1 deletion tests/fields/test_fk.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from tortoise.exceptions import (
NoValuesFetched,
OperationalError,
IntegrityError,
ValidationError,
)
from tortoise.queryset import QuerySet
Expand All @@ -15,7 +16,7 @@ def assertRaisesWrongTypeException(self, relation_name: str):
)

async def test_empty(self):
with self.assertRaises(ValidationError):
with self.assertRaises(IntegrityError):
await testmodels.MinRelation.create()

async def test_minimal__create_by_id(self):
Expand Down
6 changes: 3 additions & 3 deletions tests/fields/test_fk_with_unique.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
from tests import testmodels
from tortoise.contrib import test
from tortoise.exceptions import IntegrityError, NoValuesFetched, OperationalError, ValidationError
from tortoise.exceptions import IntegrityError, NoValuesFetched, OperationalError
from tortoise.queryset import QuerySet


class TestForeignKeyFieldWithUnique(test.TestCase):
async def test_student__empty(self):
with self.assertRaises(ValidationError):
with self.assertRaises(IntegrityError):
await testmodels.Student.create()

async def test_student__create_by_id(self):
Expand Down Expand Up @@ -77,7 +77,7 @@ async def test_delete_by_name(self):
school = await testmodels.School.create(id=1024, name="School1")
student = await testmodels.Student.create(name="Sang-Heon Jeon", school=school)
del student.school
with self.assertRaises(ValidationError):
with self.assertRaises(IntegrityError):
await student.save()

async def test_update_by_nonexistent_id(self):
Expand Down
22 changes: 10 additions & 12 deletions tests/fields/test_int.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
from tests import testmodels
from tortoise.contrib import test
from tortoise.exceptions import ValidationError
from tortoise.exceptions import ValidationError, IntegrityError
from tortoise.expressions import F
from tortoise.fields import IntField, SmallIntField, BigIntField


class TestIntFields(test.TestCase):
async def test_empty(self):
with self.assertRaises(ValidationError):
with self.assertRaises(IntegrityError):
await testmodels.IntFields.create()

async def test_create_too_great(self):
too_great = IntField.LE + 1
with self.assertRaisesRegex(
ValidationError,
"Value should be less or equal to 2147483647 and greater or equal to -2147483648"
"Value should be less or equal to 2147483647 and greater or equal to -2147483648",
):
await testmodels.IntFields.create(intnum=too_great)

async def test_create_too_small(self):
too_small = IntField.GE - 1
with self.assertRaisesRegex(
ValidationError,
"Value should be less or equal to 2147483647 and greater or equal to -2147483648"
"Value should be less or equal to 2147483647 and greater or equal to -2147483648",
):
await testmodels.IntFields.create(intnum=too_small)

Expand Down Expand Up @@ -79,22 +79,20 @@ async def test_f_expression(self):

class TestSmallIntFields(test.TestCase):
async def test_empty(self):
with self.assertRaises(ValidationError):
with self.assertRaises(IntegrityError):
await testmodels.SmallIntFields.create()

async def test_create_too_great(self):
too_great = SmallIntField.LE + 1
with self.assertRaisesRegex(
ValidationError,
"Value should be less or equal to 32767 and greater or equal to -32768"
ValidationError, "Value should be less or equal to 32767 and greater or equal to -32768"
):
await testmodels.SmallIntFields.create(smallintnum=too_great)

async def test_create_too_small(self):
too_small = SmallIntField.GE - 1
with self.assertRaisesRegex(
ValidationError,
"Value should be less or equal to 32767 and greater or equal to -32768"
ValidationError, "Value should be less or equal to 32767 and greater or equal to -32768"
):
await testmodels.SmallIntFields.create(smallintnum=too_small)

Expand Down Expand Up @@ -137,22 +135,22 @@ async def test_f_expression(self):

class TestBigIntFields(test.TestCase):
async def test_empty(self):
with self.assertRaises(ValidationError):
with self.assertRaises(IntegrityError):
await testmodels.BigIntFields.create()

async def test_create_too_great(self):
too_great = BigIntField.LE + 1
with self.assertRaisesRegex(
ValidationError,
"Value should be less or equal to 9223372036854775807 and greater or equal to -9223372036854775808"
"Value should be less or equal to 9223372036854775807 and greater or equal to -9223372036854775808",
):
await testmodels.BigIntFields.create(intnum=too_great)

async def test_create_too_small(self):
too_small = BigIntField.GE - 1
with self.assertRaisesRegex(
ValidationError,
"Value should be less or equal to 9223372036854775807 and greater or equal to -9223372036854775808"
"Value should be less or equal to 9223372036854775807 and greater or equal to -9223372036854775808",
):
await testmodels.BigIntFields.create(intnum=too_small)

Expand Down
6 changes: 3 additions & 3 deletions tests/fields/test_o2o_with_unique.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
from tests import testmodels
from tortoise.contrib import test
from tortoise.exceptions import IntegrityError, OperationalError, ValidationError
from tortoise.exceptions import IntegrityError, OperationalError
from tortoise.queryset import QuerySet


class TestOneToOneFieldWithUnique(test.TestCase):
async def test_principal__empty(self):
with self.assertRaises(ValidationError):
with self.assertRaises(IntegrityError):
await testmodels.Principal.create()

async def test_principal__create_by_id(self):
Expand Down Expand Up @@ -77,7 +77,7 @@ async def test_delete_by_name(self):
school = await testmodels.School.create(id=1024, name="School1")
principal = await testmodels.Principal.create(name="Sang-Heon Jeon", school=school)
del principal.school
with self.assertRaises(ValidationError):
with self.assertRaises(IntegrityError):
await principal.save()

async def test_update_by_nonexistent_id(self):
Expand Down
3 changes: 1 addition & 2 deletions tests/fields/test_subclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
RacePlacingEnum,
)
from tortoise.contrib import test
from tortoise.exceptions import ValidationError


async def create_participants():
Expand Down Expand Up @@ -86,5 +85,5 @@ async def test_exception_on_invalid_data_type_in_int_field(self):
contact = await Contact.create()

contact.type = "not_int"
with self.assertRaises(ValidationError):
with self.assertRaises((TypeError, ValueError)):
await contact.save()
6 changes: 4 additions & 2 deletions tortoise/fields/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ def validate(self, value: Any) -> None:
"""
for v in self.validators:
if self.null and value is None:
continue
return
try:
if isinstance(value, Enum):
v(value.value)
Expand Down Expand Up @@ -358,7 +358,9 @@ def get_for_dialect(self, dialect: str, key: str) -> Any:
if isinstance(dialect_value, property):
return getattr(dialect_cls(self), key)
return dialect_value
return getattr(self, key, None) # there is nothing special defined, return the value of self
return getattr(
self, key, None
) # there is nothing special defined, return the value of self

def describe(self, serializable: bool) -> dict:
"""
Expand Down
20 changes: 16 additions & 4 deletions tortoise/fields/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@
from pypika_tortoise.terms import Term

from tortoise import timezone
from tortoise.exceptions import ConfigurationError, FieldError
from tortoise.exceptions import ConfigurationError, FieldError, ValidationError
from tortoise.fields.base import Field
from tortoise.timezone import get_default_timezone, get_timezone, get_use_tz, localtime
from tortoise.validators import MaxLengthValidator, MinMaxValidator
from tortoise.validators import MaxLengthValidator

try:
from ciso8601 import parse_datetime
Expand Down Expand Up @@ -87,7 +87,7 @@ def __init__(
primary_key: Optional[bool] = None,
ge: Optional[int] = None,
le: Optional[int] = None,
**kwargs: Any
**kwargs: Any,
) -> None:
if primary_key or kwargs.get("pk"):
kwargs["generated"] = bool(kwargs.get("generated", True))
Expand All @@ -105,7 +105,19 @@ def __init__(
raise ConfigurationError(f"'le' must be <= {self.LE}")
self.le = le

self.validators = [MinMaxValidator(self.ge, self.le), *self.validators]
self.validators = [self.validate_definition_range(), *self.validators]

def validate_definition_range(self):
ge = self.ge
le = self.le

def _validate_definition_range(value: int):
if value is not None and not ge <= value <= le:
raise ValidationError(
f"Value should be less or equal to {self.le} and greater or equal to {self.ge}"
)

return _validate_definition_range

@property
def constraints(self) -> dict:
Expand Down
15 changes: 0 additions & 15 deletions tortoise/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,21 +101,6 @@ def __call__(self, value: int | float | Decimal) -> None:
raise ValidationError(f"Value should be less or equal to {self.max_value}")


class MinMaxValidator(NumericValidator):
def __init__(self, min_value: int | float | Decimal, max_value: int | float | Decimal) -> None:
self._validate_type(max_value)
self._validate_type(min_value)
self.max_value = max_value
self.min_value = min_value

def __call__(self, value: int | float | Decimal) -> None:
self._validate_type(value)
if not (self.min_value <= value <= self.max_value):
raise ValidationError(
f"Value should be less or equal to {self.max_value} and greater or equal to {self.min_value}"
)


class CommaSeparatedIntegerListValidator(Validator):
"""
A validator to validate whether the given value is valid comma separated integer list or not.
Expand Down

0 comments on commit 39dd1ff

Please sign in to comment.