Skip to content

Commit

Permalink
add validation sqlmodel helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
tepelbaum committed Jul 23, 2024
1 parent 0e542f1 commit 41ea32b
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
16 changes: 16 additions & 0 deletions ecodev_core/sqlmodel_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
module implementing SQLModel related helper methods. Related to validation
"""
from sqlmodel import SQLModel


class SQLModelWithVal(SQLModel):
"""
Helper class to ease validation in SQLModel classes with table=True
"""
@classmethod
def validated(cls, **kwargs):
"""
Forces validation to take place, even for SQLModel classes with table=True
"""
return cls(**cls.__bases__[0](**kwargs).model_dump())
51 changes: 51 additions & 0 deletions tests/unitary/test_sqlmodel_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"""
Module testing SQLModel helpers
"""
from typing import Optional

from pydantic import field_validator
from sqlmodel import Field

from ecodev_core import SafeTestCase
from ecodev_core.sqlmodel_utils import SQLModelWithVal


class FooBase(SQLModelWithVal):
"""
Example base class to illustrate the table validation behaviour of SQLModelWithVal
"""
bar: int

@field_validator('bar', mode='before')
def convert_bar(cls, bar):
"""
Example validation
"""
return int(bar / 1_000_000)


class Foo(FooBase, table=True): # type: ignore
"""
Example class to illustrate the table validation behaviour of SQLModelWithVal
"""
id: Optional[int] = Field(default=None, primary_key=True)


class SQLModelTest(SafeTestCase):
"""
Class testing validation behaviour of SQLModelWithVal
"""

def test_init_without_validation(self):
"""
Test creation without validation
"""
foo = Foo(bar=3_000_000)
self.assertEqual(foo.bar, 3_000_000)

def test_init_with_validation(self):
"""
Test creation with validation
"""
foo = Foo(bar=3_000_000)
self.assertEqual(foo.bar, 3)

0 comments on commit 41ea32b

Please sign in to comment.