From 1aab2d97691d77cfc97bc8cb3b0f2e659105f3e6 Mon Sep 17 00:00:00 2001 From: Drew Sirenko <68304519+AndrewSirenko@users.noreply.github.com> Date: Thu, 22 Aug 2024 16:06:01 -0400 Subject: [PATCH] Add Protobuf Matcher --- go.mod | 2 +- utils/protobuf_matcher.go | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 utils/protobuf_matcher.go diff --git a/go.mod b/go.mod index c313a8a7..eb01ef69 100644 --- a/go.mod +++ b/go.mod @@ -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 ) @@ -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 ) diff --git a/utils/protobuf_matcher.go b/utils/protobuf_matcher.go new file mode 100644 index 00000000..5a2a7016 --- /dev/null +++ b/utils/protobuf_matcher.go @@ -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) +}