]> git.aero2k.de Git - sirius.git/commitdiff
Test and implement claiming.
authorTom Hunger <tehunger@gmail.com>
Mon, 12 Jan 2015 17:39:14 +0000 (17:39 +0000)
committerTom Hunger <tehunger@gmail.com>
Mon, 12 Jan 2015 17:39:14 +0000 (17:39 +0000)
Claiming can happen before or after a printer calls home
for the first time so we have to test both orders.

sirius/config.py
sirius/models/hardware.py
sirius/models/user.py
sirius/web/test_claiming.py [new file with mode: 0644]

index aa769fb71ada87bb51fcad08f989eebfe6198623..de3c167af6f9b5b792ca04931ed823f2a414f10e 100755 (executable)
@@ -5,11 +5,16 @@ basedir = os.path.abspath(os.path.dirname(__file__))
 class Config:
        SECRET_KEY = os.environ.get('SECRET_KEY') or 'this is the lp2 secret'
        SQLALCHEMY_COMMIT_ON_TEARDOWN = True
-       
+
        @staticmethod
        def init_app(app):
                pass
 
+class TestConfig(Config):
+        DEBUG = True
+       SQLALCHEMY_DATABASE_URI = 'sqlite://'
+
+
 class DevelopmentConfig(Config):
        DEBUG = True
        SQLALCHEMY_DATABASE_URI = os.environ.get('DEV_DATABASE_URL') or \
@@ -18,15 +23,15 @@ class DevelopmentConfig(Config):
 class ProductionConfig(Config):
        SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
                'sqlite:///' + os.path.join(basedir, 'data.sqlite')
-       
+
        @classmethod
        def init_app(cls, app):
                Config.init_app(app)
-       
+
 class HerokuConfig(ProductionConfig):
        SSL_DISABLE = bool(os.environ.get('SSL_DISABLE'))
        DEBUG = True
-       
+
        @classmethod
        def init_app(cls, app):
                ProductionConfig.init_app(app)
@@ -34,7 +39,7 @@ class HerokuConfig(ProductionConfig):
                # handle proxy server headers
                from werkzeug.contrib.fixers import ProxyFix
                app.wsgi_app = ProxyFix(app.wsgi_app)
-               
+
                # log to stderr
                import logging
                from logging import StreamHandler
@@ -47,6 +52,7 @@ config = {
        'development': DevelopmentConfig,
        'production': ProductionConfig,
        'heroku': HerokuConfig,
-       
+       'test': TestConfig,
+
        'default': DevelopmentConfig
-}
\ No newline at end of file
+}
index b4c7ea088a72a692ac00f813904fd5bc95417ac0..29a6e8b9be49ae25872e269ee474c23dbffb0f7b 100644 (file)
@@ -1,5 +1,6 @@
+from sirius.coding import bitshuffle
+
 from sirius.models.db import db
-from sirius.models import user
 
 
 class Bridge(db.Model):
@@ -23,14 +24,53 @@ class Printer(db.Model):
     id = db.Column(db.Integer, primary_key=True)
     created = db.Column(db.DateTime)
     device_address = db.Column(db.String)
-    hardware_xor = db.Column(db.String)
+    hardware_xor = db.Column(db.Integer)
 
     # Update the following fields after we connected (i.e. joined over
     # hardware xor) a claim to a printer. The fields start out as
     # NULL.
-    owner = db.Column(db.Integer, db.ForeignKey(user.User.id), nullable=True)
+    owner_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=True)
     used_claim_code = db.Column(db.String, nullable=True)
 
+    def __repr__(self):
+        return 'Printer {}, xor: {}, owner: {}'.format(
+            self.device_address, self.hardware_xor, self.owner_id)
+
+
+    @classmethod
+    def phone_home(cls, device_address):
+        """This gets called every time the in-memory machinery thinks it has
+        seen a printer for the first time round, e.g. after a
+        re-connect of the websocket.
+        """
+        printer = cls.query.filter_by(device_address=device_address).first()
+        hardware_xor = bitshuffle.hardware_xor_from_device_address(device_address)
+
+        if printer is not None:
+            return
+
+        printer = cls(
+            device_address=device_address,
+            hardware_xor=hardware_xor,
+            owner_id=None,
+            used_claim_code=None,
+        )
+        db.session.add(printer)
+
+        # Connect hardware xor and printer if there is a claim code
+        # waiting.
+        claim_code_query = ClaimCode.query.filter_by(hardware_xor=hardware_xor)
+        claim_code = claim_code_query.first()
+        if claim_code is None:
+            return
+
+        assert claim_code_query.count() == 1, \
+            "claim code hardware xor collision: {}".format(hardware_xor)
+
+        printer.owner_id = claim_code.by_id
+        printer.used_claim_code = claim_code.claim_code
+        db.session.add(printer)
+
 
 class ClaimCode(db.Model):
     """Printer and claim codes are joined over the hardware xor. There are
@@ -61,10 +101,12 @@ class ClaimCode(db.Model):
     id = db.Column(db.Integer, primary_key=True)
     __tablename__ = 'claim_code'
     created = db.Column(db.DateTime)
-    by = db.Column(db.ForeignKey(user.User.id))
-    hardware_xor = db.Column(db.String)
+    by_id = db.Column(db.ForeignKey('user.id'))
+    hardware_xor = db.Column(db.Integer)
     claim_code = db.Column(db.String)
 
+    def __repr__(self):
+        return '<ClaimCode xor: {} code: {}>'.format(self.hardware_xor, self.claim_code)
 
 class DeviceLog(db.Model):
     """The device log Recorde state changes in the bridge and connected
index 142db39570590554aa645c46b557c8a38ee26665..e021a959439c26dc2d8ebf64236f319c59ff73ef 100644 (file)
@@ -1,7 +1,10 @@
 """User models. Login only via twitter for now to avoid the whole
 forgot-password/reset-password dance.
 """
+from sirius.coding import claiming
+
 from sirius.models.db import db
+from sirius.models import hardware
 
 class User(db.Model):
     __tablename__ = 'user'
@@ -10,6 +13,37 @@ class User(db.Model):
     # providers. For now we just copy the  twitter handle.
     username = db.Column(db.String)
 
+    def __repr__(self):
+        return 'User {}'.format(self.username)
+
+    def claim_printer(self, claim_code):
+        """Claiming can happen before the printer "calls home" for the first
+        time so we need to be able to deal with that."""
+
+        hardware_xor, _ = claiming.process_claim_code(claim_code)
+        hcc = hardware.ClaimCode(
+            by_id=self.id,
+            hardware_xor=hardware_xor,
+            claim_code=claim_code,
+        )
+        db.session.add(hcc)
+
+        # Check whether we've seen this printer and if so: connect it
+        # to claim code and make it "owned".
+        printer_query = hardware.Printer.query.filter_by(
+            hardware_xor=hardware_xor)
+        printer = printer_query.first()
+        if printer is None:
+            return
+
+        assert printer_query.count() == 1, \
+            "hardware xor collision: {}".format(hardware_xor)
+
+        printer.claim_code = claim_code
+        printer.hardware_xor = hardware_xor
+        printer.owner_id = hcc.by_id
+        db.session.add(printer)
+
 
 class TwitterOAuth(db.Model):
     __tablename__ = 'twitter_oauth'
diff --git a/sirius/web/test_claiming.py b/sirius/web/test_claiming.py
new file mode 100644 (file)
index 0000000..d674c49
--- /dev/null
@@ -0,0 +1,40 @@
+from flask.ext import testing
+
+
+from sirius.models import user
+from sirius.models import hardware
+from sirius.models.db import db
+from sirius.web import webapp
+
+class TestClaiming(testing.TestCase):
+
+    def create_app(self):
+        app = webapp.create_app('test')
+        return app
+
+    def setUp(self):
+        testing.TestCase.setUp(self)
+        db.create_all()
+        self.testuser = user.User(username="testuser")
+        db.session.add(self.testuser)
+        db.session.commit()
+
+    def tearDown(self):
+        db.session.remove()
+        db.drop_all()
+
+    def test_claim_first(self):
+        self.testuser.claim_printer('n5ry-p6x6-kth7-7hc4')
+        hardware.Printer.phone_home('000d6f000273ce0b')
+        db.session.commit()
+        printer = hardware.Printer.query.first()
+
+        self.assertEqual(printer.owner_id, self.testuser.id)
+
+    def test_printer_phone_home_first(self):
+        hardware.Printer.phone_home('000d6f000273ce0b')
+        self.testuser.claim_printer('n5ry-p6x6-kth7-7hc4')
+        db.session.commit()
+        printer = hardware.Printer.query.first()
+
+        self.assertEqual(printer.owner_id, self.testuser.id)