Skip to content

Commit

Permalink
Merge pull request #25 from Salman778/fix-integer-for-zero
Browse files Browse the repository at this point in the history
fix: integer validation for zero
  • Loading branch information
ahoshaiyan authored Nov 10, 2024
2 parents ad97d3f + b77bd22 commit 9f63f9d
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
3 changes: 2 additions & 1 deletion lib/mini_defender/rules/integer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,10 @@ def passes?(attribute, value, validator)
end

# Remove leading zero so Integer will not treat it as octal
# Handle leading zeros while preserving both + and - signs
value = value
.to_s
.gsub(/^0+/, '')
.gsub(/^([+-])?0+(?=\d)/, '\1')

if @mode == 'relaxed'
value = normalize_digits(value)
Expand Down
46 changes: 46 additions & 0 deletions test/rules/integer_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,50 @@ def test_relaxed_passes_with_mixed_digits
def test_passes_with_integer_with_leading_zero
assert @rule_relax.passes?('amount', '08', nil)
end

def test_passes_with_single_zero
assert @rule.passes?('amount', '0', nil)
assert_equal 0, @rule.coerce('0')
end

def test_passes_with_multiple_zeros
assert @rule.passes?('amount', '00', nil)
assert_equal 0, @rule.coerce('00')
end

# Test for leading zeros before other digits
def test_removes_leading_zeros_before_digits
assert @rule.passes?('amount', '01', nil)
assert_equal 1, @rule.coerce('01')

assert @rule.passes?('amount', '0123', nil)
assert_equal 123, @rule.coerce('0123')

assert @rule.passes?('amount', '00123', nil)
assert_equal 123, @rule.coerce('00123')
end

def test_handles_zeros_with_whitespace
assert @rule.passes?('amount', ' 0 ', nil)
assert_equal 0, @rule.coerce(' 0 ')

assert @rule.passes?('amount', ' 00 ', nil)
assert_equal 0, @rule.coerce(' 00 ')
end

def test_handles_negative_numbers_with_leading_zeros
assert @rule.passes?('amount', '-001', nil)
assert_equal(-1, @rule.coerce('-001'))

assert @rule.passes?('amount', '-00123', nil)
assert_equal(-123, @rule.coerce('-00123'))
end

def test_handles_positve_numbers_with_leading_zeros
assert @rule.passes?('amount', '+001', nil)
assert_equal(1, @rule.coerce('+001'))

assert @rule.passes?('amount', '+00123', nil)
assert_equal(123, @rule.coerce('+00123'))
end
end

0 comments on commit 9f63f9d

Please sign in to comment.