blob: 5059958c065878885d3003c926dcdcb62831061c [file] [log] [blame]
Sam McCall0cdc04a2023-06-27 03:33:00 -07001// Part of the Crubit project, under the Apache License v2.0 with LLVM
2// Exceptions. See /LICENSE for license information.
3// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
4
5#include "nullability/proto_matchers.h"
6
Dmitri Gribenko742c4c32023-07-31 12:32:09 -07007#include <memory>
8#include <ostream>
9#include <string>
10
Googlerf7154ea2023-12-11 09:30:25 -080011#include "absl/base/nullability.h"
Dmitri Gribenko742c4c32023-07-31 12:32:09 -070012#include "llvm/ADT/StringRef.h"
Sam McCall0cdc04a2023-06-27 03:33:00 -070013#include "third_party/llvm/llvm-project/third-party/unittest/googlemock/include/gmock/gmock.h"
Dmitri Gribenko742c4c32023-07-31 12:32:09 -070014#include "third_party/protobuf/message.h"
Sam McCall0cdc04a2023-06-27 03:33:00 -070015#include "third_party/protobuf/text_format.h"
16
17namespace clang::tidy::nullability {
18namespace {
19
20class EqualsProtoMatcher
21 : public testing::MatcherInterface<const proto2::Message &> {
22 std::string Expected;
23
24 public:
25 EqualsProtoMatcher(llvm::StringRef Expected) : Expected(Expected) {}
26
Googlerf7154ea2023-12-11 09:30:25 -080027 bool MatchAndExplain(
28 const proto2::Message &M,
29 absl::Nonnull<testing::MatchResultListener *> Listener) const override {
Sam McCall0cdc04a2023-06-27 03:33:00 -070030 std::unique_ptr<proto2::Message> Parsed(M.New());
31 if (!proto2::TextFormat::ParseFromString(Expected, Parsed.get())) {
32 *Listener << "where <<<\n"
33 << Expected << "\n>>> doesn't parse as " << M.GetTypeName();
34 return false;
35 }
36 // Compare textual representations.
37 std::string PrintedExpected, PrintedActual;
38 if (!proto2::TextFormat::PrintToString(*Parsed, &PrintedExpected)) {
39 *Listener << "where expected message failed to print!";
40 return false;
41 }
42 if (!proto2::TextFormat::PrintToString(M, &PrintedActual)) {
43 *Listener << "where actual message failed to print!";
44 return false;
45 }
46 return testing::ExplainMatchResult(PrintedExpected, PrintedActual,
47 Listener);
48 }
49
Googlerf7154ea2023-12-11 09:30:25 -080050 void DescribeTo(absl::Nonnull<std::ostream *> OS) const override {
Sam McCall0cdc04a2023-06-27 03:33:00 -070051 *OS << "equals proto <<<\n" << Expected << "\n>>>";
52 }
53};
54
55} // namespace
56
57testing::Matcher<const proto2::Message &> EqualsProto(llvm::StringRef Textual) {
58 return testing::MakeMatcher(new EqualsProtoMatcher(Textual));
59}
60
61} // namespace clang::tidy::nullability