Skip to content

Commit d679312

Browse files
author
Damian Rouson
committed
feat: reformulate the simple assertions
demonstrate `assert` execution in a pure procedure
1 parent 02b2d2f commit d679312

File tree

1 file changed

+29
-6
lines changed

1 file changed

+29
-6
lines changed

example/simple_assertions.f90

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,33 @@
11
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.
46
implicit none
5-
integer, parameter :: i = 1
6-
real, parameter :: x = -1.
77

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+
1033
end program

0 commit comments

Comments
 (0)