CTest set environment variable

It’s often useful to set per-test environment variables in CMake’s CTest testing frontend. The environment variables appear and disappear with the start and end of each test, in isolation from any other tests that may be running in parallel. This is accomplished via CMake test properties ENVIRONMENT and ENVIRONMENT_MODIFICATION.

Example: set environment variable FOO=1 for a test “bar” like:

set_property(TEST bar PROPERTY ENVIRONMENT "FOO=1")

multiple variables are set with a CMake list (semicolon delimited) like:

set_property(TEST bar PROPERTY ENVIRONMENT "FOO=1;BAZ=0")

Here comes an issue. In general, Windows needs DLLs to be on the current working directory or in environment variable PATH. We handle this by a script that appends to PATH for CTest on Windows:

# works for Unix, Windows, etc.
cmake_minimum_required(VERSION 3.22)
project(WindowsPath LANGUAGES C)
find_library(ZLIB REQUIRED)
add_executable(hello hello.c)
target_link_libraries(hello PRIVATE ZLIB::ZLIB)
add_test(NAME unit_hello COMMAND hello)
if(WIN32)
set_property(TEST unit_hello PROPERTY ENVIRONMENT_MODIFICATION "PATH=path_list_append:/path/to/dlls")
endif()
view raw CMakeLists.txt hosted with ❤ by GitHub
#include "zlib.h"
int main(void) { return 0; }
view raw hello.c hosted with ❤ by GitHub

In Python likewise set/unset environment variables within tests using PyTest monkeypatch fixture.