if(NOT BUILD_TESTING)
  return()
endif()

# Inspired by https://eb2.co/blog/2015/06/driving-boost.test-with-cmake
function(gather_boost_tests SOURCE_FILE_NAME)

    file(READ "${SOURCE_FILE_NAME}" SOURCE_FILE_CONTENTS)
    string(REGEX MATCHALL "BOOST_(AUTO|FIXTURE)_TEST_CASE\\([^,\\)]+"
           FOUND_TESTS ${SOURCE_FILE_CONTENTS})

    list(TRANSFORM FOUND_TESTS REPLACE ".*\\(([^,\\)]+).*" "\\1")

    set(ALL_TEST_CASES ${FOUND_TESTS} PARENT_SCOPE)
endfunction()

find_package(Boost REQUIRED unit_test_framework)

add_executable(db_test test/test.cpp)

target_include_directories(db_test PUBLIC ${Boost_INCLUDE_DIRS})
target_compile_options(db_test PUBLIC -Wall -Wextra -pedantic)
target_link_libraries(db_test ${Boost_UNIT_TEST_FRAMEWORK_LIBRARY} Tango::Tango)

configure_file(test/start_tdb.sh.in start_tdb.sh @ONLY)
configure_file(test/stop_tdb.sh.in stop_tdb.sh @ONLY)

gather_boost_tests("test/test.cpp")

# not using cmake FIXTURES_SETUP/FIXTURES_CLEANUP as these are not called per test case

message(STATUS "Found test cases: ${ALL_TEST_CASES}")

foreach(TEST_CASE IN LISTS ALL_TEST_CASES)
  add_test(NAME ${TEST_CASE} COMMAND db_test --log_level=all --logger=JUNIT,message,JU_${TEST_CASE}.xml:HRF,message,stdout --run_test=*/${TEST_CASE} --catch_system_error=yes)
  # don't allow parallel runs
  set_tests_properties(${TEST_CASE} PROPERTIES RESOURCE_LOCK Database)
endforeach()
