Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Protobuf Matcher utility #553

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ require (
github.com/onsi/ginkgo/v2 v2.13.1
github.com/onsi/gomega v1.30.0
google.golang.org/grpc v1.65.0
google.golang.org/protobuf v1.34.1
gopkg.in/yaml.v2 v2.4.0
k8s.io/klog/v2 v2.130.1
)
Expand All @@ -24,6 +25,5 @@ require (
golang.org/x/text v0.15.0 // indirect
golang.org/x/tools v0.14.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240528184218-531527333157 // indirect
google.golang.org/protobuf v1.34.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
33 changes: 33 additions & 0 deletions utils/protobuf_matcher.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package utils

import (
"github.com/golang/mock/gomock"
"google.golang.org/protobuf/encoding/prototext"
"google.golang.org/protobuf/proto"
)

// Protobuf returns a Matcher that relies upon proto.Equal to compare Protobuf messages
// Example usage with mocked request:
//
// example.EXPECT().ExampleRequest(Protobuf(requestMsg)).Return(responseMsg, nil).AnyTimes()
func Protobuf(msg proto.Message) gomock.Matcher {
return &ProtobufMatcher{msg}
}

type ProtobufMatcher struct {
msg proto.Message
}

var _ gomock.Matcher = &ProtobufMatcher{}

func (p *ProtobufMatcher) Matches(x interface{}) bool {
otherMsg, ok := x.(proto.Message)
if !ok {
return false
}
return proto.Equal(p.msg, otherMsg)
}

func (p *ProtobufMatcher) String() string {
return prototext.Format(p.msg)
}