CMake, Python and Pytest
Python can easily be used from CMake, perhaps to simplify test scripts for continuous integration.
Python scripts are managed in CMakeLists.txt
.
First, find Python interpreter:
find_package(Python COMPONENTS Interpreter REQUIRED)
Then to run a simple Python script in a CMake test:
add_test(NAME MatmulPython
COMMAND ${Python_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/matmul.py
)
To use PyTest:
add_test(NAME MatmulPython
COMMAND ${Python_EXECUTABLE} -m pytest ${CMAKE_CURRENT_SOURCE_DIR}
)
That will look under tests/test*.py
by default.
From the project directory:
cmake -B build -S .
-S .
- relative path to CMakeLists.txt e.g.
-S src
This generates the makefile, but does not compile anything, since CMake is a build script generator.
Compile:
cmake --build build --parallel
--parallel
- Compile code in parallel, if possible.
This uses the appropriate compilers and linkers to generate the executables and libraries.
Execute self-tests you’ve defined with add_test()
in CMakeLists.txt
:
ctest --test-dir build -V
If that’s too verbose, try:
ctest --test-dir build --output-on-failure
For faster testing by defaulting to running multiple tests in parallel, set CTEST_PARALLEL_LEVEL environment variable.