-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathcompiler_test.go
More file actions
286 lines (267 loc) · 8.77 KB
/
compiler_test.go
File metadata and controls
286 lines (267 loc) · 8.77 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
// Copyright 2020-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package protocompile
import (
"bytes"
"errors"
"os"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/sync/errgroup"
"google.golang.org/protobuf/reflect/protodesc"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
"google.golang.org/protobuf/types/descriptorpb"
"github.com/bufbuild/protocompile/internal"
"github.com/bufbuild/protocompile/internal/prototest"
"github.com/bufbuild/protocompile/linker"
"github.com/bufbuild/protocompile/parser"
"github.com/bufbuild/protocompile/reporter"
)
func TestParseFilesWithDependencies(t *testing.T) {
t.Parallel()
// Create some file contents that import a non-well-known proto.
// (One of the protos in internal/testdata is fine.)
contents := map[string]string{
"test.proto": `
syntax = "proto3";
import "desc_test_wellknowntypes.proto";
message TestImportedType {
testprotos.TestWellKnownTypes imported_field = 1;
}
`,
}
baseResolver := ResolverFunc(func(f string) (SearchResult, error) {
s, ok := contents[f]
if !ok {
return SearchResult{}, os.ErrNotExist
}
return SearchResult{Source: strings.NewReader(s)}, nil
})
fdset := prototest.LoadDescriptorSet(t, "./internal/testdata/all.protoset", nil)
wktDesc, wktDescProto := findAndLink(t, "desc_test_wellknowntypes.proto", fdset, nil)
ctx := t.Context()
// Establish that we *can* parse the source file with a resolver that provides
// the dependency, as either a full descriptor or as a descriptor proto.
t.Run("DependencyIncluded", func(t *testing.T) {
t.Parallel()
// Create a dependency-aware compiler.
compiler := Compiler{
Resolver: ResolverFunc(func(f string) (SearchResult, error) {
if f == "desc_test_wellknowntypes.proto" {
return SearchResult{Desc: wktDesc}, nil
}
return baseResolver.FindFileByPath(f)
}),
}
_, err := compiler.Compile(ctx, "test.proto")
require.NoError(t, err)
})
t.Run("DependencyIncludedProto", func(t *testing.T) {
t.Parallel()
// Create a dependency-aware compiler.
compiler := Compiler{
Resolver: WithStandardImports(ResolverFunc(func(f string) (SearchResult, error) {
if f == "desc_test_wellknowntypes.proto" {
return SearchResult{Proto: wktDescProto}, nil
}
return baseResolver.FindFileByPath(f)
})),
}
_, err := compiler.Compile(ctx, "test.proto")
require.NoError(t, err)
})
// Establish that we *can not* parse the source file if the resolver
// is not able to resolve the dependency.
t.Run("DependencyExcluded", func(t *testing.T) {
t.Parallel()
// Create a dependency-UNaware parser.
compiler := Compiler{Resolver: baseResolver}
_, err := compiler.Compile(ctx, "test.proto")
require.Error(t, err, "expected parse to fail")
})
t.Run("NoDependencies", func(t *testing.T) {
t.Parallel()
// Create a dependency-aware parser that should never be called.
compiler := Compiler{
Resolver: ResolverFunc(func(f string) (SearchResult, error) {
switch f {
case "test.proto":
return SearchResult{Source: strings.NewReader(`syntax = "proto3";`)}, nil
case descriptorProtoPath:
// used to see if resolver provides custom descriptor.proto
return SearchResult{}, os.ErrNotExist
default:
// no other name should be passed to resolver
t.Errorf("resolver was called for unexpected filename %q", f)
return SearchResult{}, os.ErrNotExist
}
}),
}
_, err := compiler.Compile(ctx, "test.proto")
require.NoError(t, err)
})
}
func findAndLink(t *testing.T, filename string, fdset *descriptorpb.FileDescriptorSet, soFar *protoregistry.Files) (protoreflect.FileDescriptor, *descriptorpb.FileDescriptorProto) {
for _, fd := range fdset.File {
if fd.GetName() == filename {
if soFar == nil {
soFar = &protoregistry.Files{}
}
for _, dep := range fd.GetDependency() {
depDesc, _ := findAndLink(t, dep, fdset, soFar)
err := soFar.RegisterFile(depDesc)
require.NoError(t, err)
}
desc, err := protodesc.NewFile(fd, soFar)
require.NoError(t, err)
return desc, fd
}
}
assert.FailNowf(t, "findAndLink", "could not find dependency %q in proto set", filename)
return nil, nil // make compiler happy
}
func TestDataRace(t *testing.T) {
t.Parallel()
if !internal.IsRace {
t.Skip("only useful when race detector enabled")
return
}
data, err := os.ReadFile("./internal/testdata/desc_test_complex.proto")
require.NoError(t, err)
ast, err := parser.Parse("desc_test_complex.proto", bytes.NewReader(data), reporter.NewHandler(nil))
require.NoError(t, err)
parseResult, err := parser.ResultFromAST(ast, true, reporter.NewHandler(nil))
require.NoError(t, err)
// let's also produce a resolved proto
files, err := (&Compiler{
Resolver: WithStandardImports(&SourceResolver{
ImportPaths: []string{"./internal/testdata"},
}),
SourceInfoMode: SourceInfoStandard,
}).Compile(t.Context(), "desc_test_complex.proto")
require.NoError(t, err)
resolvedProto := files[0].(linker.Result).FileDescriptorProto() //nolint:errcheck
descriptor, err := protoregistry.GlobalFiles.FindFileByPath(descriptorProtoPath)
require.NoError(t, err)
descriptorProto := protodesc.ToFileDescriptorProto(descriptor)
// We will share this descriptor/parse result (which needs to be modified by the linker
// to resolve all references) from multiple concurrent operations to make sure the race
// detector is not triggered.
testCases := []struct {
name string
resolver Resolver
}{
{
name: "share unresolved descriptor",
resolver: WithStandardImports(ResolverFunc(func(name string) (SearchResult, error) {
if name == "desc_test_complex.proto" {
return SearchResult{
Proto: parseResult.FileDescriptorProto(),
}, nil
}
return SearchResult{}, os.ErrNotExist
})),
},
{
name: "share resolved descriptor",
resolver: WithStandardImports(ResolverFunc(func(name string) (SearchResult, error) {
if name == "desc_test_complex.proto" {
return SearchResult{
Proto: resolvedProto,
}, nil
}
return SearchResult{}, os.ErrNotExist
})),
},
{
name: "share unresolved parse result",
resolver: WithStandardImports(ResolverFunc(func(name string) (SearchResult, error) {
if name == "desc_test_complex.proto" {
return SearchResult{
ParseResult: parseResult,
}, nil
}
return SearchResult{}, os.ErrNotExist
})),
},
{
name: "share google/protobuf/descriptor.proto",
resolver: WithStandardImports(ResolverFunc(func(name string) (SearchResult, error) {
// we'll parse our test proto from source, but its implicit dep on
// descriptor.proto will use a
switch name {
case "desc_test_complex.proto":
return SearchResult{
Source: bytes.NewReader(data),
}, nil
case "google/protobuf/descriptor.proto":
return SearchResult{
Proto: descriptorProto,
}, nil
default:
return SearchResult{}, os.ErrNotExist
}
})),
},
}
for i := range testCases {
testCase := testCases[i]
t.Run(testCase.name, func(t *testing.T) {
t.Parallel()
compiler1 := &Compiler{
Resolver: testCase.resolver,
SourceInfoMode: SourceInfoStandard,
}
compiler2 := &Compiler{
Resolver: testCase.resolver,
SourceInfoMode: SourceInfoStandard,
}
grp, ctx := errgroup.WithContext(t.Context())
grp.Go(func() error {
_, err := compiler1.Compile(ctx, "desc_test_complex.proto")
return err
})
grp.Go(func() error {
_, err := compiler2.Compile(ctx, "desc_test_complex.proto")
return err
})
err := grp.Wait()
if panicErr := new(PanicError); errors.As(err, panicErr) {
t.Log(panicErr.Stack)
}
require.NoError(t, err)
})
}
}
func TestPanicHandling(t *testing.T) {
t.Parallel()
c := Compiler{
Resolver: ResolverFunc(func(string) (SearchResult, error) {
panic(errors.New("mui mui bad"))
}),
}
_, err := c.Compile(t.Context(), "test.proto")
panicErr, ok := err.(PanicError)
require.True(t, ok)
t.Logf("%v\n\n%v", panicErr, panicErr.Stack)
}
func TestDescriptorProtoPath(t *testing.T) {
t.Parallel()
// sanity check our constant
path := (*descriptorpb.FileDescriptorProto)(nil).ProtoReflect().Descriptor().ParentFile().Path()
require.Equal(t, descriptorProtoPath, path)
}