c++cmakectest

Customize CTest properties and labels based on test names


I am discovering gtest tests using gtest_discover_tests(...) I then want to set certain properties and labels based on the test names.

(I have done this before several years ago so I know it's possible I just don't remember the details and no longer have access to that project.)

I seem to recall this could be made using a file named CTestCustom.cmake - I have tried playing around with it and for example if I add set(CTEST_CUSTOM_POST_TEST "echo After the test") in it that is applied and printed.

However how can I use it to iterate over the discovered tests and do operations on them? How do I get hold of the test list for example? And is it even the right file?

gtest_discover_tests is documented to:

TEST_LIST var
    Make the list of tests available in the variable var, rather than the default
    <target>_TESTS. This can be useful when the same test executable is being used
    in multiple calls to gtest_discover_tests(). Note that this variable is only
    available in CTest.

However I don't seem to have access to that variable neither in my main CMakeLists.txt or in CTestCustom.cmake.


Solution

  • I found out how to do it, instead of using CTestCustom.cmake you can use the directory property TEST_INCLUDE_FILES like so:

    # Discover and store test list in ${myTests}
    ctest_discover_tests(myTestTarget TEST_LIST myTests)
    
    # Add a test include cmake script
    set_property(DIRECTORY APPEND PROPERTY
      TEST_INCLUDE_FILES ${CMAKE_CURRENT_LIST_DIR}/modifyTests.cmake
    )
    

    The modifyTests.cmake can then operate on the discovered tests like so:

    foreach(test ${myTests})
        # Just print the test name - but here you can add test properties for example
        message(NOTICE "${test}")
    endforeach()