diff --git a/cmake/Assertion.cmake b/cmake/Assertion.cmake index b8cc39d..cdd663f 100644 --- a/cmake/Assertion.cmake +++ b/cmake/Assertion.cmake @@ -64,3 +64,34 @@ function(assert_not_strequal STR1 STR2) message(FATAL_ERROR "expected string '${STR1}' not to be equal to '${STR2}'") endif() endfunction() + +# Mocks the 'message' function. +# +# If enabled, this function will mock the 'message' function by modifying its +# behavior to store the message into a list variable instead of printing it to +# the log. +# +# Arguments: +# - ENABLED: Whether to mock the 'message' function or not. +function(mock_message ENABLED) + if("${ENABLED}") + set_property(GLOBAL PROPERTY message_mocked "${ENABLED}") + + macro(message MODE MESSAGE) + get_property(ENABLED GLOBAL PROPERTY message_mocked) + if("${ENABLED}") + list(APPEND ${MODE}_MESSAGES "${MESSAGE}") + set(${MODE}_MESSAGES "${${MODE}_MESSAGES}" PARENT_SCOPE) + if("${MODE}" STREQUAL FATAL_ERROR) + return() + endif() + else() + _message("${MODE}" "${MESSAGE}") + endif() + endmacro() + + function(mock_message ENABLED) + set_property(GLOBAL PROPERTY message_mocked "${ENABLED}") + endfunction() + endif() +endfunction() diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 3323c91..30d8c53 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -20,4 +20,5 @@ add_cmake_test( "Assert an undefined variable" "Assert equal strings" "Assert unequal strings" + "Mock message" ) diff --git a/test/cmake/AssertionTest.cmake b/test/cmake/AssertionTest.cmake index 544e719..a574eb8 100644 --- a/test/cmake/AssertionTest.cmake +++ b/test/cmake/AssertionTest.cmake @@ -27,6 +27,30 @@ function(test_assert_unequal_strings) assert_not_strequal("some string" "some other string") endfunction() +function(test_mock_message) + mock_message(ON) + + function(test) + message(WARNING "some warning message") + message(WARNING "some other warning message") + message(ERROR "some error message") + message(FATAL_ERROR "some fatal error message") + message(ERROR "some other error message") + endfunction() + test() + + mock_message(OFF) + + assert_defined(WARNING_MESSAGES) + assert_strequal("${WARNING_MESSAGES}" "some warning message;some other warning message") + + assert_defined(ERROR_MESSAGES) + assert_strequal("${ERROR_MESSAGES}" "some error message") + + assert_defined(FATAL_ERROR_MESSAGES) + assert_strequal("${FATAL_ERROR_MESSAGES}" "some fatal error message") +endfunction() + if(NOT DEFINED TEST_COMMAND) message(FATAL_ERROR "The 'TEST_COMMAND' variable should be defined") elseif(NOT COMMAND test_${TEST_COMMAND})