Add Intent component (#8434)

* Add intent component

* Add intent script component

* Add shopping list component

* Convert Snips to use intent component

* Convert Alexa to use intent component

* Lint

* Fix Alexa tests

* Update snips test

* Add intent support to conversation

* Add API to view shopping list contents

* Lint

* Fix demo test

* Lint

* lint

* Remove type from slot schema

* Add dependency to conversation

* Move intent to be a helper

* Fix conversation

* Clean up intent helper

* Fix Alexa

* Snips to use new hass.components

* Allow registering intents with conversation at any point in time

* Shopping list to register sentences

* Add HTTP endpoint to Conversation

* Add async action option to intent_script

* Update API.ai to use intents

* Cleanup Alexa

* Shopping list component to register built-in panel

* Rename shopping list intent to inlude Hass name
This commit is contained in:
Paulus Schoutsen authored and GitHub committed 2017-07-21 21:38:53 -07:00
1 parent 7bea69ce83
commit 7edf14e55f
16 files changed
+970 -396

No files matched your search

+10 -7
View File
@@ -47,10 +47,14 @@ def alexa_client(loop, hass, test_client):
"uid": "uuid"
}
},
"intents": {
}
}))
assert loop.run_until_complete(async_setup_component(
hass, 'intent_script', {
'intent_script': {
"WhereAreWeIntent": {
"speech": {
"type": "plaintext",
"type": "plain",
"text":
"""
{%- if is_state("device_tracker.paulus", "home")
@@ -69,19 +73,19 @@ def alexa_client(loop, hass, test_client):
},
"GetZodiacHoroscopeIntent": {
"speech": {
"type": "plaintext",
"type": "plain",
"text": "You told us your sign is {{ ZodiacSign }}.",
}
},
"AMAZON.PlaybackAction<object@MusicCreativeWork>": {
"speech": {
"type": "plaintext",
"type": "plain",
"text": "Playing {{ object_byArtist_name }}.",
}
},
"CallServiceIntent": {
"speech": {
"type": "plaintext",
"type": "plain",
"text": "Service called",
},
"action": {
@@ -93,8 +97,7 @@ def alexa_client(loop, hass, test_client):
}
}
}
}
}))
}))
return loop.run_until_complete(test_client(hass.http.app))
+28 -22
View File
@@ -57,14 +57,15 @@ def setUpModule():
hass.services.register("test", "apiai", mock_service)
setup.setup_component(hass, apiai.DOMAIN, {
# Key is here to verify we allow other keys in config too
"homeassistant": {},
"apiai": {
"intents": {
"WhereAreWeIntent": {
"speech":
"""
assert setup.setup_component(hass, apiai.DOMAIN, {
"apiai": {},
})
assert setup.setup_component(hass, "intent_script", {
"intent_script": {
"WhereAreWeIntent": {
"speech": {
"type": "plain",
"text": """
{%- if is_state("device_tracker.paulus", "home")
and is_state("device_tracker.anne_therese",
"home") -%}
@@ -77,19 +78,25 @@ def setUpModule():
}}
{% endif %}
""",
}
},
"GetZodiacHoroscopeIntent": {
"speech": {
"type": "plain",
"text": "You told us your sign is {{ ZodiacSign }}.",
}
},
"CallServiceIntent": {
"speech": {
"type": "plain",
"text": "Service called",
},
"GetZodiacHoroscopeIntent": {
"speech": "You told us your sign is {{ ZodiacSign }}.",
},
"CallServiceIntent": {
"speech": "Service called",
"action": {
"service": "test.apiai",
"data_template": {
"hello": "{{ ZodiacSign }}"
},
"entity_id": "switch.test",
}
"action": {
"service": "test.apiai",
"data_template": {
"hello": "{{ ZodiacSign }}"
},
"entity_id": "switch.test",
}
}
}
@@ -509,5 +516,4 @@ class TestApiai(unittest.TestCase):
self.assertEqual(200, req.status_code)
text = req.json().get("speech")
self.assertEqual(
"Intent 'unknown' is not yet configured within Home Assistant.",
text)
"This intent is not yet configured within Home Assistant.", text)
+127 -39
View File
@@ -1,16 +1,18 @@
"""The tests for the Conversation component."""
# pylint: disable=protected-access
import asyncio
import unittest
from unittest.mock import patch
from homeassistant.core import callback
from homeassistant.setup import setup_component
from homeassistant.setup import setup_component, async_setup_component
import homeassistant.components as core_components
from homeassistant.components import conversation
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.util.async import run_coroutine_threadsafe
from homeassistant.helpers import intent
from tests.common import get_test_home_assistant, assert_setup_component
from tests.common import get_test_home_assistant, async_mock_intent
class TestConversation(unittest.TestCase):
@@ -25,10 +27,9 @@ class TestConversation(unittest.TestCase):
self.assertTrue(run_coroutine_threadsafe(
core_components.async_setup(self.hass, {}), self.hass.loop
).result())
with assert_setup_component(0):
self.assertTrue(setup_component(self.hass, conversation.DOMAIN, {
conversation.DOMAIN: {}
}))
self.assertTrue(setup_component(self.hass, conversation.DOMAIN, {
conversation.DOMAIN: {}
}))
# pylint: disable=invalid-name
def tearDown(self):
@@ -119,44 +120,131 @@ class TestConversation(unittest.TestCase):
self.assertFalse(mock_call.called)
class TestConfiguration(unittest.TestCase):
"""Test the conversation configuration component."""
@asyncio.coroutine
def test_calling_intent(hass):
"""Test calling an intent from a conversation."""
intents = async_mock_intent(hass, 'OrderBeer')
# pylint: disable=invalid-name
def setUp(self):
"""Setup things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.assertTrue(setup_component(self.hass, conversation.DOMAIN, {
conversation.DOMAIN: {
'test_2': {
'sentence': 'switch boolean',
'action': {
'service': 'input_boolean.toggle'
}
}
result = yield from async_setup_component(hass, 'conversation', {
'conversation': {
'intents': {
'OrderBeer': [
'I would like the {type} beer'
]
}
}))
}
})
assert result
# pylint: disable=invalid-name
def tearDown(self):
"""Stop everything that was started."""
self.hass.stop()
yield from hass.services.async_call(
'conversation', 'process', {
conversation.ATTR_TEXT: 'I would like the Grolsch beer'
})
yield from hass.async_block_till_done()
def test_custom(self):
"""Setup and perform good turn on requests."""
calls = []
assert len(intents) == 1
intent = intents[0]
assert intent.platform == 'conversation'
assert intent.intent_type == 'OrderBeer'
assert intent.slots == {'type': {'value': 'Grolsch'}}
assert intent.text_input == 'I would like the Grolsch beer'
@callback
def record_call(service):
"""Recorder for a call."""
calls.append(service)
self.hass.services.register('input_boolean', 'toggle', record_call)
@asyncio.coroutine
def test_register_before_setup(hass):
"""Test calling an intent from a conversation."""
intents = async_mock_intent(hass, 'OrderBeer')
event_data = {conversation.ATTR_TEXT: 'switch boolean'}
self.assertTrue(self.hass.services.call(
conversation.DOMAIN, 'process', event_data, True))
hass.components.conversation.async_register('OrderBeer', [
'A {type} beer, please'
])
call = calls[-1]
self.assertEqual('input_boolean', call.domain)
self.assertEqual('toggle', call.service)
result = yield from async_setup_component(hass, 'conversation', {
'conversation': {
'intents': {
'OrderBeer': [
'I would like the {type} beer'
]
}
}
})
assert result
yield from hass.services.async_call(
'conversation', 'process', {
conversation.ATTR_TEXT: 'A Grolsch beer, please'
})
yield from hass.async_block_till_done()
assert len(intents) == 1
intent = intents[0]
assert intent.platform == 'conversation'
assert intent.intent_type == 'OrderBeer'
assert intent.slots == {'type': {'value': 'Grolsch'}}
assert intent.text_input == 'A Grolsch beer, please'
yield from hass.services.async_call(
'conversation', 'process', {
conversation.ATTR_TEXT: 'I would like the Grolsch beer'
})
yield from hass.async_block_till_done()
assert len(intents) == 2
intent = intents[1]
assert intent.platform == 'conversation'
assert intent.intent_type == 'OrderBeer'
assert intent.slots == {'type': {'value': 'Grolsch'}}
assert intent.text_input == 'I would like the Grolsch beer'
@asyncio.coroutine
def test_http_processing_intent(hass, test_client):
"""Test processing intent via HTTP API."""
class TestIntentHandler(intent.IntentHandler):
intent_type = 'OrderBeer'
@asyncio.coroutine
def async_handle(self, intent):
"""Handle the intent."""
response = intent.create_response()
response.async_set_speech(
"I've ordered a {}!".format(intent.slots['type']['value']))
response.async_set_card(
"Beer ordered",
"You chose a {}.".format(intent.slots['type']['value']))
return response
intent.async_register(hass, TestIntentHandler())
result = yield from async_setup_component(hass, 'conversation', {
'conversation': {
'intents': {
'OrderBeer': [
'I would like the {type} beer'
]
}
}
})
assert result
client = yield from test_client(hass.http.app)
resp = yield from client.post('/api/conversation/process', json={
'text': 'I would like the Grolsch beer'
})
assert resp.status == 200
data = yield from resp.json()
assert data == {
'card': {
'simple': {
'content': 'You chose a Grolsch.',
'title': 'Beer ordered'
}},
'speech': {
'plain': {
'extra_data': None,
'speech': "I've ordered a Grolsch!"
}
}
}
+44 -34
View File
@@ -1,52 +1,62 @@
"""The tests for the Demo component."""
import asyncio
import json
import os
import unittest
from homeassistant.setup import setup_component
import pytest
from homeassistant.setup import async_setup_component
from homeassistant.components import demo, device_tracker
from homeassistant.remote import JSONEncoder
from tests.common import mock_http_component, get_test_home_assistant
@pytest.fixture
def minimize_demo_platforms(hass):
"""Cleanup demo component for tests."""
orig = demo.COMPONENTS_WITH_DEMO_PLATFORM
demo.COMPONENTS_WITH_DEMO_PLATFORM = [
'switch', 'light', 'media_player']
yield
demo.COMPONENTS_WITH_DEMO_PLATFORM = orig
class TestDemo(unittest.TestCase):
"""Test the Demo component."""
@pytest.fixture(autouse=True)
def demo_cleanup(hass):
"""Clean up device tracker demo file."""
yield
try:
os.remove(hass.config.path(device_tracker.YAML_DEVICES))
except FileNotFoundError:
pass
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
self.hass = get_test_home_assistant()
mock_http_component(self.hass)
def tearDown(self): # pylint: disable=invalid-name
"""Stop everything that was started."""
self.hass.stop()
@asyncio.coroutine
def test_if_demo_state_shows_by_default(hass, minimize_demo_platforms):
"""Test if demo state shows if we give no configuration."""
yield from async_setup_component(hass, demo.DOMAIN, {demo.DOMAIN: {}})
try:
os.remove(self.hass.config.path(device_tracker.YAML_DEVICES))
except FileNotFoundError:
pass
assert hass.states.get('a.Demo_Mode') is not None
def test_if_demo_state_shows_by_default(self):
"""Test if demo state shows if we give no configuration."""
setup_component(self.hass, demo.DOMAIN, {demo.DOMAIN: {}})
self.assertIsNotNone(self.hass.states.get('a.Demo_Mode'))
@asyncio.coroutine
def test_hiding_demo_state(hass, minimize_demo_platforms):
"""Test if you can hide the demo card."""
yield from async_setup_component(hass, demo.DOMAIN, {
demo.DOMAIN: {'hide_demo_state': 1}})
def test_hiding_demo_state(self):
"""Test if you can hide the demo card."""
setup_component(self.hass, demo.DOMAIN, {
demo.DOMAIN: {'hide_demo_state': 1}})
assert hass.states.get('a.Demo_Mode') is None
self.assertIsNone(self.hass.states.get('a.Demo_Mode'))
def test_all_entities_can_be_loaded_over_json(self):
"""Test if you can hide the demo card."""
setup_component(self.hass, demo.DOMAIN, {
demo.DOMAIN: {'hide_demo_state': 1}})
@asyncio.coroutine
def test_all_entities_can_be_loaded_over_json(hass):
"""Test if you can hide the demo card."""
yield from async_setup_component(hass, demo.DOMAIN, {
demo.DOMAIN: {'hide_demo_state': 1}})
try:
json.dumps(self.hass.states.all(), cls=JSONEncoder)
except Exception:
self.fail('Unable to convert all demo entities to JSON. '
'Wrong data in state machine!')
try:
json.dumps(hass.states.async_all(), cls=JSONEncoder)
except Exception:
pytest.fail('Unable to convert all demo entities to JSON. '
'Wrong data in state machine!')
+45
View File
@@ -0,0 +1,45 @@
"""Test intent_script component."""
import asyncio
from homeassistant.bootstrap import async_setup_component
from homeassistant.helpers import intent
from tests.common import async_mock_service
@asyncio.coroutine
def test_intent_script(hass):
"""Test intent scripts work."""
calls = async_mock_service(hass, 'test', 'service')
yield from async_setup_component(hass, 'intent_script', {
'intent_script': {
'HelloWorld': {
'action': {
'service': 'test.service',
'data_template': {
'hello': '{{ name }}'
}
},
'card': {
'title': 'Hello {{ name }}',
'content': 'Content for {{ name }}',
},
'speech': {
'text': 'Good morning {{ name }}'
}
}
}
})
response = yield from intent.async_handle(
hass, 'test', 'HelloWorld', {'name': {'value': 'Paulus'}}
)
assert len(calls) == 1
assert calls[0].data['hello'] == 'Paulus'
assert response.speech['plain']['speech'] == 'Good morning Paulus'
assert response.card['simple']['title'] == 'Hello Paulus'
assert response.card['simple']['content'] == 'Content for Paulus'
+61
View File
@@ -0,0 +1,61 @@
"""Test shopping list component."""
import asyncio
from homeassistant.bootstrap import async_setup_component
from homeassistant.helpers import intent
@asyncio.coroutine
def test_add_item(hass):
"""Test adding an item intent."""
yield from async_setup_component(hass, 'shopping_list', {})
response = yield from intent.async_handle(
hass, 'test', 'HassShoppingListAddItem', {'item': {'value': 'beer'}}
)
assert response.speech['plain']['speech'] == \
"I've added beer to your shopping list"
@asyncio.coroutine
def test_recent_items_intent(hass):
"""Test recent items."""
yield from async_setup_component(hass, 'shopping_list', {})
yield from intent.async_handle(
hass, 'test', 'HassShoppingListAddItem', {'item': {'value': 'beer'}}
)
yield from intent.async_handle(
hass, 'test', 'HassShoppingListAddItem', {'item': {'value': 'wine'}}
)
yield from intent.async_handle(
hass, 'test', 'HassShoppingListAddItem', {'item': {'value': 'soda'}}
)
response = yield from intent.async_handle(
hass, 'test', 'HassShoppingListLastItems'
)
assert response.speech['plain']['speech'] == \
"These are the top 5 items in your shopping list: soda, wine, beer"
@asyncio.coroutine
def test_api(hass, test_client):
"""Test the API."""
yield from async_setup_component(hass, 'shopping_list', {})
yield from intent.async_handle(
hass, 'test', 'HassShoppingListAddItem', {'item': {'value': 'beer'}}
)
yield from intent.async_handle(
hass, 'test', 'HassShoppingListAddItem', {'item': {'value': 'wine'}}
)
client = yield from test_client(hass.http.app)
resp = yield from client.get('/api/shopping_list')
assert resp.status == 200
data = yield from resp.json()
assert data == ['beer', 'wine']
+11 -19
View File
@@ -2,7 +2,7 @@
import asyncio
from homeassistant.bootstrap import async_setup_component
from tests.common import async_fire_mqtt_message, async_mock_service
from tests.common import async_fire_mqtt_message, async_mock_intent
EXAMPLE_MSG = """
{
@@ -16,7 +16,7 @@ EXAMPLE_MSG = """
"slotName": "light_color",
"value": {
"kind": "Custom",
"value": "blue"
"value": "green"
}
}
]
@@ -27,27 +27,19 @@ EXAMPLE_MSG = """
@asyncio.coroutine
def test_snips_call_action(hass, mqtt_mock):
"""Test calling action via Snips."""
calls = async_mock_service(hass, 'test', 'service')
result = yield from async_setup_component(hass, "snips", {
"snips": {
"intents": {
"Lights": {
"action": {
"service": "test.service",
"data_template": {
"color": "{{ light_color }}"
}
}
}
}
}
"snips": {},
})
assert result
intents = async_mock_intent(hass, 'Lights')
async_fire_mqtt_message(hass, 'hermes/nlu/intentParsed',
EXAMPLE_MSG)
yield from hass.async_block_till_done()
assert len(calls) == 1
call = calls[0]
assert call.data.get('color') == 'blue'
assert len(intents) == 1
intent = intents[0]
assert intent.platform == 'snips'
assert intent.intent_type == 'Lights'
assert intent.slots == {'light_color': {'value': 'green'}}
assert intent.text_input == 'turn the lights green'