Pytest CMake Integration
pytest-cmake is a Pytest plugin that integrates Pytest into the CMake build system, allowing `ctest` to discover and run Python tests defined in `CMakeLists.txt`. It extends Pytest with options to scan CMake build directories and manage test execution within a CMake context. The current version is 1.3.0, and the project maintains an active release cadence, with minor versions released every 1-2 months.
Common errors
-
ERROR: unrecognized arguments: --py_cmake
cause The `pytest-cmake` plugin is not installed, or Pytest cannot discover it in your current environment.fixEnsure the plugin is installed by running `pip install pytest-cmake` in the active Python environment. Verify `pytest --version` lists the plugin, or `pytest --help` shows `--py_cmake`. -
pytest_cmake.plugin.PytestCmakeError: CMake build directory '/path/to/nonexistent_build' does not exist.
cause The path provided to the `--py_cmake` argument does not point to an existing directory.fixProvide a correct path to an existing CMake build directory. This directory should typically contain `CMakeCache.txt` and other build artifacts generated by CMake. -
ModuleNotFoundError: No module named 'pytest_cmake'
cause You are attempting to directly import `pytest_cmake` in your Python code. `pytest-cmake` is a plugin designed for automatic discovery by Pytest, not for direct programmatic imports.fixRemove any `import pytest_cmake` statements. The plugin's functionality is exposed via Pytest command-line options (e.g., `--py_cmake`) or through CMake's `find_package(Pytest)` and `pytest_add_test()` functions.
Warnings
- breaking The programmatic API for `pytest-cmake` was removed in version 1.0.0. If you were previously interacting with `pytest-cmake` directly via Python imports (e.g., `import pytest_cmake`) or specific functions, this functionality is no longer available.
- gotcha The `--py_cmake` option requires a path to an existing CMake build directory. If the specified path does not exist or is not a directory, `pytest-cmake` will raise an error.
- gotcha `pytest-cmake` relies on the CMake module `FindPytest.cmake` being discoverable by CMake within your build system. If CMake cannot find this module, your `find_package(Pytest)` call in `CMakeLists.txt` will fail.
Install
-
pip install pytest-cmake
Quickstart
import pytest
import os
import shutil
# Create a dummy test file for pytest to run
test_file_content = """
# test_example.py
def test_success_with_plugin_active():
assert True
"""
with open("test_example.py", "w") as f:
f.write(test_file_content)
# Create a dummy CMake build directory for pytest-cmake to scan
certified_cmake_build_dir = "my_cmake_build_dir"
os.makedirs(certified_cmake_build_dir, exist_ok=True)
with open(os.path.join(certified_cmake_build_dir, "CMakeLists.txt"), "w") as f:
f.write("cmake_minimum_required(VERSION 3.15)\nproject(DummyProject)\n")
print(f"\nRunning pytest with --py_cmake pointing to '{certified_cmake_build_dir}'...")
print("This demonstrates the plugin is loaded and its options are recognized.")
try:
# Invoke pytest programmatically. We ignore the build directory itself
# to prevent pytest from trying to run python files directly from there,
# and include our dummy test_example.py.
# The key is passing '--py_cmake' to show the plugin is active.
exit_code = pytest.main([
f"--py_cmake={certified_cmake_build_dir}",
"--ignore", certified_cmake_build_dir, # Prevent pytest scanning the build dir for tests
"test_example.py", # Run our simple test to ensure pytest executes
"-v"
])
if exit_code == 0:
print("\nSUCCESS: pytest ran successfully, and the `pytest-cmake` plugin's options were recognized.")
else:
print(f"\nPytest finished with exit code {exit_code}. Check output above for details.")
except Exception as e:
print(f"\nAn unexpected error occurred during pytest execution: {e}")
finally:
# Clean up created files/directories
os.remove("test_example.py")
shutil.rmtree(certified_cmake_build_dir)
print("\nCleaned up temporary files and directories.")