maybe_null.t.h 1.9 KB

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