response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Mock a successful sensor detection using http library.
def mock_controller_connect_http_sens_detect(): """Mock a successful sensor detection using http library.""" with patch( f"{ASUSWRT_BASE}.bridge.AsusWrtHttpBridge._get_available_temperature_sensors", return_value=[*MOCK_TEMPERATURES_HTTP], ) as mock_sens_detect: yield mock_sens_detect
Mock call to socket gethostbyname function.
def mock_controller_patch_get_host(): """Mock call to socket gethostbyname function.""" with patch( f"{ASUSWRT_BASE}.config_flow.socket.gethostbyname", return_value="192.168.1.1" ) as get_host_mock: yield get_host_mock
Mock call to os path.isfile function.
def mock_controller_patch_is_file(): """Mock call to os path.isfile function.""" with patch( f"{ASUSWRT_BASE}.config_flow.os.path.isfile", return_value=True ) as is_file_mock: yield is_file_mock
Create device registry devices so the device tracker entities are enabled when added.
def create_device_registry_devices_fixture( hass: HomeAssistant, device_registry: dr.DeviceRegistry ): """Create device registry devices so the device tracker entities are enabled when added.""" config_entry = MockConfigEntry(domain="something_else") config_entry.add_to_hass(hass) for idx, device in enumerate((MOCK_MACS[2], MOCK_MACS[3])): device_registry.async_get_or_create( name=f"Device {idx}", config_entry_id=config_entry.entry_id, connections={(dr.CONNECTION_NETWORK_MAC, dr.format_mac(device))}, )
Create mock config entry with enabled sensors.
def _setup_entry(hass: HomeAssistant, config, sensors, unique_id=None): """Create mock config entry with enabled sensors.""" entity_reg = er.async_get(hass) # init config entry config_entry = MockConfigEntry( domain=DOMAIN, data=config, options={CONF_CONSIDER_HOME: 60}, unique_id=unique_id, ) # init variable obj_prefix = slugify(HOST) sensor_prefix = f"{sensor.DOMAIN}.{obj_prefix}" unique_id_prefix = slugify(unique_id or config_entry.entry_id) # Pre-enable the status sensor for sensor_key in sensors: sensor_id = slugify(sensor_key) entity_reg.async_get_or_create( sensor.DOMAIN, DOMAIN, f"{unique_id_prefix}_{sensor_id}", suggested_object_id=f"{obj_prefix}_{sensor_id}", config_entry=config_entry, disabled_by=None, ) return config_entry, sensor_prefix
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.atag.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Mock the requests to Atag endpoint.
def mock_connection( aioclient_mock: AiohttpClientMocker, authorized=True, conn_error=False ) -> None: """Mock the requests to Atag endpoint.""" if conn_error: aioclient_mock.post( "http://127.0.0.1:10000/pair", exc=AtagException, ) aioclient_mock.post( "http://127.0.0.1:10000/retrieve", exc=AtagException, ) return PAIR_REPLY["pair_reply"].update( {"acc_status": AUTHORIZED if authorized else UNAUTHORIZED} ) RECEIVE_REPLY["retrieve_reply"].update( {"acc_status": AUTHORIZED if authorized else UNAUTHORIZED} ) aioclient_mock.post( "http://127.0.0.1:10000/retrieve", json=RECEIVE_REPLY, ) aioclient_mock.post( "http://127.0.0.1:10000/update", json=UPDATE_REPLY, ) aioclient_mock.post( "http://127.0.0.1:10000/pair", json=PAIR_REPLY, )
Mock discovery to avoid loading the whole bluetooth stack.
def mock_discovery_fixture(): """Mock discovery to avoid loading the whole bluetooth stack.""" with patch( "homeassistant.components.august.discovery_flow.async_create_flow" ) as mock_discovery: yield mock_discovery
Return a default august config.
def _mock_get_config(brand: Brand = Brand.AUGUST): """Return a default august config.""" return { DOMAIN: { CONF_LOGIN_METHOD: "email", CONF_USERNAME: "mocked_username", CONF_PASSWORD: "mocked_password", CONF_BRAND: brand, } }
Mock an august authenticator.
def _mock_authenticator(auth_state): """Mock an august authenticator.""" authenticator = MagicMock() type(authenticator).state = PropertyMock(return_value=auth_state) return authenticator
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
Mock aiohttp.ClientSession.
def mock_session(): """Mock aiohttp.ClientSession.""" mocker = AiohttpClientMocker() with patch( "aiohttp.ClientSession", side_effect=lambda *args, **kwargs: mocker.create_session( asyncio.get_event_loop() ), ): yield mocker
Test we enforce valid scheme.
def test_client_id_scheme() -> None: """Test we enforce valid scheme.""" assert indieauth._parse_client_id("http://ex.com/") assert indieauth._parse_client_id("https://ex.com/") with pytest.raises(ValueError): indieauth._parse_client_id("ftp://ex.com")
Test we enforce valid path.
def test_client_id_path() -> None: """Test we enforce valid path.""" assert indieauth._parse_client_id("http://ex.com").path == "/" assert indieauth._parse_client_id("http://ex.com/hello").path == "/hello" assert ( indieauth._parse_client_id("http://ex.com/hello/.world").path == "/hello/.world" ) assert ( indieauth._parse_client_id("http://ex.com/hello./.world").path == "/hello./.world" ) with pytest.raises(ValueError): indieauth._parse_client_id("http://ex.com/.") with pytest.raises(ValueError): indieauth._parse_client_id("http://ex.com/hello/./yo") with pytest.raises(ValueError): indieauth._parse_client_id("http://ex.com/hello/../yo")
Test we enforce valid fragment.
def test_client_id_fragment() -> None: """Test we enforce valid fragment.""" with pytest.raises(ValueError): indieauth._parse_client_id("http://ex.com/#yoo")
Test we enforce valid username/password.
def test_client_id_user_pass() -> None: """Test we enforce valid username/password.""" with pytest.raises(ValueError): indieauth._parse_client_id("http://[email protected]/") with pytest.raises(ValueError): indieauth._parse_client_id("http://user:[email protected]/")
Test we enforce valid hostname.
def test_client_id_hostname() -> None: """Test we enforce valid hostname.""" assert indieauth._parse_client_id("http://www.home-assistant.io/") assert indieauth._parse_client_id("http://[::1]") assert indieauth._parse_client_id("http://127.0.0.1") assert indieauth._parse_client_id("http://10.0.0.0") assert indieauth._parse_client_id("http://10.255.255.255") assert indieauth._parse_client_id("http://172.16.0.0") assert indieauth._parse_client_id("http://172.31.255.255") assert indieauth._parse_client_id("http://192.168.0.0") assert indieauth._parse_client_id("http://192.168.255.255") with pytest.raises(ValueError): assert indieauth._parse_client_id("http://255.255.255.255/") with pytest.raises(ValueError): assert indieauth._parse_client_id("http://11.0.0.0/") with pytest.raises(ValueError): assert indieauth._parse_client_id("http://172.32.0.0/") with pytest.raises(ValueError): assert indieauth._parse_client_id("http://192.167.0.0/")
Test we update empty paths.
def test_parse_url_lowercase_host() -> None: """Test we update empty paths.""" assert indieauth._parse_url("http://ex.com/hello").path == "/hello" assert indieauth._parse_url("http://EX.COM/hello").hostname == "ex.com" parts = indieauth._parse_url("http://EX.COM:123/HELLO") assert parts.netloc == "ex.com:123" assert parts.path == "/HELLO"
Test we update empty paths.
def test_parse_url_path() -> None: """Test we update empty paths.""" assert indieauth._parse_url("http://ex.com").path == "/"
Return a mock credential.
def mock_credential(): """Return a mock credential.""" return Credentials( id="mock-credential-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, )
Test that the auth code store will not return expired tokens.
def test_auth_code_store_expiration( mock_credential, freezer: FrozenDateTimeFactory ) -> None: """Test that the auth code store will not return expired tokens.""" store, retrieve = auth._create_auth_code_store() client_id = "bla" now = utcnow() freezer.move_to(now) code = store(client_id, mock_credential) freezer.move_to(now + timedelta(minutes=10)) assert retrieve(client_id, code) is None freezer.move_to(now) code = store(client_id, mock_credential) freezer.move_to(now + timedelta(minutes=9, seconds=59)) assert retrieve(client_id, code) == mock_credential
Test we require credentials.
def test_auth_code_store_requires_credentials(mock_credential) -> None: """Test we require credentials.""" store, _retrieve = auth._create_auth_code_store() with pytest.raises(TypeError): store(None, MockUser()) store(None, mock_credential)
Stub copying the blueprints to the config folder.
def stub_blueprint_populate_autouse(stub_blueprint_populate: None) -> None: """Stub copying the blueprints to the config folder."""
Patch blueprint loading from a different source.
def patch_blueprint(blueprint_path: str, data_path): """Patch blueprint loading from a different source.""" orig_load = models.DomainBlueprints._load_blueprint @callback def mock_load_blueprint(self, path): if path != blueprint_path: pytest.fail(f"Unexpected blueprint {path}") return orig_load(self, path) return models.Blueprint( yaml.load_yaml(data_path), expected_domain=self.domain, path=path ) with patch( "homeassistant.components.blueprint.models.DomainBlueprints._load_blueprint", mock_load_blueprint, ): yield
Track calls to a mock service.
def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation")
Test module.__all__ is correctly set.
def test_all() -> None: """Test module.__all__ is correctly set.""" help_test_all(automation)
Test deprecated automation constants.
def test_deprecated_constants( caplog: pytest.LogCaptureFixture, constant_name: str, replacement: Any, ) -> None: """Test deprecated automation constants.""" import_and_test_deprecated_constant( caplog, automation, constant_name, replacement.__name__, replacement, "2025.1" )
Track calls to a mock service.
def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation")
Fixture representing devices returned by Awair Cloud API.
def cloud_devices_fixture(): """Fixture representing devices returned by Awair Cloud API.""" return json.loads(load_fixture("awair/cloud_devices.json"))
Fixture representing devices returned by Awair local API.
def local_devices_fixture(): """Fixture representing devices returned by Awair local API.""" return json.loads(load_fixture("awair/local_devices.json"))
Fixture representing data returned from Gen1 Awair device.
def gen1_data_fixture(): """Fixture representing data returned from Gen1 Awair device.""" return json.loads(load_fixture("awair/awair.json"))
Fixture representing data returned from Gen2 Awair device.
def gen2_data_fixture(): """Fixture representing data returned from Gen2 Awair device.""" return json.loads(load_fixture("awair/awair-r2.json"))
Fixture representing data returned from Awair glow device.
def glow_data_fixture(): """Fixture representing data returned from Awair glow device.""" return json.loads(load_fixture("awair/glow.json"))
Fixture representing data returned from Awair mint device.
def mint_data_fixture(): """Fixture representing data returned from Awair mint device.""" return json.loads(load_fixture("awair/mint.json"))
Fixture representing when no devices are found in Awair's cloud API.
def no_devicess_fixture(): """Fixture representing when no devices are found in Awair's cloud API.""" return json.loads(load_fixture("awair/no_devices.json"))
Fixture representing when Awair devices are offline.
def awair_offline_fixture(): """Fixture representing when Awair devices are offline.""" return json.loads(load_fixture("awair/awair-offline.json"))
Fixture representing data returned from Awair omni device.
def omni_data_fixture(): """Fixture representing data returned from Awair omni device.""" return json.loads(load_fixture("awair/omni.json"))
Fixture representing the User object returned from Awair's Cloud API.
def user_fixture(): """Fixture representing the User object returned from Awair's Cloud API.""" return json.loads(load_fixture("awair/user.json"))
Fixture representing data returned from Awair local device.
def local_data_fixture(): """Fixture representing data returned from Awair local device.""" return json.loads(load_fixture("awair/awair-local.json"))
Assert expected properties from a dict.
def assert_expected_properties( hass: HomeAssistant, registry: er.RegistryEntry, name, unique_id, state_value, attributes: dict, ): """Assert expected properties from a dict.""" entry = registry.async_get(name) assert entry.unique_id == unique_id state = hass.states.get(name) assert state assert state.state == state_value for attr, value in attributes.items(): assert state.attributes.get(attr) == value
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.axis.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Define a config entry fixture.
def config_entry_fixture( hass: HomeAssistant, config_entry_data: MappingProxyType[str, Any], config_entry_options: MappingProxyType[str, Any], config_entry_version: int, ) -> ConfigEntry: """Define a config entry fixture.""" config_entry = MockConfigEntry( domain=AXIS_DOMAIN, entry_id="676abe5b73621446e6550a2e86ffe3dd", unique_id=FORMATTED_MAC, data=config_entry_data, options=config_entry_options, version=config_entry_version, ) config_entry.add_to_hass(hass) return config_entry
Define a config entry version fixture.
def config_entry_version_fixture() -> int: """Define a config entry version fixture.""" return 3
Define a config entry data fixture.
def config_entry_data_fixture() -> MappingProxyType[str, Any]: """Define a config entry data fixture.""" return { CONF_HOST: DEFAULT_HOST, CONF_USERNAME: "root", CONF_PASSWORD: "pass", CONF_PORT: 80, CONF_MODEL: MODEL, CONF_NAME: NAME, }
Define a config entry options fixture.
def config_entry_options_fixture() -> MappingProxyType[str, Any]: """Define a config entry options fixture.""" return {}
Mock default Vapix requests responses.
def default_request_fixture( respx_mock: respx, port_management_payload: dict[str, Any], param_properties_payload: dict[str, Any], param_ports_payload: dict[str, Any], mqtt_status_code: int, ) -> Callable[[str], None]: """Mock default Vapix requests responses.""" def __mock_default_requests(host: str) -> None: respx_mock(base_url=f"http://{host}:80") if host != DEFAULT_HOST: respx.post("/axis-cgi/apidiscovery.cgi").respond( json=API_DISCOVERY_RESPONSE, ) respx.post("/axis-cgi/basicdeviceinfo.cgi").respond( json=BASIC_DEVICE_INFO_RESPONSE, ) respx.post("/axis-cgi/io/portmanagement.cgi").respond( json=port_management_payload, ) respx.post("/axis-cgi/mqtt/client.cgi").respond( json=MQTT_CLIENT_RESPONSE, status_code=mqtt_status_code ) respx.post("/axis-cgi/streamprofile.cgi").respond( json=STREAM_PROFILES_RESPONSE, ) respx.post("/axis-cgi/viewarea/info.cgi").respond(json=VIEW_AREAS_RESPONSE) respx.post( "/axis-cgi/param.cgi", data={"action": "list", "group": "root.Brand"}, ).respond( text=BRAND_RESPONSE, headers={"Content-Type": "text/plain"}, ) respx.post( "/axis-cgi/param.cgi", data={"action": "list", "group": "root.Image"}, ).respond( text=IMAGE_RESPONSE, headers={"Content-Type": "text/plain"}, ) respx.post( "/axis-cgi/param.cgi", data={"action": "list", "group": "root.Input"}, ).respond( text=PORTS_RESPONSE, headers={"Content-Type": "text/plain"}, ) respx.post( "/axis-cgi/param.cgi", data={"action": "list", "group": "root.IOPort"}, ).respond( text=param_ports_payload, headers={"Content-Type": "text/plain"}, ) respx.post( "/axis-cgi/param.cgi", data={"action": "list", "group": "root.Output"}, ).respond( text=PORTS_RESPONSE, headers={"Content-Type": "text/plain"}, ) respx.post( "/axis-cgi/param.cgi", data={"action": "list", "group": "root.Properties"}, ).respond( text=param_properties_payload, headers={"Content-Type": "text/plain"}, ) respx.post( "/axis-cgi/param.cgi", data={"action": "list", "group": "root.PTZ"}, ).respond( text=PTZ_RESPONSE, headers={"Content-Type": "text/plain"}, ) respx.post( "/axis-cgi/param.cgi", data={"action": "list", "group": "root.StreamProfile"}, ).respond( text=STREAM_PROFILES_RESPONSE, headers={"Content-Type": "text/plain"}, ) respx.post("/axis-cgi/applications/list.cgi").respond( text=APPLICATIONS_LIST_RESPONSE, headers={"Content-Type": "text/xml"}, ) respx.post("/local/fenceguard/control.cgi").respond(json=APP_VMD4_RESPONSE) respx.post("/local/loiteringguard/control.cgi").respond(json=APP_VMD4_RESPONSE) respx.post("/local/motionguard/control.cgi").respond(json=APP_VMD4_RESPONSE) respx.post("/local/vmd/control.cgi").respond(json=APP_VMD4_RESPONSE) respx.post("/local/objectanalytics/control.cgi").respond(json=APP_AOA_RESPONSE) return __mock_default_requests
Additional Apidiscovery items.
def api_discovery_items() -> dict[str, Any]: """Additional Apidiscovery items.""" return {}
Apidiscovery mock response.
def api_discovery_fixture(api_discovery_items: dict[str, Any]) -> None: """Apidiscovery mock response.""" data = deepcopy(API_DISCOVERY_RESPONSE) if api_discovery_items: data["data"]["apiList"].append(api_discovery_items) respx.post(f"http://{DEFAULT_HOST}:80/axis-cgi/apidiscovery.cgi").respond(json=data)
Property parameter data.
def io_port_management_data_fixture() -> dict[str, Any]: """Property parameter data.""" return PORT_MANAGEMENT_RESPONSE
Property parameter data.
def param_properties_data_fixture() -> dict[str, Any]: """Property parameter data.""" return PROPERTIES_RESPONSE
Property parameter data.
def param_ports_data_fixture() -> dict[str, Any]: """Property parameter data.""" return PORTS_RESPONSE
Property parameter data.
def mqtt_status_code_fixture(): """Property parameter data.""" return 200
Mock default Vapix requests responses.
def default_vapix_requests_fixture(mock_vapix_requests: Callable[[str], None]) -> None: """Mock default Vapix requests responses.""" mock_vapix_requests(DEFAULT_HOST)
No real RTSP communication allowed.
def mock_axis_rtspclient() -> Generator[Callable[[dict | None, str], None], None, None]: """No real RTSP communication allowed.""" with patch("axis.stream_manager.RTSPClient") as rtsp_client_mock: rtsp_client_mock.return_value.session.state = State.STOPPED async def start_stream() -> None: """Set state to playing when calling RTSPClient.start.""" rtsp_client_mock.return_value.session.state = State.PLAYING rtsp_client_mock.return_value.start = start_stream def stop_stream() -> None: """Set state to stopped when calling RTSPClient.stop.""" rtsp_client_mock.return_value.session.state = State.STOPPED rtsp_client_mock.return_value.stop = stop_stream def make_rtsp_call(data: dict | None = None, state: str = "") -> None: """Generate a RTSP call.""" axis_streammanager_session_callback = rtsp_client_mock.call_args[0][4] if data: rtsp_client_mock.return_value.rtp.data = data axis_streammanager_session_callback(signal=Signal.DATA) elif state: axis_streammanager_session_callback(signal=state) else: raise NotImplementedError yield make_rtsp_call
Fixture to allow mocking received RTSP events.
def mock_rtsp_event( mock_axis_rtspclient: Callable[[dict | None, str], None], ) -> Callable[[str, str, str, str, str, str], None]: """Fixture to allow mocking received RTSP events.""" def send_event( topic: str, data_type: str, data_value: str, operation: str = "Initialized", source_name: str = "", source_idx: str = "", ) -> None: source = "" if source_name != "" and source_idx != "": source = f'<tt:SimpleItem Name="{source_name}" Value="{source_idx}"/>' event = f"""<?xml version="1.0" encoding="UTF-8"?> <tt:MetadataStream xmlns:tt="http://www.onvif.org/ver10/schema"> <tt:Event> <wsnt:NotificationMessage xmlns:tns1="http://www.onvif.org/ver10/topics" xmlns:tnsaxis="http://www.axis.com/2009/event/topics" xmlns:wsnt="http://docs.oasis-open.org/wsn/b-2" xmlns:wsa5="http://www.w3.org/2005/08/addressing"> <wsnt:Topic Dialect="http://docs.oasis-open.org/wsn/t-1/TopicExpression/Simple"> {topic} </wsnt:Topic> <wsnt:ProducerReference> <wsa5:Address> uri://bf32a3b9-e5e7-4d57-a48d-1b5be9ae7b16/ProducerReference </wsa5:Address> </wsnt:ProducerReference> <wsnt:Message> <tt:Message UtcTime="2020-11-03T20:21:48.346022Z" PropertyOperation="{operation}"> <tt:Source>{source}</tt:Source> <tt:Key></tt:Key> <tt:Data> <tt:SimpleItem Name="{data_type}" Value="{data_value}"/> </tt:Data> </tt:Message> </wsnt:Message> </wsnt:NotificationMessage> </tt:Event> </tt:MetadataStream> """ mock_axis_rtspclient(data=event.encode("utf-8")) return send_event
Fixture to allow mocking RTSP state signalling.
def mock_rtsp_signal_state( mock_axis_rtspclient: Callable[[dict | None, str], None], ) -> Callable[[bool], None]: """Fixture to allow mocking RTSP state signalling.""" def send_signal(connected: bool) -> None: """Signal state change of RTSP connection.""" signal = Signal.PLAYING if connected else Signal.FAILED mock_axis_rtspclient(state=signal) return send_signal
Mock async_forward_entry_setups.
def hass_mock_forward_entry_setup(hass): """Mock async_forward_entry_setups.""" with patch.object( hass.config_entries, "async_forward_entry_setups" ) as forward_mock: yield forward_mock
Available lights.
def light_control_items() -> list[dict[str, Any]]: """Available lights.""" return [ { "lightID": "led0", "lightType": "IR", "enabled": True, "synchronizeDayNightMode": True, "lightState": False, "automaticIntensityMode": False, "automaticAngleOfIlluminationMode": False, "nrOfLEDs": 1, "error": False, "errorInfo": "", } ]
Light control mock response.
def light_control_fixture(light_control_items: list[dict[str, Any]]) -> None: """Light control mock response.""" data = { "apiVersion": "1.1", "context": CONTEXT, "method": "getLightInformation", "data": {"items": light_control_items}, } respx.post( f"http://{DEFAULT_HOST}:80/axis-cgi/lightcontrol.cgi", json={ "apiVersion": "1.1", "context": CONTEXT, "method": "getLightInformation", }, ).respond( json=data, )
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.azure_devops.async_setup_entry", return_value=True, ) as mock_setup_entry: yield mock_setup_entry
Mock azure event hub properties, used to test the connection.
def mock_get_eventhub_properties_fixture(): """Mock azure event hub properties, used to test the connection.""" with patch(f"{PRODUCER_PATH}.get_eventhub_properties") as get_eventhub_properties: yield get_eventhub_properties
Return an empty filter.
def mock_filter_schema(): """Return an empty filter.""" return {}
Mock send_batch.
def mock_send_batch_fixture(): """Mock send_batch.""" with patch(f"{PRODUCER_PATH}.send_batch") as mock_send_batch: yield mock_send_batch
Mock the azure event hub producer client.
def mock_client_fixture(mock_send_batch): """Mock the azure event hub producer client.""" with patch(f"{PRODUCER_PATH}.close") as mock_close: yield ( mock_send_batch, mock_close, )
Mock batch creator and return mocked batch object.
def mock_create_batch_fixture(): """Mock batch creator and return mocked batch object.""" mock_batch = MagicMock() with patch(f"{PRODUCER_PATH}.create_batch", return_value=mock_batch): yield mock_batch
Mock AEH from connection string creation.
def mock_from_connection_string_fixture(): """Mock AEH from connection string creation.""" mock_aeh = MagicMock(spec=EventHubProducerClient) mock_aeh.__aenter__.return_value = mock_aeh with patch( f"{PRODUCER_PATH}.from_connection_string", return_value=mock_aeh, ) as from_conn_string: yield from_conn_string
Mock the setup entry call, used for config flow tests.
def mock_setup_entry(): """Mock the setup entry call, used for config flow tests.""" with patch( f"{AZURE_EVENT_HUB_PATH}.async_setup_entry", return_value=True ) as setup_entry: yield setup_entry
Non-async proxy for the *_access_token fixture. Workaround for https://github.com/pytest-dev/pytest-asyncio/issues/112
def sync_access_token_proxy( access_token_fixture_name: str, request: pytest.FixtureRequest, ) -> str: """Non-async proxy for the *_access_token fixture. Workaround for https://github.com/pytest-dev/pytest-asyncio/issues/112 """ return request.getfixturevalue(access_token_fixture_name)
Mock out the BAF Device object.
def _patch_device_config_flow(side_effect=None): """Mock out the BAF Device object.""" def _create_mock_baf(*args, **kwargs): return MockBAFDevice(side_effect) return patch("homeassistant.components.baf.config_flow.Device", _create_mock_baf)
Mock out the BAF Device object.
def _patch_device_init(side_effect=None): """Mock out the BAF Device object.""" def _create_mock_baf(*args, **kwargs): return MockBAFDevice(side_effect) return patch("homeassistant.components.baf.Device", _create_mock_baf)
Mock balboa spa client.
def client_fixture() -> Generator[MagicMock, None, None]: """Mock balboa spa client.""" with patch( "homeassistant.components.balboa.SpaClient", autospec=True ) as mock_balboa: client = mock_balboa.return_value callback: list[Callable] = [] def on(_, _callback: Callable): callback.append(_callback) return lambda: None def emit(_): for _cb in callback: _cb() client.on.side_effect = on client.emit.side_effect = emit client.model = "FakeSpa" client.mac_address = "ef:ef:ef:c0:ff:ee" client.software_version = "M0 V0.0" client.blowers = [] client.circulation_pump.state = 0 client.filter_cycle_1_running = False client.filter_cycle_2_running = False client.temperature_unit = 1 client.temperature = 10 client.temperature_minimum = 10 client.temperature_maximum = 40 client.target_temperature = 40 client.heat_mode.state = HeatMode.READY client.heat_mode.set_state = AsyncMock() client.heat_mode.options = list(HeatMode)[:2] client.heat_state = 2 client.lights = [] client.pumps = [] client.temperature_range.state = LowHighRange.LOW yield client
Return a mock pump.
def mock_pump(client: MagicMock): """Return a mock pump.""" pump = MagicMock(SpaControl) async def set_state(state: OffLowHighState): pump.state = state pump.client = client pump.index = 0 pump.state = OffLowHighState.OFF pump.set_state = set_state pump.options = list(OffLowHighState) client.pumps.append(pump) return pump
Return a mock light.
def mock_light(client: MagicMock): """Return a mock light.""" light = MagicMock(SpaControl) async def set_state(state: OffOnState): light.state = state light.client = client light.index = 0 light.state = OffOnState.OFF light.set_state = set_state light.options = list(OffOnState) client.lights.append(light) return light
Return a mock switch.
def mock_select(client: MagicMock): """Return a mock switch.""" select = MagicMock(SpaControl) async def set_state(state: LowHighRange): select.state = state # mock the spacontrol state select.client = client select.state = LowHighRange.LOW select.set_state = set_state client.temperature_range = select return select
Mock config entry.
def mock_config_entry(): """Mock config entry.""" return MockConfigEntry( domain=DOMAIN, unique_id=TEST_SERIAL_NUMBER, data=TEST_DATA_CREATE_ENTRY, title=TEST_NAME, )
Mock MozartClient.
def mock_mozart_client() -> Generator[AsyncMock, None, None]: """Mock MozartClient.""" with ( patch( "homeassistant.components.bang_olufsen.MozartClient", autospec=True ) as mock_client, patch( "homeassistant.components.bang_olufsen.config_flow.MozartClient", new=mock_client, ), ): client = mock_client.return_value client.get_beolink_self = AsyncMock() client.get_beolink_self.return_value = BeolinkPeer( friendly_name=TEST_FRIENDLY_NAME, jid=TEST_JID_1 ) yield client
Mock successful setup entry.
def mock_setup_entry(): """Mock successful setup entry.""" with patch( "homeassistant.components.bang_olufsen.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Return mock binary sensors.
def mock_binary_sensor_entities() -> dict[str, MockBinarySensor]: """Return mock binary sensors.""" return { device_class: MockBinarySensor( name=f"{device_class} sensor", is_on=True, unique_id=f"unique_{device_class}", device_class=device_class, ) for device_class in BinarySensorDeviceClass }
Stub copying the blueprints to the config folder.
def stub_blueprint_populate_autouse(stub_blueprint_populate: None) -> None: """Stub copying the blueprints to the config folder."""
Track calls to a mock service.
def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation")
Stub copying the blueprints to the config folder.
def stub_blueprint_populate_autouse(stub_blueprint_populate: None) -> None: """Stub copying the blueprints to the config folder."""
Track calls to a mock service.
def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation")
Test binary sensor state.
def test_state() -> None: """Test binary sensor state.""" sensor = binary_sensor.BinarySensorEntity() assert sensor.state is None with mock.patch( "homeassistant.components.binary_sensor.BinarySensorEntity.is_on", new=False, ): assert binary_sensor.BinarySensorEntity().state == STATE_OFF with mock.patch( "homeassistant.components.binary_sensor.BinarySensorEntity.is_on", new=True, ): assert binary_sensor.BinarySensorEntity().state == STATE_ON
Mock config flow.
def config_flow_fixture(hass: HomeAssistant) -> Generator[None, None, None]: """Mock config flow.""" mock_platform(hass, f"{TEST_DOMAIN}.config_flow") with mock_config_flow(TEST_DOMAIN, MockFlow): yield
Test module.__all__ is correctly set.
def test_all() -> None: """Test module.__all__ is correctly set.""" help_test_all(binary_sensor)
Test deprecated binary sensor device classes.
def test_deprecated_constant_device_class( caplog: pytest.LogCaptureFixture, device_class: binary_sensor.BinarySensorDeviceClass, ) -> None: """Test deprecated binary sensor device classes.""" import_and_test_deprecated_constant_enum( caplog, binary_sensor, device_class, "DEVICE_CLASS_", "2025.1" )
Test valid schema.
def test_valid_serial_schema() -> None: """Test valid schema.""" valid_schema = { "platform": "blackbird", "port": "/dev/ttyUSB0", "zones": { 1: {"name": "a"}, 2: {"name": "a"}, 3: {"name": "a"}, 4: {"name": "a"}, 5: {"name": "a"}, 6: {"name": "a"}, 7: {"name": "a"}, 8: {"name": "a"}, }, "sources": { 1: {"name": "a"}, 2: {"name": "a"}, 3: {"name": "a"}, 4: {"name": "a"}, 5: {"name": "a"}, 6: {"name": "a"}, 7: {"name": "a"}, 8: {"name": "a"}, }, } PLATFORM_SCHEMA(valid_schema)
Test valid schema.
def test_valid_socket_schema() -> None: """Test valid schema.""" valid_schema = { "platform": "blackbird", "host": "192.168.1.50", "zones": { 1: {"name": "a"}, 2: {"name": "a"}, 3: {"name": "a"}, 4: {"name": "a"}, 5: {"name": "a"}, }, "sources": { 1: {"name": "a"}, 2: {"name": "a"}, 3: {"name": "a"}, 4: {"name": "a"}, }, } PLATFORM_SCHEMA(valid_schema)
Test invalid schemas.
def test_invalid_schemas() -> None: """Test invalid schemas.""" schemas = ( {}, # Empty None, # None # Port and host used concurrently { "platform": "blackbird", "port": "/dev/ttyUSB0", "host": "192.168.1.50", "name": "Name", "zones": {1: {"name": "a"}}, "sources": {1: {"name": "b"}}, }, # Port or host missing { "platform": "blackbird", "name": "Name", "zones": {1: {"name": "a"}}, "sources": {1: {"name": "b"}}, }, # Invalid zone number { "platform": "blackbird", "port": "/dev/ttyUSB0", "name": "Name", "zones": {11: {"name": "a"}}, "sources": {1: {"name": "b"}}, }, # Invalid source number { "platform": "blackbird", "port": "/dev/ttyUSB0", "name": "Name", "zones": {1: {"name": "a"}}, "sources": {9: {"name": "b"}}, }, # Zone missing name { "platform": "blackbird", "port": "/dev/ttyUSB0", "name": "Name", "zones": {1: {}}, "sources": {1: {"name": "b"}}, }, # Source missing name { "platform": "blackbird", "port": "/dev/ttyUSB0", "name": "Name", "zones": {1: {"name": "a"}}, "sources": {1: {}}, }, ) for value in schemas: with pytest.raises(vol.MultipleInvalid): PLATFORM_SCHEMA(value)
Return a mock blackbird instance.
def mock_blackbird(): """Return a mock blackbird instance.""" return MockBlackbird()
Return the media player entity.
def media_player_entity(hass, setup_blackbird): """Return the media player entity.""" media_player = hass.data[DATA_BLACKBIRD]["/dev/ttyUSB0-3"] media_player.hass = hass media_player.entity_id = "media_player.zone_3" return media_player
Patch the blebox_uniapi Products class.
def patch_product_identify(path=None, **kwargs): """Patch the blebox_uniapi Products class.""" patcher = patch.object( blebox_uniapi.box.Box, "async_from_host", AsyncMock(**kwargs) ) patcher.start() return blebox_uniapi.box.Box
Mock a product returning the given features.
def setup_product_mock(category, feature_mocks, path=None): """Mock a product returning the given features.""" product_mock = mock.create_autospec( blebox_uniapi.box.Box, True, True, features=None ) type(product_mock).features = PropertyMock(return_value={category: feature_mocks}) for feature in feature_mocks: type(feature).product = PropertyMock(return_value=product_mock) patch_product_identify(path, return_value=product_mock) return product_mock
Mock just the feature, without the product setup.
def mock_only_feature(spec, set_spec: bool = True, **kwargs): """Mock just the feature, without the product setup.""" return mock.create_autospec(spec, set_spec, True, **kwargs)
Mock a feature along with whole product setup.
def mock_feature(category, spec, set_spec: bool = True, **kwargs): """Mock a feature along with whole product setup.""" feature_mock = mock_only_feature(spec, set_spec, **kwargs) feature_mock.async_update = AsyncMock() product = setup_product_mock(category, [feature_mock]) type(feature_mock.product).name = PropertyMock(return_value="Some name") type(feature_mock.product).type = PropertyMock(return_value="some type") type(feature_mock.product).model = PropertyMock(return_value="some model") type(feature_mock.product).brand = PropertyMock(return_value="BleBox") type(feature_mock.product).firmware_version = PropertyMock(return_value="1.23") type(feature_mock.product).unique_id = PropertyMock(return_value="abcd0123ef5678") type(feature_mock).product = PropertyMock(return_value=product) return feature_mock
Return a Mock of the HA entity config.
def mock_config(ip_address="172.100.123.4"): """Return a Mock of the HA entity config.""" return MockConfigEntry(domain=DOMAIN, data={CONF_HOST: ip_address, CONF_PORT: 80})
Create hass config fixture.
def config_fixture(): """Create hass config fixture.""" return {DOMAIN: {CONF_HOST: "172.100.123.4", CONF_PORT: 80}}
Return an entity wrapper from given fixture name.
def feature_fixture(request): """Return an entity wrapper from given fixture name.""" return request.getfixturevalue(request.param)
Return a default air quality fixture.
def airsensor_fixture() -> tuple[AsyncMock, str]: """Return a default air quality fixture.""" feature: AsyncMock = mock_feature( "binary_sensors", blebox_uniapi.binary_sensor.Rain, unique_id="BleBox-windRainSensor-ea68e74f4f49-0.rain", full_name="windRainSensor-0.rain", device_class="moisture", ) product = feature.product type(product).name = PropertyMock(return_value="My rain sensor") type(product).model = PropertyMock(return_value="rainSensor") return feature, "binary_sensor.windrainsensor_0_rain"
Return simple button entity mock.
def tv_lift_box_fixture(caplog): """Return simple button entity mock.""" caplog.set_level(logging.ERROR) feature = mock_feature( "buttons", blebox_uniapi.button.Button, unique_id="BleBox-tvLiftBox-4a3fdaad90aa-open_or_stop", full_name="tvLiftBox-open_or_stop", control_type=blebox_uniapi.button.ControlType.OPEN, ) product = feature.product type(product).name = PropertyMock(return_value="My tvLiftBox") type(product).model = PropertyMock(return_value="tvLiftBox") type(product)._query_string = PropertyMock(return_value="open_or_stop") return (feature, "button.tvliftbox_open_or_stop")