Skip to content

Testing

testing

Public testing utilities for flepimop2.

external_provider_package(parent_directory, copy_files=None, dependencies=None, project_name='example-provider', project_requires_python='>=3.11')

Set up an external provider package and install it into a fresh venv.

Parameters:

Name Type Description Default
parent_directory Path

Directory in which to set up the provider package and venv.

required
copy_files dict[Path, Path] | None

Optional mapping of source files to destination paths within parent_directory.

None
dependencies list[str] | None

Optional list of dependencies to include in the provider package. If omitted, defaults to ["flepimop2"].

None
project_name str

Optional name for the provider package. Defaults to "example-provider".

'example-provider'
project_requires_python str

Optional Python version specifier for the provider package. Defaults to ">=3.11".

'>=3.11'

Returns:

Type Description
str

The python executable path from the newly created venv.

Source code in src/flepimop2/testing.py
def external_provider_package(
    parent_directory: Path,
    copy_files: dict[Path, Path] | None = None,
    dependencies: list[str] | None = None,
    project_name: str = "example-provider",
    project_requires_python: str = ">=3.11",
) -> str:
    """
    Set up an external provider package and install it into a fresh venv.

    Args:
        parent_directory: Directory in which to set up the provider package and venv.
        copy_files: Optional mapping of source files to destination paths
            within `parent_directory`.
        dependencies: Optional list of dependencies to include in the provider
            package. If omitted, defaults to `["flepimop2"]`.
        project_name: Optional name for the provider package. Defaults to
            "example-provider".
        project_requires_python: Optional Python version specifier for the provider
            package. Defaults to ">=3.11".

    Returns:
        The python executable path from the newly created venv.

    """
    parent_directory = parent_directory.resolve()
    python = _which_python()
    venv_python = _create_venv(python, parent_directory)

    external_provider_root = parent_directory / "external_provider"
    external_provider_root.mkdir(parents=True, exist_ok=True)
    (parent_directory / "model_output").mkdir(parents=True, exist_ok=True)

    dependencies_text = ", ".join(
        f'"{dep}"'
        for dep in _resolve_dependencies(dependencies, require_flepimop2=True)
    )
    pyproject_text = f"""\
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "{project_name}"
version = "0.0.1"
requires-python = "{project_requires_python}"
dependencies = [{dependencies_text}]

[tool.hatch.build.targets.wheel]
# Ensure implicit namespace packages under flepimop2.* are included.
packages = ["src/flepimop2"]
"""
    (external_provider_root / "pyproject.toml").write_text(pyproject_text)

    # Ensure namespace package directories exist even without __init__.py
    (external_provider_root / "src" / "flepimop2").mkdir(parents=True, exist_ok=True)

    copy_files = copy_files or {}
    for src, dest in copy_files.items():
        dest_path = parent_directory / dest
        dest_path.parent.mkdir(parents=True, exist_ok=True)
        dest_path.write_text(src.read_text())

    subprocess.run(  # noqa: S603
        [
            venv_python,
            "-m",
            "pip",
            "install",
            str(external_provider_root),
        ],
        capture_output=True,
        text=True,
        cwd=parent_directory,
        check=True,
    )
    return venv_python

flepimop2_run(action, args=None, cwd=None)

Run a flepimop2 CLI command via subprocess.

Parameters:

Name Type Description Default
action str

CLI action name (e.g. "process", "simulate", etc). For a full list of available actions, see flepimop2 --help.

required
args list[str] | None

Additional command arguments to pass to the CLI command.

None
cwd Path | None

Optional working directory for the command.

None

Returns:

Type Description
CompletedProcess[str]

The completed process from running the CLI.

Raises:

Type Description
ValueError

If the action is empty.

Source code in src/flepimop2/testing.py
def flepimop2_run(
    action: str,
    args: list[str] | None = None,
    cwd: Path | None = None,
) -> subprocess.CompletedProcess[str]:
    """
    Run a flepimop2 CLI command via subprocess.

    Args:
        action: CLI action name (e.g. "process", "simulate", etc). For a full list of
            available actions, see `flepimop2 --help`.
        args: Additional command arguments to pass to the CLI command.
        cwd: Optional working directory for the command.

    Returns:
        The completed process from running the CLI.

    Raises:
        ValueError: If the action is empty.

    """
    if not action:
        msg = "Action must be a non-empty string"
        raise ValueError(msg)

    args = args or []
    if cwd is not None and ((venv_bin := cwd / ".venv" / "bin" / "flepimop2").exists()):
        command = [str(venv_bin), action, *args]
    else:
        command = ["flepimop2", action, *args]

    return subprocess.run(  # noqa: S603
        command,
        capture_output=True,
        text=True,
        cwd=cwd,
        check=True,
    )

project_skeleton(parent_directory, copy_files=None, dependencies=None)

Create a project skeleton in parent_directory and optionally copy files.

Parameters:

Name Type Description Default
parent_directory Path

Directory in which to create the project skeleton and venv.

required
copy_files dict[Path, Path] | None

Optional mapping of source files to destination paths within parent_directory.

None
dependencies list[str] | None

Optional list of dependencies to install into the venv.

None

Returns:

Type Description
str

The python executable path from the newly created venv.

Source code in src/flepimop2/testing.py
def project_skeleton(
    parent_directory: Path,
    copy_files: dict[Path, Path] | None = None,
    dependencies: list[str] | None = None,
) -> str:
    """
    Create a project skeleton in ``parent_directory`` and optionally copy files.

    Args:
        parent_directory: Directory in which to create the project skeleton and venv.
        copy_files: Optional mapping of source files to destination paths
            within ``parent_directory``.
        dependencies: Optional list of dependencies to install into the venv.

    Returns:
        The python executable path from the newly created venv.

    """
    parent_directory = parent_directory.resolve()
    python = _which_python()
    venv_python = _create_venv(python, parent_directory)

    if dependencies := _resolve_dependencies(dependencies, require_flepimop2=False):
        subprocess.run(  # noqa: S603
            [venv_python, "-m", "pip", "install", *dependencies],
            capture_output=True,
            text=True,
            cwd=parent_directory,
            check=True,
        )

    flepimop2_run("skeleton", args=[], cwd=parent_directory)

    copy_files = copy_files or {}
    for src, dest in copy_files.items():
        dest_path = parent_directory / dest
        dest_path.parent.mkdir(parents=True, exist_ok=True)
        dest_path.write_text(src.read_text())

    return venv_python