From b4693e9920062039810c1633a1900062e47e19ea Mon Sep 17 00:00:00 2001 From: Thanabodee Charoenpiriyakij Date: Tue, 5 Jul 2022 10:05:09 +0700 Subject: [PATCH] Do not accepting float number in integer type Treat float number as invalid type when set type to `:integer`. Fixes #467 --- lib/open_api_spex/cast/integer.ex | 6 +----- test/cast/integer_test.exs | 9 +++++---- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/lib/open_api_spex/cast/integer.ex b/lib/open_api_spex/cast/integer.ex index 461bfd3f..95a7e4a0 100644 --- a/lib/open_api_spex/cast/integer.ex +++ b/lib/open_api_spex/cast/integer.ex @@ -9,12 +9,8 @@ defmodule OpenApiSpex.Cast.Integer do end end - def cast(%{value: value} = ctx) when is_number(value) do - cast(%{ctx | value: round(value)}) - end - def cast(%{value: value} = ctx) when is_binary(value) do - case Float.parse(value) do + case Integer.parse(value) do {value, ""} -> cast(%{ctx | value: value}) _ -> Cast.error(ctx, {:invalid_type, :integer}) end diff --git a/test/cast/integer_test.exs b/test/cast/integer_test.exs index 3f11bbbe..41d6aa8e 100644 --- a/test/cast/integer_test.exs +++ b/test/cast/integer_test.exs @@ -9,12 +9,13 @@ defmodule OpenApiSpex.CastIntegerTest do test "basics" do schema = %Schema{type: :integer} assert cast(value: 1, schema: schema) == {:ok, 1} - assert cast(value: 1.5, schema: schema) == {:ok, 2} assert cast(value: "1", schema: schema) == {:ok, 1} - assert cast(value: "1.5", schema: schema) == {:ok, 2} + assert {:error, [error]} = cast(value: 1.5, schema: schema) + assert %Error{reason: :invalid_type, value: 1.5} = error + assert {:error, [error]} = cast(value: "1.5", schema: schema) + assert %Error{reason: :invalid_type, value: "1.5"} = error assert {:error, [error]} = cast(value: "other", schema: schema) - assert %Error{reason: :invalid_type} = error - assert error.value == "other" + assert %Error{reason: :invalid_type, value: "other"} = error end test "with multiple of" do