-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
67 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |