json_binder_polymorphic.t.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. //
  2. // json_binder_polymorphic.t.h
  3. // json
  4. //
  5. // Created by Sam Jaffe on 11/14/18.
  6. // Copyright © 2018 Sam Jaffe. All rights reserved.
  7. //
  8. #pragma once
  9. #include <cxxtest/TestSuite.h>
  10. #include "json/json_binder.hpp"
  11. struct Base {
  12. virtual ~Base() = default;
  13. virtual void run() const = 0;
  14. };
  15. struct Left : public Base {
  16. int a;
  17. void run() const override {}
  18. };
  19. struct Right : public Base {
  20. std::string a;
  21. void run() const override {}
  22. };
  23. bool operator==(Left const & lhs, Left const & rhs) {
  24. return lhs.a == rhs.a;
  25. }
  26. bool operator==(Right const & lhs, Right const & rhs) {
  27. return lhs.a == rhs.a;
  28. }
  29. using namespace json;
  30. using namespace json::binder;
  31. object_binder<Left> GetLeftBinder() {
  32. return object_binder<Left>()
  33. ("a", &Left::a);
  34. }
  35. object_binder<Right> GetRightBinder() {
  36. return object_binder<Right>()
  37. ("a", &Right::a);
  38. }
  39. using pBase = std::unique_ptr<Base>;
  40. polymorphic_binder<pBase> GetBinder() {
  41. return polymorphic_binder<pBase>()
  42. ("Left", GetLeftBinder())
  43. ("Right", GetRightBinder());
  44. }
  45. polymorphic_binder<pBase> & Get() {
  46. static polymorphic_binder<pBase> _ = GetBinder();
  47. return _;
  48. }
  49. using namespace json::parser;
  50. class json_binder_polymorphic_TestSuite : public CxxTest::TestSuite {
  51. public:
  52. void testCanHitLeftPolymorph() {
  53. char data[] = "{\"@id\":\"Left\", \"@value\":{\"a\":1}}";
  54. pBase out;
  55. Left expected; expected.a = 1;
  56. TS_ASSERT_THROWS_NOTHING(parse(json::binder::bind(out, Get()), data));
  57. TS_ASSERT_DIFFERS(&*out, nullptr);
  58. TS_ASSERT(dynamic_cast<Left*>(&*out));
  59. TS_ASSERT_EQUALS(dynamic_cast<Left&>(*out), expected);
  60. }
  61. void testCanHitRightPolymorph() {
  62. char data[] = "{\"@id\":\"Right\", \"@value\":{\"a\":\"hello\"}}";
  63. pBase out;
  64. Right expected; expected.a = "hello";
  65. TS_ASSERT_THROWS_NOTHING(parse(json::binder::bind(out, Get()), data));
  66. TS_ASSERT_DIFFERS(&*out, nullptr);
  67. TS_ASSERT(dynamic_cast<Right*>(&*out));
  68. TS_ASSERT_EQUALS(dynamic_cast<Right&>(*out), expected);
  69. }
  70. };