message(STATUS "Configuring libgridxc tests...")

#
# Note that the tests will only be built when this target is
# requested if the tests targets are marked "EXCLUDE_FROM_ALL".
# This mechanism is handy for individual libraries, but does
# not permit selective testing when they are subprojects of
# a larger module. The scheme is deactivated for now (lines
# with '### ' prefix).
#
# When activated, one would use, for example:
#
#    cmake --build _build -- libgridxc-tests
#    cmake --build _build -- test
#
# to build and run the tests.
#

### add_custom_target("${PROJECT_NAME}-tests")

include(TestMPIConfig)

macro(define_test
      name
      source
      mpi_enabled
      )

 message(DEBUG " --> Add libgridxc_${name} test")
 
 add_executable(
  "${PROJECT_NAME}-${name}"
  ### Deactivate the scheme for now
  ### EXCLUDE_FROM_ALL
  "${source}"
 )
### add_dependencies("${PROJECT_NAME}-tests"   "${PROJECT_NAME}-${name}")

 target_link_libraries(
  "${PROJECT_NAME}-${name}"
  PRIVATE
  "${PROJECT_NAME}-lib"
 )

 if(WITH_MPI)
    target_compile_definitions(
      "${PROJECT_NAME}-${name}"
      PRIVATE
      HAVE_MPI
    )
  target_link_libraries("${PROJECT_NAME}-${name}" PRIVATE MPI::MPI_Fortran)

 endif()
 
 if(WITH_LIBXC)
    target_compile_definitions(
      "${PROJECT_NAME}-${name}"
      PRIVATE
      HAVE_LIBXC
    )
    target_link_libraries(
      "${PROJECT_NAME}-${name}"
      PRIVATE
      libxc::XC_Fortran
    )
  endif()

  if (${mpi_enabled} AND WITH_MPI)
    separate_arguments(MPIEXEC_PREFLAGS)
    add_test( NAME "libgridxc_mpi_${name}"
              COMMAND
                ${MPIEXEC_EXECUTABLE}
                ${MPIEXEC_NUMPROC_FLAG} "${num_ranks}"
                ${MPIEXEC_PREFLAGS}
		$<TARGET_FILE:${PROJECT_NAME}-${name}> ${MPIEXEC_POSTFLAGS})

  else()
  
    add_test(NAME "libgridxc_${name}" COMMAND $<TARGET_FILE:${PROJECT_NAME}-${name}> )
    
  endif()
  
endmacro()

define_test(test1 test1.f90 OFF)
define_test(test2 test2.F90 ON)
define_test(test3 test3.F90 ON)
define_test(test4 test4.F90 ON)
# test5 is pending refactoring
define_test(test6 test6.f90 OFF)
      
if (WITH_LIBXC)
  define_test(test_libxc test_libxc.F90 ON)
  define_test(test_libxc2 test_libxc2.F90 ON)
  define_test(test_match test_match.F90 OFF)
  define_test(test_hse06 test_hse06.F90 OFF)
endif()

