GoogleTest.cmake 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  1. # Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. # file Copyright.txt or https://cmake.org/licensing for details.
  3. #[=======================================================================[.rst:
  4. GoogleTest
  5. ----------
  6. .. versionadded:: 3.9
  7. This module defines functions to help use the Google Test infrastructure. Two
  8. mechanisms for adding tests are provided. :command:`gtest_add_tests` has been
  9. around for some time, originally via ``find_package(GTest)``.
  10. :command:`gtest_discover_tests` was introduced in CMake 3.10.
  11. The (older) :command:`gtest_add_tests` scans source files to identify tests.
  12. This is usually effective, with some caveats, including in cross-compiling
  13. environments, and makes setting additional properties on tests more convenient.
  14. However, its handling of parameterized tests is less comprehensive, and it
  15. requires re-running CMake to detect changes to the list of tests.
  16. The (newer) :command:`gtest_discover_tests` discovers tests by asking the
  17. compiled test executable to enumerate its tests. This is more robust and
  18. provides better handling of parameterized tests, and does not require CMake
  19. to be re-run when tests change. However, it may not work in a cross-compiling
  20. environment, and setting test properties is less convenient.
  21. More details can be found in the documentation of the respective functions.
  22. Both commands are intended to replace use of :command:`add_test` to register
  23. tests, and will create a separate CTest test for each Google Test test case.
  24. Note that this is in some cases less efficient, as common set-up and tear-down
  25. logic cannot be shared by multiple test cases executing in the same instance.
  26. However, it provides more fine-grained pass/fail information to CTest, which is
  27. usually considered as more beneficial. By default, the CTest test name is the
  28. same as the Google Test name (i.e. ``suite.testcase``); see also
  29. ``TEST_PREFIX`` and ``TEST_SUFFIX``.
  30. .. command:: gtest_add_tests
  31. Automatically add tests with CTest by scanning source code for Google Test
  32. macros::
  33. gtest_add_tests(TARGET target
  34. [SOURCES src1...]
  35. [EXTRA_ARGS args...]
  36. [WORKING_DIRECTORY dir]
  37. [TEST_PREFIX prefix]
  38. [TEST_SUFFIX suffix]
  39. [SKIP_DEPENDENCY]
  40. [TEST_LIST outVar]
  41. )
  42. ``gtest_add_tests`` attempts to identify tests by scanning source files.
  43. Although this is generally effective, it uses only a basic regular expression
  44. match, which can be defeated by atypical test declarations, and is unable to
  45. fully "split" parameterized tests. Additionally, it requires that CMake be
  46. re-run to discover any newly added, removed or renamed tests (by default,
  47. this means that CMake is re-run when any test source file is changed, but see
  48. ``SKIP_DEPENDENCY``). However, it has the advantage of declaring tests at
  49. CMake time, which somewhat simplifies setting additional properties on tests,
  50. and always works in a cross-compiling environment.
  51. The options are:
  52. ``TARGET target``
  53. Specifies the Google Test executable, which must be a known CMake
  54. executable target. CMake will substitute the location of the built
  55. executable when running the test.
  56. ``SOURCES src1...``
  57. When provided, only the listed files will be scanned for test cases. If
  58. this option is not given, the :prop_tgt:`SOURCES` property of the
  59. specified ``target`` will be used to obtain the list of sources.
  60. ``EXTRA_ARGS args...``
  61. Any extra arguments to pass on the command line to each test case.
  62. .. versionchanged:: 3.31
  63. Empty values in ``args...`` are preserved, see :policy:`CMP0178`.
  64. ``WORKING_DIRECTORY dir``
  65. Specifies the directory in which to run the discovered test cases. If this
  66. option is not provided, the current binary directory is used.
  67. ``TEST_PREFIX prefix``
  68. Specifies a ``prefix`` to be prepended to the name of each discovered test
  69. case. This can be useful when the same source files are being used in
  70. multiple calls to ``gtest_add_test()`` but with different ``EXTRA_ARGS``.
  71. ``TEST_SUFFIX suffix``
  72. Similar to ``TEST_PREFIX`` except the ``suffix`` is appended to the name of
  73. every discovered test case. Both ``TEST_PREFIX`` and ``TEST_SUFFIX`` may
  74. be specified.
  75. ``SKIP_DEPENDENCY``
  76. Normally, the function creates a dependency which will cause CMake to be
  77. re-run if any of the sources being scanned are changed. This is to ensure
  78. that the list of discovered tests is updated. If this behavior is not
  79. desired (as may be the case while actually writing the test cases), this
  80. option can be used to prevent the dependency from being added.
  81. ``TEST_LIST outVar``
  82. The variable named by ``outVar`` will be populated in the calling scope
  83. with the list of discovered test cases. This allows the caller to do
  84. things like manipulate test properties of the discovered tests.
  85. .. versionchanged:: 3.31
  86. Empty values in the :prop_tgt:`TEST_LAUNCHER` and
  87. :prop_tgt:`CROSSCOMPILING_EMULATOR` target properties are preserved,
  88. see policy :policy:`CMP0178`.
  89. Usage example:
  90. .. code-block:: cmake
  91. include(GoogleTest)
  92. add_executable(FooTest FooUnitTest.cxx)
  93. gtest_add_tests(TARGET FooTest
  94. TEST_SUFFIX .noArgs
  95. TEST_LIST noArgsTests
  96. )
  97. gtest_add_tests(TARGET FooTest
  98. EXTRA_ARGS --someArg someValue
  99. TEST_SUFFIX .withArgs
  100. TEST_LIST withArgsTests
  101. )
  102. set_tests_properties(${noArgsTests} PROPERTIES TIMEOUT 10)
  103. set_tests_properties(${withArgsTests} PROPERTIES TIMEOUT 20)
  104. For backward compatibility, the following form is also supported::
  105. gtest_add_tests(exe args files...)
  106. ``exe``
  107. The path to the test executable or the name of a CMake target.
  108. ``args``
  109. A ;-list of extra arguments to be passed to executable. The entire
  110. list must be passed as a single argument. Enclose it in quotes,
  111. or pass ``""`` for no arguments.
  112. ``files...``
  113. A list of source files to search for tests and test fixtures.
  114. Alternatively, use ``AUTO`` to specify that ``exe`` is the name
  115. of a CMake executable target whose sources should be scanned.
  116. .. code-block:: cmake
  117. include(GoogleTest)
  118. set(FooTestArgs --foo 1 --bar 2)
  119. add_executable(FooTest FooUnitTest.cxx)
  120. gtest_add_tests(FooTest "${FooTestArgs}" AUTO)
  121. .. command:: gtest_discover_tests
  122. Automatically add tests with CTest by querying the compiled test executable
  123. for available tests::
  124. gtest_discover_tests(target
  125. [EXTRA_ARGS args...]
  126. [WORKING_DIRECTORY dir]
  127. [TEST_PREFIX prefix]
  128. [TEST_SUFFIX suffix]
  129. [TEST_FILTER expr]
  130. [NO_PRETTY_TYPES] [NO_PRETTY_VALUES]
  131. [PROPERTIES name1 value1...]
  132. [TEST_LIST var]
  133. [DISCOVERY_TIMEOUT seconds]
  134. [XML_OUTPUT_DIR dir]
  135. [DISCOVERY_MODE <POST_BUILD|PRE_TEST>]
  136. [DISCOVERY_EXTRA_ARGS args...]
  137. )
  138. .. versionadded:: 3.10
  139. ``gtest_discover_tests()`` sets up a post-build or pre-test command on the
  140. test executable that generates the list of tests by parsing the output from
  141. running the test executable with the ``--gtest_list_tests`` argument.
  142. Compared to the source parsing approach of :command:`gtest_add_tests`,
  143. this ensures that the full list of tests, including instantiations of
  144. parameterized tests, is obtained. Since test discovery occurs at build
  145. or test time, it is not necessary to re-run CMake when the list of tests
  146. changes. However, it requires that :prop_tgt:`CROSSCOMPILING_EMULATOR`
  147. is properly set in order to function in a cross-compiling environment.
  148. Additionally, setting properties on tests is somewhat less convenient, since
  149. the tests are not available at CMake time. Additional test properties may be
  150. assigned to the set of tests as a whole using the ``PROPERTIES`` option. If
  151. more fine-grained test control is needed, custom content may be provided
  152. through an external CTest script using the :prop_dir:`TEST_INCLUDE_FILES`
  153. directory property. The set of discovered tests is made accessible to such a
  154. script via the ``<target>_TESTS`` variable (see the ``TEST_LIST`` option
  155. below for further discussion and limitations).
  156. The options are:
  157. ``target``
  158. Specifies the Google Test executable, which must be a known CMake
  159. executable target. CMake will substitute the location of the built
  160. executable when running the test.
  161. ``EXTRA_ARGS args...``
  162. Any extra arguments to pass on the command line to each test case.
  163. .. versionchanged:: 3.31
  164. Empty values in ``args...`` are preserved, see :policy:`CMP0178`.
  165. ``WORKING_DIRECTORY dir``
  166. Specifies the directory in which to run the discovered test cases. If this
  167. option is not provided, the current binary directory is used.
  168. ``TEST_PREFIX prefix``
  169. Specifies a ``prefix`` to be prepended to the name of each discovered test
  170. case. This can be useful when the same test executable is being used in
  171. multiple calls to ``gtest_discover_tests()`` but with different
  172. ``EXTRA_ARGS``.
  173. ``TEST_SUFFIX suffix``
  174. Similar to ``TEST_PREFIX`` except the ``suffix`` is appended to the name of
  175. every discovered test case. Both ``TEST_PREFIX`` and ``TEST_SUFFIX`` may
  176. be specified.
  177. ``TEST_FILTER expr``
  178. .. versionadded:: 3.22
  179. Filter expression to pass as a ``--gtest_filter`` argument during test
  180. discovery. Note that the expression is a wildcard-based format that
  181. matches against the original test names as used by gtest. For type or
  182. value-parameterized tests, these names may be different to the potentially
  183. pretty-printed test names that :program:`ctest` uses.
  184. ``NO_PRETTY_TYPES``
  185. By default, the type index of type-parameterized tests is replaced by the
  186. actual type name in the CTest test name. If this behavior is undesirable
  187. (e.g. because the type names are unwieldy), this option will suppress this
  188. behavior.
  189. ``NO_PRETTY_VALUES``
  190. By default, the value index of value-parameterized tests is replaced by the
  191. actual value in the CTest test name. If this behavior is undesirable
  192. (e.g. because the value strings are unwieldy), this option will suppress
  193. this behavior.
  194. ``PROPERTIES name1 value1...``
  195. Specifies additional properties to be set on all tests discovered by this
  196. invocation of ``gtest_discover_tests()``.
  197. ``TEST_LIST var``
  198. Make the list of tests available in the variable ``var``, rather than the
  199. default ``<target>_TESTS``. This can be useful when the same test
  200. executable is being used in multiple calls to ``gtest_discover_tests()``.
  201. Note that this variable is only available in CTest.
  202. Due to a limitation of CMake's parsing rules, any test with a square
  203. bracket in its name will be omitted from the list of tests stored in
  204. this variable. Such tests will still be defined and executed by
  205. ``ctest`` as normal though.
  206. ``DISCOVERY_TIMEOUT num``
  207. .. versionadded:: 3.10.3
  208. Specifies how long (in seconds) CMake will wait for the test to enumerate
  209. available tests. If the test takes longer than this, discovery (and your
  210. build) will fail. Most test executables will enumerate their tests very
  211. quickly, but under some exceptional circumstances, a test may require a
  212. longer timeout. The default is 5. See also the ``TIMEOUT`` option of
  213. :command:`execute_process`.
  214. .. note::
  215. In CMake versions 3.10.1 and 3.10.2, this option was called ``TIMEOUT``.
  216. This clashed with the ``TIMEOUT`` test property, which is one of the
  217. common properties that would be set with the ``PROPERTIES`` keyword,
  218. usually leading to legal but unintended behavior. The keyword was
  219. changed to ``DISCOVERY_TIMEOUT`` in CMake 3.10.3 to address this
  220. problem. The ambiguous behavior of the ``TIMEOUT`` keyword in 3.10.1
  221. and 3.10.2 has not been preserved.
  222. ``XML_OUTPUT_DIR dir``
  223. .. versionadded:: 3.18
  224. If specified, the parameter is passed along with ``--gtest_output=xml:``
  225. to test executable. The actual file name is the same as the test target,
  226. including prefix and suffix. This should be used instead of
  227. ``EXTRA_ARGS --gtest_output=xml`` to avoid race conditions writing the
  228. XML result output when using parallel test execution.
  229. ``DISCOVERY_MODE``
  230. .. versionadded:: 3.18
  231. Provides greater control over when ``gtest_discover_tests()`` performs test
  232. discovery. By default, ``POST_BUILD`` sets up a post-build command
  233. to perform test discovery at build time. In certain scenarios, like
  234. cross-compiling, this ``POST_BUILD`` behavior is not desirable.
  235. By contrast, ``PRE_TEST`` delays test discovery until just prior to test
  236. execution. This way test discovery occurs in the target environment
  237. where the test has a better chance at finding appropriate runtime
  238. dependencies.
  239. ``DISCOVERY_MODE`` defaults to the value of the
  240. ``CMAKE_GTEST_DISCOVER_TESTS_DISCOVERY_MODE`` variable if it is not
  241. passed when calling ``gtest_discover_tests()``. This provides a mechanism
  242. for globally selecting a preferred test discovery behavior without having
  243. to modify each call site.
  244. ``DISCOVERY_EXTRA_ARGS args...``
  245. .. versionadded:: 3.31
  246. Any extra arguments to pass on the command line for the discovery command.
  247. .. versionadded:: 3.29
  248. The :prop_tgt:`TEST_LAUNCHER` target property is honored during test
  249. discovery and test execution.
  250. .. versionchanged:: 3.31
  251. Empty values in the :prop_tgt:`TEST_LAUNCHER` and
  252. :prop_tgt:`CROSSCOMPILING_EMULATOR` target properties are preserved,
  253. see policy :policy:`CMP0178`.
  254. #]=======================================================================]
  255. # Save project's policies
  256. block(SCOPE_FOR POLICIES)
  257. cmake_policy(VERSION 3.30)
  258. #------------------------------------------------------------------------------
  259. function(gtest_add_tests)
  260. if (ARGC LESS 1)
  261. message(FATAL_ERROR "No arguments supplied to gtest_add_tests()")
  262. endif()
  263. set(options
  264. SKIP_DEPENDENCY
  265. )
  266. set(oneValueArgs
  267. TARGET
  268. WORKING_DIRECTORY
  269. TEST_PREFIX
  270. TEST_SUFFIX
  271. TEST_LIST
  272. )
  273. set(multiValueArgs
  274. SOURCES
  275. EXTRA_ARGS
  276. )
  277. set(allKeywords ${options} ${oneValueArgs} ${multiValueArgs})
  278. cmake_policy(GET CMP0178 cmp0178
  279. PARENT_SCOPE # undocumented, do not use outside of CMake
  280. )
  281. unset(sources)
  282. if("${ARGV0}" IN_LIST allKeywords)
  283. if(cmp0178 STREQUAL "NEW")
  284. cmake_parse_arguments(PARSE_ARGV 0 arg
  285. "${options}" "${oneValueArgs}" "${multiValueArgs}"
  286. )
  287. else()
  288. cmake_parse_arguments(arg "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
  289. if(NOT cmp0178 STREQUAL "OLD")
  290. block(SCOPE_FOR VARIABLES)
  291. cmake_parse_arguments(PARSE_ARGV 0 arg_new
  292. "${options}" "${oneValueArgs}" "${multiValueArgs}"
  293. )
  294. # Due to a quirk of cmake_parse_arguments(PARSE_ARGV),
  295. # arg_new_EXTRA_ARGS will have semicolons already escaped, but
  296. # arg_EXTRA_ARGS won't. We need to pass the former through one round
  297. # of command argument parsing to de-escape them for comparison with
  298. # the latter.
  299. set(__newArgs ${arg_new_EXTRA_ARGS})
  300. if(NOT "${arg_EXTRA_ARGS}" STREQUAL "${__newArgs}")
  301. cmake_policy(GET_WARNING CMP0178 cmp0178_warning)
  302. message(AUTHOR_WARNING
  303. "The EXTRA_ARGS contain one or more empty values. Those empty "
  304. "values are being silently discarded to preserve backward "
  305. "compatibility.\n"
  306. "${cmp0178_warning}"
  307. )
  308. endif()
  309. endblock()
  310. endif()
  311. endif()
  312. set(autoAddSources YES)
  313. else()
  314. # Non-keyword syntax, convert to keyword form
  315. if (ARGC LESS 3)
  316. message(FATAL_ERROR "gtest_add_tests() without keyword options requires at least 3 arguments")
  317. endif()
  318. set(arg_TARGET "${ARGV0}")
  319. set(arg_EXTRA_ARGS "${ARGV1}")
  320. if(NOT "${ARGV2}" STREQUAL "AUTO")
  321. set(arg_SOURCES "${ARGV}")
  322. list(REMOVE_AT arg_SOURCES 0 1)
  323. endif()
  324. endif()
  325. # The non-keyword syntax allows the first argument to be an arbitrary
  326. # executable rather than a target if source files are also provided. In all
  327. # other cases, both forms require a target.
  328. if(NOT TARGET "${arg_TARGET}" AND NOT arg_SOURCES)
  329. message(FATAL_ERROR "${arg_TARGET} does not define an existing CMake target")
  330. endif()
  331. if(NOT arg_WORKING_DIRECTORY)
  332. unset(workDir)
  333. else()
  334. set(workDir WORKING_DIRECTORY "${arg_WORKING_DIRECTORY}")
  335. endif()
  336. if(NOT arg_SOURCES)
  337. get_property(arg_SOURCES TARGET ${arg_TARGET} PROPERTY SOURCES)
  338. endif()
  339. unset(testList)
  340. set(gtest_case_name_regex ".*\\([ \r\n\t]*([A-Za-z_0-9]+)[ \r\n\t]*,[ \r\n\t]*([A-Za-z_0-9]+)[ \r\n\t]*\\).*")
  341. set(gtest_test_type_regex "(TYPED_TEST|TEST)_?[FP]?")
  342. set(each_line_regex "([^\r\n]*[\r\n])")
  343. foreach(source IN LISTS arg_SOURCES)
  344. if(NOT arg_SKIP_DEPENDENCY)
  345. set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${source})
  346. endif()
  347. file(READ "${source}" contents)
  348. # Replace characters in file content that are special to CMake
  349. string(REPLACE "[" "<OPEN_BRACKET>" contents "${contents}")
  350. string(REPLACE "]" "<CLOSE_BRACKET>" contents "${contents}")
  351. string(REPLACE ";" "\\;" contents "${contents}")
  352. # Split into lines
  353. string(REGEX MATCHALL "${each_line_regex}" content_lines "${contents}")
  354. set(line "0")
  355. # Stores the line number of the start of a test definition
  356. set(accumulate_line "0")
  357. # Stores accumulated lines to match multi-line test definitions
  358. set(accumulated "")
  359. # Iterate over each line in the file so that we know the line number of a test definition
  360. foreach(line_str IN LISTS content_lines)
  361. MATH(EXPR line "${line}+1")
  362. # Check if the current line is the start of a test definition
  363. string(REGEX MATCH "[ \t]*${gtest_test_type_regex}[ \t]*[\\(]*" accumlate_start_hit "${line_str}")
  364. if(accumlate_start_hit)
  365. set(accumulate_line "${line}")
  366. endif()
  367. # Append the current line to the accumulated string
  368. set(accumulated "${accumulated}${line_str}")
  369. # Attempt to match a complete test definition in the accumulated string
  370. string(REGEX MATCH "${gtest_test_type_regex}[ \r\n\t]*\\(([A-Za-z_0-9 ,\r\n\t]+)\\)" hit "${accumulated}")
  371. if(hit)
  372. # Reset accumulated for the next match
  373. set(accumulated "")
  374. else()
  375. # Continue accumulating lines
  376. continue()
  377. endif()
  378. # At this point, the start line of the test definition is known
  379. # Hence, we can set the test's DEF_SOURCE_LINE property with
  380. # ${source}:${accumulate_line} below.
  381. # VS Code CMake Tools extension looks for DEF_SOURCE_LINE
  382. # to locate the test definition for its "Go to test" feature.
  383. string(REGEX MATCH "${gtest_test_type_regex}" test_type ${hit})
  384. # Parameterized tests have a different signature for the filter
  385. if("x${test_type}" STREQUAL "xTEST_P")
  386. string(REGEX REPLACE ${gtest_case_name_regex} "*/\\1.\\2/*" gtest_test_name ${hit})
  387. elseif("x${test_type}" STREQUAL "xTYPED_TEST_P")
  388. string(REGEX REPLACE ${gtest_case_name_regex} "*/\\1/*.\\2" gtest_test_name ${hit})
  389. elseif("x${test_type}" STREQUAL "xTEST_F" OR "x${test_type}" STREQUAL "xTEST")
  390. string(REGEX REPLACE ${gtest_case_name_regex} "\\1.\\2" gtest_test_name ${hit})
  391. elseif("x${test_type}" STREQUAL "xTYPED_TEST")
  392. string(REGEX REPLACE ${gtest_case_name_regex} "\\1/*.\\2" gtest_test_name ${hit})
  393. else()
  394. message(WARNING "Could not parse GTest ${hit} for adding to CTest.")
  395. continue()
  396. endif()
  397. set(extra_args "")
  398. foreach(arg IN LISTS arg_EXTRA_ARGS)
  399. string(APPEND extra_args " [==[${arg}]==]")
  400. endforeach()
  401. # Make sure tests disabled in GTest get disabled in CTest
  402. if(gtest_test_name MATCHES "(^|\\.)DISABLED_")
  403. # Add the disabled test if CMake is new enough
  404. # Note that this check is to allow backwards compatibility so this
  405. # module can be copied locally in projects to use with older CMake
  406. # versions
  407. if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.8.20170401)
  408. string(REGEX REPLACE
  409. "(^|\\.)DISABLED_" "\\1"
  410. orig_test_name "${gtest_test_name}"
  411. )
  412. set(ctest_test_name
  413. ${arg_TEST_PREFIX}${orig_test_name}${arg_TEST_SUFFIX}
  414. )
  415. cmake_language(EVAL CODE "
  416. add_test(NAME ${ctest_test_name}
  417. ${workDir}
  418. COMMAND ${arg_TARGET}
  419. --gtest_also_run_disabled_tests
  420. --gtest_filter=${gtest_test_name}
  421. ${extra_args}
  422. __CMP0178 [==[${cmp0178}]==]
  423. )"
  424. )
  425. set_tests_properties(${ctest_test_name} PROPERTIES DISABLED TRUE
  426. DEF_SOURCE_LINE "${source}:${accumulate_line}")
  427. list(APPEND testList ${ctest_test_name})
  428. endif()
  429. else()
  430. set(ctest_test_name ${arg_TEST_PREFIX}${gtest_test_name}${arg_TEST_SUFFIX})
  431. cmake_language(EVAL CODE "
  432. add_test(NAME ${ctest_test_name}
  433. ${workDir}
  434. COMMAND ${arg_TARGET}
  435. --gtest_filter=${gtest_test_name}
  436. ${extra_args}
  437. __CMP0178 [==[${cmp0178}]==]
  438. )"
  439. )
  440. # Makes sure a skipped GTest is reported as so by CTest
  441. set_tests_properties(
  442. ${ctest_test_name}
  443. PROPERTIES
  444. SKIP_REGULAR_EXPRESSION "\\[ SKIPPED \\]"
  445. DEF_SOURCE_LINE "${source}:${accumulate_line}"
  446. )
  447. list(APPEND testList ${ctest_test_name})
  448. endif()
  449. endforeach()
  450. endforeach()
  451. if(arg_TEST_LIST)
  452. set(${arg_TEST_LIST} ${testList} PARENT_SCOPE)
  453. endif()
  454. endfunction()
  455. #------------------------------------------------------------------------------
  456. function(gtest_discover_tests target)
  457. set(options
  458. NO_PRETTY_TYPES
  459. NO_PRETTY_VALUES
  460. )
  461. set(oneValueArgs
  462. TEST_PREFIX
  463. TEST_SUFFIX
  464. WORKING_DIRECTORY
  465. TEST_LIST
  466. DISCOVERY_TIMEOUT
  467. XML_OUTPUT_DIR
  468. DISCOVERY_MODE
  469. )
  470. set(multiValueArgs
  471. EXTRA_ARGS
  472. DISCOVERY_EXTRA_ARGS
  473. PROPERTIES
  474. TEST_FILTER
  475. )
  476. cmake_parse_arguments(PARSE_ARGV 1 arg
  477. "${options}" "${oneValueArgs}" "${multiValueArgs}"
  478. )
  479. if(NOT arg_WORKING_DIRECTORY)
  480. set(arg_WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}")
  481. endif()
  482. if(NOT arg_TEST_LIST)
  483. set(arg_TEST_LIST ${target}_TESTS)
  484. endif()
  485. if(NOT arg_DISCOVERY_TIMEOUT)
  486. set(arg_DISCOVERY_TIMEOUT 5)
  487. endif()
  488. if(NOT arg_DISCOVERY_MODE)
  489. if(NOT CMAKE_GTEST_DISCOVER_TESTS_DISCOVERY_MODE)
  490. set(CMAKE_GTEST_DISCOVER_TESTS_DISCOVERY_MODE "POST_BUILD")
  491. endif()
  492. set(arg_DISCOVERY_MODE ${CMAKE_GTEST_DISCOVER_TESTS_DISCOVERY_MODE})
  493. endif()
  494. get_property(
  495. has_counter
  496. TARGET ${target}
  497. PROPERTY CTEST_DISCOVERED_TEST_COUNTER
  498. SET
  499. )
  500. if(has_counter)
  501. get_property(
  502. counter
  503. TARGET ${target}
  504. PROPERTY CTEST_DISCOVERED_TEST_COUNTER
  505. )
  506. math(EXPR counter "${counter} + 1")
  507. else()
  508. set(counter 1)
  509. endif()
  510. set_property(
  511. TARGET ${target}
  512. PROPERTY CTEST_DISCOVERED_TEST_COUNTER
  513. ${counter}
  514. )
  515. # Define rule to generate test list for aforementioned test executable
  516. set(ctest_file_base "${CMAKE_CURRENT_BINARY_DIR}/${target}[${counter}]")
  517. set(ctest_include_file "${ctest_file_base}_include.cmake")
  518. set(ctest_tests_file "${ctest_file_base}_tests.cmake")
  519. get_property(test_launcher
  520. TARGET ${target}
  521. PROPERTY TEST_LAUNCHER
  522. )
  523. cmake_policy(GET CMP0158 _CMP0158
  524. PARENT_SCOPE # undocumented, do not use outside of CMake
  525. )
  526. if(NOT _CMP0158 OR _CMP0158 STREQUAL "OLD" OR _CMP0158 STREQUAL "NEW" AND CMAKE_CROSSCOMPILING)
  527. get_property(crosscompiling_emulator
  528. TARGET ${target}
  529. PROPERTY CROSSCOMPILING_EMULATOR
  530. )
  531. endif()
  532. if(test_launcher AND crosscompiling_emulator)
  533. set(test_executor "${test_launcher}" "${crosscompiling_emulator}")
  534. elseif(test_launcher)
  535. set(test_executor "${test_launcher}")
  536. elseif(crosscompiling_emulator)
  537. set(test_executor "${crosscompiling_emulator}")
  538. else()
  539. set(test_executor "")
  540. endif()
  541. cmake_policy(GET CMP0178 cmp0178
  542. PARENT_SCOPE # undocumented, do not use outside of CMake
  543. )
  544. if(NOT cmp0178 STREQUAL "NEW")
  545. # Preserve old behavior where empty list items are silently discarded
  546. set(test_executor_orig "${test_executor}")
  547. set(test_executor ${test_executor})
  548. set(arg_EXTRA_ARGS_orig "${arg_EXTRA_ARGS}")
  549. set(arg_EXTRA_ARGS ${arg_EXTRA_ARGS})
  550. if(NOT cmp0178 STREQUAL "OLD")
  551. if(NOT "${test_executor}" STREQUAL "${test_executor_orig}")
  552. cmake_policy(GET_WARNING CMP0178 cmp0178_warning)
  553. message(AUTHOR_WARNING
  554. "The '${target}' target's TEST_LAUNCHER or CROSSCOMPILING_EMULATOR "
  555. "test properties contain one or more empty values. Those empty "
  556. "values are being silently discarded to preserve backward "
  557. "compatibility.\n"
  558. "${cmp0178_warning}"
  559. )
  560. endif()
  561. if(NOT "${arg_EXTRA_ARGS}" STREQUAL "${arg_EXTRA_ARGS_orig}")
  562. cmake_policy(GET_WARNING CMP0178 cmp0178_warning)
  563. message(AUTHOR_WARNING
  564. "The EXTRA_ARGS value contains one or more empty values. "
  565. "Those empty values are being silently discarded to preserve "
  566. "backward compatibility.\n"
  567. "${cmp0178_warning}"
  568. )
  569. endif()
  570. endif()
  571. endif()
  572. if(arg_DISCOVERY_MODE STREQUAL "POST_BUILD")
  573. add_custom_command(
  574. TARGET ${target} POST_BUILD
  575. BYPRODUCTS "${ctest_tests_file}"
  576. COMMAND "${CMAKE_COMMAND}"
  577. -D "TEST_TARGET=${target}"
  578. -D "TEST_EXECUTABLE=$<TARGET_FILE:${target}>"
  579. -D "TEST_EXECUTOR=${test_executor}"
  580. -D "TEST_WORKING_DIR=${arg_WORKING_DIRECTORY}"
  581. -D "TEST_EXTRA_ARGS=${arg_EXTRA_ARGS}"
  582. -D "TEST_PROPERTIES=${arg_PROPERTIES}"
  583. -D "TEST_PREFIX=${arg_TEST_PREFIX}"
  584. -D "TEST_SUFFIX=${arg_TEST_SUFFIX}"
  585. -D "TEST_FILTER=${arg_TEST_FILTER}"
  586. -D "NO_PRETTY_TYPES=${arg_NO_PRETTY_TYPES}"
  587. -D "NO_PRETTY_VALUES=${arg_NO_PRETTY_VALUES}"
  588. -D "TEST_LIST=${arg_TEST_LIST}"
  589. -D "CTEST_FILE=${ctest_tests_file}"
  590. -D "TEST_DISCOVERY_TIMEOUT=${arg_DISCOVERY_TIMEOUT}"
  591. -D "TEST_DISCOVERY_EXTRA_ARGS=${arg_DISCOVERY_EXTRA_ARGS}"
  592. -D "TEST_XML_OUTPUT_DIR=${arg_XML_OUTPUT_DIR}"
  593. -P "${CMAKE_ROOT}/Modules/GoogleTestAddTests.cmake"
  594. VERBATIM
  595. )
  596. file(WRITE "${ctest_include_file}"
  597. "if(EXISTS \"${ctest_tests_file}\")\n"
  598. " include(\"${ctest_tests_file}\")\n"
  599. "else()\n"
  600. " add_test(${target}_NOT_BUILT ${target}_NOT_BUILT)\n"
  601. "endif()\n"
  602. )
  603. elseif(arg_DISCOVERY_MODE STREQUAL "PRE_TEST")
  604. get_property(GENERATOR_IS_MULTI_CONFIG GLOBAL
  605. PROPERTY GENERATOR_IS_MULTI_CONFIG
  606. )
  607. if(GENERATOR_IS_MULTI_CONFIG)
  608. set(ctest_tests_file "${ctest_file_base}_tests-$<CONFIG>.cmake")
  609. endif()
  610. string(CONCAT ctest_include_content
  611. "if(EXISTS \"$<TARGET_FILE:${target}>\")" "\n"
  612. " if(NOT EXISTS \"${ctest_tests_file}\" OR" "\n"
  613. " NOT \"${ctest_tests_file}\" IS_NEWER_THAN \"$<TARGET_FILE:${target}>\" OR\n"
  614. " NOT \"${ctest_tests_file}\" IS_NEWER_THAN \"\${CMAKE_CURRENT_LIST_FILE}\")\n"
  615. " include(\"${CMAKE_ROOT}/Modules/GoogleTestAddTests.cmake\")" "\n"
  616. " gtest_discover_tests_impl(" "\n"
  617. " TEST_EXECUTABLE" " [==[$<TARGET_FILE:${target}>]==]" "\n"
  618. " TEST_EXECUTOR" " [==[${test_executor}]==]" "\n"
  619. " TEST_WORKING_DIR" " [==[${arg_WORKING_DIRECTORY}]==]" "\n"
  620. " TEST_EXTRA_ARGS" " [==[${arg_EXTRA_ARGS}]==]" "\n"
  621. " TEST_PROPERTIES" " [==[${arg_PROPERTIES}]==]" "\n"
  622. " TEST_PREFIX" " [==[${arg_TEST_PREFIX}]==]" "\n"
  623. " TEST_SUFFIX" " [==[${arg_TEST_SUFFIX}]==]" "\n"
  624. " TEST_FILTER" " [==[${arg_TEST_FILTER}]==]" "\n"
  625. " NO_PRETTY_TYPES" " [==[${arg_NO_PRETTY_TYPES}]==]" "\n"
  626. " NO_PRETTY_VALUES" " [==[${arg_NO_PRETTY_VALUES}]==]" "\n"
  627. " TEST_LIST" " [==[${arg_TEST_LIST}]==]" "\n"
  628. " CTEST_FILE" " [==[${ctest_tests_file}]==]" "\n"
  629. " TEST_DISCOVERY_TIMEOUT" " [==[${arg_DISCOVERY_TIMEOUT}]==]" "\n"
  630. " TEST_DISCOVERY_EXTRA_ARGS [==[${arg_DISCOVERY_EXTRA_ARGS}]==]" "\n"
  631. " TEST_XML_OUTPUT_DIR" " [==[${arg_XML_OUTPUT_DIR}]==]" "\n"
  632. " )" "\n"
  633. " endif()" "\n"
  634. " include(\"${ctest_tests_file}\")" "\n"
  635. "else()" "\n"
  636. " add_test(${target}_NOT_BUILT ${target}_NOT_BUILT)" "\n"
  637. "endif()" "\n"
  638. )
  639. if(GENERATOR_IS_MULTI_CONFIG)
  640. foreach(_config ${CMAKE_CONFIGURATION_TYPES})
  641. file(GENERATE
  642. OUTPUT "${ctest_file_base}_include-${_config}.cmake"
  643. CONTENT "${ctest_include_content}"
  644. CONDITION $<CONFIG:${_config}>
  645. )
  646. endforeach()
  647. file(WRITE "${ctest_include_file}"
  648. "include(\"${ctest_file_base}_include-\${CTEST_CONFIGURATION_TYPE}.cmake\")"
  649. )
  650. else()
  651. file(GENERATE
  652. OUTPUT "${ctest_file_base}_include.cmake"
  653. CONTENT "${ctest_include_content}"
  654. )
  655. file(WRITE "${ctest_include_file}"
  656. "include(\"${ctest_file_base}_include.cmake\")"
  657. )
  658. endif()
  659. else()
  660. message(FATAL_ERROR "Unknown DISCOVERY_MODE: ${arg_DISCOVERY_MODE}")
  661. endif()
  662. # Add discovered tests to directory TEST_INCLUDE_FILES
  663. set_property(DIRECTORY
  664. APPEND PROPERTY TEST_INCLUDE_FILES "${ctest_include_file}"
  665. )
  666. endfunction()
  667. ###############################################################################
  668. # Restore project's policies
  669. endblock()