// // json_binder_polymorphic.t.h // json // // Created by Sam Jaffe on 11/14/18. // Copyright © 2018 Sam Jaffe. All rights reserved. // #pragma once #include #include "json/json_binder.hpp" struct Base { virtual ~Base() = default; virtual void run() const = 0; }; struct Left : public Base { int a; void run() const override {} }; struct Right : public Base { std::string a; void run() const override {} }; bool operator==(Left const & lhs, Left const & rhs) { return lhs.a == rhs.a; } bool operator==(Right const & lhs, Right const & rhs) { return lhs.a == rhs.a; } using namespace json; using namespace json::binder; object_binder GetLeftBinder() { return object_binder() ("a", &Left::a); } object_binder GetRightBinder() { return object_binder() ("a", &Right::a); } using pBase = std::unique_ptr; polymorphic_binder GetBinder() { return polymorphic_binder() ("Left", GetLeftBinder()) ("Right", GetRightBinder()); } polymorphic_binder & Get() { static polymorphic_binder _ = GetBinder(); return _; } using namespace json::parser; class json_binder_polymorphic_TestSuite : public CxxTest::TestSuite { public: void testCanHitLeftPolymorph() { char data[] = "{\"@id\":\"Left\", \"@value\":{\"a\":1}}"; pBase out; Left expected; expected.a = 1; TS_ASSERT_THROWS_NOTHING(parse(json::binder::bind(out, Get()), data)); TS_ASSERT_DIFFERS(&*out, nullptr); TS_ASSERT(dynamic_cast(&*out)); TS_ASSERT_EQUALS(dynamic_cast(*out), expected); } void testCanHitRightPolymorph() { char data[] = "{\"@id\":\"Right\", \"@value\":{\"a\":\"hello\"}}"; pBase out; Right expected; expected.a = "hello"; TS_ASSERT_THROWS_NOTHING(parse(json::binder::bind(out, Get()), data)); TS_ASSERT_DIFFERS(&*out, nullptr); TS_ASSERT(dynamic_cast(&*out)); TS_ASSERT_EQUALS(dynamic_cast(*out), expected); } };