CMake, Python and Pytest

less than 1 minute read

Python can easily be used from CMake, which I use to simplify test scripts, particularly for continuous integration on platforms such as Travis-CI and AppVeyor.

Usually my Python scripts require a recent Python version, which I manage in CMakeLists.txt by:

cmake_minimum_required (VERSION 3.7)

...

enable_testing()

find_package(PythonInterp)
if(PYTHON_VERSION_STRING VERSION_GREATER_EQUAL 3.6)
  add_test(NAME MatmulPython COMMAND python matmul.py WORKING_DIRECTORY ${PROJECT_SOURCE_DIR})
endif()

That WORKING_DIRECTORY is for a CMakeLists.txt in a subdirectory. If it were a top-level Python test, perhaps using Pytest:

cmake_minimum_required (VERSION 3.7)

...


enable_testing()

find_package(PythonInterp)
if(PYTHON_VERSION_STRING VERSION_GREATER_EQUAL 3.6)
  add_test(NAME MatmulPython COMMAND pytest -v WORKING_DIRECTORY ${CMAKE_SOURCE_DIR})
endif()

That will look under tests/test*.py by default, you can specify numerous Pytest options, but usually I don’t need to.

Usage

from your bin/ or build/ directory:

cmake ..
make

and then either:

make test

or

ctest -V

Leave a Comment