browser-daemon-client 0.12.2__tar.gz → 0.13.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {browser_daemon_client-0.12.2 → browser_daemon_client-0.13.0}/PKG-INFO +13 -1
- {browser_daemon_client-0.12.2 → browser_daemon_client-0.13.0}/README.md +12 -0
- {browser_daemon_client-0.12.2 → browser_daemon_client-0.13.0}/browser_daemon_client/__init__.py +99 -2
- {browser_daemon_client-0.12.2 → browser_daemon_client-0.13.0}/browser_daemon_client.egg-info/PKG-INFO +13 -1
- {browser_daemon_client-0.12.2 → browser_daemon_client-0.13.0}/browser_daemon_client.egg-info/SOURCES.txt +2 -1
- {browser_daemon_client-0.12.2 → browser_daemon_client-0.13.0}/pyproject.toml +1 -1
- {browser_daemon_client-0.12.2 → browser_daemon_client-0.13.0}/tests/test_client.py +69 -0
- browser_daemon_client-0.13.0/tests/test_ha_integration.py +435 -0
- {browser_daemon_client-0.12.2 → browser_daemon_client-0.13.0}/browser_daemon_client.egg-info/dependency_links.txt +0 -0
- {browser_daemon_client-0.12.2 → browser_daemon_client-0.13.0}/browser_daemon_client.egg-info/requires.txt +0 -0
- {browser_daemon_client-0.12.2 → browser_daemon_client-0.13.0}/browser_daemon_client.egg-info/top_level.txt +0 -0
- {browser_daemon_client-0.12.2 → browser_daemon_client-0.13.0}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: browser-daemon-client
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.13.0
|
|
4
4
|
Summary: Async client for browser-daemon: Playwright runs over HTTP, sessions and logins, with nothing but aiohttp
|
|
5
5
|
License-Expression: GPL-3.0-only
|
|
6
6
|
Project-URL: Homepage, https://github.com/pschmitt/browser-daemon
|
|
@@ -45,9 +45,21 @@ async with aiohttp.ClientSession() as http:
|
|
|
45
45
|
- `run()`: a Playwright `script` (a JavaScript function expression) or `steps`,
|
|
46
46
|
in a profile's browser, a session or a throwaway browser. Runs for a profile
|
|
47
47
|
go to the node that has it. See [docs/run.md](../docs/run.md).
|
|
48
|
+
- `login(session_id, tab, username, password, ...)`: submit credentials in an
|
|
49
|
+
existing Chromium tab and return a `LoginResult.outcome`. Set
|
|
50
|
+
`success_selector` to visible page evidence before treating the result as
|
|
51
|
+
authenticated; see [docs/run.md](../docs/run.md#log-in-to-an-existing-tab).
|
|
48
52
|
- `overview()`, `find_profile()`, `sessions()`, `session()`, `create_session()`,
|
|
49
53
|
`delete_session()`, `set_idle_timeout()`, `tabs()`, `open_tab()`,
|
|
50
54
|
`close_tab()`, `export_auth()` (a page's cookies and storage; never log them).
|
|
55
|
+
- `place_browser(profile=..., node=..., group=..., engine=...)` selects a
|
|
56
|
+
matching node and moves an idle existing profile there. `create=True` permits
|
|
57
|
+
a missing profile for a subsequent session or run; it reserves nothing.
|
|
58
|
+
- `create_session(profile="work", group="cloud")` places the profile before
|
|
59
|
+
opening it and returns `node_name` for subsequent node-specific calls.
|
|
60
|
+
Supplying both `profile` and `node` also enables automatic placement.
|
|
61
|
+
See [profile placement](../docs/profiles.md#automatic-placement-and-node-groups)
|
|
62
|
+
for transfer restrictions and failure behavior.
|
|
51
63
|
- `node=` sends a request to another node of the mesh through this one.
|
|
52
64
|
- `read_secret()` reads the cluster secret from its file.
|
|
53
65
|
|
|
@@ -34,9 +34,21 @@ async with aiohttp.ClientSession() as http:
|
|
|
34
34
|
- `run()`: a Playwright `script` (a JavaScript function expression) or `steps`,
|
|
35
35
|
in a profile's browser, a session or a throwaway browser. Runs for a profile
|
|
36
36
|
go to the node that has it. See [docs/run.md](../docs/run.md).
|
|
37
|
+
- `login(session_id, tab, username, password, ...)`: submit credentials in an
|
|
38
|
+
existing Chromium tab and return a `LoginResult.outcome`. Set
|
|
39
|
+
`success_selector` to visible page evidence before treating the result as
|
|
40
|
+
authenticated; see [docs/run.md](../docs/run.md#log-in-to-an-existing-tab).
|
|
37
41
|
- `overview()`, `find_profile()`, `sessions()`, `session()`, `create_session()`,
|
|
38
42
|
`delete_session()`, `set_idle_timeout()`, `tabs()`, `open_tab()`,
|
|
39
43
|
`close_tab()`, `export_auth()` (a page's cookies and storage; never log them).
|
|
44
|
+
- `place_browser(profile=..., node=..., group=..., engine=...)` selects a
|
|
45
|
+
matching node and moves an idle existing profile there. `create=True` permits
|
|
46
|
+
a missing profile for a subsequent session or run; it reserves nothing.
|
|
47
|
+
- `create_session(profile="work", group="cloud")` places the profile before
|
|
48
|
+
opening it and returns `node_name` for subsequent node-specific calls.
|
|
49
|
+
Supplying both `profile` and `node` also enables automatic placement.
|
|
50
|
+
See [profile placement](../docs/profiles.md#automatic-placement-and-node-groups)
|
|
51
|
+
for transfer restrictions and failure behavior.
|
|
40
52
|
- `node=` sends a request to another node of the mesh through this one.
|
|
41
53
|
- `read_secret()` reads the cluster secret from its file.
|
|
42
54
|
|
{browser_daemon_client-0.12.2 → browser_daemon_client-0.13.0}/browser_daemon_client/__init__.py
RENAMED
|
@@ -32,6 +32,7 @@ import aiohttp
|
|
|
32
32
|
__all__ = [
|
|
33
33
|
"BrowserDaemon",
|
|
34
34
|
"BrowserDaemonError",
|
|
35
|
+
"LoginResult",
|
|
35
36
|
"RunError",
|
|
36
37
|
"RunResult",
|
|
37
38
|
"RunTimeout",
|
|
@@ -83,6 +84,17 @@ class RunResult:
|
|
|
83
84
|
)
|
|
84
85
|
|
|
85
86
|
|
|
87
|
+
@dataclass
|
|
88
|
+
class LoginResult:
|
|
89
|
+
"""Outcome of a generic login attempt in an existing session tab."""
|
|
90
|
+
|
|
91
|
+
outcome: str
|
|
92
|
+
|
|
93
|
+
@classmethod
|
|
94
|
+
def from_json(cls, data: dict[str, Any]) -> LoginResult:
|
|
95
|
+
return cls(outcome=str(data.get("outcome", "unknown")))
|
|
96
|
+
|
|
97
|
+
|
|
86
98
|
class RunError(BrowserDaemonError):
|
|
87
99
|
"""The script or a step failed; :attr:`run` holds the whole answer."""
|
|
88
100
|
|
|
@@ -238,19 +250,104 @@ class BrowserDaemon:
|
|
|
238
250
|
"""The session and its `targets` (tabs)."""
|
|
239
251
|
return await self._json("GET", f"/api/sessions/{quote(session_id, safe='')}", node=node)
|
|
240
252
|
|
|
253
|
+
async def login(
|
|
254
|
+
self,
|
|
255
|
+
session_id: str,
|
|
256
|
+
tab: str,
|
|
257
|
+
username: str,
|
|
258
|
+
password: str,
|
|
259
|
+
*,
|
|
260
|
+
totp_secret: str | None = None,
|
|
261
|
+
totp_code: str | None = None,
|
|
262
|
+
allowed_origins: list[str] | None = None,
|
|
263
|
+
success_selector: str | None = None,
|
|
264
|
+
timeout: float = 30,
|
|
265
|
+
node: str | None = None,
|
|
266
|
+
) -> LoginResult:
|
|
267
|
+
"""Log in in place, without creating a new browser session or tab.
|
|
268
|
+
|
|
269
|
+
``authenticated`` is returned only when ``success_selector`` is visible.
|
|
270
|
+
Otherwise inspect ``outcome`` (``needs_totp``, ``needs_interaction``,
|
|
271
|
+
``failed`` or ``unknown``) and handle the page accordingly.
|
|
272
|
+
"""
|
|
273
|
+
if totp_secret is not None and totp_code is not None:
|
|
274
|
+
raise ValueError("give totp_secret or totp_code, not both")
|
|
275
|
+
timeout = max(1, min(90, timeout))
|
|
276
|
+
body = {
|
|
277
|
+
"tab": tab,
|
|
278
|
+
"username": username,
|
|
279
|
+
"password": password,
|
|
280
|
+
"totp_secret": totp_secret,
|
|
281
|
+
"totp_code": totp_code,
|
|
282
|
+
"allowed_origins": allowed_origins,
|
|
283
|
+
"success_selector": success_selector,
|
|
284
|
+
"timeout_seconds": max(1, round(timeout)),
|
|
285
|
+
}
|
|
286
|
+
data = await self._json(
|
|
287
|
+
"POST",
|
|
288
|
+
f"/api/sessions/{quote(session_id, safe='')}/login",
|
|
289
|
+
node=node,
|
|
290
|
+
json={key: value for key, value in body.items() if value is not None},
|
|
291
|
+
timeout=timeout + 5,
|
|
292
|
+
)
|
|
293
|
+
return LoginResult.from_json(data or {})
|
|
294
|
+
|
|
295
|
+
async def place_browser(
|
|
296
|
+
self,
|
|
297
|
+
*,
|
|
298
|
+
profile: str | None = None,
|
|
299
|
+
node: str | None = None,
|
|
300
|
+
group: str | None = None,
|
|
301
|
+
engine: str | None = None,
|
|
302
|
+
create: bool = False,
|
|
303
|
+
) -> dict[str, Any]:
|
|
304
|
+
"""Resolve placement; `create` allows a missing profile for a subsequent session."""
|
|
305
|
+
if self.local_node is None:
|
|
306
|
+
await self.overview()
|
|
307
|
+
return await self._json(
|
|
308
|
+
"POST",
|
|
309
|
+
"/api/mesh/placement",
|
|
310
|
+
json={
|
|
311
|
+
k: v
|
|
312
|
+
for k, v in {
|
|
313
|
+
"profile": profile,
|
|
314
|
+
"node": node,
|
|
315
|
+
"group": group,
|
|
316
|
+
"engine": engine,
|
|
317
|
+
"create": create,
|
|
318
|
+
}.items()
|
|
319
|
+
if v is not None
|
|
320
|
+
},
|
|
321
|
+
timeout=180,
|
|
322
|
+
)
|
|
323
|
+
|
|
241
324
|
async def create_session(
|
|
242
|
-
self,
|
|
325
|
+
self,
|
|
326
|
+
*,
|
|
327
|
+
profile: str | None = None,
|
|
328
|
+
node: str | None = None,
|
|
329
|
+
group: str | None = None,
|
|
330
|
+
**options: Any,
|
|
243
331
|
) -> dict[str, Any]:
|
|
244
332
|
"""Start a session (or attach to the profile's); options as `POST /api/sessions`."""
|
|
333
|
+
placed = None
|
|
334
|
+
if group is not None or (profile is not None and node is not None):
|
|
335
|
+
placed = await self.place_browser(
|
|
336
|
+
profile=profile, node=node, group=group, engine=options.get("engine"), create=True
|
|
337
|
+
)
|
|
338
|
+
node = placed["node"]
|
|
245
339
|
body = {"persistent": True, "profile": profile, **options}
|
|
246
340
|
if self.client and "name" not in body:
|
|
247
341
|
body["name"] = self.client
|
|
248
|
-
|
|
342
|
+
result = await self._json(
|
|
249
343
|
"POST",
|
|
250
344
|
"/api/sessions",
|
|
251
345
|
node=node,
|
|
252
346
|
json={k: v for k, v in body.items() if v is not None},
|
|
253
347
|
)
|
|
348
|
+
if placed is not None:
|
|
349
|
+
result["node_name"] = node
|
|
350
|
+
return result
|
|
254
351
|
|
|
255
352
|
async def delete_session(self, session_id: str, node: str | None = None) -> None:
|
|
256
353
|
await self._request("DELETE", f"/api/sessions/{quote(session_id, safe='')}", node=node)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: browser-daemon-client
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.13.0
|
|
4
4
|
Summary: Async client for browser-daemon: Playwright runs over HTTP, sessions and logins, with nothing but aiohttp
|
|
5
5
|
License-Expression: GPL-3.0-only
|
|
6
6
|
Project-URL: Homepage, https://github.com/pschmitt/browser-daemon
|
|
@@ -45,9 +45,21 @@ async with aiohttp.ClientSession() as http:
|
|
|
45
45
|
- `run()`: a Playwright `script` (a JavaScript function expression) or `steps`,
|
|
46
46
|
in a profile's browser, a session or a throwaway browser. Runs for a profile
|
|
47
47
|
go to the node that has it. See [docs/run.md](../docs/run.md).
|
|
48
|
+
- `login(session_id, tab, username, password, ...)`: submit credentials in an
|
|
49
|
+
existing Chromium tab and return a `LoginResult.outcome`. Set
|
|
50
|
+
`success_selector` to visible page evidence before treating the result as
|
|
51
|
+
authenticated; see [docs/run.md](../docs/run.md#log-in-to-an-existing-tab).
|
|
48
52
|
- `overview()`, `find_profile()`, `sessions()`, `session()`, `create_session()`,
|
|
49
53
|
`delete_session()`, `set_idle_timeout()`, `tabs()`, `open_tab()`,
|
|
50
54
|
`close_tab()`, `export_auth()` (a page's cookies and storage; never log them).
|
|
55
|
+
- `place_browser(profile=..., node=..., group=..., engine=...)` selects a
|
|
56
|
+
matching node and moves an idle existing profile there. `create=True` permits
|
|
57
|
+
a missing profile for a subsequent session or run; it reserves nothing.
|
|
58
|
+
- `create_session(profile="work", group="cloud")` places the profile before
|
|
59
|
+
opening it and returns `node_name` for subsequent node-specific calls.
|
|
60
|
+
Supplying both `profile` and `node` also enables automatic placement.
|
|
61
|
+
See [profile placement](../docs/profiles.md#automatic-placement-and-node-groups)
|
|
62
|
+
for transfer restrictions and failure behavior.
|
|
51
63
|
- `node=` sends a request to another node of the mesh through this one.
|
|
52
64
|
- `read_secret()` reads the cluster secret from its file.
|
|
53
65
|
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "browser-daemon-client"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.13.0"
|
|
8
8
|
description = "Async client for browser-daemon: Playwright runs over HTTP, sessions and logins, with nothing but aiohttp"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = "GPL-3.0-only"
|
|
@@ -12,6 +12,7 @@ from aiohttp.test_utils import TestServer
|
|
|
12
12
|
from browser_daemon_client import (
|
|
13
13
|
BrowserDaemon,
|
|
14
14
|
BrowserDaemonError,
|
|
15
|
+
LoginResult,
|
|
15
16
|
RunError,
|
|
16
17
|
RunTimeout,
|
|
17
18
|
read_secret,
|
|
@@ -138,6 +139,34 @@ async def test_requests_for_other_nodes_go_through_the_peer_route(daemon):
|
|
|
138
139
|
assert seen[-1]["query"] == {"minutes": "5"}
|
|
139
140
|
|
|
140
141
|
|
|
142
|
+
@pytest.mark.parametrize("selected", ["here", "worker"])
|
|
143
|
+
async def test_group_session_routes_to_placement_and_allows_new_profiles(daemon, selected):
|
|
144
|
+
bd, seen, answers = daemon
|
|
145
|
+
answers[("GET", "/api/mesh/overview")] = (200, {"local_node": {"name": "here"}})
|
|
146
|
+
answers[("POST", "/api/mesh/placement")] = (200, {"node": selected})
|
|
147
|
+
path = "/api/sessions" if selected == "here" else "/api/peers/worker/sessions"
|
|
148
|
+
answers[("POST", path)] = (201, {"id": "new-session"})
|
|
149
|
+
result = await bd.create_session(profile="new-profile", group="cloud", engine="chromium")
|
|
150
|
+
assert result == {"id": "new-session", "node_name": selected}
|
|
151
|
+
assert seen[1]["json"] == {
|
|
152
|
+
"profile": "new-profile",
|
|
153
|
+
"group": "cloud",
|
|
154
|
+
"engine": "chromium",
|
|
155
|
+
"create": True,
|
|
156
|
+
}
|
|
157
|
+
assert seen[2]["path"] == path
|
|
158
|
+
assert "group" not in seen[2]["json"]
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
async def test_refused_placement_does_not_create_a_session(daemon):
|
|
162
|
+
bd, seen, answers = daemon
|
|
163
|
+
bd.local_node = "here"
|
|
164
|
+
answers[("POST", "/api/mesh/placement")] = (409, {"error": "profile is busy"})
|
|
165
|
+
with pytest.raises(BrowserDaemonError):
|
|
166
|
+
await bd.create_session(profile="work", node="worker")
|
|
167
|
+
assert [item["path"] for item in seen] == ["/api/mesh/placement"]
|
|
168
|
+
|
|
169
|
+
|
|
141
170
|
async def test_a_session_is_named_after_the_client(daemon):
|
|
142
171
|
bd, seen, answers = daemon
|
|
143
172
|
answers[("POST", "/api/sessions")] = (201, {"id": "abc"})
|
|
@@ -150,6 +179,46 @@ async def test_a_session_is_named_after_the_client(daemon):
|
|
|
150
179
|
}
|
|
151
180
|
|
|
152
181
|
|
|
182
|
+
async def test_login_uses_existing_session_and_tab_without_logging_secrets(daemon):
|
|
183
|
+
bd, seen, answers = daemon
|
|
184
|
+
answers[("POST", "/api/sessions/session%2Fid/login")] = (
|
|
185
|
+
200,
|
|
186
|
+
{"outcome": "needs_totp"},
|
|
187
|
+
)
|
|
188
|
+
result = await bd.login(
|
|
189
|
+
"session/id",
|
|
190
|
+
"tab-id",
|
|
191
|
+
"alice",
|
|
192
|
+
"not-for-logs",
|
|
193
|
+
totp_secret="JBSWY3DPEHPK3PXP",
|
|
194
|
+
allowed_origins=["https://login.example.test"],
|
|
195
|
+
success_selector=".account-home",
|
|
196
|
+
)
|
|
197
|
+
assert result == LoginResult("needs_totp")
|
|
198
|
+
assert seen[0]["json"] == {
|
|
199
|
+
"tab": "tab-id",
|
|
200
|
+
"username": "alice",
|
|
201
|
+
"password": "not-for-logs",
|
|
202
|
+
"totp_secret": "JBSWY3DPEHPK3PXP",
|
|
203
|
+
"allowed_origins": ["https://login.example.test"],
|
|
204
|
+
"success_selector": ".account-home",
|
|
205
|
+
"timeout_seconds": 30,
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
async def test_login_refuses_both_totp_seed_and_code(daemon):
|
|
210
|
+
bd, _, _ = daemon
|
|
211
|
+
with pytest.raises(ValueError, match="not both"):
|
|
212
|
+
await bd.login(
|
|
213
|
+
"session",
|
|
214
|
+
"tab",
|
|
215
|
+
"alice",
|
|
216
|
+
"password",
|
|
217
|
+
totp_secret="seed",
|
|
218
|
+
totp_code="123456",
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
|
|
153
222
|
async def test_an_unreachable_daemon_is_a_browser_daemon_error():
|
|
154
223
|
async with aiohttp.ClientSession() as http:
|
|
155
224
|
bd = BrowserDaemon(http, "http://127.0.0.1:9", timeout=2)
|
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
"""Focused contract tests for the optional Home Assistant integration."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib
|
|
6
|
+
import importlib.util
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from types import ModuleType, SimpleNamespace
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
import pytest
|
|
13
|
+
|
|
14
|
+
ROOT = Path(__file__).resolve().parents[2]
|
|
15
|
+
INTEGRATION = ROOT / "custom_components" / "browser_daemon"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Marker:
|
|
19
|
+
def __init__(self, key: str, group: str | None = None) -> None:
|
|
20
|
+
self.key = key
|
|
21
|
+
self.group = group
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Schema:
|
|
25
|
+
def __init__(self, fields: dict[Any, Any]) -> None:
|
|
26
|
+
self.fields = fields
|
|
27
|
+
|
|
28
|
+
def __call__(self, value: dict[str, Any]) -> dict[str, Any]:
|
|
29
|
+
return value
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _install_home_assistant_stubs() -> None:
|
|
33
|
+
"""Provide only the HA contracts needed to import and exercise the platforms."""
|
|
34
|
+
ha = ModuleType("homeassistant")
|
|
35
|
+
ha.__path__ = []
|
|
36
|
+
sys.modules["homeassistant"] = ha
|
|
37
|
+
|
|
38
|
+
core = ModuleType("homeassistant.core")
|
|
39
|
+
core.HomeAssistant = type("HomeAssistant", (), {})
|
|
40
|
+
core.ServiceCall = type("ServiceCall", (), {})
|
|
41
|
+
core.SupportsResponse = SimpleNamespace(OPTIONAL="optional")
|
|
42
|
+
sys.modules["homeassistant.core"] = core
|
|
43
|
+
|
|
44
|
+
exceptions = ModuleType("homeassistant.exceptions")
|
|
45
|
+
exceptions.HomeAssistantError = type("HomeAssistantError", (Exception,), {})
|
|
46
|
+
sys.modules["homeassistant.exceptions"] = exceptions
|
|
47
|
+
|
|
48
|
+
helpers = ModuleType("homeassistant.helpers")
|
|
49
|
+
helpers.__path__ = []
|
|
50
|
+
sys.modules["homeassistant.helpers"] = helpers
|
|
51
|
+
|
|
52
|
+
validation = ModuleType("homeassistant.helpers.config_validation")
|
|
53
|
+
validation.string = str
|
|
54
|
+
validation.boolean = bool
|
|
55
|
+
validation.positive_int = int
|
|
56
|
+
validation.ensure_list = lambda value: value if isinstance(value, list) else [value]
|
|
57
|
+
validation.ensure_list_csv = validation.ensure_list
|
|
58
|
+
sys.modules["homeassistant.helpers.config_validation"] = validation
|
|
59
|
+
|
|
60
|
+
entity_platform = ModuleType("homeassistant.helpers.entity_platform")
|
|
61
|
+
entity_platform.AddEntitiesCallback = Any
|
|
62
|
+
sys.modules["homeassistant.helpers.entity_platform"] = entity_platform
|
|
63
|
+
|
|
64
|
+
config_entries = ModuleType("homeassistant.config_entries")
|
|
65
|
+
config_entries.ConfigEntry = type("ConfigEntry", (), {})
|
|
66
|
+
sys.modules["homeassistant.config_entries"] = config_entries
|
|
67
|
+
|
|
68
|
+
const = ModuleType("homeassistant.const")
|
|
69
|
+
const.Platform = SimpleNamespace(
|
|
70
|
+
SENSOR="sensor", BINARY_SENSOR="binary_sensor", BUTTON="button", IMAGE="image"
|
|
71
|
+
)
|
|
72
|
+
const.EntityCategory = SimpleNamespace(DIAGNOSTIC="diagnostic")
|
|
73
|
+
const.UnitOfInformation = SimpleNamespace(BYTES="B")
|
|
74
|
+
const.UnitOfTime = SimpleNamespace(SECONDS="s")
|
|
75
|
+
sys.modules["homeassistant.const"] = const
|
|
76
|
+
|
|
77
|
+
class EntityDescription:
|
|
78
|
+
def __init__(self, **kwargs: Any) -> None:
|
|
79
|
+
self.__dict__.update(kwargs)
|
|
80
|
+
|
|
81
|
+
sensor = ModuleType("homeassistant.components.sensor")
|
|
82
|
+
sensor.SensorDeviceClass = SimpleNamespace(DATA_SIZE="data_size", DURATION="duration")
|
|
83
|
+
sensor.SensorEntity = type("SensorEntity", (), {})
|
|
84
|
+
sensor.SensorEntityDescription = EntityDescription
|
|
85
|
+
sensor.SensorStateClass = SimpleNamespace(MEASUREMENT="measurement", TOTAL="total")
|
|
86
|
+
sys.modules["homeassistant.components"] = ModuleType("homeassistant.components")
|
|
87
|
+
sys.modules["homeassistant.components"].__path__ = []
|
|
88
|
+
sys.modules["homeassistant.components.sensor"] = sensor
|
|
89
|
+
|
|
90
|
+
binary_sensor = ModuleType("homeassistant.components.binary_sensor")
|
|
91
|
+
binary_sensor.BinarySensorDeviceClass = SimpleNamespace(
|
|
92
|
+
CONNECTIVITY="connectivity", RUNNING="running"
|
|
93
|
+
)
|
|
94
|
+
binary_sensor.BinarySensorEntity = type("BinarySensorEntity", (), {})
|
|
95
|
+
binary_sensor.BinarySensorEntityDescription = EntityDescription
|
|
96
|
+
sys.modules["homeassistant.components.binary_sensor"] = binary_sensor
|
|
97
|
+
|
|
98
|
+
voluptuous = ModuleType("voluptuous")
|
|
99
|
+
voluptuous.Schema = Schema
|
|
100
|
+
voluptuous.Required = lambda key: Marker(key)
|
|
101
|
+
voluptuous.Optional = lambda key, **kwargs: Marker(key)
|
|
102
|
+
voluptuous.Exclusive = lambda key, group: Marker(key, group)
|
|
103
|
+
voluptuous.In = lambda values: values
|
|
104
|
+
voluptuous.All = lambda *values: values
|
|
105
|
+
voluptuous.Range = lambda **kwargs: SimpleNamespace(**kwargs)
|
|
106
|
+
voluptuous.Coerce = lambda kind: kind
|
|
107
|
+
sys.modules["voluptuous"] = voluptuous
|
|
108
|
+
|
|
109
|
+
package = ModuleType("custom_components")
|
|
110
|
+
package.__path__ = [str(ROOT / "custom_components")]
|
|
111
|
+
sys.modules["custom_components"] = package
|
|
112
|
+
integration = ModuleType("custom_components.browser_daemon")
|
|
113
|
+
integration.__path__ = [str(INTEGRATION)]
|
|
114
|
+
sys.modules["custom_components.browser_daemon"] = integration
|
|
115
|
+
|
|
116
|
+
api = ModuleType("custom_components.browser_daemon.api")
|
|
117
|
+
api.BrowserDaemonError = Exception
|
|
118
|
+
sys.modules[api.__name__] = api
|
|
119
|
+
|
|
120
|
+
coordinator = ModuleType("custom_components.browser_daemon.coordinator")
|
|
121
|
+
coordinator.BrowserDaemonCoordinator = type("BrowserDaemonCoordinator", (), {})
|
|
122
|
+
sys.modules[coordinator.__name__] = coordinator
|
|
123
|
+
|
|
124
|
+
entity = ModuleType("custom_components.browser_daemon.entity")
|
|
125
|
+
|
|
126
|
+
class MeshEntity:
|
|
127
|
+
def __init__(self, coordinator: Any, key: str) -> None:
|
|
128
|
+
self.coordinator = coordinator
|
|
129
|
+
self._key = key
|
|
130
|
+
|
|
131
|
+
class NodeEntity(MeshEntity):
|
|
132
|
+
def __init__(self, coordinator: Any, node_name: str, key: str) -> None:
|
|
133
|
+
super().__init__(coordinator, key)
|
|
134
|
+
self._node_name = node_name
|
|
135
|
+
|
|
136
|
+
class BrowserEntity(MeshEntity):
|
|
137
|
+
def __init__(self, coordinator: Any, browser_id: str, key: str) -> None:
|
|
138
|
+
super().__init__(coordinator, key)
|
|
139
|
+
self._browser_id = browser_id
|
|
140
|
+
|
|
141
|
+
entity.BrowserDaemonEntity = MeshEntity
|
|
142
|
+
entity.BrowserDaemonBrowserEntity = BrowserEntity
|
|
143
|
+
entity.BrowserDaemonNodeEntity = NodeEntity
|
|
144
|
+
sys.modules[entity.__name__] = entity
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
_install_home_assistant_stubs()
|
|
148
|
+
services = importlib.import_module("custom_components.browser_daemon.services")
|
|
149
|
+
sensor_platform = importlib.import_module("custom_components.browser_daemon.sensor")
|
|
150
|
+
binary_sensor_platform = importlib.import_module("custom_components.browser_daemon.binary_sensor")
|
|
151
|
+
constants = importlib.import_module("custom_components.browser_daemon.const")
|
|
152
|
+
api_spec = importlib.util.spec_from_file_location("ha_browser_daemon_api", INTEGRATION / "api.py")
|
|
153
|
+
api = importlib.util.module_from_spec(api_spec)
|
|
154
|
+
assert api_spec.loader is not None
|
|
155
|
+
api_spec.loader.exec_module(api)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class FakeClient:
|
|
159
|
+
def __init__(self) -> None:
|
|
160
|
+
self.calls: list[tuple[str, dict[str, Any]]] = []
|
|
161
|
+
|
|
162
|
+
async def async_set_idle_timeout(self, **kwargs: Any) -> dict[str, Any]:
|
|
163
|
+
self.calls.append(("set_idle_timeout", kwargs))
|
|
164
|
+
return {"success": True, "idle_timeout_minutes": kwargs["minutes"]}
|
|
165
|
+
|
|
166
|
+
async def async_open_tab(self, **kwargs: Any) -> dict[str, Any]:
|
|
167
|
+
self.calls.append(("open_tab", kwargs))
|
|
168
|
+
return {"id": "tab"}
|
|
169
|
+
|
|
170
|
+
async def async_login(self, **kwargs: Any) -> dict[str, Any]:
|
|
171
|
+
self.calls.append(("login", kwargs))
|
|
172
|
+
return {"outcome": "needs_totp"}
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class FakeCoordinator(
|
|
176
|
+
sys.modules["custom_components.browser_daemon.coordinator"].BrowserDaemonCoordinator
|
|
177
|
+
):
|
|
178
|
+
def __init__(self, data: dict[str, Any] | None = None) -> None:
|
|
179
|
+
self.data = data or {"nodes": {}}
|
|
180
|
+
self.client = FakeClient()
|
|
181
|
+
self.listeners: list[Any] = []
|
|
182
|
+
|
|
183
|
+
def async_add_listener(self, listener: Any) -> Any:
|
|
184
|
+
self.listeners.append(listener)
|
|
185
|
+
|
|
186
|
+
def remove() -> None:
|
|
187
|
+
self.listeners.remove(listener)
|
|
188
|
+
|
|
189
|
+
return remove
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
class FakeServices:
|
|
193
|
+
def __init__(self) -> None:
|
|
194
|
+
self.registered: dict[str, dict[str, Any]] = {}
|
|
195
|
+
|
|
196
|
+
def async_register(self, domain: str, name: str, handler: Any, **kwargs: Any) -> None:
|
|
197
|
+
self.registered[name] = {"handler": handler, **kwargs}
|
|
198
|
+
|
|
199
|
+
def async_remove(self, domain: str, name: str) -> None:
|
|
200
|
+
self.registered.pop(name, None)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
class FakeResponse:
|
|
204
|
+
def __init__(
|
|
205
|
+
self,
|
|
206
|
+
status: int,
|
|
207
|
+
body: dict[str, Any] | None = None,
|
|
208
|
+
*,
|
|
209
|
+
content_type: str = "application/json",
|
|
210
|
+
) -> None:
|
|
211
|
+
self.status = status
|
|
212
|
+
self.body = body
|
|
213
|
+
self.content_type = content_type
|
|
214
|
+
self.content_length = 0 if body is None else 1
|
|
215
|
+
|
|
216
|
+
async def json(self) -> dict[str, Any]:
|
|
217
|
+
if self.body is None:
|
|
218
|
+
raise ValueError("response has no JSON body")
|
|
219
|
+
return self.body
|
|
220
|
+
|
|
221
|
+
async def text(self) -> str:
|
|
222
|
+
return ""
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
class FakeHttpSession:
|
|
226
|
+
def __init__(self, response: FakeResponse) -> None:
|
|
227
|
+
self.response = response
|
|
228
|
+
self.requests: list[dict[str, Any]] = []
|
|
229
|
+
|
|
230
|
+
async def request(self, method: str, url: str, **kwargs: Any) -> FakeResponse:
|
|
231
|
+
self.requests.append({"method": method, "url": url, **kwargs})
|
|
232
|
+
return self.response
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
@pytest.fixture
|
|
236
|
+
def service_context():
|
|
237
|
+
coordinator = FakeCoordinator()
|
|
238
|
+
hass = SimpleNamespace(data={constants.DOMAIN: {"entry": coordinator}}, services=FakeServices())
|
|
239
|
+
return hass, coordinator
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
@pytest.mark.asyncio
|
|
243
|
+
async def test_idle_timeout_service_accepts_zero_and_open_tab_targets_session(service_context):
|
|
244
|
+
hass, coordinator = service_context
|
|
245
|
+
await services.async_setup_services(hass)
|
|
246
|
+
|
|
247
|
+
idle_schema = hass.services.registered[constants.SERVICE_SET_IDLE_TIMEOUT]["schema"]
|
|
248
|
+
assert any(
|
|
249
|
+
marker.key == constants.ATTR_IDLE_TIMEOUT
|
|
250
|
+
and any(getattr(rule, "min", None) == 0 for rule in rules)
|
|
251
|
+
for marker, rules in idle_schema.fields.items()
|
|
252
|
+
if isinstance(marker, Marker)
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
result = await hass.services.registered[constants.SERVICE_SET_IDLE_TIMEOUT]["handler"](
|
|
256
|
+
SimpleNamespace(
|
|
257
|
+
data={
|
|
258
|
+
"entry_id": "entry",
|
|
259
|
+
constants.ATTR_SESSION_ID: "session",
|
|
260
|
+
constants.ATTR_IDLE_TIMEOUT: 0,
|
|
261
|
+
}
|
|
262
|
+
)
|
|
263
|
+
)
|
|
264
|
+
assert result == {"success": True, "idle_timeout_minutes": 0}
|
|
265
|
+
assert coordinator.client.calls[-1] == (
|
|
266
|
+
"set_idle_timeout",
|
|
267
|
+
{"session_id": "session", "minutes": 0, "node": None},
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
result = await hass.services.registered[constants.SERVICE_OPEN_TAB]["handler"](
|
|
271
|
+
SimpleNamespace(
|
|
272
|
+
data={"entry_id": "entry", "url": "https://example.test", "session_id": "session"}
|
|
273
|
+
)
|
|
274
|
+
)
|
|
275
|
+
assert result == {"id": "tab"}
|
|
276
|
+
assert coordinator.client.calls[-1] == (
|
|
277
|
+
"open_tab",
|
|
278
|
+
{"url": "https://example.test", "session_id": "session", "node": None},
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
await services.async_unload_services(hass)
|
|
282
|
+
assert constants.SERVICE_LOGIN not in hass.services.registered
|
|
283
|
+
assert constants.SERVICE_SET_IDLE_TIMEOUT not in hass.services.registered
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
@pytest.mark.asyncio
|
|
287
|
+
async def test_login_service_returns_expected_interaction_state(service_context):
|
|
288
|
+
hass, coordinator = service_context
|
|
289
|
+
await services.async_setup_services(hass)
|
|
290
|
+
login_schema = hass.services.registered[constants.SERVICE_LOGIN]["schema"]
|
|
291
|
+
totp_fields = [
|
|
292
|
+
marker for marker in login_schema.fields if isinstance(marker, Marker) and marker.group
|
|
293
|
+
]
|
|
294
|
+
assert {marker.key for marker in totp_fields} == {"totp_secret", "totp_code"}
|
|
295
|
+
assert {marker.group for marker in totp_fields} == {"totp"}
|
|
296
|
+
call = SimpleNamespace(
|
|
297
|
+
data={
|
|
298
|
+
"entry_id": "entry",
|
|
299
|
+
"session_id": "session",
|
|
300
|
+
"tab": "tab",
|
|
301
|
+
"username": "user",
|
|
302
|
+
"password": "password-value",
|
|
303
|
+
"totp_code": "123456",
|
|
304
|
+
"success_selector": ".account-home",
|
|
305
|
+
}
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
result = await hass.services.registered[constants.SERVICE_LOGIN]["handler"](call)
|
|
309
|
+
|
|
310
|
+
assert result == {"outcome": "needs_totp"}
|
|
311
|
+
assert coordinator.client.calls[-1] == (
|
|
312
|
+
"login",
|
|
313
|
+
{
|
|
314
|
+
"session_id": "session",
|
|
315
|
+
"tab": "tab",
|
|
316
|
+
"username": "user",
|
|
317
|
+
"password": "password-value",
|
|
318
|
+
"totp_code": "123456",
|
|
319
|
+
"success_selector": ".account-home",
|
|
320
|
+
"timeout_seconds": 30,
|
|
321
|
+
},
|
|
322
|
+
)
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
@pytest.mark.asyncio
|
|
326
|
+
async def test_api_login_uses_cluster_secret_and_returns_needs_totp():
|
|
327
|
+
http = FakeHttpSession(FakeResponse(200, {"outcome": "needs_totp"}))
|
|
328
|
+
client = api.BrowserDaemonClient(http, "http://daemon.test", cluster_secret="cluster-secret")
|
|
329
|
+
|
|
330
|
+
result = await client.async_login(
|
|
331
|
+
"session",
|
|
332
|
+
tab="tab",
|
|
333
|
+
username="user",
|
|
334
|
+
password="pass",
|
|
335
|
+
totp_secret="seed",
|
|
336
|
+
success_selector=".account-home",
|
|
337
|
+
)
|
|
338
|
+
|
|
339
|
+
assert result == {"outcome": "needs_totp"}
|
|
340
|
+
request = http.requests[0]
|
|
341
|
+
assert request["method"] == "POST"
|
|
342
|
+
assert request["url"].endswith("/api/sessions/session/login")
|
|
343
|
+
assert request["headers"]["X-Browser-Cluster-Secret"] == "cluster-secret"
|
|
344
|
+
assert request["json"] == {
|
|
345
|
+
"tab": "tab",
|
|
346
|
+
"username": "user",
|
|
347
|
+
"password": "pass",
|
|
348
|
+
"totp_secret": "seed",
|
|
349
|
+
"success_selector": ".account-home",
|
|
350
|
+
"timeout_seconds": 30,
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
@pytest.mark.asyncio
|
|
355
|
+
async def test_api_login_requires_cluster_secret():
|
|
356
|
+
http = FakeHttpSession(FakeResponse(200, {"outcome": "authenticated"}))
|
|
357
|
+
client = api.BrowserDaemonClient(http, "http://daemon.test")
|
|
358
|
+
|
|
359
|
+
with pytest.raises(api.BrowserDaemonError, match="cluster secret"):
|
|
360
|
+
await client.async_login("session", tab="tab", username="user", password="pass")
|
|
361
|
+
|
|
362
|
+
assert http.requests == []
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
@pytest.mark.asyncio
|
|
366
|
+
async def test_idle_timeout_handles_204_without_json():
|
|
367
|
+
http = FakeHttpSession(FakeResponse(204))
|
|
368
|
+
client = api.BrowserDaemonClient(http, "http://daemon.test", cluster_secret="secret")
|
|
369
|
+
|
|
370
|
+
result = await client.async_set_idle_timeout("session", 0)
|
|
371
|
+
|
|
372
|
+
assert result == {
|
|
373
|
+
"success": True,
|
|
374
|
+
"session_id": "session",
|
|
375
|
+
"idle_timeout_minutes": 0,
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
@pytest.mark.asyncio
|
|
380
|
+
@pytest.mark.parametrize("platform", [sensor_platform, binary_sensor_platform])
|
|
381
|
+
async def test_new_nodes_are_added_once_and_listener_is_removed(platform):
|
|
382
|
+
coordinator = FakeCoordinator({"nodes": {"initial": {}}})
|
|
383
|
+
hass = SimpleNamespace(data={constants.DOMAIN: {"entry": coordinator}})
|
|
384
|
+
unload_callbacks: list[Any] = []
|
|
385
|
+
entry = SimpleNamespace(entry_id="entry", async_on_unload=unload_callbacks.append)
|
|
386
|
+
batches: list[list[Any]] = []
|
|
387
|
+
|
|
388
|
+
await platform.async_setup_entry(hass, entry, batches.append)
|
|
389
|
+
assert len(coordinator.listeners) == 1
|
|
390
|
+
coordinator.data["nodes"]["new"] = {}
|
|
391
|
+
coordinator.listeners[0]()
|
|
392
|
+
new_batch = batches[-1]
|
|
393
|
+
assert new_batch
|
|
394
|
+
assert all(entity._node_name == "new" for entity in new_batch)
|
|
395
|
+
|
|
396
|
+
coordinator.listeners[0]()
|
|
397
|
+
assert len(batches) == 2
|
|
398
|
+
unload_callbacks[0]()
|
|
399
|
+
assert coordinator.listeners == []
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def test_recording_and_storage_sensors_are_gauges():
|
|
403
|
+
descriptions = {
|
|
404
|
+
description.key: description for description in sensor_platform.MESH_SENSOR_DESCRIPTIONS
|
|
405
|
+
}
|
|
406
|
+
assert descriptions["total_recordings"].state_class == "measurement"
|
|
407
|
+
assert descriptions["total_storage_bytes"].state_class == "measurement"
|
|
408
|
+
node_descriptions = {
|
|
409
|
+
description.key: description for description in sensor_platform.NODE_SENSOR_DESCRIPTIONS
|
|
410
|
+
}
|
|
411
|
+
assert node_descriptions["storage_used_bytes"].state_class == "measurement"
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def test_counter_attributes_list_profiles_sessions_and_nodes():
|
|
415
|
+
data = {
|
|
416
|
+
"local_node": {"name": "a"},
|
|
417
|
+
"nodes": {
|
|
418
|
+
"a": {"status": "online", "version": "1", "storage_used_bytes": 5},
|
|
419
|
+
"b": {"status": "offline", "node_name": "b"},
|
|
420
|
+
},
|
|
421
|
+
"profiles": [
|
|
422
|
+
{"id": "p1", "name": "work", "engine": "chromium", "size_bytes": 1, "x": 1},
|
|
423
|
+
{"id": "p2", "name": "home", "node_name": "b"},
|
|
424
|
+
],
|
|
425
|
+
"sessions": [{"id": "s1", "name": "one", "tabs_count": 2, "profile": "work"}],
|
|
426
|
+
}
|
|
427
|
+
profiles = sensor_platform.mesh_attributes("total_profiles", data)["profiles"]
|
|
428
|
+
assert [(p["name"], p["node"]) for p in profiles] == [("work", "a"), ("home", "b")]
|
|
429
|
+
assert "x" not in profiles[0]
|
|
430
|
+
sessions = sensor_platform.mesh_attributes("total_sessions", data)["sessions"]
|
|
431
|
+
assert sessions == [{"id": "s1", "name": "one", "node": "a", "profile": "work", "tabs": 2}]
|
|
432
|
+
online = sensor_platform.mesh_attributes("online_nodes", data)
|
|
433
|
+
assert online == {"online": ["a"], "offline": ["b"]}
|
|
434
|
+
per_node = sensor_platform.node_attributes("storage_used_bytes", "b", data)
|
|
435
|
+
assert [p["name"] for p in per_node["profiles"]] == ["home"]
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|