go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/proto/matcher.go (about)

     1  // Copyright 2020 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package proto
    16  
    17  import (
    18  	"github.com/golang/mock/gomock"
    19  	"google.golang.org/protobuf/encoding/prototext"
    20  	"google.golang.org/protobuf/proto"
    21  )
    22  
    23  type matcherEq struct {
    24  	expected proto.Message
    25  }
    26  
    27  var _ gomock.Matcher = (*matcherEq)(nil)
    28  
    29  // MatcherEqual returns a matcher that matches on protobuf equality.
    30  // Note: reflect.DeepEqual can't be used with protobuf messages as it may yield
    31  // unexpected results.
    32  func MatcherEqual(m proto.Message) gomock.Matcher {
    33  	return &matcherEq{
    34  		expected: m,
    35  	}
    36  }
    37  
    38  // Matches returns true if x is proto message and if it matches expected
    39  // message.
    40  func (m *matcherEq) Matches(x any) bool {
    41  	message, ok := x.(proto.Message)
    42  	if !ok {
    43  		return false
    44  	}
    45  	return proto.Equal(m.expected, message)
    46  }
    47  
    48  // String returns string representation of expected message.
    49  func (m *matcherEq) String() string {
    50  	return prototext.Format(m.expected)
    51  }