1 // Copyright 2023 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef BASE_TEST_PROTOBUF_MATCHERS_H_ 6 #define BASE_TEST_PROTOBUF_MATCHERS_H_ 7 8 #include <string> 9 #include <tuple> 10 11 #include "testing/gmock/include/gmock/gmock-matchers.h" 12 13 namespace base::test { 14 15 // Parses a binary proto and returns a raw TextProto, where all fields are 16 // unnamed. The input must be a valid serialized protobuf message. 17 std::string BinaryProtoToRawTextProto(const std::string& binary_message); 18 19 // Matcher that verifies two protobufs contain the same data. 20 MATCHER_P(EqualsProto, 21 message, 22 "Match a proto Message equal to the matcher's argument.") { 23 std::string expected_serialized; 24 if (!message.SerializeToString(&expected_serialized)) { 25 *result_listener << "Expected proto fails to serialize"; 26 return false; 27 } 28 std::string actual_serialized; 29 if (!arg.SerializeToString(&actual_serialized)) { 30 *result_listener << "Actual proto fails to serialize"; 31 return false; 32 } 33 if (expected_serialized != actual_serialized) { 34 *result_listener << "Provided proto did not match the expected proto" 35 << "\n Expected Raw TextProto:\n" 36 << BinaryProtoToRawTextProto(expected_serialized) 37 << "\n Provided Raw TextProto:\n" 38 << BinaryProtoToRawTextProto(actual_serialized); 39 return false; 40 } 41 return true; 42 } 43 44 // EqualsProto() implementation for 2-tuple matchers. 45 MATCHER(EqualsProto, 46 "Matches if the tuple's proto Message arguments are equal.") { 47 return ::testing::Matcher<decltype(std::get<0>(arg))>( 48 EqualsProto(std::get<1>(arg))) 49 .MatchAndExplain(std::get<0>(arg), result_listener); 50 } 51 52 } // namespace base::test 53 54 #endif // BASE_TEST_PROTOBUF_MATCHERS_H_ 55