From f70f34ae6efe4fcd1d1e7be52582b44ce59afb86 Mon Sep 17 00:00:00 2001 From: Shane Grant Date: Mon, 8 Jul 2013 10:29:41 -0700 Subject: [PATCH] added polymorphic unit test --- unittests.cpp | 109 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) diff --git a/unittests.cpp b/unittests.cpp index 4500fcfc..0965c4d5 100644 --- a/unittests.cpp +++ b/unittests.cpp @@ -2389,3 +2389,112 @@ BOOST_AUTO_TEST_CASE( xml_structs_specialized ) test_structs_specialized(); } +// ###################################################################### +struct PolyBase +{ + PolyBase() = default; + PolyBase( int xx, float yy ) : x(xx), y(yy) {} + int x; + float y; + + template + void serialize( Archive & ar ) + { + ar( x, y ); + } + + virtual void foo() = 0; + + bool operator==( PolyBase const & other ) const + { + return x == other.x && y == other.y; + } +}; + +struct PolyDerived : PolyBase +{ + PolyDerived() = default; + PolyDerived( int xx, float yy, bool aa, double bb ) : + PolyBase( xx, yy ), a(aa), b(bb) {} + + bool a; + double b; + + template + void serialize( Archive & ar ) + { + ar( cereal::base_class( this ), + a, b ); + } + + bool operator==( PolyDerived const & other ) const + { + return PolyBase::operator==( other ) && a == other.a && b == other.b; + } + + void foo() {} +}; + +std::ostream& operator<<(std::ostream& os, PolyDerived const & s) +{ + os << "[x: " << s.x << " y: " << s.y << " a: " << s.a << " b: " << s.b << "]"; + return os; +} + +CEREAL_REGISTER_TYPE(PolyDerived); + +template +void test_polymorphic() +{ + std::random_device rd; + std::mt19937 gen(rd()); + + auto rngB = [&](){ return random_value( gen ) % 2; }; + auto rngI = [&](){ return random_value( gen ); }; + auto rngF = [&](){ return random_value( gen ); }; + auto rngD = [&](){ return random_value( gen ); }; + + for(int i=0; i<100; ++i) + { + std::shared_ptr o_shared = std::make_shared( rngI(), rngF(), rngB(), rngD() ); + std::weak_ptr o_weak = o_shared; + std::unique_ptr o_unique( new PolyDerived( rngI(), rngF(), rngB(), rngD() ) ); + + std::ostringstream os; + { + OArchive oar(os); + + oar( o_shared, o_weak, o_unique ); + } + + decltype(o_shared) i_shared; + decltype(o_weak) i_weak; + decltype(o_unique) i_unique; + + std::istringstream is(os.str()); + { + IArchive iar(is); + + iar( i_shared, i_weak, i_unique ); + } + + auto i_locked = i_weak.lock(); + auto o_locked = o_weak.lock(); + + BOOST_CHECK_EQUAL(i_shared.get(), i_locked.get()); + BOOST_CHECK_EQUAL(*((PolyDerived*)i_shared.get()), *((PolyDerived*)o_shared.get())); + BOOST_CHECK_EQUAL(*((PolyDerived*)i_shared.get()), *((PolyDerived*)i_locked.get())); + BOOST_CHECK_EQUAL(*((PolyDerived*)i_locked.get()), *((PolyDerived*)o_locked.get())); + BOOST_CHECK_EQUAL(*((PolyDerived*)i_unique.get()), *((PolyDerived*)o_unique.get())); + } +} + +BOOST_AUTO_TEST_CASE( binary_polymorphic ) +{ + test_polymorphic(); +} + +BOOST_AUTO_TEST_CASE( xml_polymorphic ) +{ + test_polymorphic(); +}