def _create_mocked_hole(raise_exception=False): mocked_hole = MagicMock() type(mocked_hole).get_data = AsyncMock( side_effect=HoleError("") if raise_exception else None) type(mocked_hole).get_versions = AsyncMock( side_effect=HoleError("") if raise_exception else None) type(mocked_hole).enable = AsyncMock() type(mocked_hole).disable = AsyncMock() mocked_hole.data = ZERO_DATA mocked_hole.versions = SAMPLE_VERSIONS return mocked_hole
async def test_switch(opp, caplog): """Test Pi-hole switch.""" mocked_hole = _create_mocked_hole() with _patch_config_flow_hole(mocked_hole), _patch_init_hole(mocked_hole): assert await async_setup_component( opp, pi_hole.DOMAIN, {pi_hole.DOMAIN: [{ "host": "pi.hole1", "api_key": "1" }]}, ) await opp.async_block_till_done() await opp.services.async_call( switch.DOMAIN, switch.SERVICE_TURN_ON, {"entity_id": SWITCH_ENTITY_ID}, blocking=True, ) mocked_hole.enable.assert_called_once() await opp.services.async_call( switch.DOMAIN, switch.SERVICE_TURN_OFF, {"entity_id": SWITCH_ENTITY_ID}, blocking=True, ) mocked_hole.disable.assert_called_once_with(True) # Failed calls type(mocked_hole).enable = AsyncMock(side_effect=HoleError("Error1")) await opp.services.async_call( switch.DOMAIN, switch.SERVICE_TURN_ON, {"entity_id": SWITCH_ENTITY_ID}, blocking=True, ) type(mocked_hole).disable = AsyncMock(side_effect=HoleError("Error2")) await opp.services.async_call( switch.DOMAIN, switch.SERVICE_TURN_OFF, {"entity_id": SWITCH_ENTITY_ID}, blocking=True, ) errors = [x for x in caplog.records if x.levelno == logging.ERROR] assert errors[-2].message == "Unable to enable Pi-hole: Error1" assert errors[-1].message == "Unable to disable Pi-hole: Error2"