browser-daemon-client 0.12.2__tar.gz → 0.12.3__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.12.3}/PKG-INFO +5 -1
- {browser_daemon_client-0.12.2 → browser_daemon_client-0.12.3}/README.md +4 -0
- {browser_daemon_client-0.12.2 → browser_daemon_client-0.12.3}/browser_daemon_client/__init__.py +54 -0
- {browser_daemon_client-0.12.2 → browser_daemon_client-0.12.3}/browser_daemon_client.egg-info/PKG-INFO +5 -1
- {browser_daemon_client-0.12.2 → browser_daemon_client-0.12.3}/browser_daemon_client.egg-info/SOURCES.txt +2 -1
- {browser_daemon_client-0.12.2 → browser_daemon_client-0.12.3}/pyproject.toml +1 -1
- {browser_daemon_client-0.12.2 → browser_daemon_client-0.12.3}/tests/test_client.py +41 -0
- browser_daemon_client-0.12.3/tests/test_ha_integration.py +435 -0
- {browser_daemon_client-0.12.2 → browser_daemon_client-0.12.3}/browser_daemon_client.egg-info/dependency_links.txt +0 -0
- {browser_daemon_client-0.12.2 → browser_daemon_client-0.12.3}/browser_daemon_client.egg-info/requires.txt +0 -0
- {browser_daemon_client-0.12.2 → browser_daemon_client-0.12.3}/browser_daemon_client.egg-info/top_level.txt +0 -0
- {browser_daemon_client-0.12.2 → browser_daemon_client-0.12.3}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: browser-daemon-client
|
|
3
|
-
Version: 0.12.
|
|
3
|
+
Version: 0.12.3
|
|
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,6 +45,10 @@ 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).
|
|
@@ -34,6 +34,10 @@ 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).
|
{browser_daemon_client-0.12.2 → browser_daemon_client-0.12.3}/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,6 +250,48 @@ 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
|
+
|
|
241
295
|
async def create_session(
|
|
242
296
|
self, *, profile: str | None = None, node: str | None = None, **options: Any
|
|
243
297
|
) -> dict[str, Any]:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: browser-daemon-client
|
|
3
|
-
Version: 0.12.
|
|
3
|
+
Version: 0.12.3
|
|
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,6 +45,10 @@ 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).
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "browser-daemon-client"
|
|
7
|
-
version = "0.12.
|
|
7
|
+
version = "0.12.3"
|
|
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,
|
|
@@ -150,6 +151,46 @@ async def test_a_session_is_named_after_the_client(daemon):
|
|
|
150
151
|
}
|
|
151
152
|
|
|
152
153
|
|
|
154
|
+
async def test_login_uses_existing_session_and_tab_without_logging_secrets(daemon):
|
|
155
|
+
bd, seen, answers = daemon
|
|
156
|
+
answers[("POST", "/api/sessions/session%2Fid/login")] = (
|
|
157
|
+
200,
|
|
158
|
+
{"outcome": "needs_totp"},
|
|
159
|
+
)
|
|
160
|
+
result = await bd.login(
|
|
161
|
+
"session/id",
|
|
162
|
+
"tab-id",
|
|
163
|
+
"alice",
|
|
164
|
+
"not-for-logs",
|
|
165
|
+
totp_secret="JBSWY3DPEHPK3PXP",
|
|
166
|
+
allowed_origins=["https://login.example.test"],
|
|
167
|
+
success_selector=".account-home",
|
|
168
|
+
)
|
|
169
|
+
assert result == LoginResult("needs_totp")
|
|
170
|
+
assert seen[0]["json"] == {
|
|
171
|
+
"tab": "tab-id",
|
|
172
|
+
"username": "alice",
|
|
173
|
+
"password": "not-for-logs",
|
|
174
|
+
"totp_secret": "JBSWY3DPEHPK3PXP",
|
|
175
|
+
"allowed_origins": ["https://login.example.test"],
|
|
176
|
+
"success_selector": ".account-home",
|
|
177
|
+
"timeout_seconds": 30,
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
async def test_login_refuses_both_totp_seed_and_code(daemon):
|
|
182
|
+
bd, _, _ = daemon
|
|
183
|
+
with pytest.raises(ValueError, match="not both"):
|
|
184
|
+
await bd.login(
|
|
185
|
+
"session",
|
|
186
|
+
"tab",
|
|
187
|
+
"alice",
|
|
188
|
+
"password",
|
|
189
|
+
totp_secret="seed",
|
|
190
|
+
totp_code="123456",
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
|
|
153
194
|
async def test_an_unreachable_daemon_is_a_browser_daemon_error():
|
|
154
195
|
async with aiohttp.ClientSession() as http:
|
|
155
196
|
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
|