5824: Merge branch 'master' into 5824-go-sdk
[arvados.git] / services / keepstore / bufferpool_test.go
1 package main
2
3 import (
4         . "gopkg.in/check.v1"
5         "testing"
6         "time"
7 )
8
9 // Gocheck boilerplate
10 func TestBufferPool(t *testing.T) {
11         TestingT(t)
12 }
13
14 var _ = Suite(&BufferPoolSuite{})
15
16 type BufferPoolSuite struct{}
17
18 // Initialize a default-sized buffer pool for the benefit of test
19 // suites that don't run main().
20 func init() {
21         bufs = newBufferPool(maxBuffers, BLOCKSIZE)
22 }
23
24 // Restore sane default after bufferpool's own tests
25 func (s *BufferPoolSuite) TearDownTest(c *C) {
26         bufs = newBufferPool(maxBuffers, BLOCKSIZE)
27 }
28
29 func (s *BufferPoolSuite) TestBufferPoolBufSize(c *C) {
30         bufs := newBufferPool(2, 10)
31         b1 := bufs.Get(1)
32         bufs.Get(2)
33         bufs.Put(b1)
34         b3 := bufs.Get(3)
35         c.Check(len(b3), Equals, 3)
36 }
37
38 func (s *BufferPoolSuite) TestBufferPoolUnderLimit(c *C) {
39         bufs := newBufferPool(3, 10)
40         b1 := bufs.Get(10)
41         bufs.Get(10)
42         testBufferPoolRace(c, bufs, b1, "Get")
43 }
44
45 func (s *BufferPoolSuite) TestBufferPoolAtLimit(c *C) {
46         bufs := newBufferPool(2, 10)
47         b1 := bufs.Get(10)
48         bufs.Get(10)
49         testBufferPoolRace(c, bufs, b1, "Put")
50 }
51
52 func testBufferPoolRace(c *C, bufs *bufferPool, unused []byte, expectWin string) {
53         race := make(chan string)
54         go func() {
55                 bufs.Get(10)
56                 time.Sleep(time.Millisecond)
57                 race <- "Get"
58         }()
59         go func() {
60                 time.Sleep(10 * time.Millisecond)
61                 bufs.Put(unused)
62                 race <- "Put"
63         }()
64         c.Check(<-race, Equals, expectWin)
65         c.Check(<-race, Not(Equals), expectWin)
66         close(race)
67 }
68
69 func (s *BufferPoolSuite) TestBufferPoolReuse(c *C) {
70         bufs := newBufferPool(2, 10)
71         bufs.Get(10)
72         last := bufs.Get(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.
79         allocs := 1000
80         reuses := 0
81         for i := 0; i < allocs; i++ {
82                 bufs.Put(last)
83                 next := bufs.Get(10)
84                 copy(last, []byte("last"))
85                 copy(next, []byte("next"))
86                 if last[0] == 'n' {
87                         reuses++
88                 }
89                 last = next
90         }
91         c.Check(reuses > allocs*95/100, Equals, true)
92 }