Fix when 2 states match with same name (#12771)

This commit is contained in:
Paulus Schoutsen 2018-02-28 13:39:01 -08:00 committed by GitHub
parent e2a2fe36fc
commit f7e9215f5e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 6 deletions

View File

@ -97,12 +97,12 @@ def async_match_state(hass, name, states=None):
if states is None:
states = hass.states.async_all()
entity = _fuzzymatch(name, states, lambda state: state.name)
state = _fuzzymatch(name, states, lambda state: state.name)
if entity is None:
if state is None:
raise IntentHandleError('Unable to find entity {}'.format(name))
return entity
return state
@callback
@ -154,12 +154,13 @@ def _fuzzymatch(name, items, key):
matches = []
pattern = '.*?'.join(name)
regex = re.compile(pattern, re.IGNORECASE)
for item in items:
for idx, item in enumerate(items):
match = regex.search(key(item))
if match:
matches.append((len(match.group()), match.start(), item))
# Add index so we pick first match in case same group and start
matches.append((len(match.group()), match.start(), idx, item))
return sorted(matches)[0][2] if matches else None
return sorted(matches)[0][3] if matches else None
class ServiceIntentHandler(IntentHandler):

View File

@ -0,0 +1,12 @@
"""Tests for the intent helpers."""
from homeassistant.core import State
from homeassistant.helpers import intent
def test_async_match_state():
"""Test async_match_state helper."""
state1 = State('light.kitchen', 'on')
state2 = State('switch.kitchen', 'on')
state = intent.async_match_state(None, 'kitch', [state1, state2])
assert state is state1