From: Adam Simpkins Date: Fri, 10 Mar 2017 01:54:21 +0000 (-0800) Subject: teach gtest how to pretty-print StringPiece values X-Git-Tag: v2017.03.13.00~7 X-Git-Url: http://plrg.eecs.uci.edu/git/?a=commitdiff_plain;h=499cf208b86085e7b870843e7e4a2e26c13c1a68;p=folly.git teach gtest how to pretty-print StringPiece values 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 --- diff --git a/folly/test/TestUtils.h b/folly/test/TestUtils.h index a6642f92..6e3bcb2a 100644 --- a/folly/test/TestUtils.h +++ b/folly/test/TestUtils.h @@ -18,6 +18,7 @@ #include +#include #include // 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()); +} }