• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1package testing
2
3import (
4	"../../tests/MyGame/Example"
5	flatbuffers "github.com/google/flatbuffers/go"
6
7	"context"
8	"net"
9	"testing"
10
11	"google.golang.org/grpc"
12	"google.golang.org/grpc/encoding"
13)
14
15type server struct{}
16
17// test used to send and receive in grpc methods
18var test = "Flatbuffers"
19var addr = "0.0.0.0:50051"
20
21// gRPC server store method
22func (s *server) Store(context context.Context, in *Example.Monster) (*flatbuffers.Builder, error) {
23	b := flatbuffers.NewBuilder(0)
24	i := b.CreateString(test)
25	Example.StatStart(b)
26	Example.StatAddId(b, i)
27	b.Finish(Example.StatEnd(b))
28	return b, nil
29
30}
31
32// gRPC server retrieve method
33func (s *server) Retrieve(context context.Context, in *Example.Stat) (*flatbuffers.Builder, error) {
34	b := flatbuffers.NewBuilder(0)
35	i := b.CreateString(test)
36	Example.MonsterStart(b)
37	Example.MonsterAddName(b, i)
38	b.Finish(Example.MonsterEnd(b))
39	return b, nil
40}
41
42func StoreClient(c Example.MonsterStorageClient, t *testing.T) {
43	b := flatbuffers.NewBuilder(0)
44	i := b.CreateString(test)
45	Example.MonsterStart(b)
46	Example.MonsterAddName(b, i)
47	b.Finish(Example.MonsterEnd(b))
48	out, err := c.Store(context.Background(), b)
49	if err != nil {
50		t.Fatalf("Store client failed: %v", err)
51	}
52	if string(out.Id()) != test {
53		t.Errorf("StoreClient failed: expected=%s, got=%s\n", test, out.Id())
54		t.Fail()
55	}
56}
57
58func RetrieveClient(c Example.MonsterStorageClient, t *testing.T) {
59	b := flatbuffers.NewBuilder(0)
60	i := b.CreateString(test)
61	Example.StatStart(b)
62	Example.StatAddId(b, i)
63	b.Finish(Example.StatEnd(b))
64	out, err := c.Retrieve(context.Background(), b)
65	if err != nil {
66		t.Fatalf("Retrieve client failed: %v", err)
67	}
68	if string(out.Name()) != test {
69		t.Errorf("RetrieveClient failed: expected=%s, got=%s\n", test, out.Name())
70		t.Fail()
71	}
72}
73
74func TestGRPC(t *testing.T) {
75	lis, err := net.Listen("tcp", addr)
76	if err != nil {
77		t.Fatalf("Failed to listen: %v", err)
78	}
79	ser := grpc.NewServer()
80	encoding.RegisterCodec(flatbuffers.FlatbuffersCodec{})
81	Example.RegisterMonsterStorageServer(ser, &server{})
82	go func() {
83		if err := ser.Serve(lis); err != nil {
84			t.Fatalf("Failed to serve: %v", err)
85			t.FailNow()
86		}
87	}()
88	conn, err := grpc.Dial(addr, grpc.WithInsecure(), grpc.WithCodec(flatbuffers.FlatbuffersCodec{}))
89	if err != nil {
90		t.Fatalf("Failed to connect: %v", err)
91	}
92	defer conn.Close()
93	client := Example.NewMonsterStorageClient(conn)
94	StoreClient(client, t)
95	RetrieveClient(client, t)
96}
97