Skip to content

Commit

Permalink
feat: add mock message function (#8)
Browse files Browse the repository at this point in the history
* feat: add mock message function

* feat: allow enable or disable message mock

* test: add test for testing mock message function
  • Loading branch information
threeal authored May 4, 2024
1 parent 49ea225 commit 709b172
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
31 changes: 31 additions & 0 deletions cmake/Assertion.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -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()
1 change: 1 addition & 0 deletions test/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,5 @@ add_cmake_test(
"Assert an undefined variable"
"Assert equal strings"
"Assert unequal strings"
"Mock message"
)
24 changes: 24 additions & 0 deletions test/cmake/AssertionTest.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -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})
Expand Down

0 comments on commit 709b172

Please sign in to comment.