| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- //
- // json_binder_polymorphic.t.h
- // json
- //
- // Created by Sam Jaffe on 11/14/18.
- // Copyright © 2018 Sam Jaffe. All rights reserved.
- //
- #pragma once
- #include <cxxtest/TestSuite.h>
- #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<Left> GetLeftBinder() {
- return object_binder<Left>()
- ("a", &Left::a);
- }
- object_binder<Right> GetRightBinder() {
- return object_binder<Right>()
- ("a", &Right::a);
- }
- using pBase = std::unique_ptr<Base>;
- polymorphic_binder<pBase> GetBinder() {
- return polymorphic_binder<pBase>()
- ("Left", GetLeftBinder())
- ("Right", GetRightBinder());
- }
- polymorphic_binder<pBase> & Get() {
- static polymorphic_binder<pBase> _ = 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<Left*>(&*out));
- TS_ASSERT_EQUALS(dynamic_cast<Left&>(*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<Right*>(&*out));
- TS_ASSERT_EQUALS(dynamic_cast<Right&>(*out), expected);
- }
- };
|