Integrating with CMake

Once installed, the package integration within a CMake project can be done using the find_package function:

find_package(Pytest)

A specific range of versions can be targeted:

# Request Pytest version 7.2.0.
find_package(Pytest 7.2.0 EXACT REQUIRED)

# Request Pytest between version 6.0.0 and 7.2.0 included.
find_package(Pytest 6.0.0...7.2.0 REQUIRED)

# Request any version of Pytest over 4.6.11.
find_package(Pytest 4.6.11 REQUIRED)

Finding Configuration

When Python is used from its standard system location, CMake should be able to discover the newly installed configuration automatically using its Config Mode Search Procedure.

Warning

The CMAKE_FIND_USE_SYSTEM_ENVIRONMENT_PATH option should not be set to False.

When using a Python virtual environment, or if Python is installed in a non-standard location, the CMAKE_PREFIX_PATH environment variable (or CMake option) can be used to guide the discovery process:

cmake -S . -B ./build -D "CMAKE_PREFIX_PATH=/path/to/python/prefix"

This is also necessary when installing the configuration in the Python user directory:

pip install pytest-cmake --user

Building and testing example project

An example project has been made available to test the configuration.

Ensure that a minimal version of Boost Python is available, and install Pytest with its CMake configuration as described in the previous section. Then build the example:

cmake -S ./example -B ./build
cmake --build ./build

Finally, run the tests as follows:

ctest --test-dir ./build -VV

Finding Module

The package integration within a CMake project can also be done using the FindPytest.cmake module. The CMake files can be copied into a new project, or the following code can be added before invoking the find_package function:

set(pytest_url https://github.com/python-cmake/pytest-cmake/archive/main.zip)

# Fetch CMake files from the main branch of the Github repository
file(DOWNLOAD ${pytest_url} ${CMAKE_BINARY_DIR}/pytest.zip)
file(
    ARCHIVE_EXTRACT INPUT ${CMAKE_BINARY_DIR}/pytest.zip
    DESTINATION ${CMAKE_BINARY_DIR}
    PATTERNS "*.cmake"
)

# Expand the module path variable to discover the `FindPytest.cmake` module.
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_BINARY_DIR}/pytest-cmake-main/cmake)

Warning

It is strongly recommended to use the Pip installation over this method.