Exemplo n.º 1
0
    def test_accept_unlisten(self):
        def listen_callback(data, is_subscribed, response):
            response.accept()

        self.client.event.listen('a/.*', listen_callback)
        self.client.event.handle({
            'topic': 'E',
            'action': 'SP',
            'data': ['a/.*', 'a/1']
        })

        self.handler.assert_called_with(msg('E|LA|a/.*|a/1+'))

        self.client.event.unlisten('a/.*')
        self.handler.assert_called_with(msg('E|UL|a/.*+'))

        self.handler.reset_mock()
        self.client.event.handle({
            'topic': 'E',
            'action': 'A',
            'data': ['UL', 'a/.*']
        })
        self.client.on('error', self.error_callback)
        self.client.event.handle({
            'topic': 'E',
            'action': 'SP',
            'data': ['a/.*', 'a/1']
        })
        self.error_callback.assert_called_with('a/.*', 'UNSOLICITED_MESSAGE',
                                               'E')
        self.handler.assert_not_called()

        self.client.event.unlisten('a/.*')
        self.error_callback.assert_called_with('a/.*', 'NOT_LISTENING', 'X')
Exemplo n.º 2
0
    def test_send(self):
        # Send auto ACK
        response = rpc.RPCResponse(self.connection, 'addTwo', '123')
        self.io_loop.call_later(1, self.stop)
        self.wait()
        self.handler.assert_called_with(msg('P|A|REQ|addTwo|123+'))

        # Send response
        response.send(14)
        self.handler.assert_called_with(msg('P|RES|addTwo|123|N14+'))
Exemplo n.º 3
0
 def test_add_log_entry_response_ok(self):
     message = msg(topic='/test/home/sensor', payload='123445')
     with test_database(test_db, (Log, Topic), create_tables=True):
         logs = LogController()
         result = logs.add_entry(message)
         parsedResponse = json.loads(result)
         self.assertEqual('OK', parsedResponse['result'])
Exemplo n.º 4
0
 def setUp(self):
     self.payload = {}
     self.payload['client'] = "testClient"
     self.payload['password'] = Settings.MANAGEMENT_PASSWORD
     self.payload['topic'] = "/test/topic/1"
     self.msg = msg(topic=Settings.ROOT_TOPIC + '/topics/add',
                    payload=json.dumps(self.payload))
Exemplo n.º 5
0
    def test_delete_entries_older_than_10_days_from_invalid_topic(self):
        with test_database(test_db, (Log, Topic), create_tables=True):
            self.client.subscribe('/test/topic/test1')
            self.client.subscribe('/test/topic/test2')
            self.client.subscribe('/test/topic/test3')
            Topic.create(name='/test/topic/test1')
            Topic.create(name='/test/topic/test2')
            Topic.create(name='/test/topic/test3')

            Log.create(timestamp=datetime.now() - timedelta(days=40),
                       value="12",
                       topic='/test/topic/test1')
            Log.create(timestamp=datetime.now() - timedelta(days=30),
                       value="12",
                       topic='/test/topic/test1')
            Log.create(timestamp=datetime.now() - timedelta(days=20),
                       value="12",
                       topic='/test/topic2/test2')
            Log.create(timestamp=datetime.now() - timedelta(days=20),
                       value="12",
                       topic='/test/topic/test1')
            Log.create(timestamp=datetime.now() - timedelta(days=10),
                       value="12",
                       topic='/test/topic/test1')
            self.payload['options'] = 10
            self.payload['password'] = Settings.QUERY_PASSWORD
            self.payload['topic'] = '/test/topic/invalid_topic'
            self.msg = msg(topic=Settings.ROOT_TOPIC + 'log/delete/days',
                           payload=json.dumps(self.payload))
            mqtt_controller = MqttController()
            result = mqtt_controller.on_message(self.client, self.msg)
            self.assertEqual('OK',
                             json.loads(self.client.last_publish)['result'])
            self.assertEqual('0',
                             json.loads(self.client.last_publish)['values'])
Exemplo n.º 6
0
    def test_delete_entries_older_than_25_days(self):
        with test_database(test_db, (Log, Topic), create_tables=True):
            self.client.subscribe('/test/topic/test1')
            self.client.subscribe('/test/topic/test2')
            self.client.subscribe('/test/topic/test3')
            Topic.create(name='/test/topic/test1')
            Topic.create(name='/test/topic/test2')
            Topic.create(name='/test/topic/test3')

            Log.create(timestamp=datetime.now() - timedelta(days=40),
                       value="12",
                       topic='/test/topic/test1')
            Log.create(timestamp=datetime.now() - timedelta(days=30),
                       value="12",
                       topic='/test/topic/test1')
            Log.create(timestamp=datetime.now() - timedelta(days=20),
                       value="12",
                       topic='/test/topic2/test2')
            Log.create(timestamp=datetime.now() - timedelta(days=20),
                       value="12",
                       topic='/test/topic/test1')
            Log.create(timestamp=datetime.now() - timedelta(days=10),
                       value="12",
                       topic='/test/topic/test1')
            self.payload['options'] = 25
            self.payload['password'] = Settings.QUERY_PASSWORD
            self.payload['topic'] = '/test/topic/test1'
            self.msg = msg(topic=Settings.ROOT_TOPIC + 'log/delete/days',
                           payload=json.dumps(self.payload))
            mqtt_controller = MqttController()
            result = mqtt_controller.on_message(self.client, self.msg)
            result_logs = Log.select().where(Log.topic == '/test/topic/test1')
            self.assertEqual(2, result_logs.count())
Exemplo n.º 7
0
    def test_on_message_delete_last_entry_from_topic(self):
        with test_database(test_db, (Log, Topic), create_tables=True):
            self.client.subscribed_topics = []
            self.client.subscribe('/test/topic/test1')
            self.client.subscribe('/test/topic/test2')
            self.client.subscribe('/test/topic/test3')
            Topic.create(name='/test/topic/test1')
            Topic.create(name='/test/topic/test2')
            Topic.create(name='/test/topic/test3')
            Log.create(timestamp=datetime.now(),
                       topic='/test/topic/test1',
                       value='10')
            Log.create(timestamp=datetime.now(),
                       topic='/test/topic/test2',
                       value='11')
            Log.create(timestamp=datetime.now(),
                       topic='/test/topic/test1',
                       value='12')

            self.payload['options'] = None
            self.payload['password'] = Settings.QUERY_PASSWORD
            self.payload['topic'] = '/test/topic/test1'
            self.msg = msg(topic=Settings.ROOT_TOPIC + 'log/delete/last',
                           payload=json.dumps(self.payload))
            mqtt_controller = MqttController()
            result = mqtt_controller.on_message(self.client, self.msg)
            result_logs = Log.select().where(Log.topic == '/test/topic/test1')
            self.assertTrue('OK',
                            json.loads(self.client.last_publish)['result'])
            self.assertEqual(1, result_logs.count())
            self.assertEqual('10', result_logs[0].value)
Exemplo n.º 8
0
    def test_get_entries_with_invalid_time_range(self):
        with test_database(test_db, (Log, Topic), create_tables=True):
            self.client.subscribe('/test/topic/test1')
            self.client.subscribe('/test/topic/test2')
            self.client.subscribe('/test/topic/test3')
            Topic.create(name='/test/topic/test1')
            Topic.create(name='/test/topic/test2')
            Topic.create(name='/test/topic/test3')

            Log.create(timestamp=datetime.now() - timedelta(days=30),
                       value="12",
                       topic='/test/topic/test1')
            Log.create(timestamp=datetime.now() - timedelta(days=20),
                       value="12",
                       topic='/test/topic2/test2')
            Log.create(timestamp=datetime.now() - timedelta(days=20),
                       value="12",
                       topic='/test/topic/test1')
            Log.create(timestamp=datetime.now() - timedelta(days=10),
                       value="12",
                       topic='/test/topic/test1')
            self.payload['options'] = 25
            self.payload['password'] = Settings.QUERY_PASSWORD
            self.payload['topic'] = '/test/topic/test1'
            self.msg = msg(topic=Settings.ROOT_TOPIC +
                           'log/query/invalid_time',
                           payload=json.dumps(self.payload))
            mqtt_controller = MqttController()
            result = mqtt_controller.on_message(self.client, self.msg)
            self.assertEqual('KO',
                             json.loads(self.client.last_publish)['result'])
            self.assertEqual('Invalid unit time',
                             json.loads(self.client.last_publish)['error'])
Exemplo n.º 9
0
    def test_on_message_get_last_entry_from_invalid_topic(self):
        with test_database(test_db, (Log, Topic), create_tables=True):
            self.client.subscribed_topics = []
            self.client.subscribe('/test/topic/test1')
            self.client.subscribe('/test/topic/test2')
            self.client.subscribe('/test/topic/test3')
            Topic.create(name='/test/topic/test1')
            Topic.create(name='/test/topic/test2')
            Topic.create(name='/test/topic/test3')
            Log.create(timestamp=datetime.now(),
                       topic='/test/topic/test1',
                       value='10')
            Log.create(timestamp=datetime.now(),
                       topic='/test/topic/test2',
                       value='11')
            Log.create(timestamp=datetime.now(),
                       topic='/test/topic/test1',
                       value='12')

            self.payload['options'] = None
            self.payload['password'] = Settings.QUERY_PASSWORD
            self.payload['topic'] = '/test/topic/test_invalid'
            self.msg = msg(topic=Settings.ROOT_TOPIC + 'log/query/last',
                           payload=json.dumps(self.payload))
            mqtt_controller = MqttController()
            result = mqtt_controller.on_message(self.client, self.msg)
            self.assertTrue('OK',
                            json.loads(self.client.last_publish)['result'])
            self.assertFalse(json.loads(self.client.last_publish)['values'][0])
Exemplo n.º 10
0
 def setUp(self):
     self.payload = {}
     self.payload['client'] = 'testClient'
     self.payload['password'] = Settings.QUERY_PASSWORD
     self.payload['topic'] = '/test/topic'
     self.payload['options'] = '25'
     self.msg = msg(topic=Settings.ROOT_TOPIC + '/topics/add', payload=json.dumps(self.payload))
Exemplo n.º 11
0
 def test_on_message_add_log_entry_to_not_valid_topic(self):
     with test_database(test_db, (Log, Topic), create_tables=True):
         self.client.subscribed_topics = []
         self.client.subscribe('/test/topic/test1')
         Topic.create(name='/test/topic/test1')
         self.msg = msg(topic='/test/topic/test2', payload='12')
         mqtt_controller = MqttController()
         result = mqtt_controller.on_message(self.client, self.msg)
         self.assertEqual(0, Log.select().count())
Exemplo n.º 12
0
    def test_handler(self):
        self.handler.assert_not_called()
        self.client.event.emit('myEvent', 6)
        self.handler.assert_called_with(msg('E|EVT|myEvent|N6+'))

        self.client.event.subscribe('myEvent', self.event_callback)
        self.handler.assert_called_with(msg('E|S|myEvent+'))

        self.client.on('error', self.error_callback)
        self.event_callback.assert_not_called()
        self.client.event.handle({
            'topic': 'EVENT',
            'action': 'EVT',
            'data': ['myEvent', 'N23']
        })
        self.event_callback.assert_called_with(23)

        self.client.event.handle({
            'topic': 'EVENT',
            'action': 'EVT',
            'data': ['myEvent']
        })
        self.event_callback.assert_called_with()

        self.client.event.handle({
            'topic': 'EVENT',
            'action': 'EVT',
            'data': ['myEvent', 'notTypes']
        })
        self.error_callback.assert_called_with('UNKNOWN_TYPE (notTypes)',
                                               'MESSAGE_PARSE_ERROR', 'X')
        self.event_callback.reset_mock()
        self.client.event.unsubscribe('myEvent', self.event_callback)
        self.client.event.emit('myEvent', 11)
        self.event_callback.assert_not_called()

        self.client.event.handle({
            'topic': 'EVENT',
            'action': 'L',
            'data': ['myEvent']
        })
        self.error_callback.assert_called_with('myEvent',
                                               'UNSOLICITED_MESSAGE', 'E')
Exemplo n.º 13
0
    def test_reject(self):
        def listen_callback(data, is_subscribed, response):
            response.reject()

        self.client.event.listen('b/.*', listen_callback)
        self.client.event.handle({
            'topic': 'E',
            'action': 'SP',
            'data': ['b/.*', 'b/1']
        })

        self.handler.assert_called_with(msg('E|LR|b/.*|b/1+'))
Exemplo n.º 14
0
    def setUp(self):
        self.client = Mock_Client()
        self.client.subscribe('/test/topic/test1')
        self.client.subscribe('/test/topic/test2')
        self.client.subscribe('/test/topic/test3')

        self.payload = {}
        self.payload['client'] = 'testClient'
        self.payload['password'] = Settings.QUERY_PASSWORD
        self.payload['topic'] = '/test/topic'
        self.payload['options'] = '25'
        self.msg = msg(topic=Settings.ROOT_TOPIC + 'topic/add',
                       payload=json.dumps(self.payload))
Exemplo n.º 15
0
    def test_accept(self):
        def listen_callback(data, is_subscribed, response):
            response.accept()

        self.client.event.listen('a/.*', listen_callback)
        self.client.event.handle({
            'topic': 'E',
            'action': 'SP',
            'data': ['a/.*', 'a/1']
        })

        self.handler.assert_called_with(msg('E|LA|a/.*|a/1+'))
        for call in self.reactor.getDelayedCalls():
            call.cancel()
Exemplo n.º 16
0
    def test_send_no_autoack(self):
        # Create response but disable autoack
        response = rpc.RPCResponse(self.connection, 'addTwo', '123')
        response.auto_ack = False
        self.handler.assert_not_called()

        # Send the ack
        response.ack()
        self.handler.assert_called_with(msg('P|A|REQ|addTwo|123+'))

        # Do not send multiple ack messages
        self.handler.reset_mock()
        response.ack()
        self.handler.assert_not_called()
Exemplo n.º 17
0
    def test_on_message_add_topic(self):
        with test_database(test_db, (Log, Topic), create_tables=True):
            self.client.subscribed_topics = []
            self.client.subscribe('/test/topic/test1')
            self.client.subscribe('/test/topic/test2')
            self.client.subscribe('/test/topic/test3')

            self.payload['options'] = None
            self.payload['topic'] = '/test/valid_topic/to_add'
            self.payload['password'] = Settings.MANAGEMENT_PASSWORD
            self.msg = msg(topic=Settings.ROOT_TOPIC + 'topic/add',
                           payload=json.dumps(self.payload))
            mqtt_controller = MqttController()
            result = mqtt_controller.on_message(self.client, self.msg)
            self.assertEqual(4, len(self.client.subscribed_topics))
Exemplo n.º 18
0
    def test_accept_and_discard(self):
        def listen_callback(data, is_subscribed, response=None):
            if is_subscribed:
                response.accept()

                self.client.event.handle({
                    'topic': 'E',
                    'action': 'SR',
                    'data': ['b/.*', 'b/2']
                })

        self.client.event.listen('b/.*', listen_callback)
        self.client.event.handle({
            'topic': 'E',
            'action': 'SP',
            'data': ['b/.*', 'b/2']
        })

        self.handler.assert_called_with(msg('E|LA|b/.*|b/2+'))
Exemplo n.º 19
0
    def test_on_message_list_topics_good_password(self):
        with test_database(test_db, (Log, Topic), create_tables=True):
            self.client.subscribed_topics = []
            self.client.subscribe('/test/topic/test1')
            self.client.subscribe('/test/topic/test2')
            self.client.subscribe('/test/topic/test3')
            Topic.create(name='/test/topic/test1')
            Topic.create(name='/test/topic/test2')
            Topic.create(name='/test/topic/test3')

            self.payload['options'] = None
            self.payload['password'] = Settings.QUERY_PASSWORD
            self.msg = msg(topic=Settings.ROOT_TOPIC + 'topic/list',
                           payload=json.dumps(self.payload))
            mqtt_controller = MqttController()
            result = mqtt_controller.on_message(self.client, self.msg)
            self.assertTrue('OK',
                            json.loads(self.client.last_publish)['result'])
            self.assertEqual(
                3, len(json.loads(self.client.last_publish)['topics']))
Exemplo n.º 20
0
    def test_on_message_invalid_log_action(self):
        with test_database(test_db, (Log, Topic), create_tables=True):
            self.client.subscribed_topics = []
            self.client.subscribe('/test/topic/test1')
            self.client.subscribe('/test/topic/test2')
            self.client.subscribe('/test/topic/test3')
            Topic.create(name='/test/topic/test1')
            Topic.create(name='/test/topic/test2')
            Topic.create(name='/test/topic/test3')

            self.payload['options'] = None
            self.payload['password'] = Settings.QUERY_PASSWORD
            self.msg = msg(topic=Settings.ROOT_TOPIC + 'log/invalid_option',
                           payload=json.dumps(self.payload))
            mqtt_controller = MqttController()
            result = mqtt_controller.on_message(self.client, self.msg)
            self.assertTrue('KO',
                            json.loads(self.client.last_publish)['result'])
            self.assertEqual('Error: Invalid Log Option',
                             json.loads(self.client.last_publish)['error'])
Exemplo n.º 21
0
    def test_on_message_remove_not_valid_topic(self):
        with test_database(test_db, (Log, Topic), create_tables=True):
            self.client.subscribed_topics = []
            self.client.subscribe('/test/topic/test1')
            self.client.subscribe('/test/topic/test2')
            self.client.subscribe('/test/topic/test3')
            Topic.create(name='/test/topic/test1')
            Topic.create(name='/test/topic/test2')
            Topic.create(name='/test/topic/test3')

            self.payload['options'] = None
            self.payload['topic'] = '/test/topic/not_valid_topic'
            self.payload['password'] = Settings.MANAGEMENT_PASSWORD
            self.msg = msg(topic=Settings.ROOT_TOPIC + 'topic/remove',
                           payload=json.dumps(self.payload))
            mqtt_controller = MqttController()
            result = mqtt_controller.on_message(self.client, self.msg)
            self.assertEqual(3, len(self.client.subscribed_topics))
            self.assertEqual('Topic not found',
                             json.loads(self.client.last_publish)['error'])
Exemplo n.º 22
0
    def test_on_message_list_topics_bad_password(self):
        with test_database(test_db, (Log, Topic), create_tables=True):
            self.client.subscribed_topics = []
            self.client.subscribe('/test/topic/test1')
            self.client.subscribe('/test/topic/test2')
            self.client.subscribe('/test/topic/test3')
            Topic.create(name='/test/topic/test1')
            Topic.create(name='/test/topic/test2')
            Topic.create(name='/test/topic/test3')

            self.payload['options'] = None
            self.payload['topic'] = '/test/topic/not_valid_topic'
            self.payload['password'] = '******'
            self.msg = msg(topic=Settings.ROOT_TOPIC + 'topic/list',
                           payload=json.dumps(self.payload))
            mqtt_controller = MqttController()
            result = mqtt_controller.on_message(self.client, self.msg)
            self.assertFalse('topics' in json.loads(self.client.last_publish))
            self.assertEqual('Bad Password',
                             json.loads(self.client.last_publish)['error'])
Exemplo n.º 23
0
    def test_make_rpcs(self):
        # RPCHandler is created
        rpchandler = self.client.rpc
        self.assertTrue(isinstance(self.client.rpc, rpc.RPCHandler))

        # Make a successful RPC for addTwo
        rpc_callback = mock.Mock()
        rpchandler.make('addTwo', {'numA': 3, 'numB': 8}, rpc_callback)
        self.assertTrue(self.handler.call_args[0][0] in (
            msg('P|REQ|addTwo|1|O{"numA":3,"numB":8}+'),
            msg('P|REQ|addTwo|1|O{"numB":8,"numA":3}+')))

        rpchandler.handle({
            'topic': 'RPC',
            'action': 'RES',
            'data': ['addTwo', u'1', 'N11']
        })

        rpc_callback.assert_called_with(None, 11)

        # Make RPC for addTwo but receive an error
        self.assertTrue(self.handler.call_args[0][0] in (
            msg('P|REQ|addTwo|1|O{"numA":3,"numB":8}+'),
            msg('P|REQ|addTwo|1|O{"numB":8,"numA":3}+')))

        rpchandler.make('addTwo', {'numA': 3, 'numB': 8}, rpc_callback)
        rpchandler.handle({
            'topic': 'RPC',
            'action': 'E',
            'data': ['NO_PROVIDER', 'addTwo', '1']
        })
        rpc_callback.assert_called_with('NO_PROVIDER', None)
        rpc_callback.reset_mock()

        # Make RPC for addTwo but receive no ack in time
        rpchandler.make('addTwo', {'numA': 3, 'numB': 8}, rpc_callback)
        self.assertTrue(self.handler.call_args[0][0] in (
            msg('P|REQ|addTwo|1|O{"numA":3,"numB":8}+'),
            msg('P|REQ|addTwo|1|O{"numB":8,"numA":3}+')))

        self.connection._io_loop.call_later(2, self.stop)
        self.wait()
        rpc_callback.assert_called_with('ACK_TIMEOUT', None)
Exemplo n.º 24
0
    def testhandle_rpc_providers(self):
        self.assertEqual(self.client._factory._state,
                         constants.connection_state.OPEN)
        # RPCHandler is created
        rpchandler = self.client.rpc
        self.assertTrue(isinstance(self.client.rpc, rpc.RPCHandler))

        # Register a provider for addTwo RPC
        rpchandler.provide('addTwo', self._add_two_callback)
        self.handler.assert_called_once_with(msg('P|S|addTwo+'))
        self.assertEquals(self.rpc_calls, 0)

        # Timeout error emitted if no ack message received on time
        self.wait()
        expected_error = ('No ACK message received in time for addTwo',
                          'ACK_TIMEOUT', 'P')
        self.assertTrue(expected_error in self.client_errors)

        # Reply to a sync RPC request
        rpchandler.handle({
            'topic':
            'RPC',
            'action':
            'REQ',
            'data': ['addTwo', '678', 'O{"numA":2,"numB":3,"sync":true}']
        })
        self.wait()
        self.handler.assert_called_with(msg('P|RES|addTwo|678|N5+'))

        # Reply to an async RPC request
        rpchandler.handle({
            'topic': 'RPC',
            'action': 'REQ',
            'data': ['addTwo', '123', 'O{"numA":7,"numB":3}']
        })

        self.connection._io_loop.call_later(0.1, self.stop)
        self.wait()
        self.handler.assert_called_with(msg('P|A|REQ|addTwo|123+'))

        self.wait()
        self.handler.assert_called_with(msg('P|RES|addTwo|123|N10+'))

        # Send rejection if no provider exists
        rpchandler.handle({
            'topic':
            'RPC',
            'action':
            'REQ',
            'data': ['doesNotExist', '432', 'O{"numA":7,"numB":3}']
        })
        self.handler.assert_called_with(msg('P|REJ|doesNotExist|432+'))

        # Deregister provider for the addTwo RPC
        rpchandler.unprovide('addTwo')
        self.handler.assert_called_with(msg('P|US|addTwo+'))

        # Timeout emitted after no ACK message received for the unprovide
        self.client_errors = []
        self.connection._io_loop.call_later(3.5, self.stop)
        self.wait()
        expected_error = ('No ACK message received in time for addTwo',
                          'ACK_TIMEOUT', 'P')
        self.assertTrue(expected_error in self.client_errors)

        # Reject call to deregistered provider
        rpchandler.handle({
            'topc':
            'RPC',
            'action':
            'REQ',
            'data': ['addTwo', '434', 'O{"numA":2,"numB":7, "sync": true}']
        })

        self.handler.assert_called_with(msg('P|REJ|addTwo|434+'))
Exemplo n.º 25
0
 def test_error(self):
     response = rpc.RPCResponse(self.connection, 'addTwo', '123')
     response.error('Error message')
     self.handler.assert_called_with(msg('P|E|Error message|addTwo|123+'))
     self.assertRaises(ValueError, functools.partial(response.send, 'abc'))
Exemplo n.º 26
0
 def test_reject(self):
     response = rpc.RPCResponse(self.connection, 'addTwo', '123')
     response.reject()
     self.handler.assert_called_with(msg('P|REJ|addTwo|123+'))
     self.assertRaises(ValueError, functools.partial(response.send, 'abc'))