Add managed cron editing and bump version to 0.4.0

This commit is contained in:
mdaleo404 committed 2026-10-06 09:11:09 +01:00
1 parent c93c6fdc26
commit d55d16323a
11 files changed
+488 -23

No files matched your search

+30 -2
View File
@@ -58,7 +58,20 @@ def test_cron_lifecycle_preserves_content() -> None:
job = backend.find(NAME)
assert job is not None
backend.apply(backend.plan_remove(job))
update = JobSpec(
name=NAME,
backend=Backend.CRON,
scope=Scope.USER,
command=Command(argv=("/usr/bin/true", "updated")),
cron_expression="30 3 * * *",
)
backend.apply(backend.plan_update(job, update))
updated = backend.find(NAME)
assert updated is not None
assert updated.schedule.expression == "30 3 * * *"
assert updated.command.raw == "/usr/bin/true updated"
backend.apply(backend.plan_remove(updated))
assert "# unrelated comment" in backend.read().text
assert backend.find(NAME) is None
finally:
@@ -104,7 +117,22 @@ def test_system_cron_lifecycle() -> None:
assert job.managed is True
assert job.cron is not None and job.cron.user == "root"
backend.apply(backend.plan_remove(job))
update = JobSpec(
name=SYSTEM_NAME,
backend=Backend.CRON,
scope=Scope.SYSTEM,
command=Command(argv=("/usr/bin/true", "updated")),
cron_expression="30 3 * * *",
run_as="root",
)
backend.apply(backend.plan_update(job, update))
updated = backend.find(SYSTEM_NAME)
assert updated is not None
assert updated.schedule.expression == "30 3 * * *"
assert updated.cron is not None and updated.cron.user == "root"
assert updated.command.raw == "/usr/bin/true updated"
backend.apply(backend.plan_remove(updated))
assert not os.path.exists(path)
assert backend.find(SYSTEM_NAME) is None
finally:
+43 -2
View File
@@ -6,9 +6,9 @@ import sys
import pytest
from schedls.cli import _parse_environment, _spec_for_new, build_parser, main, split_command
from schedls.cli import _parse_environment, _spec_for_edit, _spec_for_new, build_parser, main, split_command
from schedls.errors import InvalidNameError, UsageError
from schedls.models import Backend, Scope
from schedls.models import Backend, Command, CronDetails, JobSource, Schedule, ScheduledJob, ScheduleKind, Scope
def test_split_command() -> None:
@@ -174,6 +174,47 @@ def test_spec_for_new_rejects_run_as_for_timer() -> None:
_spec_for_new(args, ["/bin/true"])
def _cron_job() -> ScheduledJob:
return ScheduledJob(
name="cleanup",
backend=Backend.CRON,
scope=Scope.USER,
managed=True,
enabled=None,
schedule=Schedule(ScheduleKind.CRON, "0 2 * * *"),
command=Command(raw="/usr/local/bin/cleanup"),
source=JobSource("current user's crontab", line=1),
cron=CronDetails(expression="0 2 * * *", line=1),
)
def test_spec_for_edit_cron_preserves_command_and_changes_schedule() -> None:
args = build_parser().parse_args(["edit", "cleanup", "--daily", "03:00"])
job = _cron_job()
spec = _spec_for_edit(job, args, [])
assert spec.backend is Backend.CRON
assert spec.cron_expression == "0 3 * * *"
assert spec.command == job.command
def test_spec_for_edit_cron_replaces_command() -> None:
args = build_parser().parse_args(["edit", "cleanup", "--command"])
spec = _spec_for_edit(_cron_job(), args, ["/usr/local/bin/cleanup", "--full"])
assert spec.command.argv == ("/usr/local/bin/cleanup", "--full")
@pytest.mark.parametrize("extra", [["--calendar", "daily"], ["--persistent"], ["--env", "A=1"]])
def test_spec_for_edit_cron_rejects_systemd_options(extra: list[str]) -> None:
args = build_parser().parse_args(["edit", "cleanup", *extra])
with pytest.raises(UsageError):
_spec_for_edit(_cron_job(), args, [])
@pytest.mark.parametrize("value", ["0", "-1", "1000001", "abc"])
def test_logs_lines_must_be_a_bounded_positive_integer(value: str) -> None:
with pytest.raises(SystemExit):
+127 -6
View File
@@ -5,7 +5,7 @@ import os
import pytest
from schedls.backends.base import FileChange, Plan
from schedls.backends.cron import CronBackend, CronPaths
from schedls.backends.cron import CronBackend, CronPaths, CrontabDocument
from schedls.errors import ConflictError, InvalidScheduleError, SafetyRefusalError
from schedls.models import Backend, Command, JobSpec, Scope
from schedls.renderers import cron as renderer
@@ -181,6 +181,110 @@ def test_plan_create_system_cron_conflict(tmp_path, fake_runner, monkeypatch) ->
CronBackend(fake_runner, paths).plan_create(_system_spec())
def test_update_user_cron_preserves_existing_command(tmp_path, fake_runner) -> None:
document = CrontabDocument(
"# unrelated comment\n"
"# schedls:begin name=backup\n"
"0 2 * * * /usr/bin/printf '50\\%s\\n'\n"
"# schedls:end name=backup\n"
)
state = {"text": document.text}
def crontab(argv, input_text):
if argv == ["crontab", "-l"]:
return state["text"], ""
if argv == ["crontab", "-"]:
state["text"] = input_text or ""
return "", ""
return 1, "", "unsupported"
fake_runner.available.add("crontab")
fake_runner.handlers["crontab"] = crontab
backend = CronBackend(fake_runner, _make_paths(tmp_path))
job = backend.discover([Scope.USER])[0]
plan = backend.plan_update(
job,
JobSpec(
name="backup",
backend=Backend.CRON,
scope=Scope.USER,
command=job.command,
cron_expression="30 3 * * *",
),
)
assert plan.action == "update"
assert "# unrelated comment" in plan.payload["new_text"]
assert "30 3 * * * /usr/bin/printf '50\\%s\\n'" in plan.payload["new_text"]
assert "50\\\\%" not in plan.payload["new_text"]
state["text"] = state["text"].replace("0 2 * * *", "15 2 * * *")
with pytest.raises(SafetyRefusalError, match="crontab changed"):
backend.apply(plan)
plan = backend.plan_update(
job,
JobSpec(
name="backup",
backend=Backend.CRON,
scope=Scope.USER,
command=job.command,
cron_expression="30 3 * * *",
),
)
result = backend.apply(plan)
assert result.changed
assert state["text"] == plan.payload["new_text"]
def test_plan_update_system_cron_preserves_run_as_and_other_content(tmp_path, fake_runner, monkeypatch) -> None:
paths = _make_paths(tmp_path)
path = _write(
tmp_path / "etc/cron.d/schedls-cleanup",
"# unrelated comment\n" + renderer.render_system_file("cleanup", ["30 3 * * 0 root /usr/bin/cleanup"]),
)
backend = CronBackend(fake_runner, paths)
job = backend.discover([Scope.SYSTEM])[0]
monkeypatch.setattr(os, "geteuid", lambda: 0)
trusted_directories: list[tuple[str, int]] = []
def check_trusted_directory(path: str, *, expected_uid: int) -> None:
trusted_directories.append((path, expected_uid))
monkeypatch.setattr("schedls.backends.cron.check_trusted_directory", check_trusted_directory)
plan = backend.plan_update(
job,
_system_spec(
name="cleanup",
command=Command(argv=("/usr/bin/cleanup", "--full")),
cron_expression="15 4 * * *",
run_as="www-data",
),
)
assert plan.action == "update"
assert plan.files[0].path == str(path)
assert "# unrelated comment" in plan.files[0].content
assert "15 4 * * * root /usr/bin/cleanup --full" in plan.files[0].content
assert "www-data" not in plan.files[0].content
assert trusted_directories == [(paths.cron_d, 0)]
def test_plan_update_system_cron_requires_root(tmp_path, fake_runner, monkeypatch) -> None:
paths = _make_paths(tmp_path)
_write(
tmp_path / "etc/cron.d/schedls-cleanup",
renderer.render_system_file("cleanup", ["30 3 * * 0 root /usr/bin/cleanup"]),
)
backend = CronBackend(fake_runner, paths)
job = backend.discover([Scope.SYSTEM])[0]
monkeypatch.setattr(os, "geteuid", lambda: 1000)
with pytest.raises(SafetyRefusalError):
backend.plan_update(job, _system_spec(name="cleanup"))
def test_apply_file_mode_create_and_remove(tmp_path, fake_runner) -> None:
paths = _make_paths(tmp_path)
(tmp_path / "etc/cron.d").mkdir(parents=True, exist_ok=True)
@@ -203,6 +307,23 @@ def test_apply_file_mode_create_and_remove(tmp_path, fake_runner) -> None:
assert result.changed
assert path.read_text() == content
updated_content = renderer.render_system_file("backup", ["30 3 * * * root /usr/bin/backup --full"])
update = Plan(backend="cron", action="update")
update.files = [FileChange(path=str(path), content=updated_content, mode=0o644, expected_uid=uid)]
update.payload = {
"mode": "file",
"action": "update",
"name": "backup",
"path": str(path),
"expected_uid": uid,
"snapshots": {str(path): content},
"expected_line": "30 3 * * * root /usr/bin/backup --full",
}
result = backend.apply(update)
assert result.changed
assert result.messages == ["System cron drop-in updated."]
assert path.read_text() == updated_content
remove = Plan(backend="cron", action="remove")
remove.files = [FileChange(path=str(path), content=None, expected_uid=uid)]
remove.payload = {
@@ -211,24 +332,24 @@ def test_apply_file_mode_create_and_remove(tmp_path, fake_runner) -> None:
"name": "backup",
"path": str(path),
"expected_uid": uid,
"snapshots": {str(path): content},
"snapshots": {str(path): updated_content},
}
result = backend.apply(remove)
assert result.changed
assert not path.exists()
def test_apply_file_mode_refuses_changed_snapshot(tmp_path, fake_runner) -> None:
def test_apply_file_update_refuses_changed_snapshot(tmp_path, fake_runner) -> None:
paths = _make_paths(tmp_path)
_write(tmp_path / "etc/cron.d/schedls-backup", "changed\n")
backend = CronBackend(fake_runner, paths)
path = tmp_path / "etc/cron.d/schedls-backup"
plan = Plan(backend="cron", action="remove")
plan.files = [FileChange(path=str(path), content=None, expected_uid=os.getuid())]
plan = Plan(backend="cron", action="update")
plan.files = [FileChange(path=str(path), content="new content\n", expected_uid=os.getuid())]
plan.payload = {
"mode": "file",
"action": "remove",
"action": "update",
"name": "backup",
"path": str(path),
"expected_uid": os.getuid(),
+24
View File
@@ -72,6 +72,28 @@ def test_without_block_removes_only_block() -> None:
assert "@daily /usr/local/bin/nightly" in updated
def test_with_updated_job_preserves_all_other_content() -> None:
document = CrontabDocument(SAMPLE)
updated = document.with_updated_job("backup", "30 3 * * * /usr/local/bin/backup /srv/data")
assert updated == SAMPLE.replace(
"0 2 * * * /usr/local/bin/backup /srv/data",
"30 3 * * * /usr/local/bin/backup /srv/data",
)
def test_with_updated_job_requires_exactly_one_job() -> None:
document = CrontabDocument(
"# schedls:begin name=backup\n"
"0 2 * * * /usr/local/bin/backup\n"
"0 3 * * * /usr/local/bin/other\n"
"# schedls:end name=backup\n"
)
with pytest.raises(SafetyRefusalError, match="exactly one job"):
document.with_updated_job("backup", "30 3 * * * /usr/local/bin/backup")
def test_without_unknown_block_refused() -> None:
document = CrontabDocument(SAMPLE)
with pytest.raises(SafetyRefusalError):
@@ -85,6 +107,8 @@ def test_malformed_marker_blocks_mutation() -> None:
document.with_block("new", ["0 3 * * * /bin/true"])
with pytest.raises(SafetyRefusalError):
document.without_block("broken")
with pytest.raises(SafetyRefusalError):
document.with_updated_job("broken", "0 3 * * * /bin/true")
def test_empty_crontab() -> None:
+25
View File
@@ -9,6 +9,7 @@ from schedls.errors import ConfirmationRequiredError, InvalidScheduleError
from schedls.models import (
Backend,
Command,
CronDetails,
JobSource,
Schedule,
ScheduledJob,
@@ -60,6 +61,20 @@ def _systemd_job() -> ScheduledJob:
)
def _cron_job() -> ScheduledJob:
return ScheduledJob(
name="cleanup",
backend=Backend.CRON,
scope=Scope.USER,
managed=True,
enabled=None,
schedule=Schedule(ScheduleKind.CRON, "0 2 * * *"),
command=Command(raw="/usr/local/bin/cleanup"),
source=JobSource(detail="current user's crontab"),
cron=CronDetails(expression="0 2 * * *"),
)
def test_text_requires_a_value() -> None:
prompter, fake = make_prompter(["", "backup"])
assert prompter.text("Name") == "backup"
@@ -260,6 +275,16 @@ def test_wizard_edit_changes_schedule(monkeypatch: pytest.MonkeyPatch) -> None:
assert spec.calendar == ("*-*-* 03:00:00",)
def test_wizard_edit_changes_cron_schedule(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr("sys.stdin", FakeStdin(isatty=True))
args = build_parser().parse_args(["edit", "cleanup", "-i"])
prompter, _ = make_prompter(["n", "y", "", "03:00"])
args, tail = _wizard_edit(_cron_job(), args, [], prompter)
spec = _spec_for_edit(_cron_job(), args, tail)
assert spec.cron_expression == "0 3 * * *"
def test_wizard_edit_keeps_changes_optional(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr("sys.stdin", FakeStdin(isatty=True))
job = _systemd_job()