]> git.aero2k.de Git - sirius.git/commitdiff
Connect real database to real protocol loop and fix a few minor bugs.
authorTom Hunger <tehunger@gmail.com>
Thu, 15 Jan 2015 15:37:41 +0000 (15:37 +0000)
committerTom Hunger <tehunger@gmail.com>
Thu, 15 Jan 2015 16:02:50 +0000 (16:02 +0000)
The most interesting bit here is the with app.app_context() for the
websocket code. It's required because the websocket loop needs to access
the database occasionally.

migrations/versions/3be2a0e43b88_sirius_models.py [moved from migrations/versions/4a0698610fcd_sirius_models.py with 96% similarity]
sirius/models/hardware.py
sirius/models/user.py
sirius/protocol/protocol_loop.py
sirius/protocol/test_protocol_loop.py
sirius/web/webapp.py

similarity index 96%
rename from migrations/versions/4a0698610fcd_sirius_models.py
rename to migrations/versions/3be2a0e43b88_sirius_models.py
index 6f7087873a59928f333960cb8cd2442f849e9d6d..07a645c2d3bad9d1f44df4a8373915ae6006360f 100644 (file)
@@ -1,13 +1,13 @@
 """Sirius models.
 
-Revision ID: 4a0698610fcd
+Revision ID: 3be2a0e43b88
 Revises: None
-Create Date: 2015-01-15 11:27:22.373207
+Create Date: 2015-01-15 15:33:10.629707
 
 """
 
 # revision identifiers, used by Alembic.
-revision = '4a0698610fcd'
+revision = '3be2a0e43b88'
 down_revision = None
 
 from alembic import op
@@ -16,6 +16,12 @@ import sqlalchemy as sa
 
 def upgrade():
     ### commands auto generated by Alembic - please adjust! ###
+    op.create_table('user',
+    sa.Column('id', sa.Integer(), nullable=False),
+    sa.Column('created', sa.DateTime(), nullable=True),
+    sa.Column('username', sa.String(), nullable=True),
+    sa.PrimaryKeyConstraint('id')
+    )
     op.create_table('bridge',
     sa.Column('id', sa.Integer(), nullable=False),
     sa.Column('created', sa.DateTime(), nullable=True),
@@ -29,23 +35,17 @@ def upgrade():
     sa.Column('entry', sa.String(), nullable=True),
     sa.PrimaryKeyConstraint('id')
     )
-    op.create_table('user',
+    op.create_table('printer',
     sa.Column('id', sa.Integer(), nullable=False),
     sa.Column('created', sa.DateTime(), nullable=True),
-    sa.Column('username', sa.String(), nullable=True),
+    sa.Column('device_address', sa.String(), nullable=True),
+    sa.Column('hardware_xor', sa.Integer(), nullable=True),
+    sa.Column('name', sa.String(), nullable=True),
+    sa.Column('owner_id', sa.Integer(), nullable=True),
+    sa.Column('used_claim_code', sa.String(), nullable=True),
+    sa.ForeignKeyConstraint(['owner_id'], ['user.id'], ),
     sa.PrimaryKeyConstraint('id')
     )
-    op.create_table('twitter_o_auth',
-    sa.Column('id', sa.Integer(), nullable=False),
-    sa.Column('created', sa.DateTime(), nullable=True),
-    sa.Column('user_id', sa.Integer(), nullable=True),
-    sa.Column('screen_name', sa.String(), nullable=True),
-    sa.Column('token', sa.String(), nullable=True),
-    sa.ForeignKeyConstraint(['user_id'], [u'user.id'], ),
-    sa.PrimaryKeyConstraint('id'),
-    sa.UniqueConstraint('screen_name'),
-    sa.UniqueConstraint('token')
-    )
     op.create_table('claim_code',
     sa.Column('id', sa.Integer(), nullable=False),
     sa.Column('created', sa.DateTime(), nullable=True),
@@ -56,26 +56,26 @@ def upgrade():
     sa.ForeignKeyConstraint(['by_id'], ['user.id'], ),
     sa.PrimaryKeyConstraint('id')
     )
-    op.create_table('printer',
+    op.create_table('twitter_o_auth',
     sa.Column('id', sa.Integer(), nullable=False),
     sa.Column('created', sa.DateTime(), nullable=True),
-    sa.Column('device_address', sa.String(), nullable=True),
-    sa.Column('hardware_xor', sa.Integer(), nullable=True),
-    sa.Column('name', sa.String(), nullable=True),
-    sa.Column('owner_id', sa.Integer(), nullable=True),
-    sa.Column('used_claim_code', sa.String(), nullable=True),
-    sa.ForeignKeyConstraint(['owner_id'], ['user.id'], ),
-    sa.PrimaryKeyConstraint('id')
+    sa.Column('user_id', sa.Integer(), nullable=True),
+    sa.Column('screen_name', sa.String(), nullable=True),
+    sa.Column('token', sa.String(), nullable=True),
+    sa.ForeignKeyConstraint(['user_id'], [u'user.id'], ),
+    sa.PrimaryKeyConstraint('id'),
+    sa.UniqueConstraint('screen_name'),
+    sa.UniqueConstraint('token')
     )
     ### end Alembic commands ###
 
 
 def downgrade():
     ### commands auto generated by Alembic - please adjust! ###
-    op.drop_table('printer')
-    op.drop_table('claim_code')
     op.drop_table('twitter_o_auth')
-    op.drop_table('user')
+    op.drop_table('claim_code')
+    op.drop_table('printer')
     op.drop_table('device_log')
     op.drop_table('bridge')
+    op.drop_table('user')
     ### end Alembic commands ###
index 600799cd06a9aa6258e24fd44a803c03ed214a9e..dd1b486ece925251701c0d36b2ab8573b4ab359b 100644 (file)
@@ -60,6 +60,7 @@ class Printer(db.Model):
             used_claim_code=None,
         )
         db.session.add(printer)
+        db.session.commit()
 
         # Connect hardware xor and printer if there is a claim code
         # waiting.
@@ -75,6 +76,17 @@ class Printer(db.Model):
         printer.name = claim_code.name
         printer.used_claim_code = claim_code.claim_code
         db.session.add(printer)
+        db.session.commit()
+
+    @classmethod
+    def get_claim_code(cls, device_address):
+        """Find and return a claim code."""
+        printer = cls.query.filter_by(device_address=device_address).first()
+        if printer is None:
+            return None
+        db.session.commit()
+
+        return printer.used_claim_code
 
 
 class ClaimCode(db.Model):
index d74d4527f8c2e38c2fb380246e0c6348717e5be3..35d43c1217d3f834ba9e3209b2515686fbd3964a 100644 (file)
@@ -53,7 +53,7 @@ class User(db.Model):
         assert printer_query.count() == 1, \
             "hardware xor collision: {}".format(hardware_xor)
 
-        printer.claim_code = claim_code
+        printer.used_claim_code = claim_code
         printer.hardware_xor = hardware_xor
         printer.owner_id = hcc.by_id
         printer.name = name
index 925a45b9359b623f4f92761df0e580ef3f372710..22b54dc01481935d91e711d67759b3c533400a11 100644 (file)
@@ -13,7 +13,8 @@ import logging
 from sirius.coding import encoders
 from sirius.coding import decoders
 from sirius import stats
-from sirius import database
+
+from sirius.models import hardware
 
 logger = logging.getLogger(__name__)
 
@@ -140,6 +141,7 @@ def _accept_step(x, bridge_state):
     :param bridge_state: The BridgeState for this connection
     """
     if type(x) == messages.DeviceConnect:
+        hardware.Printer.phone_home(x.device_address)
         bridge_state.connected_devices.add(x.device_address)
 
     elif type(x) == messages.DeviceDisconnect:
@@ -149,10 +151,11 @@ def _accept_step(x, bridge_state):
         pass # TODO - write log to a place
 
     elif type(x) == messages.EncryptionKeyRequired:
+        hardware.Printer.phone_home(x.device_address)
         bridge_state.connected_devices.add(x.device_address)
 
-        claimed_device = database.get_claim_code(x.hardware_xor)
-        if claimed_device is None:
+        claim_code = hardware.Printer.get_claim_code(x.device_address)
+        if claim_code is None:
             # It's OK to have an unclaimed device, we just ignore it
             # for now.
             stats.inc('unclaimed.encryption_key_required.count')
@@ -161,12 +164,13 @@ def _accept_step(x, bridge_state):
         add_key = messages.AddDeviceEncryptionKey(
             bridge_address=x.bridge_address,
             device_address=x.device_address,
-            claim_code=claimed_device.claim_code,
+            claim_code=claim_code,
         )
 
         send_message(x.device_address, add_key)
 
     elif type(x) == messages.DeviceHeartbeat:
+        hardware.Printer.phone_home(x.device_address)
         bridge_state.connected_devices.add(x.device_address)
 
     elif type(x) == messages.PowerOn:
index e944c9b8ae7d8cb556c8504491a9de09e097a6a8..f4199c914e944df5e6cc3c3e3c8b3e3285aa36f4 100644 (file)
@@ -4,7 +4,13 @@ Run like:
 
 $ bin/nosetests sirius/
 """
-import unittest
+from flask.ext import testing
+
+# TODO: It's a bit ugly that the protocol loop depends on the flask setup
+# for database access but it's the easiest solution for now.
+from sirius.web import webapp
+from sirius.models.db import db
+from sirius.models import hardware
 
 from sirius.protocol import messages
 from sirius.protocol import protocol_loop
@@ -78,6 +84,21 @@ m_command_response = messages.BridgeCommandResponse(
     timestamp=0,
 )
 
+class BaseTest(testing.TestCase):
+
+    def create_app(self):
+        app = webapp.create_app('test')
+        return app
+
+    def setUp(self):
+        testing.TestCase.setUp(self)
+        db.create_all()
+
+    def tearDown(self):
+        db.session.remove()
+        db.drop_all()
+
+
 class FakeWebsocket:
     "Use to create an in-memory a BridgeState."
     def __init__(self):
@@ -86,9 +107,10 @@ class FakeWebsocket:
         self.messages.append(message)
 
 
-class TestNormalFlow(unittest.TestCase):
+class TestNormalFlow(BaseTest):
     "A bunch of smoke tests that exercise the _accept_step."
     def setUp(self):
+        BaseTest.setUp(self)
         self.bridge_state = protocol_loop.BridgeState(
             FakeWebsocket(), m_power_on.bridge_address)
 
@@ -118,6 +140,13 @@ class TestNormalFlow(unittest.TestCase):
         self.assertNotIn(m_hearbeat.device_address, self.bridge_state.connected_devices)
 
     def test_encryption_key_required(self):
+        # Pretend this printer is claimed:
+        hardware.Printer.phone_home('000d6f000273ce0b')
+        p = hardware.Printer.query.first()
+        p.used_claim_code = 'n5ry-p6x6-kth7-7hc4'
+        db.session.add(p)
+        db.session.commit()
+
         protocol_loop.bridge_by_address = {
             self.bridge_state.address: self.bridge_state
         }
@@ -126,9 +155,10 @@ class TestNormalFlow(unittest.TestCase):
         self.assertEquals(len(self.bridge_state.websocket.messages), 1)
 
 
-class TestBrokenFlow(unittest.TestCase):
+class TestBrokenFlow(BaseTest):
     "Check unexpected interactions."
     def setUp(self):
+        BaseTest.setUp(self)
         self.bridge_state = protocol_loop.BridgeState(
             None, m_power_on.bridge_address)
 
@@ -149,9 +179,10 @@ class TestBrokenFlow(unittest.TestCase):
         protocol_loop._accept_step(m_command_response, self.bridge_state)
 
 
-class TestMultiDevice(unittest.TestCase):
+class TestMultiDevice(BaseTest):
     "What happens when we have more than one device."
     def setUp(self):
+        BaseTest.setUp(self)
         self.bridge_state = protocol_loop.BridgeState(
             FakeWebsocket(), m_power_on.bridge_address)
 
index 5298a0d5df17b9639bdcc3ba69c03f191efddb43..3f4a7051363f47cfd660687c142cb6ce1fb0e814 100644 (file)
@@ -53,7 +53,8 @@ def create_app(config_name):
 
     @sockets.route('/api/v1/connection')
     def api_v1_connection(ws):
-        protocol_loop.accept(ws)
+        with app.app_context():
+            protocol_loop.accept(ws)
 
     logger.debug('Creating app.')
     return app