cmake_minimum_required(VERSION 3.19)

include(FetchContent)
FetchContent_Declare(googletest URL https://github.com/google/googletest/archive/refs/tags/v1.16.0.zip)
FetchContent_MakeAvailable(googletest)

enable_testing()

include_directories(${PYTHON_INCLUDE_DIRS})
include_directories(${PYBIND11_INCLUDE_DIRS})

file(GLOB TEST_SOURCES "*.cpp" "*.hpp")
add_executable(native_tests ${TEST_SOURCES} ${SOURCE_FILES} ${HEADER_FILES})

set(NATIVE_TEST_LIBRARIES gtest gtest_main ${PYTHON_LIBRARIES} pybind11::module)

if(NOT (CMAKE_BUILD_TYPE STREQUAL "Debug")
   AND NOT (DEFINED ENV{DD_COMPILE_ABSEIL} AND ("$ENV{DD_COMPILE_ABSEIL}" STREQUAL "0" OR "$ENV{DD_COMPILE_ABSEIL}"
                                                                                          STREQUAL "false")))
    list(APPEND NATIVE_TEST_LIBRARIES absl::node_hash_map)
endif()

if(NOT MSVC AND NATIVE_TEST_COVERAGE)
    target_compile_options(native_tests PRIVATE -ggdb --coverage)
    list(APPEND NATIVE_TEST_LIBRARIES gcov)
endif()

target_link_libraries(native_tests ${NATIVE_TEST_LIBRARIES})

# Enable ASan for native tests to detect memory errors at runtime. option(NATIVE_TEST_ASAN "Enable AddressSanitizer for
# native tests" ON) if(NATIVE_TEST_ASAN AND NOT MSVC) target_compile_options(native_tests PRIVATE -fsanitize=address
# -fno-omit-frame-pointer) target_link_options(native_tests PRIVATE -fsanitize=address) endif()

# Discover tests
include(GoogleTest)
gtest_discover_tests(native_tests)

# replace gtest_discover_tests to use ASan for native tests to detect memory errors at runtime. gtest_discover_tests(
# native_tests DISCOVERY_MODE PRE_TEST PROPERTIES ENVIRONMENT
# "ASAN_OPTIONS=detect_leaks=0:halt_on_error=1:abort_on_error=1;LSAN_OPTIONS=verbosity=1:log_threads=1")

add_custom_target(
    test_valgrind
    COMMAND
        PYTHONMALLOC=malloc valgrind --track-origins=yes --leak-check=full
        --suppressions=../../../../../scripts/iast/valgrind-python.supp --show-reachable=yes
        ${CMAKE_BINARY_DIR}/tests/native_tests --gtest_filter=-TestTimer.*
    WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/tests)
add_dependencies(test_valgrind native_tests)
