async def test_reload(opp, opp_admin_user, opp_read_only_user): """Test reload service.""" count_start = len(opp.states.async_entity_ids()) assert await async_setup_component( opp, DOMAIN, {DOMAIN: {"test_1": {"initial": "test 1"}, "test_2": {"initial": "test 2"}}}, ) assert count_start + 2 == len(opp.states.async_entity_ids()) state_1 = opp.states.get("input_text.test_1") state_2 = opp.states.get("input_text.test_2") state_3 = opp.states.get("input_text.test_3") assert state_1 is not None assert state_2 is not None assert state_3 is None assert state_1.state == "test 1" assert state_2.state == "test 2" assert state_1.attributes[ATTR_MIN] == 0 assert state_2.attributes[ATTR_MAX] == 100 with patch( "openpeerpower.config.load_yaml_config_file", autospec=True, return_value={ DOMAIN: { "test_2": {"initial": "test reloaded", ATTR_MIN: 12}, "test_3": {"initial": "test 3", ATTR_MAX: 21}, } }, ): with pytest.raises(Unauthorized): await opp.services.async_call( DOMAIN, SERVICE_RELOAD, blocking=True, context=Context(user_id=opp_read_only_user.id), ) await opp.services.async_call( DOMAIN, SERVICE_RELOAD, blocking=True, context=Context(user_id=opp_admin_user.id), ) await opp.async_block_till_done() assert count_start + 2 == len(opp.states.async_entity_ids()) state_1 = opp.states.get("input_text.test_1") state_2 = opp.states.get("input_text.test_2") state_3 = opp.states.get("input_text.test_3") assert state_1 is None assert state_2 is not None assert state_3 is not None assert state_2.attributes[ATTR_MIN] == 12 assert state_3.attributes[ATTR_MAX] == 21
async def test_counter_max(opp, opp_admin_user): """Test that max works.""" assert await async_setup_component( opp, "counter", {"counter": {"test": {"maximum": "0", "initial": "0"}}} ) state = opp.states.get("counter.test") assert state is not None assert state.state == "0" await opp.services.async_call( "counter", "increment", {"entity_id": state.entity_id}, True, Context(user_id=opp_admin_user.id), ) state2 = opp.states.get("counter.test") assert state2 is not None assert state2.state == "0" await opp.services.async_call( "counter", "decrement", {"entity_id": state.entity_id}, True, Context(user_id=opp_admin_user.id), ) state2 = opp.states.get("counter.test") assert state2 is not None assert state2.state == "-1"
def context(request: web.Request) -> Context: """Generate a context from a request.""" user = request.get("opp_user") if user is None: return Context() return Context(user_id=user.id)
async def test_turn_on_with_timer_service( opp: OpenPeerPower, mock_bridge: Generator[None, Any, None], mock_api: Generator[None, Any, None], opp_owner_user: MockUser, ) -> None: """Test the set_auto_off service.""" assert await async_setup_component(opp, DOMAIN, MANDATORY_CONFIGURATION) await opp.async_block_till_done() assert opp.services.has_service(DOMAIN, SERVICE_TURN_ON_WITH_TIMER_NAME) await opp.services.async_call( DOMAIN, SERVICE_TURN_ON_WITH_TIMER_NAME, { CONF_ENTITY_ID: SWITCH_ENTITY_ID, CONF_TIMER_MINUTES: DUMMY_TIMER_MINUTES_SET }, blocking=True, context=Context(user_id=opp_owner_user.id), ) with raises(UnknownUser) as unknown_user_exc: await opp.services.async_call( DOMAIN, SERVICE_TURN_ON_WITH_TIMER_NAME, { CONF_ENTITY_ID: SWITCH_ENTITY_ID, CONF_TIMER_MINUTES: DUMMY_TIMER_MINUTES_SET, }, blocking=True, context=Context(user_id="not_real_user"), ) assert unknown_user_exc.type is UnknownUser with patch( "openpeerpower.components.switcher_kis.switch.SwitcherV2Api.control_device" ) as mock_control_device: await opp.services.async_call( DOMAIN, SERVICE_TURN_ON_WITH_TIMER_NAME, { CONF_ENTITY_ID: SWITCH_ENTITY_ID, CONF_TIMER_MINUTES: DUMMY_TIMER_MINUTES_SET, }, ) await opp.async_block_till_done() mock_control_device.assert_called_once_with( COMMAND_ON, int(DUMMY_TIMER_MINUTES_SET))
async def test_set_auto_off_service( opp: OpenPeerPower, mock_bridge: Generator[None, Any, None], mock_api: Generator[None, Any, None], opp_owner_user: MockUser, ) -> None: """Test the set_auto_off service.""" assert await async_setup_component(opp, DOMAIN, MANDATORY_CONFIGURATION) await opp.async_block_till_done() assert opp.services.has_service(DOMAIN, SERVICE_SET_AUTO_OFF_NAME) await opp.services.async_call( DOMAIN, SERVICE_SET_AUTO_OFF_NAME, { CONF_ENTITY_ID: SWITCH_ENTITY_ID, CONF_AUTO_OFF: DUMMY_AUTO_OFF_SET }, blocking=True, context=Context(user_id=opp_owner_user.id), ) with raises(UnknownUser) as unknown_user_exc: await opp.services.async_call( DOMAIN, SERVICE_SET_AUTO_OFF_NAME, { CONF_ENTITY_ID: SWITCH_ENTITY_ID, CONF_AUTO_OFF: DUMMY_AUTO_OFF_SET }, blocking=True, context=Context(user_id="not_real_user"), ) assert unknown_user_exc.type is UnknownUser with patch( "openpeerpower.components.switcher_kis.switch.SwitcherV2Api.set_auto_shutdown" ) as mock_set_auto_shutdown: await opp.services.async_call( DOMAIN, SERVICE_SET_AUTO_OFF_NAME, { CONF_ENTITY_ID: SWITCH_ENTITY_ID, CONF_AUTO_OFF: DUMMY_AUTO_OFF_SET }, ) await opp.async_block_till_done() mock_set_auto_shutdown.assert_called_once_with( time_period_str(DUMMY_AUTO_OFF_SET))
async def test_state_with_context(opp): """Test that context is forwarded.""" opp.states.async_set(ENTITY_1, STATE_OFF, {}) turn_on_calls = async_mock_service(opp, DOMAIN, SERVICE_TURN_ON) turn_off_calls = async_mock_service(opp, DOMAIN, SERVICE_TURN_OFF) mode_calls = async_mock_service(opp, DOMAIN, SERVICE_SET_MODE) humidity_calls = async_mock_service(opp, DOMAIN, SERVICE_SET_HUMIDITY) context = Context() await async_reproduce_states( opp, [State(ENTITY_1, STATE_ON, { ATTR_MODE: MODE_AWAY, ATTR_HUMIDITY: 45 })], context=context, ) await opp.async_block_till_done() assert len(turn_on_calls) == 1 assert turn_on_calls[0].data == {"entity_id": ENTITY_1} assert turn_on_calls[0].context == context assert len(turn_off_calls) == 0 assert len(mode_calls) == 1 assert mode_calls[0].data == {"entity_id": ENTITY_1, "mode": "away"} assert mode_calls[0].context == context assert len(humidity_calls) == 1 assert humidity_calls[0].data == {"entity_id": ENTITY_1, "humidity": 45} assert humidity_calls[0].context == context
async def assert_request_calls_service( namespace, name, endpoint, service, opp, response_type="Response", payload=None, instance=None, ): """Assert an API request calls a opp.service.""" context = Context() request = get_new_request(namespace, name, endpoint) if payload: request["directive"]["payload"] = payload if instance: request["directive"]["header"]["instance"] = instance domain, service_name = service.split(".") calls = async_mock_service(opp, domain, service_name) msg = await smart_home.async_handle_message(opp, DEFAULT_CONFIG, request, context) await opp.async_block_till_done() assert len(calls) == 1 call = calls[0] assert "event" in msg assert call.data["entity_id"] == endpoint.replace("#", ".") assert msg["event"]["header"]["name"] == response_type assert call.context == context return call, msg
async def test_input_datetime_context(opp, opp_admin_user): """Test that input_datetime context works.""" assert await async_setup_component( opp, "input_datetime", {"input_datetime": { "only_date": { "has_date": True } }}) state = opp.states.get("input_datetime.only_date") assert state is not None await opp.services.async_call( "input_datetime", "set_datetime", { "entity_id": state.entity_id, "date": "2018-01-02" }, blocking=True, context=Context(user_id=opp_admin_user.id), ) state2 = opp.states.get("input_datetime.only_date") assert state2 is not None assert state.state != state2.state assert state2.context.user_id == opp_admin_user.id
async def async_handle( opp: OpenPeerPowerType, platform: str, intent_type: str, slots: Optional[_SlotsType] = None, text_input: Optional[str] = None, context: Optional[Context] = None, ) -> "IntentResponse": """Handle an intent.""" handler: IntentHandler = opp.data.get(DATA_KEY, {}).get(intent_type) if handler is None: raise UnknownIntent(f"Unknown intent {intent_type}") if context is None: context = Context() intent = Intent(opp, platform, intent_type, slots or {}, text_input, context) try: _LOGGER.info("Triggering intent handler %s", handler) result = await handler.async_handle(intent) return result except vol.Invalid as err: _LOGGER.warning("Received invalid slot info for %s: %s", intent_type, err) raise InvalidSlotInfo( f"Received invalid slot info for {intent_type}") from err except IntentHandleError: raise except Exception as err: raise IntentUnexpectedError(f"Error handling {intent_type}") from err
async def test_trigger_service(opp, calls): """Test the automation trigger service.""" assert await async_setup_component( opp, automation.DOMAIN, { automation.DOMAIN: { "alias": "hello", "trigger": {"platform": "event", "event_type": "test_event"}, "action": { "service": "test.automation", "data_template": {"trigger": "{{ trigger }}"}, }, } }, ) context = Context() await opp.services.async_call( "automation", "trigger", {"entity_id": "automation.hello"}, blocking=True, context=context, ) assert len(calls) == 1 assert calls[0].data.get("trigger") == {"platform": None} assert calls[0].context.parent_id is context.id
async def test_if_fires_on_entity_change_below(opp, calls): """Test the firing with changed entity.""" context = Context() assert await async_setup_component( opp, automation.DOMAIN, { automation.DOMAIN: { "trigger": { "platform": "numeric_state", "entity_id": "test.entity", "below": 10, }, "action": { "service": "test.automation" }, } }, ) # 9 is below 10 opp.states.async_set("test.entity", 9, context=context) await opp.async_block_till_done() assert 1 == len(calls) assert calls[0].context.parent_id == context.id # Set above 12 so the automation will fire again opp.states.async_set("test.entity", 12) await common.async_turn_off(opp) await opp.async_block_till_done() opp.states.async_set("test.entity", 9) await opp.async_block_till_done() assert 1 == len(calls)
async def test_if_fires_on_event(opp, calls): """Test the firing of events.""" context = Context() assert await async_setup_component( opp, automation.DOMAIN, { automation.DOMAIN: { "trigger": { "platform": "event", "event_type": "test_event" }, "action": { "service": "test.automation" }, } }, ) opp.bus.async_fire("test_event", context=context) await opp.async_block_till_done() assert 1 == len(calls) assert calls[0].context.parent_id == context.id await common.async_turn_off(opp) await opp.async_block_till_done() opp.bus.async_fire("test_event") await opp.async_block_till_done() assert 1 == len(calls)
async def test_input_number_context(opp, opp_admin_user): """Test that input_number context works.""" assert await async_setup_component( opp, "input_number", {"input_number": { "b1": { "min": 0, "max": 100 } }}) state = opp.states.get("input_number.b1") assert state is not None await opp.services.async_call( "input_number", "increment", {"entity_id": state.entity_id}, True, Context(user_id=opp_admin_user.id), ) state2 = opp.states.get("input_number.b1") assert state2 is not None assert state.state != state2.state assert state2.context.user_id == opp_admin_user.id
async def test_input_select_context(opp, opp_admin_user): """Test that input_select context works.""" assert await async_setup_component( opp, "input_select", { "input_select": { "s1": { "options": ["first option", "middle option", "last option"] } } }, ) state = opp.states.get("input_select.s1") assert state is not None await opp.services.async_call( "input_select", "select_next", {"entity_id": state.entity_id}, True, Context(user_id=opp_admin_user.id), ) state2 = opp.states.get("input_select.s1") assert state2 is not None assert state.state != state2.state assert state2.context.user_id == opp_admin_user.id
async def test_if_fires_on_multiple_events(opp, calls): """Test the firing of events.""" context = Context() assert await async_setup_component( opp, automation.DOMAIN, { automation.DOMAIN: { "trigger": { "platform": "event", "event_type": ["test_event", "test2_event"], }, "action": { "service": "test.automation" }, } }, ) opp.bus.async_fire("test_event", context=context) await opp.async_block_till_done() opp.bus.async_fire("test2_event", context=context) await opp.async_block_till_done() assert len(calls) == 2 assert calls[0].context.parent_id == context.id assert calls[1].context.parent_id == context.id
async def test_permit_with_install_code_fail(opp, app_controller, opp_admin_user, params): """Test permit service with install code.""" with pytest.raises(vol.Invalid): await opp.services.async_call(DOMAIN, SERVICE_PERMIT, params, True, Context(user_id=opp_admin_user.id)) assert app_controller.permit.await_count == 0 assert app_controller.permit_with_key.call_count == 0
async def test_set_context(opp): """Test setting context.""" context = Context() ent = entity.Entity() ent.opp = opp ent.entity_id = "hello.world" ent.async_set_context(context) await ent.async_update_op_state() assert opp.states.get("hello.world").context == context
async def test_subscribe_trigger(opp, websocket_client): """Test subscribing to a trigger.""" init_count = sum(opp.bus.async_listeners().values()) await websocket_client.send_json({ "id": 5, "type": "subscribe_trigger", "trigger": { "platform": "event", "event_type": "test_event" }, "variables": { "hello": "world" }, }) msg = await websocket_client.receive_json() assert msg["id"] == 5 assert msg["type"] == const.TYPE_RESULT assert msg["success"] # Verify we have a new listener assert sum(opp.bus.async_listeners().values()) == init_count + 1 context = Context() opp.bus.async_fire("ignore_event") opp.bus.async_fire("test_event", {"hello": "world"}, context=context) opp.bus.async_fire("ignore_event") with timeout(3): msg = await websocket_client.receive_json() assert msg["id"] == 5 assert msg["type"] == "event" assert msg["event"]["context"]["id"] == context.id assert msg["event"]["variables"]["trigger"]["platform"] == "event" event = msg["event"]["variables"]["trigger"]["event"] assert event["event_type"] == "test_event" assert event["data"] == {"hello": "world"} assert event["origin"] == "LOCAL" await websocket_client.send_json({ "id": 6, "type": "unsubscribe_events", "subscription": 5 }) msg = await websocket_client.receive_json() assert msg["id"] == 6 assert msg["type"] == const.TYPE_RESULT assert msg["success"] # Check our listener got unsubscribed assert sum(opp.bus.async_listeners().values()) == init_count
async def test_permit_ha12(opp, app_controller, opp_admin_user, params, duration, node): """Test permit service.""" await opp.services.async_call(DOMAIN, SERVICE_PERMIT, params, True, Context(user_id=opp_admin_user.id)) assert app_controller.permit.await_count == 1 assert app_controller.permit.await_args[1]["time_s"] == duration assert app_controller.permit.await_args[1]["node"] == node assert app_controller.permit_with_key.call_count == 0
async def async_alexa_message(self, payload: Dict[Any, Any]) -> Dict[Any, Any]: """Process cloud alexa message to client.""" cloud_user = await self._prefs.get_cloud_user() return await alexa_sh.async_handle_message( self._opp, self.alexa_config, payload, context=Context(user_id=cloud_user), enabled=self._prefs.alexa_enabled, )
async def test_reload(opp, opp_admin_user): """Test reloading the YAML config.""" assert await async_setup_component( opp, DOMAIN, { DOMAIN: [ {"name": "Person 1", "id": "id-1"}, {"name": "Person 2", "id": "id-2"}, ] }, ) assert len(opp.states.async_entity_ids()) == 2 state_1 = opp.states.get("person.person_1") state_2 = opp.states.get("person.person_2") state_3 = opp.states.get("person.person_3") assert state_1 is not None assert state_1.name == "Person 1" assert state_2 is not None assert state_2.name == "Person 2" assert state_3 is None with patch( "openpeerpower.config.load_yaml_config_file", autospec=True, return_value={ DOMAIN: [ {"name": "Person 1-updated", "id": "id-1"}, {"name": "Person 3", "id": "id-3"}, ] }, ): await opp.services.async_call( DOMAIN, SERVICE_RELOAD, blocking=True, context=Context(user_id=opp_admin_user.id), ) await opp.async_block_till_done() assert len(opp.states.async_entity_ids()) == 2 state_1 = opp.states.get("person.person_1") state_2 = opp.states.get("person.person_2") state_3 = opp.states.get("person.person_3") assert state_1 is not None assert state_1.name == "Person 1-updated" assert state_2 is None assert state_3 is not None assert state_3.name == "Person 3"
async def test_permit_with_qr_code(opp, app_controller, opp_admin_user, params, src_ieee, code): """Test permit service with install code from qr code.""" await opp.services.async_call(DOMAIN, SERVICE_PERMIT, params, True, Context(user_id=opp_admin_user.id)) assert app_controller.permit.await_count == 0 assert app_controller.permit_with_key.call_count == 1 assert app_controller.permit_with_key.await_args[1]["time_s"] == 60 assert app_controller.permit_with_key.await_args[1]["node"] == src_ieee assert app_controller.permit_with_key.await_args[1]["code"] == code
async def test_services(opp, config_entry, config, opp_read_only_user): """Test join/unjoin requires control access.""" await setup_platform(opp, config_entry, config) with pytest.raises(Unauthorized): await opp.services.async_call( DOMAIN, media_player.SERVICE_JOIN, {"master": "media_player.bla", "entity_id": "media_player.blub"}, blocking=True, context=Context(user_id=opp_read_only_user.id), )
async def test_state_with_context(opp): """Test that context is forwarded.""" calls = async_mock_service(opp, DOMAIN, SERVICE_TURN_ON) context = Context() await async_reproduce_states(opp, [State(ENTITY_1, "on")], context=context) await opp.async_block_till_done() assert len(calls) == 1 assert calls[0].data == {"entity_id": ENTITY_1} assert calls[0].context == context
def __init__( self, config: AbstractConfig, user_id: str, source: str, request_id: str, devices: list[dict] | None, ) -> None: """Initialize the request data.""" self.config = config self.source = source self.request_id = request_id self.context = Context(user_id=user_id) self.devices = devices
def to_native(self): """Convert to a natve OP Event.""" context = Context(id=self.context_id, user_id=self.context_user_id) try: return Event( self.event_type, json.loads(self.event_data), EventOrigin(self.origin), _process_timestamp(self.time_fired), context=context, ) except ValueError: # When json.loads fails _LOGGER.exception("Error converting to event: %s", self) return None
async def test_if_fires_on_zone_appear(opp, calls): """Test for firing if entity appears in zone.""" assert await async_setup_component( opp, automation.DOMAIN, { automation.DOMAIN: { "trigger": { "platform": "geo_location", "source": "test_source", "zone": "zone.test", "event": "enter", }, "action": { "service": "test.automation", "data_template": { "some": "{{ trigger.%s }}" % "}} - {{ trigger.".join(( "platform", "entity_id", "from_state.state", "to_state.state", "zone.name", )) }, }, } }, ) # Entity appears in zone without previously existing outside the zone. context = Context() opp.states.async_set( "geo_location.entity", "hello", { "latitude": 32.880586, "longitude": -117.237564, "source": "test_source" }, context=context, ) await opp.async_block_till_done() assert 1 == len(calls) assert calls[0].context.parent_id == context.id assert ("geo_location - geo_location.entity - - hello - test" == calls[0].data["some"])
async def test_setup_no_config(opp, opp_admin_user): """Test component setup with no config.""" count_start = len(opp.states.async_entity_ids()) assert await async_setup_component(opp, DOMAIN, {}) with patch( "openpeerpower.config.load_yaml_config_file", autospec=True, return_value={} ): await opp.services.async_call( DOMAIN, SERVICE_RELOAD, blocking=True, context=Context(user_id=opp_admin_user.id), ) assert count_start == len(opp.states.async_entity_ids())
async def test_humanify_automation_trigger_event(opp): """Test humanifying Shelly click event.""" opp.config.components.add("recorder") assert await async_setup_component(opp, "automation", {}) assert await async_setup_component(opp, "logbook", {}) entity_attr_cache = logbook.EntityAttributeCache(opp) context = Context() event1, event2 = list( logbook.humanify( opp, [ MockLazyEventPartialState( automation.EVENT_AUTOMATION_TRIGGERED, { "name": "Bla", "entity_id": "automation.bla", "source": "state change of input_boolean.yo", }, context=context, ), MockLazyEventPartialState( automation.EVENT_AUTOMATION_TRIGGERED, { "name": "Bla", "entity_id": "automation.bla", }, context=context, ), ], entity_attr_cache, {}, ) ) assert event1["name"] == "Bla" assert event1["message"] == "has been triggered by state change of input_boolean.yo" assert event1["source"] == "state change of input_boolean.yo" assert event1["context_id"] == context.id assert event1["entity_id"] == "automation.bla" assert event2["name"] == "Bla" assert event2["message"] == "has been triggered" assert event2["source"] is None assert event2["context_id"] == context.id assert event2["entity_id"] == "automation.bla"
async def test_set_context_expired(opp): """Test setting context.""" context = Context() with patch.object(entity.Entity, "context_recent_time", new_callable=PropertyMock) as recent: recent.return_value = timedelta(seconds=-5) ent = entity.Entity() ent.opp = opp ent.entity_id = "hello.world" ent.async_set_context(context) await ent.async_update_op_state() assert opp.states.get("hello.world").context != context assert ent._context is None assert ent._context_set is None