Skip to content

Commit ad9bf8b

Browse files
authored
Merge pull request #51 from Cosmicoppai/co/timeout
added the check for negative sec
2 parents 7d10160 + 7d2af46 commit ad9bf8b

File tree

2 files changed

+11
-3
lines changed

2 files changed

+11
-3
lines changed

lib/timeout.rb

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,9 +141,10 @@ def self.ensure_timeout_thread_created
141141
# Perform an operation in a block, raising an error if it takes longer than
142142
# +sec+ seconds to complete.
143143
#
144-
# +sec+:: Number of seconds to wait for the block to terminate. Any number
145-
# may be used, including Floats to specify fractional seconds. A
144+
# +sec+:: Number of seconds to wait for the block to terminate. Any non-negative number
145+
# or nil may be used, including Floats to specify fractional seconds. A
146146
# value of 0 or +nil+ will execute the block without any timeout.
147+
# Any negative number will raise an ArgumentError.
147148
# +klass+:: Exception Class to raise if the block fails to terminate
148149
# in +sec+ seconds. Omitting will use the default, Timeout::Error
149150
# +message+:: Error message to raise with Exception Class.
@@ -165,6 +166,7 @@ def self.ensure_timeout_thread_created
165166
# a module method, so you can call it directly as Timeout.timeout().
166167
def timeout(sec, klass = nil, message = nil, &block) #:yield: +sec+
167168
return yield(sec) if sec == nil or sec.zero?
169+
raise ArgumentError, "Timeout sec must be a non-negative number" if 0 > sec
168170

169171
message ||= "execution expired"
170172

test/test_timeout.rb

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,12 @@ def test_allows_nil_seconds
3131
end
3232
end
3333

34+
def test_raise_for_neg_second
35+
assert_raise(ArgumentError) do
36+
Timeout.timeout(-1) { sleep(0.01) }
37+
end
38+
end
39+
3440
def test_included
3541
c = Class.new do
3642
include Timeout
@@ -114,7 +120,7 @@ def test_nested_timeout_which_error_bubbles_up
114120
def test_cannot_convert_into_time_interval
115121
bug3168 = '[ruby-dev:41010]'
116122
def (n = Object.new).zero?; false; end
117-
assert_raise(TypeError, bug3168) {Timeout.timeout(n) { sleep 0.1 }}
123+
assert_raise(ArgumentError, bug3168) {Timeout.timeout(n) { sleep 0.1 }}
118124
end
119125

120126
def test_skip_rescue_standarderror

0 commit comments

Comments
 (0)