teach gtest how to pretty-print StringPiece values
authorAdam Simpkins <simpkins@fb.com>
Fri, 10 Mar 2017 01:54:21 +0000 (17:54 -0800)
committerFacebook Github Bot <facebook-github-bot@users.noreply.github.com>
Fri, 10 Mar 2017 02:05:17 +0000 (18:05 -0800)
Summary:
Even though an ostream operator<<() is defined for StringPiece, gtest doesn't
use it when printing StringPiece values in test failure messages.  Because
StringPiece defines a nested iterator type gtest instead treats StringPiece as
a container, and prints each of its elements (characters) one-by-one.  This is
fairly awkward to read.

This diff defines an explicit PrintTo() function for StringPiece in
folly/test/TestUtils.h.  This makes gtest print StringPiece values nicely if
you include TestUtils.h in your test sources.

Reviewed By: yfeldblum

Differential Revision: D4672257

fbshipit-source-id: 4b39ccc116e5382c29c37c2abe879293d310faf5

folly/test/TestUtils.h

index a6642f926f905530f2ff08f7bd08c11dc8584fbb..6e3bcb2a1111479ee08e16d9076cab9eb5588310 100644 (file)
@@ -18,6 +18,7 @@
 
 #include <chrono>
 
+#include <folly/Range.h>
 #include <folly/portability/GTest.h>
 
 // We use this to indicate that tests have failed because of timing
@@ -45,4 +46,16 @@ AreWithinSecs(T1 val1, T2 val2, std::chrono::seconds acceptableDeltaSecs) {
   }
 }
 }
+
+// Define a PrintTo() function for StringPiece, so that gtest checks
+// will print it as a string.  Without this gtest identifies StringPiece as a
+// container type, and therefore tries printing its elements individually,
+// despite the fact that there is an ostream operator<<() defined for
+// StringPiece.
+inline void PrintTo(StringPiece sp, ::std::ostream* os) {
+  // gtest's PrintToString() function will quote the string and escape internal
+  // quotes and non-printable characters, the same way gtest does for the
+  // standard string types.
+  *os << ::testing::PrintToString(sp.str());
+}
 }