Debian Codegraph @

tests/common.py

raw ◀ ▶
1 Debian patch touch this file
1 """Test the helper method for writing tests."""
2
3 from __future__ import annotations
4
5 import asyncio
6 import json
7 from pathlib import Path
8 import threading
9 from typing import Any, Literal
10 from unittest.mock import Mock
11
12 from freezegun.api import (
13 FrozenDateTimeFactory,
14 StepTickTimeFactory,
15 TickingDateTimeFactory,
16 )
17 import pytest
•18 from snitun.client.access_list import AccessList
19
20 from hass_nabucasa.client import CloudClient
21
22 FROZEN_NOW_AS_TIMESTAMP = 1537185600 # 2018-09-17 12:00:00 UTC
23
24 WELL_KNOWN_SERVICE_DISCOVERY_JSON = (
25 Path(__file__).parent / "fixtures" / "service_discovery.json"
26 )
27
28 type FreezeTimeFixture = (
29 FrozenDateTimeFactory | StepTickTimeFactory | TickingDateTimeFactory
30 )
31
32
33 def construct_service_discovery_actions(
34 overrides: dict[str, str] | None = None,
35 ) -> dict[str, str]:
36 """Return complete set of actions from fixture."""
37 with WELL_KNOWN_SERVICE_DISCOVERY_JSON.open() as f:
38 fixture_data = json.load(f)
39
40 return {
41 **fixture_data["actions"],
42 **(overrides or {}),
43 }
44
45
46 class MockClient(CloudClient):
47 """Interface class for Home Assistant."""
48
49 def __init__(self, base_path, loop, websession) -> None:
50 """Initialize MockClient."""
51 self._loop = loop
52 self._websession = websession
53 self._cloudhooks = {}
54 self._aiohttp_runner = Mock()
55 self.prop_remote_autostart = True
56
57 self.mock_user = []
58 self.mock_dispatcher = []
59 self.mock_alexa = []
60 self.mock_google = []
61 self.mock_webhooks = []
62 self.mock_system = []
63 self.mock_repairs = []
64 self.mock_connection_info = []
65
66 self.mock_return = []
67 self._base_path = base_path
68
69 self.pref_should_connect = False
70
71 @property
72 def base_path(self) -> Path:
73 """Return path to base dir."""
74 return self._base_path
75
76 @property
77 def loop(self):
78 """Return client loop."""
79 return self._loop
80
81 @property
82 def websession(self):
83 """Return client session for aiohttp."""
84 return self._websession
85
86 @property
87 def client_name(self):
88 """Return name of the client, this will be used as the user-agent."""
89 return "hass-nabucasa/tests"
90
91 @property
92 def aiohttp_runner(self):
93 """Return client webinterface aiohttp application."""
94 return self._aiohttp_runner
95
96 @property
97 def cloudhooks(self):
98 """Return list of cloudhooks."""
99 return self._cloudhooks
100
101 @property
102 def remote_autostart(self) -> bool:
103 """Return true if we want start a remote connection."""
104 return self.prop_remote_autostart
105
106 async def cloud_connected(self):
107 """Handle cloud connected."""
108
109 async def cloud_disconnected(self):
110 """Handle cloud disconnected."""
111
112 async def cloud_started(self):
113 """Handle cloud started."""
114
115 async def cloud_stopped(self):
116 """Handle stopping."""
117
118 async def logout_cleanups(self):
119 """Need nothing to do."""
120
121 def user_message(self, identifier: str, title: str, message: str) -> None:
122 """Create a message for user to UI."""
123 if self.loop._thread_id != threading.get_ident():
124 raise RuntimeError(
125 "`CloudClient.user_message` should be called from the event loop"
126 )
127 self.mock_user.append((identifier, title, message))
128
129 def dispatcher_message(self, identifier: str, data: Any = None) -> None:
130 """Send data to dispatcher."""
131 self.mock_dispatcher.append((identifier, data))
132
133 async def async_cloud_connect_update(self, connect: bool) -> None:
134 """Process cloud remote message to client."""
135 self.pref_should_connect = connect
136
137 async def async_alexa_message(self, payload):
138 """Process cloud alexa message to client."""
139 self.mock_alexa.append(payload)
140 return self.mock_return.pop()
141
142 async def async_google_message(self, payload):
143 """Process cloud google message to client."""
144 self.mock_google.append(payload)
145 return self.mock_return.pop()
146
147 async def async_webhook_message(self, payload):
148 """Process cloud webhook message to client."""
149 self.mock_webhooks.append(payload)
150 return self.mock_return.pop()
151
152 async def async_system_message(self, payload):
153 """Process cloud system message to client."""
154 self.mock_system.append(payload)
155 return self.mock_return.pop()
156
157 async def async_cloud_connection_info(self, payload) -> dict[Any, Any]:
158 """Process cloud connection info message to client."""
159 self.mock_connection_info.append(payload)
160 return self.mock_return.pop()
161
162 async def async_cloudhooks_update(self, data):
163 """Update internal cloudhooks data."""
164 self._cloudhooks = data
165
166 async def async_create_repair_issue(
167 self,
168 identifier: str,
169 translation_key: str,
170 *,
171 placeholders: dict[str, str] | None = None,
172 severity: Literal["error", "warning"] = "warning",
173 ) -> None:
174 """Create a repair issue."""
175 self.mock_repairs.append(
176 {
177 "identifier": identifier,
178 "translation_key": translation_key,
179 "placeholders": placeholders,
180 "severity": severity,
181 },
182 )
183
184 async def async_delete_repair_issue(self, identifier: str) -> None:
185 """Delete a repair issue."""
186 issue = next(
187 (issue for issue in self.mock_repairs if issue["identifier"] == identifier),
188 None,
189 )
190 if issue is not None:
191 self.mock_repairs.remove(issue)
192
193
194 class MockAcme:
195 """Mock AcmeHandler."""
196
197 def __init__(self) -> None:
198 """Initialize MockAcme."""
199 self.is_valid = True
200 self.call_issue = False
201 self.call_reset = False
202 self.call_load = False
203 self.call_hardening = False
204 self.init_args = None
205
206 self.common_name = None
207 self.alternative_names = None
208 self.expire_date = None
209 self.fingerprint = None
210
211 self.email = "[email protected]"
212
213 @property
214 def domains(self):
215 """Return all domains."""
216 return self.alternative_names
217
218 def set_false(self):
219 """Set certificate as not valid."""
220 self.is_valid = False
221
222 @property
223 def certificate_available(self) -> bool:
224 """Return true if certificate is available."""
225 return self.common_name is not None
226
227 @property
228 def is_valid_certificate(self) -> bool:
229 """Return valid certificate."""
230 return self.is_valid
231
232 async def issue_certificate(self):
233 """Issue a certificate."""
234 self.call_issue = True
235
236 async def reset_acme(self):
237 """Issue a certificate."""
238 self.call_reset = True
239
240 async def load_certificate(self):
241 """Load certificate."""
242 self.call_load = True
243
244 async def hardening_files(self):
245 """Hardening files."""
246 self.call_hardening = True
247
248 def __call__(self, *args, **kwargs) -> MockAcme:
249 """Init."""
250 self.init_args = args
251 self.init_kwargs = kwargs
252 return self
253
254
255 class MockSnitun:
256 """Mock Snitun client."""
257
258 def __init__(self) -> None:
259 """Initialize MockAcme."""
260 self.call_start = False
261 self.call_stop = False
262 self.call_connect = False
263 self.call_disconnect = False
264 self.init_args = None
265 self.connect_args = None
•266 self.connect_kwargs = None
267 self.init_kwarg = None
268 self.wait_task = asyncio.Event()
269
•270 self.start_access_list = None
271
272 @property
273 def is_connected(self):
274 """Return if it is connected."""
275 return self.call_connect and not self.call_disconnect
276
277 def wait(self):
278 """Return waitable object."""
279 return self.wait_task.wait()
280
281 async def start(
282 self,
•283 access_list: AccessList | None = None,
284 ) -> None:
285 """Start snitun."""
•286 self.start_access_list = access_list
287 self.call_start = True
288
289 async def stop(self):
290 """Stop snitun."""
291 self.call_stop = True
292
293 async def connect(
294 self,
295 token: bytes,
296 aes_key: bytes,
297 aes_iv: bytes,
•298 throttling: int | None = None,
299 protocol_version: int = 0,
300 ) -> None:
301 """Connect snitun."""
302 self.call_connect = True
303 self.connect_args = [token, aes_key, aes_iv, throttling]
•304 self.connect_kwargs = {
305 "throttling": throttling,
306 "protocol_version": protocol_version,
307 }
308
309 async def disconnect(self):
310 """Disconnect snitun."""
311 self.wait_task.set()
312 self.call_disconnect = True
313
314 def __call__(self, *args, **kwarg) -> MockSnitun:
315 """Init."""
316 self.init_args = args
317 self.init_kwarg = kwarg
318 return self
319
320
321 def extract_log_messages(caplog: pytest.LogCaptureFixture) -> str:
322 """Extract log messages as string from caplog fixture."""
323 return "\n".join(
324 [
325 f"[{record.levelname}] {record.name}: {record.message}"
326 for record in caplog.records
327 if record.name.startswith("hass_nabucasa")
328 ]
329 )