1
|
|
|
package grpcserver |
2
|
|
|
|
3
|
|
|
import ( |
4
|
|
|
"context" |
5
|
|
|
"github.com/arazmj/gerdu/lrucache" |
6
|
|
|
"github.com/arazmj/gerdu/proto" |
7
|
|
|
"google.golang.org/grpc" |
8
|
|
|
"google.golang.org/grpc/test/bufconn" |
9
|
|
|
"log" |
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
|
|
|
verbose: false, |
24
|
|
|
}) |
25
|
|
|
go func() { |
26
|
|
|
if err := s.Serve(lis); err != nil { |
27
|
|
|
log.Fatalf("Server exited with error: %v", err) |
28
|
|
|
} |
29
|
|
|
}() |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
func bufDialer(context.Context, string) (net.Conn, error) { |
33
|
|
|
return lis.Dial() |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
func TestServerGrpc(t *testing.T) { |
37
|
|
|
ctx := context.Background() |
38
|
|
|
conn, err := grpc.DialContext(ctx, "bufnet", grpc.WithContextDialer(bufDialer), grpc.WithInsecure()) |
39
|
|
|
if err != nil { |
40
|
|
|
t.Fatalf("Failed to dial bufnet: %v", err) |
41
|
|
|
} |
42
|
|
|
defer conn.Close() |
43
|
|
|
client := proto.NewGerduClient(conn) |
44
|
|
|
resp, err := client.Put(ctx, &proto.PutRequest{ |
45
|
|
|
Key: "Key1", |
46
|
|
|
Value: []byte("Value1"), |
47
|
|
|
}) |
48
|
|
|
if err != nil { |
49
|
|
|
t.Fatalf("gRPC Put failed: %v", err) |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
if resp.Created != true { |
53
|
|
|
t.Fatalf("gRPC Put could not create the key") |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
response, err := client.Get(ctx, &proto.GetRequest{ |
57
|
|
|
Key: "Key1", |
58
|
|
|
}) |
59
|
|
|
|
60
|
|
|
if err != nil { |
61
|
|
|
t.Fatalf("gRPC Get failed: %v", err) |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
value := string(response.Value) |
65
|
|
|
if value != "Value1" { |
66
|
|
|
t.Fatalf("gRPC Get the value does not match expecting Value1, but got %v", value) |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|