| 1 |
"""Tests for Service Discovery API.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import asyncio |
| 6 |
from collections.abc import Generator |
| 7 |
import re |
| 8 |
from typing import TYPE_CHECKING, Any |
| 9 |
from unittest.mock import AsyncMock, patch |
| 10 |
|
| 11 |
from aiohttp import ClientError |
| 12 |
import pytest |
| 13 |
from syrupy import SnapshotAssertion |
| 14 |
|
| 15 |
from hass_nabucasa.const import FIVE_MINUTES_IN_SECONDS |
| 16 |
from hass_nabucasa.events.types import CloudEventType |
| 17 |
from hass_nabucasa.service_discovery import ( |
| 18 |
MIN_REFRESH_INTERVAL, |
| 19 |
ServiceDiscovery, |
| 20 |
ServiceDiscoveryError, |
| 21 |
ServiceDiscoveryMissingActionError, |
| 22 |
ServiceDiscoveryMissingParameterError, |
| 23 |
_calculate_sleep_time, |
| 24 |
) |
| 25 |
from hass_nabucasa.utils import utcnow |
| 26 |
|
| 27 |
from .common import ( |
| 28 |
FreezeTimeFixture, |
| 29 |
extract_log_messages, |
| 30 |
) |
| 31 |
|
| 32 |
if TYPE_CHECKING: |
| 33 |
from hass_nabucasa import Cloud |
| 34 |
from tests.utils.aiohttp import AiohttpClientMocker |
| 35 |
|
| 36 |
BASE_EXPECTED_RESULT = { |
| 37 |
"actions": {"test_api_action": "https://example.com/test/{param}/action"}, |
| 38 |
"valid_for": 3600, |
| 39 |
"version": "1.0", |
| 40 |
} |
| 41 |
|
| 42 |
|
| 43 |
def assert_snapshot_with_logs( |
| 44 |
result: Any, caplog: pytest.LogCaptureFixture, snapshot: SnapshotAssertion |
| 45 |
) -> None: |
| 46 |
"""Assert result and logs match snapshot.""" |
| 47 |
assert {"result": result, "log": extract_log_messages(caplog)} == snapshot |
| 48 |
|
| 49 |
|
| 50 |
@pytest.fixture(autouse=True) |
| 51 |
def jitter_patch() -> Generator[Any, Any, Any]: |
| 52 |
"""Mock jitter to always return 0.""" |
| 53 |
with patch("hass_nabucasa.service_discovery.jitter", return_value=111): |
| 54 |
yield |
| 55 |
|
| 56 |
|
| 57 |
@pytest.fixture(autouse=True) |
| 58 |
def add_test_api_action_to_service_discovery(): |
| 59 |
"""Add test_api_action for this module's tests.""" |
| 60 |
with ( |
| 61 |
patch( |
| 62 |
"hass_nabucasa.service_discovery.VALID_ACTION_NAMES", |
| 63 |
frozenset(BASE_EXPECTED_RESULT["actions"].keys()), |
| 64 |
), |
| 65 |
): |
| 66 |
yield |
| 67 |
|
| 68 |
|
| 69 |
@pytest.mark.parametrize( |
| 70 |
"exception,mockargs,exception_msg", |
| 71 |
[ |
| 72 |
[ |
| 73 |
ServiceDiscoveryError, |
| 74 |
{"status": 500, "text": "Internal Server Error"}, |
| 75 |
"Failed to parse API response", |
| 76 |
], |
| 77 |
[ |
| 78 |
ServiceDiscoveryError, |
| 79 |
{"status": 429, "text": "Too fast"}, |
| 80 |
"Failed to parse API response", |
| 81 |
], |
| 82 |
[ |
| 83 |
ServiceDiscoveryError, |
| 84 |
{"exc": TimeoutError()}, |
| 85 |
"Timeout reached while calling API", |
| 86 |
], |
| 87 |
[ |
| 88 |
ServiceDiscoveryError, |
| 89 |
{"exc": ClientError("boom!")}, |
| 90 |
"Failed to fetch: boom!", |
| 91 |
], |
| 92 |
[ |
| 93 |
ServiceDiscoveryError, |
| 94 |
{"exc": Exception("boom!")}, |
| 95 |
"Unexpected error while calling API: boom!", |
| 96 |
], |
| 97 |
], |
| 98 |
ids=["500-error", "429-error", "timeout", "client-error", "unexpected-error"], |
| 99 |
) |
| 100 |
async def test_fetch_well_known_endpoint_problems( |
| 101 |
aioclient_mock: AiohttpClientMocker, |
| 102 |
cloud: Cloud, |
| 103 |
exception: Exception, |
| 104 |
mockargs: dict[str, Any], |
| 105 |
exception_msg: str, |
| 106 |
caplog: pytest.LogCaptureFixture, |
| 107 |
): |
| 108 |
"""Test problems with well-known service discovery endpoint.""" |
| 109 |
aioclient_mock.get( |
| 110 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 111 |
**mockargs, |
| 112 |
) |
| 113 |
|
| 114 |
with pytest.raises(exception, match=re.escape(exception_msg)): |
| 115 |
await cloud.service_discovery._fetch_well_known_service_discovery() |
| 116 |
|
| 117 |
|
| 118 |
async def test_fetch_well_known_success( |
| 119 |
aioclient_mock: AiohttpClientMocker, |
| 120 |
cloud: Cloud, |
| 121 |
caplog: pytest.LogCaptureFixture, |
| 122 |
snapshot: SnapshotAssertion, |
| 123 |
): |
| 124 |
"""Test successful fetch of well-known service discovery endpoint.""" |
| 125 |
aioclient_mock.get( |
| 126 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 127 |
json=BASE_EXPECTED_RESULT, |
| 128 |
) |
| 129 |
|
| 130 |
result = await cloud.service_discovery._fetch_well_known_service_discovery() |
| 131 |
|
| 132 |
assert result == BASE_EXPECTED_RESULT |
| 133 |
assert_snapshot_with_logs(result, caplog, snapshot) |
| 134 |
|
| 135 |
|
| 136 |
async def test_fetch_well_known_invalid_response( |
| 137 |
aioclient_mock: AiohttpClientMocker, |
| 138 |
cloud: Cloud, |
| 139 |
caplog: pytest.LogCaptureFixture, |
| 140 |
): |
| 141 |
"""Test invalid response from well-known service discovery endpoint.""" |
| 142 |
aioclient_mock.get( |
| 143 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 144 |
json={"invalid": "data"}, |
| 145 |
) |
| 146 |
|
| 147 |
with pytest.raises( |
| 148 |
ServiceDiscoveryError, match=re.escape("required key not provided") |
| 149 |
): |
| 150 |
await cloud.service_discovery._fetch_well_known_service_discovery() |
| 151 |
|
| 152 |
|
| 153 |
async def test_load_service_discovery_data_caches_result( |
| 154 |
aioclient_mock: AiohttpClientMocker, |
| 155 |
cloud: Cloud, |
| 156 |
caplog: pytest.LogCaptureFixture, |
| 157 |
snapshot: SnapshotAssertion, |
| 158 |
): |
| 159 |
"""Test that service discovery data is cached.""" |
| 160 |
aioclient_mock.get( |
| 161 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 162 |
json=BASE_EXPECTED_RESULT, |
| 163 |
) |
| 164 |
|
| 165 |
cache1 = await cloud.service_discovery._load_service_discovery_data() |
| 166 |
assert "Service discovery data cached" in caplog.text |
| 167 |
assert cache1 is not None |
| 168 |
assert cloud.service_discovery._memory_cache is not None |
| 169 |
|
| 170 |
cache2 = await cloud.service_discovery._load_service_discovery_data() |
| 171 |
assert cache1 is cache2 |
| 172 |
|
| 173 |
assert_snapshot_with_logs( |
| 174 |
{"cache1": cache1["data"], "cache2": cache2["data"]}, |
| 175 |
caplog, |
| 176 |
snapshot, |
| 177 |
) |
| 178 |
|
| 179 |
|
| 180 |
async def test_load_service_discovery_data_uses_expired_cache_on_failure( |
| 181 |
aioclient_mock: AiohttpClientMocker, |
| 182 |
cloud: Cloud, |
| 183 |
caplog: pytest.LogCaptureFixture, |
| 184 |
snapshot: SnapshotAssertion, |
| 185 |
): |
| 186 |
"""Test that expired cache is used when API fails.""" |
| 187 |
expected_result = { |
| 188 |
**BASE_EXPECTED_RESULT, |
| 189 |
"version": "1.0", |
| 190 |
} |
| 191 |
|
| 192 |
aioclient_mock.get( |
| 193 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 194 |
json=expected_result, |
| 195 |
) |
| 196 |
|
| 197 |
cache1 = await cloud.service_discovery._load_service_discovery_data() |
| 198 |
assert cache1 is not None |
| 199 |
|
| 200 |
await asyncio.sleep(0.01) |
| 201 |
|
| 202 |
aioclient_mock.clear_requests() |
| 203 |
aioclient_mock.get( |
| 204 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 205 |
status=500, |
| 206 |
text="Internal Server Error", |
| 207 |
) |
| 208 |
aioclient_mock.get( |
| 209 |
"https://example.com/.well-known/service-discovery", |
| 210 |
status=500, |
| 211 |
text="Internal Server Error", |
| 212 |
) |
| 213 |
|
| 214 |
cache2 = await cloud.service_discovery._load_service_discovery_data() |
| 215 |
assert cache2 is cache1 |
| 216 |
assert_snapshot_with_logs( |
| 217 |
{"cache1": cache1["data"], "cache2": cache2["data"]}, |
| 218 |
caplog, |
| 219 |
snapshot, |
| 220 |
) |
| 221 |
|
| 222 |
|
| 223 |
async def test_load_service_discovery_data_raises_when_no_cache_and_failure( |
| 224 |
aioclient_mock: AiohttpClientMocker, |
| 225 |
cloud: Cloud, |
| 226 |
caplog: pytest.LogCaptureFixture, |
| 227 |
): |
| 228 |
"""Test that error is raised when no cache exists and API fails.""" |
| 229 |
aioclient_mock.get( |
| 230 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 231 |
status=500, |
| 232 |
text="Internal Server Error", |
| 233 |
) |
| 234 |
|
| 235 |
with pytest.raises( |
| 236 |
ServiceDiscoveryError, match=re.escape("Failed to parse API response") |
| 237 |
): |
| 238 |
await cloud.service_discovery._load_service_discovery_data() |
| 239 |
|
| 240 |
|
| 241 |
async def test_async_start_service_discovery_success( |
| 242 |
aioclient_mock: AiohttpClientMocker, |
| 243 |
cloud: Cloud, |
| 244 |
caplog: pytest.LogCaptureFixture, |
| 245 |
): |
| 246 |
"""Test starting service discovery successfully.""" |
| 247 |
aioclient_mock.get( |
| 248 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 249 |
json=BASE_EXPECTED_RESULT, |
| 250 |
) |
| 251 |
|
| 252 |
await cloud.service_discovery.async_start_service_discovery() |
| 253 |
|
| 254 |
assert cloud.service_discovery._service_discovery_refresh_task is not None |
| 255 |
assert not cloud.service_discovery._service_discovery_refresh_task.done() |
| 256 |
|
| 257 |
await cloud.service_discovery.async_stop_service_discovery() |
| 258 |
|
| 259 |
|
| 260 |
async def test_async_start_service_discovery_handles_initial_failure( |
| 261 |
aioclient_mock: AiohttpClientMocker, |
| 262 |
cloud: Cloud, |
| 263 |
caplog: pytest.LogCaptureFixture, |
| 264 |
): |
| 265 |
"""Test that service discovery handles initial load failure gracefully.""" |
| 266 |
aioclient_mock.get( |
| 267 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 268 |
status=500, |
| 269 |
text="Internal Server Error", |
| 270 |
) |
| 271 |
|
| 272 |
await cloud.service_discovery.async_start_service_discovery() |
| 273 |
|
| 274 |
assert "Failed to load initial service discovery data" in caplog.text |
| 275 |
assert cloud.service_discovery._service_discovery_refresh_task is not None |
| 276 |
|
| 277 |
await cloud.service_discovery.async_stop_service_discovery() |
| 278 |
|
| 279 |
|
| 280 |
async def test_async_stop_service_discovery( |
| 281 |
aioclient_mock: AiohttpClientMocker, |
| 282 |
cloud: Cloud, |
| 283 |
caplog: pytest.LogCaptureFixture, |
| 284 |
): |
| 285 |
"""Test stopping service discovery.""" |
| 286 |
aioclient_mock.get( |
| 287 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 288 |
json=BASE_EXPECTED_RESULT, |
| 289 |
) |
| 290 |
|
| 291 |
await cloud.service_discovery.async_start_service_discovery() |
| 292 |
|
| 293 |
assert cloud.service_discovery._service_discovery_refresh_task is not None |
| 294 |
|
| 295 |
await cloud.service_discovery.async_stop_service_discovery() |
| 296 |
|
| 297 |
assert cloud.service_discovery._service_discovery_refresh_task is None |
| 298 |
|
| 299 |
|
| 300 |
async def test_action_url_returns_cached_url( |
| 301 |
aioclient_mock: AiohttpClientMocker, |
| 302 |
cloud: Cloud, |
| 303 |
caplog: pytest.LogCaptureFixture, |
| 304 |
snapshot: SnapshotAssertion, |
| 305 |
): |
| 306 |
"""Test that action_url returns cached URL.""" |
| 307 |
aioclient_mock.get( |
| 308 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 309 |
json=BASE_EXPECTED_RESULT, |
| 310 |
) |
| 311 |
|
| 312 |
await cloud.service_discovery._load_service_discovery_data() |
| 313 |
|
| 314 |
url = cloud.service_discovery.action_url("test_api_action", param="test") |
| 315 |
assert isinstance(url, str) |
| 316 |
assert url == "https://example.com/test/test/action" |
| 317 |
assert_snapshot_with_logs(url, caplog, snapshot) |
| 318 |
|
| 319 |
|
| 320 |
async def test_action_url_returns_fallback_url( |
| 321 |
aioclient_mock: AiohttpClientMocker, |
| 322 |
cloud: Cloud, |
| 323 |
caplog: pytest.LogCaptureFixture, |
| 324 |
snapshot: SnapshotAssertion, |
| 325 |
): |
| 326 |
"""Test that action_url returns fallback URL when not cached.""" |
| 327 |
cloud.service_discovery._fallback_actions = { |
| 328 |
"test_api_action": "https://example.com/test/fallback/action" |
| 329 |
} |
| 330 |
url = cloud.service_discovery.action_url("test_api_action", param="test") |
| 331 |
assert url == "https://example.com/test/fallback/action" |
| 332 |
assert "Using fallback action URL" in caplog.text |
| 333 |
assert_snapshot_with_logs(url, caplog, snapshot) |
| 334 |
|
| 335 |
|
| 336 |
async def test_action_url_with_format_parameters( |
| 337 |
aioclient_mock: AiohttpClientMocker, |
| 338 |
cloud: Cloud, |
| 339 |
caplog: pytest.LogCaptureFixture, |
| 340 |
snapshot: SnapshotAssertion, |
| 341 |
): |
| 342 |
"""Test that action_url correctly applies format parameters.""" |
| 343 |
aioclient_mock.get( |
| 344 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 345 |
json=BASE_EXPECTED_RESULT, |
| 346 |
) |
| 347 |
|
| 348 |
await cloud.service_discovery._load_service_discovery_data() |
| 349 |
|
| 350 |
url = cloud.service_discovery.action_url("test_api_action", param="test") |
| 351 |
assert isinstance(url, str) |
| 352 |
assert "test" in url |
| 353 |
assert_snapshot_with_logs(url, caplog, snapshot) |
| 354 |
|
| 355 |
|
| 356 |
async def test_action_url_missing_format_parameter( |
| 357 |
aioclient_mock: AiohttpClientMocker, |
| 358 |
cloud: Cloud, |
| 359 |
caplog: pytest.LogCaptureFixture, |
| 360 |
): |
| 361 |
"""Test that action_url raises error when format parameter is missing.""" |
| 362 |
aioclient_mock.get( |
| 363 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 364 |
json=BASE_EXPECTED_RESULT, |
| 365 |
) |
| 366 |
|
| 367 |
await cloud.service_discovery._load_service_discovery_data() |
| 368 |
|
| 369 |
with pytest.raises(ServiceDiscoveryMissingParameterError): |
| 370 |
cloud.service_discovery.action_url("test_api_action") |
| 371 |
|
| 372 |
|
| 373 |
async def test_action_url_with_override( |
| 374 |
aioclient_mock: AiohttpClientMocker, |
| 375 |
cloud: Cloud, |
| 376 |
caplog: pytest.LogCaptureFixture, |
| 377 |
snapshot: SnapshotAssertion, |
| 378 |
): |
| 379 |
"""Test that action_url uses override when provided.""" |
| 380 |
override_url = "https://override.example.com/custom" |
| 381 |
cloud.service_discovery._action_overrides = {"test_api_action": override_url} |
| 382 |
|
| 383 |
url = cloud.service_discovery.action_url("test_api_action") |
| 384 |
assert url == override_url |
| 385 |
assert "Using overridden action URL" in caplog.text |
| 386 |
assert_snapshot_with_logs(url, caplog, snapshot) |
| 387 |
|
| 388 |
|
| 389 |
async def test_get_fallback_action_url_for_missing_action( |
| 390 |
aioclient_mock: AiohttpClientMocker, |
| 391 |
cloud: Cloud, |
| 392 |
caplog: pytest.LogCaptureFixture, |
| 393 |
): |
| 394 |
"""Test that fallback raises error for unknown action.""" |
| 395 |
with pytest.raises(ServiceDiscoveryMissingActionError): |
| 396 |
cloud.service_discovery._get_fallback_action_url("invalid_action") # type: ignore[arg-type] |
| 397 |
|
| 398 |
|
| 399 |
async def test_service_discovery_with_action_overrides( |
| 400 |
aioclient_mock: AiohttpClientMocker, |
| 401 |
cloud: Cloud, |
| 402 |
caplog: pytest.LogCaptureFixture, |
| 403 |
snapshot: SnapshotAssertion, |
| 404 |
): |
| 405 |
"""Test that ServiceDiscovery can be initialized with action overrides.""" |
| 406 |
override_url = "https://override.example.com/custom" |
| 407 |
discovery = ServiceDiscovery( |
| 408 |
cloud, action_overrides={"test_api_action": override_url} |
| 409 |
) |
| 410 |
|
| 411 |
url = discovery.action_url("test_api_action") |
| 412 |
assert url == override_url |
| 413 |
assert_snapshot_with_logs(url, caplog, snapshot) |
| 414 |
|
| 415 |
|
| 416 |
async def test_invalid_action_name_in_response( |
| 417 |
aioclient_mock: AiohttpClientMocker, |
| 418 |
cloud: Cloud, |
| 419 |
caplog: pytest.LogCaptureFixture, |
| 420 |
snapshot: SnapshotAssertion, |
| 421 |
): |
| 422 |
"""Test that invalid action names in response are filtered out.""" |
| 423 |
expected_result = { |
| 424 |
**BASE_EXPECTED_RESULT, |
| 425 |
"actions": { |
| 426 |
**BASE_EXPECTED_RESULT["actions"], |
| 427 |
"invalid_action": "https://example.com/invalid", |
| 428 |
}, |
| 429 |
"valid_for": 3600, |
| 430 |
"version": "1.0", |
| 431 |
} |
| 432 |
|
| 433 |
aioclient_mock.get( |
| 434 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 435 |
json=expected_result, |
| 436 |
) |
| 437 |
|
| 438 |
result = await cloud.service_discovery._fetch_well_known_service_discovery() |
| 439 |
assert "test_api_action" in result["actions"] |
| 440 |
assert "invalid_action" not in result["actions"] |
| 441 |
assert_snapshot_with_logs(result, caplog, snapshot) |
| 442 |
|
| 443 |
|
| 444 |
async def test_concurrent_cache_load_uses_lock( |
| 445 |
aioclient_mock: AiohttpClientMocker, |
| 446 |
cloud: Cloud, |
| 447 |
caplog: pytest.LogCaptureFixture, |
| 448 |
): |
| 449 |
"""Test that concurrent cache loads are serialized by lock.""" |
| 450 |
aioclient_mock.get( |
| 451 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 452 |
json=BASE_EXPECTED_RESULT, |
| 453 |
) |
| 454 |
|
| 455 |
results = await asyncio.gather( |
| 456 |
cloud.service_discovery._load_service_discovery_data(), |
| 457 |
cloud.service_discovery._load_service_discovery_data(), |
| 458 |
cloud.service_discovery._load_service_discovery_data(), |
| 459 |
) |
| 460 |
|
| 461 |
assert aioclient_mock.call_count == 1 |
| 462 |
assert all(r == results[0] for r in results) |
| 463 |
assert all(r["data"]["version"] == "1.0" for r in results) |
| 464 |
|
| 465 |
|
| 466 |
async def test_background_task_lifecycle_success( |
| 467 |
aioclient_mock: AiohttpClientMocker, |
| 468 |
cloud: Cloud, |
| 469 |
caplog: pytest.LogCaptureFixture, |
| 470 |
): |
| 471 |
"""Test complete lifecycle of background refresh task.""" |
| 472 |
aioclient_mock.get( |
| 473 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 474 |
json=BASE_EXPECTED_RESULT, |
| 475 |
) |
| 476 |
|
| 477 |
await cloud.service_discovery.async_start_service_discovery() |
| 478 |
assert cloud.service_discovery._service_discovery_refresh_task is not None |
| 479 |
assert not cloud.service_discovery._service_discovery_refresh_task.done() |
| 480 |
assert cloud.service_discovery._memory_cache is not None |
| 481 |
assert cloud.service_discovery._memory_cache["data"]["version"] == "1.0" |
| 482 |
|
| 483 |
await cloud.service_discovery.async_stop_service_discovery() |
| 484 |
assert cloud.service_discovery._service_discovery_refresh_task is None |
| 485 |
|
| 486 |
|
| 487 |
async def test_background_task_handles_api_failures( |
| 488 |
aioclient_mock: AiohttpClientMocker, |
| 489 |
cloud: Cloud, |
| 490 |
caplog: pytest.LogCaptureFixture, |
| 491 |
): |
| 492 |
"""Test that background task survives initial API failures.""" |
| 493 |
aioclient_mock.get( |
| 494 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 495 |
status=500, |
| 496 |
text="Internal Server Error", |
| 497 |
) |
| 498 |
|
| 499 |
await cloud.service_discovery.async_start_service_discovery() |
| 500 |
|
| 501 |
assert "Failed to load initial service discovery data" in caplog.text |
| 502 |
assert cloud.service_discovery._service_discovery_refresh_task is not None |
| 503 |
assert not cloud.service_discovery._service_discovery_refresh_task.done() |
| 504 |
|
| 505 |
await cloud.service_discovery.async_stop_service_discovery() |
| 506 |
|
| 507 |
|
| 508 |
async def test_stop_during_active_refresh( |
| 509 |
aioclient_mock: AiohttpClientMocker, |
| 510 |
cloud: Cloud, |
| 511 |
caplog: pytest.LogCaptureFixture, |
| 512 |
): |
| 513 |
"""Test stopping service discovery during an active refresh.""" |
| 514 |
aioclient_mock.get( |
| 515 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 516 |
json={ |
| 517 |
**BASE_EXPECTED_RESULT, |
| 518 |
"valid_for": 1, |
| 519 |
}, |
| 520 |
) |
| 521 |
|
| 522 |
await cloud.service_discovery.async_start_service_discovery() |
| 523 |
await asyncio.sleep(0.1) |
| 524 |
|
| 525 |
await cloud.service_discovery.async_stop_service_discovery() |
| 526 |
|
| 527 |
assert cloud.service_discovery._service_discovery_refresh_task is None |
| 528 |
assert "Service discovery refresh task cancelled" in caplog.text |
| 529 |
|
| 530 |
|
| 531 |
async def test_multiple_start_stop_cycles( |
| 532 |
aioclient_mock: AiohttpClientMocker, |
| 533 |
cloud: Cloud, |
| 534 |
caplog: pytest.LogCaptureFixture, |
| 535 |
): |
| 536 |
"""Test multiple start/stop cycles work correctly.""" |
| 537 |
aioclient_mock.get( |
| 538 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 539 |
json=BASE_EXPECTED_RESULT, |
| 540 |
) |
| 541 |
|
| 542 |
for _ in range(3): |
| 543 |
await cloud.service_discovery.async_start_service_discovery() |
| 544 |
assert cloud.service_discovery._service_discovery_refresh_task is not None |
| 545 |
|
| 546 |
await cloud.service_discovery.async_stop_service_discovery() |
| 547 |
assert cloud.service_discovery._service_discovery_refresh_task is None |
| 548 |
|
| 549 |
|
| 550 |
async def test_cloud_initialization_lifecycle( |
| 551 |
aioclient_mock: AiohttpClientMocker, |
| 552 |
cloud: Cloud, |
| 553 |
caplog: pytest.LogCaptureFixture, |
| 554 |
): |
| 555 |
"""Test service discovery integrates properly with Cloud lifecycle.""" |
| 556 |
aioclient_mock.get( |
| 557 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 558 |
json=BASE_EXPECTED_RESULT, |
| 559 |
) |
| 560 |
|
| 561 |
assert cloud.service_discovery is not None |
| 562 |
assert cloud.service_discovery._service_discovery_refresh_task is None |
| 563 |
|
| 564 |
await cloud.service_discovery.async_start_service_discovery() |
| 565 |
assert cloud.service_discovery._memory_cache is not None |
| 566 |
|
| 567 |
await cloud.stop() |
| 568 |
assert cloud.service_discovery._service_discovery_refresh_task is None |
| 569 |
|
| 570 |
|
| 571 |
async def test_early_action_validation( |
| 572 |
aioclient_mock: AiohttpClientMocker, |
| 573 |
cloud: Cloud, |
| 574 |
caplog: pytest.LogCaptureFixture, |
| 575 |
): |
| 576 |
"""Test that action_url validates action name early.""" |
| 577 |
with pytest.raises( |
| 578 |
ServiceDiscoveryMissingActionError, match="Unknown action: invalid_action" |
| 579 |
): |
| 580 |
cloud.service_discovery.action_url("invalid_action") # type: ignore[arg-type] |
| 581 |
|
| 582 |
|
| 583 |
async def test_forward_compatibility_extra_top_level_fields( |
| 584 |
aioclient_mock: AiohttpClientMocker, |
| 585 |
cloud: Cloud, |
| 586 |
caplog: pytest.LogCaptureFixture, |
| 587 |
snapshot: SnapshotAssertion, |
| 588 |
): |
| 589 |
"""Test that extra top-level fields in API response are ignored.""" |
| 590 |
api_response = { |
| 591 |
**BASE_EXPECTED_RESULT, |
| 592 |
"newFeature": "some_value", |
| 593 |
"anotherField": {"nested": "data"}, |
| 594 |
"experimental": True, |
| 595 |
} |
| 596 |
|
| 597 |
aioclient_mock.get( |
| 598 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 599 |
json=api_response, |
| 600 |
) |
| 601 |
|
| 602 |
result = await cloud.service_discovery._fetch_well_known_service_discovery() |
| 603 |
|
| 604 |
assert "newFeature" not in result |
| 605 |
assert "anotherField" not in result |
| 606 |
assert "experimental" not in result |
| 607 |
assert result["actions"] == BASE_EXPECTED_RESULT["actions"] |
| 608 |
assert result["valid_for"] == 3600 |
| 609 |
assert result["version"] == "1.0" |
| 610 |
assert_snapshot_with_logs(result, caplog, snapshot) |
| 611 |
|
| 612 |
|
| 613 |
async def test_forward_compatibility_extra_actions( |
| 614 |
aioclient_mock: AiohttpClientMocker, |
| 615 |
cloud: Cloud, |
| 616 |
caplog: pytest.LogCaptureFixture, |
| 617 |
snapshot: SnapshotAssertion, |
| 618 |
): |
| 619 |
"""Test that extra actions in API response are ignored.""" |
| 620 |
api_response = { |
| 621 |
**BASE_EXPECTED_RESULT, |
| 622 |
"actions": { |
| 623 |
**BASE_EXPECTED_RESULT["actions"], |
| 624 |
"future_action_1": "https://example.com/future/action1", |
| 625 |
"future_action_2": "https://example.com/future/action2", |
| 626 |
"experimental_feature": "https://example.com/experimental", |
| 627 |
}, |
| 628 |
"valid_for": 3600, |
| 629 |
"version": "1.0", |
| 630 |
} |
| 631 |
|
| 632 |
aioclient_mock.get( |
| 633 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 634 |
json=api_response, |
| 635 |
) |
| 636 |
|
| 637 |
result = await cloud.service_discovery._fetch_well_known_service_discovery() |
| 638 |
|
| 639 |
assert "future_action_1" not in result["actions"] |
| 640 |
assert "future_action_2" not in result["actions"] |
| 641 |
assert "experimental_feature" not in result["actions"] |
| 642 |
assert "test_api_action" in result["actions"] |
| 643 |
assert_snapshot_with_logs(result, caplog, snapshot) |
| 644 |
|
| 645 |
|
| 646 |
async def test_forward_compatibility_combined( |
| 647 |
aioclient_mock: AiohttpClientMocker, |
| 648 |
cloud: Cloud, |
| 649 |
caplog: pytest.LogCaptureFixture, |
| 650 |
snapshot: SnapshotAssertion, |
| 651 |
): |
| 652 |
"""Test forward compatibility with both extra top-level fields and extra actions.""" |
| 653 |
api_response = { |
| 654 |
**BASE_EXPECTED_RESULT, |
| 655 |
"actions": { |
| 656 |
**BASE_EXPECTED_RESULT["actions"], |
| 657 |
"future_action": "https://example.com/future", |
| 658 |
}, |
| 659 |
"valid_for": 3600, |
| 660 |
"version": "2.0", |
| 661 |
"newTopLevelField": "future_data", |
| 662 |
"metadata": {"extra": "info"}, |
| 663 |
} |
| 664 |
|
| 665 |
aioclient_mock.get( |
| 666 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 667 |
json=api_response, |
| 668 |
) |
| 669 |
|
| 670 |
result = await cloud.service_discovery._fetch_well_known_service_discovery() |
| 671 |
|
| 672 |
assert "newTopLevelField" not in result |
| 673 |
assert "metadata" not in result |
| 674 |
assert "future_action" not in result["actions"] |
| 675 |
assert "test_api_action" in result["actions"] |
| 676 |
assert result["valid_for"] == 3600 |
| 677 |
assert result["version"] == "2.0" |
| 678 |
|
| 679 |
assert_snapshot_with_logs(result, caplog, snapshot) |
| 680 |
|
| 681 |
|
| 682 |
async def test_network_failure_during_background_refresh( |
| 683 |
aioclient_mock: AiohttpClientMocker, |
| 684 |
cloud: Cloud, |
| 685 |
caplog: pytest.LogCaptureFixture, |
| 686 |
snapshot: SnapshotAssertion, |
| 687 |
): |
| 688 |
"""Test that network failures during background refresh are handled gracefully.""" |
| 689 |
aioclient_mock.get( |
| 690 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 691 |
json={ |
| 692 |
**BASE_EXPECTED_RESULT, |
| 693 |
"valid_for": 0, |
| 694 |
}, |
| 695 |
) |
| 696 |
|
| 697 |
await cloud.service_discovery.async_start_service_discovery() |
| 698 |
assert cloud.service_discovery._memory_cache is not None |
| 699 |
original_cache = cloud.service_discovery._memory_cache |
| 700 |
|
| 701 |
aioclient_mock.clear_requests() |
| 702 |
aioclient_mock.get( |
| 703 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 704 |
exc=ClientError("Network error during refresh"), |
| 705 |
) |
| 706 |
|
| 707 |
await asyncio.sleep(0.2) |
| 708 |
|
| 709 |
assert cloud.service_discovery._service_discovery_refresh_task is not None |
| 710 |
assert not cloud.service_discovery._service_discovery_refresh_task.done() |
| 711 |
assert cloud.service_discovery._memory_cache is original_cache |
| 712 |
|
| 713 |
await cloud.service_discovery.async_stop_service_discovery() |
| 714 |
|
| 715 |
assert_snapshot_with_logs( |
| 716 |
{"cache_preserved": (original_cache is cloud.service_discovery._memory_cache)}, |
| 717 |
caplog, |
| 718 |
snapshot, |
| 719 |
) |
| 720 |
|
| 721 |
|
| 722 |
async def test_extremely_long_running_refresh_cycle( |
| 723 |
aioclient_mock: AiohttpClientMocker, |
| 724 |
cloud: Cloud, |
| 725 |
caplog: pytest.LogCaptureFixture, |
| 726 |
snapshot: SnapshotAssertion, |
| 727 |
): |
| 728 |
"""Test that extremely long valid_for times are handled correctly.""" |
| 729 |
one_year_seconds = 365 * 24 * 60 * 60 |
| 730 |
aioclient_mock.get( |
| 731 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 732 |
json={ |
| 733 |
**BASE_EXPECTED_RESULT, |
| 734 |
"valid_for": one_year_seconds, |
| 735 |
}, |
| 736 |
) |
| 737 |
|
| 738 |
await cloud.service_discovery.async_start_service_discovery() |
| 739 |
assert cloud.service_discovery._memory_cache is not None |
| 740 |
|
| 741 |
valid_for_value = cloud.service_discovery._memory_cache["data"]["valid_for"] |
| 742 |
assert valid_for_value == one_year_seconds |
| 743 |
|
| 744 |
assert cloud.service_discovery._service_discovery_refresh_task is not None |
| 745 |
assert not cloud.service_discovery._service_discovery_refresh_task.done() |
| 746 |
|
| 747 |
url = cloud.service_discovery.action_url("test_api_action", param="test") |
| 748 |
|
| 749 |
await cloud.service_discovery.async_stop_service_discovery() |
| 750 |
|
| 751 |
assert_snapshot_with_logs( |
| 752 |
{ |
| 753 |
"url": url, |
| 754 |
"valid_for": valid_for_value, |
| 755 |
"task_running": cloud.service_discovery._service_discovery_refresh_task |
| 756 |
is None, |
| 757 |
}, |
| 758 |
caplog, |
| 759 |
snapshot, |
| 760 |
) |
| 761 |
|
| 762 |
|
| 763 |
async def test_race_condition_stop_during_fetch( |
| 764 |
aioclient_mock: AiohttpClientMocker, |
| 765 |
cloud: Cloud, |
| 766 |
caplog: pytest.LogCaptureFixture, |
| 767 |
snapshot: SnapshotAssertion, |
| 768 |
): |
| 769 |
"""Test race condition when stop is called during an ongoing fetch.""" |
| 770 |
aioclient_mock.get( |
| 771 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 772 |
json={ |
| 773 |
**BASE_EXPECTED_RESULT, |
| 774 |
"valid_for": 0, |
| 775 |
}, |
| 776 |
) |
| 777 |
|
| 778 |
await cloud.service_discovery.async_start_service_discovery() |
| 779 |
assert cloud.service_discovery._service_discovery_refresh_task is not None |
| 780 |
|
| 781 |
await asyncio.sleep(0.05) |
| 782 |
|
| 783 |
await cloud.service_discovery.async_stop_service_discovery() |
| 784 |
|
| 785 |
assert cloud.service_discovery._service_discovery_refresh_task is None |
| 786 |
|
| 787 |
assert_snapshot_with_logs( |
| 788 |
{ |
| 789 |
"task_stopped": ( |
| 790 |
cloud.service_discovery._service_discovery_refresh_task is None |
| 791 |
) |
| 792 |
}, |
| 793 |
caplog, |
| 794 |
snapshot, |
| 795 |
) |
| 796 |
|
| 797 |
|
| 798 |
async def test_race_condition_multiple_concurrent_stops( |
| 799 |
aioclient_mock: AiohttpClientMocker, |
| 800 |
cloud: Cloud, |
| 801 |
caplog: pytest.LogCaptureFixture, |
| 802 |
snapshot: SnapshotAssertion, |
| 803 |
): |
| 804 |
"""Test race condition when multiple stop calls happen concurrently.""" |
| 805 |
aioclient_mock.get( |
| 806 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 807 |
json={ |
| 808 |
**BASE_EXPECTED_RESULT, |
| 809 |
"valid_for": 1, |
| 810 |
}, |
| 811 |
) |
| 812 |
|
| 813 |
await cloud.service_discovery.async_start_service_discovery() |
| 814 |
assert cloud.service_discovery._service_discovery_refresh_task is not None |
| 815 |
|
| 816 |
await asyncio.gather( |
| 817 |
cloud.service_discovery.async_stop_service_discovery(), |
| 818 |
cloud.service_discovery.async_stop_service_discovery(), |
| 819 |
cloud.service_discovery.async_stop_service_discovery(), |
| 820 |
) |
| 821 |
|
| 822 |
assert cloud.service_discovery._service_discovery_refresh_task is None |
| 823 |
|
| 824 |
assert_snapshot_with_logs( |
| 825 |
{ |
| 826 |
"task_stopped": cloud.service_discovery._service_discovery_refresh_task |
| 827 |
is None |
| 828 |
}, |
| 829 |
caplog, |
| 830 |
snapshot, |
| 831 |
) |
| 832 |
|
| 833 |
|
| 834 |
async def test_race_condition_stop_and_start_rapid_cycling( |
| 835 |
aioclient_mock: AiohttpClientMocker, |
| 836 |
cloud: Cloud, |
| 837 |
caplog: pytest.LogCaptureFixture, |
| 838 |
snapshot: SnapshotAssertion, |
| 839 |
): |
| 840 |
"""Test rapid start/stop cycling for race conditions.""" |
| 841 |
aioclient_mock.get( |
| 842 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 843 |
json=BASE_EXPECTED_RESULT, |
| 844 |
) |
| 845 |
|
| 846 |
for _ in range(5): |
| 847 |
await cloud.service_discovery.async_start_service_discovery() |
| 848 |
await asyncio.sleep(0.01) |
| 849 |
await cloud.service_discovery.async_stop_service_discovery() |
| 850 |
|
| 851 |
assert cloud.service_discovery._service_discovery_refresh_task is None |
| 852 |
|
| 853 |
assert_snapshot_with_logs( |
| 854 |
{ |
| 855 |
"final_state_clean": cloud.service_discovery._service_discovery_refresh_task |
| 856 |
is None |
| 857 |
}, |
| 858 |
caplog, |
| 859 |
snapshot, |
| 860 |
) |
| 861 |
|
| 862 |
|
| 863 |
async def test_background_refresh_with_changing_network_conditions( |
| 864 |
aioclient_mock: AiohttpClientMocker, |
| 865 |
cloud: Cloud, |
| 866 |
caplog: pytest.LogCaptureFixture, |
| 867 |
snapshot: SnapshotAssertion, |
| 868 |
): |
| 869 |
"""Test background refresh handles alternating success and failure.""" |
| 870 |
aioclient_mock.get( |
| 871 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 872 |
json=BASE_EXPECTED_RESULT, |
| 873 |
) |
| 874 |
|
| 875 |
await cloud.service_discovery.async_start_service_discovery() |
| 876 |
first_cache = cloud.service_discovery._memory_cache |
| 877 |
assert first_cache is not None |
| 878 |
assert first_cache["data"]["version"] == "1.0" |
| 879 |
|
| 880 |
aioclient_mock.clear_requests() |
| 881 |
aioclient_mock.get( |
| 882 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 883 |
exc=ClientError("Temporary network failure"), |
| 884 |
) |
| 885 |
|
| 886 |
cloud.service_discovery._memory_cache = None |
| 887 |
with pytest.raises(ServiceDiscoveryError): |
| 888 |
await cloud.service_discovery._load_service_discovery_data() |
| 889 |
|
| 890 |
expired_cache = first_cache.copy() |
| 891 |
expired_cache["valid_until"] = 0 |
| 892 |
cloud.service_discovery._memory_cache = expired_cache |
| 893 |
|
| 894 |
aioclient_mock.clear_requests() |
| 895 |
aioclient_mock.get( |
| 896 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 897 |
json={ |
| 898 |
**BASE_EXPECTED_RESULT, |
| 899 |
"version": "2.0", |
| 900 |
}, |
| 901 |
) |
| 902 |
|
| 903 |
second_cache = await cloud.service_discovery._load_service_discovery_data() |
| 904 |
assert second_cache["data"]["version"] == "2.0" |
| 905 |
assert first_cache is not second_cache |
| 906 |
|
| 907 |
await cloud.service_discovery.async_stop_service_discovery() |
| 908 |
|
| 909 |
assert_snapshot_with_logs( |
| 910 |
{ |
| 911 |
"first_version": first_cache["data"]["version"], |
| 912 |
"second_version": second_cache["data"]["version"], |
| 913 |
"cache_updated": first_cache is not second_cache, |
| 914 |
}, |
| 915 |
caplog, |
| 916 |
snapshot, |
| 917 |
) |
| 918 |
|
| 919 |
|
| 920 |
@pytest.mark.parametrize( |
| 921 |
"valid_for_seconds,expected_min,expected_max", |
| 922 |
[ |
| 923 |
# Expired/small: jitter(60, 300) |
| 924 |
(10, MIN_REFRESH_INTERVAL, FIVE_MINUTES_IN_SECONDS), |
| 925 |
(3600, 3605, 7200), # 1 hour: remaining + jitter(5, 3600) |
| 926 |
(7200, 7205, 10800), # 2 hours: remaining + jitter(5, 3600) |
| 927 |
(259200, 259205, 262800), # 3 days: remaining + jitter(5, 3600) |
| 928 |
], |
| 929 |
) |
| 930 |
def test_sleep_time_calculation_with_jitter( |
| 931 |
valid_for_seconds: int, |
| 932 |
expected_min: int, |
| 933 |
expected_max: int, |
| 934 |
): |
| 935 |
"""Test sleep time calculation with jitter applied.""" |
| 936 |
now = utcnow().timestamp() |
| 937 |
valid_until = now + valid_for_seconds |
| 938 |
result = _calculate_sleep_time(valid_until) |
| 939 |
assert expected_min <= result <= expected_max |
| 940 |
|
| 941 |
|
| 942 |
async def test_background_refresh_with_no_cache_uses_12_hour_retry( |
| 943 |
aioclient_mock: AiohttpClientMocker, |
| 944 |
cloud: Cloud, |
| 945 |
caplog: pytest.LogCaptureFixture, |
| 946 |
snapshot: SnapshotAssertion, |
| 947 |
frozen_time: FreezeTimeFixture, |
| 948 |
): |
| 949 |
"""Test that background refresh with no cache schedules 12-hour retry.""" |
| 950 |
aioclient_mock.get( |
| 951 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 952 |
status=500, |
| 953 |
text="Internal Server Error", |
| 954 |
) |
| 955 |
|
| 956 |
await cloud.service_discovery.async_start_service_discovery() |
| 957 |
|
| 958 |
await asyncio.sleep(0.1) |
| 959 |
|
| 960 |
assert cloud.service_discovery._service_discovery_refresh_task is not None |
| 961 |
assert not cloud.service_discovery._service_discovery_refresh_task.done() |
| 962 |
assert cloud.service_discovery._memory_cache is None |
| 963 |
|
| 964 |
# With jitter, expect between ~11h58m and ~13h (12h + up to 1h jitter) |
| 965 |
pattern = r"Scheduling service discovery refresh in (11h:5[0-9]m|12h|13h:0m)" |
| 966 |
assert re.search(pattern, caplog.text) |
| 967 |
|
| 968 |
aioclient_mock.clear_requests() |
| 969 |
aioclient_mock.get( |
| 970 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 971 |
json=BASE_EXPECTED_RESULT, |
| 972 |
) |
| 973 |
|
| 974 |
# Tick past the maximum possible sleep time (12h + 1h jitter = 13h) |
| 975 |
frozen_time.tick(13 * 3600 + 1) |
| 976 |
await asyncio.sleep(0.1) |
| 977 |
|
| 978 |
assert cloud.service_discovery._memory_cache is not None |
| 979 |
assert cloud.service_discovery._memory_cache["data"]["version"] == "1.0" |
| 980 |
|
| 981 |
await cloud.service_discovery.async_stop_service_discovery() |
| 982 |
|
| 983 |
assert_snapshot_with_logs( |
| 984 |
{ |
| 985 |
"cache_populated_after_retry": True, |
| 986 |
"version": "1.0", |
| 987 |
}, |
| 988 |
caplog, |
| 989 |
snapshot, |
| 990 |
) |
| 991 |
|
| 992 |
|
| 993 |
async def test_service_discovery_fetch_without_token_check( |
| 994 |
aioclient_mock: AiohttpClientMocker, |
| 995 |
cloud: Cloud, |
| 996 |
): |
| 997 |
"""Test that service discovery fetch skips token validation.""" |
| 998 |
aioclient_mock.get( |
| 999 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 1000 |
json=BASE_EXPECTED_RESULT, |
| 1001 |
) |
| 1002 |
|
| 1003 |
cloud.auth.async_check_token = AsyncMock( |
| 1004 |
side_effect=Exception("Token check should not be called!") |
| 1005 |
) |
| 1006 |
|
| 1007 |
result = await cloud.service_discovery._fetch_well_known_service_discovery() |
| 1008 |
|
| 1009 |
assert result["version"] == "1.0" |
| 1010 |
assert not cloud.auth.async_check_token.called |
| 1011 |
|
| 1012 |
|
| 1013 |
async def test_service_discovery_update_event_published( |
| 1014 |
aioclient_mock: AiohttpClientMocker, |
| 1015 |
cloud: Cloud, |
| 1016 |
): |
| 1017 |
"""Test that service discovery update event is published when data is loaded.""" |
| 1018 |
aioclient_mock.get( |
| 1019 |
f"https://{cloud.api_server}/.well-known/service-discovery", |
| 1020 |
json=BASE_EXPECTED_RESULT, |
| 1021 |
) |
| 1022 |
|
| 1023 |
cloud.events.publish = AsyncMock() |
| 1024 |
|
| 1025 |
await cloud.service_discovery._load_service_discovery_data() |
| 1026 |
|
| 1027 |
assert cloud.events.publish.call_count == 1 |
| 1028 |
event = cloud.events.publish.call_args[1]["event"] |
| 1029 |
assert event.type == CloudEventType.SERVICE_DISCOVERY_UPDATE |
| 1030 |
|
| 1031 |
# Verify that the event is NOT published when cached data is returned |
| 1032 |
await cloud.service_discovery._load_service_discovery_data() |
| 1033 |
assert cloud.events.publish.call_count == 1 |