|
| 1 | +module usage_test |
| 2 | + use reference_counter_m, only: ref_reference_t |
| 3 | + use vegetables, only: & |
| 4 | + result_t, & |
| 5 | + test_item_t, & |
| 6 | + assert_equals, & |
| 7 | + assert_not, & |
| 8 | + assert_that, & |
| 9 | + describe, & |
| 10 | + fail, & |
| 11 | + it |
| 12 | + |
| 13 | + implicit none |
| 14 | + private |
| 15 | + public :: test_usage |
| 16 | + |
| 17 | + type, extends(ref_reference_t) :: object_t |
| 18 | + integer, pointer :: ref => null() |
| 19 | + contains |
| 20 | + procedure :: free |
| 21 | + end type |
| 22 | + |
| 23 | + interface object_t |
| 24 | + module procedure construct |
| 25 | + end interface |
| 26 | + |
| 27 | + integer, allocatable, target :: the_resource |
| 28 | + integer, parameter :: the_answer = 42 |
| 29 | +contains |
| 30 | + function construct() result(object) |
| 31 | + type(object_t) :: object |
| 32 | + |
| 33 | + allocate(the_resource) |
| 34 | + object%ref => the_resource |
| 35 | + object%ref = the_answer |
| 36 | + call object%start_ref_counter |
| 37 | + end function |
| 38 | + |
| 39 | + subroutine free(self) |
| 40 | + class(object_t), intent(inout) :: self |
| 41 | + |
| 42 | + deallocate(the_resource) |
| 43 | + nullify(self%ref) |
| 44 | + end subroutine |
| 45 | + |
| 46 | + function test_usage() result(tests) |
| 47 | + type(test_item_t) :: tests |
| 48 | + |
| 49 | + tests = describe( & |
| 50 | + "Using a reference-counted object", & |
| 51 | + [ it("creates a resource when constructed", check_creation) & |
| 52 | + , it("removes the resource when it goes out of scope", check_deletion) & |
| 53 | + , it("a copy points to the same resource", check_copy) & |
| 54 | + ]) |
| 55 | + end function |
| 56 | + |
| 57 | + function check_creation() result(result_) |
| 58 | + type(result_t) :: result_ |
| 59 | + |
| 60 | + type(object_t) :: object |
| 61 | + |
| 62 | + object = object_t() |
| 63 | + if (allocated(the_resource)) then |
| 64 | + result_ = assert_equals(the_answer, the_resource) |
| 65 | + else |
| 66 | + result_ = fail("resource not retained") |
| 67 | + end if |
| 68 | + end function |
| 69 | + |
| 70 | + function check_deletion() result(result_) |
| 71 | + type(result_t) :: result_ |
| 72 | + |
| 73 | + block |
| 74 | + type(object_t) :: object |
| 75 | + |
| 76 | + object = object_t() |
| 77 | + end block |
| 78 | + result_ = assert_not(allocated(the_resource)) |
| 79 | + end function |
| 80 | + |
| 81 | + function check_copy() result(result_) |
| 82 | + type(result_t) :: result_ |
| 83 | + |
| 84 | + type(object_t) :: object1, object2 |
| 85 | + |
| 86 | + object1 = object_t() |
| 87 | + object2 = object1 |
| 88 | + result_ = assert_that(associated(object2%ref, object1%ref)) |
| 89 | + end function |
| 90 | +end module |
0 commit comments