[CMake] Custom target for running tests as part of the build

Steve Lorimer steve.lorimer at gmail.com
Tue Aug 23 11:20:13 EDT 2016


We have several unit tests which we would like to be run as part of our
build process.

To achieve this I have a helper script which creates a custom command that
runs the test, and if successful, creates a file "test_name.passed".

I then add a custom target "test_name.run" which depends on
"test_name.passed".

The idea is that if "test_name.passed" doesn't exist or is older than
"test_name", the custom command will be run.

Builds will continue to run the custom command until the test passes.
Subsequent builds won't call the custom command, so the test won't be run
if it doesn't need to.

Here is the script:

    # create test.passed command which runs the test and creates a sentinel
file if it passes
    add_custom_command(
        OUTPUT  ${TEST_NAME}.passed
        COMMAND $<TARGET_FILE:${TEST_NAME}>
        COMMAND ${CMAKE_COMMAND} -E touch ${TEST_NAME}.passed
        DEPENDS ${TEST_NAME}
        )

    # create test.run module which depends on test.passed
    add_custom_target(${TEST_NAME}.run
        ALL
        DEPENDS ${TEST_NAME}.passed
        )

The problem is that our tests often log a tonne of information to stdout,
and it makes for a very noisy build.

I'm trying to now capture stdout to a file, and only in the event of a
failure, display the test output.

My first attempt was to try a Bash shell scripting syntax - capture stdout
into a file and when the exit status is an error, cat the file.

    add_custom_command(
        OUTPUT  ${TEST_NAME}.passed
        COMMAND $<TARGET_FILE:${TEST_NAME}> > ${TEST_NAME}.output || cat
${TEST_NAME}.output
        COMMAND ${CMAKE_COMMAND} -E touch ${TEST_NAME}.passed
        DEPENDS ${TEST_NAME}
        )

This doesn't work, as even if the test fails I am getting the sentinal
"test_name.passed" file created, which means the next time I try to build
it thinks the test passed.

Is there a way to achieve what I want? Bonus points for a cross-platform
method, but if it has to be Linux only, then so be it.

Thanks in advance
Steve
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://public.kitware.com/pipermail/cmake/attachments/20160823/efd4ef04/attachment.html>


More information about the CMake mailing list