-
Notifications
You must be signed in to change notification settings - Fork 3
/
server_test.go
102 lines (85 loc) · 2.61 KB
/
server_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package planb_test
import (
"io/ioutil"
"net"
"os"
"path/filepath"
"time"
"github.com/bsm/planb"
"github.com/bsm/pool"
"github.com/bsm/redeo"
"github.com/bsm/redeo/client"
"github.com/bsm/redeo/resp"
"github.com/hashicorp/raft"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Server", func() {
var serve = func(cb func(string, client.Conn)) func() {
return func() {
// init dir
dir, err := ioutil.TempDir("", "planb-test")
Expect(err).NotTo(HaveOccurred())
defer os.RemoveAll(dir)
// init listener
lis, err := net.Listen("tcp", "127.0.0.1:")
Expect(err).NotTo(HaveOccurred())
addr := lis.Addr().String()
defer lis.Close()
// init config
conf := planb.NewConfig()
conf.Raft.LogOutput = ioutil.Discard
// setup server
store := planb.NewInmemStore()
rfs := raft.NewInmemStore()
srv, err := planb.NewServer(raft.ServerAddress(addr), dir, store, rfs, rfs, conf)
Expect(err).NotTo(HaveOccurred())
defer srv.Close()
// handle commands
srv.HandleRO("echo", nil, redeo.WrapperFunc(func(cmd *resp.Command) interface{} {
if len(cmd.Args) < 1 {
return redeo.ErrWrongNumberOfArgs(cmd.Name)
}
return cmd.Args[0]
}))
srv.HandleRO("now", nil, redeo.WrapperFunc(func(cmd *resp.Command) interface{} {
return time.Now().Unix()
}))
srv.HandleRW("reset", nil, redeo.WrapperFunc(func(cmd *resp.Command) interface{} {
return true
}))
// start server
go srv.Serve(lis)
pool, err := client.New(&pool.Options{InitialSize: 1}, func() (net.Conn, error) {
return net.Dial("tcp", addr)
})
Expect(err).NotTo(HaveOccurred())
defer pool.Close()
conn, err := pool.Get()
Expect(err).NotTo(HaveOccurred())
cb(dir, conn)
}
}
It("should create dir structure", serve(func(dir string, cn client.Conn) {
Expect(filepath.Glob(filepath.Join(dir, "*"))).To(ConsistOf(
dir+"/node-id",
dir+"/snapshots",
))
data, err := ioutil.ReadFile(dir + "/node-id")
Expect(err).NotTo(HaveOccurred())
Expect(string(data)).To(HaveLen(36))
}))
It("should handle read-only commands", serve(func(dir string, cn client.Conn) {
cn.WriteCmdString("ECHO", "HeLLo")
Expect(cn.Flush()).To(Succeed())
Expect(cn.ReadBulkString()).To(Equal("HeLLo"))
cn.WriteCmdString("NOW")
Expect(cn.Flush()).To(Succeed())
Expect(cn.ReadInt()).To(BeNumerically("~", time.Now().Unix(), 2))
}))
It("should fail on read/write commands if not leader", serve(func(dir string, cn client.Conn) {
cn.WriteCmdString("RESET")
Expect(cn.Flush()).To(Succeed())
Expect(cn.ReadError()).To(Equal("READONLY node is not the leader"))
}))
})