blob: 87f02fd3d24fa3e349a3b8d8bc436983b2e37398 [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
11#include "llvm/ADT/StringRef.h"
Sam McCall0cdc04a2023-06-27 03:33:00 -070012#include "third_party/llvm/llvm-project/third-party/unittest/googlemock/include/gmock/gmock.h"
Dmitri Gribenko742c4c32023-07-31 12:32:09 -070013#include "third_party/protobuf/message.h"
Sam McCall0cdc04a2023-06-27 03:33:00 -070014#include "third_party/protobuf/text_format.h"
15
16namespace clang::tidy::nullability {
17namespace {
18
19class EqualsProtoMatcher
20 : public testing::MatcherInterface<const proto2::Message &> {
21 std::string Expected;
22
23 public:
24 EqualsProtoMatcher(llvm::StringRef Expected) : Expected(Expected) {}
25
26 bool MatchAndExplain(const proto2::Message &M,
27 testing::MatchResultListener *Listener) const override {
28 std::unique_ptr<proto2::Message> Parsed(M.New());
29 if (!proto2::TextFormat::ParseFromString(Expected, Parsed.get())) {
30 *Listener << "where <<<\n"
31 << Expected << "\n>>> doesn't parse as " << M.GetTypeName();
32 return false;
33 }
34 // Compare textual representations.
35 std::string PrintedExpected, PrintedActual;
36 if (!proto2::TextFormat::PrintToString(*Parsed, &PrintedExpected)) {
37 *Listener << "where expected message failed to print!";
38 return false;
39 }
40 if (!proto2::TextFormat::PrintToString(M, &PrintedActual)) {
41 *Listener << "where actual message failed to print!";
42 return false;
43 }
44 return testing::ExplainMatchResult(PrintedExpected, PrintedActual,
45 Listener);
46 }
47
48 void DescribeTo(std::ostream *OS) const override {
49 *OS << "equals proto <<<\n" << Expected << "\n>>>";
50 }
51};
52
53} // namespace
54
55testing::Matcher<const proto2::Message &> EqualsProto(llvm::StringRef Textual) {
56 return testing::MakeMatcher(new EqualsProtoMatcher(Textual));
57}
58
59} // namespace clang::tidy::nullability