create_executable.py


Overview

`create_executable.py` is a utility script designed to automate the creation of a standalone executable that embeds a pytest test runner. It leverages **PyInstaller** to package a Python script (`runtests_script.py`) into a single executable file. This executable, when run, will execute tests using pytest.

The script dynamically determines the necessary hidden imports for pytest to work correctly in the frozen executable and passes these to PyInstaller to ensure all required modules are included. This approach ensures that the resulting executable can run tests without missing dependencies, which is a common issue when freezing Python applications that rely on dynamic imports.


Detailed Explanation

Script Behavior

This file is intended to be run as a standalone script (`python create_executable.py`). It does not define any classes or functions but executes logic within the `if __name__ == "__main__":` block.


Main Process

if __name__ == "__main__":
    import subprocess
    import pytest

    hidden = []
    for x in pytest.freeze_includes():
        hidden.extend(["--hidden-import", x])
    hidden.extend(["--hidden-import", "distutils"])
    args = ["pyinstaller", "--noconfirm", *hidden, "runtests_script.py"]
    subprocess.check_call(" ".join(args), shell=True)

Parameters and Return Values

This script does not define functions or classes and therefore does not have parameters or return values. Instead, its behavior is driven entirely by the build process it triggers.


Usage Example

To create the pytest runner executable, run this script from the command line:

python create_executable.py

This command will invoke PyInstaller with the appropriate hidden imports to build a standalone executable from `runtests_script.py`.


Important Implementation Details


Interaction with Other Parts of the System


Visual Diagram

flowchart TD
    A[Start: Run create_executable.py] --> B[Import subprocess and pytest]
    B --> C[Call pytest.freeze_includes()]
    C --> D[Build hidden import arguments list]
    D --> E[Add --hidden-import distutils]
    E --> F[Form PyInstaller command]
    F --> G[Execute PyInstaller command via subprocess]
    G --> H{Success?}
    H -- Yes --> I[Executable created successfully]
    H -- No --> J[Raise error and stop]

Summary

`create_executable.py` is a straightforward but crucial build utility that automates the packaging of a pytest-based test runner executable using PyInstaller. It dynamically resolves hidden imports necessary for pytest to function in frozen form, reducing manual configuration errors. This enables developers to distribute or run tests in environments where Python and pytest may not be installed, improving portability and ease of test execution.