Ruby mogilefs-client 3.4.0
[ruby-mogilefs-client.git] / test / test_pool.rb
blobdc40e85127f44c84504936f6003e885e30a57a33
1 # -*- encoding: binary -*-
2 require 'test/unit'
4 $TESTING = true
5 require 'mogilefs'
6 require 'mogilefs/pool'
8 class MogileFS::Pool
10   attr_reader :objects, :queue
12 end
14 class Resource; end
16 class ResourceWithArgs
18   def initialize(args)
19   end
21 end
22 class PoolClient < MogileFS::Client
23   attr_reader :alive
25   def initialize(*args)
26     @args = args
27     @alive = true
28   end
30   def backend
31     self
32   end
34   def shutdown
35     @alive = false
36   end
37 end
39 class TestPool < Test::Unit::TestCase
41   def setup
42     @pool = MogileFS::Pool.new Resource
43   end
45   def test_get
46     o1 = @pool.get
47     o2 = @pool.get
48     assert_kind_of Resource, o1
49     assert_kind_of Resource, o2
50     assert_not_equal o1, o2
51   end
53   def test_get_with_args
54     @pool = MogileFS::Pool.new ResourceWithArgs, 'my arg'
55     o = @pool.get
56     assert_kind_of ResourceWithArgs, o
57   end
59   def test_put
60     o = @pool.get
61     @pool.put o
63     assert_raises(MogileFS::Pool::BadObjectError) { @pool.put nil }
64     assert_raises(MogileFS::Pool::BadObjectError) { @pool.put Resource.new }
65   end
67   def test_put_destroy
68     objs = (0...7).map { @pool.get } # pool full
70     assert_equal 7, @pool.objects.length
71     assert_equal 0, @pool.queue.length
73     4.times { @pool.put objs.shift }
75     assert_equal 7, @pool.objects.length
76     assert_equal 4, @pool.queue.length
78     @pool.put objs.shift # trip threshold
80     assert_equal 4, @pool.objects.length
81     assert_equal 2, @pool.queue.length
83     @pool.put objs.shift # don't need to remove any more
85     assert_equal 4, @pool.objects.length
86     assert_equal 3, @pool.queue.length
88     @pool.put objs.shift until objs.empty?
90     assert_equal 4, @pool.objects.length
91     assert_equal 4, @pool.queue.length
92   end
94   def test_use
95     val = @pool.use { |o| assert_kind_of Resource, o }
96     assert_equal nil, val, "Don't return object from pool"
97   end
99   def test_use_with_exception
100     @pool.use { |o| raise } rescue nil
101     assert_equal 1, @pool.queue.length, "Resource not returned to pool"
102   end
104   def test_use_reuse
105     o1 = nil
106     o2 = nil
108     @pool.use { |o| o1 = o }
109     @pool.use { |o| o2 = o }
111     assert_equal o1, o2, "Objects must be reused"
112   end
114   def test_auto_shutdown
115     pool = MogileFS::Pool.new(PoolClient, 666)
116     tmp = []
117     6.times { tmp << pool.get }
118     tmp.each { |obj| pool.put(obj) }
119     alive = Hash.new { |h,k| h[k] = 0 }
120     tmp.each { |obj| alive[obj.alive] += 1 }
121     assert_equal 3, alive[true]
122     assert_equal 3, alive[false]
123   end