Skip to content

Commit 262bc02

Browse files
committed
fix(cli): simplify cloud job JSON parsing
1 parent a4c3a40 commit 262bc02

2 files changed

Lines changed: 22 additions & 144 deletions

File tree

‎roborock/cli.py‎

Lines changed: 6 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
from collections.abc import Callable
3535
from dataclasses import asdict, dataclass
3636
from pathlib import Path
37-
from typing import Any, cast
37+
from typing import Any, TextIO, cast
3838

3939
try:
4040
import click
@@ -428,56 +428,28 @@ 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-
458431
@click.command()
459432
@click.option("--device_id", required=True)
460433
@click.option(
461434
"--job-file",
462-
"job",
463435
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).",
436+
type=click.File("r", encoding="utf-8"),
437+
help="JSON file containing the schedule to update.",
467438
)
468439
@click.pass_context
469440
@async_command
470-
async def update_job(ctx: click.Context, device_id: str, job: HomeDataSchedule) -> None:
441+
async def update_job(ctx: click.Context, device_id: str, job_file: TextIO) -> None:
471442
"""Replace a cloud job using a complete schedule JSON file.
472443
473444
Include all existing settings in the file, including unchanged cleaning parameters.
474445
"""
475446
context: RoborockContext = ctx.obj
476447
try:
448+
job = HomeDataSchedule.from_dict(json.load(job_file))
477449
connection_cache = context.connection_cache()
478450
client = RoborockApiClient(connection_cache.email)
479451
await client.update_job(connection_cache.user_data, device_id, job)
480-
except RoborockException as err:
452+
except Exception as err:
481453
click.echo(f"Error: {err}", err=True)
482454
raise SystemExit(1) from err
483455
click.echo(f"Updated job {job.id} for device {device_id}")

‎tests/test_cli.py‎

Lines changed: 16 additions & 110 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ def mock_api(monkeypatch: pytest.MonkeyPatch) -> Mock:
3737

3838
@pytest.fixture
3939
def job_data() -> dict[str, Any]:
40-
"""A full schedule including model-specific cleaning settings."""
40+
"""A schedule including model-specific cleaning settings."""
4141
return {
4242
"id": 3878757,
4343
"cron": "05 10 * * ?",
@@ -47,10 +47,8 @@ def job_data() -> dict[str, Any]:
4747
}
4848

4949

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
50+
def test_update_job(mock_api: Mock, tmp_path: Path, job_data: dict[str, Any]) -> None:
51+
"""The CLI parses JSON into a schedule and calls the API using cached credentials."""
5452
job_file = tmp_path / "job.json"
5553
job_file.write_text(json.dumps(job_data), encoding="utf-8")
5654

@@ -59,123 +57,31 @@ def test_update_job(mock_api: Mock, tmp_path: Path, job_data: dict[str, Any], en
5957
assert result.exit_code == 0, result.output
6058
assert result.output == "Updated job 3878757 for device 123456\n"
6159
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()
60+
mock_api.return_value.update_job.assert_awaited_once_with(
61+
UserData.from_dict(USER_DATA), "123456", HomeDataSchedule(**job_data)
62+
)
7863

7964

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()
65+
def test_update_job_invalid_json(mock_api: Mock, tmp_path: Path) -> None:
66+
"""A JSON parsing failure is reported without calling the cloud API."""
8367
job_file = tmp_path / "job.json"
84-
job_file.write_text(json.dumps(job_data), encoding="utf-8")
68+
job_file.write_text("[", encoding="utf-8")
8569

8670
result = CliRunner().invoke(cli, ["update-job", "--device_id", "123456", "--job-file", str(job_file)])
8771

8872
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
73+
assert "Error: Expecting value" in result.output
13474
mock_api.assert_not_called()
13575

13676

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}
77+
def test_update_job_api_error(mock_api: Mock, tmp_path: Path, job_data: dict[str, Any]) -> None:
78+
"""A cloud rejection is reported with an unsuccessful command exit."""
79+
mock_api.return_value.update_job.side_effect = RoborockException("Job not found")
14080
job_file = tmp_path / "job.json"
14181
job_file.write_text(json.dumps(job_data), encoding="utf-8")
14282

14383
result = CliRunner().invoke(cli, ["update-job", "--device_id", "123456", "--job-file", str(job_file)])
14484

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()
85+
assert result.exit_code == 1
86+
assert result.output == "Error: Job not found\n"
87+
mock_api.return_value.update_job.assert_awaited_once()

0 commit comments

Comments
 (0)