From: Tom Jackson Date: Thu, 21 Jan 2016 22:19:37 +0000 (-0800) Subject: Add PrintTo for dynamic X-Git-Tag: deprecate-dynamic-initializer~145 X-Git-Url: http://demsky.eecs.uci.edu/git/?a=commitdiff_plain;h=e202187f468b692b5d352142a81a5ce0229b7e8a;p=folly.git Add PrintTo for dynamic Summary: Making `EXPECT_EQ(dyn1, dyn2)` easier to debug Reviewed By: luciang, ot, yfeldblum Differential Revision: D2848318 fb-gh-sync-id: 0c7cdd292665a493f2b792798df4e6966c1f28db --- diff --git a/folly/json.cpp b/folly/json.cpp index 63fa2ba0..438cdf2e 100644 --- a/folly/json.cpp +++ b/folly/json.cpp @@ -833,6 +833,15 @@ void dynamic::print_as_pseudo_json(std::ostream& out) const { out << json::serialize(*this, opts); } +void PrintTo(const dynamic& dyn, std::ostream* os) { + json::serialization_opts opts; + opts.allow_nan_inf = true; + opts.allow_non_string_keys = true; + opts.pretty_formatting = true; + opts.sort_keys = true; + *os << json::serialize(dyn, opts); +} + ////////////////////////////////////////////////////////////////////// } diff --git a/folly/json.h b/folly/json.h index ead3afd0..3d229f3f 100644 --- a/folly/json.h +++ b/folly/json.h @@ -41,6 +41,8 @@ #ifndef FOLLY_JSON_H_ #define FOLLY_JSON_H_ +#include + #include #include #include @@ -158,6 +160,11 @@ fbstring toJson(dynamic const&); */ fbstring toPrettyJson(dynamic const&); +/* + * Printer for GTest. + * Uppercase name to fill GTest's API, which calls this method through ADL. + */ +void PrintTo(const dynamic&, std::ostream*); ////////////////////////////////////////////////////////////////////// } diff --git a/folly/test/JsonTest.cpp b/folly/test/JsonTest.cpp index d514e8f3..74838a03 100644 --- a/folly/test/JsonTest.cpp +++ b/folly/test/JsonTest.cpp @@ -13,13 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include +#include +#include #include - -#include #include -#include -#include +#include using folly::dynamic; using folly::parseJson; @@ -465,6 +465,63 @@ TEST(Json, SortKeys) { EXPECT_EQ(sorted_keys, folly::json::serialize(value, opts_on)); } +TEST(Json, PrintTo) { + std::ostrstream oss; + + dynamic value = dynamic::object + ("foo", "bar") + ("junk", 12) + ("another", 32.2) + (true, false) // include non-string keys + (false, true) + (2, 3) + (0, 1) + (1, 2) + (1.5, 2.25) + (0.5, 0.25) + (0, 1) + (1, 2) + ("a", + { + dynamic::object("a", "b") + ("c", "d"), + 12.5, + "Yo Dawg", + { "heh" }, + nullptr + } + ) + ; + + std::string expected = + R"({ + false : true, + true : false, + 0.5 : 0.25, + 1.5 : 2.25, + 0 : 1, + 1 : 2, + 2 : 3, + "a" : [ + { + "a" : "b", + "c" : "d" + }, + 12.5, + "Yo Dawg", + [ + "heh" + ], + null + ], + "another" : 32.2, + "foo" : "bar", + "junk" : 12 +})"; + PrintTo(value, &oss); + EXPECT_EQ(expected, oss.str()); +} + int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); gflags::ParseCommandLineFlags(&argc, &argv, true);