feat(scheduled-jobs): the Task Scheduler as scheduled jobs (#8)
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 15s
driver / test (3.12) (pull_request) Failing after 14s
driver / types (pull_request) Failing after 23s
driver / test (3.13) (pull_request) Failing after 13s
driver / lowest (pull_request) Failing after 14s
driver / security (pull_request) Failing after 32s
driver / build (pull_request) Successful in 25s
CI / driver (pull_request) Failing after 1m21s
driver / publish (pull_request) Skipped
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 15s
driver / test (3.12) (pull_request) Failing after 14s
driver / types (pull_request) Failing after 23s
driver / test (3.13) (pull_request) Failing after 13s
driver / lowest (pull_request) Failing after 14s
driver / security (pull_request) Failing after 32s
driver / build (pull_request) Successful in 25s
CI / driver (pull_request) Failing after 1m21s
driver / publish (pull_request) Skipped
netOrk shows and controls every scheduled job of a host; on Windows that is the Task Scheduler. The driver now implements napalm-device-types' ScheduledJobsMixin over PowerShell Remoting, one script per call as every getter does. get_scheduled_jobs reads every task with its run info in one script (Get-ScheduledTask, Get-ScheduledTaskInfo) as task:<path><name>, its triggers summarised. Tasks under \Microsoft\ are the platform's, others the admin's: Windows does not record which software installed a task. The time zone is mapped to IANA for the common Windows zones, else None. A reading cut short, or holding fewer tasks than it counted, raises. manage_scheduled_job switches the task's own flag or starts it; Start-ScheduledTask returns once the task has started, so the result says that and no more. A disabled task, or one that refuses a start on demand, is not offered run. put_scheduled_job registers an application's task \<name> in the root folder from XML, so a create and a change write the whole definition the same way: the command runs in cmd.exe /d /s /c, the principal is SYSTEM or a local user without a stored password (S4U), and the cron expression becomes triggers only where Task Scheduler can say it exactly; any other shape is refused, naming why. The description keeps the job's name and cron expression, so the reading gives back what was written, and the digest also covers the triggers, so a change by hand is seen. delete_scheduled_job unregisters such a task and no other. Every write reads the task again first, and every value goes into PowerShell single-quoted with its quotes doubled. Requires napalm-device-types 4.26.0. Closes #8
This commit is contained in:
1 parent
581c2df5e8
commit
a508b872b0
12 files changed
+1898
-23
No files matched your search
+100
@@ -0,0 +1,100 @@
|
||||
{
|
||||
"time_zone": "W. Europe Standard Time",
|
||||
"count": 5,
|
||||
"tasks": [
|
||||
{
|
||||
"path": "\\Microsoft\\Windows\\Defrag\\",
|
||||
"name": "ScheduledDefrag",
|
||||
"state": "Ready",
|
||||
"user": "SYSTEM",
|
||||
"group": null,
|
||||
"on_demand": true,
|
||||
"description": "This task optimizes local storage drives.",
|
||||
"actions": [
|
||||
{"class": "MSFT_TaskExecAction", "execute": "%windir%\\system32\\defrag.exe", "arguments": "-c -h -o -$", "class_id": null}
|
||||
],
|
||||
"triggers": [
|
||||
{"class": "MSFT_TaskWeeklyTrigger", "enabled": true, "start": "2026-01-01T01:00:00", "days_interval": null, "weeks_interval": 1, "days_of_week": 1, "interval": "", "duration": "", "delay": ""}
|
||||
],
|
||||
"last_run": "2026-11-01T00:00:12.0000000Z",
|
||||
"last_result": 0,
|
||||
"next_run": "2026-11-08T00:00:00.0000000Z"
|
||||
},
|
||||
{
|
||||
"path": "\\Microsoft\\Windows\\UpdateOrchestrator\\",
|
||||
"name": "Reboot",
|
||||
"state": "Disabled",
|
||||
"user": "SYSTEM",
|
||||
"group": null,
|
||||
"on_demand": true,
|
||||
"description": null,
|
||||
"actions": [
|
||||
{"class": "MSFT_TaskExecAction", "execute": "%systemroot%\\system32\\MusNotification.exe", "arguments": "RebootDialog", "class_id": null}
|
||||
],
|
||||
"triggers": [
|
||||
{"class": "MSFT_TaskTimeTrigger", "enabled": true, "start": "2026-11-04T03:00:00+01:00", "days_interval": null, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": ""}
|
||||
],
|
||||
"last_run": "1999-11-29T23:00:00.0000000Z",
|
||||
"last_result": 267011,
|
||||
"next_run": null
|
||||
},
|
||||
{
|
||||
"path": "\\",
|
||||
"name": "Admin's backup",
|
||||
"state": "Ready",
|
||||
"user": "Administrator",
|
||||
"group": null,
|
||||
"on_demand": true,
|
||||
"description": "Copies D:\\data to the NAS",
|
||||
"actions": [
|
||||
{"class": "MSFT_TaskExecAction", "execute": "robocopy.exe", "arguments": "D:\\data \\\\nas\\backup /MIR", "class_id": null},
|
||||
{"class": "MSFT_TaskExecAction", "execute": "C:\\scripts\\notify.cmd", "arguments": null, "class_id": null}
|
||||
],
|
||||
"triggers": [
|
||||
{"class": "MSFT_TaskDailyTrigger", "enabled": true, "start": "2026-01-01T00:00:00", "days_interval": 1, "weeks_interval": null, "days_of_week": null, "interval": "PT1H", "duration": "P1D", "delay": ""},
|
||||
{"class": "MSFT_TaskDailyTrigger", "enabled": false, "start": "2026-01-01T12:30:00", "days_interval": 2, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": ""}
|
||||
],
|
||||
"last_run": "/Date(1793854800000)/",
|
||||
"last_result": 2147942402,
|
||||
"next_run": "/Date(1793858400000)/"
|
||||
},
|
||||
{
|
||||
"path": "\\",
|
||||
"name": "nightly-dump",
|
||||
"state": "Ready",
|
||||
"user": "backup",
|
||||
"group": null,
|
||||
"on_demand": true,
|
||||
"description": "napalm-scheduled-job: nightly-dump Dump the database\nschedule: 30 2 * * *",
|
||||
"actions": [
|
||||
{"class": "MSFT_TaskExecAction", "execute": "%SystemRoot%\\System32\\cmd.exe", "arguments": "/d /s /c \"pg_dump -f D:\\dump.sql app\"", "class_id": null}
|
||||
],
|
||||
"triggers": [
|
||||
{"class": "MSFT_TaskTrigger", "enabled": true, "start": "2020-01-01T02:30:00", "days_interval": 1, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": ""}
|
||||
],
|
||||
"last_run": "2026-11-03T01:30:04.1234567Z",
|
||||
"last_result": 1,
|
||||
"next_run": "2026-11-04T01:30:00Z"
|
||||
},
|
||||
{
|
||||
"path": "\\Vendor\\",
|
||||
"name": "Updater",
|
||||
"state": "Running",
|
||||
"user": null,
|
||||
"group": "Users",
|
||||
"on_demand": false,
|
||||
"description": "",
|
||||
"actions": [
|
||||
{"class": "MSFT_TaskComHandlerAction", "execute": null, "arguments": null, "class_id": "{A6BA00FE-40E8-477C-B713-C64A14F18ADB}"}
|
||||
],
|
||||
"triggers": [
|
||||
{"class": "MSFT_TaskLogonTrigger", "enabled": true, "start": "", "days_interval": null, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": "PT15M"},
|
||||
{"class": "MSFT_TaskBootTrigger", "enabled": null, "start": "", "days_interval": null, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": ""},
|
||||
{"class": "MSFT_TaskSessionStateChangeTrigger", "enabled": true, "start": "", "days_interval": null, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": ""}
|
||||
],
|
||||
"last_run": "2026-11-03T06:00:00Z",
|
||||
"last_result": 267009,
|
||||
"next_run": null
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,639 @@
|
||||
"""Scheduled jobs on Windows: the Task Scheduler over PowerShell Remoting (#8).
|
||||
|
||||
The reading is one script whose JSON a fake transport answers from
|
||||
tests/fixtures/synthetic/scheduled_tasks.json; every write is one script, read
|
||||
here as text. What a real host does with those scripts the fixtures cannot
|
||||
prove -- see the README there.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import (
|
||||
ScheduledJobChanged,
|
||||
ScheduledJobRefused,
|
||||
ScheduledJobsMixin,
|
||||
job_digest,
|
||||
)
|
||||
|
||||
from napalm_windows import WindowsDriver, task_xml
|
||||
from napalm_windows import scheduled_tasks as mod
|
||||
from napalm_windows.time_zones import iana_time_zone
|
||||
from napalm_windows.transport import PowerShellError
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "scheduled_tasks.json"
|
||||
|
||||
DEFRAG = "task:\\Microsoft\\Windows\\Defrag\\ScheduledDefrag"
|
||||
REBOOT = "task:\\Microsoft\\Windows\\UpdateOrchestrator\\Reboot"
|
||||
BACKUP = "task:\\Admin's backup"
|
||||
DUMP = "task:\\nightly-dump"
|
||||
UPDATER = "task:\\Vendor\\Updater"
|
||||
|
||||
|
||||
def _reading() -> dict[str, Any]:
|
||||
return json.loads(FIXTURE.read_text())
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
"""Answers the reading script with *reading*; records every other script."""
|
||||
|
||||
def __init__(self, reading: Any, fail: str | None = None):
|
||||
self.reading = reading
|
||||
self.fail = fail
|
||||
self.sent: list[str] = []
|
||||
self.is_open = True
|
||||
|
||||
def run(self, script: str) -> str:
|
||||
self.sent.append(script)
|
||||
if script == mod._PS_SCHEDULED_TASKS:
|
||||
return self.reading if isinstance(self.reading, str) else json.dumps(self.reading)
|
||||
if self.fail:
|
||||
raise PowerShellError(self.fail)
|
||||
return ""
|
||||
|
||||
def close(self) -> None:
|
||||
self.is_open = False
|
||||
|
||||
@property
|
||||
def writes(self) -> list[str]:
|
||||
return [s for s in self.sent if s != mod._PS_SCHEDULED_TASKS]
|
||||
|
||||
|
||||
def _driver(reading: Any = None, fail: str | None = None) -> WindowsDriver:
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(_reading() if reading is None else reading, fail) # type: ignore[assignment]
|
||||
return d
|
||||
|
||||
|
||||
def _jobs(reading: Any = None) -> dict[str, dict[str, Any]]:
|
||||
return {j["key"]: dict(j) for j in _driver(reading).get_scheduled_jobs()["jobs"]}
|
||||
|
||||
|
||||
def _digest(key: str, reading: Any = None) -> str:
|
||||
return str(_jobs(reading)[key]["digest"])
|
||||
|
||||
|
||||
def _spec(**changes: Any) -> dict[str, Any]:
|
||||
spec = {
|
||||
"name": "nightly-dump",
|
||||
"schedule": "30 2 * * *",
|
||||
"run_as": "backup",
|
||||
"command": "pg_dump -f D:\\dump.sql app",
|
||||
"enabled": True,
|
||||
"description": "Dump the database",
|
||||
}
|
||||
spec.update(changes)
|
||||
return spec
|
||||
|
||||
|
||||
def _without_dump() -> dict[str, Any]:
|
||||
reading = _reading()
|
||||
reading["tasks"] = [t for t in reading["tasks"] if t["name"] != "nightly-dump"]
|
||||
reading["count"] = len(reading["tasks"])
|
||||
return reading
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The contract
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_a_windows_host_offers_every_verb():
|
||||
assert issubclass(WindowsDriver, ScheduledJobsMixin)
|
||||
for verb in (
|
||||
"get_scheduled_jobs",
|
||||
"manage_scheduled_job",
|
||||
"put_scheduled_job",
|
||||
"delete_scheduled_job",
|
||||
):
|
||||
assert callable(getattr(WindowsDriver, verb))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Reading
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestReading:
|
||||
def test_every_task_in_one_round_trip(self):
|
||||
d = _driver()
|
||||
|
||||
reading = d.get_scheduled_jobs()
|
||||
|
||||
assert len(reading["jobs"]) == 5
|
||||
assert d._transport.sent == [mod._PS_SCHEDULED_TASKS]
|
||||
|
||||
def test_the_script_joins_the_task_and_its_run_info_and_changes_nothing(self):
|
||||
script = mod._PS_SCHEDULED_TASKS
|
||||
assert "Get-ScheduledTask" in script
|
||||
assert "Get-ScheduledTaskInfo" in script
|
||||
assert "ConvertTo-Json" in script
|
||||
for verb in ("Set-", "Register-", "Unregister-", "Enable-", "Disable-", "Start-"):
|
||||
assert verb not in script
|
||||
|
||||
def test_a_platform_task(self):
|
||||
job = _jobs()[DEFRAG]
|
||||
|
||||
assert {k: job[k] for k in job if k != "digest"} == {
|
||||
"key": DEFRAG,
|
||||
"kind": "task",
|
||||
"source": "\\Microsoft\\Windows\\Defrag\\ScheduledDefrag",
|
||||
"run_as": "SYSTEM",
|
||||
"schedule": "weekly on Sun at 01:00",
|
||||
"schedule_kind": "triggers",
|
||||
"command": "%windir%\\system32\\defrag.exe -c -h -o -$",
|
||||
"enabled": True,
|
||||
"managed_by": "platform",
|
||||
"actions": ["enable", "disable", "run"],
|
||||
"description": "This task optimizes local storage drives.",
|
||||
"last_run": "2026-11-01T00:00:12+00:00",
|
||||
"last_result": "success",
|
||||
"next_run": "2026-11-08T00:00:00+00:00",
|
||||
}
|
||||
|
||||
def test_the_digest_is_the_contracts(self):
|
||||
job = _jobs()[DEFRAG]
|
||||
|
||||
assert job["digest"] == job_digest(job)
|
||||
|
||||
def test_a_disabled_task_is_not_enabled_and_cannot_be_run(self):
|
||||
job = _jobs()[REBOOT]
|
||||
|
||||
assert job["enabled"] is False
|
||||
assert job["actions"] == ["enable", "disable"]
|
||||
|
||||
def test_a_task_that_never_ran_has_no_last_run_or_result(self):
|
||||
"""Task Scheduler says 30 November 1999 for never, and 0x41303 for its result."""
|
||||
job = _jobs()[REBOOT]
|
||||
|
||||
assert (job["last_run"], job["last_result"], job["next_run"]) == (None, None, None)
|
||||
|
||||
def test_a_task_without_a_description_has_none(self):
|
||||
assert "description" not in _jobs()[REBOOT]
|
||||
|
||||
def test_a_once_trigger_keeps_its_offset(self):
|
||||
assert _jobs()[REBOOT]["schedule"] == "once at 2026-11-04 03:00+01:00"
|
||||
|
||||
def test_an_admins_task_with_two_actions_and_two_triggers(self):
|
||||
job = _jobs()[BACKUP]
|
||||
|
||||
assert job["managed_by"] == "admin"
|
||||
assert job["run_as"] == "Administrator"
|
||||
assert (
|
||||
job["command"] == "robocopy.exe D:\\data \\\\nas\\backup /MIR\nC:\\scripts\\notify.cmd"
|
||||
)
|
||||
assert job["schedule"] == (
|
||||
"daily at 00:00, every 1 hour for 1 day; every 2 days at 12:30 (disabled)"
|
||||
)
|
||||
assert job["actions"] == ["enable", "disable", "run"]
|
||||
|
||||
def test_json_dates_are_iso_utc(self):
|
||||
job = _jobs()[BACKUP]
|
||||
|
||||
assert job["last_run"] == "2026-11-05T05:00:00+00:00"
|
||||
assert job["next_run"] == "2026-11-05T06:00:00+00:00"
|
||||
|
||||
def test_a_failure_code_is_hex(self):
|
||||
assert _jobs()[BACKUP]["last_result"] == "0x80070002"
|
||||
|
||||
def test_an_applications_task(self):
|
||||
job = _jobs()[DUMP]
|
||||
|
||||
assert job["managed_by"] == "application"
|
||||
assert job["name"] == "nightly-dump"
|
||||
assert job["description"] == "Dump the database"
|
||||
assert (job["schedule"], job["schedule_kind"]) == ("30 2 * * *", "cron")
|
||||
assert job["command"] == "pg_dump -f D:\\dump.sql app"
|
||||
assert job["run_as"] == "backup"
|
||||
assert job["actions"] == ["enable", "disable", "run", "edit", "delete"]
|
||||
assert job["last_result"] == "0x1"
|
||||
assert job["last_run"] == "2026-11-03T01:30:04.123456+00:00"
|
||||
|
||||
def test_an_applications_digest_covers_its_triggers(self):
|
||||
"""Triggers changed by hand change the digest, although the cron line stays."""
|
||||
changed = _reading()
|
||||
changed["tasks"][3]["triggers"][0]["start"] = "2020-01-01T03:30:00"
|
||||
|
||||
assert _digest(DUMP, changed) != _digest(DUMP)
|
||||
assert _jobs(changed)[DUMP]["schedule"] == "30 2 * * *"
|
||||
|
||||
def test_an_application_task_without_its_schedule_line_shows_its_triggers(self):
|
||||
reading = _reading()
|
||||
reading["tasks"][3]["description"] = "napalm-scheduled-job: nightly-dump"
|
||||
job = _jobs(reading)[DUMP]
|
||||
|
||||
assert (job["managed_by"], job["name"]) == ("application", "nightly-dump")
|
||||
assert "description" not in job
|
||||
assert (job["schedule"], job["schedule_kind"]) == ("trigger at 02:30", "triggers")
|
||||
|
||||
def test_an_application_task_whose_action_was_changed_shows_it(self):
|
||||
reading = _reading()
|
||||
reading["tasks"][3]["actions"][0]["arguments"] = "/c whoami"
|
||||
|
||||
assert _jobs(reading)[DUMP]["command"] == "%SystemRoot%\\System32\\cmd.exe /c whoami"
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("path", "name"),
|
||||
[("\\Vendor\\", "nightly-dump"), ("\\", "other-name"), ("\\", "Nightly Dump")],
|
||||
)
|
||||
def test_the_marker_counts_only_on_the_root_task_of_that_name(self, path, name):
|
||||
reading = _reading()
|
||||
reading["tasks"][3].update(path=path, name=name)
|
||||
|
||||
job = _jobs(reading)[f"task:{path}{name}"]
|
||||
|
||||
assert job["managed_by"] == "admin"
|
||||
assert "edit" not in job["actions"]
|
||||
assert "name" not in job
|
||||
|
||||
def test_a_group_principal_a_com_handler_and_event_triggers(self):
|
||||
job = _jobs()[UPDATER]
|
||||
|
||||
assert job["run_as"] == "Users"
|
||||
assert job["command"] == "COM handler {A6BA00FE-40E8-477C-B713-C64A14F18ADB}"
|
||||
assert job["schedule"] == "at logon after 15 minutes; at startup; session state change"
|
||||
assert job["enabled"] is True
|
||||
assert job["last_result"] == "running"
|
||||
|
||||
def test_a_task_that_cannot_be_started_on_demand_does_not_offer_run(self):
|
||||
assert _jobs()[UPDATER]["actions"] == ["enable", "disable"]
|
||||
|
||||
def test_the_time_zone_is_iana(self):
|
||||
assert _driver().get_scheduled_jobs()["time_zone"] == "Europe/Berlin"
|
||||
|
||||
def test_an_unknown_time_zone_is_none(self):
|
||||
reading = _reading()
|
||||
reading["time_zone"] = "Mars Standard Time"
|
||||
|
||||
assert _driver(reading).get_scheduled_jobs()["time_zone"] is None
|
||||
|
||||
def test_one_task_arrives_as_a_bare_object(self):
|
||||
"""ConvertTo-Json unwraps a one-element array, nested ones too."""
|
||||
task = _reading()["tasks"][2]
|
||||
task["actions"] = task["actions"][0]
|
||||
task["triggers"] = task["triggers"][0]
|
||||
reading = {"time_zone": "UTC", "count": 1, "tasks": task}
|
||||
|
||||
(job,) = _driver(reading).get_scheduled_jobs()["jobs"]
|
||||
|
||||
assert job["key"] == BACKUP
|
||||
assert job["command"] == "robocopy.exe D:\\data \\\\nas\\backup /MIR"
|
||||
assert job["schedule"] == "daily at 00:00, every 1 hour for 1 day"
|
||||
|
||||
def test_a_host_without_tasks(self):
|
||||
reading = {"time_zone": None, "count": 0, "tasks": None}
|
||||
|
||||
assert _driver(reading).get_scheduled_jobs() == {"jobs": [], "time_zone": None}
|
||||
|
||||
def test_a_reading_cut_short_raises(self):
|
||||
with pytest.raises(ValueError):
|
||||
_driver(json.dumps(_reading())[:-40]).get_scheduled_jobs()
|
||||
|
||||
def test_a_reading_with_fewer_tasks_than_counted_raises(self):
|
||||
reading = _reading()
|
||||
reading["count"] = 6
|
||||
|
||||
with pytest.raises(ValueError, match="6"):
|
||||
_driver(reading).get_scheduled_jobs()
|
||||
|
||||
def test_an_empty_answer_raises(self):
|
||||
with pytest.raises(ValueError):
|
||||
_driver("").get_scheduled_jobs()
|
||||
|
||||
def test_a_failed_reading_raises(self):
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(_reading()) # type: ignore[assignment]
|
||||
d._transport.reading = None
|
||||
d._transport.run = lambda script: (_ for _ in ()).throw(PowerShellError("Access denied")) # type: ignore[method-assign]
|
||||
|
||||
with pytest.raises(PowerShellError):
|
||||
d.get_scheduled_jobs()
|
||||
|
||||
|
||||
class TestOddTasks:
|
||||
def _job(self, **changes: Any) -> dict[str, Any]:
|
||||
task = _reading()["tasks"][0]
|
||||
task.update(changes)
|
||||
return _jobs({"time_zone": None, "count": 1, "tasks": [task]})[DEFRAG]
|
||||
|
||||
def test_an_action_without_a_command_or_handler_names_its_class(self):
|
||||
job = self._job(actions=[{"class": "MSFT_TaskSendEmailAction"}])
|
||||
|
||||
assert job["command"] == "MSFT_TaskSendEmailAction"
|
||||
|
||||
def test_a_start_and_delay_it_cannot_read_are_kept_as_they_are(self):
|
||||
trigger = {"class": "MSFT_TaskDailyTrigger", "start": "soon", "delay": "a while"}
|
||||
|
||||
assert self._job(triggers=[trigger])["schedule"] == "daily at soon after a while"
|
||||
|
||||
def test_a_task_that_never_ran_since_it_was_read_has_no_result(self):
|
||||
job = self._job(last_result=267011)
|
||||
|
||||
assert job["last_run"] is not None
|
||||
assert job["last_result"] is None
|
||||
|
||||
def test_a_negative_result_is_the_same_code(self):
|
||||
assert self._job(last_result=-2147024894)["last_result"] == "0x80070002"
|
||||
|
||||
def test_a_reading_that_is_not_an_object_raises(self):
|
||||
with pytest.raises(ValueError, match="reading"):
|
||||
_driver("[]").get_scheduled_jobs()
|
||||
|
||||
|
||||
class TestTimestamps:
|
||||
@pytest.mark.parametrize(
|
||||
("value", "iso"),
|
||||
[
|
||||
(None, None),
|
||||
("", None),
|
||||
("2026-11-03T01:30:00Z", "2026-11-03T01:30:00+00:00"),
|
||||
("2026-11-03T02:30:00+01:00", "2026-11-03T01:30:00+00:00"),
|
||||
("2026-11-03T01:30:00", "2026-11-03T01:30:00+00:00"),
|
||||
("/Date(1793854800000)/", "2026-11-05T05:00:00+00:00"),
|
||||
("/Date(1793854800000+0100)/", "2026-11-05T05:00:00+00:00"),
|
||||
(1793854800, "2026-11-05T05:00:00+00:00"),
|
||||
("1999-11-30T00:00:00", None),
|
||||
("/Date(943916400000)/", None),
|
||||
("not a date", None),
|
||||
],
|
||||
)
|
||||
def test_to_iso_utc(self, value, iso):
|
||||
assert mod._timestamp(value) == iso
|
||||
|
||||
|
||||
class TestTimeZones:
|
||||
@pytest.mark.parametrize(
|
||||
("windows", "iana"),
|
||||
[
|
||||
("W. Europe Standard Time", "Europe/Berlin"),
|
||||
("GMT Standard Time", "Europe/London"),
|
||||
("Eastern Standard Time", "America/New_York"),
|
||||
("UTC", "Etc/UTC"),
|
||||
("Tokyo Standard Time", "Asia/Tokyo"),
|
||||
("Mars Standard Time", None),
|
||||
(None, None),
|
||||
],
|
||||
)
|
||||
def test_a_windows_zone_id_as_iana(self, windows, iana):
|
||||
assert iana_time_zone(windows) == iana
|
||||
|
||||
def test_every_name_in_the_table_is_a_real_zone(self):
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from napalm_windows.time_zones import WINDOWS_TO_IANA
|
||||
|
||||
for name in WINDOWS_TO_IANA.values():
|
||||
ZoneInfo(name)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Enable, disable, run
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestManage:
|
||||
@pytest.mark.parametrize(
|
||||
("action", "cmdlet"),
|
||||
[("enable", "Enable-ScheduledTask"), ("disable", "Disable-ScheduledTask")],
|
||||
)
|
||||
def test_switches_the_tasks_own_flag(self, action, cmdlet):
|
||||
d = _driver()
|
||||
|
||||
result = d.manage_scheduled_job(DEFRAG, action, digest=_digest(DEFRAG))
|
||||
|
||||
(script,) = d._transport.writes
|
||||
assert cmdlet in script
|
||||
assert "'\\Microsoft\\Windows\\Defrag\\'" in script
|
||||
assert "'ScheduledDefrag'" in script
|
||||
assert result == {"success": True, "output": f"{DEFRAG} {action}d"}
|
||||
|
||||
def test_run_says_the_task_was_started_not_that_it_finished(self):
|
||||
d = _driver()
|
||||
|
||||
result = d.manage_scheduled_job(DEFRAG, "run", digest=_digest(DEFRAG))
|
||||
|
||||
(script,) = d._transport.writes
|
||||
assert "Start-ScheduledTask" in script
|
||||
assert result["success"] is True
|
||||
assert "started" in result["output"]
|
||||
assert "next reading" in result["output"]
|
||||
|
||||
def test_reads_again_before_it_writes(self):
|
||||
d = _driver()
|
||||
|
||||
d.manage_scheduled_job(DEFRAG, "disable", digest=_digest(DEFRAG))
|
||||
|
||||
assert d._transport.sent[0] == mod._PS_SCHEDULED_TASKS
|
||||
|
||||
def test_the_task_is_found_by_exact_path_and_name(self):
|
||||
"""Not by -TaskName, which takes wildcards."""
|
||||
d = _driver()
|
||||
|
||||
d.manage_scheduled_job(DEFRAG, "disable", digest=_digest(DEFRAG))
|
||||
|
||||
script = d._transport.writes[0]
|
||||
assert "-eq '\\Microsoft\\Windows\\Defrag\\'" in script
|
||||
assert "-eq 'ScheduledDefrag'" in script
|
||||
assert "-TaskName" not in script
|
||||
|
||||
def test_a_quote_in_a_task_name_is_doubled(self):
|
||||
d = _driver()
|
||||
|
||||
d.manage_scheduled_job(BACKUP, "disable", digest=_digest(BACKUP))
|
||||
|
||||
assert "'Admin''s backup'" in d._transport.writes[0]
|
||||
|
||||
def test_a_changed_task_is_not_switched(self):
|
||||
d = _driver()
|
||||
|
||||
with pytest.raises(ScheduledJobChanged):
|
||||
d.manage_scheduled_job(DEFRAG, "disable", digest="0" * 16)
|
||||
assert d._transport.writes == []
|
||||
|
||||
def test_an_unknown_task_raises_lookup_error(self):
|
||||
with pytest.raises(LookupError):
|
||||
_driver().manage_scheduled_job("task:\\nope", "run", digest="0" * 16)
|
||||
|
||||
def test_an_unknown_action_is_refused_before_anything_is_sent(self):
|
||||
d = _driver()
|
||||
|
||||
with pytest.raises(ScheduledJobRefused, match="action"):
|
||||
d.manage_scheduled_job(DEFRAG, "delete", digest=_digest(DEFRAG))
|
||||
assert d._transport.writes == []
|
||||
|
||||
def test_a_disabled_task_is_not_run(self):
|
||||
d = _driver()
|
||||
|
||||
with pytest.raises(ScheduledJobRefused, match="run"):
|
||||
d.manage_scheduled_job(REBOOT, "run", digest=_digest(REBOOT))
|
||||
assert d._transport.writes == []
|
||||
|
||||
def test_what_powershell_says_is_the_result(self):
|
||||
d = _driver(fail="Access is denied.")
|
||||
|
||||
result = d.manage_scheduled_job(DEFRAG, "disable", digest=_digest(DEFRAG))
|
||||
|
||||
assert result == {"success": False, "output": "Access is denied."}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# An application's own task
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestPut:
|
||||
def test_creates_the_task_in_the_root_folder_from_xml(self):
|
||||
d = _driver(_without_dump())
|
||||
|
||||
result = d.put_scheduled_job(_spec()) # type: ignore[arg-type]
|
||||
|
||||
(script,) = d._transport.writes
|
||||
assert "Register-ScheduledTask -TaskPath '\\' -TaskName 'nightly-dump' -Xml '" in script
|
||||
assert "-Force" in script
|
||||
assert result == {"success": True, "output": f"{DUMP} created"}
|
||||
|
||||
def test_the_xml_carries_the_definition(self):
|
||||
d = _driver(_without_dump())
|
||||
|
||||
d.put_scheduled_job(_spec()) # type: ignore[arg-type]
|
||||
|
||||
script = d._transport.writes[0]
|
||||
assert task_xml.task_xml(_spec()).replace("'", "''") in script # type: ignore[arg-type]
|
||||
|
||||
def test_a_task_of_that_name_there_already(self):
|
||||
d = _driver()
|
||||
|
||||
with pytest.raises(ScheduledJobChanged, match="already"):
|
||||
d.put_scheduled_job(_spec()) # type: ignore[arg-type]
|
||||
assert d._transport.writes == []
|
||||
|
||||
def test_an_admins_root_task_of_that_name_is_not_overwritten(self):
|
||||
reading = _reading()
|
||||
reading["tasks"][3]["description"] = "mine"
|
||||
|
||||
d = _driver(reading)
|
||||
with pytest.raises(ScheduledJobChanged, match="already"):
|
||||
d.put_scheduled_job(_spec()) # type: ignore[arg-type]
|
||||
with pytest.raises(ScheduledJobRefused, match="application"):
|
||||
d.put_scheduled_job(_spec(), digest=_digest(DUMP, reading)) # type: ignore[arg-type]
|
||||
assert d._transport.writes == []
|
||||
|
||||
def test_changes_its_own_task_with_the_digest_it_saw(self):
|
||||
d = _driver()
|
||||
|
||||
result = d.put_scheduled_job(_spec(schedule="*/5 * * * *"), digest=_digest(DUMP)) # type: ignore[arg-type]
|
||||
|
||||
assert "Register-ScheduledTask" in d._transport.writes[0]
|
||||
assert "<Interval>PT5M</Interval>" in d._transport.writes[0]
|
||||
assert result == {"success": True, "output": f"{DUMP} changed"}
|
||||
|
||||
def test_a_changed_task_is_not_overwritten(self):
|
||||
d = _driver()
|
||||
|
||||
with pytest.raises(ScheduledJobChanged):
|
||||
d.put_scheduled_job(_spec(), digest="0" * 16) # type: ignore[arg-type]
|
||||
assert d._transport.writes == []
|
||||
|
||||
def test_a_task_that_went_away_is_not_changed(self):
|
||||
d = _driver(_without_dump())
|
||||
|
||||
with pytest.raises(LookupError):
|
||||
d.put_scheduled_job(_spec(), digest="0" * 16) # type: ignore[arg-type]
|
||||
|
||||
def test_a_spec_the_contract_refuses_is_refused_before_anything_is_sent(self):
|
||||
d = _driver()
|
||||
|
||||
with pytest.raises(ScheduledJobRefused, match="name"):
|
||||
d.put_scheduled_job(_spec(name="Nightly Dump")) # type: ignore[arg-type]
|
||||
assert d._transport.sent == []
|
||||
|
||||
def test_a_schedule_task_scheduler_cannot_take_is_refused_before_anything_is_sent(self):
|
||||
d = _driver(_without_dump())
|
||||
|
||||
with pytest.raises(ScheduledJobRefused, match="weekday"):
|
||||
d.put_scheduled_job(_spec(schedule="0 0 1 * 1")) # type: ignore[arg-type]
|
||||
assert d._transport.sent == []
|
||||
|
||||
def test_quotes_in_the_command_are_doubled_for_powershell(self):
|
||||
d = _driver(_without_dump())
|
||||
|
||||
d.put_scheduled_job(_spec(command="echo it's done’")) # type: ignore[arg-type]
|
||||
|
||||
script = d._transport.writes[0]
|
||||
assert "echo it''s done’’" in script
|
||||
body = script.split("-Xml '", 1)[1].rsplit("' -Force", 1)[0]
|
||||
for quote in ("'", "‘", "’", "‚", "‛"):
|
||||
assert quote not in body.replace(quote * 2, "")
|
||||
|
||||
def test_what_powershell_says_is_the_result(self):
|
||||
d = _driver(_without_dump(), fail="The user name or password is incorrect.")
|
||||
|
||||
result = d.put_scheduled_job(_spec()) # type: ignore[arg-type]
|
||||
|
||||
assert result == {"success": False, "output": "The user name or password is incorrect."}
|
||||
|
||||
|
||||
class TestDelete:
|
||||
def test_unregisters_its_own_task(self):
|
||||
d = _driver()
|
||||
|
||||
result = d.delete_scheduled_job(DUMP, digest=_digest(DUMP))
|
||||
|
||||
(script,) = d._transport.writes
|
||||
assert (
|
||||
"Unregister-ScheduledTask -TaskPath '\\' -TaskName 'nightly-dump' -Confirm:$false"
|
||||
in script
|
||||
)
|
||||
assert result == {"success": True, "output": f"{DUMP} deleted"}
|
||||
|
||||
@pytest.mark.parametrize("key", [DEFRAG, BACKUP])
|
||||
def test_a_task_an_application_did_not_write_is_refused(self, key):
|
||||
d = _driver()
|
||||
|
||||
with pytest.raises(ScheduledJobRefused, match="application"):
|
||||
d.delete_scheduled_job(key, digest=_digest(key))
|
||||
assert d._transport.writes == []
|
||||
|
||||
def test_a_changed_task_is_not_deleted(self):
|
||||
d = _driver()
|
||||
|
||||
with pytest.raises(ScheduledJobChanged):
|
||||
d.delete_scheduled_job(DUMP, digest="0" * 16)
|
||||
assert d._transport.writes == []
|
||||
|
||||
def test_an_unknown_task_raises_lookup_error(self):
|
||||
with pytest.raises(LookupError):
|
||||
_driver().delete_scheduled_job("task:\\nope", digest="0" * 16)
|
||||
|
||||
def test_what_powershell_says_is_the_result(self):
|
||||
d = _driver(fail="Access is denied.")
|
||||
|
||||
result = d.delete_scheduled_job(DUMP, digest=_digest(DUMP))
|
||||
|
||||
assert result == {"success": False, "output": "Access is denied."}
|
||||
|
||||
|
||||
def test_a_written_task_reads_back_as_the_spec():
|
||||
"""What put writes, the reading parses back to the same cron line and command."""
|
||||
spec = _spec(command='"C:\\Program Files\\app\\run.exe" --quiet & echo done')
|
||||
xml = task_xml.task_xml(spec) # type: ignore[arg-type]
|
||||
execute, arguments = task_xml.command_action(spec["command"])
|
||||
reading = _reading()
|
||||
task = copy.deepcopy(reading["tasks"][3])
|
||||
task["actions"] = [{"class": "MSFT_TaskExecAction", "execute": execute, "arguments": arguments}]
|
||||
task["description"] = task_xml.description(spec) # type: ignore[arg-type]
|
||||
reading["tasks"][3] = task
|
||||
|
||||
job = _jobs(reading)[DUMP]
|
||||
|
||||
assert (job["command"], job["schedule"], job["description"]) == (
|
||||
spec["command"],
|
||||
spec["schedule"],
|
||||
spec["description"],
|
||||
)
|
||||
assert f"<Command>{execute}</Command>" in xml
|
||||
@@ -0,0 +1,260 @@
|
||||
"""An application's task as Task Scheduler XML, and a cron expression as its triggers (#8).
|
||||
|
||||
A cron shape Task Scheduler can express exactly becomes triggers; every other
|
||||
shape is refused, naming why.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import xml.etree.ElementTree as ET # noqa: S405 - parses only what the tests built
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import ScheduledJobRefused
|
||||
|
||||
from napalm_windows import task_xml
|
||||
|
||||
NS = {"t": "http://schemas.microsoft.com/windows/2004/02/mit/task"}
|
||||
|
||||
|
||||
def _spec(**changes: Any) -> Any:
|
||||
spec = {
|
||||
"name": "nightly-dump",
|
||||
"schedule": "30 2 * * *",
|
||||
"run_as": "backup",
|
||||
"command": "pg_dump -f D:\\dump.sql app",
|
||||
"enabled": True,
|
||||
"description": "Dump the database",
|
||||
}
|
||||
spec.update(changes)
|
||||
return spec
|
||||
|
||||
|
||||
def _task(**changes: Any) -> ET.Element:
|
||||
return ET.fromstring(task_xml.task_xml(_spec(**changes))) # noqa: S314
|
||||
|
||||
|
||||
def _text(task: ET.Element, path: str) -> str | None:
|
||||
found = task.find(path, NS)
|
||||
return None if found is None else found.text
|
||||
|
||||
|
||||
def _triggers(schedule: str) -> list[dict[str, Any]]:
|
||||
"""Each trigger as start, repetition and day schedule, for comparing."""
|
||||
triggers = []
|
||||
found = _task(schedule=schedule).find("t:Triggers", NS)
|
||||
assert found is not None
|
||||
for trigger in found:
|
||||
tag = trigger.tag.split("}")[1]
|
||||
entry: dict[str, Any] = {"type": tag}
|
||||
if tag == "CalendarTrigger":
|
||||
entry["start"] = _text(trigger, "t:StartBoundary")
|
||||
entry["repeat"] = (
|
||||
_text(trigger, "t:Repetition/t:Interval"),
|
||||
_text(trigger, "t:Repetition/t:Duration"),
|
||||
)
|
||||
schedule_by = next(c for c in trigger if c.tag.split("}")[1].startswith("Schedule"))
|
||||
entry["by"] = schedule_by.tag.split("}")[1]
|
||||
entry["days"] = [d.text for d in schedule_by.iter(f"{{{NS['t']}}}Day")]
|
||||
entry["names"] = [
|
||||
c.tag.split("}")[1]
|
||||
for part in ("DaysOfWeek", "Months")
|
||||
for parent in schedule_by.iter(f"{{{NS['t']}}}{part}")
|
||||
for c in parent
|
||||
]
|
||||
triggers.append(entry)
|
||||
return triggers
|
||||
|
||||
|
||||
class TestTriggers:
|
||||
def test_daily_at_one_time(self):
|
||||
assert _triggers("30 2 * * *") == [
|
||||
{
|
||||
"type": "CalendarTrigger",
|
||||
"start": "2020-01-01T02:30:00",
|
||||
"repeat": (None, None),
|
||||
"by": "ScheduleByDay",
|
||||
"days": [],
|
||||
"names": [],
|
||||
}
|
||||
]
|
||||
|
||||
def test_the_daily_alias(self):
|
||||
assert [t["start"] for t in _triggers("@daily")] == ["2020-01-01T00:00:00"]
|
||||
|
||||
def test_weekdays_at_two_times_are_two_weekly_triggers(self):
|
||||
triggers = _triggers("0 8,17 * * 1-5")
|
||||
|
||||
assert [t["start"] for t in triggers] == ["2020-01-01T08:00:00", "2020-01-01T17:00:00"]
|
||||
assert {t["by"] for t in triggers} == {"ScheduleByWeek"}
|
||||
assert triggers[0]["names"] == ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
|
||||
|
||||
def test_sunday_is_0_and_7(self):
|
||||
assert _triggers("0 0 * * 0")[0]["names"] == _triggers("0 0 * * 7")[0]["names"]
|
||||
assert _triggers("0 0 * * 7")[0]["names"] == ["Sunday"]
|
||||
|
||||
def test_every_five_minutes_is_one_repetition(self):
|
||||
assert _triggers("*/5 * * * *") == [
|
||||
{
|
||||
"type": "CalendarTrigger",
|
||||
"start": "2020-01-01T00:00:00",
|
||||
"repeat": ("PT5M", "PT23H56M"),
|
||||
"by": "ScheduleByDay",
|
||||
"days": [],
|
||||
"names": [],
|
||||
}
|
||||
]
|
||||
|
||||
def test_every_quarter_hour_in_working_hours(self):
|
||||
(trigger,) = _triggers("*/15 8-17 * * 1-5")
|
||||
|
||||
assert (trigger["start"], trigger["repeat"]) == (
|
||||
"2020-01-01T08:00:00",
|
||||
("PT15M", "PT9H46M"),
|
||||
)
|
||||
assert trigger["by"] == "ScheduleByWeek"
|
||||
|
||||
def test_every_six_hours(self):
|
||||
(trigger,) = _triggers("0 */6 * * *")
|
||||
|
||||
assert trigger["repeat"] == ("PT6H", "PT18H1M")
|
||||
|
||||
def test_every_minute(self):
|
||||
(trigger,) = _triggers("* * * * *")
|
||||
|
||||
assert (trigger["start"], trigger["repeat"]) == ("2020-01-01T00:00:00", ("PT1M", "PT24H"))
|
||||
|
||||
def test_a_step_that_does_not_divide_the_hour_repeats_within_each_hour(self):
|
||||
"""*/7 fires at :56 and then at :00 -- four minutes, not seven: one repetition per hour."""
|
||||
triggers = _triggers("*/7 * * * *")
|
||||
|
||||
assert len(triggers) == 24
|
||||
assert triggers[1]["start"] == "2020-01-01T01:00:00"
|
||||
assert {t["repeat"] for t in triggers} == {("PT7M", "PT57M")}
|
||||
|
||||
def test_two_hours_of_every_other_minute(self):
|
||||
triggers = _triggers("*/2 8,17 * * *")
|
||||
|
||||
assert [(t["start"], t["repeat"]) for t in triggers] == [
|
||||
("2020-01-01T08:00:00", ("PT2M", "PT59M")),
|
||||
("2020-01-01T17:00:00", ("PT2M", "PT59M")),
|
||||
]
|
||||
|
||||
def test_days_of_the_month(self):
|
||||
(trigger,) = _triggers("0 3 1,15 * *")
|
||||
|
||||
assert (trigger["by"], trigger["days"]) == ("ScheduleByMonth", ["1", "15"])
|
||||
assert len(trigger["names"]) == 12
|
||||
|
||||
def test_some_months_only(self):
|
||||
(trigger,) = _triggers("0 0 * 1,jul *")
|
||||
|
||||
assert trigger["by"] == "ScheduleByMonth"
|
||||
assert trigger["days"] == [str(d) for d in range(1, 32)]
|
||||
assert trigger["names"] == ["January", "July"]
|
||||
|
||||
def test_reboot_is_a_boot_trigger(self):
|
||||
assert _triggers("@reboot") == [{"type": "BootTrigger"}]
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("schedule", "why"),
|
||||
[
|
||||
("0 0 1 * 1", "either"),
|
||||
("0 0 */2 * 1", "weekday"),
|
||||
("0 0 * 1 1", "weekday"),
|
||||
("0,1,5 * * * *", "48"),
|
||||
],
|
||||
)
|
||||
def test_a_shape_task_scheduler_cannot_take_is_refused(self, schedule, why):
|
||||
with pytest.raises(ScheduledJobRefused, match=why):
|
||||
task_xml.task_xml(_spec(schedule=schedule))
|
||||
|
||||
def test_an_expression_cron_would_not_take_is_refused(self):
|
||||
with pytest.raises(ScheduledJobRefused, match="range"):
|
||||
task_xml.triggers("61 * * * *")
|
||||
|
||||
def test_at_most_48_triggers(self):
|
||||
assert len(_triggers("0,30 0-23 * * *")) == 1 # one repetition
|
||||
assert len(_triggers("0,20 0-11,13-23 * * *")) == 46
|
||||
with pytest.raises(ScheduledJobRefused, match="48"):
|
||||
task_xml.task_xml(_spec(schedule="0,20,30 0-11,13-23 * * *"))
|
||||
|
||||
|
||||
class TestTask:
|
||||
def test_the_description_names_the_job_and_keeps_its_cron_line(self):
|
||||
assert _text(_task(), "t:RegistrationInfo/t:Description") == (
|
||||
"napalm-scheduled-job: nightly-dump Dump the database\nschedule: 30 2 * * *"
|
||||
)
|
||||
|
||||
def test_a_job_without_a_description(self):
|
||||
assert task_xml.description(_spec(description="")) == (
|
||||
"napalm-scheduled-job: nightly-dump\nschedule: 30 2 * * *"
|
||||
)
|
||||
|
||||
def test_the_command_runs_in_cmd(self):
|
||||
task = _task(command='"C:\\Program Files\\app.exe" -x & echo <done>')
|
||||
|
||||
assert _text(task, "t:Actions/t:Exec/t:Command") == "%SystemRoot%\\System32\\cmd.exe"
|
||||
assert _text(task, "t:Actions/t:Exec/t:Arguments") == (
|
||||
'/d /s /c ""C:\\Program Files\\app.exe" -x & echo <done>"'
|
||||
)
|
||||
|
||||
def test_the_xml_is_escaped(self):
|
||||
raw = task_xml.task_xml(_spec(command="a & b < c", description="x > y & z"))
|
||||
|
||||
assert "a & b < c" in raw
|
||||
assert "x > y & z" in raw
|
||||
|
||||
def test_a_user_runs_without_a_stored_password(self):
|
||||
task = _task(run_as="backup")
|
||||
|
||||
assert _text(task, "t:Principals/t:Principal/t:UserId") == "backup"
|
||||
assert _text(task, "t:Principals/t:Principal/t:LogonType") == "S4U"
|
||||
assert _text(task, "t:Principals/t:Principal/t:RunLevel") == "LeastPrivilege"
|
||||
|
||||
@pytest.mark.parametrize("run_as", ["SYSTEM", "system"])
|
||||
def test_system_is_the_local_system_account(self, run_as):
|
||||
task = _task(run_as=run_as)
|
||||
|
||||
assert _text(task, "t:Principals/t:Principal/t:UserId") == "S-1-5-18"
|
||||
assert _text(task, "t:Principals/t:Principal/t:LogonType") is None
|
||||
assert _text(task, "t:Principals/t:Principal/t:RunLevel") == "HighestAvailable"
|
||||
|
||||
@pytest.mark.parametrize("enabled", [True, False])
|
||||
def test_enabled_is_the_tasks_flag(self, enabled):
|
||||
assert _text(_task(enabled=enabled), "t:Settings/t:Enabled") == str(enabled).lower()
|
||||
|
||||
def test_runs_like_cron_on_battery_and_without_catching_up(self):
|
||||
task = _task()
|
||||
|
||||
assert _text(task, "t:Settings/t:DisallowStartIfOnBatteries") == "false"
|
||||
assert _text(task, "t:Settings/t:StopIfGoingOnBatteries") == "false"
|
||||
assert _text(task, "t:Settings/t:StartWhenAvailable") == "false"
|
||||
assert _text(task, "t:Settings/t:MultipleInstancesPolicy") == "IgnoreNew"
|
||||
|
||||
def test_a_command_is_one_line(self):
|
||||
with pytest.raises(ScheduledJobRefused, match="one line"):
|
||||
task_xml.task_xml(_spec(command="echo a\necho b"))
|
||||
|
||||
def test_a_control_character_is_refused(self):
|
||||
with pytest.raises(ScheduledJobRefused, match="control"):
|
||||
task_xml.task_xml(_spec(command="echo \x07"))
|
||||
|
||||
def test_trailing_whitespace_of_the_command_is_dropped(self):
|
||||
assert task_xml.command_action("echo hi\n") == (
|
||||
"%SystemRoot%\\System32\\cmd.exe",
|
||||
'/d /s /c "echo hi"',
|
||||
)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("execute", "arguments", "command"),
|
||||
[
|
||||
("%SystemRoot%\\System32\\cmd.exe", '/d /s /c "echo hi"', "echo hi"),
|
||||
("%systemroot%\\system32\\CMD.EXE", '/d /s /c "echo hi"', "echo hi"),
|
||||
("%SystemRoot%\\System32\\cmd.exe", "/c echo hi", None),
|
||||
("powershell.exe", '/d /s /c "echo hi"', None),
|
||||
("%SystemRoot%\\System32\\cmd.exe", None, None),
|
||||
],
|
||||
)
|
||||
def test_the_command_back_from_the_action(self, execute, arguments, command):
|
||||
assert task_xml.own_command(execute, arguments) == command
|
||||
Reference in new issue
Block a user