1# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
2# file Copyright.txt or https://cmake.org/licensing for details.
3
4set(prefix "${TEST_PREFIX}")
5set(suffix "${TEST_SUFFIX}")
6set(spec ${TEST_SPEC})
7set(extra_args ${TEST_EXTRA_ARGS})
8set(properties ${TEST_PROPERTIES})
9set(script)
10set(suite)
11set(tests)
12
13function(add_command NAME)
14  set(_args "")
15  foreach(_arg ${ARGN})
16    if(_arg MATCHES "[^-./:a-zA-Z0-9_]")
17      set(_args "${_args} [==[${_arg}]==]") # form a bracket_argument
18    else()
19      set(_args "${_args} ${_arg}")
20    endif()
21  endforeach()
22  set(script "${script}${NAME}(${_args})\n" PARENT_SCOPE)
23endfunction()
24
25# Run test executable to get list of available tests
26if(NOT EXISTS "${TEST_EXECUTABLE}")
27  message(FATAL_ERROR
28    "Specified test executable '${TEST_EXECUTABLE}' does not exist"
29  )
30endif()
31execute_process(
32  COMMAND ${TEST_EXECUTOR} "${TEST_EXECUTABLE}" ${spec} --list-test-names-only
33  OUTPUT_VARIABLE output
34  RESULT_VARIABLE result
35)
36# Catch --list-test-names-only reports the number of tests, so 0 is... surprising
37if(${result} EQUAL 0)
38  message(WARNING
39    "Test executable '${TEST_EXECUTABLE}' contains no tests!\n"
40  )
41elseif(${result} LESS 0)
42  message(FATAL_ERROR
43    "Error running test executable '${TEST_EXECUTABLE}':\n"
44    "  Result: ${result}\n"
45    "  Output: ${output}\n"
46  )
47endif()
48
49string(REPLACE "\n" ";" output "${output}")
50
51# Parse output
52foreach(line ${output})
53  set(test ${line})
54  # use escape commas to handle properly test cases with commans inside the name
55  string(REPLACE "," "\\," test_name ${test})
56  # ...and add to script
57  add_command(add_test
58    "${prefix}${test}${suffix}"
59    ${TEST_EXECUTOR}
60    "${TEST_EXECUTABLE}"
61    "${test_name}"
62    ${extra_args}
63  )
64  add_command(set_tests_properties
65    "${prefix}${test}${suffix}"
66    PROPERTIES
67    WORKING_DIRECTORY "${TEST_WORKING_DIR}"
68    ${properties}
69  )
70  list(APPEND tests "${prefix}${test}${suffix}")
71endforeach()
72
73# Create a list of all discovered tests, which users may use to e.g. set
74# properties on the tests
75add_command(set ${TEST_LIST} ${tests})
76
77# Write CTest script
78file(WRITE "${CTEST_FILE}" "${script}")
79