Pytest CMake Integration

1.3.0 · active · verified Fri Apr 17

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

Warnings

Install

Quickstart

This quickstart demonstrates how to programmatically invoke Pytest using `pytest.main()` while activating the `pytest-cmake` plugin's `--py_cmake` option. It shows that the plugin is correctly installed and its command-line arguments are recognized by Pytest. For actual integration with CMake tests, your `CMakeLists.txt` would need to use `find_package(Pytest)` and `pytest_add_test()`.

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.")

view raw JSON →