[CMake] Target to build only unit tests?

Andreas Mohr andi at lisas.de
Wed Dec 21 14:12:30 EST 2011


Hi,

On Wed, Dec 21, 2011 at 11:59:13AM -0500, cmake-request at cmake.org wrote:
> Date: Wed, 21 Dec 2011 11:52:27 -0500
> From: David Cole <david.cole at kitware.com>
> Subject: Re: [CMake] Target to build only unit tests?
> To: Robert Dailey <rcdailey at gmail.com>
> Cc: CMake ML <cmake at cmake.org>
> Message-ID:
> 	<CAAdwe9XG5mOOEnNxWSx0GYLCZwqC_7TuYBY+8ZO0W4tu+-cHcg at mail.gmail.com>
> Content-Type: text/plain; charset=ISO-8859-1
> 
> On Wed, Dec 21, 2011 at 11:29 AM, Robert Dailey <rcdailey at gmail.com> wrote:
> > Is there a target generated by CMake to build ONLY unit tests? I'm using
> > Visual Studio 2008.
> >
> 
> No, there is not.
> 
> 
> > If not, is there a way I can make one?
> 
> Yes, of course. You can do anything you want with a combination of
> add_custom_command and add_custom_target.


Something worthwhile might be (whipped up quickly, untested):

# Implement include guard (e.g. reduce cmake --trace clutter)
if(UNIT_TEST_HELPERS_DEFINED)
  return()
endif(UNIT_TEST_HELPERS_DEFINED)
set(UNIT_TEST_HELPERS_DEFINED true)

if(NOT TARGET unit_tests_all)
  add_custom_target(unit_tests_all ALL)
endif(NOT TARGET unit_tests_all)

# Properly very worthwhile to have a fixed convention for unit test
# targets. Or perhaps use "unit_test_"? (...too?)
set(unit_test_targets_common_name_prefix "ut_")

function(unit_test_register_conditional _target)
  if(_target MATCHES "^${unit_test_targets_common_name_prefix}")
    add_dependencies(unit_tests_all ${_target})
  endif(_target MATCHES "^${unit_test_targets_common_name_prefix}")
function(unit_test_register_conditional _target)

function(super_power_target_post_handling _target)
  unit_test_register_conditional(${_target})
  ...something_else_that_might_be_useful...()
endfunction(super_power_target_post_handling _target)


Then push that code into a CMake Module file (to be added to
cmake/Modules/ in your source root or some such),
and do
include(ModuleName)
where needed, and call
super_power_target_post_handling(current_target)
for every target where common post-handling might be useful.

But obviously super_power_target_post_handling() shouldn't fetch
your morning cereals - it should still contain functionality
that's specific enough, to not end up with messy imprecise (unknown!) handling
that might change at any time.



And then, in case there's a build shell script, one could implement
poor man's unit test handling by doing something like:

[ ... run build stuff ... ]
pseudo_random=$(date +%s) # UNIX Epoch seconds (don't use %N nanoseconds since it's not portable, plus it's overkill)
run_tests=$((${pseudo_random} % 42)) # modulo, obviously
if [ ${run_tests} -eq 0 ]; then
  echo "INFO: running unit tests..."
  [[[ result of grep CMAKE_BUILD_COMMAND CMakeCache.txt ]]] unit_tests_all
fi

Andreas Mohr


More information about the CMake mailing list