10 func TestBufferPool(t *testing.T) {
14 var _ = Suite(&BufferPoolSuite{})
16 type BufferPoolSuite struct{}
18 // Initialize a default-sized buffer pool for the benefit of test
19 // suites that don't run main().
21 bufs = newBufferPool(maxBuffers, BlockSize)
24 // Restore sane default after bufferpool's own tests
25 func (s *BufferPoolSuite) TearDownTest(c *C) {
26 bufs = newBufferPool(maxBuffers, BlockSize)
29 func (s *BufferPoolSuite) TestBufferPoolBufSize(c *C) {
30 bufs := newBufferPool(2, 10)
35 c.Check(len(b3), Equals, 3)
38 func (s *BufferPoolSuite) TestBufferPoolUnderLimit(c *C) {
39 bufs := newBufferPool(3, 10)
42 testBufferPoolRace(c, bufs, b1, "Get")
45 func (s *BufferPoolSuite) TestBufferPoolAtLimit(c *C) {
46 bufs := newBufferPool(2, 10)
49 testBufferPoolRace(c, bufs, b1, "Put")
52 func testBufferPoolRace(c *C, bufs *bufferPool, unused []byte, expectWin string) {
53 race := make(chan string)
56 time.Sleep(time.Millisecond)
60 time.Sleep(10 * time.Millisecond)
64 c.Check(<-race, Equals, expectWin)
65 c.Check(<-race, Not(Equals), expectWin)
69 func (s *BufferPoolSuite) TestBufferPoolReuse(c *C) {
70 bufs := newBufferPool(2, 10)
73 // The buffer pool is allowed to throw away unused buffers
74 // (e.g., during sync.Pool's garbage collection hook, in the
75 // the current implementation). However, if unused buffers are
76 // getting thrown away and reallocated more than {arbitrary
77 // frequency threshold} during a busy loop, it's not acting
78 // much like a buffer pool.
81 for i := 0; i < allocs; i++ {
84 copy(last, []byte("last"))
85 copy(next, []byte("next"))
91 c.Check(reuses > allocs*95/100, Equals, true)