Skip to content

Commit

Permalink
be more lenient about giving int values to string variables
Browse files Browse the repository at this point in the history
  • Loading branch information
defreng committed Nov 9, 2023
1 parent 08cc986 commit 0dda277
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
17 changes: 15 additions & 2 deletions src/foxops/engine/models/template_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,14 @@
from pathlib import Path
from typing import Annotated, Any, Literal, Self, Type, Union

from pydantic import AfterValidator, BaseModel, Field, ValidationError, create_model
from pydantic import (
AfterValidator,
BaseModel,
BeforeValidator,
Field,
ValidationError,
create_model,
)
from ruamel.yaml import YAML


Expand Down Expand Up @@ -39,12 +46,18 @@ def pydantic_field_default(self) -> Any:
return self.default if self.default is not None else ...


def convert_to_string(v: Any) -> str:
if isinstance(v, (int, float, bool)):
return str(v)
return v


class StringVariableDefinition(BaseFlatVariableDefinition):
type: Literal["str", "string"] = "string"
default: str | None = None

def pydantic_field_model(self) -> Any:
return str
return Annotated[str, BeforeValidator(convert_to_string)]


class IntegerVariableDefinition(BaseFlatVariableDefinition):
Expand Down
22 changes: 22 additions & 0 deletions tests/engine/models/test_template_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,3 +290,25 @@ def test_template_data_validation_for_nested_objects_with_defaults_inside():

# THEN
assert parsed_data.test_object.test_string == "test"


def test_template_string_variables_accept_integer_inputs_and_converts_them():
# GIVEN
template_config = TemplateConfig(
variables={
"test_string": StringVariableDefinition(
description="test string",
),
}
)
template_data = {
"test_string": 1,
}
parsed_config = TemplateConfig.model_validate(template_config)

# WHEN
data_model = parsed_config.data_model()
parsed_data = data_model.model_validate(template_data)

# THEN
assert parsed_data.test_string == "1"

0 comments on commit 0dda277

Please sign in to comment.