Skip to content

Commit

Permalink
Basic testing
Browse files Browse the repository at this point in the history
  • Loading branch information
bufdev committed Mar 4, 2024
1 parent f223137 commit a87d344
Show file tree
Hide file tree
Showing 6 changed files with 188 additions and 13 deletions.
13 changes: 12 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,15 @@ module github.com/bufbuild/protoplugin

go 1.21

require google.golang.org/protobuf v1.32.0
require (
github.com/bufbuild/protocompile v0.8.0
github.com/stretchr/testify v1.9.0
google.golang.org/protobuf v1.32.0
)

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
golang.org/x/sync v0.5.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
20 changes: 16 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,6 +1,18 @@
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
github.com/bufbuild/protocompile v0.8.0 h1:9Kp1q6OkS9L4nM3FYbr8vlJnEwtbpDPQlQOVXfR+78s=
github.com/bufbuild/protocompile v0.8.0/go.mod h1:+Etjg4guZoAqzVk2czwEQP12yaxLJ8DxuqCJ9qHdH94=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE=
golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
google.golang.org/protobuf v1.32.0 h1:pPC6BG5ex8PDFnkbrGU3EixyhKcQ2aDuBS36lqK/C7I=
google.golang.org/protobuf v1.32.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
3 changes: 3 additions & 0 deletions protoplugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ func Run(
) error {
// We don't use args yet, but reserving it for future use in case we want to implement automatic handling of a version flag.
_ = args
if stderr == nil {
stderr = io.Discard
}

runOptions := newRunOptions()
for _, option := range options {
Expand Down
147 changes: 147 additions & 0 deletions protoplugin_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
// Copyright 2024 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 protoplugin

import (
"bytes"
"context"
"io"
"io/fs"
"sort"
"strings"
"testing"

"github.com/bufbuild/protocompile"
"github.com/bufbuild/protocompile/protoutil"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/descriptorpb"
"google.golang.org/protobuf/types/pluginpb"
)

func TestBasic(t *testing.T) {
t.Parallel()

testBasic(
t,
[]string{
"a.proto",
},
map[string][]byte{
"a.proto": []byte(`syntax = "proto3"; package foo; message A1 {} message A2 {}`),
"b.proto": []byte(`syntax = "proto3"; package foo; message B {}`),
},
HandlerFunc(
func(
ctx context.Context,
responseWriter *ResponseWriter,
request *Request,
) error {
fileDescriptorProtos, err := request.GenerateFileDescriptorProtos()
if err != nil {
return err
}
for _, fileDescriptorProto := range fileDescriptorProtos {
topLevelMessageNames := make([]string, len(fileDescriptorProto.GetMessageType()))
for i, descriptorProto := range fileDescriptorProto.GetMessageType() {
topLevelMessageNames[i] = descriptorProto.GetName()
}
responseWriter.AddFile(
fileDescriptorProto.GetName()+".txt",
strings.Join(topLevelMessageNames, "\n")+"\n",
)
}
return nil
},
),
map[string]string{
"a.proto.txt": "A1\nA2\n",
},
)
}

func testBasic(

Check failure on line 75 in protoplugin_test.go

View workflow job for this annotation

GitHub Actions / ci (1.22.x)

test helper function should start from t.Helper() (thelper)
t *testing.T,
fileToGenerate []string,
pathToData map[string][]byte,
handler Handler,
expectedPathToContent map[string]string,
) {
ctx := context.Background()

fileDescriptorProtos, err := compile(ctx, pathToData)
require.NoError(t, err)

codeGeneratorRequest := &pluginpb.CodeGeneratorRequest{
FileToGenerate: fileToGenerate,
ProtoFile: fileDescriptorProtos,
}
codeGeneratorRequestData, err := proto.Marshal(codeGeneratorRequest)
require.NoError(t, err)

stdin := bytes.NewReader(codeGeneratorRequestData)
stdout := bytes.NewBuffer(nil)

err = Run(
ctx,
nil,
stdin,
stdout,
nil,
handler,
)
require.NoError(t, err)

codeGeneratorResponse := &pluginpb.CodeGeneratorResponse{}
err = proto.Unmarshal(stdout.Bytes(), codeGeneratorResponse)
require.NoError(t, err)
require.Nil(t, codeGeneratorResponse.Error)

Check failure on line 110 in protoplugin_test.go

View workflow job for this annotation

GitHub Actions / ci (1.22.x)

avoid direct access to proto field codeGeneratorResponse.Error, use codeGeneratorResponse.GetError() instead (protogetter)

pathToContent := make(map[string]string)
for _, file := range codeGeneratorResponse.File {

Check failure on line 113 in protoplugin_test.go

View workflow job for this annotation

GitHub Actions / ci (1.22.x)

avoid direct access to proto field codeGeneratorResponse.File, use codeGeneratorResponse.GetFile() instead (protogetter)
require.NotEmpty(t, file.GetName())
pathToContent[file.GetName()] = file.GetContent()
}

require.Equal(t, expectedPathToContent, pathToContent)
}

func compile(ctx context.Context, pathToData map[string][]byte) ([]*descriptorpb.FileDescriptorProto, error) {
compiler := protocompile.Compiler{
Resolver: &protocompile.SourceResolver{
Accessor: func(path string) (io.ReadCloser, error) {
data, ok := pathToData[path]
if !ok {
return nil, &fs.PathError{Op: "read", Path: path, Err: fs.ErrNotExist}
}
return io.NopCloser(bytes.NewReader(data)), nil
},
},
}
paths := make([]string, 0, len(pathToData))
for path := range pathToData {
paths = append(paths, path)
}
sort.Strings(paths)
files, err := compiler.Compile(ctx, paths...)
if err != nil {
return nil, err
}
fileDescriptorProtos := make([]*descriptorpb.FileDescriptorProto, len(files))
for i, file := range files {
fileDescriptorProtos[i] = protoutil.ProtoFromFileDescriptor(file)
}
return fileDescriptorProtos, nil
}
2 changes: 1 addition & 1 deletion response_writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ func (r *ResponseWriter) toCodeGeneratorResponse() (*pluginpb.CodeGeneratorRespo
r.lock.RLock()
defer r.lock.RUnlock()

if r.responseSupportedFeatures&uint64(pluginpb.CodeGeneratorResponse_FEATURE_SUPPORTS_EDITIONS) == 0 {
if r.responseSupportedFeatures&uint64(pluginpb.CodeGeneratorResponse_FEATURE_SUPPORTS_EDITIONS) != 0 {
if r.responseMinimumEdition == 0 {
r.addSystemError(
errors.New("CodeGeneratorResponse: FEATURE_SUPPORTS_EDITIONS specified but no minimum_edition set"),
Expand Down
16 changes: 9 additions & 7 deletions validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,15 @@ func validateCodeGeneratorRequest(request *pluginpb.CodeGeneratorRequest) error
); err != nil {
return err
}
if err := validateCodeGeneratorRequestFileDescriptorProtos(
"source_file_descriptors",
request.GetSourceFileDescriptors(),
request.GetFileToGenerate(),
true,
); err != nil {
return err
if len(request.GetSourceFileDescriptors()) > 0 {
if err := validateCodeGeneratorRequestFileDescriptorProtos(
"source_file_descriptors",
request.GetSourceFileDescriptors(),
request.GetFileToGenerate(),
true,
); err != nil {
return err
}
}
if version := request.GetCompilerVersion(); version != nil {
if major := version.GetMajor(); major < 0 {
Expand Down

0 comments on commit a87d344

Please sign in to comment.