1# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
2# file Copyright.txt or https://cmake.org/licensing for details.
3
4#[=======================================================================[.rst:
5GoogleTest
6----------
7
8This module defines functions to help use the Google Test infrastructure.  Two
9mechanisms for adding tests are provided. :command:`gtest_add_tests` has been
10around for some time, originally via ``find_package(GTest)``.
11:command:`gtest_discover_tests` was introduced in CMake 3.10.
12
13The (older) :command:`gtest_add_tests` scans source files to identify tests.
14This is usually effective, with some caveats, including in cross-compiling
15environments, and makes setting additional properties on tests more convenient.
16However, its handling of parameterized tests is less comprehensive, and it
17requires re-running CMake to detect changes to the list of tests.
18
19The (newer) :command:`gtest_discover_tests` discovers tests by asking the
20compiled test executable to enumerate its tests.  This is more robust and
21provides better handling of parameterized tests, and does not require CMake
22to be re-run when tests change.  However, it may not work in a cross-compiling
23environment, and setting test properties is less convenient.
24
25More details can be found in the documentation of the respective functions.
26
27Both commands are intended to replace use of :command:`add_test` to register
28tests, and will create a separate CTest test for each Google Test test case.
29Note that this is in some cases less efficient, as common set-up and tear-down
30logic cannot be shared by multiple test cases executing in the same instance.
31However, it provides more fine-grained pass/fail information to CTest, which is
32usually considered as more beneficial.  By default, the CTest test name is the
33same as the Google Test name (i.e. ``suite.testcase``); see also
34``TEST_PREFIX`` and ``TEST_SUFFIX``.
35
36.. command:: gtest_add_tests
37
38  Automatically add tests with CTest by scanning source code for Google Test
39  macros::
40
41    gtest_add_tests(TARGET target
42                    [SOURCES src1...]
43                    [EXTRA_ARGS arg1...]
44                    [WORKING_DIRECTORY dir]
45                    [TEST_PREFIX prefix]
46                    [TEST_SUFFIX suffix]
47                    [SKIP_DEPENDENCY]
48                    [TEST_LIST outVar]
49    )
50
51  ``gtest_add_tests`` attempts to identify tests by scanning source files.
52  Although this is generally effective, it uses only a basic regular expression
53  match, which can be defeated by atypical test declarations, and is unable to
54  fully "split" parameterized tests.  Additionally, it requires that CMake be
55  re-run to discover any newly added, removed or renamed tests (by default,
56  this means that CMake is re-run when any test source file is changed, but see
57  ``SKIP_DEPENDENCY``).  However, it has the advantage of declaring tests at
58  CMake time, which somewhat simplifies setting additional properties on tests,
59  and always works in a cross-compiling environment.
60
61  The options are:
62
63  ``TARGET target``
64    Specifies the Google Test executable, which must be a known CMake
65    executable target.  CMake will substitute the location of the built
66    executable when running the test.
67
68  ``SOURCES src1...``
69    When provided, only the listed files will be scanned for test cases.  If
70    this option is not given, the :prop_tgt:`SOURCES` property of the
71    specified ``target`` will be used to obtain the list of sources.
72
73  ``EXTRA_ARGS arg1...``
74    Any extra arguments to pass on the command line to each test case.
75
76  ``WORKING_DIRECTORY dir``
77    Specifies the directory in which to run the discovered test cases.  If this
78    option is not provided, the current binary directory is used.
79
80  ``TEST_PREFIX prefix``
81    Specifies a ``prefix`` to be prepended to the name of each discovered test
82    case.  This can be useful when the same source files are being used in
83    multiple calls to ``gtest_add_test()`` but with different ``EXTRA_ARGS``.
84
85  ``TEST_SUFFIX suffix``
86    Similar to ``TEST_PREFIX`` except the ``suffix`` is appended to the name of
87    every discovered test case.  Both ``TEST_PREFIX`` and ``TEST_SUFFIX`` may
88    be specified.
89
90  ``SKIP_DEPENDENCY``
91    Normally, the function creates a dependency which will cause CMake to be
92    re-run if any of the sources being scanned are changed.  This is to ensure
93    that the list of discovered tests is updated.  If this behavior is not
94    desired (as may be the case while actually writing the test cases), this
95    option can be used to prevent the dependency from being added.
96
97  ``TEST_LIST outVar``
98    The variable named by ``outVar`` will be populated in the calling scope
99    with the list of discovered test cases.  This allows the caller to do
100    things like manipulate test properties of the discovered tests.
101
102  .. code-block:: cmake
103
104    include(GoogleTest)
105    add_executable(FooTest FooUnitTest.cxx)
106    gtest_add_tests(TARGET      FooTest
107                    TEST_SUFFIX .noArgs
108                    TEST_LIST   noArgsTests
109    )
110    gtest_add_tests(TARGET      FooTest
111                    EXTRA_ARGS  --someArg someValue
112                    TEST_SUFFIX .withArgs
113                    TEST_LIST   withArgsTests
114    )
115    set_tests_properties(${noArgsTests}   PROPERTIES TIMEOUT 10)
116    set_tests_properties(${withArgsTests} PROPERTIES TIMEOUT 20)
117
118  For backward compatibility, the following form is also supported::
119
120    gtest_add_tests(exe args files...)
121
122  ``exe``
123    The path to the test executable or the name of a CMake target.
124  ``args``
125    A ;-list of extra arguments to be passed to executable.  The entire
126    list must be passed as a single argument.  Enclose it in quotes,
127    or pass ``""`` for no arguments.
128  ``files...``
129    A list of source files to search for tests and test fixtures.
130    Alternatively, use ``AUTO`` to specify that ``exe`` is the name
131    of a CMake executable target whose sources should be scanned.
132
133  .. code-block:: cmake
134
135    include(GoogleTest)
136    set(FooTestArgs --foo 1 --bar 2)
137    add_executable(FooTest FooUnitTest.cxx)
138    gtest_add_tests(FooTest "${FooTestArgs}" AUTO)
139
140.. command:: gtest_discover_tests
141
142  Automatically add tests with CTest by querying the compiled test executable
143  for available tests::
144
145    gtest_discover_tests(target
146                         [EXTRA_ARGS arg1...]
147                         [WORKING_DIRECTORY dir]
148                         [TEST_PREFIX prefix]
149                         [TEST_SUFFIX suffix]
150                         [NO_PRETTY_TYPES] [NO_PRETTY_VALUES]
151                         [PROPERTIES name1 value1...]
152                         [TEST_LIST var]
153                         [DISCOVERY_TIMEOUT seconds]
154    )
155
156  ``gtest_discover_tests`` sets up a post-build command on the test executable
157  that generates the list of tests by parsing the output from running the test
158  with the ``--gtest_list_tests`` argument.  Compared to the source parsing
159  approach of :command:`gtest_add_tests`, this ensures that the full list of
160  tests, including instantiations of parameterized tests, is obtained.  Since
161  test discovery occurs at build time, it is not necessary to re-run CMake when
162  the list of tests changes.
163  However, it requires that :prop_tgt:`CROSSCOMPILING_EMULATOR` is properly set
164  in order to function in a cross-compiling environment.
165
166  Additionally, setting properties on tests is somewhat less convenient, since
167  the tests are not available at CMake time.  Additional test properties may be
168  assigned to the set of tests as a whole using the ``PROPERTIES`` option.  If
169  more fine-grained test control is needed, custom content may be provided
170  through an external CTest script using the :prop_dir:`TEST_INCLUDE_FILES`
171  directory property.  The set of discovered tests is made accessible to such a
172  script via the ``<target>_TESTS`` variable.
173
174  The options are:
175
176  ``target``
177    Specifies the Google Test executable, which must be a known CMake
178    executable target.  CMake will substitute the location of the built
179    executable when running the test.
180
181  ``EXTRA_ARGS arg1...``
182    Any extra arguments to pass on the command line to each test case.
183
184  ``WORKING_DIRECTORY dir``
185    Specifies the directory in which to run the discovered test cases.  If this
186    option is not provided, the current binary directory is used.
187
188  ``TEST_PREFIX prefix``
189    Specifies a ``prefix`` to be prepended to the name of each discovered test
190    case.  This can be useful when the same test executable is being used in
191    multiple calls to ``gtest_discover_tests()`` but with different
192    ``EXTRA_ARGS``.
193
194  ``TEST_SUFFIX suffix``
195    Similar to ``TEST_PREFIX`` except the ``suffix`` is appended to the name of
196    every discovered test case.  Both ``TEST_PREFIX`` and ``TEST_SUFFIX`` may
197    be specified.
198
199  ``NO_PRETTY_TYPES``
200    By default, the type index of type-parameterized tests is replaced by the
201    actual type name in the CTest test name.  If this behavior is undesirable
202    (e.g. because the type names are unwieldy), this option will suppress this
203    behavior.
204
205  ``NO_PRETTY_VALUES``
206    By default, the value index of value-parameterized tests is replaced by the
207    actual value in the CTest test name.  If this behavior is undesirable
208    (e.g. because the value strings are unwieldy), this option will suppress
209    this behavior.
210
211  ``PROPERTIES name1 value1...``
212    Specifies additional properties to be set on all tests discovered by this
213    invocation of ``gtest_discover_tests``.
214
215  ``TEST_LIST var``
216    Make the list of tests available in the variable ``var``, rather than the
217    default ``<target>_TESTS``.  This can be useful when the same test
218    executable is being used in multiple calls to ``gtest_discover_tests()``.
219    Note that this variable is only available in CTest.
220
221  ``DISCOVERY_TIMEOUT num``
222    Specifies how long (in seconds) CMake will wait for the test to enumerate
223    available tests.  If the test takes longer than this, discovery (and your
224    build) will fail.  Most test executables will enumerate their tests very
225    quickly, but under some exceptional circumstances, a test may require a
226    longer timeout.  The default is 5.  See also the ``TIMEOUT`` option of
227    :command:`execute_process`.
228
229    .. note::
230
231      In CMake versions 3.10.1 and 3.10.2, this option was called ``TIMEOUT``.
232      This clashed with the ``TIMEOUT`` test property, which is one of the
233      common properties that would be set with the ``PROPERTIES`` keyword,
234      usually leading to legal but unintended behavior.  The keyword was
235      changed to ``DISCOVERY_TIMEOUT`` in CMake 3.10.3 to address this
236      problem.  The ambiguous behavior of the ``TIMEOUT`` keyword in 3.10.1
237      and 3.10.2 has not been preserved.
238
239#]=======================================================================]
240
241#------------------------------------------------------------------------------
242function(gtest_add_tests)
243
244  if (ARGC LESS 1)
245    message(FATAL_ERROR "No arguments supplied to gtest_add_tests()")
246  endif()
247
248  set(options
249      SKIP_DEPENDENCY
250  )
251  set(oneValueArgs
252      TARGET
253      WORKING_DIRECTORY
254      TEST_PREFIX
255      TEST_SUFFIX
256      TEST_LIST
257  )
258  set(multiValueArgs
259      SOURCES
260      EXTRA_ARGS
261  )
262  set(allKeywords ${options} ${oneValueArgs} ${multiValueArgs})
263
264  unset(sources)
265  if("${ARGV0}" IN_LIST allKeywords)
266    cmake_parse_arguments(ARGS "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
267    set(autoAddSources YES)
268  else()
269    # Non-keyword syntax, convert to keyword form
270    if (ARGC LESS 3)
271      message(FATAL_ERROR "gtest_add_tests() without keyword options requires at least 3 arguments")
272    endif()
273    set(ARGS_TARGET     "${ARGV0}")
274    set(ARGS_EXTRA_ARGS "${ARGV1}")
275    if(NOT "${ARGV2}" STREQUAL "AUTO")
276      set(ARGS_SOURCES "${ARGV}")
277      list(REMOVE_AT ARGS_SOURCES 0 1)
278    endif()
279  endif()
280
281  # The non-keyword syntax allows the first argument to be an arbitrary
282  # executable rather than a target if source files are also provided. In all
283  # other cases, both forms require a target.
284  if(NOT TARGET "${ARGS_TARGET}" AND NOT ARGS_SOURCES)
285    message(FATAL_ERROR "${ARGS_TARGET} does not define an existing CMake target")
286  endif()
287  if(NOT ARGS_WORKING_DIRECTORY)
288    unset(workDir)
289  else()
290    set(workDir WORKING_DIRECTORY "${ARGS_WORKING_DIRECTORY}")
291  endif()
292
293  if(NOT ARGS_SOURCES)
294    get_property(ARGS_SOURCES TARGET ${ARGS_TARGET} PROPERTY SOURCES)
295  endif()
296
297  unset(testList)
298
299  set(gtest_case_name_regex ".*\\( *([A-Za-z_0-9]+) *, *([A-Za-z_0-9]+) *\\).*")
300  set(gtest_test_type_regex "(TYPED_TEST|TEST_?[FP]?)")
301
302  foreach(source IN LISTS ARGS_SOURCES)
303    if(NOT ARGS_SKIP_DEPENDENCY)
304      set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${source})
305    endif()
306    file(READ "${source}" contents)
307    string(REGEX MATCHALL "${gtest_test_type_regex} *\\(([A-Za-z_0-9 ,]+)\\)" found_tests ${contents})
308    foreach(hit ${found_tests})
309      string(REGEX MATCH "${gtest_test_type_regex}" test_type ${hit})
310
311      # Parameterized tests have a different signature for the filter
312      if("x${test_type}" STREQUAL "xTEST_P")
313        string(REGEX REPLACE ${gtest_case_name_regex}  "*/\\1.\\2/*" gtest_test_name ${hit})
314      elseif("x${test_type}" STREQUAL "xTEST_F" OR "x${test_type}" STREQUAL "xTEST")
315        string(REGEX REPLACE ${gtest_case_name_regex} "\\1.\\2" gtest_test_name ${hit})
316      elseif("x${test_type}" STREQUAL "xTYPED_TEST")
317        string(REGEX REPLACE ${gtest_case_name_regex} "\\1/*.\\2" gtest_test_name ${hit})
318      else()
319        message(WARNING "Could not parse GTest ${hit} for adding to CTest.")
320        continue()
321      endif()
322
323      # Make sure tests disabled in GTest get disabled in CTest
324      if(gtest_test_name MATCHES "(^|\\.)DISABLED_")
325        # Add the disabled test if CMake is new enough
326        # Note that this check is to allow backwards compatibility so this
327        # module can be copied locally in projects to use with older CMake
328        # versions
329        if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.8.20170401)
330          string(REGEX REPLACE
331                 "(^|\\.)DISABLED_" "\\1"
332                 orig_test_name "${gtest_test_name}"
333          )
334          set(ctest_test_name
335              ${ARGS_TEST_PREFIX}${orig_test_name}${ARGS_TEST_SUFFIX}
336          )
337          add_test(NAME ${ctest_test_name}
338                   ${workDir}
339                   COMMAND ${ARGS_TARGET}
340                     --gtest_also_run_disabled_tests
341                     --gtest_filter=${gtest_test_name}
342                     ${ARGS_EXTRA_ARGS}
343          )
344          set_tests_properties(${ctest_test_name} PROPERTIES DISABLED TRUE)
345          list(APPEND testList ${ctest_test_name})
346        endif()
347      else()
348        set(ctest_test_name ${ARGS_TEST_PREFIX}${gtest_test_name}${ARGS_TEST_SUFFIX})
349        add_test(NAME ${ctest_test_name}
350                 ${workDir}
351                 COMMAND ${ARGS_TARGET}
352                   --gtest_filter=${gtest_test_name}
353                   ${ARGS_EXTRA_ARGS}
354        )
355        list(APPEND testList ${ctest_test_name})
356      endif()
357    endforeach()
358  endforeach()
359
360  if(ARGS_TEST_LIST)
361    set(${ARGS_TEST_LIST} ${testList} PARENT_SCOPE)
362  endif()
363
364endfunction()
365
366#------------------------------------------------------------------------------
367function(gtest_discover_tests TARGET)
368  cmake_parse_arguments(
369    ""
370    "NO_PRETTY_TYPES;NO_PRETTY_VALUES"
371    "TEST_PREFIX;TEST_SUFFIX;WORKING_DIRECTORY;TEST_LIST;DISCOVERY_TIMEOUT"
372    "EXTRA_ARGS;PROPERTIES"
373    ${ARGN}
374  )
375
376  if(NOT _WORKING_DIRECTORY)
377    set(_WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}")
378  endif()
379  if(NOT _TEST_LIST)
380    set(_TEST_LIST ${TARGET}_TESTS)
381  endif()
382  if(NOT _DISCOVERY_TIMEOUT)
383    set(_DISCOVERY_TIMEOUT 5)
384  endif()
385
386  get_property(
387    has_counter
388    TARGET ${TARGET}
389    PROPERTY CTEST_DISCOVERED_TEST_COUNTER
390    SET
391  )
392  if(has_counter)
393    get_property(
394      counter
395      TARGET ${TARGET}
396      PROPERTY CTEST_DISCOVERED_TEST_COUNTER
397    )
398    math(EXPR counter "${counter} + 1")
399  else()
400    set(counter 1)
401  endif()
402  set_property(
403    TARGET ${TARGET}
404    PROPERTY CTEST_DISCOVERED_TEST_COUNTER
405    ${counter}
406  )
407
408  # Define rule to generate test list for aforementioned test executable
409  set(ctest_file_base "${CMAKE_CURRENT_BINARY_DIR}/${TARGET}[${counter}]")
410  set(ctest_include_file "${ctest_file_base}_include.cmake")
411  set(ctest_tests_file "${ctest_file_base}_tests.cmake")
412  get_property(crosscompiling_emulator
413    TARGET ${TARGET}
414    PROPERTY CROSSCOMPILING_EMULATOR
415  )
416  add_custom_command(
417    TARGET ${TARGET} POST_BUILD
418    BYPRODUCTS "${ctest_tests_file}"
419    COMMAND "${CMAKE_COMMAND}"
420            -D "TEST_TARGET=${TARGET}"
421            -D "TEST_EXECUTABLE=$<TARGET_FILE:${TARGET}>"
422            -D "TEST_EXECUTOR=${crosscompiling_emulator}"
423            -D "TEST_WORKING_DIR=${_WORKING_DIRECTORY}"
424            -D "TEST_EXTRA_ARGS=${_EXTRA_ARGS}"
425            -D "TEST_PROPERTIES=${_PROPERTIES}"
426            -D "TEST_PREFIX=${_TEST_PREFIX}"
427            -D "TEST_SUFFIX=${_TEST_SUFFIX}"
428            -D "NO_PRETTY_TYPES=${_NO_PRETTY_TYPES}"
429            -D "NO_PRETTY_VALUES=${_NO_PRETTY_VALUES}"
430            -D "TEST_LIST=${_TEST_LIST}"
431            -D "CTEST_FILE=${ctest_tests_file}"
432            -D "TEST_DISCOVERY_TIMEOUT=${_DISCOVERY_TIMEOUT}"
433            -P "${_GOOGLETEST_DISCOVER_TESTS_SCRIPT}"
434    VERBATIM
435  )
436
437  file(WRITE "${ctest_include_file}"
438    "if(EXISTS \"${ctest_tests_file}\")\n"
439    "  include(\"${ctest_tests_file}\")\n"
440    "else()\n"
441    "  add_test(${TARGET}_NOT_BUILT ${TARGET}_NOT_BUILT)\n"
442    "endif()\n"
443  )
444
445  # Add discovered tests to directory TEST_INCLUDE_FILES
446  set_property(DIRECTORY
447    APPEND PROPERTY TEST_INCLUDE_FILES "${ctest_include_file}"
448  )
449
450  # Backport to cmake 3.9 and earlier - TEST_INCLUDE_FILES property
451  # was added in cmake 3.10; prior to that we only have the singular
452  # TEST_INCLUDE_FILE property, which only allows one file to be included
453  # per directory. Therefore if running with cmake before 3.10, add a final
454  # step where we manually combine all elements in TEST_INCLUDE_FILES into a
455  # single unified file, and use TEST_INCLUDE_FILE to include that.
456  if (CMAKE_VERSION VERSION_LESS 3.10)
457    set(ctest_unified_include_file "${ctest_file_base}_include_unified.cmake")
458    get_property(_test_include_file_VALUE DIRECTORY PROPERTY TEST_INCLUDE_FILES)
459    foreach (file IN LISTS _test_include_file_VALUE)
460      file(READ ${file} contents)
461      set(unified ${unified}${contents})
462    endforeach ()
463    file(WRITE "${ctest_unified_include_file}" "${unified}")
464    set_property(DIRECTORY
465      PROPERTY TEST_INCLUDE_FILE "${ctest_unified_include_file}"
466    )
467  endif()
468
469endfunction()
470
471###############################################################################
472
473set(_GOOGLETEST_DISCOVER_TESTS_SCRIPT
474  ${CMAKE_CURRENT_LIST_DIR}/GoogleTestAddTests.cmake
475)
476