maybe_null_test.cxx 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. //
  2. // maybe_null.t.h
  3. // pointers
  4. //
  5. // Created by Sam Jaffe on 12/2/16.
  6. //
  7. #pragma once
  8. // Define DEBUG in order to obtain certain checks...
  9. #ifndef DEBUG
  10. #define DEBUG
  11. #endif
  12. #include "pointer/maybe_null.hpp"
  13. #include <memory>
  14. #include <gmock/gmock.h>
  15. class maybe_null_TestSuite : public CxxTest::TestSuite {
  16. public:
  17. using ptr_base = std::shared_ptr<int>;
  18. using ptr_t = maybe_null<ptr_base>;
  19. public:
  20. void test_can_hold_nullptr() const {
  21. ptr_t mn{nullptr};
  22. TS_ASSERT_EQUALS(bool(mn), false);
  23. }
  24. void test_is_valid_wo_nullptr() const {
  25. ptr_t mn = make_with(5);
  26. TS_ASSERT_EQUALS(bool(mn), true);
  27. }
  28. void test_nullptr_throws_or_false() const {
  29. ptr_t mn{nullptr};
  30. TS_ASSERT_THROWS(*mn, unchecked_pointer_exception);
  31. }
  32. void test_object_contains_ptr() const {
  33. ptr_base i{new int};
  34. ptr_t n{i};
  35. TS_ASSERT_EQUALS(bool(n), true);
  36. TS_ASSERT_EQUALS(n.get(), i.get());
  37. TS_ASSERT_EQUALS(*n, *i);
  38. }
  39. void test_object_sets_value() const {
  40. static int const value1{5};
  41. static int const value2{4};
  42. ptr_base i{new int{value1}};
  43. ptr_t n{i};
  44. TS_ASSERT_EQUALS(bool(n), true);
  45. TS_ASSERT_EQUALS(*n, value1);
  46. *n = value2;
  47. TS_ASSERT_EQUALS(bool(n), true);
  48. TS_ASSERT_EQUALS(*i, value2);
  49. }
  50. void test_do_not_own() const {
  51. bool has_delete{false};
  52. struct test_t {
  53. ~test_t() { _r = true; }
  54. bool & _r;
  55. };
  56. test_t * test_struct = new test_t{has_delete};
  57. maybe_null<test_t *>{test_struct};
  58. TS_ASSERT_EQUALS(has_delete, false);
  59. delete test_struct;
  60. TS_ASSERT_EQUALS(has_delete, true);
  61. }
  62. void test_type_conversion() {
  63. struct base {};
  64. struct derived : public base {};
  65. derived d;
  66. maybe_null<derived*> m{&d};
  67. maybe_null<base*> b = m;
  68. TS_ASSERT_EQUALS(b.get(), m.get());
  69. }
  70. private:
  71. template <typename T>
  72. static maybe_null<std::shared_ptr<T>> make_with(T p) {
  73. return maybe_null<std::shared_ptr<T>>(std::make_shared<T>(p));
  74. }
  75. };