Skip to content

8. Testing the command line ​

The command line of heat is part of its interface: it deserves tests. FLAP is built for it:

  • parse(args='...') parses a string instead of the real command line, split as a shell would;
  • init(standalone=.false.) makes --help, --version, ... return a status instead of ending the program;
  • init(usage_lun=, error_lun=) sends the messages to a unit of your choice, a scratch file in a test;
  • reset_parse forgets a parse, keeping the definitions, so one CLI can parse many command lines.

Put the definitions in one procedure, used by the program and by its tests:

f90
subroutine define(cli)
!< The definitions of heat (in a real program, a module procedure shared by heat and its tests).
type(command_line_interface), intent(inout) :: cli

call cli%init(progname='heat', standalone=.false., usage_lun=lun, error_lun=lun)
call cli%add(switch='--nx', help='Cells along each direction', required=.false., act='store', def='64')
endsubroutine define
f90
open(newunit=lun, status='scratch', action='readwrite')
call define(cli)
f90
! a command line given as a string
call cli%parse(args='--nx 128', error=error)
call check(error == 0 .and. cli%get_source(switch='--nx') == SOURCE_COMMANDLINE, 'parse --nx 128')
call cli%get(switch='--nx', val=nx, error=error)
call check(nx == 128, 'get --nx')

! parse another command line with the same definitions
call cli%reset_parse
call cli%parse(args='', error=error)
call check(cli%get_source(switch='--nx') == SOURCE_DEFAULT, 'the default')

! errors and statuses are returned, never stop the program (standalone=.false.)
call cli%reset_parse
call cli%parse(args='--nx 1 --nx 2', error=error)
call check(error == ERROR_DUPLICATED_CLAS, 'a repeated switch')
call cli%reset_parse
call cli%parse(args='--help', error=error)
call check(error == STATUS_PRINT_H, '--help returns a status')
call check(caught('Optional switches:'), 'the help is written on the unit')
$ heat_test
heat_test: all checks passed

Every error and status has a named constant (ERROR_DUPLICATED_CLAS, STATUS_PRINT_H, ...), exported by flap, so a test never compares with bare numbers. FLAP's own test suite works this way: see src/tests.

What you learned

parse(args=), standalone=.false., output units, reset_parse, get_source, the named error constants. Reference: Parsing, Error Codes.

Next: 9. Asking the user.