| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- //
- // maybe_null.t.h
- // pointers
- //
- // Created by Sam Jaffe on 12/2/16.
- //
- #pragma once
- #include <cxxtest/TestSuite.h>
- #include <memory>
- #undef DEBUG
- #define DEBUG
- #include "maybe_null.hpp"
- class maybe_null_TestSuite : public CxxTest::TestSuite {
- public:
- using ptr_base = std::shared_ptr<int>;
- using ptr_t = maybe_null<ptr_base>;
- public:
- void test_can_hold_nullptr() const {
- ptr_t mn{nullptr};
- TS_ASSERT_EQUALS(bool(mn), false);
- }
-
- void test_is_valid_wo_nullptr() const {
- ptr_t mn = make_with(5);
- TS_ASSERT_EQUALS(bool(mn), true);
- }
-
- void test_nullptr_throws_or_false() const {
- ptr_t mn{nullptr};
- TS_ASSERT_THROWS(*mn, unchecked_pointer_exception);
- }
-
- void test_object_contains_ptr() const {
- ptr_base i{new int};
- ptr_t n{i};
- TS_ASSERT_EQUALS(bool(n), true);
- TS_ASSERT_EQUALS(n.get(), i.get());
- TS_ASSERT_EQUALS(*n, *i);
- }
-
- void test_object_sets_value() const {
- static int const value1{5};
- static int const value2{4};
-
- ptr_base i{new int{value1}};
- ptr_t n{i};
- TS_ASSERT_EQUALS(bool(n), true);
- TS_ASSERT_EQUALS(*n, value1);
- *n = value2;
- TS_ASSERT_EQUALS(bool(n), true);
- TS_ASSERT_EQUALS(*i, value2);
- }
-
- void test_do_not_own() const {
- bool has_delete{false};
- struct test_t {
- ~test_t() { _r = true; }
- bool & _r;
- };
- test_t * test_struct = new test_t{has_delete};
- maybe_null<test_t *>{test_struct};
- TS_ASSERT_EQUALS(has_delete, false);
- delete test_struct;
- TS_ASSERT_EQUALS(has_delete, true);
- }
-
- void test_type_conversion() {
- struct base {};
- struct derived : public base {};
- derived d;
- maybe_null<derived*> m{&d};
- maybe_null<base*> b = maybe_null<base*>(m);
- TS_ASSERT_EQUALS(b.get(), m.get());
- }
-
- private:
- template <typename T>
- static maybe_null<std::shared_ptr<T>> make_with(T p) {
- return maybe_null<std::shared_ptr<T>>(std::make_shared<T>(p));
- }
- };
|