kneifftools / tests /_cli_helpers.py
kneiff's picture
chore(history)!: publish anonymous repository root
2857cf3
Raw
History Blame Contribute Delete
2.62 kB
from __future__ import annotations
import os
import sys
from pathlib import Path
from typing import Any
from click.testing import Result
import pytest
from typer.testing import CliRunner
from kneiff.cli.app import app
from kneiff.config import CONFIG_SECTIONS
from kneiff.project_scaffold import ensure_project_resources
def invoke_cli(runner: CliRunner, args: list[str], **kwargs: Any) -> Result:
"""Run a CLI command with process args matching the installed executable.
:param runner: Typer test runner used for the invocation.
:param args: CLI tokens after the executable name.
:param kwargs: Additional ``CliRunner.invoke`` options.
:return: Captured command result.
"""
original_argv = sys.argv[:]
original_env = os.environ.copy()
sys.argv = ["knf", *args]
try:
return runner.invoke(app, args, **kwargs)
finally:
os.environ.clear()
os.environ.update(original_env)
sys.argv = original_argv
def set_test_config_home(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
"""Point AppRC registry lookups at this test's temporary config tree.
:param monkeypatch: Pytest environment patching helper.
:param tmp_path: Per-test temporary directory.
:return: None.
"""
config_home = tmp_path / "config"
monkeypatch.setenv("XDG_CONFIG_HOME", str(config_home))
monkeypatch.delenv("KNF_APPRC_TOML", raising=False)
def set_test_storage(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path:
"""Create and select one isolated AppRC storage root.
:param monkeypatch: Pytest environment patching helper.
:param tmp_path: Per-test temporary directory.
:return: Selected storage root.
"""
set_test_config_home(monkeypatch, tmp_path)
for owner in CONFIG_SECTIONS:
for field in owner.fields:
monkeypatch.delenv(owner.env_key(field.name), raising=False)
storage_root = tmp_path
(storage_root / ".env.apprc-storage").touch()
monkeypatch.setenv("KNF_STORAGE", str(storage_root))
return storage_root
def set_test_project_storage(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> Path:
"""Create and select a complete shallow Kneiff project scaffold.
:param monkeypatch: Pytest environment patching helper.
:param tmp_path: Per-test temporary directory.
:return: Selected project root.
"""
storage_root = set_test_storage(monkeypatch, tmp_path)
ensure_project_resources(
storage_root,
activation_token="Test_Character",
species_token="test_species",
)
return storage_root