|
1
|
|
|
package grpcserver |
|
2
|
|
|
|
|
3
|
|
|
import ( |
|
4
|
|
|
"context" |
|
5
|
|
|
"github.com/arazmj/gerdu/lrucache" |
|
6
|
|
|
"github.com/arazmj/gerdu/proto" |
|
7
|
|
|
log "github.com/sirupsen/logrus" |
|
8
|
|
|
"google.golang.org/grpc" |
|
9
|
|
|
"google.golang.org/grpc/test/bufconn" |
|
10
|
|
|
"net" |
|
11
|
|
|
"testing" |
|
12
|
|
|
) |
|
13
|
|
|
|
|
14
|
|
|
const bufSize = 1024 * 1024 |
|
15
|
|
|
|
|
16
|
|
|
var lis *bufconn.Listener |
|
17
|
|
|
|
|
18
|
|
|
func init() { |
|
19
|
|
|
lis = bufconn.Listen(bufSize) |
|
20
|
|
|
s := grpc.NewServer() |
|
21
|
|
|
proto.RegisterGerduServer(s, &server{ |
|
22
|
|
|
gerdu: lrucache.NewCache(1000), |
|
23
|
|
|
}) |
|
24
|
|
|
go func() { |
|
25
|
|
|
if err := s.Serve(lis); err != nil { |
|
26
|
|
|
log.Fatalf("Server exited with error: %v", err) |
|
27
|
|
|
} |
|
28
|
|
|
}() |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
func bufDialer(context.Context, string) (net.Conn, error) { |
|
32
|
|
|
return lis.Dial() |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
func TestServerGrpc(t *testing.T) { |
|
36
|
|
|
ctx := context.Background() |
|
37
|
|
|
conn, err := grpc.DialContext(ctx, "bufnet", grpc.WithContextDialer(bufDialer), grpc.WithInsecure()) |
|
38
|
|
|
if err != nil { |
|
39
|
|
|
t.Fatalf("Failed to dial bufnet: %v", err) |
|
40
|
|
|
} |
|
41
|
|
|
defer conn.Close() |
|
42
|
|
|
client := proto.NewGerduClient(conn) |
|
43
|
|
|
resp, err := client.Put(ctx, &proto.PutRequest{ |
|
44
|
|
|
Key: "Key1", |
|
45
|
|
|
Value: []byte("Value1"), |
|
46
|
|
|
}) |
|
47
|
|
|
if err != nil { |
|
48
|
|
|
t.Fatalf("gRPC Put failed: %v", err) |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
if resp.Created != true { |
|
52
|
|
|
t.Fatalf("gRPC Put could not create the key") |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
response, err := client.Get(ctx, &proto.GetRequest{ |
|
56
|
|
|
Key: "Key1", |
|
57
|
|
|
}) |
|
58
|
|
|
|
|
59
|
|
|
if err != nil { |
|
60
|
|
|
t.Fatalf("gRPC Get failed: %v", err) |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
value := string(response.Value) |
|
64
|
|
|
if value != "Value1" { |
|
65
|
|
|
t.Fatalf("gRPC Get the value does not match expecting Value1, but got %v", value) |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
client.Delete(ctx, &proto.DeleteRequest{Key: "Key1"}) |
|
69
|
|
|
_, err = client.Get(ctx, &proto.GetRequest{ |
|
70
|
|
|
Key: "Key1", |
|
71
|
|
|
}) |
|
72
|
|
|
|
|
73
|
|
|
if err == nil { |
|
74
|
|
|
t.Fatalf("gRPC Deleted key should not get: %v", err) |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|