test_rtti.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #include <typeinfo>
  2. #include "unity.h"
  3. #ifdef CONFIG_COMPILER_CXX_RTTI
  4. using namespace std;
  5. class Base {
  6. public:
  7. virtual ~Base() {} ;
  8. virtual char name() = 0;
  9. };
  10. class DerivedA : public Base {
  11. public:
  12. char name() override
  13. {
  14. return 'A';
  15. }
  16. };
  17. class DerivedB : public Base {
  18. public:
  19. char name() override
  20. {
  21. return 'B';
  22. }
  23. };
  24. TEST_CASE("unsuccessful dynamic cast on pointer returns nullptr", "[cxx]")
  25. {
  26. Base *base = new DerivedA();
  27. DerivedB *derived = dynamic_cast<DerivedB*>(base);
  28. TEST_ASSERT_EQUAL(derived, nullptr);
  29. delete base;
  30. derived = nullptr;
  31. }
  32. TEST_CASE("dynamic cast works", "[cxx]")
  33. {
  34. Base *base = new DerivedA();
  35. DerivedA *derived = dynamic_cast<DerivedA*>(base);
  36. TEST_ASSERT_EQUAL(derived, base);
  37. delete base;
  38. }
  39. TEST_CASE("typeid of dynamic objects works", "[cxx]")
  40. {
  41. Base *base = new DerivedA();
  42. DerivedA *derived = dynamic_cast<DerivedA*>(base);
  43. TEST_ASSERT_EQUAL(typeid(*derived).hash_code(), typeid(*base).hash_code());
  44. TEST_ASSERT_EQUAL(typeid(*derived).hash_code(), typeid(DerivedA).hash_code());
  45. delete base;
  46. derived = nullptr;
  47. }
  48. int dummy_function1(int arg1, double arg2);
  49. int dummy_function2(int arg1, double arg2);
  50. TEST_CASE("typeid of function works", "[cxx]")
  51. {
  52. TEST_ASSERT_EQUAL(typeid(dummy_function1).hash_code(), typeid(dummy_function2).hash_code());
  53. }
  54. #ifdef CONFIG_COMPILER_CXX_EXCEPTIONS
  55. TEST_CASE("unsuccessful dynamic cast on reference throws exception", "[cxx]")
  56. {
  57. bool thrown = false;
  58. DerivedA derived_a;
  59. Base &base = derived_a;
  60. try {
  61. DerivedB &derived_b = dynamic_cast<DerivedB&>(base);
  62. derived_b.name(); // suppress warning
  63. } catch (bad_cast &e) {
  64. thrown = true;
  65. }
  66. TEST_ASSERT(thrown);
  67. }
  68. TEST_CASE("typeid on nullptr throws bad_typeid", "[cxx]")
  69. {
  70. Base *base = nullptr;
  71. size_t hash = 0;
  72. bool thrown = false;
  73. try {
  74. hash = typeid(*base).hash_code();
  75. } catch (bad_typeid &e) {
  76. thrown = true;
  77. }
  78. TEST_ASSERT_EQUAL(0, hash);
  79. TEST_ASSERT(thrown);
  80. }
  81. #endif // CONFIG_COMPILER_CXX_EXCEPTIONS
  82. #endif // CONFIG_COMPILER_CXX_RTTI