|
1 | 1 | program assertion_examples |
2 | | - !! Demonstrate the use of assetions |
3 | | - use assert_m, only : assert |
| 2 | + !! Demonstrate the use of assertions as runtime checks on the satisfaction of |
| 3 | + !! of two kinds of constraints: |
| 4 | + !! 1. Preconditions: requirements for correct execution at the start of a procedure and |
| 5 | + !! 2. Postconditions: requirements for correct execution at the end of a procedure. |
4 | 6 | implicit none |
5 | | - integer, parameter :: i = 1 |
6 | | - real, parameter :: x = -1. |
7 | 7 |
|
8 | | - call assert(i > 0, "i > 1") ! Passes |
9 | | - call assert(x > 0, description="x > 0", diagnostic_data=x) ! Fails with output containing diagnostic data |
| 8 | + print *, reciprocal(2.) |
| 9 | + |
| 10 | +contains |
| 11 | + |
| 12 | + pure real function reciprocal(x) result(reciprocal_of_x) |
| 13 | + !! Erroneous calculation of the reciprocal of the function's argument |
| 14 | + use assert_m, only : assert |
| 15 | + real, intent(in) :: x |
| 16 | + |
| 17 | + call assert(assertion = x /= 0., description = "reciprocal: x /= 0", diagnostic_data = x) ! Precondition passes |
| 18 | + |
| 19 | + reciprocal_of_x = 0. ! incorrect value for the reciprocal of x |
| 20 | + |
| 21 | + block |
| 22 | + real, parameter :: tolerance = 1.E-06 |
| 23 | + |
| 24 | + associate(error => x*reciprocal_of_x - 1.) |
| 25 | + |
| 26 | + call assert(abs(error) < tolerance, "reciprocal: abs(error) < tolerance", error) ! Postcondition fails |
| 27 | + |
| 28 | + end associate |
| 29 | + end block |
| 30 | + |
| 31 | + end function |
| 32 | + |
10 | 33 | end program |
0 commit comments