ParseAndAddCatchTests.cmake 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. #==================================================================================================#
  2. # supported macros #
  3. # - TEST_CASE, #
  4. # - TEMPLATE_TEST_CASE #
  5. # - SCENARIO, #
  6. # - TEST_CASE_METHOD, #
  7. # - CATCH_TEST_CASE, #
  8. # - CATCH_TEMPLATE_TEST_CASE #
  9. # - CATCH_SCENARIO, #
  10. # - CATCH_TEST_CASE_METHOD. #
  11. # #
  12. # Usage #
  13. # 1. make sure this module is in the path or add this otherwise: #
  14. # set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake.modules/") #
  15. # 2. make sure that you've enabled testing option for the project by the call: #
  16. # enable_testing() #
  17. # 3. add the lines to the script for testing target (sample CMakeLists.txt): #
  18. # project(testing_target) #
  19. # set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake.modules/") #
  20. # enable_testing() #
  21. # #
  22. # find_path(CATCH_INCLUDE_DIR "catch.hpp") #
  23. # include_directories(${INCLUDE_DIRECTORIES} ${CATCH_INCLUDE_DIR}) #
  24. # #
  25. # file(GLOB SOURCE_FILES "*.cpp") #
  26. # add_executable(${PROJECT_NAME} ${SOURCE_FILES}) #
  27. # #
  28. # include(ParseAndAddCatchTests) #
  29. # ParseAndAddCatchTests(${PROJECT_NAME}) #
  30. # #
  31. # The following variables affect the behavior of the script: #
  32. # #
  33. # PARSE_CATCH_TESTS_VERBOSE (Default OFF) #
  34. # -- enables debug messages #
  35. # PARSE_CATCH_TESTS_NO_HIDDEN_TESTS (Default OFF) #
  36. # -- excludes tests marked with [!hide], [.] or [.foo] tags #
  37. # PARSE_CATCH_TESTS_ADD_FIXTURE_IN_TEST_NAME (Default ON) #
  38. # -- adds fixture class name to the test name #
  39. # PARSE_CATCH_TESTS_ADD_TARGET_IN_TEST_NAME (Default ON) #
  40. # -- adds cmake target name to the test name #
  41. # PARSE_CATCH_TESTS_ADD_TO_CONFIGURE_DEPENDS (Default OFF) #
  42. # -- causes CMake to rerun when file with tests changes so that new tests will be discovered #
  43. # #
  44. # One can also set (locally) the optional variable OptionalCatchTestLauncher to precise the way #
  45. # a test should be run. For instance to use test MPI, one can write #
  46. # set(OptionalCatchTestLauncher ${MPIEXEC} ${MPIEXEC_NUMPROC_FLAG} ${NUMPROC}) #
  47. # just before calling this ParseAndAddCatchTests function #
  48. # #
  49. # The AdditionalCatchParameters optional variable can be used to pass extra argument to the test #
  50. # command. For example, to include successful tests in the output, one can write #
  51. # set(AdditionalCatchParameters --success) #
  52. # #
  53. # After the script, the ParseAndAddCatchTests_TESTS property for the target, and for each source #
  54. # file in the target is set, and contains the list of the tests extracted from that target, or #
  55. # from that file. This is useful, for example to add further labels or properties to the tests. #
  56. # #
  57. #==================================================================================================#
  58. if (CMAKE_MINIMUM_REQUIRED_VERSION VERSION_LESS 2.8.8)
  59. message(FATAL_ERROR "ParseAndAddCatchTests requires CMake 2.8.8 or newer")
  60. endif()
  61. option(PARSE_CATCH_TESTS_VERBOSE "Print Catch to CTest parser debug messages" OFF)
  62. option(PARSE_CATCH_TESTS_NO_HIDDEN_TESTS "Exclude tests with [!hide], [.] or [.foo] tags" OFF)
  63. option(PARSE_CATCH_TESTS_ADD_FIXTURE_IN_TEST_NAME "Add fixture class name to the test name" ON)
  64. option(PARSE_CATCH_TESTS_ADD_TARGET_IN_TEST_NAME "Add target name to the test name" ON)
  65. option(PARSE_CATCH_TESTS_ADD_TO_CONFIGURE_DEPENDS "Add test file to CMAKE_CONFIGURE_DEPENDS property" OFF)
  66. function(ParseAndAddCatchTests_PrintDebugMessage)
  67. if(PARSE_CATCH_TESTS_VERBOSE)
  68. message(STATUS "ParseAndAddCatchTests: ${ARGV}")
  69. endif()
  70. endfunction()
  71. # This removes the contents between
  72. # - block comments (i.e. /* ... */)
  73. # - full line comments (i.e. // ... )
  74. # contents have been read into '${CppCode}'.
  75. # !keep partial line comments
  76. function(ParseAndAddCatchTests_RemoveComments CppCode)
  77. string(ASCII 2 CMakeBeginBlockComment)
  78. string(ASCII 3 CMakeEndBlockComment)
  79. string(REGEX REPLACE "/\\*" "${CMakeBeginBlockComment}" ${CppCode} "${${CppCode}}")
  80. string(REGEX REPLACE "\\*/" "${CMakeEndBlockComment}" ${CppCode} "${${CppCode}}")
  81. string(REGEX REPLACE "${CMakeBeginBlockComment}[^${CMakeEndBlockComment}]*${CMakeEndBlockComment}" "" ${CppCode} "${${CppCode}}")
  82. string(REGEX REPLACE "\n[ \t]*//+[^\n]+" "\n" ${CppCode} "${${CppCode}}")
  83. set(${CppCode} "${${CppCode}}" PARENT_SCOPE)
  84. endfunction()
  85. # Worker function
  86. function(ParseAndAddCatchTests_ParseFile SourceFile TestTarget)
  87. # If SourceFile is an object library, do not scan it (as it is not a file). Exit without giving a warning about a missing file.
  88. if(SourceFile MATCHES "\\\$<TARGET_OBJECTS:.+>")
  89. ParseAndAddCatchTests_PrintDebugMessage("Detected OBJECT library: ${SourceFile} this will not be scanned for tests.")
  90. return()
  91. endif()
  92. # According to CMake docs EXISTS behavior is well-defined only for full paths.
  93. get_filename_component(SourceFile ${SourceFile} ABSOLUTE)
  94. if(NOT EXISTS ${SourceFile})
  95. message(WARNING "Cannot find source file: ${SourceFile}")
  96. return()
  97. endif()
  98. ParseAndAddCatchTests_PrintDebugMessage("parsing ${SourceFile}")
  99. file(STRINGS ${SourceFile} Contents NEWLINE_CONSUME)
  100. # Remove block and fullline comments
  101. ParseAndAddCatchTests_RemoveComments(Contents)
  102. # Find definition of test names
  103. # https://regex101.com/r/JygOND/1
  104. string(REGEX MATCHALL "[ \t]*(CATCH_)?(TEMPLATE_)?(TEST_CASE_METHOD|SCENARIO|TEST_CASE)[ \t]*\\([ \t\n]*\"[^\"]*\"[ \t\n]*(,[ \t\n]*\"[^\"]*\")?(,[ \t\n]*[^\,\)]*)*\\)[ \t\n]*\{+[ \t]*(//[^\n]*[Tt][Ii][Mm][Ee][Oo][Uu][Tt][ \t]*[0-9]+)*" Tests "${Contents}")
  105. if(PARSE_CATCH_TESTS_ADD_TO_CONFIGURE_DEPENDS AND Tests)
  106. ParseAndAddCatchTests_PrintDebugMessage("Adding ${SourceFile} to CMAKE_CONFIGURE_DEPENDS property")
  107. set_property(
  108. DIRECTORY
  109. APPEND
  110. PROPERTY CMAKE_CONFIGURE_DEPENDS ${SourceFile}
  111. )
  112. endif()
  113. # check CMP0110 policy for new add_test() behavior
  114. if(POLICY CMP0110)
  115. cmake_policy(GET CMP0110 _cmp0110_value) # new add_test() behavior
  116. else()
  117. # just to be thorough explicitly set the variable
  118. set(_cmp0110_value)
  119. endif()
  120. foreach(TestName ${Tests})
  121. # Strip newlines
  122. string(REGEX REPLACE "\\\\\n|\n" "" TestName "${TestName}")
  123. # Get test type and fixture if applicable
  124. string(REGEX MATCH "(CATCH_)?(TEMPLATE_)?(TEST_CASE_METHOD|SCENARIO|TEST_CASE)[ \t]*\\([^,^\"]*" TestTypeAndFixture "${TestName}")
  125. string(REGEX MATCH "(CATCH_)?(TEMPLATE_)?(TEST_CASE_METHOD|SCENARIO|TEST_CASE)" TestType "${TestTypeAndFixture}")
  126. string(REGEX REPLACE "${TestType}\\([ \t]*" "" TestFixture "${TestTypeAndFixture}")
  127. # Get string parts of test definition
  128. string(REGEX MATCHALL "\"+([^\\^\"]|\\\\\")+\"+" TestStrings "${TestName}")
  129. # Strip wrapping quotation marks
  130. string(REGEX REPLACE "^\"(.*)\"$" "\\1" TestStrings "${TestStrings}")
  131. string(REPLACE "\";\"" ";" TestStrings "${TestStrings}")
  132. # Validate that a test name and tags have been provided
  133. list(LENGTH TestStrings TestStringsLength)
  134. if(TestStringsLength GREATER 2 OR TestStringsLength LESS 1)
  135. message(FATAL_ERROR "You must provide a valid test name and tags for all tests in ${SourceFile}")
  136. endif()
  137. # Assign name and tags
  138. list(GET TestStrings 0 Name)
  139. if("${TestType}" STREQUAL "SCENARIO")
  140. set(Name "Scenario: ${Name}")
  141. endif()
  142. if(PARSE_CATCH_TESTS_ADD_FIXTURE_IN_TEST_NAME AND "${TestType}" MATCHES "(CATCH_)?TEST_CASE_METHOD" AND TestFixture )
  143. set(CTestName "${TestFixture}:${Name}")
  144. else()
  145. set(CTestName "${Name}")
  146. endif()
  147. if(PARSE_CATCH_TESTS_ADD_TARGET_IN_TEST_NAME)
  148. set(CTestName "${TestTarget}:${CTestName}")
  149. endif()
  150. # add target to labels to enable running all tests added from this target
  151. set(Labels ${TestTarget})
  152. if(TestStringsLength EQUAL 2)
  153. list(GET TestStrings 1 Tags)
  154. string(TOLOWER "${Tags}" Tags)
  155. # remove target from labels if the test is hidden
  156. if("${Tags}" MATCHES ".*\\[!?(hide|\\.)\\].*")
  157. list(REMOVE_ITEM Labels ${TestTarget})
  158. endif()
  159. string(REPLACE "]" ";" Tags "${Tags}")
  160. string(REPLACE "[" "" Tags "${Tags}")
  161. else()
  162. # unset tags variable from previous loop
  163. unset(Tags)
  164. endif()
  165. list(APPEND Labels ${Tags})
  166. set(HiddenTagFound OFF)
  167. foreach(label ${Labels})
  168. string(REGEX MATCH "^!hide|^\\." result ${label})
  169. if(result)
  170. set(HiddenTagFound ON)
  171. break()
  172. endif(result)
  173. endforeach(label)
  174. if(PARSE_CATCH_TESTS_NO_HIDDEN_TESTS AND ${HiddenTagFound} AND ${CMAKE_VERSION} VERSION_LESS "3.9")
  175. ParseAndAddCatchTests_PrintDebugMessage("Skipping test \"${CTestName}\" as it has [!hide], [.] or [.foo] label")
  176. else()
  177. ParseAndAddCatchTests_PrintDebugMessage("Adding test \"${CTestName}\"")
  178. if(Labels)
  179. ParseAndAddCatchTests_PrintDebugMessage("Setting labels to ${Labels}")
  180. endif()
  181. # Escape commas in the test spec
  182. string(REPLACE "," "\\," Name ${Name})
  183. # Work around CMake 3.18.0 change in `add_test()`, before the escaped quotes were necessary,
  184. # only with CMake 3.18.0 the escaped double quotes confuse the call. This change is reverted in 3.18.1
  185. # And properly introduced in 3.19 with the CMP0110 policy
  186. if(_cmp0110_value STREQUAL "NEW" OR ${CMAKE_VERSION} VERSION_EQUAL "3.18")
  187. ParseAndAddCatchTests_PrintDebugMessage("CMP0110 set to NEW, no need for add_test(\"\") workaround")
  188. else()
  189. ParseAndAddCatchTests_PrintDebugMessage("CMP0110 set to OLD adding \"\" for add_test() workaround")
  190. set(CTestName "\"${CTestName}\"")
  191. endif()
  192. # Handle template test cases
  193. if("${TestTypeAndFixture}" MATCHES ".*TEMPLATE_.*")
  194. set(Name "${Name} - *")
  195. endif()
  196. # Add the test and set its properties
  197. add_test(NAME "${CTestName}" COMMAND ${OptionalCatchTestLauncher} $<TARGET_FILE:${TestTarget}> ${Name} ${AdditionalCatchParameters})
  198. # Old CMake versions do not document VERSION_GREATER_EQUAL, so we use VERSION_GREATER with 3.8 instead
  199. if(PARSE_CATCH_TESTS_NO_HIDDEN_TESTS AND ${HiddenTagFound} AND ${CMAKE_VERSION} VERSION_GREATER "3.8")
  200. ParseAndAddCatchTests_PrintDebugMessage("Setting DISABLED test property")
  201. set_tests_properties("${CTestName}" PROPERTIES DISABLED ON)
  202. else()
  203. set_tests_properties("${CTestName}" PROPERTIES FAIL_REGULAR_EXPRESSION "No tests ran"
  204. LABELS "${Labels}")
  205. endif()
  206. set_property(
  207. TARGET ${TestTarget}
  208. APPEND
  209. PROPERTY ParseAndAddCatchTests_TESTS "${CTestName}")
  210. set_property(
  211. SOURCE ${SourceFile}
  212. APPEND
  213. PROPERTY ParseAndAddCatchTests_TESTS "${CTestName}")
  214. endif()
  215. endforeach()
  216. endfunction()
  217. # entry point
  218. function(ParseAndAddCatchTests TestTarget)
  219. message(DEPRECATION "ParseAndAddCatchTest: function deprecated because of possibility of missed test cases. Consider using 'catch_discover_tests' from 'Catch.cmake'")
  220. ParseAndAddCatchTests_PrintDebugMessage("Started parsing ${TestTarget}")
  221. get_target_property(SourceFiles ${TestTarget} SOURCES)
  222. ParseAndAddCatchTests_PrintDebugMessage("Found the following sources: ${SourceFiles}")
  223. foreach(SourceFile ${SourceFiles})
  224. ParseAndAddCatchTests_ParseFile(${SourceFile} ${TestTarget})
  225. endforeach()
  226. ParseAndAddCatchTests_PrintDebugMessage("Finished parsing ${TestTarget}")
  227. endfunction()