#!
#! This CMake file run a command that is supposed to produce an output file,
#! and then compare this output file to a given file
#! Use this file to test if a command produces the same output file as a given expected file.
#!
#! \note
#! You have to call camitk_test_init(..) first to prepare all variables
#!
#! Inspired from http://stackoverflow.com/questions/3305545/how-to-adapt-my-unit-tests-to-cmake-and-ctest
#! and http://www.cmake.org/pipermail/cmake/2009-July/030619.html

# declare outputfiles
get_filename_component(OUTFILE ${CAMITK_TEST_PASS_FILE} NAME )
set(CAMITK_TEST_COMMAND_OUTPUT_FILE ${CAMITK_TEST_OUTPUT_DIR}/${OUTFILE}) # the output of the tested command goes in this files

# remove previous savings
execute_process(COMMAND ${CMAKE_COMMAND} -E remove -f ${CAMITK_TEST_COMMAND_OUTPUT_FILE} )

# expands all arguments
set(CAMITK_TEST_COMMAND_ARG "${CAMITK_TEST_COMMAND_ARG} -o ${CAMITK_TEST_OUTPUT_DIR}" ) #space before -o is important here  #-o is the directory where the output file will be saved
string(REPLACE " " ";" CAMITK_TEST_COMMAND_ARG_LIST ${CAMITK_TEST_COMMAND_ARG})

# Run test
execute_process(COMMAND ${CAMITK_TEST_COMMAND} ${CAMITK_TEST_COMMAND_ARG_LIST})

# check file exists
if (NOT EXISTS ${CAMITK_TEST_PASS_FILE})
  message(STATUS "[FAIL]")
  message(FATAL_ERROR "${CAMITK_TEST_NAME}: input file ${CAMITK_TEST_PASS_FILE} not found." )
endif()

if (NOT EXISTS ${CAMITK_TEST_COMMAND_OUTPUT_FILE})
  message(STATUS "[FAIL]")
  message(FATAL_ERROR "${CAMITK_TEST_NAME}: output file ${CAMITK_TEST_COMMAND_OUTPUT_FILE} not found." )
endif()

# Then compare the files
message(STATUS "Comparing file \"${CAMITK_TEST_PASS_FILE}\" to \"${CAMITK_TEST_COMMAND_OUTPUT_FILE}\"...")
execute_process(
  COMMAND ${CMAKE_COMMAND} -E compare_files ${CAMITK_TEST_PASS_FILE} ${CAMITK_TEST_COMMAND_OUTPUT_FILE}
  RESULT_VARIABLE CAMITK_TEST_PASS_FILE_RESULT
  )

# check result
if( CAMITK_TEST_PASS_FILE_RESULT )
  message(STATUS "[FAIL]")
  message(FATAL_ERROR "${CAMITK_TEST_NAME}: ${CAMITK_TEST_COMMAND_OUTPUT_FILE} does not match ${CAMITK_TEST_PASS_FILE}" )
else()
  message(STATUS "[OK]")
endif()
