Esempio n. 1
0
    def test_topic_is_archive_topic(self):
        """ This is a big hack to attempt to test the following in genLoopPackets
                if topic == self.archive_topic:
                    continue
        """

        topic = ''.join([
            random.choice(string.ascii_letters + string.digits)
            for n in range(32)
        ])

        config_dict = {}
        config_dict['topic'] = topic
        config_dict['archive_topic'] = topic

        packet = None

        with mock.patch('user.MQTTSubscribe.MQTTSubscriber') as mock_manager:
            with mock.patch('user.MQTTSubscribe.time') as mock_time:
                type(
                    mock_manager.return_value
                ).subscribed_topics = mock.PropertyMock(return_value=[topic])
                mock_time.sleep.side_effect = mock.Mock(
                    side_effect=SystemExit()
                )  # Hack one, use this to escape the infinit loop
                with self.assertRaises(SystemExit):
                    SUT = MQTTSubscribeDriver(**config_dict)

                    gen = SUT.genLoopPackets()
                    packet = next(gen)

                mock_time.sleep.assert_called_once()
                self.assertIsNone(
                    packet
                )  # hack two, the generator never really returns because of the side effect exception
Esempio n. 2
0
    def test_queue_empty(self):
        topic = ''.join([
            random.choice(string.ascii_letters + string.digits)
            for n in range(32)
        ])
        self.setup_queue_tests(topic)
        queue = dict({'name': topic})

        with mock.patch('user.MQTTSubscribe.MQTTSubscriber') as mock_manager:
            with mock.patch('user.MQTTSubscribe.time') as mock_time:
                type(mock_manager.return_value).queues = mock.PropertyMock(
                    return_value=[queue])
                type(mock_manager.return_value).get_data = mock.Mock(
                    side_effect=[
                        self.empty_generator(),
                        self.generator([self.queue_data])
                    ])

                SUT = MQTTSubscribeDriver(**self.config_dict)
                gen = SUT.genLoopPackets()
                next(gen, None)

                mock_time.sleep.assert_called_once()
                self.assertEqual(mock_manager.return_value.get_data.call_count,
                                 2)
Esempio n. 3
0
    def test_close_port():
        config_dict = {}
        config_dict['topic'] = 'foo/bar'

        with mock.patch('user.MQTTSubscribe.MQTTSubscriber'):
            SUT = MQTTSubscribeDriver(**config_dict)
            SUT.closePort()
            SUT.subscriber.disconnect.assert_called_once()  # pylint: disable=no-member
Esempio n. 4
0
    def test_close_port():
        config_dict = {}
        config_dict['topic'] = ''.join([
            random.choice(string.ascii_letters + string.digits)
            for n in range(32)
        ])

        with mock.patch('user.MQTTSubscribe.MQTTSubscriber'):
            SUT = MQTTSubscribeDriver(**config_dict)
            SUT.closePort()
            SUT.subscriber.disconnect.assert_called_once()  # pylint: disable=no-member
    def test_queuereturns_none(self):
        archive_topic = 'archive'
        self.setup_archive_queue_tests(archive_topic)

        with mock.patch('user.MQTTSubscribe.MQTTSubscriber') as mock_manager:
            type(mock_manager.return_value).get_data = mock.Mock(return_value=self.generator([None]))

            SUT = MQTTSubscribeDriver(**self.config_dict)
            gen = SUT.genArchiveRecords(0)
            data = next(gen, None)

            self.assertIsNone(data)
Esempio n. 6
0
    def test_archive_topic_not_set(self):
        config_dict = {}
        config_dict['topics'] = {}

        records = list()

        with mock.patch('user.MQTTSubscribe.MQTTSubscriber'):
            with self.assertRaises(NotImplementedError) as error:
                SUT = MQTTSubscribeDriver(**config_dict)

                for record in SUT.genArchiveRecords(int(time.time() + 10.5)):
                    records.append(record)

            self.assertEqual(len(error.exception.args), 0)
    def test_queue(self):
        archive_topic = 'archive'
        self.setup_archive_queue_tests(archive_topic)
        queue_list = [self.queue_data, self.queue_data]

        with mock.patch('user.MQTTSubscribe.MQTTSubscriber') as mock_manager:
            type(mock_manager.return_value).get_data = mock.Mock(return_value=self.generator([self.queue_data, self.queue_data, None]))
            records = list()

            SUT = MQTTSubscribeDriver(**self.config_dict)

            for record in SUT.genArchiveRecords(int(time.time() - 10.5)):
                records.append(record)

            self.assertListEqual(records, queue_list)
    def test_queue_returns_none(self):
        topic = random_string()
        self.setup_queue_tests(topic)
        queue = dict(
            {'name': topic}
            )

        with mock.patch('user.MQTTSubscribe.MQTTSubscriber') as mock_manager:
            with mock.patch('user.MQTTSubscribe.time') as mock_time:
                type(mock_manager.return_value).queues = mock.PropertyMock(return_value=[queue])
                type(mock_manager.return_value).get_data = mock.Mock(side_effect=[self.generator([None]), self.generator([self.queue_data])])

                SUT = MQTTSubscribeDriver(**self.config_dict)
                gen = SUT.genLoopPackets()
                next(gen, None)

                mock_time.sleep.assert_called_once()
                self.assertEqual(mock_manager.return_value.get_data.call_count, 2)
    def test_queue(self):
        topic = 'foo/bar'
        self.setup_queue_tests(topic)

        with mock.patch('user.MQTTSubscribe.MQTTSubscribe') as mock_manager:
            with mock.patch('user.MQTTSubscribe.time') as mock_time:
                type(
                    mock_manager.return_value
                ).subscribed_topics = mock.PropertyMock(return_value=[topic])
                type(mock_manager.return_value).get_data = mock.Mock(
                    return_value=self.generator([self.queue_data]))

                SUT = MQTTSubscribeDriver(**self.config_dict)

                gen = SUT.genLoopPackets()
                packet = next(gen)

                mock_time.sleep.assert_not_called()
                self.assertDictEqual(packet, self.queue_data)
    def test_queue_empty(self):
        topic = 'foo/bar'
        self.setup_queue_tests(topic)

        with mock.patch('user.MQTTSubscribe.MQTTSubscribe') as mock_manager:
            with mock.patch('user.MQTTSubscribe.time') as mock_time:
                type(
                    mock_manager.return_value
                ).subscribed_topics = mock.PropertyMock(return_value=[topic])
                type(mock_manager.return_value).get_data = mock.Mock(
                    return_value=self.generator([None, self.queue_data]))

                SUT = MQTTSubscribeDriver(**self.config_dict)
                gen = SUT.genLoopPackets()
                next(gen, None)

                mock_time.sleep.assert_called_once()
                self.assertEqual(mock_manager.return_value.get_data.call_count,
                                 2)
Esempio n. 11
0
    def test_no_archive_topic(self):
        config_dict = {}
        config_dict['topic'] = 'foo/bar'

        with mock.patch('user.MQTTSubscribe.MQTTSubscriber'):
            with self.assertRaises(NotImplementedError) as error:
                SUT = MQTTSubscribeDriver(**config_dict)
                SUT.archive_interval  # pylint: disable=pointless-statement

            self.assertEqual(len(error.exception.args), 0)
Esempio n. 12
0
    def test_archive_topic(self):
        topic = 'foo/bar'
        default_archive_interval = 900
        config_dict = {}
        config_dict['topic'] = topic
        config_dict['archive_topic'] = topic
        config_dict['archive_interval'] = 900

        with mock.patch('user.MQTTSubscribe.MQTTSubscriber'):
            SUT = MQTTSubscribeDriver(**config_dict)
            archive_interval = SUT.archive_interval
            self.assertEqual(archive_interval, default_archive_interval)
Esempio n. 13
0
    def test_no_archive_topic(self):
        config_dict = {}
        config_dict['topic'] = ''.join([
            random.choice(string.ascii_letters + string.digits)
            for n in range(32)
        ])

        with mock.patch('user.MQTTSubscribe.MQTTSubscriber'):
            with self.assertRaises(NotImplementedError) as error:
                SUT = MQTTSubscribeDriver(**config_dict)
                SUT.archive_interval  # pylint: disable=pointless-statement

            self.assertEqual(len(error.exception.args), 0)
Esempio n. 14
0
    def test_queue(self):
        topic = ''.join([
            random.choice(string.ascii_letters + string.digits)
            for n in range(32)
        ])
        self.setup_queue_tests(topic)
        queue = dict({'name': topic})

        with mock.patch('user.MQTTSubscribe.MQTTSubscriber') as mock_manager:
            with mock.patch('user.MQTTSubscribe.time') as mock_time:
                type(mock_manager.return_value).queues = mock.PropertyMock(
                    return_value=[queue])
                type(mock_manager.return_value).get_data = mock.Mock(
                    return_value=self.generator([self.queue_data]))

                SUT = MQTTSubscribeDriver(**self.config_dict)

                gen = SUT.genLoopPackets()
                packet = next(gen)

                mock_time.sleep.assert_not_called()
                self.assertDictEqual(packet, self.queue_data)
Esempio n. 15
0
    def test_archive_topic(self):
        topic = ''.join([
            random.choice(string.ascii_letters + string.digits)
            for n in range(32)
        ])
        default_archive_interval = 900
        config_dict = {}
        config_dict['topic'] = topic
        config_dict['archive_topic'] = topic
        config_dict['archive_interval'] = 900

        with mock.patch('user.MQTTSubscribe.MQTTSubscriber'):
            SUT = MQTTSubscribeDriver(**config_dict)
            archive_interval = SUT.archive_interval
            self.assertEqual(archive_interval, default_archive_interval)
Esempio n. 16
0
    def runit(self, payload, file_pointer, check_results=True):
        test_data = json.load(file_pointer, object_hook=utils.byteify)
        config_dict = configobj.ConfigObj(test_data['config'])
        testruns = test_data['testruns']

        cdict = config_dict['MQTTSubscribeService']
        if not 'message_callback' in config_dict['MQTTSubscribeService']:
            config_dict['MQTTSubscribeService']['message_callback'] = {}
        config_dict['MQTTSubscribeService']['message_callback'][
            'type'] = payload

        driver = MQTTSubscribeDriver(**cdict)

        host = 'localhost'
        port = 1883
        keepalive = 60

        userdata = {'topics': [], 'connected_flag': False}
        client = mqtt.Client(userdata=userdata)
        client.on_connect = utils.on_connect
        client.connect(host, port, keepalive)
        client.loop_start()

        max_connect_wait = 1  # ToDo - configure
        i = 1
        while not userdata['connected_flag']:
            if i > max_connect_wait:
                self.fail("Timed out waiting for connections.")
            time.sleep(1)
            i += 1

        userdata2 = {
            'topics': cdict['topics'].sections,
            'connected_flag': False,
            'msg': False,
            'max_msg_wait': 1  # ToDo - configure
        }
        client2 = mqtt.Client(userdata=userdata2)
        client2.on_connect = utils.on_connect
        client2.on_message = utils.on_message
        client2.connect(host, port, keepalive)
        client2.loop_start()

        max_connect2_wait = 1  # ToDo - configure
        i = 1
        while not userdata2['connected_flag']:
            #print("waiting to connect")
            if i > max_connect2_wait:
                self.fail("Timed out waiting for connection 2.")
            time.sleep(1)
            i += 1

        max_waits = 10
        for testrun in testruns:
            for topics in testrun['messages']:
                for topic in topics:
                    topic_info = topics[topic]
                    msg_count = utils.send_msg(utils.send_mqtt_msg, payload,
                                               client.publish, topic,
                                               topic_info, userdata2, self)
                    wait_count = utils.wait_on_queue(driver, msg_count,
                                                     max_waits, 1)

                    # If queue not filled, fail now
                    # otherwise will end up in 'infinite' loop in genLoopPackets
                    if wait_count >= max_waits:
                        self.fail("Could not fill queue.")

            records = []
            gen = driver.genLoopPackets()

            more_data = False
            # hack to check if there is more data in the queues
            for topics in testrun['messages']:
                for topic in driver.subscriber.manager.subscribed_topics:
                    if driver.subscriber.manager.has_data(topic):
                        more_data = True

            while more_data:
                data = next(gen, None)
                records.append(data)
                more_data = False
                # hack to check if there is more data in the queues
                for topics in testrun['messages']:
                    for topic in driver.subscriber.manager.subscribed_topics:
                        if driver.subscriber.manager.has_data(topic):
                            more_data = True

            if check_results:
                results = testrun['results']
                result = {}
                found = False
                for result in results:
                    if 'driver' in result['test']:
                        if payload in result['payloads']:
                            found = True
                            break
                self.assertTrue(found, "No results for %s" % payload)

                utils.check(self, payload, records, result['records'])
            else:
                for record in records:
                    print(record)

        driver.closePort()
        client.disconnect()
        client2.disconnect()