CMake, Python and Pytest

Python can easily be used from CMake, which I use to simplify test scripts, particularly for continuous integration.

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

cmake_minimum_required(VERSION 3.12)
enable_testing()

find_package(Python3 COMPONENTS Interpreter)
if(Python3_Interpreter_FOUND)
  add_test(NAME MatmulPython COMMAND Python3::Interpreter 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.12)
enable_testing()


find_package(Python3 COMPONENTS Interpreter)
if(Python3_Interpreter_FOUND)
  add_test(NAME MatmulPython COMMAND Python3::Interpreter -m pytest -rsv 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

  1. from your bin/ or build/ directory:
    cmake ..
    

    This generates the makefile, but does not compile anything, since CMake is a build script generator.

  2. Compile
    cmake --build .
    

    This uses the appropriate compilers and linkers to generate the executables and libraries.

  3. Execute self-tests you’ve defined with add_test() in CMakeLists.txt:
    ctest -V
    

Tags: , ,

Categories: ,

Written by Michael Hirsch, Ph.D. //

Comments