writebehind
2015-03-31
writebehind/writebehind_test.go
First pass implementation. Create our first implementation of this. Use a map of string=>int64 to store our values. The idea here is that users will create one cache for each metric they want to collect--each column that needs updating, in MySQL land. Release it under the MIT license, because why not? Very proud that the first commit carries 100% test coverage, no golint errors, no go vet errors, and has a benchmark.
1 package writebehind
3 import (
4 "encoding/json"
5 "testing"
6 "time"
7 )
9 func TestSync(t *testing.T) {
10 m := MemoryIncrementer{}
11 c := NewCache(&m, time.Millisecond)
12 defer c.Stop()
13 c.Sync() // test that unnecessary sync is a no-op
14 c.Increment("test1", 10)
15 c.Increment("test2", 100)
16 time.Sleep(time.Millisecond)
17 if m.Get("test1") != 10 {
18 t.Errorf("Expected test1 to be %d, got %d", 10, m.values["test1"])
19 }
20 if m.Get("test2") != 100 {
21 t.Errorf("Expected test2 to be %d, got %d", 100, m.values["test2"])
22 }
23 c.Increment("test1", 10)
24 c.Increment("test2", 100)
25 time.Sleep(time.Millisecond)
26 if m.Get("test1") != 20 {
27 t.Errorf("Expected test1 to be %d, got %d", 20, m.values["test1"])
28 }
29 if m.Get("test2") != 200 {
30 t.Errorf("Expected test2 to be %d, got %d", 200, m.values["test2"])
31 }
32 }
34 func TestString(t *testing.T) {
35 m := MemoryIncrementer{}
36 c := NewCache(&m, time.Millisecond)
37 defer c.Stop()
38 c.Increment("test1", 10)
39 c.Increment("test2", 100)
40 c.Increment(`"test3"`, 1000)
41 str := c.String()
42 var result map[string]int64
43 err := json.Unmarshal([]byte(str), &result)
44 if err != nil {
45 t.Errorf("Error unmarshalling returned JSON: %#+v", err)
46 }
47 if result["test1"] != 10 {
48 t.Errorf("Expected test1 to be %d, got %d", 10, result["test1"])
49 }
50 if result["test2"] != 100 {
51 t.Errorf("Expected test2 to be %d, got %d", 100, result["test2"])
52 }
53 if result["\"test3\""] != 1000 {
54 t.Errorf("Expected \"test3\" to be %d, got %d", 1000, result["\"test3\""])
55 }
56 }
58 func BenchmarkSync(b *testing.B) {
59 m := MemoryIncrementer{}
60 c := NewCache(&m, time.Second*5)
61 defer c.Stop()
63 b.RunParallel(func(pb *testing.PB) {
64 for pb.Next() {
65 c.Increment("myvalue", 1)
66 c.Increment("othervalue", 1)
67 c.Increment("other other value", 1)
68 c.Increment("weird value", 1)
69 }
70 })
71 }