Merge pull request #21 from fronzbot/cleanup

Cleanup and Coverage Increase
This commit is contained in:
Kevin Fronczak
2017-03-20 15:57:43 -04:00
committed by GitHub
9 changed files with 814 additions and 861 deletions
+8 -8
View File
@@ -10,7 +10,7 @@ The Client API is a straightforward REST API using JSON and HTTPS.
## This Document
The purpose here is to describe what is going on behind the scenes, and what commands we know are available to communicate with Blink servers. This is NOT a description of the blinkpy module, but a description of the commands blinkpy relies on to effectively communicate.
##Login
## Login
Client login to the Blink Servers.
@@ -41,7 +41,7 @@ JSON response containing information including Network ID and Account ID.
Network ID is needed to issue arm/disarm calls
##Sync Modules
## Sync Modules
Obtain information about the Blink Sync Modules on the given network.
@@ -55,7 +55,7 @@ JSON response containing information about the known state of the Sync module, m
Probably not strictly needed but checking result can verify that the sync module is online and will respond to requests to arm/disarm, etc.
##Arm
## Arm
Arm the given network (start recording/reporting motion events)
@@ -68,7 +68,7 @@ JSON response containing information about the arm command request, including th
**Notes:**
When this call returns, it does not mean the arm request is complete, the client must gather the request ID from the response and poll for the status of the command.
##Disarm
## Disarm
Disarm the given network (stop recording/reporting motion events)
@@ -82,7 +82,7 @@ JSON response containing information about the disarm command request, including
When this call returns, it does not mean the disarm request is complete, the client must gather the request ID from the response and poll for the status of the command.
##Command Status
## Command Status
Get status info on the given command
@@ -98,7 +98,7 @@ After an arm/disarm command, the client appears to poll this URL every second or
**Known Commands:**
lv_relay, arm, disarm, thumbnail, clip
##Home Screen
## Home Screen
Return information displayed on the home screen of the mobile client
@@ -207,7 +207,7 @@ Deletes all videos
**Response**
Unknown - not tested
##Cameras
## Cameras
**Request**
Gets a list of cameras
@@ -252,7 +252,7 @@ JSON response containing camera information
*Note*: enabling or disabling motion detection is independent of arming or disarming the system. No motion detection or video recording will take place unless the system is armed.
##Miscellaneous
## Miscellaneous
**Request**
Gets information about devices that have connected to the blink service
+53
View File
@@ -0,0 +1,53 @@
# Changelog
-----------
A list of changes between each release
0.6.0.dev0 (unreleased)
^^^^^^^^^^^^^^^^^^
- Removed redundent properties that only called hidden variables
- Revised request wrapper function to be more intelligent
- Added tests to ensure exceptions are caught and handled (100% coverage!)
0.5.2 (2017-03-12)
^^^^^^^^^^^^^^^^^^
- Fixed packaging mishap, same as 0.5.0 otherwise
0.5.0 (2017-03-12)
^^^^^^^^^^^^^^^^^^
- Fixed region handling problem
- Added rest.piri subdomain as a backup if region can't be found
- Improved the file writing function
- Large test coverage increase
0.4.4 (2017-03-06)
^^^^^^^^^^^^^^^^^^
- Fixed bug where region id was not being set in the header
0.4.3 (2017-03-05)
^^^^^^^^^^^^^^^^^^
- Changed to bdist_wheel release
0.4.2 (2017-01-28)
^^^^^^^^^^^^^^^^^^
- Fixed inability to retrieve motion data due to Key Error
0.4.1 (2017-01-27)
^^^^^^^^^^^^^^^^^^
- Fixed refresh bug (0.3.1 did not actually fix the problem)
- Image refresh routine added (per camera)
- Dictionary of thumbnails per camera added
- Improved test coverage
0.3.1 (2017-01-25)
^^^^^^^^^^^^^^^^^^
- Fixed refresh bug (Key Error)
0.3.0 (2017-01-25)
^^^^^^^^^^^^^^^^^^
- Added device id to camera lookup table
- Added image to file method
0.2.0 (2017-01-21)
^^^^^^^^^^^^^^^^^^
- Initial release of blinkpy
+60 -198
View File
@@ -25,25 +25,22 @@ from helpers.constants import (BLINK_URL, LOGIN_URL,
def _request(url, data=None, headers=None, reqtype='get',
stream=False, json_resp=True):
"""Wrapper function for request."""
if reqtype is 'post' and json_resp:
response = requests.post(url, headers=headers,
data=data).json()
elif reqtype is 'post' and not json_resp:
if reqtype == 'post':
response = requests.post(url, headers=headers,
data=data)
elif reqtype is 'get' and json_resp:
response = requests.get(url, headers=headers,
stream=stream).json()
elif reqtype is 'get' and not json_resp:
elif reqtype == 'get':
response = requests.get(url, headers=headers,
stream=stream)
else:
raise BlinkException(ERROR.REQUEST)
if json_resp and 'code' in response:
if json_resp and 'code' in response.json():
raise BlinkAuthenticationException(
(response['code'], response['message']))
(response.json()['code'], response.json()['message']))
if json_resp:
return response.json()
else:
return response
@@ -81,169 +78,58 @@ class BlinkCamera(object):
def __init__(self, config, urls):
"""Initiailize BlinkCamera."""
self.urls = urls
self._id = str(config['device_id'])
self._name = config['name']
self.id = str(config['device_id']) # pylint: disable=invalid-name
self.name = config['name']
self._status = config['armed']
self._thumb = self.urls.base_url + config['thumbnail'] + '.jpg'
self._clip = self.urls.base_url + config['thumbnail'] + '.mp4'
self._temperature = config['temp']
self._battery = config['battery']
self._notifications = config['notifications']
self._motion = {}
self._header = None
self._image_link = None
self._arm_link = None
self._region_id = config['region_id']
@property
# pylint: disable=invalid-name
def id(self):
"""Return camera id."""
return self._id
@property
def name(self):
"""Return camera name."""
return self._name
@name.setter
def name(self, value):
"""Set camera name."""
self._name = value
@property
def region_id(self):
"""Return region id."""
return self._region_id
self.thumbnail = self.urls.base_url + config['thumbnail'] + '.jpg'
self.clip = self.urls.base_url + config['thumbnail'] + '.mp4'
self.temperature = config['temp']
self.battery = config['battery']
self.notifications = config['notifications']
self.motion = {}
self.header = None
self.image_link = None
self.arm_link = None
self.region_id = config['region_id']
@property
def armed(self):
"""Return camera arm status."""
return self._status
@property
def clip(self):
"""Return current clip."""
return self._clip
@clip.setter
def clip(self, value):
"""Set current clip."""
self._clip = value
@property
def thumbnail(self):
"""Return current thumbnail."""
return self._thumb
@thumbnail.setter
def thumbnail(self, value):
"""Set current thumbnail."""
self._thumb = value
@property
def temperature(self):
"""Return camera temperature."""
return self._temperature
@temperature.setter
def temperature(self, value):
"""Set camera temperature."""
self._temperature = value
@property
def battery(self):
"""Return battery level."""
return self._battery
@battery.setter
def battery(self, value):
"""Set battery level."""
self._battery = value
@property
def notifications(self):
"""Return number of notifications."""
return self._notifications
@notifications.setter
def notifications(self, value):
"""Set number of notifications."""
self._notifications = value
@property
def image_link(self):
"""Return image link."""
return self._image_link
@image_link.setter
def image_link(self, value):
"""Set image link."""
self._image_link = value
@property
def arm_link(self):
"""Return link to arm camera."""
return self._arm_link
@arm_link.setter
def arm_link(self, value):
"""Set link to arm camera."""
self._arm_link = value
@property
def header(self):
"""Return request header."""
return self._header
@header.setter
def header(self, value):
"""Set request header."""
self._header = value
@property
def motion(self):
"""Return last motion event detail."""
return self._motion
@motion.setter
def motion(self, value):
"""Set link to last motion and timestamp."""
self._motion = value
def snap_picture(self):
"""Take a picture with camera to create a new thumbnail."""
_request(self._image_link, headers=self._header, reqtype='post')
_request(self.image_link, headers=self.header, reqtype='post')
def set_motion_detect(self, enable):
"""Set motion detection."""
url = self._arm_link
url = self.arm_link
if enable:
_request(url + 'enable', headers=self._header, reqtype='post')
_request(url + 'enable', headers=self.header, reqtype='post')
else:
_request(url + 'disable', headers=self._header, reqtype='post')
_request(url + 'disable', headers=self.header, reqtype='post')
def update(self, values):
"""Update camera information."""
self._name = values['name']
self.name = values['name']
self._status = values['armed']
self._thumb = self.urls.base_url + values['thumbnail'] + '.jpg'
self._clip = self.urls.base_url + values['thumbnail'] + '.mp4'
self._temperature = values['temp']
self._battery = values['battery']
self._notifications = values['notifications']
self.thumbnail = self.urls.base_url + values['thumbnail'] + '.jpg'
self.clip = self.urls.base_url + values['thumbnail'] + '.mp4'
self.temperature = values['temp']
self.battery = values['battery']
self.notifications = values['notifications']
def image_refresh(self):
"""Refresh current thumbnail."""
url = self.urls.home_url
response = _request(url, headers=self._header,
response = _request(url, headers=self.header,
reqtype='get')['devices']
for element in response:
try:
if str(element['device_id']) == self._id:
self._thumb = (self.urls.base_url +
if str(element['device_id']) == self.id:
self.thumbnail = (self.urls.base_url +
element['thumbnail'] + '.jpg')
return self._thumb
return self.thumbnail
except KeyError:
pass
return None
@@ -251,7 +137,7 @@ class BlinkCamera(object):
def image_to_file(self, path):
"""Write image to file."""
thumb = self.image_refresh()
response = _request(thumb, headers=self._header,
response = _request(thumb, headers=self.header,
reqtype='get', stream=True, json_resp=False)
if response.status_code == 200:
with open(path, 'wb') as imgfile:
@@ -267,27 +153,22 @@ class Blink(object):
self._password = password
self._token = None
self._auth_header = None
self._network_id = None
self._account_id = None
self._region = None
self._region_id = None
self.network_id = None
self.account_id = None
self.region = None
self.region_id = None
self._host = None
self._events = []
self._cameras = {}
self.cameras = {}
self._idlookup = {}
self.urls = None
@property
def cameras(self):
"""Return camera/id pairs."""
return self._cameras
@property
def camera_thumbs(self):
"""Return camera thumbnails."""
self.refresh()
data = {}
for name, camera in self._cameras.items():
for name, camera in self.cameras.items():
data[name] = camera.thumbnail
return data
@@ -297,30 +178,10 @@ class Blink(object):
"""Return id/camera pairs."""
return self._idlookup
@property
def network_id(self):
"""Return network id."""
return self._network_id
@property
def account_id(self):
"""Return account id."""
return self._account_id
@property
def region(self):
"""Return current region."""
return self._region
@property
def region_id(self):
"""Return region id."""
return self._region_id
@property
def events(self):
"""Get all events on server."""
url = self.urls.event_url + self._network_id
url = self.urls.event_url + self.network_id
headers = self._auth_header
self._events = _request(url, headers=headers,
reqtype='get')['event']
@@ -329,7 +190,7 @@ class Blink(object):
@property
def online(self):
"""Return boolean system online status."""
url = self.urls.network_url + self._network_id + '/syncmodules'
url = self.urls.network_url + self.network_id + '/syncmodules'
headers = self._auth_header
return ONLINE[_request(url, headers=headers,
reqtype='get')['syncmodule']['status']]
@@ -340,8 +201,8 @@ class Blink(object):
for element in recent:
try:
camera_id = str(element['camera_id'])
camera_name = self._idlookup[camera_id]
camera = self._cameras[camera_name]
camera_name = self.id_table[camera_id]
camera = self.cameras[camera_name]
if element['type'] == 'motion':
url = self.urls.base_url + element['video_url']
camera.motion = {'video': url,
@@ -362,21 +223,22 @@ class Blink(object):
value_to_append = 'arm'
else:
value_to_append = 'disarm'
url = self.urls.network_url + self._network_id + '/' + value_to_append
url = self.urls.network_url + self.network_id + '/' + value_to_append
_request(url, headers=self._auth_header, reqtype='post')
def refresh(self):
"""Get all blink cameras and pulls their most recent status."""
response = self.get_summary()['devices']
for name in self._cameras:
camera = self._cameras[name]
for name in self.cameras:
camera = self.cameras[name]
for element in response:
try:
if str(element['device_id']) == camera.id:
camera.update(element)
except KeyError:
pass
return None
def get_summary(self):
"""Get a full summary of device information."""
@@ -395,16 +257,16 @@ class Blink(object):
if ('device_type' in element and
element['device_type'] == 'camera'):
# Add region to config
element['region_id'] = self._region_id
element['region_id'] = self.region_id
device = BlinkCamera(element, self.urls)
self._cameras[device.name] = device
self.cameras[device.name] = device
self._idlookup[device.id] = device.name
def set_links(self):
"""Set access links and required headers for each camera in system."""
for name in self._cameras:
camera = self._cameras[name]
network_id_url = self.urls.network_url + self._network_id
for name in self.cameras:
camera = self.cameras[name]
network_id_url = self.urls.network_url + self.network_id
image_url = network_id_url + '/camera/' + camera.id + '/thumbnail'
arm_url = network_id_url + '/camera/' + camera.id + '/'
camera.image_link = image_url
@@ -448,20 +310,20 @@ class Blink(object):
data=data, json_resp=False, reqtype='post')
if response.status_code is 200:
response = response.json()
(self._region_id, self._region), = response['region'].items()
(self.region_id, self.region), = response['region'].items()
else:
response = _request(LOGIN_BACKUP_URL, headers=headers,
data=data, reqtype='post')
self._region_id = 'rest.piri'
self._region = "UNKNOWN"
self.region_id = 'rest.piri'
self.region = "UNKNOWN"
self._host = self._region_id + '.' + BLINK_URL
self._host = self.region_id + '.' + BLINK_URL
self._token = response['authtoken']['authtoken']
self._auth_header = {'Host': self._host,
'TOKEN_AUTH': self._token}
self.urls = BlinkURLHandler(self._region_id)
self.urls = BlinkURLHandler(self.region_id)
def get_ids(self):
"""Set the network ID and Account ID."""
@@ -472,5 +334,5 @@ class Blink(object):
raise BlinkException(ERROR.AUTH_TOKEN)
response = _request(url, headers=headers, reqtype='get')
self._network_id = str(response['networks'][0]['id'])
self._account_id = str(response['networks'][0]['account_id'])
self.network_id = str(response['networks'][0]['id'])
self.account_id = str(response['networks'][0]['account_id'])
+3 -2
View File
@@ -5,8 +5,9 @@ Generates constants for use in blinkpy
import os
MAJOR_VERSION = 0
MINOR_VERSION = 5
PATCH_VERSION = '3.dev0'
MINOR_VERSION = 6
PATCH_VERSION = '0.dev0'
__version__ = '{}.{}.{}'.format(MAJOR_VERSION, MINOR_VERSION, PATCH_VERSION)
REQUIRED_PYTHON_VER = (3, 4, 2)
+2
View File
@@ -1,3 +1,5 @@
flake8==3.3
pylint==1.6.5
pydocstyle==1.1.1
pytest>=2.9.2
pytest-sugar>=0.8.0
+12
View File
@@ -118,6 +118,12 @@ RESPONSE['network'] = {'armed': NETWORKS_RESPONSE['networks'][0]['armed'],
RESPONSE['event'] = [FIRST_EVENT, SECOND_EVENT]
RESPONSE['syncmodule'] = {'name': 'Vengerberg', 'status': 'online'}
BAD_RESPONSE = {}
BAD_RESPONSE['account'] = {'nothing': 'here'}
BAD_RESPONSE['devices'] = [{'foo': 'bar', 'device_type': 'camera'},
{'device_type': 'camera', 'device_id': 2112}]
BAD_RESPONSE['network'] = {'bar': 'foo'}
MOCK_BYTES = '\x00\x10JFIF\x00\x01'
IMAGE_TO_WRITE_URL = list()
@@ -211,7 +217,11 @@ def mocked_requests_get(*args, **kwargs):
# pylint: disable=unused-variable
(region_id, region), = LOGIN_RESPONSE['region'].items()
if args[0] != 'use_bad_response':
set_region_id = args[0].split('/')[2].split('.')[0]
else:
set_region_id = 'ciri'
if set_region_id == 'rest':
set_region_id = (set_region_id + '.' +
args[0].split('/')[2].split('.')[1])
@@ -224,6 +234,8 @@ def mocked_requests_get(*args, **kwargs):
' Expected ' + set_region_id)
elif args[0] in IMAGE_TO_WRITE_URL:
return MockGetResponse({}, 200, raw_data=MOCK_BYTES)
elif args[0] == 'use_bad_response':
return MockGetResponse(BAD_RESPONSE, 200)
else:
return MockGetResponse(RESPONSE, 200)
+13
View File
@@ -105,6 +105,19 @@ class TestBlinkFunctions(unittest.TestCase):
camera = self.blink.cameras[camera_name]
self.assertEqual(camera.thumbnail, test_thumbnail)
@mock.patch('blinkpy.blinkpy.requests.post',
side_effect=mresp.mocked_requests_post)
@mock.patch('blinkpy.blinkpy.requests.get',
side_effect=mresp.mocked_requests_get)
def test_image_with_bad_data(self, mock_get, mock_post):
"""Checks for handling of bad keys."""
self.blink.setup_system()
for camera_name in self.blink.cameras:
camera = self.blink.cameras[camera_name]
camera.snap_picture()
camera.urls.home_url = "use_bad_response"
self.assertEqual(camera.image_refresh(), None)
def test_camera_update(self):
"""Checks that the update function is doing the right thing."""
self.test_urls = blinkpy.BlinkURLHandler('test')
+10
View File
@@ -81,6 +81,16 @@ class TestBlinkSetup(unittest.TestCase):
# pylint: disable=protected-access
blinkpy.blinkpy._request(None, reqtype='post')
@mock.patch('blinkpy.blinkpy.requests.post',
side_effect=mresp.mocked_requests_post)
@mock.patch('blinkpy.blinkpy.requests.get',
side_effect=mresp.mocked_requests_get)
def test_system_bad_refresh(self, mock_get, mock_post):
"""Checks for handling of bad keys."""
self.blink.setup_system()
self.blink.urls.home_url = 'use_bad_response'
self.assertEqual(self.blink.refresh(), None)
@mock.patch('blinkpy.blinkpy.requests.post',
side_effect=mresp.mocked_requests_post)
@mock.patch('blinkpy.blinkpy.requests.get',
+1 -1
View File
@@ -7,7 +7,7 @@ setenv =
LANG=en_US.UTF-8
PYTHONPATH = {toxinidir}
commands =
py.test -v --timeout=30 --duration=10 --cov=blinkpy --cov-report term-missing {posargs}
py.test --timeout=30 --duration=10 --cov=blinkpy --cov-report term-missing {posargs}
deps =
-r{toxinidir}/requirements.txt
-r{toxinidir}/requirements_test.txt