forked from homeassistant-ai/ha-mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_tools_utility_supervisor_logs.py
More file actions
1586 lines (1314 loc) · 64.9 KB
/
Copy pathtest_tools_utility_supervisor_logs.py
File metadata and controls
1586 lines (1314 loc) · 64.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Unit tests for `ha_get_logs(source="supervisor"|"system_service")`.
Covers two REST-client paths and their tools_utility wrappers:
- `HomeAssistantClient.get_addon_logs()` — branches on `is_running_in_addon()`:
inside the addon container hits Supervisor directly at
`http://supervisor/addons/{slug}/logs` (the HA-Core proxy rejects the
Supervisor token there — see #1116); otherwise falls back to
`/api/hassio/addons/{slug}/logs` (returned as text/plain — see #950).
- `HomeAssistantClient._get_system_service_logs()` — branches on
`is_running_in_addon()` like `get_addon_logs`: in-addon hits
`http://supervisor/{service}/logs`; non-addon falls back to the HA Core
proxy at `/api/hassio/{service}/logs` (#1260 fix on top of #1116 scope).
service ∈ {supervisor, host, core, dns, audio, cli, multicast, observer}.
- The wrappers (`_get_supervisor_log`, `_get_system_service_log`) — response
shape, tail slicing, search filter, slug-enum validation, and structured-
error translation.
"""
import asyncio
import json
import re
from pathlib import Path
from types import SimpleNamespace
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
import httpx
import pytest
from fastmcp.exceptions import ToolError
from ha_mcp.client.rest_client import (
_ERROR_LOG_LINES,
HomeAssistantAPIError,
HomeAssistantAuthError,
HomeAssistantClient,
HomeAssistantConnectionError,
)
from ha_mcp.tools.tools_utility import (
DEFAULT_LOG_LIMIT,
MAX_LIMIT,
SUPERVISOR_SEARCH_WINDOW_LINES,
register_utility_tools,
)
@pytest.fixture
def mock_client():
"""HomeAssistantClient with stubbed internals — no real network.
Mirror every instance attribute the real ``__init__`` sets, so a
`getattr` fallback in production code isn't needed to paper over a
test-fixture omission (and so future `__init__` attribute additions
that this fixture forgets to mirror fail loudly here instead of
silently no-op-ing).
"""
with patch.object(HomeAssistantClient, "__init__", lambda self, **kwargs: None):
client = HomeAssistantClient()
client.base_url = "http://test.local:8123"
client.token = "test-token"
client.timeout = 30
client.verify_ssl = True
client.httpx_client = MagicMock()
client._supervised_detected = None
return client
@pytest.fixture
def non_addon_install():
"""Force `is_running_in_addon()` False (HA-Core-proxy path)."""
with patch("ha_mcp.client.rest_client.is_running_in_addon", return_value=False):
yield
@pytest.fixture
def addon_install():
"""Force `is_running_in_addon()` True with a stubbed SUPERVISOR_TOKEN."""
with (
patch("ha_mcp.client.rest_client.is_running_in_addon", return_value=True),
patch.dict("os.environ", {"SUPERVISOR_TOKEN": "supervisor-token-test"}),
):
yield
@pytest.fixture
def addon_install_no_token():
"""`is_running_in_addon()` True but SUPERVISOR_TOKEN deliberately empty.
Models the detection/config mismatch that triggers the fail-fast path in
`_supervisor_logs_get` (gate fired but env var not actually set).
"""
with (
patch("ha_mcp.client.rest_client.is_running_in_addon", return_value=True),
patch.dict("os.environ", {"SUPERVISOR_TOKEN": ""}, clear=False),
):
yield
def _register_and_collect(client: Any) -> dict[str, Any]:
"""Register utility tools on a collector mcp and return the registered tools.
The production decorator chain is ``@mcp.tool(...)`` outside ``@log_tool_usage``,
so the collected entry is the ``log_tool_usage``-wrapped async function.
"""
collected: dict[str, Any] = {}
def _tool(**_kwargs: Any) -> Any:
def _wrap(fn: Any) -> Any:
collected[fn.__name__] = fn
return fn
return _wrap
mcp = SimpleNamespace(tool=_tool)
register_utility_tools(mcp, client)
return collected
def _parse_tool_error(exc_info: pytest.ExceptionInfo[ToolError]) -> dict[str, Any]:
"""Parse the JSON payload from a ToolError raised by a tool."""
payload: dict[str, Any] = json.loads(str(exc_info.value))
return payload
class TestGetAddonLogs:
"""Tests for the REST-client `get_addon_logs` method on non-addon installs.
These exercise the HA-Core-proxy fallback branch (`/hassio/addons/{slug}/logs`)
via `httpx_client.request`. The `non_addon_install` fixture forces
`is_running_in_addon()` False so `get_addon_logs` doesn't take the
Supervisor-direct branch — that path opens a fresh `httpx.AsyncClient`
and would bypass the `mock_client.httpx_client` mock entirely.
"""
@pytest.fixture(autouse=True)
def _force_non_addon(self, non_addon_install):
"""Apply `non_addon_install` to every test in this class."""
yield
@pytest.mark.asyncio
async def test_returns_text_on_200(self, mock_client):
"""Successful 200 response returns the raw text body."""
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.text = "2026-04-11 10:00:00 addon starting\nready\n"
mock_client.httpx_client.request = AsyncMock(return_value=mock_response)
result = await mock_client.get_addon_logs("core_mosquitto")
assert "addon starting" in result
assert "ready" in result
@pytest.mark.asyncio
async def test_calls_correct_endpoint_with_text_accept(self, mock_client):
"""Endpoint path and Accept: text/plain header must match the HA proxy contract."""
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.text = ""
mock_client.httpx_client.request = AsyncMock(return_value=mock_response)
await mock_client.get_addon_logs("81f33d0f_ha_mcp_dev")
mock_client.httpx_client.request.assert_called_once()
args, kwargs = mock_client.httpx_client.request.call_args
assert args[0] == "GET"
assert args[1] == "/hassio/addons/81f33d0f_ha_mcp_dev/logs"
assert kwargs["headers"]["Accept"] == "text/plain"
@pytest.mark.asyncio
async def test_raises_auth_error_on_401(self, mock_client):
mock_response = MagicMock()
mock_response.status_code = 401
mock_response.text = "unauthorized"
mock_client.httpx_client.request = AsyncMock(return_value=mock_response)
with pytest.raises(HomeAssistantAuthError):
await mock_client.get_addon_logs("core_mosquitto")
@pytest.mark.asyncio
async def test_raises_api_error_on_404_with_slug_context(self, mock_client):
"""404 (unknown slug) raises HomeAssistantAPIError with status 404 and body.
The Supervisor-proxied endpoint returns `text/plain` error bodies, not
JSON, so `response.json()` raises and the error message falls back to
`response.text`. Mirror that here.
"""
mock_response = MagicMock()
mock_response.status_code = 404
mock_response.text = "Addon is not installed"
mock_response.json = MagicMock(side_effect=ValueError("not json"))
mock_client.httpx_client.request = AsyncMock(return_value=mock_response)
with pytest.raises(HomeAssistantAPIError) as exc_info:
await mock_client.get_addon_logs("nonexistent_slug")
assert exc_info.value.status_code == 404
assert "Addon is not installed" in str(exc_info.value)
@pytest.mark.asyncio
async def test_raises_connection_error_on_network_failure(self, mock_client):
mock_client.httpx_client.request = AsyncMock(
side_effect=httpx.ConnectError("no route")
)
with pytest.raises(HomeAssistantConnectionError):
await mock_client.get_addon_logs("core_mosquitto")
@pytest.mark.asyncio
async def test_raises_connection_error_on_timeout(self, mock_client):
mock_client.httpx_client.request = AsyncMock(
side_effect=httpx.TimeoutException("timeout")
)
with pytest.raises(HomeAssistantConnectionError):
await mock_client.get_addon_logs("core_mosquitto")
@pytest.mark.asyncio
async def test_does_not_parse_json(self, mock_client):
"""Regression guard for #950: the fetch must not try to JSON-decode the
text/plain log body (that's what broke the old websocket path)."""
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.text = "plain log line 1\nplain log line 2\n"
# Make .json() raise so any stray call would fail the test.
mock_response.json = MagicMock(
side_effect=ValueError("json parse should not be called")
)
mock_client.httpx_client.request = AsyncMock(return_value=mock_response)
result = await mock_client.get_addon_logs("core_mosquitto")
assert "plain log line 1" in result
mock_response.json.assert_not_called()
class TestGetAddonLogsViaSupervisor:
"""Supervisor-direct branch of `get_addon_logs`."""
@pytest.fixture
def mock_async_client_class(self):
inner_client = MagicMock()
inner_client.get = AsyncMock()
cm = MagicMock()
cm.__aenter__ = AsyncMock(return_value=inner_client)
cm.__aexit__ = AsyncMock(return_value=None)
client_class = MagicMock(return_value=cm)
# Patching `httpx.AsyncClient` directly (not through the `rest_client`
# module attribute) is robust to either `import httpx` or a future
# `from httpx import AsyncClient` form.
with patch("httpx.AsyncClient", client_class):
yield inner_client, client_class
@pytest.mark.asyncio
async def test_uses_direct_supervisor_url_and_supervisor_token(
self, mock_client, addon_install, mock_async_client_class
):
inner_client, client_class = mock_async_client_class
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.text = "addon log line 1\nready\n"
inner_client.get.return_value = mock_response
result = await mock_client.get_addon_logs("81f33d0f_ha_mcp")
assert "addon log line 1" in result
inner_client.get.assert_awaited_once()
args, kwargs = inner_client.get.call_args
# Wire shape: relative path on the call, with per-call ``Accept``
# layered over the ctor-set ``Authorization`` — no per-call
# Authorization kwarg, which would displace the ctor header.
assert args[0] == "/addons/81f33d0f_ha_mcp/logs"
assert kwargs["headers"]["Accept"] == "text/plain"
assert "Authorization" not in kwargs.get("headers", {})
# Constructor kwargs propagated — guards against a regression that
# hard-codes verify, timeout, base_url, or the Bearer token.
ctor_kwargs = client_class.call_args.kwargs
assert ctor_kwargs["verify"] is True # mirrors mock_client.verify_ssl
assert isinstance(ctor_kwargs["timeout"], httpx.Timeout)
assert ctor_kwargs["base_url"] == "http://supervisor"
assert ctor_kwargs["headers"]["Authorization"] == "Bearer supervisor-token-test"
# The HA-Core-proxy path must NOT have been touched.
mock_client.httpx_client.request.assert_not_called()
@pytest.mark.asyncio
async def test_raises_auth_error_on_401(
self, mock_client, addon_install, mock_async_client_class
):
inner_client, _ = mock_async_client_class
mock_response = MagicMock()
mock_response.status_code = 401
mock_response.text = "unauthorized"
inner_client.get.return_value = mock_response
with pytest.raises(HomeAssistantAuthError):
await mock_client.get_addon_logs("core_mosquitto")
@pytest.mark.asyncio
async def test_raises_auth_error_on_empty_supervisor_token(
self, mock_client, addon_install_no_token, mock_async_client_class
):
"""Gate fires but SUPERVISOR_TOKEN is empty → fail-fast with a distinct
message so it doesn't read as "token rejected" (#1126 review item 1)."""
inner_client, _ = mock_async_client_class
with pytest.raises(HomeAssistantAuthError) as exc_info:
await mock_client.get_addon_logs("core_mosquitto")
assert "absent at call time" in str(exc_info.value)
assert "SUPERVISOR_TOKEN" in str(exc_info.value)
# No HTTP request must have been issued — fail-fast happens before.
inner_client.get.assert_not_called()
@pytest.mark.asyncio
async def test_raises_api_error_on_403_with_permission_hints(
self, mock_client, addon_install, mock_async_client_class, caplog
):
"""A 403 names every Supervisor app authorization boundary.
Supervisor uses it for an unrecognized token, missing API permission,
and an insufficient role (#1126 review items 2 + 9).
"""
inner_client, _ = mock_async_client_class
mock_response = MagicMock()
mock_response.status_code = 403
mock_response.text = ""
mock_response.reason_phrase = "Forbidden"
inner_client.get.return_value = mock_response
import logging
with (
caplog.at_level(logging.WARNING, logger="ha_mcp.client.rest_client"),
pytest.raises(HomeAssistantAPIError) as exc_info,
):
await mock_client.get_addon_logs("core_mosquitto")
assert exc_info.value.status_code == 403
msg = str(exc_info.value)
assert "unrecognized" in msg
assert "hassio_api" in msg
assert "hassio_role" in msg and "manager" in msg
# Warning log fired before the raise (#1126 review item 9).
assert any("403" in r.message for r in caplog.records)
@pytest.mark.asyncio
async def test_raises_api_error_on_404(
self, mock_client, addon_install, mock_async_client_class
):
inner_client, _ = mock_async_client_class
mock_response = MagicMock()
mock_response.status_code = 404
mock_response.text = "Addon is not installed"
mock_response.reason_phrase = "Not Found"
inner_client.get.return_value = mock_response
with pytest.raises(HomeAssistantAPIError) as exc_info:
await mock_client.get_addon_logs("nonexistent_slug")
assert exc_info.value.status_code == 404
assert "Addon is not installed" in str(exc_info.value)
@pytest.mark.asyncio
async def test_parses_supervisor_json_envelope(
self, mock_client, addon_install, mock_async_client_class
):
"""Supervisor's `{"result":"error","message":"..."}` envelope is parsed
first — user-facing message gets the human prose, not the JSON blob
(#1126 review item 6)."""
inner_client, _ = mock_async_client_class
mock_response = MagicMock()
mock_response.status_code = 400
mock_response.text = '{"result":"error","message":"Add-on is not running"}'
mock_response.reason_phrase = "Bad Request"
inner_client.get.return_value = mock_response
with pytest.raises(HomeAssistantAPIError) as exc_info:
await mock_client.get_addon_logs("core_mosquitto")
assert exc_info.value.status_code == 400
msg = str(exc_info.value)
assert "Add-on is not running" in msg
# The full JSON blob must NOT be in the user-facing message.
assert '{"result"' not in msg
@pytest.mark.asyncio
async def test_empty_body_falls_back_to_reason_phrase(
self, mock_client, addon_install, mock_async_client_class
):
inner_client, _ = mock_async_client_class
mock_response = MagicMock()
mock_response.status_code = 502
mock_response.text = ""
mock_response.reason_phrase = "Bad Gateway"
inner_client.get.return_value = mock_response
with pytest.raises(HomeAssistantAPIError) as exc_info:
await mock_client.get_addon_logs("core_mosquitto")
assert exc_info.value.status_code == 502
assert "Bad Gateway" in str(exc_info.value)
assert not str(exc_info.value).endswith(" - ")
@pytest.mark.asyncio
async def test_empty_body_no_reason_phrase_uses_placeholder(
self, mock_client, addon_install, mock_async_client_class
):
"""Tier-3 fallback parity for the supervisor branch: empty body AND
empty reason_phrase → `<empty body>` placeholder (#1126 review item 12).
`TestRawRequestEmptyBodyFallback` covers this for the proxy branch."""
inner_client, _ = mock_async_client_class
mock_response = MagicMock()
mock_response.status_code = 503
mock_response.text = ""
mock_response.reason_phrase = ""
inner_client.get.return_value = mock_response
with pytest.raises(HomeAssistantAPIError) as exc_info:
await mock_client.get_addon_logs("core_mosquitto")
assert exc_info.value.status_code == 503
assert "<empty body>" in str(exc_info.value)
@pytest.mark.asyncio
async def test_raises_connection_error_on_timeout_with_distinct_message(
self, mock_client, addon_install, mock_async_client_class
):
"""Timeout vs transport error get distinct messages so callers (and
log-watchers) can tell them apart (#1126 review item 7)."""
inner_client, _ = mock_async_client_class
inner_client.get.side_effect = httpx.TimeoutException("supervisor timeout")
with pytest.raises(HomeAssistantConnectionError) as exc_info:
await mock_client.get_addon_logs("core_mosquitto")
assert "Timeout" in str(exc_info.value)
@pytest.mark.asyncio
@pytest.mark.timeout(10)
async def test_supervisor_log_fetch_has_overall_deadline(
self, mock_client, addon_install, mock_async_client_class
):
"""A stalled Supervisor log body must not wait forever on per-chunk IO."""
inner_client, _ = mock_async_client_class
mock_client.timeout = 0.01
async def _hang_forever(*_args, **_kwargs):
"""Model a Supervisor response that never completes."""
await asyncio.Event().wait()
inner_client.get.side_effect = _hang_forever
with pytest.raises(HomeAssistantConnectionError) as exc_info:
await mock_client.get_addon_logs("core_mosquitto")
assert "after 0.01s: TimeoutError" in str(exc_info.value)
@pytest.mark.asyncio
async def test_raises_connection_error_on_network_failure_with_distinct_message(
self, mock_client, addon_install, mock_async_client_class
):
inner_client, _ = mock_async_client_class
inner_client.get.side_effect = httpx.ConnectError("supervisor unreachable")
with pytest.raises(HomeAssistantConnectionError) as exc_info:
await mock_client.get_addon_logs("core_mosquitto")
assert "Transport" in str(exc_info.value)
@pytest.mark.asyncio
async def test_raises_connection_error_on_remote_protocol_error(
self, mock_client, addon_install, mock_async_client_class
):
"""A non-Connect/non-Timeout subclass of `httpx.HTTPError` (e.g.
RemoteProtocolError on partial responses) hits the broad-except clause
— pinned so a future refactor can't silently narrow it (#1126 review
item 11)."""
inner_client, _ = mock_async_client_class
inner_client.get.side_effect = httpx.RemoteProtocolError(
"server closed connection without response"
)
with pytest.raises(HomeAssistantConnectionError) as exc_info:
await mock_client.get_addon_logs("core_mosquitto")
assert "Transport" in str(exc_info.value)
class TestGetAddonLogsBranchSelection:
"""The branch decision is made via `is_running_in_addon()`. Pin both
directions so a future refactor of the gate (e.g. inlining the
``SUPERVISOR_TOKEN`` env-var check) doesn't silently regress one branch.
"""
@pytest.mark.asyncio
async def test_non_addon_install_uses_ha_core_proxy(self, mock_client):
"""`is_running_in_addon()` False → HA-Core-proxy path, no Supervisor URL."""
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.text = "via proxy\n"
mock_client.httpx_client.request = AsyncMock(return_value=mock_response)
with patch("ha_mcp.client.rest_client.is_running_in_addon", return_value=False):
result = await mock_client.get_addon_logs("core_mosquitto")
assert "via proxy" in result
mock_client.httpx_client.request.assert_called_once()
args, _ = mock_client.httpx_client.request.call_args
assert args[1] == "/hassio/addons/core_mosquitto/logs"
@pytest.mark.asyncio
async def test_addon_install_does_not_call_ha_core_proxy(self, mock_client):
"""`is_running_in_addon()` True → HA-Core-proxy path must be skipped.
Shrunk per #1126 review item 14: the URL/auth contract for the
Supervisor-direct branch lives in `TestGetAddonLogsViaSupervisor`;
this test only verifies the gate consultation. Asserting URL/auth
here too would mock-the-mock without re-asserting anything.
"""
inner_client = MagicMock()
inner_client.get = AsyncMock()
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.text = ""
inner_client.get.return_value = mock_response
cm = MagicMock()
cm.__aenter__ = AsyncMock(return_value=inner_client)
cm.__aexit__ = AsyncMock(return_value=None)
with (
patch(
"ha_mcp.client.rest_client.is_running_in_addon",
return_value=True,
),
patch.dict("os.environ", {"SUPERVISOR_TOKEN": "supervisor-token-branch"}),
patch("httpx.AsyncClient", return_value=cm),
):
await mock_client.get_addon_logs("core_mosquitto")
# Sole assertion: HA-Core-proxy path NOT taken. URL/auth contract is
# pinned by TestGetAddonLogsViaSupervisor.
mock_client.httpx_client.request.assert_not_called()
class TestGetErrorLogBranchSelection:
"""`get_error_log()` has a three-way branch on
`is_running_in_addon()` + `_is_supervised_install()`:
- Addon → Supervisor REST direct (#1116-era fix).
- External + Supervised/HAOS → HA Core ``/api/hassio/core/logs``
proxy with user LLA (#1349 item 4 fix). ``/api/error_log`` is
unregistered on Supervised installs because HA Core's
``bootstrap.py`` sets ``err_log_path = None`` when ``SUPERVISOR``
env is present (no ``hass.data[DATA_LOGGING]`` → no
``APIErrorLog`` view registration).
- External + Container/pip → historical ``/api/error_log`` path.
"""
@pytest.mark.asyncio
async def test_non_addon_non_supervised_uses_ha_core_error_log_proxy(
self, mock_client
):
"""External Container-HA client → probe /config, fall through to /error_log.
The probe of /api/config is the supervised-detection hop added
with the #1349 item 4 fix; on Container HA it returns a config
without ``hassio`` in components, so we fall through to the
historical /error_log branch. That branch uses ``_raw_request``
(text/plain), not ``_request`` (JSON) — earlier code lost log
content to a silent JSONDecodeError.
"""
mock_response = MagicMock()
mock_response.text = "error log via proxy\n"
mock_client._request = AsyncMock(return_value={"components": ["sun", "demo"]})
mock_client._raw_request = AsyncMock(return_value=mock_response)
with patch("ha_mcp.client.rest_client.is_running_in_addon", return_value=False):
result = await mock_client.get_error_log()
assert "error log via proxy" in result
# Probe via _request, fetch via _raw_request.
mock_client._request.assert_awaited_once_with("GET", "/config")
mock_client._raw_request.assert_awaited_once_with(
"GET", "/error_log", headers={"Accept": "text/plain"}
)
@pytest.mark.asyncio
async def test_non_addon_supervised_uses_hassio_core_logs_proxy(self, mock_client):
"""External HAOS/Supervised client → /api/hassio/core/logs proxy.
``/api/error_log`` returns 404 by-design on HAOS, so the supervised
branch routes through HA Core's hassio proxy with the user LLA.
Verified end-to-end against a real HAOS during PR #1349 (item 4).
"""
mock_response = MagicMock()
mock_response.text = "hassio-proxied log content\n"
mock_client._request = AsyncMock(
return_value={"components": ["sun", "hassio", "demo"]}
)
mock_client._raw_request = AsyncMock(return_value=mock_response)
with patch("ha_mcp.client.rest_client.is_running_in_addon", return_value=False):
result = await mock_client.get_error_log()
assert "hassio-proxied log content" in result
# Probe call.
mock_client._request.assert_awaited_once_with("GET", "/config")
# Fetch via _raw_request (text/plain payload, not JSON).
mock_client._raw_request.assert_awaited_once_with(
"GET",
f"/hassio/core/logs?lines={_ERROR_LOG_LINES}",
headers={"Accept": "text/plain"},
)
@pytest.mark.asyncio
async def test_addon_install_routes_to_supervisor_core(self, mock_client):
"""`is_running_in_addon()` True → ``_supervisor_logs_get("core")``.
The HA-Core-proxy ``/error_log`` path must NOT be called: HA Core
doesn't register ``APIErrorLog`` when running under Supervisor.
"""
mock_client._request = AsyncMock()
mock_client._supervisor_logs_get = AsyncMock(
return_value="error log via supervisor\n"
)
with patch("ha_mcp.client.rest_client.is_running_in_addon", return_value=True):
result = await mock_client.get_error_log()
assert "error log via supervisor" in result
# An explicit window is required: without `lines`, Supervisor applies
# its 100-line default, far too short a slice to tell what keeps
# repeating.
mock_client._supervisor_logs_get.assert_called_once_with(
"core", lines=_ERROR_LOG_LINES
)
mock_client._request.assert_not_called()
@pytest.mark.asyncio
async def test_addon_and_supervised_branches_request_the_same_window(
self, mock_client
):
"""Both Supervisor-backed branches must read the same amount of log.
Asserted on the requests the two branches actually issue — a source
check would also pass on a match inside a comment.
"""
mock_client._supervisor_logs_get = AsyncMock(return_value="x")
with patch("ha_mcp.client.rest_client.is_running_in_addon", return_value=True):
await mock_client.get_error_log()
addon_lines = mock_client._supervisor_logs_get.call_args.kwargs["lines"]
mock_response = MagicMock()
mock_response.text = "x"
mock_client._request = AsyncMock(return_value={"components": ["hassio"]})
mock_client._raw_request = AsyncMock(return_value=mock_response)
with patch("ha_mcp.client.rest_client.is_running_in_addon", return_value=False):
await mock_client.get_error_log()
supervised_url = mock_client._raw_request.call_args.args[1]
assert addon_lines == _ERROR_LOG_LINES
assert supervised_url.endswith(f"lines={addon_lines}")
class TestGetSystemServiceLogs:
"""REST-client `_get_system_service_logs` — system-service variant of the
Supervisor-direct path covering ``/{service}/logs``."""
@pytest.fixture
def mock_async_client_class(self):
inner_client = MagicMock()
inner_client.get = AsyncMock()
cm = MagicMock()
cm.__aenter__ = AsyncMock(return_value=inner_client)
cm.__aexit__ = AsyncMock(return_value=None)
client_class = MagicMock(return_value=cm)
with patch("httpx.AsyncClient", client_class):
yield inner_client, client_class
@pytest.mark.asyncio
async def test_uses_service_url_with_supervisor_token(
self, mock_client, addon_install, mock_async_client_class
):
inner_client, client_class = mock_async_client_class
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.text = "supervisor service log line\n"
inner_client.get.return_value = mock_response
result = await mock_client._get_system_service_logs("supervisor")
assert "supervisor service log line" in result
args, kwargs = inner_client.get.call_args
# Wire shape: relative path on the call, with ``Authorization``
# assembled on the constructor (mirrors the addon-logs branch).
assert args[0] == "/supervisor/logs"
assert "Authorization" not in kwargs.get("headers", {})
# Constructor kwargs propagated (parity with addon-logs branch).
ctor_kwargs = client_class.call_args.kwargs
assert ctor_kwargs["verify"] is True
assert isinstance(ctor_kwargs["timeout"], httpx.Timeout)
assert ctor_kwargs["base_url"] == "http://supervisor"
assert ctor_kwargs["headers"]["Authorization"] == "Bearer supervisor-token-test"
@pytest.mark.asyncio
async def test_raises_auth_error_on_empty_supervisor_token(
self, mock_client, addon_install_no_token, mock_async_client_class
):
"""Same fail-fast as the addon-logs branch — shared helper means
coverage extends to system_service automatically."""
inner_client, _ = mock_async_client_class
with pytest.raises(HomeAssistantAuthError) as exc_info:
await mock_client._get_system_service_logs("host")
assert "absent at call time" in str(exc_info.value)
inner_client.get.assert_not_called()
@pytest.mark.asyncio
async def test_raises_api_error_on_403_with_role_hint(
self, mock_client, addon_install, mock_async_client_class
):
inner_client, _ = mock_async_client_class
mock_response = MagicMock()
mock_response.status_code = 403
mock_response.text = ""
mock_response.reason_phrase = "Forbidden"
inner_client.get.return_value = mock_response
with pytest.raises(HomeAssistantAPIError) as exc_info:
await mock_client._get_system_service_logs("core")
assert exc_info.value.status_code == 403
assert "hassio_role" in str(exc_info.value)
@pytest.mark.asyncio
async def test_raises_api_error_on_404(
self, mock_client, addon_install, mock_async_client_class
):
"""Supervisor returns 404 for unknown service paths — caller-layer
validation already rejects unknown service names, so this is the
fail-safe for upstream Supervisor changes."""
inner_client, _ = mock_async_client_class
mock_response = MagicMock()
mock_response.status_code = 404
mock_response.text = "service unknown"
mock_response.reason_phrase = "Not Found"
inner_client.get.return_value = mock_response
with pytest.raises(HomeAssistantAPIError) as exc_info:
await mock_client._get_system_service_logs("nonexistent")
assert exc_info.value.status_code == 404
class TestGetSystemServiceLogsBranchSelection:
"""`_get_system_service_logs()` mirrors `get_addon_logs()`'s
`is_running_in_addon()` branch. Pre-#1260 this method had only the
Supervisor-direct branch, so non-addon installs (Docker image, uvx
``ha-mcp``, etc.) fell straight through to the ``SUPERVISOR_TOKEN``
fail-fast in ``_supervisor_logs_get`` for every service slug. Pin both
directions so a future refactor of the gate doesn't silently regress
either, plus a non-addon-branch error-path smoke test so the proxy
delegation doesn't accidentally swallow ``_raw_request``'s exception
envelope.
"""
@pytest.mark.parametrize(
"service",
["supervisor", "host", "core", "dns", "audio", "cli", "multicast", "observer"],
)
@pytest.mark.asyncio
async def test_non_addon_install_uses_ha_core_proxy(self, mock_client, service):
"""`is_running_in_addon()` False → HA-Core-proxy path for every slug.
HA Core's hassio HTTP proxy (PATHS_ADMIN in
`homeassistant/components/hassio/http.py`) whitelists all seven
Supervisor service-log paths, so an admin LLA can reach any of them
from outside the addon. Parametrize over the full set so a future
proxy regression for a single slug surfaces here.
Also pins ``Accept: text/plain`` on the request: without it the HA
Core proxy negotiates ``application/json`` and the body stops being
raw log text — same silent-failure signature #950 describes one
layer up.
"""
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.text = f"{service} via proxy\n"
mock_client.httpx_client.request = AsyncMock(return_value=mock_response)
with patch("ha_mcp.client.rest_client.is_running_in_addon", return_value=False):
result = await mock_client._get_system_service_logs(service)
assert f"{service} via proxy" in result
mock_client.httpx_client.request.assert_called_once()
args, kwargs = mock_client.httpx_client.request.call_args
assert args[1] == f"/hassio/{service}/logs"
assert kwargs["headers"]["Accept"] == "text/plain"
@pytest.mark.asyncio
async def test_non_addon_install_404_raises_api_error_with_service_context(
self, mock_client
):
"""Proxy returns 404 → ``HomeAssistantAPIError(status_code=404)``.
Anchors the live "observer returned 404 on hubs that don't run it"
case from the #1260 end-to-end verification. ``_raw_request`` is
what raises (one layer down), but this test guards against a future
refactor wrapping the proxy call in a swallow-and-return-empty
try/except in ``_get_system_service_logs`` itself — which would
break the bug-report flow that depends on these exceptions.
Parallels ``TestGetAddonLogs.test_raises_api_error_on_404_with_slug_context``.
"""
mock_response = MagicMock()
mock_response.status_code = 404
mock_response.text = "service not available"
mock_response.json = MagicMock(side_effect=ValueError("not json"))
mock_client.httpx_client.request = AsyncMock(return_value=mock_response)
with (
patch("ha_mcp.client.rest_client.is_running_in_addon", return_value=False),
pytest.raises(HomeAssistantAPIError) as exc_info,
):
await mock_client._get_system_service_logs("observer")
assert exc_info.value.status_code == 404
assert "service not available" in str(exc_info.value)
@pytest.mark.asyncio
async def test_addon_install_does_not_call_ha_core_proxy(self, mock_client):
"""`is_running_in_addon()` True → HA-Core-proxy path must be skipped.
URL/auth contract for the Supervisor-direct branch is pinned by
`TestGetSystemServiceLogs`; this test only verifies the gate
consultation.
"""
inner_client = MagicMock()
inner_client.get = AsyncMock()
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.text = ""
inner_client.get.return_value = mock_response
cm = MagicMock()
cm.__aenter__ = AsyncMock(return_value=inner_client)
cm.__aexit__ = AsyncMock(return_value=None)
with (
patch(
"ha_mcp.client.rest_client.is_running_in_addon",
return_value=True,
),
patch.dict("os.environ", {"SUPERVISOR_TOKEN": "supervisor-token-branch"}),
patch("httpx.AsyncClient", return_value=cm),
):
await mock_client._get_system_service_logs("supervisor")
mock_client.httpx_client.request.assert_not_called()
class TestRawRequestEmptyBodyFallback:
"""Error message must stay actionable even when the 4xx body is empty.
If `_raw_request` just used `error_data.get("message", "Unknown error")`
when the proxy returned a blank body, the raised error read
`"API error: 4xx - "` — same silent-failure signature #950 describes,
one layer down.
"""
@pytest.mark.asyncio
async def test_empty_body_falls_back_to_reason_phrase(self, mock_client):
mock_response = MagicMock()
mock_response.status_code = 502
mock_response.reason_phrase = "Bad Gateway"
mock_response.text = ""
mock_response.json = MagicMock(side_effect=ValueError("empty"))
mock_client.httpx_client.request = AsyncMock(return_value=mock_response)
with pytest.raises(HomeAssistantAPIError) as exc_info:
await mock_client._raw_request("GET", "/anything")
# Message must not be the bare "API error: 502 - " with an empty tail.
assert "Bad Gateway" in str(exc_info.value)
assert not str(exc_info.value).endswith(" - ")
@pytest.mark.asyncio
async def test_whitespace_only_body_falls_back(self, mock_client):
"""A whitespace-only JSON body like `{"message": " "}` still yields an
actionable tail, not `"API error: 4xx - "`."""
mock_response = MagicMock()
mock_response.status_code = 500
mock_response.reason_phrase = "Internal Server Error"
mock_response.text = '{"message": " "}'
mock_response.json = MagicMock(return_value={"message": " "})
mock_client.httpx_client.request = AsyncMock(return_value=mock_response)
with pytest.raises(HomeAssistantAPIError) as exc_info:
await mock_client._raw_request("GET", "/anything")
assert "Internal Server Error" in str(exc_info.value)
@pytest.mark.asyncio
async def test_empty_body_and_no_reason_phrase_uses_placeholder(self, mock_client):
mock_response = MagicMock()
mock_response.status_code = 500
mock_response.reason_phrase = ""
mock_response.text = ""
mock_response.json = MagicMock(side_effect=ValueError("empty"))
mock_client.httpx_client.request = AsyncMock(return_value=mock_response)
with pytest.raises(HomeAssistantAPIError) as exc_info:
await mock_client._raw_request("GET", "/anything")
assert "<empty body>" in str(exc_info.value)
class TestGetSupervisorLogWrapper:
"""Tests for the `_get_supervisor_log` wrapper exercised via `ha_get_logs`.
Locks down the response shape, the `[-limit:]` tail slicing, the `search`
filter, and the `HomeAssistantAPIError → exception_to_structured_error`
translation the REST-client tests don't cover.
"""
@pytest.fixture
def client_with_logs(self):
"""Client whose `get_addon_logs` is a configurable AsyncMock."""
client = MagicMock()
client.get_addon_logs = AsyncMock()
return client
@pytest.mark.asyncio
async def test_happy_path_response_shape(self, client_with_logs):
client_with_logs.get_addon_logs.return_value = "line 1\nline 2\nline 3\n"
tools = _register_and_collect(client_with_logs)
result = await tools["ha_get_logs"](source="supervisor", slug="core_mosquitto")
assert result["success"] is True
assert result["source"] == "supervisor"
assert result["slug"] == "core_mosquitto"
assert result["log"] == "line 3\nline 2\nline 1" # newest-first default
assert result["total_lines"] == 3
assert result["returned_lines"] == 3
assert "limit" in result
# No filters applied → key is omitted
assert "filters_applied" not in result
client_with_logs.get_addon_logs.assert_awaited_once_with(
"core_mosquitto", lines=DEFAULT_LOG_LIMIT
)
@pytest.mark.asyncio
async def test_tail_slicing_returns_last_n_lines(self, client_with_logs):
"""`lines[-effective_limit:]` — users want recent activity, not the head."""
client_with_logs.get_addon_logs.return_value = (
"\n".join(f"line {i}" for i in range(1, 21)) + "\n"
)
tools = _register_and_collect(client_with_logs)
result = await tools["ha_get_logs"](
source="supervisor", slug="core_mosquitto", limit=5
)
returned = result["log"].splitlines()
# Still the last 5 lines (recent window), now newest-first by default.
assert returned == ["line 20", "line 19", "line 18", "line 17", "line 16"]
assert result["total_lines"] == 20
assert result["returned_lines"] == 5
assert result["limit"] == 5
@pytest.mark.asyncio
async def test_search_filter_is_case_insensitive_and_recorded(
self, client_with_logs
):
client_with_logs.get_addon_logs.return_value = (
"INFO startup complete\n"
"ERROR something broke\n"
"DEBUG trivial\n"
"ERROR another failure\n"
)
tools = _register_and_collect(client_with_logs)
result = await tools["ha_get_logs"](
source="supervisor", slug="core_mosquitto", search="error"
)
lines = result["log"].splitlines()
assert len(lines) == 2
assert all("ERROR" in ln for ln in lines)
assert result["total_lines"] == 2 # total after filter
assert result["filters_applied"] == {"search": "error"}
@pytest.mark.asyncio
async def test_404_raises_tool_error_with_not_found_suggestion(
self, client_with_logs