FIX: fix double validation (#314)

The old float validation had several bugs. It will recognize strings
like "a1.2" and "3.4b" as valid doubles, but will not recognize integers
like "1234" as doubles. Also, since an empty string is not falsy in Ruby,
it will recognize "Inf" as -Infinity.

This commit fixes these issues
This commit is contained in:
锦心 2024-08-21 15:39:56 +08:00 committed by GitHub
parent 6bf3ac7426
commit 1d991c6192
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 23 additions and 3 deletions

View File

@ -153,16 +153,16 @@ module ::DiscourseDataExplorer
invalid_format string, e.message invalid_format string, e.message
end end
when :double when :double
if string =~ /-?\d*(\.\d+)/ if string.strip =~ /^-?\d*\.?\d+$/
value = Float(string) value = Float(string)
elsif string =~ /^(-?)Inf(inity)?$/i elsif string =~ /^(-?)Inf(inity)?$/i
if $1 if $1.present?
value = -Float::INFINITY value = -Float::INFINITY
else else
value = Float::INFINITY value = Float::INFINITY
end end
elsif string =~ /^(-?)NaN$/i elsif string =~ /^(-?)NaN$/i
if $1 if $1.present?
value = -Float::NAN value = -Float::NAN
else else
value = Float::NAN value = Float::NAN

View File

@ -16,6 +16,26 @@ RSpec.describe DiscourseDataExplorer::Parameter do
) )
end end
describe "double type" do
let!(:double_param) { param("double", :double, nil, false) }
it "raises an error if not a double" do
expect { double_param.cast_to_ruby("abcd") }.to raise_error(
::DiscourseDataExplorer::ValidationError,
)
end
it "returns the float number if it can be a valid double" do
expect(double_param.cast_to_ruby("3.14")).to eq(3.14)
expect(double_param.cast_to_ruby(".314")).to eq(0.314)
expect(double_param.cast_to_ruby("1")).to eq(1.0)
expect(double_param.cast_to_ruby("Inf")).to eq(Float::INFINITY)
expect(double_param.cast_to_ruby("-Infinity")).to eq(-Float::INFINITY)
expect(double_param.cast_to_ruby("-NaN").nan?).to eq(true)
expect(double_param.cast_to_ruby("NaN").nan?).to eq(true)
end
end
describe "post_id type" do describe "post_id type" do
fab!(:post) fab!(:post)