示例#1
0
    def setUp(self):
        self.mc = MongoConnection('localhost', 27017, '', '', 'testdb')

        try:
            self.mc.database['config'].insert_one(testdata.config)
        except Exception as e:
            print(e)

        bulk = self.mc.database['alerts'].initialize_unordered_bulk_op()
        for alert in testdata.alerts:
            bulk.insert(alert)
        try:
            bulk.execute()
        except BulkWriteError as bwe:
            print(bwe)

        # self.fmc = FMonConfiguration(self.mc)
        # self.alerts = Alerts(self.mc, self.fmc)
        self.al = query.ArduinoLog(db=self.mc._client, name=self.mc._db)
        self.mc.timeseries_insert(testdata.light_not_transgressing)
        asensor, bsensor, csensor = [
            x['sensor'] for x in testdata.config['sensors']
            if x['type'] == 'event'
        ]
        self.mc.event_insert({'name': csensor, 'value': 0})
        self.mc.event_insert({'name': asensor, 'value': 0})
        self.mc.event_insert({'Event': {'name': asensor, 'value': 1}})
        self.mc.event_insert({'Event': {'name': bsensor, 'value': 1}})
        self.mc.event_insert({'Event': {'name': bsensor, 'value': 1}})
        self.mc.event_insert({'Event': {'name': asensor, 'value': 0}})
示例#2
0
class TestCreate(TestCase):
    def setUp(self):
        self.mc = MongoConnection('localhost', 27017, '', '', 'testdb')
        
        try:
            self.mc.database['config'].insert_one(config)
        except Exception as e:
            print(e)
            
        bulk = self.mc.database['alerts'].initialize_unordered_bulk_op()
        for alert in alerts:
            bulk.insert(alert)
        try:
            bulk.execute()
        except BulkWriteError as bwe:
            print(bwe)
            
        self.fmc = FMonConfiguration(self.mc)
        

    def tearDown(self):
        self.mc.database['config'].drop()
        self.mc.database['alerts'].drop()
        self.mc.database['timeseriesdata'].drop()
        self.mc.database['eventdata'].drop()
        try:
            self.mc.drop_database('testdb')
        except:
            print("Didn't drop db.")

    def test_serial_port(self):
        self.assertEqual(self.fmc.port, config['serial']['port'])
        self.assertEqual(self.fmc.baudrate, config['serial']['baudrate'])

    def test_sensors(self):
        sensors = self.fmc.sensors
        self.assertEqual(sensors[0]['sensor'], config['sensors'][0]['sensor'])
        self.assertEqual(sensors[0]['type'], config['sensors'][0]['type'])

        self.assertEqual(sensors[1]['sensor'], config['sensors'][1]['sensor'])
        self.assertEqual(sensors[1]['type'], config['sensors'][1]['type'])

        self.assertEqual(sensors[2]['sensor'], config['sensors'][2]['sensor'])
        self.assertEqual(sensors[2]['type'], config['sensors'][2]['type'])

    def test_id(self):
        self.assertEqual(self.fmc.id, config['id_info']['uuid'])
        self.assertEqual(self.fmc.location, config['id_info']['store'])
        self.assertEqual(self.fmc.fixture, config['id_info']['fixture'])
示例#3
0
    def setUp(self):
        self.mc = MongoConnection('localhost', 27017, '', '', 'testdb')
        try:
            self.mc.database['config'].insert_one(testdata.config)
        except Exception as e:
            print(e)

        bulk = self.mc.database['alerts'].initialize_unordered_bulk_op()
        for alert in testdata.alerts:
            bulk.insert(alert)
        try:
            bulk.execute()
        except BulkWriteError as bwe:
            print(bwe)
        self.fm = fmon.Fmon()
示例#4
0
class TestCreate(TestCase):
    def setUp(self):
        self.mc = MongoConnection('localhost', 27017, '', '', 'testdb')

        try:
            self.mc.database['config'].insert_one(config)
        except Exception as e:
            print(e)

        bulk = self.mc.database['alerts'].initialize_unordered_bulk_op()
        for alert in alerts:
            bulk.insert(alert)
        try:
            bulk.execute()
        except BulkWriteError as bwe:
            print(bwe)

        self.fmc = FMonConfiguration(self.mc)

    def tearDown(self):
        self.mc.database['config'].drop()
        self.mc.database['alerts'].drop()
        self.mc.database['timeseriesdata'].drop()
        self.mc.database['eventdata'].drop()
        try:
            self.mc.drop_database('testdb')
        except:
            print("Didn't drop db.")

    def test_serial_port(self):
        self.assertEqual(self.fmc.port, config['serial']['port'])
        self.assertEqual(self.fmc.baudrate, config['serial']['baudrate'])

    def test_sensors(self):
        sensors = self.fmc.sensors
        self.assertEqual(sensors[0]['sensor'], config['sensors'][0]['sensor'])
        self.assertEqual(sensors[0]['type'], config['sensors'][0]['type'])

        self.assertEqual(sensors[1]['sensor'], config['sensors'][1]['sensor'])
        self.assertEqual(sensors[1]['type'], config['sensors'][1]['type'])

        self.assertEqual(sensors[2]['sensor'], config['sensors'][2]['sensor'])
        self.assertEqual(sensors[2]['type'], config['sensors'][2]['type'])

    def test_id(self):
        self.assertEqual(self.fmc.id, config['id_info']['uuid'])
        self.assertEqual(self.fmc.location, config['id_info']['store'])
        self.assertEqual(self.fmc.fixture, config['id_info']['fixture'])
示例#5
0
    def setUp(self):
        self.mc = MongoConnection('localhost', 27017, '', '', 'testdb')

        try:
            self.mc.database['config'].insert_one(testdata.config)
        except Exception as e:
            print(e)

        bulk = self.mc.database['alerts'].initialize_unordered_bulk_op()
        for alert in testdata.alerts:
            bulk.insert(alert)
        try:
            bulk.execute()
        except BulkWriteError as bwe:
            print(bwe)

        # self.fmc = FMonConfiguration(self.mc)
        # self.alerts = Alerts(self.mc, self.fmc)
        self.al = query.ArduinoLog(db=self.mc._client, name=self.mc._db)
        self.mc.timeseries_insert(testdata.light_not_transgressing)
        asensor, bsensor, csensor = [x['sensor']
                                     for x in testdata.config['sensors']
                                     if x['type'] == 'event']
        self.mc.event_insert({'name': csensor, 'value': 0})
        self.mc.event_insert({'name': asensor, 'value': 0})
        self.mc.event_insert({ 'Event': { 'name': asensor, 'value': 1 } })
        self.mc.event_insert({ 'Event': { 'name': bsensor, 'value': 1 } })
        self.mc.event_insert({ 'Event': { 'name': bsensor, 'value': 1 } })
        self.mc.event_insert({ 'Event': { 'name': asensor, 'value': 0 } })
示例#6
0
 def setUp(self):
     self.mc = MongoConnection('localhost', 27017, '', '', 'testdb')
     try:
         self.mc.database['config'].insert_one(testdata.config)
     except Exception as e:
         print(e)
         
     bulk = self.mc.database['alerts'].initialize_unordered_bulk_op()
     for alert in testdata.alerts:
         bulk.insert(alert)
     try:
         bulk.execute()
     except BulkWriteError as bwe:
         print(bwe)
     self.fm = fmon.Fmon()
示例#7
0
class TestCreate(TestCase):
    def setUp(self):
        self.mc = MongoConnection('localhost', 27017, '', '', 'testdb')
        try:
            self.mc.database['config'].insert_one(testdata.config)
        except Exception as e:
            print(e)

        bulk = self.mc.database['alerts'].initialize_unordered_bulk_op()
        for alert in testdata.alerts:
            bulk.insert(alert)
        try:
            bulk.execute()
        except BulkWriteError as bwe:
            print(bwe)
        self.fm = fmon.Fmon()

    def tearDown(self):
        self.mc.database['config'].drop()
        self.mc.database['alerts'].drop()
        self.mc.database['timeseriesdata'].drop()
        self.mc.database['eventdata'].drop()
        try:
            self.mc.drop_database('testdb')
        except:
            print("Didn't drop db.")

    def test_connection(self):
        self.assertIsNotNone(self.mc.connection)

    def test_database(self):
        self.assertIsNotNone(self.mc.database)

    def test_config_data(self):
        self.assertIsNotNone(self.mc.config_data)

    def test_timeseries_data(self):
        self.assertIsNotNone(self.mc.timeseries_data)

    def test_timeseries_insert(self):
        #self.fm.logger.error(testdata.json_string)
        j = json.loads(testdata.json_string)
        self.mc.timeseries_insert(j)

    def test_event_insert(self):
        self.mc.event_insert({"Event": {"type": "PIR detect", "value": 0}})

        self.mc.event_insert({"type": "PIR reset", "value": 0})

    def test_create_sensor_payloads(self):
        import json
        x = json.loads(testdata.json_string)
        y = self.mc.create_insert_payloads(x)
        self.fm.logger.debug(y)

    # This is unnecessary because of upserts.
    # def test_has_hour(self):
    #     import datetime
    #     x = datetime.datetime(1979, 11, 6)
    #     self.assertTrue(self.mc.has_hour(self.mc.current_hour))
    #     self.assertFalse(self.mc.has_hour(x))

    def test_get_alerts(self):
        c = self.mc.alerts.find()
        self.assertEqual(c[0]['sensor'], testdata.alerts[0]['sensor'])
        self.assertEqual(c[1]['recipients'][0],
                         testdata.alerts[0]['recipients'][0])
示例#8
0
class TestCreate(TestCase):
    def setUp(self):
        self.mc = MongoConnection('localhost', 27017, '', '', 'testdb')

        try:
            self.mc.database['config'].insert_one(testdata.config)
        except Exception as e:
            print(e)
            
        bulk = self.mc.database['alerts'].initialize_unordered_bulk_op()
        for alert in testdata.alerts:
            bulk.insert(alert)
        try:
            bulk.execute()
        except BulkWriteError as bwe:
            print(bwe)
            
        self.fmc = FMonConfiguration(self.mc)
        self.alerts = Alerts(self.mc, self.fmc)

    def tearDown(self):
        self.mc.database['config'].drop()
        self.mc.database['alerts'].drop()
        self.mc.database['timeseriesdata'].drop()
        self.mc.database['eventdata'].drop()
        try:
            self.mc.drop_database('testdb')
        except:
            print("Didn't drop db.")
        
    def test_found_something(self):
        self.assertIsNotNone(self.alerts)

    def test_get_alerts(self):
        al = self.alerts.alert_list
        self.assertIsInstance(al, set,
                              msg='This is a {}.'.format(type(al)))

    def test_get_alert_item(self):
        alight, atemp = self.alerts.alert_list
        self.assertIsNotNone(alight.sensor)
        self.assertEqual(atemp.recipients[0],
                         '*****@*****.**')

    def test_query_alert_count(self):
        self.assertGreater(len(self.alerts), 1)

    def test_query_alert_generator(self):
        res = False
        for alert in self.alerts:
            if "*****@*****.**" in alert.recipients:
                res = True
        self.assertTrue(res)

    def test_return_repr(self):
        self.assertEqual(str(self.alerts), 'Alerts: 2 items')

    def test_get_alert_limits(self):
        for alert in self.alerts:
            if alert.sensor == testdata.alerts[0]['sensor']:
                self.assertEqual(alert.limits['days'], 0b1111100)
            if alert.sensor == testdata.alerts[1]['sensor']:
                self.assertEqual(alert.limits['days'], 0b0000111)

    @patch('fmon.alerts.datetime')
    def test_check_ok_to_send(self, mock_date):
        mock_date.today.return_value = datetime(2016, 6, 20, 10, 0)
        mock_date.now.return_value = datetime(2016, 6, 20, 10, 0)
        for alert in self.alerts:
            if alert.sensor == 'light':
                self.assertTrue(alert.ok_to_send, msg="light should be true")
                alert.sent = True
                self.assertFalse(alert.ok_to_send)
            if alert.sensor == 'tempF':
                self.assertFalse(alert.ok_to_send, msg= "tempF should be f")
            
    def test_send_alerts(self):
        a = {alert.sensor: alert for alert in self.alerts}
        self.alerts.send_alerts(testdata.light_transgressing)
        if a[testdata.alerts[0]['sensor']].agreeable_day(datetime.now().weekday()):
            self.assertTrue(a[testdata.alerts[0]['sensor']].sent)
        else:
            self.assertFalse(a[testdata.alerts[0]['sensor']].sent)
        sent = a[testdata.alerts[1]['sensor']].sent
        self.assertFalse(sent)

        self.alerts.send_alerts(testdata.light_not_transgressing)
        msg = 'true: {}'.format(testdata.light_transgressing)
        sent = a[testdata.alerts[0]['sensor']].sent
        self.assertFalse(sent)

    def test_agreeable_day(self):        
        a = {alert.sensor: alert for alert in self.alerts}
        print(a)
        self.assertTrue(
            a[testdata.alerts[1]['sensor']].agreeable_day(5))

        self.assertTrue(
            a[testdata.alerts[1]['sensor']].agreeable_day(6))

        self.assertFalse(
            a[testdata.alerts[1]['sensor']].agreeable_day(3))

        self.assertTrue(
            a[testdata.alerts[0]['sensor']].agreeable_day(2))

        self.assertTrue(
            a[testdata.alerts[0]['sensor']].agreeable_day(3))

        self.assertFalse(
            a[testdata.alerts[0]['sensor']].agreeable_day(6))

    def test_within_workday(self):
        a = [alert for alert in self.alerts]
        self.assertTrue(a[0].within_workday(800))
        self.assertFalse(a[0].within_workday(1200))
        self.assertFalse(a[0].within_workday(200))
        self.assertTrue(a[1].within_workday(800))
        self.assertFalse(a[1].within_workday(1200))
        self.assertFalse(a[1].within_workday(200))

    def test_equality(self):
        a = {alert.sensor: alert for alert in self.alerts}
        x = a[testdata.alerts[0]['sensor']]
        y = a[testdata.alerts[0]['sensor']]
        y.sent = True
        
        self.assertIsNotNone(x)
        self.assertIsNotNone(y)
        self.assertEqual(x, y)

    def test_transgressing_range(self):
        a = {alert.sensor: alert for alert in self.alerts}
        msg_tr = 'false: {}'.format(testdata.light_transgressing)
        msg_ntr = 'true: {}'.format(testdata.light_not_transgressing)
        self.assertFalse(a[testdata.alerts[0]['sensor']].
                         transgressing_range(testdata.light_not_transgressing), msg=msg_ntr)
        self.assertTrue(a[testdata.alerts[0]['sensor']].transgressing_range(testdata.light_transgressing), msg=msg_tr)
        self.assertFalse(a[testdata.alerts[1]['sensor']].
                         transgressing_range(testdata.light_not_transgressing), msg=msg_ntr)
示例#9
0
class TestCreate(TestCase):
    def setUp(self):
        self.mc = MongoConnection('localhost', 27017, '', '', 'testdb')

        try:
            self.mc.database['config'].insert_one(testdata.config)
        except Exception as e:
            print(e)

        bulk = self.mc.database['alerts'].initialize_unordered_bulk_op()
        for alert in testdata.alerts:
            bulk.insert(alert)
        try:
            bulk.execute()
        except BulkWriteError as bwe:
            print(bwe)

        self.fmc = FMonConfiguration(self.mc)
        self.alerts = Alerts(self.mc, self.fmc)

    def tearDown(self):
        self.mc.database['config'].drop()
        self.mc.database['alerts'].drop()
        self.mc.database['timeseriesdata'].drop()
        self.mc.database['eventdata'].drop()
        try:
            self.mc.drop_database('testdb')
        except:
            print("Didn't drop db.")

    def test_found_something(self):
        self.assertIsNotNone(self.alerts)

    def test_get_alerts(self):
        al = self.alerts.alert_list
        self.assertIsInstance(al, set, msg='This is a {}.'.format(type(al)))

    def test_get_alert_item(self):
        alight, atemp = self.alerts.alert_list
        self.assertIsNotNone(alight.sensor)
        self.assertEqual(atemp.recipients[0], '*****@*****.**')

    def test_query_alert_count(self):
        self.assertGreater(len(self.alerts), 1)

    def test_query_alert_generator(self):
        res = False
        for alert in self.alerts:
            if "*****@*****.**" in alert.recipients:
                res = True
        self.assertTrue(res)

    def test_return_repr(self):
        self.assertEqual(str(self.alerts), 'Alerts: 2 items')

    def test_get_alert_limits(self):
        for alert in self.alerts:
            if alert.sensor == testdata.alerts[0]['sensor']:
                self.assertEqual(alert.limits['days'], 0b1111100)
            if alert.sensor == testdata.alerts[1]['sensor']:
                self.assertEqual(alert.limits['days'], 0b0000111)

    @patch('fmon.alerts.datetime')
    def test_check_ok_to_send(self, mock_date):
        mock_date.today.return_value = datetime(2016, 6, 20, 10, 0)
        mock_date.now.return_value = datetime(2016, 6, 20, 10, 0)
        for alert in self.alerts:
            if alert.sensor == 'light':
                self.assertTrue(alert.ok_to_send, msg="light should be true")
                alert.sent = True
                self.assertFalse(alert.ok_to_send)
            if alert.sensor == 'tempF':
                self.assertFalse(alert.ok_to_send, msg="tempF should be f")

    def test_send_alerts(self):
        a = {alert.sensor: alert for alert in self.alerts}
        self.alerts.send_alerts(testdata.light_transgressing)
        if a[testdata.alerts[0]['sensor']].agreeable_day(
                datetime.now().weekday()):
            self.assertTrue(a[testdata.alerts[0]['sensor']].sent)
        else:
            self.assertFalse(a[testdata.alerts[0]['sensor']].sent)
        sent = a[testdata.alerts[1]['sensor']].sent
        self.assertFalse(sent)

        self.alerts.send_alerts(testdata.light_not_transgressing)
        msg = 'true: {}'.format(testdata.light_transgressing)
        sent = a[testdata.alerts[0]['sensor']].sent
        self.assertFalse(sent)

    def test_agreeable_day(self):
        a = {alert.sensor: alert for alert in self.alerts}
        print(a)
        self.assertTrue(a[testdata.alerts[1]['sensor']].agreeable_day(5))

        self.assertTrue(a[testdata.alerts[1]['sensor']].agreeable_day(6))

        self.assertFalse(a[testdata.alerts[1]['sensor']].agreeable_day(3))

        self.assertTrue(a[testdata.alerts[0]['sensor']].agreeable_day(2))

        self.assertTrue(a[testdata.alerts[0]['sensor']].agreeable_day(3))

        self.assertFalse(a[testdata.alerts[0]['sensor']].agreeable_day(6))

    def test_within_workday(self):
        a = [alert for alert in self.alerts]
        self.assertTrue(a[0].within_workday(800))
        self.assertFalse(a[0].within_workday(1200))
        self.assertFalse(a[0].within_workday(200))
        self.assertTrue(a[1].within_workday(800))
        self.assertFalse(a[1].within_workday(1200))
        self.assertFalse(a[1].within_workday(200))

    def test_equality(self):
        a = {alert.sensor: alert for alert in self.alerts}
        x = a[testdata.alerts[0]['sensor']]
        y = a[testdata.alerts[0]['sensor']]
        y.sent = True

        self.assertIsNotNone(x)
        self.assertIsNotNone(y)
        self.assertEqual(x, y)

    def test_transgressing_range(self):
        a = {alert.sensor: alert for alert in self.alerts}
        msg_tr = 'false: {}'.format(testdata.light_transgressing)
        msg_ntr = 'true: {}'.format(testdata.light_not_transgressing)
        self.assertFalse(a[testdata.alerts[0]['sensor']].transgressing_range(
            testdata.light_not_transgressing),
                         msg=msg_ntr)
        self.assertTrue(a[testdata.alerts[0]['sensor']].transgressing_range(
            testdata.light_transgressing),
                        msg=msg_tr)
        self.assertFalse(a[testdata.alerts[1]['sensor']].transgressing_range(
            testdata.light_not_transgressing),
                         msg=msg_ntr)
示例#10
0
class TestCreate(TestCase):
    def setUp(self):
        self.mc = MongoConnection('localhost', 27017, '', '', 'testdb')

        try:
            self.mc.database['config'].insert_one(testdata.config)
        except Exception as e:
            print(e)

        bulk = self.mc.database['alerts'].initialize_unordered_bulk_op()
        for alert in testdata.alerts:
            bulk.insert(alert)
        try:
            bulk.execute()
        except BulkWriteError as bwe:
            print(bwe)

        # self.fmc = FMonConfiguration(self.mc)
        # self.alerts = Alerts(self.mc, self.fmc)
        self.al = query.ArduinoLog(db=self.mc._client, name=self.mc._db)
        self.mc.timeseries_insert(testdata.light_not_transgressing)
        asensor, bsensor, csensor = [
            x['sensor'] for x in testdata.config['sensors']
            if x['type'] == 'event'
        ]
        self.mc.event_insert({'name': csensor, 'value': 0})
        self.mc.event_insert({'name': asensor, 'value': 0})
        self.mc.event_insert({'Event': {'name': asensor, 'value': 1}})
        self.mc.event_insert({'Event': {'name': bsensor, 'value': 1}})
        self.mc.event_insert({'Event': {'name': bsensor, 'value': 1}})
        self.mc.event_insert({'Event': {'name': asensor, 'value': 0}})

    def tearDown(self):
        # from time import sleep
        # sleep(15)
        self.mc.database['config'].drop()
        self.mc.database['alerts'].drop()
        self.mc.database['timeseriesdata'].drop()
        self.mc.database['eventdata'].drop()
        try:
            self.mc.drop_database('testdb')
        except:
            print("Didn't drop db.")

    def test_get_ts_sensors(self):
        from_config = [
            s['sensor'] for s in testdata.config['sensors']
            if s['type'] == 'timeseries'
        ]
        from_config.sort()
        from_al = [s for s in self.al.ts_sensors]
        from_al.sort()
        self.assertEqual(from_config,
                         from_al,
                         msg='{}: {}'.format(from_config, from_al))

    def test_get_ev_sensors(self):
        from_config = [
            s['sensor'] for s in testdata.config['sensors']
            if s['type'] == 'event'
        ]
        from_config.sort()
        from_al = [s for s in self.al.ev_sensors if s is not None]

        from_al.sort()
        self.assertEqual(from_config,
                         from_al,
                         msg='{}: {}'.format(from_config, from_al))

    def test_get_all_sensors(self):
        aas = [s for s in self.al.all_sensors]
        aas.sort()

        cas = [s['sensor'] for s in testdata.config['sensors']]
        cas.sort()
        self.assertEqual(aas, cas)

    def test_last_value(self):
        asensor = testdata.config['sensors'][2]['sensor']
        lv = testdata.light_not_transgressing[asensor]
        self.assertEqual(self.al.last_value(asensor), lv)

    def test_last_values(self):
        lvs = testdata.light_not_transgressing
        olvs = self.al.last_values()
        dd = {}
        for d in olvs:
            k, v = d['name'], d['values']
            dd[k] = v[len(v) - 1]
        self.assertEqual(dd, lvs)

    def test_ts_ev(self):
        ev = self.al.ev
        ts = self.al.ts
        from pymongo.collection import Collection
        self.assertIsInstance(ev, Collection)
        self.assertIsInstance(ev, Collection)

    def test_sample_count(self):
        asensor = testdata.config['sensors'][2]['sensor']
        cnt = self.al.sample_count(asensor)
        self.assertEqual(cnt, 1)
        self.mc.timeseries_insert(testdata.light_not_transgressing)
        self.mc.timeseries_insert(testdata.light_transgressing)
        cnt = self.al.sample_count(asensor)
        self.assertEqual(cnt, 3)

    def test_latest_documents(self):
        ld = self.al.latest_documents()
        self.assertEqual(len(ld), len(self.al.ts_sensors))

        dd = {}
        for d in ld:
            k, v = d['name'], d['values']
            dd[k] = v[len(v) - 1]
        self.assertEqual(dd, testdata.light_not_transgressing)

    def test_hour_cursor(self):
        asensor = testdata.config['sensors'][0]['sensor']
        self.mc.timeseries_insert(testdata.light_not_transgressing)
        self.mc.timeseries_insert(testdata.light_transgressing)
        hc = self.al.hour_cursor(asensor)
        vs = hc[0]['values']
        self.assertEqual(vs[len(vs) - 1],
                         testdata.light_transgressing[asensor])

    def test_hour_list(self):
        asensor = testdata.config['sensors'][0]['sensor']
        l = self.al.hour_list(asensor)
        self.assertEqual(l[0], testdata.light_transgressing[asensor])

    def test_hour_events_cursor(self):
        asensor = self.al.ev_sensors[1]
        bsensor = self.al.ev_sensors[2]
        hec1 = self.al.hour_events_cursor()
        l1 = [x for x in hec1]
        self.assertEqual(hec1.count(), 6)
        self.assertEqual(len(l1), 6)
        self.assertEqual(l1[0]['name'], bsensor)
        self.assertEqual(l1[1]['name'], asensor)

    def test_hour_event_list(self):
        ev = self.al.ev_sensors
        hel = self.al.hour_event_list()
        self.assertEqual(hel[0]['name'], ev[2])

    def test_avg_hour(self):
        pass

    def test_min_hour(self):
        pass

    def test_max_hour(self):
        pass

    def test_std_hour(self):
        pass

    def test_cv_hour(self):
        pass

    def test_count_matches(self):
        filter = {'name': {'$in': self.al.ts_sensors}}
        self.assertEqual(self.al.count_matches(filter, 'timeseriesdata'),
                         len(self.al.ts_sensors))
        filter = {'name': {'$in': self.al.ev_sensors}}
        self.assertEqual(self.al.count_matches(filter, 'eventdata'), 6)

    def test_count_values(self):
        asensor = testdata.config['sensors'][0]['sensor']
        bsensor = testdata.config['sensors'][2]['sensor']
        self.assertGreater(self.al.count_values(asensor), 0)
        self.assertGreater(self.al.count_values(bsensor), 0)

    def test_hour_stats(self):
        asensor = testdata.config['sensors'][2]['sensor']
        hs = self.al.hour_stats(asensor)
        for i in ['min', 'max', 'avg']:
            self.assertGreater(abs(hs[i]), 0)

    def test_list_events(self):
        self.assertEqual(len(self.al.list_events()), 6)

    def test_list_values(self):
        asensor = testdata.config['sensors'][2]['sensor']
        lv = self.al.list_values(asensor)
        self.assertEqual(lv[0]['name'], asensor)
        self.assertEqual(lv[0]['ts'], query.current_hour())
示例#11
0
class TestCreate(TestCase):
    def setUp(self):
        self.mc = MongoConnection('localhost', 27017, '', '', 'testdb')

        try:
            self.mc.database['config'].insert_one(testdata.config)
        except Exception as e:
            print(e)

        bulk = self.mc.database['alerts'].initialize_unordered_bulk_op()
        for alert in testdata.alerts:
            bulk.insert(alert)
        try:
            bulk.execute()
        except BulkWriteError as bwe:
            print(bwe)

        # self.fmc = FMonConfiguration(self.mc)
        # self.alerts = Alerts(self.mc, self.fmc)
        self.al = query.ArduinoLog(db=self.mc._client, name=self.mc._db)
        self.mc.timeseries_insert(testdata.light_not_transgressing)
        asensor, bsensor, csensor = [x['sensor']
                                     for x in testdata.config['sensors']
                                     if x['type'] == 'event']
        self.mc.event_insert({'name': csensor, 'value': 0})
        self.mc.event_insert({'name': asensor, 'value': 0})
        self.mc.event_insert({ 'Event': { 'name': asensor, 'value': 1 } })
        self.mc.event_insert({ 'Event': { 'name': bsensor, 'value': 1 } })
        self.mc.event_insert({ 'Event': { 'name': bsensor, 'value': 1 } })
        self.mc.event_insert({ 'Event': { 'name': asensor, 'value': 0 } })

    def tearDown(self):
        # from time import sleep
        # sleep(15)
        self.mc.database['config'].drop()
        self.mc.database['alerts'].drop()
        self.mc.database['timeseriesdata'].drop()
        self.mc.database['eventdata'].drop()
        try:
            self.mc.drop_database('testdb')
        except:
            print("Didn't drop db.")

    def test_get_ts_sensors(self):
        from_config = [s['sensor'] for s in testdata.config['sensors']
                       if s['type'] == 'timeseries']
        from_config.sort()
        from_al = [s for s in self.al.ts_sensors]
        from_al.sort()
        self.assertEqual(from_config, from_al,
                         msg='{}: {}'.format(from_config, from_al))

    def test_get_ev_sensors(self):
        from_config = [s['sensor'] for s in testdata.config['sensors']
                       if s['type'] == 'event']
        from_config.sort()
        from_al = [s for s in self.al.ev_sensors if s is not None]

        from_al.sort()
        self.assertEqual(from_config, from_al,
                         msg='{}: {}'.format(from_config, from_al))

    def test_get_all_sensors(self):
        aas = [s for s in self.al.all_sensors]
        aas.sort()

        cas = [s['sensor'] for s in testdata.config['sensors']]
        cas.sort()
        self.assertEqual(aas, cas)

    def test_last_value(self):
        asensor = testdata.config['sensors'][2]['sensor']
        lv = testdata.light_not_transgressing[asensor]
        self.assertEqual(self.al.last_value(asensor), lv)

    def test_last_values(self):
        lvs = testdata.light_not_transgressing
        olvs = self.al.last_values()
        dd = {}
        for d in olvs:
            k, v = d['name'], d['values']
            dd[k] = v[len(v) - 1]
        self.assertEqual(dd, lvs)

    def test_ts_ev(self):
        ev = self.al.ev
        ts = self.al.ts
        from pymongo.collection import Collection
        self.assertIsInstance(ev, Collection)
        self.assertIsInstance(ev, Collection)

    def test_sample_count(self):
        asensor = testdata.config['sensors'][2]['sensor']
        cnt = self.al.sample_count(asensor)
        self.assertEqual(cnt, 1)
        self.mc.timeseries_insert(testdata.light_not_transgressing)
        self.mc.timeseries_insert(testdata.light_transgressing)
        cnt = self.al.sample_count(asensor)
        self.assertEqual(cnt, 3)

    def test_latest_documents(self):
        ld = self.al.latest_documents()
        self.assertEqual(len(ld), len(self.al.ts_sensors))

        dd = {}
        for d in ld:
            k, v = d['name'], d['values']
            dd[k] = v[len(v) - 1]
        self.assertEqual(dd, testdata.light_not_transgressing)

    def test_hour_cursor(self):
        asensor = testdata.config['sensors'][0]['sensor']
        self.mc.timeseries_insert(testdata.light_not_transgressing)
        self.mc.timeseries_insert(testdata.light_transgressing)
        hc = self.al.hour_cursor(asensor)
        vs = hc[0]['values']
        self.assertEqual(vs[len(vs) - 1],
                         testdata.light_transgressing[asensor])

    def test_hour_list(self):
        asensor = testdata.config['sensors'][0]['sensor']
        l = self.al.hour_list(asensor)
        self.assertEqual(l[0], testdata.light_transgressing[asensor])

    def test_hour_events_cursor(self):
        asensor = self.al.ev_sensors[1]
        bsensor = self.al.ev_sensors[2]
        hec1 = self.al.hour_events_cursor()
        l1 = [x for x in hec1]
        self.assertEqual(hec1.count(), 6)
        self.assertEqual(len(l1), 6)
        self.assertEqual(l1[0]['name'], bsensor)
        self.assertEqual(l1[1]['name'], asensor)

    def test_hour_event_list(self):
        ev = self.al.ev_sensors
        hel = self.al.hour_event_list()
        self.assertEqual(hel[0]['name'], ev[2])

    def test_avg_hour(self):
        pass

    def test_min_hour(self):
        pass

    def test_max_hour(self):
        pass

    def test_std_hour(self):
        pass

    def test_cv_hour(self):
        pass

    def test_count_matches(self):
        filter = { 'name': { '$in': self.al.ts_sensors } }
        self.assertEqual(self.al.count_matches(filter, 'timeseriesdata'),
                         len(self.al.ts_sensors))
        filter = { 'name': { '$in': self.al.ev_sensors } }
        self.assertEqual(self.al.count_matches(filter, 'eventdata'),
                         6)

    def test_count_values(self):
        asensor = testdata.config['sensors'][0]['sensor']
        bsensor = testdata.config['sensors'][2]['sensor']
        self.assertGreater(self.al.count_values(asensor),
                           0)
        self.assertGreater(self.al.count_values(bsensor),
                           0)

    def test_hour_stats(self):
        asensor = testdata.config['sensors'][2]['sensor']
        hs = self.al.hour_stats(asensor)
        for i in ['min', 'max', 'avg']:
            self.assertGreater(abs(hs[i]), 0)

    def test_list_events(self):
        self.assertEqual(len(self.al.list_events()), 6)

    def test_list_values(self):
        asensor = testdata.config['sensors'][2]['sensor']
        lv = self.al.list_values(asensor)
        self.assertEqual(lv[0]['name'], asensor)
        self.assertEqual(lv[0]['ts'], query.current_hour())
示例#12
0
class TestCreate(TestCase):
    def setUp(self):
        self.mc = MongoConnection('localhost', 27017, '', '', 'testdb')
        try:
            self.mc.database['config'].insert_one(testdata.config)
        except Exception as e:
            print(e)
            
        bulk = self.mc.database['alerts'].initialize_unordered_bulk_op()
        for alert in testdata.alerts:
            bulk.insert(alert)
        try:
            bulk.execute()
        except BulkWriteError as bwe:
            print(bwe)
        self.fm = fmon.Fmon()

    def tearDown(self):
        self.mc.database['config'].drop()
        self.mc.database['alerts'].drop()
        self.mc.database['timeseriesdata'].drop()
        self.mc.database['eventdata'].drop()
        try:
            self.mc.drop_database('testdb')
        except:
            print("Didn't drop db.")

    def test_connection(self):
        self.assertIsNotNone(self.mc.connection)

    def test_database(self):
        self.assertIsNotNone(self.mc.database)

    def test_config_data(self):
        self.assertIsNotNone(self.mc.config_data)

    def test_timeseries_data(self):
        self.assertIsNotNone(self.mc.timeseries_data)

    def test_timeseries_insert(self):
        #self.fm.logger.error(testdata.json_string)
        j = json.loads(testdata.json_string)
        self.mc.timeseries_insert(j)

    def test_event_insert(self):
        self.mc.event_insert({ "Event":
              { "type": "PIR detect",
                "value": 0
              }
            })

        self.mc.event_insert(
              { "type": "PIR reset",
                "value": 0
              })

    def test_create_sensor_payloads(self):
        import json
        x = json.loads(testdata.json_string)
        y = self.mc.create_insert_payloads(x)
        self.fm.logger.debug(y)

    # This is unnecessary because of upserts.
    # def test_has_hour(self):
    #     import datetime
    #     x = datetime.datetime(1979, 11, 6)
    #     self.assertTrue(self.mc.has_hour(self.mc.current_hour))
    #     self.assertFalse(self.mc.has_hour(x))

    def test_get_alerts(self):
        c = self.mc.alerts.find()
        self.assertEqual(c[0]['sensor'], testdata.alerts[0]['sensor'])
        self.assertEqual(c[1]['recipients'][0], testdata.alerts[0]['recipients'][0])