1
0
Fork 0
mirror of https://github.com/mperham/connection_pool synced 2023-03-27 23:22:21 -04:00
connection_pool/test/test_connection_pool.rb

90 lines
1.9 KiB
Ruby
Raw Normal View History

Thread.abort_on_exception = true
2011-05-14 18:36:17 -04:00
require 'helper'
class TestConnectionPool < MiniTest::Unit::TestCase
class NetworkConnection
2011-05-14 22:42:07 -04:00
def initialize
@x = 0
end
2011-05-14 18:36:17 -04:00
def do_something
2011-05-14 22:42:07 -04:00
@x += 1
sleep 0.05
@x
end
def fast
@x += 1
2011-05-14 18:36:17 -04:00
end
2012-02-08 12:44:18 -05:00
def do_something_with_block
@x += yield
2012-02-08 12:45:26 -05:00
sleep 0.05
2012-02-08 12:44:18 -05:00
@x
end
2011-05-14 18:36:17 -04:00
end
def test_basic_multithreaded_usage
pool = ConnectionPool.new(:size => 5) { NetworkConnection.new }
threads = []
2011-05-14 22:42:07 -04:00
15.times do
2011-05-14 18:36:17 -04:00
threads << Thread.new do
2011-05-14 22:42:07 -04:00
pool.with_connection do |net|
2011-05-14 18:36:17 -04:00
net.do_something
end
end
end
2011-09-25 22:23:35 -04:00
2011-05-14 18:36:17 -04:00
a = Time.now
2011-05-14 22:42:07 -04:00
result = threads.map(&:value)
2011-05-14 18:36:17 -04:00
b = Time.now
2011-05-14 22:42:07 -04:00
assert_operator((b - a), :>, 0.125)
2012-02-05 22:54:48 -05:00
assert_equal([1,2,3].cycle(5).sort, result.sort)
2011-05-14 18:36:17 -04:00
end
def test_timeout
2011-05-14 22:42:07 -04:00
pool = ConnectionPool.new(:timeout => 0.05, :size => 1) { NetworkConnection.new }
2011-05-14 18:36:17 -04:00
Thread.new do
pool.with do |net|
net.do_something
2011-05-14 22:42:07 -04:00
sleep 0.1
2011-05-14 18:36:17 -04:00
end
end
2011-05-14 22:42:07 -04:00
sleep 0.05
2011-05-14 18:36:17 -04:00
assert_raises Timeout::Error do
pool.with { |net| net.do_something }
2011-05-14 18:36:17 -04:00
end
sleep 0.05
pool.with do |conn|
refute_nil conn
end
2011-05-14 18:36:17 -04:00
end
def test_passthru
pool = ConnectionPool.wrap(:timeout => 0.1, :size => 1) { NetworkConnection.new }
2011-05-14 22:42:07 -04:00
assert_equal 1, pool.do_something
assert_equal 2, pool.do_something
2012-02-08 12:44:18 -05:00
assert_equal 5, pool.do_something_with_block { 3 }
assert_equal 6, pool.with { |net| net.fast }
2011-05-14 22:42:07 -04:00
end
def test_return_value
pool = ConnectionPool.new(:timeout => 0.1, :size => 1) { NetworkConnection.new }
result = pool.with_connection do |net|
net.fast
end
assert_equal 1, result
2011-05-14 18:36:17 -04:00
end
def test_heavy_threading
pool = ConnectionPool.new(:timeout => 0.5, :size => 3) { NetworkConnection.new }
20.times do
Thread.new do
pool.with do |net|
sleep 0.05
end
end
end
sleep 0.5
end
end