From fe8a168161a3b4c1bbd2d8d916c510cfe4711cbd Mon Sep 17 00:00:00 2001 From: Sam McCall Date: Wed, 28 Jun 2023 01:13:52 +0200 Subject: [PATCH] [unittest] teach gTest to print entries of DenseMap as pairs When an assertion like the following fails: EXPECT_THAT(map, ElementsAre(Pair("p", "nullable")))); Error message before: Actual: { 40-byte object } After: Actual: { ("p", "nonnull") } It is not ideal that we need to refer directly to DenseMapPair inside the internal namespace, but I believe the practical maintenance risk is low. This change is covered by DenseMap's unittests, as we've covered SmallString etc in the past. Differential Revision: https://reviews.llvm.org/D153930 --- llvm/unittests/ADT/DenseMapTest.cpp | 9 +++++++++ .../include/gtest/internal/custom/gtest-printers.h | 12 ++++++++++++ 2 files changed, 21 insertions(+) diff --git a/llvm/unittests/ADT/DenseMapTest.cpp b/llvm/unittests/ADT/DenseMapTest.cpp index 94764a83024c..cc3244528f27 100644 --- a/llvm/unittests/ADT/DenseMapTest.cpp +++ b/llvm/unittests/ADT/DenseMapTest.cpp @@ -9,6 +9,7 @@ #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DenseMapInfo.h" #include "llvm/ADT/DenseMapInfoVariant.h" +#include "llvm/ADT/StringRef.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include @@ -756,4 +757,12 @@ TEST(DenseMapCustomTest, VariantSupport) { // operator==. EXPECT_FALSE(DenseMapInfo::isEqual(Keys[2], Keys[2])); } + +// Test that gTest prints map entries as pairs instead of opaque objects. +// See third-party/unittest/googletest/internal/custom/gtest-printers.h +TEST(DenseMapCustomTest, PairPrinting) { + DenseMap Map = {{1, "one"}, {2, "two"}}; + EXPECT_EQ(R"({ (1, "one"), (2, "two") })", ::testing::PrintToString(Map)); +} + } // namespace diff --git a/third-party/unittest/googletest/include/gtest/internal/custom/gtest-printers.h b/third-party/unittest/googletest/include/gtest/internal/custom/gtest-printers.h index b7320920061c..f27922104bef 100644 --- a/third-party/unittest/googletest/include/gtest/internal/custom/gtest-printers.h +++ b/third-party/unittest/googletest/include/gtest/internal/custom/gtest-printers.h @@ -40,6 +40,7 @@ #define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_ #if !GTEST_NO_LLVM_SUPPORT +#include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringRef.h" #include @@ -63,6 +64,17 @@ inline void PrintTo(const SmallString &S, std::ostream *OS) { inline void PrintTo(const SmallVectorImpl &S, std::ostream *OS) { *OS << ::testing::PrintToString(std::string(S.data(), S.size())); } + +// DenseMap's entries inherit from std::pair, and should act like pairs. +// However gTest's provided `PrintTo(pair)` template won't deduce K and V +// because of the needed derived-to-base conversion. +namespace detail { +template +inline void PrintTo(const DenseMapPair &Pair, std::ostream *OS) { + *OS << ::testing::PrintToString(static_cast &>(Pair)); +} +} // namespace detail + } // namespace llvm #endif // !GTEST_NO_LLVM_SUPPORT