Exemplo n.º 1
0
def auto_create_template(json_payload, new_device):
    if ('attrs' in json_payload) and (new_device.templates is None):
        device_template = DeviceTemplate(label="device.%s template" %
                                         new_device.id)
        db.session.add(device_template)
        new_device.templates = [device_template]
        load_attrs(json_payload['attrs'], device_template, DeviceAttr, db)

    # TODO: perhaps it'd be best if all ids were random hex strings?
    if ('attrs' in json_payload) and (new_device.templates is not None):
        for attr in json_payload['attrs']:
            orm_template = find_template(new_device.templates,
                                         attr['template_id'])
            if orm_template is None:
                raise HTTPRequestError(
                    400, 'Unknown template "{}" in attr list'.format(template))

            target = int(attr['id'])
            found = False
            for orm_attr in orm_template.attrs:
                if target == orm_attr.id:
                    found = True
                    orm_override = DeviceOverride(
                        device=new_device,
                        attr=orm_attr,
                        static_value=attr['static_value'])
                    db.session.add(orm_override)
            if not found:
                raise HTTPRequestError(
                    400,
                    "Unkown attribute \"{}\" in override list".format(target))
Exemplo n.º 2
0
    def test_set_templates_on_device(self, db_mock):
        db_mock.session = AlchemyMagicMock()

        json_payload = {
            'templates': [{
                'import_id':
                1,
                'attrs': [{
                    'label': 'temperature',
                    'type': 'dynamic',
                    'value_type': 'float'
                }]
            }],
            'label':
            'test_device',
            'id':
            1,
            'created':
            '2019-08-29T18:18:07.801602+00:00'
        }

        saved_templates = [DeviceTemplate(label='test_template', attrs=[])]

        self.assertIsNone(
            ImportHandler.set_templates_on_device(Mock(), json_payload,
                                                  saved_templates))
Exemplo n.º 3
0
    def test_save_devices(self, db_mock):
        db_mock.session = AlchemyMagicMock()

        json_payload = {
            "devices": [{
                "id": "68fc",
                "label": "test_device_0"
            }, {
                "id": "94dc",
                "label": "test_device_1"
            }]
        }
        json_data = {
            "devices": [{
                "id": "68fc",
                "label": "test_device_0"
            }, {
                "id": "94dc",
                "label": "test_device_1"
            }]
        }

        saved_templates = [DeviceTemplate(label='test_template', attrs=[])]

        result = ImportHandler.save_devices(json_data, json_payload,
                                            saved_templates)
        self.assertIsNotNone(result)
        self.assertTrue(result)
    def create_template(req):
        """
        Creates a new template.

        :param req: The received HTTP request, as created by Flask.
        :return The created template.
        :raises HTTPRequestError: If no authorization token was provided (no
        tenant was informed)
        :raises HTTPRequestError: If template attribute constraints were
        violated. This might happen if two attributes have the same name, for
        instance.
        """
        init_tenant_context(req, db)
        tpl, json_payload = parse_payload(req, template_schema)
        loaded_template = DeviceTemplate(**tpl)
        load_attrs(json_payload['attrs'], loaded_template, DeviceAttr, db)
        db.session.add(loaded_template)

        try:
            db.session.commit()
            LOGGER.debug(f" Created template in database")
        except IntegrityError as e:
            LOGGER.error(f' {e}')
            raise HTTPRequestError(
                400,
                'Template attribute constraints are violated by the request')

        results = {
            'template': template_schema.dump(loaded_template),
            'result': 'ok'
        }
        return results
Exemplo n.º 5
0
def auto_create_template(json_payload, new_device):
    if ('attrs' in json_payload) and (new_device.templates is None):
        device_template = DeviceTemplate(
            label="device.%s template" % new_device.id)
        db.session.add(device_template)
        new_device.templates = [device_template]
        load_attrs(json_payload['attrs'], device_template, DeviceAttr, db)
Exemplo n.º 6
0
    def save_templates(json_data, json_payload):
        saved_templates = []
        for template in json_data['templates']:
            loaded_template = DeviceTemplate(**template)
            for json in json_payload['templates']:
                if (json['import_id'] == template["id"]):
                    load_attrs(json['attrs'], loaded_template, DeviceAttr, db)
            db.session.add(loaded_template)
            saved_templates.append(loaded_template)

        LOGGER.info(f" Saved templates")
        return saved_templates
Exemplo n.º 7
0
    def test_remove_template(self, db_mock):
        db_mock.session = AlchemyMagicMock()
        token = generate_token()

        template = DeviceTemplate(id=1, label='template1')

        with patch('DeviceManager.TemplateHandler.assert_template_exists'
                   ) as mock_template_exist_wrapper:
            mock_template_exist_wrapper.return_value = template

            result = TemplateHandler.remove_template(1, token)
            self.assertIsNotNone(result)
            self.assertTrue(result)
            self.assertTrue(result['removed'])
            self.assertEqual(result['result'], 'ok')
Exemplo n.º 8
0
def auto_create_template(json_payload, new_device):
    if ('attrs' in json_payload) and (new_device.templates is None):
        device_template = DeviceTemplate(
            label="device.%s template" % new_device.id)
        db.session.add(device_template)
        LOGGER.debug(f" Adding auto-created template {device_template} into database")
        new_device.templates = [device_template]
        load_attrs(json_payload['attrs'], device_template, DeviceAttr, db)

    # TODO: perhaps it'd be best if all ids were random hex strings?
    if ('attrs' in json_payload) and (new_device.templates is not None):
        for attr in json_payload['attrs']:
            orm_template = find_template(new_device.templates, attr['template_id'])
            if orm_template is None:
                LOGGER.error(f" Unknown template {orm_template} in attr list")
                raise HTTPRequestError(400, 'Unknown template "{}" in attr list'.format(orm_template))
            create_orm_override(attr, new_device, orm_template)
Exemplo n.º 9
0
    def test_get_template(self, db_mock):
        db_mock.session = AlchemyMagicMock()
        token = generate_token()

        template = DeviceTemplate(id=1, label='template1')
        params_query = {'attr_format': 'both'}

        with patch('DeviceManager.TemplateHandler.assert_template_exists'
                   ) as mock_template_exist_wrapper:
            mock_template_exist_wrapper.return_value = template
            result = TemplateHandler.get_template(params_query,
                                                  'template_id_test', token)
            self.assertIsNotNone(result)

            mock_template_exist_wrapper.return_value = None
            result = TemplateHandler.get_template(params_query,
                                                  'template_id_test', token)
            self.assertFalse(result)
Exemplo n.º 10
0
    def test_update_template(self, db_mock):
        db_mock.session = AlchemyMagicMock()
        token = generate_token()

        template = DeviceTemplate(id=1, label='SensorModel')

        data = """{
            "label": "SensorModelUpdated",
            "attrs": [
                {
                    "label": "temperature",
                    "type": "dynamic",
                    "value_type": "float"
                },
                {
                    "label": "model-id",
                    "type": "static",
                    "value_type": "string",
                    "static_value": "model-001"
                }
            ]
        }"""

        params_query = {'content_type': 'application/json', 'data': data}

        with patch('DeviceManager.TemplateHandler.assert_template_exists'
                   ) as mock_template_exist_wrapper:
            mock_template_exist_wrapper.return_value = template

            with patch.object(KafkaInstanceHandler,
                              "getInstance",
                              return_value=MagicMock()):
                result = TemplateHandler.update_template(
                    params_query, 1, token)
                self.assertIsNotNone(result)
                self.assertTrue(result)
                self.assertTrue(result['updated'])
                self.assertEqual(result['result'], 'ok')
Exemplo n.º 11
0
 def test_not_refresh_template_update_column(self, db_mock):
     template = DeviceTemplate(id=1, label='template1')
     db_mock.session.new = set()
     db_mock.session.deleted = set()
     refresh_template_update_column(db_mock, template)
     self.assertIsNone(template.updated)
Exemplo n.º 12
0
 def test_refresh_template_update_column(self, db_mock):
     template = DeviceTemplate(id=1, label='template1')
     refresh_template_update_column(db_mock, template)
     self.assertTrue(isinstance(template.updated, datetime))