|
1 | 1 | import asyncio
|
2 | 2 | import logging
|
3 | 3 | import os
|
| 4 | +import time |
| 5 | +from datetime import datetime, timedelta, timezone |
| 6 | +from functools import partial |
4 | 7 | from unittest.mock import MagicMock, patch
|
5 | 8 |
|
6 | 9 | import pytest
|
|
13 | 16 | from scapy.layers.l2 import Ether
|
14 | 17 | from scapy.packet import Packet
|
15 | 18 |
|
16 |
| -from aiodhcpwatcher import DHCPRequest, async_init, async_start |
| 19 | +from aiodhcpwatcher import AUTO_RECOVER_TIME, DHCPRequest, async_init, async_start |
| 20 | + |
| 21 | +utcnow = partial(datetime.now, timezone.utc) |
| 22 | +_MONOTONIC_RESOLUTION = time.get_clock_info("monotonic").resolution |
17 | 23 |
|
18 | 24 | logging.basicConfig(level=logging.DEBUG)
|
19 | 25 |
|
20 | 26 |
|
| 27 | +def async_fire_time_changed(utc_datetime: datetime) -> None: |
| 28 | + timestamp = utc_datetime.timestamp() |
| 29 | + loop = asyncio.get_running_loop() |
| 30 | + for task in list(loop._scheduled): # type: ignore[attr-defined] |
| 31 | + if not isinstance(task, asyncio.TimerHandle): |
| 32 | + continue |
| 33 | + if task.cancelled(): |
| 34 | + continue |
| 35 | + |
| 36 | + mock_seconds_into_future = timestamp - time.time() |
| 37 | + future_seconds = task.when() - (loop.time() + _MONOTONIC_RESOLUTION) |
| 38 | + |
| 39 | + if mock_seconds_into_future >= future_seconds: |
| 40 | + task._run() |
| 41 | + task.cancel() |
| 42 | + |
| 43 | + |
21 | 44 | # connect b8:b7:f1:6d:b5:33 192.168.210.56
|
22 | 45 | RAW_DHCP_REQUEST = (
|
23 | 46 | b"\xff\xff\xff\xff\xff\xff\xb8\xb7\xf1m\xb53\x08\x00E\x00\x01P\x06E"
|
|
161 | 184 | )
|
162 | 185 |
|
163 | 186 |
|
| 187 | +async def _write_test_packets_to_pipe(w: int) -> None: |
| 188 | + for test_packet in ( |
| 189 | + RAW_DHCP_REQUEST_WITHOUT_HOSTNAME, |
| 190 | + RAW_DHCP_REQUEST, |
| 191 | + RAW_DHCP_RENEWAL, |
| 192 | + RAW_DHCP_REQUEST_WITHOUT_HOSTNAME, |
| 193 | + DHCP_REQUEST_BAD_UTF8, |
| 194 | + DHCP_REQUEST_IDNA, |
| 195 | + ): |
| 196 | + os.write(w, test_packet) |
| 197 | + for _ in range(3): |
| 198 | + await asyncio.sleep(0) |
| 199 | + os.write(w, b"garbage") |
| 200 | + for _ in range(3): |
| 201 | + await asyncio.sleep(0) |
| 202 | + |
| 203 | + |
164 | 204 | class MockSocket:
|
165 | 205 |
|
166 |
| - def __init__(self, reader: int) -> None: |
| 206 | + def __init__(self, reader: int, exc: type[Exception] | None = None) -> None: |
167 | 207 | self._fileno = reader
|
168 | 208 | self.close = MagicMock()
|
169 | 209 | self.buffer = b""
|
| 210 | + self.exc = exc |
170 | 211 |
|
171 | 212 | def recv(self) -> Packet:
|
| 213 | + if self.exc: |
| 214 | + raise self.exc |
172 | 215 | raw = os.read(self._fileno, 1000000)
|
173 | 216 | try:
|
174 | 217 | packet = Ether(raw)
|
@@ -206,20 +249,7 @@ def _handle_dhcp_packet(data: DHCPRequest) -> None:
|
206 | 249 | "aiodhcpwatcher.AIODHCPWatcher._make_listen_socket", return_value=mock_socket
|
207 | 250 | ), patch("aiodhcpwatcher.AIODHCPWatcher._verify_working_pcap"):
|
208 | 251 | stop = await async_start(_handle_dhcp_packet)
|
209 |
| - for test_packet in ( |
210 |
| - RAW_DHCP_REQUEST_WITHOUT_HOSTNAME, |
211 |
| - RAW_DHCP_REQUEST, |
212 |
| - RAW_DHCP_RENEWAL, |
213 |
| - RAW_DHCP_REQUEST_WITHOUT_HOSTNAME, |
214 |
| - DHCP_REQUEST_BAD_UTF8, |
215 |
| - DHCP_REQUEST_IDNA, |
216 |
| - ): |
217 |
| - os.write(w, test_packet) |
218 |
| - for _ in range(3): |
219 |
| - await asyncio.sleep(0) |
220 |
| - os.write(w, b"garbage") |
221 |
| - for _ in range(3): |
222 |
| - await asyncio.sleep(0) |
| 252 | + await _write_test_packets_to_pipe(w) |
223 | 253 |
|
224 | 254 | stop()
|
225 | 255 |
|
@@ -255,6 +285,139 @@ def _handle_dhcp_packet(data: DHCPRequest) -> None:
|
255 | 285 | ]
|
256 | 286 |
|
257 | 287 |
|
| 288 | +@pytest.mark.asyncio |
| 289 | +async def test_watcher_fatal_exception(caplog: pytest.LogCaptureFixture) -> None: |
| 290 | + """Test mocking a dhcp packet to the watcher.""" |
| 291 | + requests: list[DHCPRequest] = [] |
| 292 | + |
| 293 | + def _handle_dhcp_packet(data: DHCPRequest) -> None: |
| 294 | + requests.append(data) |
| 295 | + |
| 296 | + r, w = os.pipe() |
| 297 | + |
| 298 | + mock_socket = MockSocket(r, ValueError) |
| 299 | + with patch( |
| 300 | + "aiodhcpwatcher.AIODHCPWatcher._make_listen_socket", return_value=mock_socket |
| 301 | + ), patch("aiodhcpwatcher.AIODHCPWatcher._verify_working_pcap"): |
| 302 | + stop = await async_start(_handle_dhcp_packet) |
| 303 | + await _write_test_packets_to_pipe(w) |
| 304 | + |
| 305 | + stop() |
| 306 | + |
| 307 | + os.close(r) |
| 308 | + os.close(w) |
| 309 | + assert requests == [] |
| 310 | + assert "Fatal error while processing dhcp packet" in caplog.text |
| 311 | + |
| 312 | + |
| 313 | +@pytest.mark.asyncio |
| 314 | +async def test_watcher_temp_exception(caplog: pytest.LogCaptureFixture) -> None: |
| 315 | + """Test mocking a dhcp packet to the watcher.""" |
| 316 | + requests: list[DHCPRequest] = [] |
| 317 | + |
| 318 | + def _handle_dhcp_packet(data: DHCPRequest) -> None: |
| 319 | + requests.append(data) |
| 320 | + |
| 321 | + r, w = os.pipe() |
| 322 | + |
| 323 | + mock_socket = MockSocket(r, OSError) |
| 324 | + with patch( |
| 325 | + "aiodhcpwatcher.AIODHCPWatcher._make_listen_socket", return_value=mock_socket |
| 326 | + ), patch("aiodhcpwatcher.AIODHCPWatcher._verify_working_pcap"): |
| 327 | + stop = await async_start(_handle_dhcp_packet) |
| 328 | + await _write_test_packets_to_pipe(w) |
| 329 | + os.close(r) |
| 330 | + os.close(w) |
| 331 | + assert requests == [] |
| 332 | + assert "Error while processing dhcp packet" in caplog.text |
| 333 | + |
| 334 | + r, w = os.pipe() |
| 335 | + mock_socket = MockSocket(r) |
| 336 | + with patch( |
| 337 | + "aiodhcpwatcher.AIODHCPWatcher._make_listen_socket", return_value=mock_socket |
| 338 | + ), patch("aiodhcpwatcher.AIODHCPWatcher._verify_working_pcap"): |
| 339 | + |
| 340 | + async_fire_time_changed(utcnow() + timedelta(seconds=AUTO_RECOVER_TIME)) |
| 341 | + await asyncio.sleep(0.1) |
| 342 | + |
| 343 | + await _write_test_packets_to_pipe(w) |
| 344 | + |
| 345 | + stop() |
| 346 | + |
| 347 | + os.close(r) |
| 348 | + os.close(w) |
| 349 | + assert requests == [ |
| 350 | + DHCPRequest( |
| 351 | + ip_address="192.168.107.151", hostname="", mac_address="60:6b:bd:59:e4:b4" |
| 352 | + ), |
| 353 | + DHCPRequest( |
| 354 | + ip_address="192.168.210.56", |
| 355 | + hostname="connect", |
| 356 | + mac_address="b8:b7:f1:6d:b5:33", |
| 357 | + ), |
| 358 | + DHCPRequest( |
| 359 | + ip_address="192.168.1.120", |
| 360 | + hostname="iRobot-AE9EC12DD3B04885BCBFA36AFB01E1CC", |
| 361 | + mac_address="50:14:79:03:85:2c", |
| 362 | + ), |
| 363 | + DHCPRequest( |
| 364 | + ip_address="192.168.107.151", hostname="", mac_address="60:6b:bd:59:e4:b4" |
| 365 | + ), |
| 366 | + DHCPRequest( |
| 367 | + ip_address="192.168.210.56", |
| 368 | + hostname="connec�", |
| 369 | + mac_address="b8:b7:f1:6d:b5:33", |
| 370 | + ), |
| 371 | + DHCPRequest( |
| 372 | + ip_address="192.168.210.56", |
| 373 | + hostname="ó", |
| 374 | + mac_address="b8:b7:f1:6d:b5:33", |
| 375 | + ), |
| 376 | + ] |
| 377 | + |
| 378 | + |
| 379 | +@pytest.mark.asyncio |
| 380 | +async def test_watcher_stop_after_temp_exception( |
| 381 | + caplog: pytest.LogCaptureFixture, |
| 382 | +) -> None: |
| 383 | + """Test mocking a dhcp packet to the watcher.""" |
| 384 | + requests: list[DHCPRequest] = [] |
| 385 | + |
| 386 | + def _handle_dhcp_packet(data: DHCPRequest) -> None: |
| 387 | + requests.append(data) |
| 388 | + |
| 389 | + r, w = os.pipe() |
| 390 | + |
| 391 | + mock_socket = MockSocket(r, OSError) |
| 392 | + with patch( |
| 393 | + "aiodhcpwatcher.AIODHCPWatcher._make_listen_socket", return_value=mock_socket |
| 394 | + ), patch("aiodhcpwatcher.AIODHCPWatcher._verify_working_pcap"): |
| 395 | + stop = await async_start(_handle_dhcp_packet) |
| 396 | + await _write_test_packets_to_pipe(w) |
| 397 | + |
| 398 | + os.close(r) |
| 399 | + os.close(w) |
| 400 | + assert requests == [] |
| 401 | + assert "Error while processing dhcp packet" in caplog.text |
| 402 | + stop() |
| 403 | + |
| 404 | + r, w = os.pipe() |
| 405 | + mock_socket = MockSocket(r) |
| 406 | + with patch( |
| 407 | + "aiodhcpwatcher.AIODHCPWatcher._make_listen_socket", return_value=mock_socket |
| 408 | + ), patch("aiodhcpwatcher.AIODHCPWatcher._verify_working_pcap"): |
| 409 | + |
| 410 | + async_fire_time_changed(utcnow() + timedelta(seconds=30)) |
| 411 | + await asyncio.sleep(0) |
| 412 | + await _write_test_packets_to_pipe(w) |
| 413 | + |
| 414 | + stop() |
| 415 | + |
| 416 | + os.close(r) |
| 417 | + os.close(w) |
| 418 | + assert requests == [] |
| 419 | + |
| 420 | + |
258 | 421 | @pytest.mark.asyncio
|
259 | 422 | async def test_setup_fails_broken_filtering(caplog: pytest.LogCaptureFixture) -> None:
|
260 | 423 | """Test that the setup fails when filtering is broken."""
|
|
0 commit comments