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

+5 -2
View File
@@ -114,6 +114,7 @@ $ schedls new rotate --timer --daily 03:00 --shell 'find /tmp -mtime +7 -delete'
```console
$ schedls edit backup --daily 03:00
$ schedls edit cleanup --cron-expr '0 4 * * 0'
$ schedls edit backup --jitter 5min --no-persistent
$ schedls edit backup --command -- /usr/local/bin/backup /srv/data
$ schedls edit backup -i
@@ -126,8 +127,10 @@ everything else keeps its current value.
Passing `--` without `--command` is an error, so the command can never be
changed by accident.
- `--no-persistent` clears `Persistent=` on a systemd timer.
- Editing is supported for systemd timers only. Editing cron jobs is not yet
supported and reports a usage error.
- Editing is supported for schedls-managed systemd timers and cron jobs. A cron
edit changes only the job line in its managed block and preserves every other
cron line. Editing a system cron drop-in requires root and preserves its
existing `run-as` user.
### `rm NAME`
+16 -1
View File
@@ -58,6 +58,22 @@ block:
If markers are malformed or a `begin` has no matching `end`, mutations refuse
to proceed rather than guess.
## Editing
`schedls edit` supports jobs in valid schedls-managed blocks. It updates only
the single cron job line in the block, leaving comments, environment
assignments, and all other cron entries unchanged. If a block has malformed
markers or does not contain exactly one job line, schedls refuses to edit it.
When only the schedule changes, schedls retains the existing cron command
without reverse-parsing or re-quoting shell syntax. Replacing a command uses
the normal safe command renderer.
For a system drop-in, editing requires root and re-checks the expected
`/etc/cron.d/schedls-<name>` path, ownership, trusted directory, and file
snapshot before atomically replacing the file. The existing `run-as` user is
preserved.
## System drop-ins
A system cron job is a file named after the schedule:
@@ -143,7 +159,6 @@ command-line compatibility but have no effect on cron jobs; see
## Not yet supported
- editing cron jobs (user or system);
- token-level updates of `/etc/crontab` (read-only, shared file);
- anacron (`/etc/anacrontab`);
- removing or editing periodic directory scripts;
+1 -1
View File
@@ -113,6 +113,6 @@ completion. Development dependencies are locked and audited in CI.
## Availability, privacy
`0.3.0` requires `systemd-analyze` to create or validate calendar expressions
`0.4.0` requires `systemd-analyze` to create or validate calendar expressions
and refuses the operation if it is unavailable. `schedls` makes no network
requests and collects no telemetry.
+1 -2
View File
@@ -1,6 +1,6 @@
[project]
name = "schedls"
version = "0.3.0"
version = "0.4.0"
description = "Inspect and manage Linux scheduled jobs"
authors = [
{ name = "Marco D'Aleo", email = "marco@marcodaleo.com" }
@@ -11,7 +11,6 @@ requires-python = ">=3.11,<4.0"
dependencies = ["argcomplete>=3.3,<4.0"]
keywords = ["cron", "crontab", "systemd", "timer", "scheduler", "cli", "sysadmin"]
classifiers = [
"Development Status :: 3 - Alpha",
"Environment :: Console",
"Intended Audience :: System Administrators",
"Operating System :: POSIX :: Linux",
+191 -5
View File
@@ -33,6 +33,7 @@ from ..runner import CommandRunner
from ..security import (
atomic_write_text,
check_trusted_directory,
has_unsafe_control_characters,
remove_file,
validate_name,
)
@@ -251,6 +252,30 @@ class CrontabDocument:
return ""
return "\n".join(keep) + "\n"
def managed_job_line(self, name: str) -> CrontabEntry:
if self.has_malformed_markers():
raise SafetyRefusalError("existing crontab contains malformed schedls markers; refusing to edit.")
block = self._blocks.get(name)
if block is None:
raise SafetyRefusalError(f"no schedls-managed cron block named {name!r}.")
job_lines = [entry for entry in block.job_lines if entry.kind == "job"]
if len(job_lines) != 1:
raise SafetyRefusalError(
f"schedls-managed cron block {name!r} must contain exactly one job; refusing to edit."
)
return job_lines[0]
def with_updated_job(self, name: str, line: str) -> str:
job = self.managed_job_line(name)
if has_unsafe_control_characters(line):
raise SafetyRefusalError("cron job line must not contain NUL or newline")
lines = list(self.lines)
lines[job.index - 1] = line
body = "\n".join(lines)
if self.had_trailing_newline and body:
return body + "\n"
return body
def _split_job(stripped: str, *, system: bool = False) -> tuple[str | None, str | None, str | None]:
nickname = _NICKNAME_RE.match(stripped)
@@ -279,6 +304,7 @@ class CronBackend(SchedulerBackend):
capabilities = Capabilities(
discovery=True,
create=True,
update=True,
remove=True,
next_run=False,
validation=True,
@@ -657,6 +683,124 @@ class CronBackend(SchedulerBackend):
}
return plan
def plan_update(self, current: ScheduledJob, spec: JobSpec) -> Plan:
if not current.managed:
raise SafetyRefusalError(
f"{current.name} was not created by schedls.",
hint="schedls will not modify unmanaged schedules by default.",
)
if current.backend is not Backend.CRON or spec.backend is not Backend.CRON:
raise SafetyRefusalError(f"{current.name} is not a cron job.")
if current.name != spec.name or current.scope is not spec.scope:
raise SafetyRefusalError("cron job updates must keep the existing name and scope.")
if current.scope is Scope.SYSTEM:
return self._plan_update_system(current, spec)
if current.scope is Scope.USER:
return self._plan_update_user(current, spec)
raise SafetyRefusalError("unsupported cron scope.")
def _plan_update_user(self, current: ScheduledJob, spec: JobSpec) -> Plan:
if not self.crontab_available():
raise OperationalError("crontab is not available")
document = self.read()
old_line = document.managed_job_line(current.name)
expression = renderer.validate_expression(spec.cron_expression or "")
line = self._render_updated_line(
expression,
spec.command,
old_line.command,
preserve_command=spec.command == current.command,
)
new_text = document.with_updated_job(current.name, line)
plan = Plan(backend=self.name, action="update")
plan.summary = [
("Backend", "cron (current user)"),
("Schedule", expression),
("Command", spec.command.display()),
("Execute via", "/bin/sh"),
]
plan.commands = self._install_commands(new_text)
plan.warnings.append("Cron executes command text through /bin/sh (or the crontab's configured SHELL).")
plan.payload = {
"mode": "crontab",
"action": "update",
"name": current.name,
"old_text": document.text,
"new_text": new_text,
"expected_line": line,
}
return plan
def _plan_update_system(self, current: ScheduledJob, spec: JobSpec) -> Plan:
if os.geteuid() != 0:
raise SafetyRefusalError(
"editing a system cron job requires appropriate privileges.",
hint="Run the command under sudo yourself if that is your intention:\n sudo schedls edit ...",
)
renderer.validate_system_name(current.name)
directory = self.paths.cron_d
if not os.path.isdir(directory):
raise OperationalError(f"system cron directory does not exist: {directory}")
check_trusted_directory(directory, expected_uid=0)
path = current.source.path
expected_path = os.path.join(directory, f"{_MANAGED_PREFIX}{current.name}")
if path != expected_path:
raise SafetyRefusalError(f"refusing to edit unexpected system cron file: {path!r}")
content = _read_text(path)
if content is None:
raise OperationalError(f"could not read {path}")
document = CrontabDocument(content, system=True)
old_line = document.managed_job_line(current.name)
run_as = renderer.validate_run_as(old_line.user or "")
expression = renderer.validate_expression(spec.cron_expression or "")
line = self._render_updated_line(
expression,
spec.command,
old_line.command,
run_as=run_as,
preserve_command=spec.command == current.command,
)
new_text = document.with_updated_job(current.name, line)
plan = Plan(backend=self.name, action="update")
plan.summary = [
("Backend", "cron (system)"),
("Schedule", expression),
("Run as", run_as),
("Command", spec.command.display()),
("File", path),
]
plan.files = [FileChange(path=path, content=new_text, mode=0o644, expected_uid=0)]
plan.warnings.append("Cron executes command text through /bin/sh (or the crontab's configured SHELL).")
plan.payload = {
"mode": "file",
"action": "update",
"name": current.name,
"path": path,
"expected_uid": 0,
"snapshots": {path: content},
"expected_line": line,
}
return plan
@staticmethod
def _render_updated_line(
expression: str,
command: Command,
existing_command: str | None,
*,
preserve_command: bool,
run_as: str | None = None,
) -> str:
if preserve_command:
if not existing_command or has_unsafe_control_characters(existing_command):
raise SafetyRefusalError("existing cron command cannot be safely preserved.")
if run_as is None:
return f"{expression} {existing_command}"
return f"{expression} {run_as} {existing_command}"
if run_as is None:
return renderer.render_line(expression, command)
return renderer.render_system_line(expression, command, run_as)
def plan_remove(self, job: ScheduledJob) -> Plan:
if not job.managed:
raise SafetyRefusalError(
@@ -777,7 +921,14 @@ class CronBackend(SchedulerBackend):
raise OperationalError(str(exc)) from exc
self._verify_installed(plan)
action = plan.payload.get("action")
message = "System cron drop-in installed." if action == "create" else "System cron drop-in removed."
if action == "create":
message = "System cron drop-in installed."
elif action == "update":
message = "System cron drop-in updated."
elif action == "remove":
message = "System cron drop-in removed."
else:
message = "System cron drop-in changed."
return MutationResult(changed=bool(written), messages=[message])
def _rollback_file(
@@ -811,16 +962,51 @@ class CronBackend(SchedulerBackend):
def _verify_installed(self, plan: Plan) -> None:
name = plan.payload.get("name")
action = plan.payload.get("action")
expected_line = plan.payload.get("expected_line")
if plan.payload.get("mode") == "file":
if plan.payload.get("action") != "create" or not name:
if action not in {"create", "update"} or not name:
return
document = CrontabDocument(_read_text(plan.payload.get("path", "")) or "", system=True)
if name not in document.managed_blocks():
try:
job_line = document.managed_job_line(name)
except SafetyRefusalError as exc:
raise OperationalError("the drop-in was written but the schedls block could not be verified.") from exc
if not self._matches_expected_line(job_line, expected_line, system=True):
raise OperationalError("the drop-in was written but the schedls block could not be verified.")
return
document = self.read()
if plan.payload.get("action") == "create" and name and name not in document.managed_blocks():
raise OperationalError("the crontab was installed but the schedls block could not be verified.")
if action in {"create", "update"} and name:
try:
job_line = document.managed_job_line(name)
except SafetyRefusalError as exc:
raise OperationalError(
"the crontab was installed but the schedls block could not be verified."
) from exc
if not self._matches_expected_line(job_line, expected_line, system=False):
raise OperationalError("the crontab was installed but the schedls block could not be verified.")
@staticmethod
def _matches_expected_line(job_line: CrontabEntry, expected_line: object, *, system: bool) -> bool:
if expected_line is None:
return True
if not isinstance(expected_line, str):
return False
expected_entries = [
entry for entry in CrontabDocument(expected_line, system=system).entries if entry.kind == "job"
]
if len(expected_entries) != 1:
return False
expected = expected_entries[0]
return (
job_line.expression,
job_line.user,
job_line.command,
) == (
expected.expression,
expected.user,
expected.command,
)
def _restore(self, text: str) -> None:
with contextlib.suppress(Exception):
+25 -2
View File
@@ -583,6 +583,25 @@ def _spec_for_edit(job: ScheduledJob, args: argparse.Namespace, tail: list[str])
else (job.systemd.working_directory if job.systemd else None),
environment=_parse_environment(args.env) if args.env else (job.systemd.environment if job.systemd else ()),
)
if job.backend is Backend.CRON:
if args.calendar:
raise UsageError("--calendar is a systemd option; use --cron-expr for cron.")
if args.persistent or args.no_persistent or args.jitter or args.accuracy or args.working_directory:
raise UsageError("--persistent/--jitter/--accuracy/--working-directory are systemd options.")
if args.env:
raise UsageError("--env is a systemd option; cron environment variables are not supported yet.")
expression = _cron_expression_from_args(args)
if expression is None:
expression = job.cron.expression if job.cron else job.schedule.expression
if not expression:
raise UsageError("the existing cron job has no schedule; refusing to edit it.")
return JobSpec(
name=job.name,
backend=Backend.CRON,
scope=job.scope,
command=command,
cron_expression=expression,
)
raise UsageError(f"editing {job.backend.value} jobs is not supported yet.")
@@ -708,9 +727,13 @@ def _wizard_edit(
else:
args.replace_command = True
tail = list(command.argv)
if (
job.backend in {Backend.SYSTEMD, Backend.CRON}
and not _has_schedule(args)
and prompter.yes_no("Change the schedule?", default=False)
):
_apply_schedule(args, prompter.schedule(job.backend))
if job.backend is Backend.SYSTEMD:
if not _has_schedule(args) and prompter.yes_no("Change the schedule?", default=False):
_apply_schedule(args, prompter.schedule(job.backend))
_wizard_edit_advanced(job, args, prompter)
return args, tail
+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()