Project: pygitweb

053f925 """Tests for project actions API."""
from __future__ import annotations
import stat
import sys
from pathlib import Path
import pytest
from pygittools.actions import (
73c9c30 Action,
ActionSet,
ActionSpec,
ProjectActions,
04f3c66 RunParallel,
RunTask,
8fa7f0b _resolve_usage,
8ac8a11 catalog_registry,
73c9c30 find_project_root,
9f80683 load_action_catalog,
73c9c30 load_action_sets,
load_action_specs,
9f80683 load_mise_action_specs,
73c9c30 project_actions,
project_venv_python,
04f3c66 root_visible_specs,
9f80683 run_action,
8fa7f0b run_action_file,
9f80683 run_mise_task,
04f3c66 set_registry,
8ac8a11 visible_specs,
053f925 )
89fd393 def _write_pyproject(root: Path, tasks_toml: str) -> None:
"""Write a demo pyproject; ``tasks_toml`` is full ``[tool.pgt.tasks…]`` text."""
73c9c30 (root / "pyproject.toml").write_text(
89fd393 f'[project]\nname = "demo"\nversion = "0"\n\n{tasks_toml}\n',
73c9c30 encoding="utf-8",
)
053f925
def _make_venv(root: Path) -> Path:
73c9c30 venv = root / ".venv"
bin_dir = venv / "bin"
bin_dir.mkdir(parents=True)
python = bin_dir / "python"
python.symlink_to(sys.executable)
return python
053f925
def test_find_project_root(tmp_path: Path) -> None:
73c9c30 nested = tmp_path / "a" / "b"
nested.mkdir(parents=True)
(tmp_path / "pyproject.toml").write_text("[project]\nname='x'\n", encoding="utf-8")
89fd393 (nested / "actions.toml").write_text("[local.tasks]\n", encoding="utf-8")
73c9c30 assert find_project_root(nested) == tmp_path.resolve()
assert find_project_root(tmp_path) == tmp_path.resolve()
053f925
966394d def test_find_project_root_actions_toml_only(tmp_path: Path) -> None:
73c9c30 nested = tmp_path / "a" / "b"
nested.mkdir(parents=True)
89fd393 (tmp_path / "actions.toml").write_text("[quality.tasks]\n", encoding="utf-8")
73c9c30 assert find_project_root(nested) == tmp_path.resolve()
966394d
9f80683 def test_find_project_root_mise_toml_only(tmp_path: Path) -> None:
nested = tmp_path / "a" / "b"
nested.mkdir(parents=True)
(tmp_path / "mise.toml").write_text("[tasks.hello]\nrun = 'echo hi'\n", encoding="utf-8")
assert find_project_root(nested) == tmp_path.resolve()
89fd393 def test_load_action_specs_task_tables(tmp_path: Path) -> None:
73c9c30 _write_pyproject(
tmp_path,
89fd393 """
[tool.pgt.tasks.lint]
file = "scripts/lint.py"
[tool.pgt.tasks.test]
file = "scripts/test.py"
""",
73c9c30 )
specs = load_action_specs(tmp_path)
assert specs == [
8fa7f0b ActionSpec(name="lint", file="scripts/lint.py"),
ActionSpec(name="test", file="scripts/test.py"),
73c9c30 ]
053f925
89fd393 def test_load_action_specs_string_shorthand(tmp_path: Path) -> None:
_write_pyproject(tmp_path, '[tool.pgt.tasks]\nlint = "ruff check"\n')
assert load_action_specs(tmp_path) == [ActionSpec(name="lint", run=("ruff check",))]
def test_load_action_specs_rejects_actions_array(tmp_path: Path) -> None:
(tmp_path / "pyproject.toml").write_text(
'[project]\nname = "demo"\nversion = "0"\n\n[tool.pgt]\nactions = [{ name = "lint", file = "x.py" }]\n',
encoding="utf-8",
)
with pytest.raises(ValueError, match="uses 'actions'"):
load_action_specs(tmp_path)
053f925
8fa7f0b def test_load_action_specs_rejects_task_level_args(tmp_path: Path) -> None:
73c9c30 _write_pyproject(
tmp_path,
89fd393 """
[tool.pgt.tasks.py]
file = "scripts/pytest_version.py"
args = ["3.12", "-q"]
""",
73c9c30 )
8fa7f0b with pytest.raises(ValueError, match="task-level 'args'"):
load_action_specs(tmp_path)
def test_load_action_specs_rejects_script_key(tmp_path: Path) -> None:
89fd393 _write_pyproject(
tmp_path,
"""
[tool.pgt.tasks.py]
script = "x.py"
""",
)
8fa7f0b with pytest.raises(ValueError, match="uses 'script'"):
load_action_specs(tmp_path)
966394d
8ac8a11 def test_load_action_specs_description_depends_hide(tmp_path: Path) -> None:
_write_pyproject(
tmp_path,
89fd393 """
[tool.pgt.tasks.unit]
file = "unit.py"
description = "fast tests"
hide = true
[tool.pgt.tasks.check]
file = "check.py"
depends = ["unit"]
description = "all checks"
""",
8ac8a11 )
assert load_action_specs(tmp_path) == [
8fa7f0b ActionSpec(name="unit", file="unit.py", description="fast tests", hide=True),
8ac8a11 ActionSpec(
name="check",
8fa7f0b file="check.py",
8ac8a11 description="all checks",
depends=("unit",),
),
]
assert [spec.name for spec in visible_specs(load_action_specs(tmp_path))] == ["check"]
04f3c66 def test_workspace_action_groups() -> None:
73c9c30 root = Path(__file__).resolve().parents[3]
sets = {item.name: item for item in load_action_sets(root)}
f84f28d assert set(sets) == {"default", "test-versions", "all-tests"}
04f3c66 by_name = {spec.name: spec for spec in sets["default"].specs}
8fa7f0b assert by_name["pytest-pygittools"].file == "scripts/pytest_impacted.py"
assert by_name["pytest-pygittools"].args == ()
assert 'default="pygittools"' in by_name["pytest-pygittools"].usage
assert "\n" in by_name["pytest-pygittools"].usage
assert by_name["pytest-pygitweb"].file == "scripts/pytest_impacted.py"
assert by_name["pytest-pygitweb"].args == ()
assert 'default="pygitweb"' in by_name["pytest-pygitweb"].usage
assert 'default="--impacted-tests-dir pygitweb"' in by_name["pytest-pygitweb"].usage
assert "\n" in by_name["pytest-pygitweb"].usage
tools_env, _, tools_early = _resolve_usage(by_name["pytest-pygittools"])
assert tools_early is None
assert tools_env["usage_module"] == "pygittools"
web_env, _, web_early = _resolve_usage(by_name["pytest-pygitweb"])
assert web_early is None
assert web_env["usage_module"] == "pygitweb"
assert web_env["usage_pytest_args"] == "--impacted-tests-dir pygitweb"
f84f28d versions = sets["test-versions"]
8fa7f0b assert [spec.name for spec in versions.specs] == [
"pytest-3-12",
"pytest-3-13",
"pytest-3-14",
"pytest-3-15",
]
assert all(spec.args == () for spec in versions.specs)
expected_defaults = ["3.12", "3.13", "3.14", "3.15"]
assert all(
f84f28d f'default="{version}"' in spec.usage and "\n" in spec.usage and "[pytest-args]" in spec.usage
for spec, version in zip(versions.specs, expected_defaults, strict=True)
)
assert [spec.description for spec in versions.specs] == [
"nox tests-3.12",
"nox tests-3.13",
"nox tests-3.14",
"nox tests-3.15",
]
8fa7f0b assert {spec.file for spec in versions.specs} == {"scripts/pytest_version.py"}
04f3c66 all_tests = sets["all-tests"]
8fa7f0b assert [spec.name for spec in all_tests.specs] == ["pytest-all"]
assert all_tests.specs[0].file == "scripts/pytest.py"
assert all_tests.specs[0].args == ()
assert 'default="--playwright --js-tests"' in all_tests.specs[0].usage
04f3c66 assert [spec.name for spec in root_visible_specs(sets["default"].specs)] == [
8fa7f0b "ruff-check",
"ruff-format",
04f3c66 "mypy",
8fa7f0b "pytest-pygittools",
"pytest-pygitweb",
04f3c66 ]
966394d
8fa7f0b def test_run_action_file_passes_args(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
path = tmp_path / "echo_args.py"
path.write_text("print('unused')\n", encoding="utf-8")
73c9c30 bin_dir = tmp_path / ".venv" / "bin"
win_dir = tmp_path / ".venv" / "Scripts"
bin_dir.mkdir(parents=True)
win_dir.mkdir()
(bin_dir / "python").write_text("", encoding="utf-8")
(win_dir / "python.exe").write_text("", encoding="utf-8")
captured: list[list[str]] = []
class _Proc:
returncode = 0
stdout = "ok"
stderr = ""
def fake_run(cmd: list[str], **kwargs: object) -> _Proc:
del kwargs
captured.append(list(cmd))
return _Proc()
monkeypatch.setattr("pygittools.actions.subprocess.run", fake_run)
8fa7f0b spec = ActionSpec(name="py", file="echo_args.py", args=("3.12", "-q"))
73c9c30 ok, message = ProjectActions(tmp_path, [spec]).action("py")
python = project_venv_python(tmp_path)
assert python is not None
assert ok is True
assert message == "ok"
8fa7f0b assert captured == [[str(python), str(path.resolve()), "3.12", "-q"]]
966394d
bae6568 def test_load_action_specs_usage(tmp_path: Path) -> None:
_write_pyproject(
tmp_path,
89fd393 """
[tool.pgt.tasks.py]
file = "x.py"
usage = 'arg "<version>" default="3.12"'
raw_args = true
""",
bae6568 )
assert load_action_specs(tmp_path) == [
ActionSpec(
name="py",
8fa7f0b file="x.py",
usage='arg "<version>" default="3.12"',
bae6568 raw_args=True,
),
]
8fa7f0b def test_run_action_usage_defaults_without_args(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
path = tmp_path / "echo_env.py"
path.write_text(
"import os\nprint(os.environ['usage_version'])\n",
encoding="utf-8",
)
bin_dir = tmp_path / ".venv" / "bin"
win_dir = tmp_path / ".venv" / "Scripts"
bin_dir.mkdir(parents=True)
win_dir.mkdir()
(bin_dir / "python").write_text("", encoding="utf-8")
(win_dir / "python.exe").write_text("", encoding="utf-8")
captured_env: dict[str, str] = {}
class _Proc:
returncode = 0
stdout = "3.12"
stderr = ""
def fake_run(cmd: list[str], **kwargs: object) -> _Proc:
del cmd
env = kwargs["env"]
assert isinstance(env, dict)
captured_env.update({str(k): str(v) for k, v in env.items()})
return _Proc()
monkeypatch.setattr("pygittools.actions.subprocess.run", fake_run)
spec = ActionSpec(
name="py",
file="echo_env.py",
usage='arg "<version>" default="3.12"',
)
ok, message = run_action(tmp_path, spec)
assert ok is True
assert message == "3.12"
assert captured_env["usage_version"] == "3.12"
bae6568 def test_run_action_sets_usage_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
8fa7f0b path = tmp_path / "echo_env.py"
path.write_text(
bae6568 "import os\nprint(f\"v={os.environ['usage_version']} a={os.environ.get('usage_extra', '')}\")\n",
encoding="utf-8",
)
bin_dir = tmp_path / ".venv" / "bin"
bin_dir.mkdir(parents=True)
(bin_dir / "python").write_text("", encoding="utf-8")
(tmp_path / ".venv" / "Scripts").mkdir()
(tmp_path / ".venv" / "Scripts" / "python.exe").write_text("", encoding="utf-8")
captured_env: dict[str, str] = {}
captured_cmd: list[str] = []
class _Proc:
returncode = 0
stdout = "v=3.12 a="
stderr = ""
def fake_run(cmd: list[str], **kwargs: object) -> _Proc:
nonlocal captured_env, captured_cmd
captured_cmd = list(cmd)
env = kwargs["env"]
assert isinstance(env, dict)
captured_env = {str(k): str(v) for k, v in env.items()}
return _Proc()
monkeypatch.setattr("pygittools.actions.subprocess.run", fake_run)
monkeypatch.setenv("usage_leak", "nope")
spec = ActionSpec(
name="py",
8fa7f0b file="echo_env.py",
bae6568 usage='arg "<version>"',
args=("3.12",),
)
ok, message = ProjectActions(tmp_path, [spec]).action("py")
python = project_venv_python(tmp_path)
assert python is not None
assert ok is True
assert message == "v=3.12 a="
8fa7f0b assert captured_cmd == [str(python), str(path.resolve())]
bae6568 assert captured_env["usage_version"] == "3.12"
assert "usage_leak" not in captured_env
def test_run_action_usage_invalid_choice(tmp_path: Path) -> None:
spec = ActionSpec(
name="deploy",
run="echo should-not-run",
usage='arg "<environment>" { choices "dev" "prod" }',
args=("qa",),
)
ok, message = run_action(tmp_path, spec)
assert ok is False
assert "Invalid choice" in message
def test_run_action_usage_help(tmp_path: Path) -> None:
spec = ActionSpec(
name="deploy",
description="Deploy application",
run="echo should-not-run",
usage='arg "<environment>" help="Target environment"',
args=("--help",),
)
ok, message = run_action(tmp_path, spec)
assert ok is True
assert "Deploy application" in message
assert "Usage: deploy" in message
def test_run_shell_receives_usage_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
captured_env: dict[str, str] = {}
class _Proc:
returncode = 0
stdout = "staging"
stderr = ""
def fake_run(cmd: list[str], **kwargs: object) -> _Proc:
del cmd
env = kwargs["env"]
assert isinstance(env, dict)
captured_env.clear()
captured_env.update({str(k): str(v) for k, v in env.items()})
return _Proc()
monkeypatch.setattr("pygittools.actions.subprocess.run", fake_run)
spec = ActionSpec(
name="deploy",
run='echo "${usage_environment?}"',
usage='arg "<environment>"',
args=("staging",),
)
ok, message = run_action(tmp_path, spec)
assert ok is True
assert message == "staging"
assert captured_env["usage_environment"] == "staging"
053f925 def test_load_action_specs_invalid(tmp_path: Path) -> None:
89fd393 _write_pyproject(tmp_path, "[tool.pgt]\ntasks = []\n")
with pytest.raises(ValueError, match="must be a table of tasks"):
73c9c30 load_action_specs(tmp_path)
053f925
966394d def test_load_action_sets_from_pyproject_and_actions_toml(tmp_path: Path) -> None:
89fd393 _write_pyproject(
tmp_path,
"""
[tool.pgt.tasks.lint]
file = "scripts/lint.py"
[tool.pgt.sets.release.tasks.build]
file = "scripts/build.py"
966394d """,
73c9c30 )
(tmp_path / "actions.toml").write_text(
"""
966394d name = "tools"
89fd393 [tasks.fmt]
8fa7f0b file = "scripts/fmt.py"
966394d
89fd393 [quality.tasks.test]
file = "scripts/test.py"
966394d """,
73c9c30 encoding="utf-8",
)
assert load_action_sets(tmp_path) == [
8fa7f0b ActionSet(name="default", specs=(ActionSpec(name="lint", file="scripts/lint.py"),)),
ActionSet(name="release", specs=(ActionSpec(name="build", file="scripts/build.py"),)),
ActionSet(name="tools", specs=(ActionSpec(name="fmt", file="scripts/fmt.py"),)),
ActionSet(name="quality", specs=(ActionSpec(name="test", file="scripts/test.py"),)),
73c9c30 ]
966394d
def test_load_action_sets_named_pyproject_flat_set(tmp_path: Path) -> None:
73c9c30 (tmp_path / "pyproject.toml").write_text(
"""
966394d [tool.pgt]
name = "checks"
89fd393
[tool.pgt.tasks.lint]
file = "lint.py"
966394d """,
73c9c30 encoding="utf-8",
)
sets = load_action_sets(tmp_path)
assert [item.name for item in sets] == ["checks"]
966394d
04f3c66 def test_load_action_sets_duplicate_set_name(tmp_path: Path) -> None:
89fd393 _write_pyproject(
tmp_path,
"""
[tool.pgt.tasks.lint]
file = "lint.py"
""",
)
73c9c30 (tmp_path / "actions.toml").write_text(
89fd393 '[default.tasks.other]\nfile = "other.py"\n',
73c9c30 encoding="utf-8",
)
with pytest.raises(ValueError, match="Duplicate action set name: default"):
load_action_sets(tmp_path)
966394d
def test_load_action_sets_invalid_table(tmp_path: Path) -> None:
73c9c30 (tmp_path / "actions.toml").write_text('quality = "nope"\n', encoding="utf-8")
with pytest.raises(ValueError, match="unexpected key"):
load_action_sets(tmp_path)
966394d
053f925 def test_project_actions_is_action(tmp_path: Path) -> None:
89fd393 _write_pyproject(tmp_path, '[tool.pgt.tasks.ok]\nfile = "ok.py"\n')
73c9c30 runner = project_actions(tmp_path)
assert isinstance(runner, Action)
assert issubclass(ProjectActions, Action)
053f925
@pytest.mark.skipif(sys.platform == "win32", reason="symlink venv setup requires SeCreateSymbolicLinkPrivilege")
8fa7f0b def test_run_action_file_python_success(tmp_path: Path) -> None:
73c9c30 _make_venv(tmp_path)
8fa7f0b path = tmp_path / "ok.py"
path.write_text("print('hello-ok')\n", encoding="utf-8")
ok, message = run_action_file(tmp_path, "ok.py")
73c9c30 assert ok is True
assert message == "hello-ok"
053f925
@pytest.mark.skipif(sys.platform == "win32", reason="symlink venv setup requires SeCreateSymbolicLinkPrivilege")
8fa7f0b def test_run_action_file_python_failure(tmp_path: Path) -> None:
73c9c30 _make_venv(tmp_path)
8fa7f0b path = tmp_path / "fail.py"
path.write_text("import sys\nprint('boom', file=sys.stderr)\nsys.exit(2)\n", encoding="utf-8")
ok, message = run_action_file(tmp_path, "fail.py")
73c9c30 assert ok is False
assert "boom" in message
053f925
8fa7f0b def test_run_action_file_missing_venv(tmp_path: Path) -> None:
path = tmp_path / "ok.py"
path.write_text("print('x')\n", encoding="utf-8")
ok, message = run_action_file(tmp_path, "ok.py")
73c9c30 assert ok is False
assert "venv not found" in message
053f925
@pytest.mark.skipif(sys.platform == "win32", reason="symlink venv setup requires SeCreateSymbolicLinkPrivilege")
8fa7f0b def test_run_action_file_shell(tmp_path: Path) -> None:
73c9c30 _make_venv(tmp_path)
8fa7f0b path = tmp_path / "hi.sh"
path.write_text("#!/bin/bash\necho shell-ok\n", encoding="utf-8")
path.chmod(path.stat().st_mode | stat.S_IXUSR)
ok, message = run_action_file(tmp_path, "hi.sh")
73c9c30 assert ok is True
assert message == "shell-ok"
assert project_venv_python(tmp_path) is not None
053f925
def test_project_actions_unknown(tmp_path: Path) -> None:
89fd393 _write_pyproject(tmp_path, "[tool.pgt]\n")
73c9c30 ok, message = ProjectActions(tmp_path).action("missing")
assert ok is False
assert "Unknown action" in message
053f925
@pytest.mark.skipif(sys.platform == "win32", reason="symlink venv setup requires SeCreateSymbolicLinkPrivilege")
def test_project_actions_runs_named(tmp_path: Path) -> None:
73c9c30 _make_venv(tmp_path)
89fd393 _write_pyproject(tmp_path, '[tool.pgt.tasks.greet]\nfile = "greet.py"\n')
73c9c30 (tmp_path / "greet.py").write_text("print('hi')\n", encoding="utf-8")
ok, message = ProjectActions(tmp_path).action("greet")
assert ok is True
assert message == "hi"
9f80683
def test_load_mise_action_specs_without_mise(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr("pygittools.actions.shutil.which", lambda _name: None)
assert load_mise_action_specs(tmp_path) == []
def test_load_mise_action_specs_parses_json(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr("pygittools.actions.shutil.which", lambda _name: "/usr/bin/mise")
class _Proc:
returncode = 0
stdout = """[
{"name": "lint", "description": "Run lint", "file": "scripts/lint.py", "hide": false},
{"name": "hidden", "description": "", "hide": true},
{"name": "test", "description": " ", "hide": false}
]"""
stderr = ""
monkeypatch.setattr("pygittools.actions.subprocess.run", lambda *_a, **_k: _Proc())
assert load_mise_action_specs(tmp_path) == [
8fa7f0b ActionSpec(name="lint", file="scripts/lint.py", source="mise", description="Run lint"),
ActionSpec(name="test", file="", source="mise", description=""),
9f80683 ]
def test_load_mise_action_specs_soft_fails(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr("pygittools.actions.shutil.which", lambda _name: "/usr/bin/mise")
class _Proc:
returncode = 1
stdout = ""
stderr = "boom"
monkeypatch.setattr("pygittools.actions.subprocess.run", lambda *_a, **_k: _Proc())
assert load_mise_action_specs(tmp_path) == []
04f3c66 def test_load_action_catalog_is_pgt_sets_only(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
89fd393 _write_pyproject(tmp_path, '[tool.pgt.tasks.lint]\nfile = "scripts/lint.py"\n')
9f80683 monkeypatch.setattr(
"pygittools.actions.load_mise_action_specs",
8fa7f0b lambda _root: [ActionSpec(name="build", file="", source="mise", description="Build")],
9f80683 )
assert load_action_catalog(tmp_path) == [
8fa7f0b ActionSet(name="default", specs=(ActionSpec(name="lint", file="scripts/lint.py"),)),
9f80683 ]
def test_run_mise_task_invokes_cli(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr("pygittools.actions.shutil.which", lambda _name: "/usr/bin/mise")
captured: list[list[str]] = []
class _Proc:
returncode = 0
stdout = "built\n"
stderr = ""
def fake_run(cmd: list[str], **kwargs: object) -> _Proc:
captured.append(list(cmd))
assert kwargs["cwd"] == tmp_path
return _Proc()
monkeypatch.setattr("pygittools.actions.subprocess.run", fake_run)
ok, message = run_mise_task(tmp_path, "build", ("--release",))
assert ok is True
assert message == "built"
assert captured == [["mise", "run", "build", "--", "--release"]]
def test_run_action_dispatches_by_source(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
calls: list[str] = []
def fake_mise(root: Path, name: str, args: tuple[str, ...] = ()) -> tuple[bool, str]:
del root, args
calls.append(f"mise:{name}")
return True, "mise-ok"
8fa7f0b def fake_file(root: Path, script: str, args: tuple[str, ...] = (), *, environ: object = None) -> tuple[bool, str]:
bae6568 del root, args, environ
9f80683 calls.append(f"pgt:{script}")
return True, "pgt-ok"
monkeypatch.setattr("pygittools.actions.run_mise_task", fake_mise)
8fa7f0b monkeypatch.setattr("pygittools.actions.run_action_file", fake_file)
assert run_action(tmp_path, ActionSpec(name="build", file="", source="mise")) == (True, "mise-ok")
assert run_action(tmp_path, ActionSpec(name="lint", file="lint.py")) == (True, "pgt-ok")
9f80683 assert calls == ["mise:build", "pgt:lint.py"]
def test_project_actions_runs_mise_spec(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(
"pygittools.actions.run_mise_task",
lambda root, name, args=(): (True, f"{root.name}:{name}:{args}"),
)
8fa7f0b spec = ActionSpec(name="build", file="", source="mise", args=("--quiet",))
9f80683 ok, message = ProjectActions(tmp_path, [spec]).action("build")
assert ok is True
assert message == f"{tmp_path.name}:build:('--quiet',)"
8ac8a11
04f3c66 def test_depends_unknown_name(tmp_path: Path) -> None:
_write_pyproject(
tmp_path,
89fd393 """
[tool.pgt.tasks.check]
depends = ["missing"]
""",
8ac8a11 )
04f3c66 with pytest.raises(ValueError, match="Unknown depends 'missing'"):
8ac8a11 load_action_sets(tmp_path)
04f3c66 def test_run_unknown_name(tmp_path: Path) -> None:
8ac8a11 _write_pyproject(
tmp_path,
89fd393 """
[tool.pgt.tasks.check]
run = [{ task = "missing" }]
""",
8ac8a11 )
04f3c66 with pytest.raises(ValueError, match="Unknown run 'missing'"):
8ac8a11 load_action_sets(tmp_path)
04f3c66 def test_depends_only_hub_requires_body(tmp_path: Path) -> None:
89fd393 _write_pyproject(tmp_path, "[tool.pgt.tasks.check]\n")
8fa7f0b with pytest.raises(ValueError, match="requires 'file', 'depends', or 'run'"):
04f3c66 load_action_specs(tmp_path)
def test_load_action_specs_run_steps(tmp_path: Path) -> None:
_write_pyproject(
tmp_path,
89fd393 """
[tool.pgt.tasks.lint]
file = "lint.py"
[tool.pgt.tasks.test]
file = "test.py"
[tool.pgt.tasks.check]
run = [
{ task = "lint" },
{ tasks = ["test"] },
"echo done",
]
""",
04f3c66 )
check = next(spec for spec in load_action_specs(tmp_path) if spec.name == "check")
assert check.run == (
RunTask(task="lint"),
RunParallel(tasks=("test",)),
"echo done",
)
8ac8a11 def test_run_action_runs_depends_first(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
calls: list[str] = []
8fa7f0b def fake_file(root: Path, script: str, args: tuple[str, ...] = (), *, environ: object = None) -> tuple[bool, str]:
bae6568 del root, args, environ
8ac8a11 calls.append(script)
return True, "ok"
8fa7f0b monkeypatch.setattr("pygittools.actions.run_action_file", fake_file)
unit = ActionSpec(name="unit", file="unit.py", hide=True)
check = ActionSpec(name="check", file="check.py", depends=("unit",))
8ac8a11 ok, message = run_action(tmp_path, check, registry={"unit": unit, "check": check})
assert ok is True
assert message == "ok"
assert calls == ["unit.py", "check.py"]
04f3c66 def test_run_action_depends_parallel(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
import threading
import time
active = 0
max_active = 0
lock = threading.Lock()
calls: list[str] = []
8fa7f0b def fake_file(root: Path, script: str, args: tuple[str, ...] = (), *, environ: object = None) -> tuple[bool, str]:
bae6568 del root, args, environ
04f3c66 nonlocal active, max_active
with lock:
active += 1
max_active = max(max_active, active)
calls.append(script)
time.sleep(0.05)
with lock:
active -= 1
return True, f"ran-{script}"
8fa7f0b monkeypatch.setattr("pygittools.actions.run_action_file", fake_file)
a = ActionSpec(name="a", file="a.py")
b = ActionSpec(name="b", file="b.py")
04f3c66 hub = ActionSpec(name="hub", depends=("a", "b"))
ok, message = run_action(tmp_path, hub, registry={"a": a, "b": b, "hub": hub})
assert ok is True
assert message.startswith("ran-")
assert set(calls) == {"a.py", "b.py"}
assert max_active >= 2
9761069 def test_run_action_shared_depends_run_once(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""Diamond depends: a and b both need setup; setup must run once (mise-style)."""
import threading
import time
active = 0
max_active = 0
lock = threading.Lock()
calls: list[str] = []
def fake_file(root: Path, script: str, args: tuple[str, ...] = (), *, environ: object = None) -> tuple[bool, str]:
del root, args, environ
nonlocal active, max_active
with lock:
active += 1
max_active = max(max_active, active)
calls.append(script)
time.sleep(0.05)
with lock:
active -= 1
return True, f"ran-{script}"
monkeypatch.setattr("pygittools.actions.run_action_file", fake_file)
setup = ActionSpec(name="setup", file="setup.py")
a = ActionSpec(name="a", file="a.py", depends=("setup",))
b = ActionSpec(name="b", file="b.py", depends=("setup",))
hub = ActionSpec(name="hub", depends=("a", "b"))
ok, message = run_action(
tmp_path,
hub,
registry={"setup": setup, "a": a, "b": b, "hub": hub},
)
assert ok is True
assert message.startswith("ran-")
assert calls.count("setup.py") == 1
assert set(calls) == {"setup.py", "a.py", "b.py"}
assert max_active >= 2
def test_run_action_shared_depends_failure_shared(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
calls: list[str] = []
def fake_file(root: Path, script: str, args: tuple[str, ...] = (), *, environ: object = None) -> tuple[bool, str]:
del root, args, environ
calls.append(script)
if script == "setup.py":
return False, "setup failed"
return True, "ok"
monkeypatch.setattr("pygittools.actions.run_action_file", fake_file)
setup = ActionSpec(name="setup", file="setup.py")
a = ActionSpec(name="a", file="a.py", depends=("setup",))
b = ActionSpec(name="b", file="b.py", depends=("setup",))
hub = ActionSpec(name="hub", depends=("a", "b"))
ok, message = run_action(
tmp_path,
hub,
registry={"setup": setup, "a": a, "b": b, "hub": hub},
)
assert ok is False
assert "setup failed" in message
assert calls == ["setup.py"]
04f3c66 def test_run_action_run_steps_ordered(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
calls: list[str] = []
8fa7f0b def fake_file(root: Path, script: str, args: tuple[str, ...] = (), *, environ: object = None) -> tuple[bool, str]:
bae6568 del root, args, environ
04f3c66 calls.append(script)
return True, f"ran-{script}"
8fa7f0b monkeypatch.setattr("pygittools.actions.run_action_file", fake_file)
lint = ActionSpec(name="lint", file="lint.py")
test = ActionSpec(name="test", file="test.py")
04f3c66 check = ActionSpec(
name="check",
run=(RunTask(task="lint"), RunTask(task="test")),
)
ok, message = run_action(
tmp_path,
check,
registry={"lint": lint, "test": test, "check": check},
)
assert ok is True
assert message == "ran-test.py"
assert calls == ["lint.py", "test.py"]
def test_run_action_depends_only_hub(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
calls: list[str] = []
8fa7f0b def fake_file(root: Path, script: str, args: tuple[str, ...] = (), *, environ: object = None) -> tuple[bool, str]:
bae6568 del root, args, environ
04f3c66 calls.append(script)
return True, f"ran-{script}"
8fa7f0b monkeypatch.setattr("pygittools.actions.run_action_file", fake_file)
unit = ActionSpec(name="unit", file="unit.py")
04f3c66 check = ActionSpec(name="check", depends=("unit",))
ok, message = run_action(tmp_path, check, registry={"unit": unit, "check": check})
assert ok is True
assert message == "ran-unit.py"
assert calls == ["unit.py"]
8ac8a11 def test_run_action_circular_depends(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(
8fa7f0b "pygittools.actions.run_action_file",
8ac8a11 lambda *_a, **_k: (True, "ok"),
)
8fa7f0b a = ActionSpec(name="a", file="a.py", depends=("b",))
b = ActionSpec(name="b", file="b.py", depends=("a",))
8ac8a11 ok, message = run_action(tmp_path, a, registry={"a": a, "b": b})
assert ok is False
assert "Circular depends" in message
04f3c66 def test_root_visible_specs_skips_referenced_leaves() -> None:
specs = (
8fa7f0b ActionSpec(name="lint", file="lint.py"),
ActionSpec(name="test", file="test.py"),
04f3c66 ActionSpec(name="check", run=(RunTask(task="lint"), RunTask(task="test"))),
8fa7f0b ActionSpec(name="hidden", file="h.py", hide=True),
04f3c66 ActionSpec(name="group", depends=("hidden",)),
)
assert [spec.name for spec in root_visible_specs(specs)] == ["check", "group"]
def test_catalog_registry_rejects_duplicate_names() -> None:
8ac8a11 sets = [
8fa7f0b ActionSet(name="default", specs=(ActionSpec(name="lint", file="a.py"),)),
ActionSet(name="extra", specs=(ActionSpec(name="lint", file="b.py"),)),
8ac8a11 ]
04f3c66 with pytest.raises(ValueError, match="Duplicate action name 'lint'"):
catalog_registry(sets)
8ac8a11
04f3c66 def test_same_action_name_in_two_sets_stays_in_its_set(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
calls: list[str] = []
8fa7f0b def fake_file(root: Path, script: str, args: tuple[str, ...] = (), *, environ: object = None) -> tuple[bool, str]:
bae6568 del root, args, environ
04f3c66 calls.append(script)
return True, script
8fa7f0b monkeypatch.setattr("pygittools.actions.run_action_file", fake_file)
default_lint = ActionSpec(name="lint", file="default_lint.py")
extra_lint = ActionSpec(name="lint", file="extra_lint.py")
04f3c66 check = ActionSpec(name="check", depends=("lint",))
default_set = ActionSet(name="default", specs=(default_lint, check))
extra_set = ActionSet(name="extra", specs=(extra_lint,))
ok, message = run_action(tmp_path, check, registry=set_registry(default_set.specs))
assert ok is True
assert message == "default_lint.py"
assert calls == ["default_lint.py"]
calls.clear()
ok, message = run_action(tmp_path, extra_lint, registry=set_registry(extra_set.specs))
assert ok is True
assert message == "extra_lint.py"
assert calls == ["extra_lint.py"]
def test_run_action_reports_each_referenced_task(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
8fa7f0b def fake_file(root: Path, script: str, args: tuple[str, ...] = (), *, environ: object = None) -> tuple[bool, str]:
bae6568 del root, args, environ
04f3c66 return True, script
8fa7f0b monkeypatch.setattr("pygittools.actions.run_action_file", fake_file)
04f3c66 events: list[tuple[str, str, str]] = []
def on_action(name: str, status: str, message: str) -> None:
events.append((name, status, message))
8fa7f0b lint = ActionSpec(name="lint", file="lint.py")
test = ActionSpec(name="test", file="test.py")
04f3c66 check = ActionSpec(name="check", run=(RunTask(task="lint"), RunTask(task="test")))
ok, message = run_action(
tmp_path,
check,
registry=set_registry((lint, test, check)),
on_action=on_action,
)
assert ok is True
assert message == "test.py"
assert [event for event in events if event[1] == "success"] == [
("lint", "success", "lint.py"),
("test", "success", "test.py"),
("check", "success", "test.py"),
]
def test_workspace_catalog_excludes_mise_group() -> None:
8ac8a11 root = Path(__file__).resolve().parents[3]
04f3c66 assert [item.name for item in load_action_catalog(root)] == [
"default",
f84f28d "test-versions",
04f3c66 "all-tests",
]
89fd393
def test_workspace_mise_toml_lists_check_task() -> None:
root = Path(__file__).resolve().parents[3]
mise = root / "mise.toml"
assert mise.is_file()
text = mise.read_text(encoding="utf-8")
assert "[tasks.check]" in text
assert "[tasks.ruff-check]" in text
assert "[tasks.pytest-pygittools]" in text