response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Get default bulb state.
def get_default_bulb_state() -> dict[str, Any]: """Get default bulb state.""" return { "type": "rgblamp", "battery": False, "reachable": True, "meshroot": True, "on": False, "color": "46;18;100", "mode": "hsv", "ramp": 10, "power": 0.45, "fw_version": "2.58.0", }
Get default switch state.
def get_default_switch_state() -> dict[str, Any]: """Get default switch state.""" return { "power": 1.69, "Ws": 0.81, "relay": True, "temperature": 24.87, "version": "2.59.32", "mac": "6001940376EB", "ssid": "personal", "ip": "192.168.0.23", "mask": "255.255.255.0", "gw": "192.168.0.1", "dns": "192.168.0.1", "static": False, "connected": True, "signal": 94, }
Fixture to set the oauth token expiration time.
def mock_expires_at() -> float: """Fixture to set the oauth token expiration time.""" return time.time() + 3600
Return the default mocked config entry.
def mock_config_entry(hass: HomeAssistant, expires_at: float) -> MockConfigEntry: """Return the default mocked config entry.""" config_entry = MockConfigEntry( version=1, domain=DOMAIN, title="myUplink test", data={ "auth_implementation": DOMAIN, "token": { "access_token": "Fake_token", "scope": "WRITESYSTEM READSYSTEM offline_access", "expires_in": 86399, "refresh_token": "3012bc9f-7a65-4240-b817-9154ffdcc30f", "token_type": "Bearer", "expires_at": expires_at, }, }, entry_id="myuplink_test", ) config_entry.add_to_hass(hass) return config_entry
Fixture for loading device file.
def load_device_file() -> str: """Fixture for loading device file.""" return load_fixture("device.json", DOMAIN)
Fixture for device.
def device_fixture(load_device_file: str) -> Device: """Fixture for device.""" return Device(json_loads(load_device_file))
Load fixture file for systems endpoint.
def load_systems_jv_file(load_systems_file: str) -> dict[str, Any]: """Load fixture file for systems endpoint.""" return json_loads(load_systems_file)
Load fixture file for systems.
def load_systems_file() -> str: """Load fixture file for systems.""" return load_fixture("systems-2dev.json", DOMAIN)
Fixture for systems.
def system_fixture(load_systems_file: str) -> list[System]: """Fixture for systems.""" data = json_loads(load_systems_file) return [System(system_data) for system_data in data["systems"]]
Load fixture file for device-points endpoint.
def load_device_points_file() -> str: """Load fixture file for device-points endpoint.""" return "device_points_nibe_f730.json"
Load fixture file for device_points.
def load_device_points_jv_file(load_device_points_file) -> str: """Load fixture file for device_points.""" return load_fixture(load_device_points_file, DOMAIN)
Fixture for device_points.
def device_points_fixture(load_device_points_jv_file: str) -> list[DevicePoint]: """Fixture for device_points.""" data = orjson.loads(load_device_points_jv_file) return [DevicePoint(point_data) for point_data in data]
Mock a myuplink client.
def mock_myuplink_client( load_device_file, device_fixture, load_device_points_jv_file, device_points_fixture, system_fixture, load_systems_jv_file, ) -> Generator[MagicMock, None, None]: """Mock a myuplink client.""" with patch( "homeassistant.components.myuplink.MyUplinkAPI", autospec=True, ) as mock_client: client = mock_client.return_value client.async_get_systems.return_value = system_fixture client.async_get_systems_json.return_value = load_systems_jv_file client.async_get_device.return_value = device_fixture client.async_get_device_json.return_value = load_device_file client.async_get_device_points.return_value = device_points_fixture client.async_get_device_points_json.return_value = load_device_points_jv_file yield client
Fixture for platforms.
def platforms() -> list[str]: """Fixture for platforms.""" return []
Fixture that sets up NamecheapDNS.
def setup_namecheapdns(hass, aioclient_mock): """Fixture that sets up NamecheapDNS.""" aioclient_mock.get( namecheapdns.UPDATE_URL, params={"host": HOST, "domain": DOMAIN, "password": PASSWORD}, text="<interface-response><ErrCount>0</ErrCount></interface-response>", ) hass.loop.run_until_complete( async_setup_component( hass, namecheapdns.DOMAIN, {"namecheapdns": {"host": HOST, "domain": DOMAIN, "password": PASSWORD}}, ) )
Mock the nessclient Client constructor. Replaces nessclient.Client with a Mock which always returns the same MagicMock() instance.
def mock_nessclient(): """Mock the nessclient Client constructor. Replaces nessclient.Client with a Mock which always returns the same MagicMock() instance. """ _mock_instance = MagicMock(MockClient()) _mock_factory = MagicMock() _mock_factory.return_value = _mock_instance with patch( "homeassistant.components.ness_alarm.Client", new=_mock_factory, create=True ): yield _mock_instance
Return aiohttp_client and allow opening sockets.
def aiohttp_client(event_loop, aiohttp_client, socket_enabled): """Return aiohttp_client and allow opening sockets.""" return aiohttp_client
Test cleanup, remove any media storage persisted during the test.
def cleanup_media_storage(hass): """Test cleanup, remove any media storage persisted during the test.""" tmp_path = str(uuid.uuid4()) with patch("homeassistant.components.nest.media_source.MEDIA_PATH", new=tmp_path): yield shutil.rmtree(hass.config.path(tmp_path), ignore_errors=True)
Set up the FakeSusbcriber.
def subscriber() -> YieldFixture[FakeSubscriber]: """Set up the FakeSusbcriber.""" subscriber = FakeSubscriber() with patch( "homeassistant.components.nest.api.GoogleNestSubscriber", return_value=subscriber, ): yield subscriber
Fixture for injecting errors into the subscriber.
def mock_subscriber() -> YieldFixture[AsyncMock]: """Fixture for injecting errors into the subscriber.""" mock_subscriber = AsyncMock(FakeSubscriber) with patch( "homeassistant.components.nest.api.GoogleNestSubscriber", return_value=mock_subscriber, ): yield mock_subscriber
Fixture to specify platforms to test.
def platforms() -> list[str]: """Fixture to specify platforms to test.""" return []
Fixture to let tests override subscriber id regardless of configuration type used.
def subscriber_id() -> str: """Fixture to let tests override subscriber id regardless of configuration type used.""" return SUBSCRIBER_ID
Fixture that sets up the configuration used for the test.
def nest_test_config(request) -> NestTestConfig: """Fixture that sets up the configuration used for the test.""" return TEST_CONFIG_APP_CREDS
Fixture that sets up the configuration.yaml for the test.
def config( subscriber_id: str | None, nest_test_config: NestTestConfig ) -> dict[str, Any]: """Fixture that sets up the configuration.yaml for the test.""" config = copy.deepcopy(nest_test_config.config) if CONF_SUBSCRIBER_ID in config.get(DOMAIN, {}): if subscriber_id: config[DOMAIN][CONF_SUBSCRIBER_ID] = subscriber_id else: del config[DOMAIN][CONF_SUBSCRIBER_ID] return config
Fixture to set ConfigEntry unique id.
def config_entry_unique_id() -> str: """Fixture to set ConfigEntry unique id.""" return PROJECT_ID
Fixture for expiration time of the config entry auth token.
def token_expiration_time() -> float: """Fixture for expiration time of the config entry auth token.""" return time.time() + 86400
Fixture for OAuth 'token' data for a ConfigEntry.
def token_entry(token_expiration_time: float) -> dict[str, Any]: """Fixture for OAuth 'token' data for a ConfigEntry.""" return { "access_token": FAKE_TOKEN, "refresh_token": FAKE_REFRESH_TOKEN, "scope": " ".join(SDM_SCOPES), "token_type": "Bearer", "expires_at": token_expiration_time, }
Fixture that sets up the ConfigEntry for the test.
def config_entry( subscriber_id: str | None, nest_test_config: NestTestConfig, config_entry_unique_id: str, token_entry: dict[str, Any], ) -> MockConfigEntry | None: """Fixture that sets up the ConfigEntry for the test.""" if nest_test_config.config_entry_data is None: return None data = copy.deepcopy(nest_test_config.config_entry_data) if CONF_SUBSCRIBER_ID in data: if subscriber_id: data[CONF_SUBSCRIBER_ID] = subscriber_id else: del data[CONF_SUBSCRIBER_ID] data["token"] = token_entry return MockConfigEntry(domain=DOMAIN, data=data, unique_id=config_entry_unique_id)
Fixture to reset client library diagnostic counters.
def reset_diagnostics() -> Generator[None, None, None]: """Fixture to reset client library diagnostic counters.""" yield diagnostics.reset()
Disable default subscriber since tests use their own patch.
def subscriber() -> None: """Disable default subscriber since tests use their own patch.""" return None
Fixture to set platforms used in the test.
def platforms() -> list[str]: """Fixture to set platforms used in the test.""" return ["camera"]
Fixture to create a basic camera device.
def camera_device(create_device: CreateDevice) -> None: """Fixture to create a basic camera device.""" create_device.create(DEVICE_TRAITS)
Fixture to create a WebRTC camera device.
def webrtc_camera_device(create_device: CreateDevice) -> None: """Fixture to create a WebRTC camera device.""" create_device.create( { "sdm.devices.traits.Info": { "customName": "My Camera", }, "sdm.devices.traits.CameraLiveStream": { "maxVideoResolution": { "width": 640, "height": 480, }, "videoCodecs": ["H264"], "audioCodecs": ["AAC"], "supportedProtocols": ["WEB_RTC"], }, } )
Create an EventMessage for a motion event.
def make_motion_event( event_id: str = MOTION_EVENT_ID, event_session_id: str = EVENT_SESSION_ID, timestamp: datetime.datetime | None = None, ) -> EventMessage: """Create an EventMessage for a motion event.""" if not timestamp: timestamp = utcnow() return EventMessage( { "eventId": "some-event-id", # Ignored; we use the resource updated event id below "timestamp": timestamp.isoformat(timespec="seconds"), "resourceUpdate": { "name": DEVICE_ID, "events": { "sdm.devices.events.CameraMotion.Motion": { "eventSessionId": event_session_id, "eventId": event_id, }, }, }, }, auth=None, )
Make response for the API that generates a streaming url.
def make_stream_url_response( expiration: datetime.datetime | None = None, token_num: int = 0 ) -> aiohttp.web.Response: """Make response for the API that generates a streaming url.""" if not expiration: # Default to an arbitrary time in the future expiration = utcnow() + datetime.timedelta(seconds=100) return aiohttp.web.json_response( { "results": { "streamUrls": { "rtspUrl": f"rtsp://some/url?auth=g.{token_num}.streamingToken" }, "streamExtensionToken": f"g.{token_num}.extensionToken", "streamToken": f"g.{token_num}.streamingToken", "expiresAt": expiration.isoformat(timespec="seconds"), }, } )
Fixture to specify platforms to test.
def platforms() -> list[str]: """Fixture to specify platforms to test.""" return ["climate"]
Fixture that sets default traits used for devices.
def device_traits() -> dict[str, Any]: """Fixture that sets default traits used for devices.""" return {"sdm.devices.traits.Info": {"customName": "My Thermostat"}}
Fixture with empty configuration and no existing config entry.
def nest_test_config(request) -> NestTestConfig: """Fixture with empty configuration and no existing config entry.""" return TEST_CONFIGFLOW_APP_CREDS
Test a device name from an Info trait.
def test_device_custom_name() -> None: """Test a device name from an Info trait.""" device = Device.MakeDevice( { "name": "some-device-id", "type": "sdm.devices.types.DOORBELL", "traits": { "sdm.devices.traits.Info": { "customName": "My Doorbell", }, }, }, auth=None, ) device_info = NestDeviceInfo(device) assert device_info.device_name == "My Doorbell" assert device_info.device_model == "Doorbell" assert device_info.device_brand == "Google Nest" assert device_info.device_info == { ATTR_IDENTIFIERS: {("nest", "some-device-id")}, ATTR_NAME: "My Doorbell", ATTR_MANUFACTURER: "Google Nest", ATTR_MODEL: "Doorbell", ATTR_SUGGESTED_AREA: None, }
Test a device name from the room name.
def test_device_name_room() -> None: """Test a device name from the room name.""" device = Device.MakeDevice( { "name": "some-device-id", "type": "sdm.devices.types.DOORBELL", "parentRelations": [ {"parent": "some-structure-id", "displayName": "Some Room"} ], }, auth=None, ) device_info = NestDeviceInfo(device) assert device_info.device_name == "Some Room" assert device_info.device_model == "Doorbell" assert device_info.device_brand == "Google Nest" assert device_info.device_info == { ATTR_IDENTIFIERS: {("nest", "some-device-id")}, ATTR_NAME: "Some Room", ATTR_MANUFACTURER: "Google Nest", ATTR_MODEL: "Doorbell", ATTR_SUGGESTED_AREA: "Some Room", }
Test a device that has a name inferred from the type.
def test_device_no_name() -> None: """Test a device that has a name inferred from the type.""" device = Device.MakeDevice( {"name": "some-device-id", "type": "sdm.devices.types.DOORBELL", "traits": {}}, auth=None, ) device_info = NestDeviceInfo(device) assert device_info.device_name == "Doorbell" assert device_info.device_model == "Doorbell" assert device_info.device_brand == "Google Nest" assert device_info.device_info == { ATTR_IDENTIFIERS: {("nest", "some-device-id")}, ATTR_NAME: "Doorbell", ATTR_MANUFACTURER: "Google Nest", ATTR_MODEL: "Doorbell", ATTR_SUGGESTED_AREA: None, }
Test a device with a type name that is not recognized.
def test_device_invalid_type() -> None: """Test a device with a type name that is not recognized.""" device = Device.MakeDevice( { "name": "some-device-id", "type": "sdm.devices.types.INVALID_TYPE", "traits": { "sdm.devices.traits.Info": { "customName": "My Doorbell", }, }, }, auth=None, ) device_info = NestDeviceInfo(device) assert device_info.device_name == "My Doorbell" assert device_info.device_model is None assert device_info.device_brand == "Google Nest" assert device_info.device_info == { ATTR_IDENTIFIERS: {("nest", "some-device-id")}, ATTR_NAME: "My Doorbell", ATTR_MANUFACTURER: "Google Nest", ATTR_MODEL: None, ATTR_SUGGESTED_AREA: None, }
Test the suggested area with different device name and room name.
def test_suggested_area() -> None: """Test the suggested area with different device name and room name.""" device = Device.MakeDevice( { "name": "some-device-id", "type": "sdm.devices.types.DOORBELL", "traits": { "sdm.devices.traits.Info": { "customName": "My Doorbell", }, }, "parentRelations": [ {"parent": "some-structure-id", "displayName": "Some Room"} ], }, auth=None, ) device_info = NestDeviceInfo(device) assert device_info.device_name == "My Doorbell" assert device_info.device_model == "Doorbell" assert device_info.device_brand == "Google Nest" assert device_info.device_info == { ATTR_IDENTIFIERS: {("nest", "some-device-id")}, ATTR_NAME: "My Doorbell", ATTR_MANUFACTURER: "Google Nest", ATTR_MODEL: "Doorbell", ATTR_SUGGESTED_AREA: "Some Room", }
Fixture to setup the platforms to test.
def platforms() -> list[str]: """Fixture to setup the platforms to test.""" return ["camera"]
Create a nest camera.
def make_camera(device_id, name=DEVICE_NAME, traits={}): """Create a nest camera.""" traits = traits.copy() traits.update( { "sdm.devices.traits.Info": { "customName": name, }, "sdm.devices.traits.CameraLiveStream": { "maxVideoResolution": { "width": 640, "height": 480, }, "videoCodecs": ["H264"], "audioCodecs": ["AAC"], }, } ) return { "name": device_id, "type": "sdm.devices.types.CAMERA", "traits": traits, }
Track calls to a mock service.
def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation")
Fixture to specify platforms to test.
def platforms() -> list[str]: """Fixture to specify platforms to test.""" return ["sensor", "camera"]
Fixture for platforms to setup.
def platforms() -> list[str]: """Fixture for platforms to setup.""" return [PLATFORM]
Fixture for the type of device under test.
def device_type() -> str: """Fixture for the type of device under test.""" return "sdm.devices.types.DOORBELL"
Fixture for the present traits of the device under test.
def device_traits() -> list[str]: """Fixture for the present traits of the device under test.""" return ["sdm.devices.traits.DoorbellChime"]
Fixture to create a device under test.
def device( device_type: str, device_traits: dict[str, Any], create_device: CreateDevice ) -> None: """Fixture to create a device under test.""" return create_device.create( raw_data={ "name": DEVICE_ID, "type": device_type, "traits": create_device_traits(device_traits), } )
View of an event with relevant keys for testing.
def event_view(d: Mapping[str, Any]) -> Mapping[str, Any]: """View of an event with relevant keys for testing.""" return {key: value for key, value in d.items() if key in EVENT_KEYS}
Create fake traits for a device.
def create_device_traits(event_traits=[]): """Create fake traits for a device.""" result = { "sdm.devices.traits.Info": { "customName": "Front", }, "sdm.devices.traits.CameraLiveStream": { "maxVideoResolution": { "width": 640, "height": 480, }, "videoCodecs": ["H264"], "audioCodecs": ["AAC"], }, } result.update({t: {} for t in event_traits}) return result
Create an EventMessage for a single event type.
def create_event(event_type, device_id=DEVICE_ID, timestamp=None): """Create an EventMessage for a single event type.""" events = { event_type: { "eventSessionId": EVENT_SESSION_ID, "eventId": EVENT_ID, }, } return create_events(events=events, device_id=device_id)
Create an EventMessage for events.
def create_events(events, device_id=DEVICE_ID, timestamp=None): """Create an EventMessage for events.""" if not timestamp: timestamp = utcnow() return EventMessage( { "eventId": "some-event-id", "timestamp": timestamp.isoformat(timespec="seconds"), "resourceUpdate": { "name": device_id, "events": events, }, }, auth=None, )
Fixture to setup the platforms to test.
def platforms() -> list[str]: """Fixture to setup the platforms to test.""" return ["sensor"]
Fixture to capture nest init error messages.
def error_caplog(caplog): """Fixture to capture nest init error messages.""" with caplog.at_level(logging.ERROR, logger="homeassistant.components.nest"): yield caplog
Fixture to capture nest init warning messages.
def warning_caplog(caplog): """Fixture to capture nest init warning messages.""" with caplog.at_level(logging.WARNING, logger="homeassistant.components.nest"): yield caplog
Fixture to inject failures into FakeSubscriber start.
def subscriber_side_effect() -> None: """Fixture to inject failures into FakeSubscriber start.""" return None
Fixture overriding default subscriber behavior to allow failure injection.
def failing_subscriber(subscriber_side_effect: Any) -> YieldFixture[FakeSubscriber]: """Fixture overriding default subscriber behavior to allow failure injection.""" subscriber = FakeSubscriber() with patch( "homeassistant.components.nest.api.GoogleNestSubscriber.start_async", side_effect=subscriber_side_effect, ): yield subscriber
Generate image content for a frame of a video.
def frame_image_data(frame_i, total_frames): """Generate image content for a frame of a video.""" img = np.empty((480, 320, 3)) img[:, :, 0] = 0.5 + 0.5 * np.sin(2 * np.pi * (0 / 3 + frame_i / total_frames)) img[:, :, 1] = 0.5 + 0.5 * np.sin(2 * np.pi * (1 / 3 + frame_i / total_frames)) img[:, :, 2] = 0.5 + 0.5 * np.sin(2 * np.pi * (2 / 3 + frame_i / total_frames)) img = np.round(255 * img).astype(np.uint8) return np.clip(img, 0, 255)
Fixture for platforms to setup.
def platforms() -> list[str]: """Fixture for platforms to setup.""" return [PLATFORM]
Fixture for the type of device under test.
def device_type() -> str: """Fixture for the type of device under test.""" return CAMERA_DEVICE_TYPE
Fixture for the present traits of the device under test.
def device_traits() -> dict[str, Any]: """Fixture for the present traits of the device under test.""" return CAMERA_TRAITS
Fixture to create a device under test.
def device( device_type: str, device_traits: dict[str, Any], create_device: CreateDevice ) -> None: """Fixture to create a device under test.""" return create_device.create( raw_data={ "name": DEVICE_ID, "type": device_type, "traits": device_traits, } )
Generate test mp4 clip.
def mp4() -> io.BytesIO: """Generate test mp4 clip.""" total_frames = 10 fps = 10 output = io.BytesIO() output.name = "test.mp4" container = av.open(output, mode="w", format="mp4") stream = container.add_stream("libx264", rate=fps) stream.width = 480 stream.height = 320 stream.pix_fmt = "yuv420p" for frame_i in range(total_frames): img = frame_image_data(frame_i, total_frames) frame = av.VideoFrame.from_ndarray(img, format="rgb24") for packet in stream.encode(frame): container.mux(packet) # Flush stream for packet in stream.encode(): container.mux(packet) # Close the file container.close() output.seek(0) return output
Fixture to enable media fetching for tests to exercise.
def enable_prefetch(subscriber: FakeSubscriber) -> None: """Fixture to enable media fetching for tests to exercise.""" subscriber.cache_policy.fetch = True
Fixture for overrideing cache size.
def cache_size() -> int: """Fixture for overrideing cache size.""" return 100
Fixture for patching the cache size.
def apply_cache_size(cache_size): """Fixture for patching the cache size.""" with patch("homeassistant.components.nest.EVENT_MEDIA_CACHE_SIZE", new=cache_size): yield
Create an EventMessage for a single event type.
def create_event( event_session_id, event_id, event_type, timestamp=None, device_id=None ): """Create an EventMessage for a single event type.""" if not timestamp: timestamp = dt_util.now() event_data = { event_type: { "eventSessionId": event_session_id, "eventId": event_id, }, } return create_event_message(event_data, timestamp, device_id=device_id)
Create an EventMessage for a single event type.
def create_event_message(event_data, timestamp, device_id=None): """Create an EventMessage for a single event type.""" if device_id is None: device_id = DEVICE_ID return EventMessage( { "eventId": f"{EVENT_ID}-{timestamp}", "timestamp": timestamp.isoformat(timespec="seconds"), "resourceUpdate": { "name": device_id, "events": event_data, }, }, auth=None, )
Return event payload data for a battery camera event.
def create_battery_event_data( event_type, event_session_id=EVENT_SESSION_ID, event_id="n:2" ): """Return event payload data for a battery camera event.""" return { event_type: { "eventSessionId": event_session_id, "eventId": event_id, }, "sdm.devices.events.CameraClipPreview.ClipPreview": { "eventSessionId": event_session_id, "previewUrl": "https://127.0.0.1/example", }, }
Persist changes to event store immediately.
def event_store() -> Generator[None, None, None]: """Persist changes to event store immediately.""" with patch( "homeassistant.components.nest.media_source.STORAGE_SAVE_DELAY_SECONDS", new=0, ): yield
Fixture to setup the platforms to test.
def platforms() -> list[str]: """Fixture to setup the platforms to test.""" return ["sensor"]
Fixture that sets default traits used for devices.
def device_traits() -> dict[str, Any]: """Fixture that sets default traits used for devices.""" return {"sdm.devices.traits.Info": {"customName": "My Sensor"}}
Restrict loaded platforms to list given.
def selected_platforms(platforms: list[Platform]) -> AsyncMock: """Restrict loaded platforms to list given.""" with ( patch("homeassistant.components.netatmo.data_handler.PLATFORMS", platforms), patch( "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation", ), patch( "homeassistant.components.netatmo.webhook_generate_url", ), ): yield
Mock a config entry.
def mock_config_entry_fixture(hass: HomeAssistant) -> MockConfigEntry: """Mock a config entry.""" mock_entry = MockConfigEntry( domain="netatmo", data={ "auth_implementation": "cloud", "token": { "refresh_token": "mock-refresh-token", "access_token": "mock-access-token", "type": "Bearer", "expires_in": 60, "expires_at": time() + 1000, "scope": ALL_SCOPES, }, }, options={ "weather_areas": { "Home avg": { "lat_ne": 32.2345678, "lon_ne": -117.1234567, "lat_sw": 32.1234567, "lon_sw": -117.2345678, "show_on_map": False, "area_name": "Home avg", "mode": "avg", }, "Home max": { "lat_ne": 32.2345678, "lon_ne": -117.1234567, "lat_sw": 32.1234567, "lon_sw": -117.2345678, "show_on_map": True, "area_name": "Home max", "mode": "max", }, } }, ) mock_entry.add_to_hass(hass) return mock_entry
Restrict loaded platforms to list given.
def netatmo_auth() -> AsyncMock: """Restrict loaded platforms to list given.""" with patch( "homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth" ) as mock_auth: mock_auth.return_value.async_post_request.side_effect = fake_post_request mock_auth.return_value.async_post_api_request.side_effect = fake_post_request mock_auth.return_value.async_get_image.side_effect = fake_get_image mock_auth.return_value.async_addwebhook.side_effect = AsyncMock() mock_auth.return_value.async_dropwebhook.side_effect = AsyncMock() yield
Track calls to a mock service.
def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation")
Mock a successful service.
def mock_controller_service(): """Mock a successful service.""" with ( patch("homeassistant.components.netgear.async_setup_entry", return_value=True), patch("homeassistant.components.netgear.router.Netgear") as service_mock, ): service_mock.return_value.get_info = Mock(return_value=ROUTER_INFOS) service_mock.return_value.port = 80 service_mock.return_value.ssl = False yield service_mock
Mock cannot connect error.
def cannot_connect(aioclient_mock: AiohttpClientMocker) -> None: """Mock cannot connect error.""" aioclient_mock.get(f"http://{HOST}/model.json", exc=ClientError) aioclient_mock.post(f"http://{HOST}/Forms/config", exc=ClientError)
Mock Netgear LTE unknown error.
def unknown(aioclient_mock: AiohttpClientMocker) -> None: """Mock Netgear LTE unknown error.""" aioclient_mock.get( f"http://{HOST}/model.json", text="something went wrong", headers={"Content-Type": "application/javascript"}, )
Mock Netgear LTE connection.
def mock_connection(aioclient_mock: AiohttpClientMocker) -> None: """Mock Netgear LTE connection.""" aioclient_mock.get( f"http://{HOST}/model.json", text=load_fixture("netgear_lte/model.json"), headers={"Content-Type": CONTENT_TYPE_JSON}, ) aioclient_mock.post( f"http://{HOST}/Forms/config", headers={"Content-Type": CONTENT_TYPE_JSON}, ) aioclient_mock.post( f"http://{HOST}/Forms/smsSendMsg", headers={"Content-Type": CONTENT_TYPE_JSON}, )
Create Netgear LTE entry in Home Assistant.
def mock_config_entry(hass: HomeAssistant) -> MockConfigEntry: """Create Netgear LTE entry in Home Assistant.""" return MockConfigEntry( domain=DOMAIN, data=CONF_DATA, unique_id="FFFFFFFFFFFFF", title="Netgear LM1200" )
Override mock of network util's async_get_source_ip.
def mock_get_source_ip(): """Override mock of network util's async_get_source_ip."""
Override mock of network util's async_get_adapters.
def mock_network(): """Override mock of network util's async_get_adapters."""
Generate alternative directions values. When only on edirection is returned, it is not returned as a list, but instead an object.
def route_config_direction(request: pytest.FixtureRequest) -> Any: """Generate alternative directions values. When only on edirection is returned, it is not returned as a list, but instead an object. """ return request.param
Mock all list functions in nextbus to test validate logic.
def mock_nextbus_lists( mock_nextbus: MagicMock, route_config_direction: Any ) -> MagicMock: """Mock all list functions in nextbus to test validate logic.""" instance = mock_nextbus.return_value instance.get_agency_list.return_value = { "agency": [{"tag": "sf-muni", "title": "San Francisco Muni"}] } instance.get_route_list.return_value = { "route": [{"tag": "F", "title": "F - Market & Wharves"}] } instance.get_route_config.return_value = { "route": { "stop": [ {"tag": "5650", "title": "Market St & 7th St"}, {"tag": "5651", "title": "Market St & 7th St"}, # Error case test. Duplicate title with no unique direction {"tag": "5652", "title": "Market St & 7th St"}, ], "direction": route_config_direction, } } return instance
Create a mock for the nextbus component setup.
def mock_setup_entry() -> Generator[MagicMock, None, None]: """Create a mock for the nextbus component setup.""" with patch( "homeassistant.components.nextbus.async_setup_entry", return_value=True, ) as mock_setup_entry: yield mock_setup_entry
Create a mock py_nextbus module.
def mock_nextbus() -> Generator[MagicMock, None, None]: """Create a mock py_nextbus module.""" with patch("homeassistant.components.nextbus.config_flow.NextBusClient") as client: yield client
Create a mock py_nextbus module.
def mock_nextbus() -> Generator[MagicMock, None, None]: """Create a mock py_nextbus module.""" with patch("homeassistant.components.nextbus.coordinator.NextBusClient") as client: yield client
Create a mock of NextBusClient predictions.
def mock_nextbus_predictions( mock_nextbus: MagicMock, ) -> Generator[MagicMock, None, None]: """Create a mock of NextBusClient predictions.""" instance = mock_nextbus.return_value instance.get_predictions_for_multi_stops.return_value = BASIC_RESULTS return instance.get_predictions_for_multi_stops
Test input listification.
def test_listify(input: Any, expected: list[Any]) -> None: """Test input listification.""" assert listify(input) == expected
Test maybe getting the first thing from a list.
def test_maybe_first(input: list[Any] | None, expected: Any) -> None: """Test maybe getting the first thing from a list.""" assert maybe_first(input) == expected
Mock of NextcloudMonitor.
def mock_nextcloud_monitor() -> Mock: """Mock of NextcloudMonitor.""" return Mock( update=Mock(return_value=True), )
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.nextcloud.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Mock the NextDNS class.
def mock_nextdns(): """Mock the NextDNS class.""" with ( patch( "homeassistant.components.nextdns.NextDns.get_profiles", return_value=PROFILES, ), patch( "homeassistant.components.nextdns.NextDns.get_analytics_status", return_value=STATUS, ), patch( "homeassistant.components.nextdns.NextDns.get_analytics_encryption", return_value=ENCRYPTION, ), patch( "homeassistant.components.nextdns.NextDns.get_analytics_dnssec", return_value=DNSSEC, ), patch( "homeassistant.components.nextdns.NextDns.get_analytics_ip_versions", return_value=IP_VERSIONS, ), patch( "homeassistant.components.nextdns.NextDns.get_analytics_protocols", return_value=PROTOCOLS, ), patch( "homeassistant.components.nextdns.NextDns.get_settings", return_value=SETTINGS, ), patch( "homeassistant.components.nextdns.NextDns.connection_status", return_value=CONNECTION_STATUS, ), ): yield
Make sure we never actually run setup.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Make sure we never actually run setup.""" with patch( "homeassistant.components.nibe_heatpump.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Initialize coils for a climate group, with some default values.
def _setup_climate_group( coils: dict[int, Any], model: Model, climate_id: str ) -> tuple[ClimateCoilGroup, UnitCoilGroup]: """Initialize coils for a climate group, with some default values.""" climate = CLIMATE_COILGROUPS[model.series][climate_id] unit = UNIT_COILGROUPS[model.series]["main"] if climate.active_accessory is not None: coils[climate.active_accessory] = "ON" coils[climate.current] = 20.5 coils[climate.setpoint_heat] = 21.0 coils[climate.setpoint_cool] = 30.0 coils[climate.mixing_valve_state] = 20 coils[climate.use_room_sensor] = "ON" coils[unit.prio] = "OFF" coils[unit.cooling_with_room_sensor] = "ON" return climate, unit
Mock of the request function.
def mocked_request_function(url: str) -> dict[str, Any]: """Mock of the request function.""" dummy_response: dict[str, Any] = json.loads( load_fixture("sample_warnings.json", "nina") ) dummy_response_details: dict[str, Any] = json.loads( load_fixture("sample_warning_details.json", "nina") ) dummy_response_regions: dict[str, Any] = json.loads( load_fixture("sample_regions.json", "nina") ) dummy_response_labels: dict[str, Any] = json.loads( load_fixture("sample_labels.json", "nina") ) if "https://warnung.bund.de/api31/dashboard/" in url: return dummy_response if "https://warnung.bund.de/api/appdata/gsb/labels/de_labels.json" in url: return dummy_response_labels if ( url == "https://www.xrepository.de/api/xrepository/urn:de:bund:destatis:bevoelkerungsstatistik:schluessel:rs_2021-07-31/download/Regionalschl_ssel_2021-07-31.json" ): return dummy_response_regions warning_id = url.replace("https://warnung.bund.de/api31/warnings/", "").replace( ".json", "" ) return dummy_response_details[warning_id]