Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(internal): remove unused int/float conversion #203

Merged
merged 1 commit into from
Nov 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 6 additions & 9 deletions src/increase/_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -313,16 +313,13 @@ def construct_type(*, value: object, type_: type) -> object:
return [construct_type(value=entry, type_=inner_type) for entry in value]

if origin == float:
try:
return float(cast(Any, value))
except Exception:
return value
if isinstance(value, int):
coerced = float(value)
if coerced != value:
return value
return coerced

if origin == int:
try:
return int(cast(Any, value))
except Exception:
return value
return value

if type_ == datetime:
try:
Expand Down
29 changes: 20 additions & 9 deletions tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -439,21 +439,32 @@ class Model(BaseModel):
assert model_json(model) == expected_json


def test_coerces_int() -> None:
def test_does_not_coerce_int() -> None:
class Model(BaseModel):
bar: int

assert Model.construct(bar=1).bar == 1
assert Model.construct(bar=10.9).bar == 10
assert Model.construct(bar="19").bar == 19
assert Model.construct(bar=False).bar == 0
assert Model.construct(bar=10.9).bar == 10.9
assert Model.construct(bar="19").bar == "19" # type: ignore[comparison-overlap]
assert Model.construct(bar=False).bar is False

# TODO: support this
# assert Model.construct(bar="True").bar == 1

# mismatched types are left as-is
m = Model.construct(bar={"foo": "bar"})
assert m.bar == {"foo": "bar"} # type: ignore[comparison-overlap]
def test_int_to_float_safe_conversion() -> None:
class Model(BaseModel):
float_field: float

m = Model.construct(float_field=10)
assert m.float_field == 10.0
assert isinstance(m.float_field, float)

m = Model.construct(float_field=10.12)
assert m.float_field == 10.12
assert isinstance(m.float_field, float)

# number too big
m = Model.construct(float_field=2**53 + 1)
assert m.float_field == 2**53 + 1
assert isinstance(m.float_field, int)


def test_deprecated_alias() -> None:
Expand Down