Skip to content

Commit

Permalink
Fix optional field conversion to str
Browse files Browse the repository at this point in the history
  • Loading branch information
gabrielguarisa committed Nov 16, 2023
1 parent d1774ad commit c99f1bc
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "retrack"
version = "1.0.0"
version = "1.0.1"
description = "A business rules engine"
authors = ["Gabriel Guarisa <[email protected]>", "Nathalia Trotte <[email protected]>"]
license = "MIT"
Expand Down
23 changes: 22 additions & 1 deletion retrack/engine/request_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,20 @@
from retrack.nodes.base import BaseNode, NodeKind


class StrFieldValidator:
def __init__(self, default: typing.Optional[typing.Any] = None):
self.default = default

def __call__(self, value: typing.Any) -> typing.Any:
if value in [None, "None", "", "null"]:
if self.default is None:
raise ValueError("value cannot be None")
else:
return self.default

return str(value) if type(value) != str else value


class RequestManager:
def __init__(self, inputs: typing.List[BaseNode]):
self._model = None
Expand Down Expand Up @@ -71,11 +85,18 @@ def __create_model(
fields = {}
for input_field in self.inputs:
fields[input_field.data.name] = (
typing.Annotated[str, pydantic.BeforeValidator(str)],
typing.Annotated[
str if input_field.data.default is None else typing.Optional[str],
pydantic.BeforeValidator(
StrFieldValidator(input_field.data.default)
),
],
pydantic.Field(
default=Ellipsis
if input_field.data.default is None
else input_field.data.default,
optional=input_field.data.default is not None,
validate_default=False,
),
)

Expand Down
8 changes: 8 additions & 0 deletions tests/test_engine/test_request_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,11 @@ def test_validate_dict_with_model(valid_input_dict_before_validation):

assert issubclass(rm.model, pydantic.BaseModel)
assert rm.model.model_validate({"example": 1111}) == rm.model(example="1111")


def test_validate_dict_with_none_value(valid_input_dict_before_validation):
rm = RequestManager([Input(**valid_input_dict_before_validation)])

assert issubclass(rm.model, pydantic.BaseModel)
assert rm.model(example=None) == rm.model(example="Hello World")
assert rm.model() == rm.model(example="Hello World")

0 comments on commit c99f1bc

Please sign in to comment.