forked from home-assistant/core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconftest.py
1937 lines (1577 loc) · 61.6 KB
/
conftest.py
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
"""Set up some common test helper things."""
from __future__ import annotations
import asyncio
from collections.abc import AsyncGenerator, Callable, Coroutine, Generator
from contextlib import AsyncExitStack, asynccontextmanager, contextmanager
import datetime
import functools
import gc
import itertools
import logging
import os
import reprlib
from shutil import rmtree
import sqlite3
import ssl
import threading
from typing import TYPE_CHECKING, Any, cast
from unittest.mock import AsyncMock, MagicMock, Mock, _patch, patch
from aiohttp import client
from aiohttp.test_utils import (
BaseTestServer,
TestClient,
TestServer,
make_mocked_request,
)
from aiohttp.typedefs import JSONDecoder
from aiohttp.web import Application
import bcrypt
import freezegun
import multidict
import pytest
import pytest_socket
import requests_mock
import respx
from syrupy.assertion import SnapshotAssertion
from syrupy.session import SnapshotSession
from homeassistant import block_async_io
from homeassistant.exceptions import ServiceNotFound
# Setup patching of recorder functions before any other Home Assistant imports
from . import patch_recorder # noqa: F401, isort:skip
# Setup patching of dt_util time functions before any other Home Assistant imports
from . import patch_time # noqa: F401, isort:skip
from homeassistant import core as ha, loader, runner
from homeassistant.auth.const import GROUP_ID_ADMIN, GROUP_ID_READ_ONLY
from homeassistant.auth.models import Credentials
from homeassistant.auth.providers import homeassistant
from homeassistant.components.device_tracker.legacy import Device
# pylint: disable-next=hass-component-root-import
from homeassistant.components.websocket_api.auth import (
TYPE_AUTH,
TYPE_AUTH_OK,
TYPE_AUTH_REQUIRED,
)
# pylint: disable-next=hass-component-root-import
from homeassistant.components.websocket_api.http import URL
from homeassistant.config import YAML_CONFIG_FILE
from homeassistant.config_entries import ConfigEntries, ConfigEntry, ConfigEntryState
from homeassistant.const import BASE_PLATFORMS, HASSIO_USER_NAME
from homeassistant.core import (
Context,
CoreState,
HassJob,
HomeAssistant,
ServiceCall,
ServiceResponse,
)
from homeassistant.helpers import (
area_registry as ar,
category_registry as cr,
config_entry_oauth2_flow,
device_registry as dr,
entity_registry as er,
floor_registry as fr,
issue_registry as ir,
label_registry as lr,
recorder as recorder_helper,
)
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.translation import _TranslationsCacheData
from homeassistant.helpers.typing import ConfigType
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util, location
from homeassistant.util.async_ import create_eager_task, get_scheduled_timer_handles
from homeassistant.util.json import json_loads
from .ignore_uncaught_exceptions import IGNORE_UNCAUGHT_EXCEPTIONS
from .syrupy import HomeAssistantSnapshotExtension, override_syrupy_finish
from .typing import (
ClientSessionGenerator,
MockHAClientWebSocket,
MqttMockHAClient,
MqttMockHAClientGenerator,
MqttMockPahoClient,
RecorderInstanceGenerator,
WebSocketGenerator,
)
if TYPE_CHECKING:
# Local import to avoid processing recorder and SQLite modules when running a
# testcase which does not use the recorder.
from homeassistant.components import recorder
pytest.register_assert_rewrite("tests.common")
from .common import ( # noqa: E402, isort:skip
CLIENT_ID,
INSTANCES,
MockConfigEntry,
MockUser,
async_fire_mqtt_message,
async_test_home_assistant,
mock_storage,
patch_yaml_files,
extract_stack_to_frame,
)
from .test_util.aiohttp import ( # noqa: E402, isort:skip
AiohttpClientMocker,
mock_aiohttp_client,
)
_LOGGER = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
logging.getLogger("sqlalchemy.engine").setLevel(logging.INFO)
asyncio.set_event_loop_policy(runner.HassEventLoopPolicy(False))
# Disable fixtures overriding our beautiful policy
asyncio.set_event_loop_policy = lambda policy: None
def pytest_addoption(parser: pytest.Parser) -> None:
"""Register custom pytest options."""
parser.addoption("--dburl", action="store", default="sqlite://")
def pytest_configure(config: pytest.Config) -> None:
"""Register marker for tests that log exceptions."""
config.addinivalue_line(
"markers", "no_fail_on_log_exception: mark test to not fail on logged exception"
)
if config.getoption("verbose") > 0:
logging.getLogger().setLevel(logging.DEBUG)
# Override default finish to detect unused snapshots despite xdist
# Temporary workaround until it is finalised inside syrupy
# See https://github.com/syrupy-project/syrupy/pull/901
SnapshotSession.finish = override_syrupy_finish
def pytest_runtest_setup() -> None:
"""Prepare pytest_socket and freezegun.
pytest_socket:
Throw if tests attempt to open sockets.
allow_unix_socket is set to True because it's needed by asyncio.
Important: socket_allow_hosts must be called before disable_socket, otherwise all
destinations will be allowed.
freezegun:
Modified to include https://github.com/spulec/freezegun/pull/424
"""
pytest_socket.socket_allow_hosts(["127.0.0.1"])
pytest_socket.disable_socket(allow_unix_socket=True)
freezegun.api.datetime_to_fakedatetime = ha_datetime_to_fakedatetime # type: ignore[attr-defined]
freezegun.api.FakeDatetime = HAFakeDatetime # type: ignore[attr-defined]
def adapt_datetime(val):
return val.isoformat(" ")
# Setup HAFakeDatetime converter for sqlite3
sqlite3.register_adapter(HAFakeDatetime, adapt_datetime)
# Setup HAFakeDatetime converter for pymysql
try:
# pylint: disable-next=import-outside-toplevel
import MySQLdb.converters as MySQLdb_converters
except ImportError:
pass
else:
MySQLdb_converters.conversions[HAFakeDatetime] = (
MySQLdb_converters.DateTime2literal
)
def ha_datetime_to_fakedatetime(datetime) -> freezegun.api.FakeDatetime: # type: ignore[name-defined]
"""Convert datetime to FakeDatetime.
Modified to include https://github.com/spulec/freezegun/pull/424.
"""
return freezegun.api.FakeDatetime( # type: ignore[attr-defined]
datetime.year,
datetime.month,
datetime.day,
datetime.hour,
datetime.minute,
datetime.second,
datetime.microsecond,
datetime.tzinfo,
fold=datetime.fold,
)
class HAFakeDatetime(freezegun.api.FakeDatetime): # type: ignore[name-defined]
"""Modified to include https://github.com/spulec/freezegun/pull/424."""
@classmethod
def now(cls, tz=None):
"""Return frozen now."""
now = cls._time_to_freeze() or freezegun.api.real_datetime.now()
if tz:
result = tz.fromutc(now.replace(tzinfo=tz))
else:
result = now
# Add the _tz_offset only if it's non-zero to preserve fold
if cls._tz_offset():
result += cls._tz_offset()
return ha_datetime_to_fakedatetime(result)
def check_real[**_P, _R](func: Callable[_P, Coroutine[Any, Any, _R]]):
"""Force a function to require a keyword _test_real to be passed in."""
@functools.wraps(func)
async def guard_func(*args: _P.args, **kwargs: _P.kwargs) -> _R:
real = kwargs.pop("_test_real", None)
if not real:
raise RuntimeError(
f'Forgot to mock or pass "_test_real=True" to {func.__name__}'
)
return await func(*args, **kwargs)
return guard_func
# Guard a few functions that would make network connections
location.async_detect_location_info = check_real(location.async_detect_location_info)
@pytest.fixture(name="caplog")
def caplog_fixture(caplog: pytest.LogCaptureFixture) -> pytest.LogCaptureFixture:
"""Set log level to debug for tests using the caplog fixture."""
caplog.set_level(logging.DEBUG)
return caplog
@pytest.fixture(autouse=True, scope="module")
def garbage_collection() -> None:
"""Run garbage collection at known locations.
This is to mimic the behavior of pytest-aiohttp, and is
required to avoid warnings during garbage collection from
spilling over into next test case. We run it per module which
handles the most common cases and let each module override
to run per test case if needed.
"""
gc.collect()
@pytest.fixture(autouse=True)
def expected_lingering_tasks() -> bool:
"""Temporary ability to bypass test failures.
Parametrize to True to bypass the pytest failure.
@pytest.mark.parametrize("expected_lingering_tasks", [True])
This should be removed when all lingering tasks have been cleaned up.
"""
return False
@pytest.fixture(autouse=True)
def expected_lingering_timers() -> bool:
"""Temporary ability to bypass test failures.
Parametrize to True to bypass the pytest failure.
@pytest.mark.parametrize("expected_lingering_timers", [True])
This should be removed when all lingering timers have been cleaned up.
"""
current_test = os.getenv("PYTEST_CURRENT_TEST")
if (
current_test
and current_test.startswith("tests/components/")
and current_test.split("/")[2] not in BASE_PLATFORMS
):
# As a starting point, we ignore non-platform components
return True
return False
@pytest.fixture
def wait_for_stop_scripts_after_shutdown() -> bool:
"""Add ability to bypass _schedule_stop_scripts_after_shutdown.
_schedule_stop_scripts_after_shutdown leaves a lingering timer.
Parametrize to True to bypass the pytest failure.
@pytest.mark.parametrize("wait_for_stop_scripts_at_shutdown", [True])
"""
return False
@pytest.fixture(autouse=True)
def skip_stop_scripts(
wait_for_stop_scripts_after_shutdown: bool,
) -> Generator[None]:
"""Add ability to bypass _schedule_stop_scripts_after_shutdown."""
if wait_for_stop_scripts_after_shutdown:
yield
return
with patch(
"homeassistant.helpers.script._schedule_stop_scripts_after_shutdown",
Mock(),
):
yield
@contextmanager
def long_repr_strings() -> Generator[None]:
"""Increase reprlib maxstring and maxother to 300."""
arepr = reprlib.aRepr
original_maxstring = arepr.maxstring
original_maxother = arepr.maxother
arepr.maxstring = 300
arepr.maxother = 300
try:
yield
finally:
arepr.maxstring = original_maxstring
arepr.maxother = original_maxother
@pytest.fixture(autouse=True)
def enable_event_loop_debug(event_loop: asyncio.AbstractEventLoop) -> None:
"""Enable event loop debug mode."""
event_loop.set_debug(True)
@pytest.fixture(autouse=True)
def verify_cleanup(
event_loop: asyncio.AbstractEventLoop,
expected_lingering_tasks: bool,
expected_lingering_timers: bool,
) -> Generator[None]:
"""Verify that the test has cleaned up resources correctly."""
threads_before = frozenset(threading.enumerate())
tasks_before = asyncio.all_tasks(event_loop)
yield
event_loop.run_until_complete(event_loop.shutdown_default_executor())
if len(INSTANCES) >= 2:
count = len(INSTANCES)
for inst in INSTANCES:
inst.stop()
pytest.exit(f"Detected non stopped instances ({count}), aborting test run")
# Warn and clean-up lingering tasks and timers
# before moving on to the next test.
tasks = asyncio.all_tasks(event_loop) - tasks_before
for task in tasks:
if expected_lingering_tasks:
_LOGGER.warning("Lingering task after test %r", task)
else:
pytest.fail(f"Lingering task after test {task!r}")
task.cancel()
if tasks:
event_loop.run_until_complete(asyncio.wait(tasks))
for handle in get_scheduled_timer_handles(event_loop):
if not handle.cancelled():
with long_repr_strings():
if expected_lingering_timers:
_LOGGER.warning("Lingering timer after test %r", handle)
elif handle._args and isinstance(job := handle._args[-1], HassJob):
if job.cancel_on_shutdown:
continue
pytest.fail(f"Lingering timer after job {job!r}")
else:
pytest.fail(f"Lingering timer after test {handle!r}")
handle.cancel()
# Verify no threads where left behind.
threads = frozenset(threading.enumerate()) - threads_before
for thread in threads:
assert isinstance(thread, threading._DummyThread) or thread.name.startswith(
"waitpid-"
)
try:
# Verify the default time zone has been restored
assert dt_util.DEFAULT_TIME_ZONE is datetime.UTC
finally:
# Restore the default time zone to not break subsequent tests
dt_util.DEFAULT_TIME_ZONE = datetime.UTC
try:
# Verify respx.mock has been cleaned up
assert not respx.mock.routes, "respx.mock routes not cleaned up, maybe the test needs to be decorated with @respx.mock"
finally:
# Clear mock routes not break subsequent tests
respx.mock.clear()
@pytest.fixture(autouse=True)
def reset_hass_threading_local_object() -> Generator[None]:
"""Reset the _Hass threading.local object for every test case."""
yield
ha._hass.__dict__.clear()
@pytest.fixture(autouse=True, scope="session")
def bcrypt_cost() -> Generator[None]:
"""Run with reduced rounds during tests, to speed up uses."""
gensalt_orig = bcrypt.gensalt
def gensalt_mock(rounds=12, prefix=b"2b"):
return gensalt_orig(4, prefix)
bcrypt.gensalt = gensalt_mock
yield
bcrypt.gensalt = gensalt_orig
@pytest.fixture
def hass_storage() -> Generator[dict[str, Any]]:
"""Fixture to mock storage."""
with mock_storage() as stored_data:
yield stored_data
@pytest.fixture
def load_registries() -> bool:
"""Fixture to control the loading of registries when setting up the hass fixture.
To avoid loading the registries, tests can be marked with:
@pytest.mark.parametrize("load_registries", [False])
"""
return True
class CoalescingResponse(client.ClientWebSocketResponse):
"""ClientWebSocketResponse client that mimics the websocket js code."""
def __init__(self, *args: Any, **kwargs: Any) -> None:
"""Init the ClientWebSocketResponse."""
super().__init__(*args, **kwargs)
self._recv_buffer: list[Any] = []
async def receive_json(
self,
*,
loads: JSONDecoder = json_loads,
timeout: float | None = None,
) -> Any:
"""receive_json or from buffer."""
if self._recv_buffer:
return self._recv_buffer.pop(0)
data = await self.receive_str(timeout=timeout)
decoded = loads(data)
if isinstance(decoded, list):
self._recv_buffer = decoded
return self._recv_buffer.pop(0)
return decoded
class CoalescingClient(TestClient):
"""Client that mimics the websocket js code."""
def __init__(self, *args: Any, **kwargs: Any) -> None:
"""Init TestClient."""
super().__init__(*args, ws_response_class=CoalescingResponse, **kwargs)
@pytest.fixture
def aiohttp_client_cls() -> type[CoalescingClient]:
"""Override the test class for aiohttp."""
return CoalescingClient
@pytest.fixture
def aiohttp_client(
event_loop: asyncio.AbstractEventLoop,
) -> Generator[ClientSessionGenerator]:
"""Override the default aiohttp_client since 3.x does not support aiohttp_client_cls.
Remove this when upgrading to 4.x as aiohttp_client_cls
will do the same thing
aiohttp_client(app, **kwargs)
aiohttp_client(server, **kwargs)
aiohttp_client(raw_server, **kwargs)
"""
loop = event_loop
clients = []
async def go(
param: Application | BaseTestServer,
/,
*args: Any,
server_kwargs: dict[str, Any] | None = None,
**kwargs: Any,
) -> TestClient:
if isinstance(param, Callable) and not isinstance( # type: ignore[arg-type]
param, (Application, BaseTestServer)
):
param = param(loop, *args, **kwargs)
kwargs = {}
else:
assert not args, "args should be empty"
client: TestClient
if isinstance(param, Application):
server_kwargs = server_kwargs or {}
server = TestServer(param, loop=loop, **server_kwargs)
# Registering a view after starting the server should still work.
server.app._router.freeze = lambda: None
client = CoalescingClient(server, loop=loop, **kwargs)
elif isinstance(param, BaseTestServer):
client = TestClient(param, loop=loop, **kwargs)
else:
raise TypeError(f"Unknown argument type: {type(param)!r}")
await client.start_server()
clients.append(client)
return client
yield go
async def finalize() -> None:
while clients:
await clients.pop().close()
loop.run_until_complete(finalize())
@pytest.fixture
def hass_fixture_setup() -> list[bool]:
"""Fixture which is truthy if the hass fixture has been setup."""
return []
@pytest.fixture
async def hass(
hass_fixture_setup: list[bool],
load_registries: bool,
hass_storage: dict[str, Any],
request: pytest.FixtureRequest,
mock_recorder_before_hass: None,
) -> AsyncGenerator[HomeAssistant]:
"""Create a test instance of Home Assistant."""
loop = asyncio.get_running_loop()
hass_fixture_setup.append(True)
def exc_handle(loop, context):
"""Handle exceptions by rethrowing them, which will fail the test."""
# Most of these contexts will contain an exception, but not all.
# The docs note the key as "optional"
# See https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.call_exception_handler
if "exception" in context:
exceptions.append(context["exception"])
else:
exceptions.append(
Exception(
"Received exception handler without exception, "
f"but with message: {context["message"]}"
)
)
orig_exception_handler(loop, context)
exceptions: list[Exception] = []
async with async_test_home_assistant(loop, load_registries) as hass:
orig_exception_handler = loop.get_exception_handler()
loop.set_exception_handler(exc_handle)
yield hass
# Config entries are not normally unloaded on HA shutdown. They are unloaded here
# to ensure that they could, and to help track lingering tasks and timers.
loaded_entries = [
entry
for entry in hass.config_entries.async_entries()
if entry.state is ConfigEntryState.LOADED
]
if loaded_entries:
await asyncio.gather(
*(
create_eager_task(
hass.config_entries.async_unload(config_entry.entry_id),
loop=hass.loop,
)
for config_entry in loaded_entries
)
)
await hass.async_stop(force=True)
for ex in exceptions:
if (
request.module.__name__,
request.function.__name__,
) in IGNORE_UNCAUGHT_EXCEPTIONS:
continue
raise ex
@pytest.fixture
async def stop_hass() -> AsyncGenerator[None]:
"""Make sure all hass are stopped."""
orig_hass = ha.HomeAssistant
event_loop = asyncio.get_running_loop()
created = []
def mock_hass(*args):
hass_inst = orig_hass(*args)
created.append(hass_inst)
return hass_inst
with patch("homeassistant.core.HomeAssistant", mock_hass):
yield
for hass_inst in created:
if hass_inst.state == ha.CoreState.stopped:
continue
with patch.object(hass_inst.loop, "stop"):
await hass_inst.async_block_till_done()
await hass_inst.async_stop(force=True)
await event_loop.shutdown_default_executor()
@pytest.fixture(name="requests_mock")
def requests_mock_fixture() -> Generator[requests_mock.Mocker]:
"""Fixture to provide a requests mocker."""
with requests_mock.mock() as m:
yield m
@pytest.fixture
def aioclient_mock() -> Generator[AiohttpClientMocker]:
"""Fixture to mock aioclient calls."""
with mock_aiohttp_client() as mock_session:
yield mock_session
@pytest.fixture
def mock_device_tracker_conf() -> Generator[list[Device]]:
"""Prevent device tracker from reading/writing data."""
devices: list[Device] = []
async def mock_update_config(path: str, dev_id: str, entity: Device) -> None:
devices.append(entity)
with (
patch(
(
"homeassistant.components.device_tracker.legacy"
".DeviceTracker.async_update_config"
),
side_effect=mock_update_config,
),
patch(
"homeassistant.components.device_tracker.legacy.async_load_config",
side_effect=lambda *args: devices,
),
):
yield devices
@pytest.fixture
async def hass_admin_credential(
hass: HomeAssistant, local_auth: homeassistant.HassAuthProvider
) -> Credentials:
"""Provide credentials for admin user."""
return Credentials(
id="mock-credential-id",
auth_provider_type="homeassistant",
auth_provider_id=None,
data={"username": "admin"},
is_new=False,
)
@pytest.fixture
async def hass_access_token(
hass: HomeAssistant, hass_admin_user: MockUser, hass_admin_credential: Credentials
) -> str:
"""Return an access token to access Home Assistant."""
await hass.auth.async_link_user(hass_admin_user, hass_admin_credential)
refresh_token = await hass.auth.async_create_refresh_token(
hass_admin_user, CLIENT_ID, credential=hass_admin_credential
)
return hass.auth.async_create_access_token(refresh_token)
@pytest.fixture
def hass_owner_user(
hass: HomeAssistant, local_auth: homeassistant.HassAuthProvider
) -> MockUser:
"""Return a Home Assistant admin user."""
return MockUser(is_owner=True).add_to_hass(hass)
@pytest.fixture
async def hass_admin_user(
hass: HomeAssistant, local_auth: homeassistant.HassAuthProvider
) -> MockUser:
"""Return a Home Assistant admin user."""
admin_group = await hass.auth.async_get_group(GROUP_ID_ADMIN)
return MockUser(groups=[admin_group]).add_to_hass(hass)
@pytest.fixture
async def hass_read_only_user(
hass: HomeAssistant, local_auth: homeassistant.HassAuthProvider
) -> MockUser:
"""Return a Home Assistant read only user."""
read_only_group = await hass.auth.async_get_group(GROUP_ID_READ_ONLY)
return MockUser(groups=[read_only_group]).add_to_hass(hass)
@pytest.fixture
async def hass_read_only_access_token(
hass: HomeAssistant,
hass_read_only_user: MockUser,
local_auth: homeassistant.HassAuthProvider,
) -> str:
"""Return a Home Assistant read only user."""
credential = Credentials(
id="mock-readonly-credential-id",
auth_provider_type="homeassistant",
auth_provider_id=None,
data={"username": "readonly"},
is_new=False,
)
hass_read_only_user.credentials.append(credential)
refresh_token = await hass.auth.async_create_refresh_token(
hass_read_only_user, CLIENT_ID, credential=credential
)
return hass.auth.async_create_access_token(refresh_token)
@pytest.fixture
async def hass_supervisor_user(
hass: HomeAssistant, local_auth: homeassistant.HassAuthProvider
) -> MockUser:
"""Return the Home Assistant Supervisor user."""
admin_group = await hass.auth.async_get_group(GROUP_ID_ADMIN)
return MockUser(
name=HASSIO_USER_NAME, groups=[admin_group], system_generated=True
).add_to_hass(hass)
@pytest.fixture
async def hass_supervisor_access_token(
hass: HomeAssistant,
hass_supervisor_user: MockUser,
local_auth: homeassistant.HassAuthProvider,
) -> str:
"""Return a Home Assistant Supervisor access token."""
refresh_token = await hass.auth.async_create_refresh_token(hass_supervisor_user)
return hass.auth.async_create_access_token(refresh_token)
@pytest.fixture
async def local_auth(hass: HomeAssistant) -> homeassistant.HassAuthProvider:
"""Load local auth provider."""
prv = homeassistant.HassAuthProvider(
hass, hass.auth._store, {"type": "homeassistant"}
)
await prv.async_initialize()
hass.auth._providers[(prv.type, prv.id)] = prv
return prv
@pytest.fixture
def hass_client(
hass: HomeAssistant,
aiohttp_client: ClientSessionGenerator,
hass_access_token: str,
socket_enabled: None,
) -> ClientSessionGenerator:
"""Return an authenticated HTTP client."""
async def auth_client(access_token: str | None = hass_access_token) -> TestClient:
"""Return an authenticated client."""
return await aiohttp_client(
hass.http.app, headers={"Authorization": f"Bearer {access_token}"}
)
return auth_client
@pytest.fixture
def hass_client_no_auth(
hass: HomeAssistant,
aiohttp_client: ClientSessionGenerator,
socket_enabled: None,
) -> ClientSessionGenerator:
"""Return an unauthenticated HTTP client."""
async def client() -> TestClient:
"""Return an authenticated client."""
return await aiohttp_client(hass.http.app)
return client
@pytest.fixture
def current_request() -> Generator[MagicMock]:
"""Mock current request."""
with patch("homeassistant.components.http.current_request") as mock_request_context:
mocked_request = make_mocked_request(
"GET",
"/some/request",
headers={"Host": "example.com"},
sslcontext=ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT),
)
mock_request_context.get.return_value = mocked_request
yield mock_request_context
@pytest.fixture
def current_request_with_host(current_request: MagicMock) -> None:
"""Mock current request with a host header."""
new_headers = multidict.CIMultiDict(current_request.get.return_value.headers)
new_headers[config_entry_oauth2_flow.HEADER_FRONTEND_BASE] = "https://example.com"
current_request.get.return_value = current_request.get.return_value.clone(
headers=new_headers
)
@pytest.fixture
def hass_ws_client(
aiohttp_client: ClientSessionGenerator,
hass_access_token: str,
hass: HomeAssistant,
socket_enabled: None,
) -> WebSocketGenerator:
"""Websocket client fixture connected to websocket server."""
async def create_client(
hass: HomeAssistant = hass, access_token: str | None = hass_access_token
) -> MockHAClientWebSocket:
"""Create a websocket client."""
assert await async_setup_component(hass, "websocket_api", {})
client = await aiohttp_client(hass.http.app)
websocket = await client.ws_connect(URL)
auth_resp = await websocket.receive_json()
assert auth_resp["type"] == TYPE_AUTH_REQUIRED
if access_token is None:
await websocket.send_json({"type": TYPE_AUTH, "access_token": "incorrect"})
else:
await websocket.send_json({"type": TYPE_AUTH, "access_token": access_token})
auth_ok = await websocket.receive_json()
assert auth_ok["type"] == TYPE_AUTH_OK
def _get_next_id() -> Generator[int]:
i = 0
while True:
yield (i := i + 1)
id_generator = _get_next_id()
def _send_json_auto_id(data: dict[str, Any]) -> Coroutine[Any, Any, None]:
data["id"] = next(id_generator)
return websocket.send_json(data)
async def _remove_device(device_id: str, config_entry_id: str) -> Any:
await _send_json_auto_id(
{
"type": "config/device_registry/remove_config_entry",
"config_entry_id": config_entry_id,
"device_id": device_id,
}
)
return await websocket.receive_json()
# wrap in client
wrapped_websocket = cast(MockHAClientWebSocket, websocket)
wrapped_websocket.client = client
wrapped_websocket.send_json_auto_id = _send_json_auto_id
wrapped_websocket.remove_device = _remove_device
return wrapped_websocket
return create_client
@pytest.fixture(autouse=True)
def fail_on_log_exception(
request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Fixture to fail if a callback wrapped by catch_log_exception or coroutine wrapped by async_create_catching_coro throws."""
if "no_fail_on_log_exception" in request.keywords:
return
def log_exception(format_err, *args):
raise # noqa: PLE0704
monkeypatch.setattr("homeassistant.util.logging.log_exception", log_exception)
@pytest.fixture
def mqtt_config_entry_data() -> dict[str, Any] | None:
"""Fixture to allow overriding MQTT config."""
return None
@pytest.fixture
def mqtt_client_mock(hass: HomeAssistant) -> Generator[MqttMockPahoClient]:
"""Fixture to mock MQTT client."""
mid: int = 0
def get_mid() -> int:
nonlocal mid
mid += 1
return mid
class FakeInfo:
"""Class to fake MQTT info."""
def __init__(self, mid: int) -> None:
self.mid = mid
self.rc = 0
with patch(
"homeassistant.components.mqtt.async_client.AsyncMQTTClient"
) as mock_client:
# The below use a call_soon for the on_publish/on_subscribe/on_unsubscribe
# callbacks to simulate the behavior of the real MQTT client which will
# not be synchronous.
@ha.callback
def _async_fire_mqtt_message(topic, payload, qos, retain):
async_fire_mqtt_message(hass, topic, payload or b"", qos, retain)
mid = get_mid()
hass.loop.call_soon(mock_client.on_publish, 0, 0, mid)
return FakeInfo(mid)
def _subscribe(topic, qos=0):
mid = get_mid()
hass.loop.call_soon(mock_client.on_subscribe, 0, 0, mid)
return (0, mid)
def _unsubscribe(topic):
mid = get_mid()
hass.loop.call_soon(mock_client.on_unsubscribe, 0, 0, mid)
return (0, mid)
def _connect(*args, **kwargs):
# Connect always calls reconnect once, but we
# mock it out so we call reconnect to simulate
# the behavior.
mock_client.reconnect()
hass.loop.call_soon_threadsafe(
mock_client.on_connect, mock_client, None, 0, 0, 0
)
mock_client.on_socket_open(
mock_client, None, Mock(fileno=Mock(return_value=-1))
)
mock_client.on_socket_register_write(
mock_client, None, Mock(fileno=Mock(return_value=-1))
)
return 0
mock_client = mock_client.return_value
mock_client.connect.side_effect = _connect
mock_client.subscribe.side_effect = _subscribe
mock_client.unsubscribe.side_effect = _unsubscribe
mock_client.publish.side_effect = _async_fire_mqtt_message
mock_client.loop_read.return_value = 0
yield mock_client
@pytest.fixture
async def mqtt_mock(
hass: HomeAssistant,
mock_hass_config: None,