...
1 package codegenerator_test
2
3 import (
4 "bytes"
5 "errors"
6 "io"
7 "strings"
8 "testing"
9
10 "github.com/google/go-cmp/cmp"
11 "github.com/grpc-ecosystem/grpc-gateway/v2/internal/codegenerator"
12 "google.golang.org/protobuf/proto"
13 "google.golang.org/protobuf/testing/protocmp"
14 "google.golang.org/protobuf/types/pluginpb"
15 )
16
17 var parseReqTests = []struct {
18 name string
19 in io.Reader
20 out *pluginpb.CodeGeneratorRequest
21 expectErr bool
22 }{
23 {
24 "Empty input should produce empty output",
25 mustGetReader(&pluginpb.CodeGeneratorRequest{}),
26 &pluginpb.CodeGeneratorRequest{},
27 false,
28 },
29 {
30 "Invalid reader should produce error",
31 &invalidReader{},
32 nil,
33 true,
34 },
35 {
36 "Invalid proto message should produce error",
37 strings.NewReader("{}"),
38 nil,
39 true,
40 },
41 }
42
43 func TestParseRequest(t *testing.T) {
44 for _, tt := range parseReqTests {
45 t.Run(tt.name, func(t *testing.T) {
46 out, err := codegenerator.ParseRequest(tt.in)
47 if tt.expectErr && err == nil {
48 t.Error("did not error as expected")
49 }
50 if diff := cmp.Diff(out, tt.out, protocmp.Transform()); diff != "" {
51 t.Errorf(diff)
52 }
53 })
54 }
55 }
56
57 func mustGetReader(pb proto.Message) io.Reader {
58 b, err := proto.Marshal(pb)
59 if err != nil {
60 panic(err)
61 }
62 return bytes.NewBuffer(b)
63 }
64
65 type invalidReader struct {
66 }
67
68 func (*invalidReader) Read(p []byte) (int, error) {
69 return 0, errors.New("invalid reader")
70 }
71
View as plain text