diff --git a/lib/timeout.rb b/lib/timeout.rb index 6448f4f..a1595a8 100644 --- a/lib/timeout.rb +++ b/lib/timeout.rb @@ -141,9 +141,10 @@ def self.ensure_timeout_thread_created # Perform an operation in a block, raising an error if it takes longer than # +sec+ seconds to complete. # - # +sec+:: Number of seconds to wait for the block to terminate. Any number - # may be used, including Floats to specify fractional seconds. A + # +sec+:: Number of seconds to wait for the block to terminate. Any non-negative number + # or nil may be used, including Floats to specify fractional seconds. A # value of 0 or +nil+ will execute the block without any timeout. + # Any negative number will raise an ArgumentError. # +klass+:: Exception Class to raise if the block fails to terminate # in +sec+ seconds. Omitting will use the default, Timeout::Error # +message+:: Error message to raise with Exception Class. @@ -165,6 +166,7 @@ def self.ensure_timeout_thread_created # a module method, so you can call it directly as Timeout.timeout(). def timeout(sec, klass = nil, message = nil, &block) #:yield: +sec+ return yield(sec) if sec == nil or sec.zero? + raise ArgumentError, "Timeout sec must be a non-negative number" if 0 > sec message ||= "execution expired" diff --git a/test/test_timeout.rb b/test/test_timeout.rb index 34966f9..0115686 100644 --- a/test/test_timeout.rb +++ b/test/test_timeout.rb @@ -31,6 +31,12 @@ def test_allows_nil_seconds end end + def test_raise_for_neg_second + assert_raise(ArgumentError) do + Timeout.timeout(-1) { sleep(0.01) } + end + end + def test_included c = Class.new do include Timeout @@ -114,7 +120,7 @@ def test_nested_timeout_which_error_bubbles_up def test_cannot_convert_into_time_interval bug3168 = '[ruby-dev:41010]' def (n = Object.new).zero?; false; end - assert_raise(TypeError, bug3168) {Timeout.timeout(n) { sleep 0.1 }} + assert_raise(ArgumentError, bug3168) {Timeout.timeout(n) { sleep 0.1 }} end def test_skip_rescue_standarderror