Commit e202187f authored by Tom Jackson's avatar Tom Jackson Committed by facebook-github-bot-0

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
parent 31260110
......@@ -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);
}
//////////////////////////////////////////////////////////////////////
}
......@@ -41,6 +41,8 @@
#ifndef FOLLY_JSON_H_
#define FOLLY_JSON_H_
#include <iosfwd>
#include <folly/dynamic.h>
#include <folly/FBString.h>
#include <folly/Range.h>
......@@ -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*);
//////////////////////////////////////////////////////////////////////
}
......
......@@ -13,13 +13,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <limits>
#include <strstream>
#include <boost/next_prior.hpp>
#include <folly/json.h>
#include <gtest/gtest.h>
#include <gflags/gflags.h>
#include <limits>
#include <boost/next_prior.hpp>
#include <gtest/gtest.h>
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);
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment