Skip to content

Commit

Permalink
Merge pull request #26 from Postcard/v0.3.3
Browse files Browse the repository at this point in the history
V0.3.3
  • Loading branch information
benoitguigal committed Jun 2, 2015
2 parents 419dcc9 + 699fd90 commit 7c32b86
Show file tree
Hide file tree
Showing 6 changed files with 96 additions and 73 deletions.
9 changes: 8 additions & 1 deletion figureraspbian/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import pifacedigitalio

from . import processus, settings, utils
from . import processus, settings, api
from .db import Database, managed

# Log configuration
Expand Down Expand Up @@ -40,6 +40,13 @@ def get_listener():
with managed(Database()) as db:
db.update_installation()

logger.info("Downloading ticket css...")
ticket_css_url = "%s/%s" % (settings.API_HOST, 'static/css/ticket.css')
try:
api.download(ticket_css_url, settings.STATIC_ROOT)
except Exception:
pass

listener = get_listener()

try:
Expand Down
9 changes: 6 additions & 3 deletions figureraspbian/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,20 @@ class ApiException(Exception):

session = requests.Session()
session.headers.update({
'As-User': int(settings.USER),
'Authorization': 'Bearer %s' % settings.TOKEN,
'Accept': 'application/json'
'Accept': 'application/json',
})


def get_installation():
url = "%s/resiniodevices/%s/" % (settings.API_HOST, settings.RESIN_DEVICE_UUID)
url = "%s/installations/active/" % settings.API_HOST
r = session.get(url=url, timeout=10)
if r.status_code == 200:
r.encoding = 'utf-8'
return json.loads(r.text)['active_installation']
return json.loads(r.text)
elif r.status_code == 404:
return None
else:
raise ApiException("Failed retrieving installation")

Expand Down
36 changes: 24 additions & 12 deletions figureraspbian/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,22 +148,34 @@ def update(self):
""" Update the installation from Figure API """
installation = api.get_installation()
if installation is not None:
scenario = installation['scenario']
ticket_template = scenario['ticket_template']
# Download all images that have not been previously downloaded
items = [image_variable['items'] for image_variable in ticket_template['image_variables']]
items.append(ticket_template['images'])
items = [item for sub_items in items for item in sub_items]
items = map(lambda x: x['image'], items)
if not self.ticket_template:
local_items = []
else:
local_items = [image_variable['items'] for image_variable in self.ticket_template['image_variables']]
local_items.append(self.ticket_template['images'])
local_items = [item for sub_items in local_items for item in sub_items]
local_items = map(lambda x: x['image'], local_items)
images_to_download = list(set(items) - set(local_items))
for image in images_to_download:
api.download(image, IMAGE_DIR)
is_new = self.id != installation['id']
new_codes = api.get_codes(installation['id']) if is_new else None

if new_codes:
self.codes = new_codes
self.start = installation['start']
self.end = installation['end']
self.id = installation['id']
self.scenario = installation['scenario']
self.ticket_template = self.scenario['ticket_template']
for image in self.ticket_template['images']:
api.download(image['image'], IMAGE_DIR)
for image_variable in self.ticket_template['image_variables']:
for image in image_variable['items']:
api.download(image['image'], IMAGE_DIR)
if is_new:
self.codes = api.get_codes(self.id)
self._p_changed = True
ticket_css_url = "%s/%s" % (settings.API_HOST, 'static/css/ticket.css')
api.download(ticket_css_url, settings.STATIC_ROOT)
self.scenario = scenario
self.ticket_template = ticket_template
self._p_changed = True

def get_code(self):
# claim a code
Expand Down
8 changes: 6 additions & 2 deletions figureraspbian/processus.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import logging
logging.basicConfig(level='INFO')
logger = logging.getLogger(__name__)
import codecs
import io
from PIL import Image

from . import devices, settings, ticketrenderer
Expand Down Expand Up @@ -41,6 +41,10 @@ def run():
# Render ticket
start = time.time()
code = db.get_code()
end = time.time()
logger.info('Successfully claimed code in %s seconds', end - start)

start = time.time()
random_text_selections = [ticketrenderer.random_selection(variable) for
variable in
ticket_template['text_variables']]
Expand All @@ -57,7 +61,7 @@ def run():
random_image_selections)
ticket_html_path = join(settings.STATIC_ROOT, 'ticket.html')

with codecs.open(ticket_html_path, 'w', 'utf-8') as ticket_html:
with io.open(ticket_html_path, mode='w', encoding='utf-8') as ticket_html:
ticket_html.write(rendered_html)

# get ticket as base64 stream
Expand Down
8 changes: 4 additions & 4 deletions figureraspbian/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@ def get_env_setting(setting, default=None):
error_msg = "Set the %s env variable" % setting
raise ImproperlyConfigured(error_msg)

# Resin IO unique identifier
RESIN_DEVICE_UUID = get_env_setting('RESIN_DEVICE_UUID')

# Environment. Dev if local machine. Prod if Raspberry Pi
ENVIRONMENT = get_env_setting('ENVIRONMENT', 'development')
Expand All @@ -32,9 +30,12 @@ def get_env_setting(setting, default=None):
# Http host of the API
API_HOST = get_env_setting('API_HOST', 'http://localhost:8000')

# Access Token to authenticate user to the API
# Token to authenticate to the API
TOKEN = get_env_setting('TOKEN')

# User to whom the device is belonging
USER = get_env_setting('FIGURE_USER')

# Root directory for static files
STATIC_ROOT = get_env_setting('STATIC_ROOT', '/Users/benoit/git/figure-raspbian/static')

Expand Down Expand Up @@ -69,7 +70,6 @@ def get_env_setting(setting, default=None):


def log_config():
logger.info('RESIN_DEVICE_UUID: %s' % RESIN_DEVICE_UUID)
logger.info('ENVIRONMENT: %s' % ENVIRONMENT)
logger.info('FIGURE_DIR: %s' % FIGURE_DIR)
logger.info('API_HOST: %s' % API_HOST)
Expand Down
99 changes: 48 additions & 51 deletions figureraspbian/tests.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# -*- coding: utf8 -*-

from copy import deepcopy
import unittest
import os
from datetime import datetime
Expand Down Expand Up @@ -97,63 +97,32 @@ def test_get_installation(self):
api should get installation
"""
installation = api.get_installation()
self.assertTrue('scenario_obj' in installation)
self.assertTrue('scenario' in installation)
self.assertTrue('start' in installation)
self.assertTrue('end' in installation)
self.assertTrue('place' in installation)

def test_get_scenario(self):
"""
api should get scenario
"""
scenario = api.get_scenario('1')
self.assertTrue('name' in scenario)
self.assertTrue('ticket_template' in scenario)
ticket_template = scenario['ticket_template']
self.assertTrue('images_objects' in ticket_template)
self.assertTrue('text_variables_objects' in ticket_template)
self.assertTrue('image_variables_objects' in ticket_template)

def test_download(self):
"""
api should correctly download a file
"""
downloaded = api.download('static/snapshots/example.jpg', settings.SNAPSHOT_DIR)
self.assertEqual(os.path.basename(downloaded), 'example.jpg')

def test_download_when_redirect(self):
"""
api should correctly download a file when redirect
"""
downloaded = api.download('snapshots/example/', settings.SNAPSHOT_DIR)
path = os.path.join(settings.MEDIA_ROOT, 'snapshots')
url = os.path.join(settings.API_HOST, 'static/snapshots/example.jpg')
downloaded = api.download(url, path)
self.assertEqual(os.path.basename(downloaded), 'example.jpg')

def test_create_random_text_selection(self):
"""
api should create a random text selection
"""
created = api.create_random_text_selection('1', '1')
self.assertIsNotNone(created)

def test_create_random_image_selection(self):
"""
api should create a random text selection
"""
created = api.create_random_image_selection('1', '1')
self.assertIsNotNone(created)

def test_create_ticket(self):
"""
api should create ticket
"""
snapshot = "%s/resources/2_20150331.jpg" % settings.FIGURE_DIR
snapshot = "%s/media/snapshots/example.jpg" % settings.FIGURE_DIR
ticket = snapshot # for testing purposes
code = 'JIKO2'
dt = datetime.now(pytz.timezone(settings.TIMEZONE))
random_text_selections = [('1', {'id': '1', 'text': 'toto'})]
random_image_selections = []
ticket = {
'installation': '2',
'installation': '18',
'snapshot': snapshot,
'ticket': ticket,
'dt': dt,
Expand Down Expand Up @@ -194,8 +163,22 @@ def setUp(self):
]
}
],
"image_variables": [],
"images": []
"image_variables": [{
"owner": "test@figuredevices.com",
"id": 1,
"name": "Profession",
"items": [
{
"image": "http://image1"
},
{
"image": "http://image2"
}
]
}],
"images": [
{"image": "http://image3"},
{"image": "http://image4"}]
}
},
"place": None,
Expand Down Expand Up @@ -237,8 +220,7 @@ def test_update_installation(self):
api.download = MagicMock()
api.get_installation = MagicMock(return_value=self.mock_installation)
api.get_codes = MagicMock(return_value=self.mock_codes)
database = Database()
with managed(database) as db:
with managed(Database()) as db:
self.assertIsNone(db.data.installation.id)
db.update_installation()
installation = db.data.installation
Expand All @@ -248,8 +230,32 @@ def test_update_installation(self):
self.assertEqual(installation.scenario['name'], 'Marabouts')
self.assertIsNotNone(installation.ticket_template)
self.assertEqual(installation.codes, self.mock_codes)
calls = [call("http://image4", os.path.join(settings.MEDIA_ROOT, 'images')),
call("http://image1", os.path.join(settings.MEDIA_ROOT, 'images')),
call("http://image2", os.path.join(settings.MEDIA_ROOT, 'images')),
call("http://image3", os.path.join(settings.MEDIA_ROOT, 'images'))]
api.download.assert_has_calls(calls)

with managed(Database()) as db:
self.assertEqual(db.data.installation.codes, self.mock_codes)
api.download = MagicMock()
db.update_installation()
self.assertFalse(api.download.called)
mock_installation = deepcopy(self.mock_installation)
mock_installation['scenario']['ticket_template']['image_variables'] = [{
"owner": "test@figuredevices.com",
"id": 1,
"name": "Profession",
"items": [
{
"image": "http://image5"
}]}]
mock_installation['scenario']['ticket_template']['images'] = [{"image": "http://image6"}]
api.get_installation = MagicMock(return_value=mock_installation)
db.update_installation()
calls = [call("http://image5", os.path.join(settings.MEDIA_ROOT, 'images')),
call("http://image6", os.path.join(settings.MEDIA_ROOT, 'images'))]
api.download.assert_has_calls(calls)

def test_get_installation_return_none(self):
"""
Expand Down Expand Up @@ -464,15 +470,6 @@ def test_processus(self):
self.assertEqual(len(db.dbroot['tickets']._tickets.items()), 1)


class TestPhantomJS(unittest.TestCase):

def test_save_screenshot(self):
"""
save_screenshot should make a screenshot of ticket.html and save it to a file
"""
phantomjs.save_screenshot('./media/tickets/test.jpg')


if __name__ == '__main__':
unittest.main()

Expand Down

0 comments on commit 7c32b86

Please sign in to comment.