forked from peanutzhen/peanutcache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_test.go
82 lines (74 loc) · 1.56 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
// Copyright 2021 Peanutzhen. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package peanutcache
import (
"fmt"
"log"
"math/rand"
"reflect"
"testing"
"time"
)
func createTestSvr() (*Group, *server) {
mysql := map[string]string{
"Tom": "630",
"Jack": "589",
"Sam": "567",
}
g := NewGroup("scores", 2<<10, RetrieverFunc(
func(key string) ([]byte, error) {
log.Println("[Mysql] search key", key)
if v, ok := mysql[key]; ok {
return []byte(v), nil
}
return nil, fmt.Errorf("%s not exist", key)
}))
r := rand.New(rand.NewSource(time.Now().UnixNano()))
// 随机一个端口 避免冲突
port := 50000 + r.Intn(100)
addr := fmt.Sprintf("localhost:%d", port)
svr, err := NewServer(addr)
if err != nil {
log.Fatal(err)
}
svr.SetPeers()
g.RegisterSvr(svr)
return g, svr
}
func TestServer_GetExistsKey(t *testing.T) {
g, svr := createTestSvr()
go func() {
err := svr.Start()
if err != nil {
log.Fatal(err)
}
}()
view, err := g.Get("Tom")
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(view.String(), "630") {
t.Errorf("Tom %s(actual)/%s(ok)", view.String(), "630")
}
log.Printf("Tom -> %s", view.String())
DestroyGroup(g.name)
}
func TestServer_GetUnknownKey(t *testing.T) {
g, svr := createTestSvr()
go func() {
err := svr.Start()
if err != nil {
log.Fatal(err)
}
}()
_, err := g.Get("Unknown")
if err != nil {
if err.Error() != "Unknown not exist" {
t.Fatal(err)
} else {
t.Log(err.Error())
}
}
DestroyGroup(g.name)
}