Skip to content

Commit a4c3a40

Browse files
committed
feat(cli): add cloud job update command
1 parent 1020253 commit a4c3a40

2 files changed

Lines changed: 238 additions & 1 deletion

File tree

‎roborock/cli.py‎

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@
5050
) from err
5151

5252
from roborock import RoborockCommand
53-
from roborock.data import RoborockBase, UserData
53+
from roborock.data import HomeDataSchedule, RoborockBase, UserData
5454
from roborock.data.b01_q10.b01_q10_code_mappings import (
5555
B01_Q10_DP,
5656
YXCleanType,
@@ -428,6 +428,61 @@ async def execute_scene(ctx, scene_id):
428428
await client.execute_scene(connection_cache.user_data, scene_id)
429429

430430

431+
def _load_job_file(ctx: click.Context, param: click.Parameter, value: Path) -> HomeDataSchedule:
432+
"""Read a complete job replacement without coercing user-supplied JSON types."""
433+
try:
434+
data = json.loads(value.read_text(encoding="utf-8"))
435+
except (OSError, UnicodeError, json.JSONDecodeError) as err:
436+
raise click.BadParameter(f"Could not read job JSON: {err}") from err
437+
if not isinstance(data, dict):
438+
raise click.BadParameter("Expected a JSON object")
439+
required = {"id", "cron", "repeated", "enabled", "param"}
440+
if missing := required - data.keys():
441+
raise click.BadParameter(f"Complete job required; missing fields: {', '.join(sorted(missing))}")
442+
if unknown := data.keys() - required:
443+
raise click.BadParameter(f"Unknown job fields: {', '.join(sorted(unknown))}")
444+
if type(data["id"]) is not int:
445+
raise click.BadParameter("'id' must be an integer")
446+
if not isinstance(data["cron"], str) or not data["cron"].strip():
447+
raise click.BadParameter("'cron' must be a nonempty string")
448+
for field in ("repeated", "enabled"):
449+
if not isinstance(data[field], bool):
450+
raise click.BadParameter(f"'{field}' must be a boolean")
451+
if not isinstance(data["param"], dict):
452+
raise click.BadParameter("'param' must be an object")
453+
return HomeDataSchedule(
454+
id=data["id"], cron=data["cron"], repeated=data["repeated"], enabled=data["enabled"], param=data["param"]
455+
)
456+
457+
458+
@click.command()
459+
@click.option("--device_id", required=True)
460+
@click.option(
461+
"--job-file",
462+
"job",
463+
required=True,
464+
type=click.Path(exists=True, dir_okay=False, readable=True, path_type=Path),
465+
callback=_load_job_file,
466+
help="JSON file containing id, cron, repeated, enabled, and param (object).",
467+
)
468+
@click.pass_context
469+
@async_command
470+
async def update_job(ctx: click.Context, device_id: str, job: HomeDataSchedule) -> None:
471+
"""Replace a cloud job using a complete schedule JSON file.
472+
473+
Include all existing settings in the file, including unchanged cleaning parameters.
474+
"""
475+
context: RoborockContext = ctx.obj
476+
try:
477+
connection_cache = context.connection_cache()
478+
client = RoborockApiClient(connection_cache.email)
479+
await client.update_job(connection_cache.user_data, device_id, job)
480+
except RoborockException as err:
481+
click.echo(f"Error: {err}", err=True)
482+
raise SystemExit(1) from err
483+
click.echo(f"Updated job {job.id} for device {device_id}")
484+
485+
431486
async def _v1_trait(context: RoborockContext, device_id: str, display_func: Callable[[], V1TraitMixin]) -> Trait:
432487
device_manager = await context.get_device_manager()
433488
device = await device_manager.get_device(device_id)
@@ -1366,6 +1421,7 @@ def write_markdown_table(product_features: dict[str, dict[str, any]], all_featur
13661421
cli.add_command(list_devices)
13671422
cli.add_command(list_scenes)
13681423
cli.add_command(execute_scene)
1424+
cli.add_command(update_job)
13691425
cli.add_command(status)
13701426
cli.add_command(command)
13711427
cli.add_command(parser)

‎tests/test_cli.py‎

Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
"""Tests for the command line interface."""
2+
3+
import json
4+
from pathlib import Path
5+
from typing import Any
6+
from unittest.mock import Mock
7+
8+
import pytest
9+
from click.testing import CliRunner
10+
11+
from roborock.cli import ConnectionCache, RoborockContext, cli
12+
from roborock.data import HomeDataSchedule, UserData
13+
from roborock.exceptions import RoborockException
14+
from roborock.web_api import RoborockApiClient
15+
from tests.mock_data import USER_DATA, USER_EMAIL
16+
17+
18+
@pytest.fixture(autouse=True)
19+
def isolated_login(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
20+
"""Use temporary cached credentials so commands never load the user's login."""
21+
login_file = tmp_path / ".roborock"
22+
monkeypatch.setattr(RoborockContext, "roborock_file", login_file)
23+
monkeypatch.setattr(RoborockContext, "roborock_cache_file", tmp_path / ".roborock.cache")
24+
login_file.write_text(
25+
json.dumps(ConnectionCache(user_data=UserData.from_dict(USER_DATA), email=USER_EMAIL).as_dict()),
26+
encoding="utf-8",
27+
)
28+
29+
30+
@pytest.fixture
31+
def mock_api(monkeypatch: pytest.MonkeyPatch) -> Mock:
32+
"""Replace the cloud client, including all asynchronous network operations."""
33+
factory = Mock(return_value=Mock(spec=RoborockApiClient))
34+
monkeypatch.setattr("roborock.cli.RoborockApiClient", factory)
35+
return factory
36+
37+
38+
@pytest.fixture
39+
def job_data() -> dict[str, Any]:
40+
"""A full schedule including model-specific cleaning settings."""
41+
return {
42+
"id": 3878757,
43+
"cron": "05 10 * * ?",
44+
"repeated": True,
45+
"enabled": False,
46+
"param": {"mapId": 0, "rooms": [1, 2], "custom_key": {"id": 7, "value": None}},
47+
}
48+
49+
50+
@pytest.mark.parametrize("enabled", [False, True])
51+
def test_update_job(mock_api: Mock, tmp_path: Path, job_data: dict[str, Any], enabled: bool) -> None:
52+
"""The CLI passes a complete typed schedule using only the cached account."""
53+
job_data["enabled"] = enabled
54+
job_file = tmp_path / "job.json"
55+
job_file.write_text(json.dumps(job_data), encoding="utf-8")
56+
57+
result = CliRunner().invoke(cli, ["update-job", "--device_id", "123456", "--job-file", str(job_file)])
58+
59+
assert result.exit_code == 0, result.output
60+
assert result.output == "Updated job 3878757 for device 123456\n"
61+
mock_api.assert_called_once_with(USER_EMAIL)
62+
client = mock_api.return_value
63+
client.update_job.assert_awaited_once_with(UserData.from_dict(USER_DATA), "123456", HomeDataSchedule(**job_data))
64+
client.get_home_data_v3.assert_not_called()
65+
66+
67+
def test_update_job_api_error(mock_api: Mock, tmp_path: Path, job_data: dict[str, Any]) -> None:
68+
"""A cloud rejection produces an unsuccessful command exit."""
69+
mock_api.return_value.update_job.side_effect = RoborockException("Job not found")
70+
job_file = tmp_path / "job.json"
71+
job_file.write_text(json.dumps(job_data), encoding="utf-8")
72+
73+
result = CliRunner().invoke(cli, ["update-job", "--device_id", "123456", "--job-file", str(job_file)])
74+
75+
assert result.exit_code == 1
76+
assert result.output == "Error: Job not found\n"
77+
mock_api.return_value.update_job.assert_awaited_once()
78+
79+
80+
def test_update_job_requires_login(mock_api: Mock, tmp_path: Path, job_data: dict[str, Any]) -> None:
81+
"""Missing cached credentials fail without creating a cloud client."""
82+
(tmp_path / ".roborock").unlink()
83+
job_file = tmp_path / "job.json"
84+
job_file.write_text(json.dumps(job_data), encoding="utf-8")
85+
86+
result = CliRunner().invoke(cli, ["update-job", "--device_id", "123456", "--job-file", str(job_file)])
87+
88+
assert result.exit_code == 1
89+
assert result.output == "Error: You must login first\n"
90+
mock_api.assert_not_called()
91+
92+
93+
@pytest.mark.parametrize("field", ["id", "cron", "repeated", "enabled", "param"])
94+
def test_update_job_missing_fields(mock_api: Mock, tmp_path: Path, job_data: dict[str, Any], field: str) -> None:
95+
"""Partial schedule files cannot reach the update endpoint."""
96+
del job_data[field]
97+
job_file = tmp_path / "job.json"
98+
job_file.write_text(json.dumps(job_data), encoding="utf-8")
99+
100+
result = CliRunner().invoke(cli, ["update-job", "--device_id", "123456", "--job-file", str(job_file)])
101+
102+
assert result.exit_code == 2
103+
assert f"Complete job required; missing fields: {field}" in result.output
104+
mock_api.assert_not_called()
105+
106+
107+
@pytest.mark.parametrize(
108+
("field", "value"),
109+
[
110+
("id", True),
111+
("id", "3878757"),
112+
("id", 1.5),
113+
("cron", None),
114+
("cron", " "),
115+
("repeated", 1),
116+
("enabled", "false"),
117+
("param", None),
118+
("param", []),
119+
("param", "{}"),
120+
],
121+
)
122+
def test_update_job_invalid_fields(
123+
mock_api: Mock, tmp_path: Path, job_data: dict[str, Any], field: str, value: Any
124+
) -> None:
125+
"""Malformed scalar types are rejected instead of silently coerced."""
126+
job_data[field] = value
127+
job_file = tmp_path / "job.json"
128+
job_file.write_text(json.dumps(job_data), encoding="utf-8")
129+
130+
result = CliRunner().invoke(cli, ["update-job", "--device_id", "123456", "--job-file", str(job_file)])
131+
132+
assert result.exit_code == 2
133+
assert f"'{field}' must be" in result.output
134+
mock_api.assert_not_called()
135+
136+
137+
def test_update_job_unknown_fields(mock_api: Mock, tmp_path: Path, job_data: dict[str, Any]) -> None:
138+
"""Unknown top-level settings cannot be silently discarded during replacement."""
139+
job_data["additionalSetting"] = {"value": 1}
140+
job_file = tmp_path / "job.json"
141+
job_file.write_text(json.dumps(job_data), encoding="utf-8")
142+
143+
result = CliRunner().invoke(cli, ["update-job", "--device_id", "123456", "--job-file", str(job_file)])
144+
145+
assert result.exit_code == 2
146+
assert "Unknown job fields: additionalSetting" in result.output
147+
mock_api.assert_not_called()
148+
149+
150+
@pytest.mark.parametrize("contents", ["[", "[]", "null", '"schedule"'])
151+
def test_update_job_invalid_json(mock_api: Mock, tmp_path: Path, contents: str) -> None:
152+
"""Invalid JSON and non-object roots fail before creating a cloud client."""
153+
job_file = tmp_path / "job.json"
154+
job_file.write_text(contents, encoding="utf-8")
155+
156+
result = CliRunner().invoke(cli, ["update-job", "--device_id", "123456", "--job-file", str(job_file)])
157+
158+
assert result.exit_code == 2
159+
assert "Invalid value for '--job-file'" in result.output
160+
mock_api.assert_not_called()
161+
162+
163+
def test_update_job_missing_file(mock_api: Mock, tmp_path: Path) -> None:
164+
"""A nonexistent input file fails without cloud access."""
165+
result = CliRunner().invoke(
166+
cli, ["update-job", "--device_id", "123456", "--job-file", str(tmp_path / "missing.json")]
167+
)
168+
169+
assert result.exit_code == 2
170+
assert "does not exist" in result.output
171+
mock_api.assert_not_called()
172+
173+
174+
def test_update_job_help(mock_api: Mock) -> None:
175+
"""Help explains that this operation replaces all schedule settings."""
176+
result = CliRunner().invoke(cli, ["update-job", "--help"])
177+
178+
assert result.exit_code == 0
179+
assert "Include all existing settings" in result.output
180+
assert "id, cron, repeated, enabled, and param" in result.output
181+
mock_api.assert_not_called()

0 commit comments

Comments
 (0)