-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Base Model: modified a bit to check for lack of serialization, to gen…
…erate a standard and more informative exception if artifact or other model can't be serialized.
- Loading branch information
1 parent
c73a9af
commit 946d600
Showing
3 changed files
with
72 additions
and
2 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
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 @@ | ||
""" | ||
mlte/model/api/serialization_exception.py | ||
Exception used for serialization issues. | ||
""" | ||
from __future__ import annotations | ||
|
||
|
||
class SerializationException(TypeError): | ||
"""Exception used for JSON serialization issues.""" | ||
|
||
def __init__(self, error: TypeError, object: str): | ||
super().__init__( | ||
f"Object {object} cannot be serialized into JSON, ensure all attributes are serializable: " | ||
+ str(error) | ||
) |
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,43 @@ | ||
""" | ||
test/model/test_base_model.py | ||
Unit tests for base model functionality. | ||
""" | ||
|
||
from __future__ import annotations | ||
|
||
from typing import Any | ||
|
||
import pytest | ||
|
||
from mlte.model.base_model import BaseModel | ||
from mlte.model.serialization_exception import SerializationException | ||
|
||
|
||
class ModelTest(BaseModel): | ||
int_num: int = 1 | ||
float_num: float = 1.2 | ||
str_obj: str = "test" | ||
bool_obj: bool = False | ||
obj: Any = "" | ||
|
||
|
||
class NonSerializable: | ||
attr3: str = "test" | ||
attr1: dict[str, Any] = {"baz": ModelTest()} | ||
|
||
|
||
def test_to_json(): | ||
test_obj = ModelTest() | ||
json_obj = test_obj.to_json() | ||
reconstructed = ModelTest.from_json(json_obj) | ||
|
||
assert test_obj == reconstructed | ||
|
||
|
||
def test_to_json_to_str_not_serializable(): | ||
test_obj = ModelTest() | ||
test_obj.obj = NonSerializable() | ||
|
||
with pytest.raises(SerializationException): | ||
_ = test_obj.to_json() |