This commit is contained in:
Paulus Schoutsen committed 2019-07-31 12:25:30 -07:00
1 parent da05dfe708
commit 4de97abc3a
2676 files changed
+163166 -140084

No files matched your search

+15 -14
View File
@@ -4,19 +4,19 @@ from unittest.mock import patch
import pytest
TEST_CALENDAR = {
'id': 'qwertyuiopasdfghjklzxcvbnm@import.calendar.google.com',
'etag': '"3584134138943410"',
'timeZone': 'UTC',
'accessRole': 'reader',
'foregroundColor': '#000000',
'selected': True,
'kind': 'calendar#calendarListEntry',
'backgroundColor': '#16a765',
'description': 'Test Calendar',
'summary': 'We are, we are, a... Test Calendar',
'colorId': '8',
'defaultReminders': [],
'track': True
"id": "qwertyuiopasdfghjklzxcvbnm@import.calendar.google.com",
"etag": '"3584134138943410"',
"timeZone": "UTC",
"accessRole": "reader",
"foregroundColor": "#000000",
"selected": True,
"kind": "calendar#calendarListEntry",
"backgroundColor": "#16a765",
"description": "Test Calendar",
"summary": "We are, we are, a... Test Calendar",
"colorId": "8",
"defaultReminders": [],
"track": True,
}
@@ -30,6 +30,7 @@ def test_calendar():
def mock_next_event():
"""Mock the google calendar data."""
patch_google_cal = patch(
'homeassistant.components.google.calendar.GoogleCalendarData')
"homeassistant.components.google.calendar.GoogleCalendarData"
)
with patch_google_cal as google_cal_data:
yield google_cal_data
+140 -141
View File
@@ -6,9 +6,17 @@ import httplib2
import pytest
from homeassistant.components.google import (
CONF_CAL_ID, CONF_CLIENT_ID, CONF_CLIENT_SECRET, CONF_DEVICE_ID,
CONF_ENTITIES, CONF_NAME, CONF_TRACK, DEVICE_SCHEMA,
SERVICE_SCAN_CALENDARS, do_setup)
CONF_CAL_ID,
CONF_CLIENT_ID,
CONF_CLIENT_SECRET,
CONF_DEVICE_ID,
CONF_ENTITIES,
CONF_NAME,
CONF_TRACK,
DEVICE_SCHEMA,
SERVICE_SCAN_CALENDARS,
do_setup,
)
from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.helpers.template import DATE_STR_FORMAT
from homeassistant.setup import async_setup_component
@@ -18,74 +26,71 @@ import homeassistant.util.dt as dt_util
from tests.common import async_mock_service
GOOGLE_CONFIG = {
CONF_CLIENT_ID: 'client_id',
CONF_CLIENT_SECRET: 'client_secret',
}
TEST_ENTITY = 'calendar.we_are_we_are_a_test_calendar'
TEST_ENTITY_NAME = 'We are, we are, a... Test Calendar'
GOOGLE_CONFIG = {CONF_CLIENT_ID: "client_id", CONF_CLIENT_SECRET: "client_secret"}
TEST_ENTITY = "calendar.we_are_we_are_a_test_calendar"
TEST_ENTITY_NAME = "We are, we are, a... Test Calendar"
TEST_EVENT = {
'summary': 'Test All Day Event',
'start': {
"summary": "Test All Day Event",
"start": {},
"end": {},
"location": "Test Cases",
"description": "test event",
"kind": "calendar#event",
"created": "2016-06-23T16:37:57.000Z",
"transparency": "transparent",
"updated": "2016-06-24T01:57:21.045Z",
"reminders": {"useDefault": True},
"organizer": {
"email": "uvrttabwegnui4gtia3vyqb@import.calendar.google.com",
"displayName": "Organizer Name",
"self": True,
},
'end': {
"sequence": 0,
"creator": {
"email": "uvrttabwegnui4gtia3vyqb@import.calendar.google.com",
"displayName": "Organizer Name",
"self": True,
},
'location': 'Test Cases',
'description': 'test event',
'kind': 'calendar#event',
'created': '2016-06-23T16:37:57.000Z',
'transparency': 'transparent',
'updated': '2016-06-24T01:57:21.045Z',
'reminders': {'useDefault': True},
'organizer': {
'email': 'uvrttabwegnui4gtia3vyqb@import.calendar.google.com',
'displayName': 'Organizer Name',
'self': True
},
'sequence': 0,
'creator': {
'email': 'uvrttabwegnui4gtia3vyqb@import.calendar.google.com',
'displayName': 'Organizer Name',
'self': True
},
'id': '_c8rinwq863h45qnucyoi43ny8',
'etag': '"2933466882090000"',
'htmlLink': 'https://www.google.com/calendar/event?eid=*******',
'iCalUID': 'cydrevtfuybguinhomj@google.com',
'status': 'confirmed'
"id": "_c8rinwq863h45qnucyoi43ny8",
"etag": '"2933466882090000"',
"htmlLink": "https://www.google.com/calendar/event?eid=*******",
"iCalUID": "cydrevtfuybguinhomj@google.com",
"status": "confirmed",
}
def get_calendar_info(calendar):
"""Convert data from Google into DEVICE_SCHEMA."""
calendar_info = DEVICE_SCHEMA({
CONF_CAL_ID: calendar['id'],
CONF_ENTITIES: [{
CONF_TRACK: calendar['track'],
CONF_NAME: calendar['summary'],
CONF_DEVICE_ID: slugify(calendar['summary']),
}]
})
calendar_info = DEVICE_SCHEMA(
{
CONF_CAL_ID: calendar["id"],
CONF_ENTITIES: [
{
CONF_TRACK: calendar["track"],
CONF_NAME: calendar["summary"],
CONF_DEVICE_ID: slugify(calendar["summary"]),
}
],
}
)
return calendar_info
@pytest.fixture(autouse=True)
def mock_google_setup(hass, test_calendar):
"""Mock the google set up functions."""
hass.loop.run_until_complete(
async_setup_component(hass, 'group', {'group': {}}))
hass.loop.run_until_complete(async_setup_component(hass, "group", {"group": {}}))
calendar = get_calendar_info(test_calendar)
calendars = {calendar[CONF_CAL_ID]: calendar}
patch_google_auth = patch(
'homeassistant.components.google.do_authentication',
side_effect=do_setup)
"homeassistant.components.google.do_authentication", side_effect=do_setup
)
patch_google_load = patch(
'homeassistant.components.google.load_config',
return_value=calendars)
patch_google_services = patch(
'homeassistant.components.google.setup_services')
async_mock_service(hass, 'google', SERVICE_SCAN_CALENDARS)
"homeassistant.components.google.load_config", return_value=calendars
)
patch_google_services = patch("homeassistant.components.google.setup_services")
async_mock_service(hass, "google", SERVICE_SCAN_CALENDARS)
with patch_google_auth, patch_google_load, patch_google_services:
yield
@@ -102,48 +107,47 @@ def set_time_zone():
"""Set the time zone for the tests."""
# Set our timezone to CST/Regina so we can check calculations
# This keeps UTC-6 all year round
dt_util.set_default_time_zone(dt_util.get_time_zone('America/Regina'))
dt_util.set_default_time_zone(dt_util.get_time_zone("America/Regina"))
yield
dt_util.set_default_time_zone(dt_util.get_time_zone('UTC'))
dt_util.set_default_time_zone(dt_util.get_time_zone("UTC"))
@pytest.fixture(name='google_service')
@pytest.fixture(name="google_service")
def mock_google_service():
"""Mock google service."""
patch_google_service = patch(
'homeassistant.components.google.calendar.GoogleCalendarService')
"homeassistant.components.google.calendar.GoogleCalendarService"
)
with patch_google_service as mock_service:
yield mock_service
async def test_all_day_event(hass, mock_next_event):
"""Test that we can create an event trigger on device."""
week_from_today = (
dt_util.dt.date.today() + dt_util.dt.timedelta(days=7))
week_from_today = dt_util.dt.date.today() + dt_util.dt.timedelta(days=7)
end_event = week_from_today + dt_util.dt.timedelta(days=1)
event = copy.deepcopy(TEST_EVENT)
start = week_from_today.isoformat()
end = end_event.isoformat()
event['start']['date'] = start
event['end']['date'] = end
event["start"]["date"] = start
event["end"]["date"] = end
mock_next_event.return_value.event = event
assert await async_setup_component(
hass, 'google', {'google': GOOGLE_CONFIG})
assert await async_setup_component(hass, "google", {"google": GOOGLE_CONFIG})
await hass.async_block_till_done()
state = hass.states.get(TEST_ENTITY)
assert state.name == TEST_ENTITY_NAME
assert state.state == STATE_OFF
assert dict(state.attributes) == {
'friendly_name': TEST_ENTITY_NAME,
'message': event['summary'],
'all_day': True,
'offset_reached': False,
'start_time': week_from_today.strftime(DATE_STR_FORMAT),
'end_time': end_event.strftime(DATE_STR_FORMAT),
'location': event['location'],
'description': event['description'],
"friendly_name": TEST_ENTITY_NAME,
"message": event["summary"],
"all_day": True,
"offset_reached": False,
"start_time": week_from_today.strftime(DATE_STR_FORMAT),
"end_time": end_event.strftime(DATE_STR_FORMAT),
"location": event["location"],
"description": event["description"],
}
@@ -154,26 +158,25 @@ async def test_future_event(hass, mock_next_event):
start = one_hour_from_now.isoformat()
end = end_event.isoformat()
event = copy.deepcopy(TEST_EVENT)
event['start']['dateTime'] = start
event['end']['dateTime'] = end
event["start"]["dateTime"] = start
event["end"]["dateTime"] = end
mock_next_event.return_value.event = event
assert await async_setup_component(
hass, 'google', {'google': GOOGLE_CONFIG})
assert await async_setup_component(hass, "google", {"google": GOOGLE_CONFIG})
await hass.async_block_till_done()
state = hass.states.get(TEST_ENTITY)
assert state.name == TEST_ENTITY_NAME
assert state.state == STATE_OFF
assert dict(state.attributes) == {
'friendly_name': TEST_ENTITY_NAME,
'message': event['summary'],
'all_day': False,
'offset_reached': False,
'start_time': one_hour_from_now.strftime(DATE_STR_FORMAT),
'end_time': end_event.strftime(DATE_STR_FORMAT),
'location': event['location'],
'description': event['description'],
"friendly_name": TEST_ENTITY_NAME,
"message": event["summary"],
"all_day": False,
"offset_reached": False,
"start_time": one_hour_from_now.strftime(DATE_STR_FORMAT),
"end_time": end_event.strftime(DATE_STR_FORMAT),
"location": event["location"],
"description": event["description"],
}
@@ -184,26 +187,25 @@ async def test_in_progress_event(hass, mock_next_event):
start = middle_of_event.isoformat()
end = end_event.isoformat()
event = copy.deepcopy(TEST_EVENT)
event['start']['dateTime'] = start
event['end']['dateTime'] = end
event["start"]["dateTime"] = start
event["end"]["dateTime"] = end
mock_next_event.return_value.event = event
assert await async_setup_component(
hass, 'google', {'google': GOOGLE_CONFIG})
assert await async_setup_component(hass, "google", {"google": GOOGLE_CONFIG})
await hass.async_block_till_done()
state = hass.states.get(TEST_ENTITY)
assert state.name == TEST_ENTITY_NAME
assert state.state == STATE_ON
assert dict(state.attributes) == {
'friendly_name': TEST_ENTITY_NAME,
'message': event['summary'],
'all_day': False,
'offset_reached': False,
'start_time': middle_of_event.strftime(DATE_STR_FORMAT),
'end_time': end_event.strftime(DATE_STR_FORMAT),
'location': event['location'],
'description': event['description'],
"friendly_name": TEST_ENTITY_NAME,
"message": event["summary"],
"all_day": False,
"offset_reached": False,
"start_time": middle_of_event.strftime(DATE_STR_FORMAT),
"end_time": end_event.strftime(DATE_STR_FORMAT),
"location": event["location"],
"description": event["description"],
}
@@ -213,29 +215,28 @@ async def test_offset_in_progress_event(hass, mock_next_event):
end_event = middle_of_event + dt_util.dt.timedelta(minutes=60)
start = middle_of_event.isoformat()
end = end_event.isoformat()
event_summary = 'Test Event in Progress'
event_summary = "Test Event in Progress"
event = copy.deepcopy(TEST_EVENT)
event['start']['dateTime'] = start
event['end']['dateTime'] = end
event['summary'] = '{} !!-15'.format(event_summary)
event["start"]["dateTime"] = start
event["end"]["dateTime"] = end
event["summary"] = "{} !!-15".format(event_summary)
mock_next_event.return_value.event = event
assert await async_setup_component(
hass, 'google', {'google': GOOGLE_CONFIG})
assert await async_setup_component(hass, "google", {"google": GOOGLE_CONFIG})
await hass.async_block_till_done()
state = hass.states.get(TEST_ENTITY)
assert state.name == TEST_ENTITY_NAME
assert state.state == STATE_OFF
assert dict(state.attributes) == {
'friendly_name': TEST_ENTITY_NAME,
'message': event_summary,
'all_day': False,
'offset_reached': True,
'start_time': middle_of_event.strftime(DATE_STR_FORMAT),
'end_time': end_event.strftime(DATE_STR_FORMAT),
'location': event['location'],
'description': event['description'],
"friendly_name": TEST_ENTITY_NAME,
"message": event_summary,
"all_day": False,
"offset_reached": True,
"start_time": middle_of_event.strftime(DATE_STR_FORMAT),
"end_time": end_event.strftime(DATE_STR_FORMAT),
"location": event["location"],
"description": event["description"],
}
@@ -246,29 +247,28 @@ async def test_all_day_offset_in_progress_event(hass, mock_next_event):
end_event = tomorrow + dt_util.dt.timedelta(days=1)
start = tomorrow.isoformat()
end = end_event.isoformat()
event_summary = 'Test All Day Event Offset In Progress'
event_summary = "Test All Day Event Offset In Progress"
event = copy.deepcopy(TEST_EVENT)
event['start']['date'] = start
event['end']['date'] = end
event['summary'] = '{} !!-25:0'.format(event_summary)
event["start"]["date"] = start
event["end"]["date"] = end
event["summary"] = "{} !!-25:0".format(event_summary)
mock_next_event.return_value.event = event
assert await async_setup_component(
hass, 'google', {'google': GOOGLE_CONFIG})
assert await async_setup_component(hass, "google", {"google": GOOGLE_CONFIG})
await hass.async_block_till_done()
state = hass.states.get(TEST_ENTITY)
assert state.name == TEST_ENTITY_NAME
assert state.state == STATE_OFF
assert dict(state.attributes) == {
'friendly_name': TEST_ENTITY_NAME,
'message': event_summary,
'all_day': True,
'offset_reached': True,
'start_time': tomorrow.strftime(DATE_STR_FORMAT),
'end_time': end_event.strftime(DATE_STR_FORMAT),
'location': event['location'],
'description': event['description'],
"friendly_name": TEST_ENTITY_NAME,
"message": event_summary,
"all_day": True,
"offset_reached": True,
"start_time": tomorrow.strftime(DATE_STR_FORMAT),
"end_time": end_event.strftime(DATE_STR_FORMAT),
"location": event["location"],
"description": event["description"],
}
@@ -278,41 +278,40 @@ async def test_all_day_offset_event(hass, mock_next_event):
end_event = tomorrow + dt_util.dt.timedelta(days=1)
start = tomorrow.isoformat()
end = end_event.isoformat()
offset_hours = (1 + dt_util.now().hour)
event_summary = 'Test All Day Event Offset'
offset_hours = 1 + dt_util.now().hour
event_summary = "Test All Day Event Offset"
event = copy.deepcopy(TEST_EVENT)
event['start']['date'] = start
event['end']['date'] = end
event['summary'] = '{} !!-{}:0'.format(event_summary, offset_hours)
event["start"]["date"] = start
event["end"]["date"] = end
event["summary"] = "{} !!-{}:0".format(event_summary, offset_hours)
mock_next_event.return_value.event = event
assert await async_setup_component(
hass, 'google', {'google': GOOGLE_CONFIG})
assert await async_setup_component(hass, "google", {"google": GOOGLE_CONFIG})
await hass.async_block_till_done()
state = hass.states.get(TEST_ENTITY)
assert state.name == TEST_ENTITY_NAME
assert state.state == STATE_OFF
assert dict(state.attributes) == {
'friendly_name': TEST_ENTITY_NAME,
'message': event_summary,
'all_day': True,
'offset_reached': False,
'start_time': tomorrow.strftime(DATE_STR_FORMAT),
'end_time': end_event.strftime(DATE_STR_FORMAT),
'location': event['location'],
'description': event['description'],
"friendly_name": TEST_ENTITY_NAME,
"message": event_summary,
"all_day": True,
"offset_reached": False,
"start_time": tomorrow.strftime(DATE_STR_FORMAT),
"end_time": end_event.strftime(DATE_STR_FORMAT),
"location": event["location"],
"description": event["description"],
}
async def test_update_error(hass, google_service):
"""Test that the calendar handles a server error."""
google_service.return_value.get = Mock(
side_effect=httplib2.ServerNotFoundError("unit test"))
assert await async_setup_component(
hass, 'google', {'google': GOOGLE_CONFIG})
side_effect=httplib2.ServerNotFoundError("unit test")
)
assert await async_setup_component(hass, "google", {"google": GOOGLE_CONFIG})
await hass.async_block_till_done()
state = hass.states.get(TEST_ENTITY)
assert state.name == TEST_ENTITY_NAME
assert state.state == 'off'
assert state.state == "off"
+29 -36
View File
@@ -7,21 +7,16 @@ import homeassistant.components.google as google
from homeassistant.setup import async_setup_component
@pytest.fixture(name='google_setup')
@pytest.fixture(name="google_setup")
def mock_google_setup(hass):
"""Mock the google set up functions."""
p_auth = patch(
'homeassistant.components.google.do_authentication',
side_effect=google.do_setup)
p_service = patch(
'homeassistant.components.google.GoogleCalendarService.get')
p_discovery = patch(
'homeassistant.components.google.discovery.load_platform')
p_load = patch(
'homeassistant.components.google.load_config',
return_value={})
p_save = patch(
'homeassistant.components.google.update_config')
"homeassistant.components.google.do_authentication", side_effect=google.do_setup
)
p_service = patch("homeassistant.components.google.GoogleCalendarService.get")
p_discovery = patch("homeassistant.components.google.discovery.load_platform")
p_load = patch("homeassistant.components.google.load_config", return_value={})
p_save = patch("homeassistant.components.google.update_config")
with p_auth, p_load, p_service, p_discovery, p_save:
yield
@@ -29,45 +24,43 @@ def mock_google_setup(hass):
async def test_setup_component(hass, google_setup):
"""Test setup component."""
config = {
'google': {
'client_id': 'id',
'client_secret': 'secret',
}
}
config = {"google": {"client_id": "id", "client_secret": "secret"}}
assert await async_setup_component(hass, 'google', config)
assert await async_setup_component(hass, "google", config)
async def test_get_calendar_info(hass, test_calendar):
"""Test getting the calendar info."""
calendar_info = await hass.async_add_executor_job(
google.get_calendar_info, hass, test_calendar)
google.get_calendar_info, hass, test_calendar
)
assert calendar_info == {
'cal_id': 'qwertyuiopasdfghjklzxcvbnm@import.calendar.google.com',
'entities': [{
'device_id': 'we_are_we_are_a_test_calendar',
'name': 'We are, we are, a... Test Calendar',
'track': True,
'ignore_availability': True,
}]
"cal_id": "qwertyuiopasdfghjklzxcvbnm@import.calendar.google.com",
"entities": [
{
"device_id": "we_are_we_are_a_test_calendar",
"name": "We are, we are, a... Test Calendar",
"track": True,
"ignore_availability": True,
}
],
}
async def test_found_calendar(
hass, google_setup, mock_next_event, test_calendar):
async def test_found_calendar(hass, google_setup, mock_next_event, test_calendar):
"""Test when a calendar is found."""
config = {
'google': {
'client_id': 'id',
'client_secret': 'secret',
'track_new_calendar': True,
"google": {
"client_id": "id",
"client_secret": "secret",
"track_new_calendar": True,
}
}
assert await async_setup_component(hass, 'google', config)
assert await async_setup_component(hass, "google", config)
assert hass.data[google.DATA_INDEX] == {}
await hass.services.async_call(
'google', google.SERVICE_FOUND_CALENDARS, test_calendar, blocking=True)
"google", google.SERVICE_FOUND_CALENDARS, test_calendar, blocking=True
)
assert hass.data[google.DATA_INDEX].get(test_calendar['id']) is not None
assert hass.data[google.DATA_INDEX].get(test_calendar["id"]) is not None