Branching mogilefs-client to version 1.2.1
[ruby-mogilefs-client.git] / test / test_pool.rb
blob1a64752f6a9f8312cb813de609bd7208f18c897b
1 require 'test/unit'
3 $TESTING = true
5 require 'mogilefs/pool'
7 class MogileFS::Pool
9   attr_reader :objects, :queue
11 end
13 class Resource; end
15 class ResourceWithArgs
17   def initialize(args)
18   end
20 end
22 class TestPool < Test::Unit::TestCase
24   def setup
25     @pool = MogileFS::Pool.new Resource
26   end
28   def test_get
29     o1 = @pool.get
30     o2 = @pool.get
31     assert_kind_of Resource, o1
32     assert_kind_of Resource, o2
33     assert_not_equal o1, o2
34   end
36   def test_get_with_args
37     @pool = MogileFS::Pool.new ResourceWithArgs, 'my arg'
38     o = @pool.get
39     assert_kind_of ResourceWithArgs, o
40   end
42   def test_put
43     o = @pool.get
44     @pool.put o
46     assert_raises(MogileFS::Pool::BadObjectError) { @pool.put nil }
47     assert_raises(MogileFS::Pool::BadObjectError) { @pool.put Resource.new }
48   end
50   def test_put_destroy
51     objs = (0...7).map { @pool.get } # pool full
53     assert_equal 7, @pool.objects.length
54     assert_equal 0, @pool.queue.length
56     4.times { @pool.put objs.shift }
58     assert_equal 7, @pool.objects.length
59     assert_equal 4, @pool.queue.length
61     @pool.put objs.shift # trip threshold
63     assert_equal 4, @pool.objects.length
64     assert_equal 2, @pool.queue.length
66     @pool.put objs.shift # don't need to remove any more
68     assert_equal 4, @pool.objects.length
69     assert_equal 3, @pool.queue.length
71     @pool.put objs.shift until objs.empty?
73     assert_equal 4, @pool.objects.length
74     assert_equal 4, @pool.queue.length
75   end
77   def test_use
78     val = @pool.use { |o| assert_kind_of Resource, o }
79     assert_equal nil, val, "Don't return object from pool"
80   end
82   def test_use_with_exception
83     @pool.use { |o| raise } rescue nil
84     assert_equal 1, @pool.queue.length, "Resource not returned to pool"
85   end
87   def test_use_reuse
88     o1 = nil
89     o2 = nil
91     @pool.use { |o| o1 = o }
92     @pool.use { |o| o2 = o }
94     assert_equal o1, o2, "Objects must be reused"
95   end
97 end