Beispiel #1
0
class TestDataCenterAssetForm(RalphTestCase):
    def setUp(self):
        self.dca = DataCenterAssetFactory(rack=RackFactory(), position=1)
        self.dca1 = DataCenterAssetFactory(rack=RackFactory(), position=2)

        self.user = get_user_model().objects.create_superuser(
            username='******',
            password='******',
            email='*****@*****.**'
        )
        result = self.client.login(username='******', password='******')
        self.assertEqual(result, True)
        self.factory = RequestFactory()

    def _get_initial_data(self, dca=None):
        dca = dca or self.dca
        data = {
            'barcode': dca.barcode,
            'depreciation_rate': 25,
            'rack': dca.rack.pk,
            'hostname': dca.hostname,
            'model': dca.model.pk,
            'orientation': 1,
            'position': dca.position,
            'service_env': dca.service_env.pk,
            'sn': dca.sn,
            'status': 1,
            'custom_fields-customfieldvalue-content_type-object_id-INITIAL_FORMS': '0',
            'custom_fields-customfieldvalue-content_type-object_id-MAX_NUM_FORMS': '1000',
            'custom_fields-customfieldvalue-content_type-object_id-MIN_NUM_FORMS': '0',
            'custom_fields-customfieldvalue-content_type-object_id-TOTAL_FORMS': '3',
        }
        return data

    def test_enter_valid_mgmt_should_pass(self):
        data = self._get_initial_data()
        data.update({
            'management_ip': '10.20.30.40',
            'management_hostname': 'qwerty.mydc.net',
        })
        response = self.client.post(self.dca.get_absolute_url(), data)
        self.assertEqual(response.status_code, 302)
        self.dca.refresh_from_db()
        self.assertEqual(self.dca.management_ip, '10.20.30.40')
        self.assertEqual(self.dca.management_hostname, 'qwerty.mydc.net')

    def test_enter_duplicated_mgmt_ip_should_not_pass(self):
        IPAddressFactory(
            is_management=True, address='10.20.30.41',
            ethernet__base_object=self.dca1,
        )
        data = self._get_initial_data()
        data.update({
            'management_ip': '10.20.30.41',
            'management_hostname': 'qwerty.mydc.net',
        })
        response = self.client.post(self.dca.get_absolute_url(), data)
        self.assertEqual(response.status_code, 200)
        self.dca.refresh_from_db()
        self.assertIn(
            'Management IP is already assigned to',
            response.context['errors'][0]
        )

    def test_enter_duplicated_mgmt_hostname_should_not_pass(self):
        IPAddressFactory(
            is_management=True, address='10.20.30.41',
            hostname='qwerty.mydc.net',
            ethernet__base_object=self.dca1,
        )
        data = self._get_initial_data()
        data.update({
            'management_ip': '10.20.30.42',
            'management_hostname': 'qwerty.mydc.net',
        })
        response = self.client.post(self.dca.get_absolute_url(), data)
        self.assertEqual(response.status_code, 200)
        self.assertIn(
            'Management hostname is already assigned to',
            response.context['errors'][0]
        )

    def test_reenter_mgmt_ip_should_pass(self):
        IPAddressFactory(
            is_management=True, address='10.20.30.41',
            ethernet__base_object=self.dca,  # mgmt ip assigned to the same obj
        )
        data = self._get_initial_data()
        data.update({
            'management_ip': '10.20.30.41',
            'management_hostname': 'qwerty.mydc.net',
        })
        response = self.client.post(self.dca.get_absolute_url(), data)
        self.assertEqual(response.status_code, 302)
        self.dca.refresh_from_db()
        self.assertEqual(self.dca.management_ip, '10.20.30.41')
        self.assertEqual(self.dca.management_hostname, 'qwerty.mydc.net')

    def test_change_mgmt_ip_should_pass(self):
        IPAddressFactory(
            is_management=True, address='10.20.30.41',
            ethernet__base_object=self.dca,
        )
        ip_count = IPAddress.objects.count()
        data = self._get_initial_data()
        data.update({
            'management_ip': '10.20.30.42',
            'management_hostname': 'qwerty22.mydc.net',
        })
        response = self.client.post(self.dca.get_absolute_url(), data)
        self.assertEqual(response.status_code, 302)
        self.dca.refresh_from_db()
        self.assertEqual(self.dca.management_ip, '10.20.30.42')
        self.assertEqual(self.dca.management_hostname, 'qwerty22.mydc.net')
        self.assertEqual(ip_count, IPAddress.objects.count())

    def test_clean_mgmt_hostname_should_pass(self):
        IPAddressFactory(
            is_management=True, address='10.20.30.41',
            ethernet__base_object=self.dca,
        )
        data = self._get_initial_data()
        data.update({
            'management_ip': '10.20.30.42',
            'management_hostname': '',
        })
        response = self.client.post(self.dca.get_absolute_url(), data)
        self.assertEqual(response.status_code, 302)
        self.dca.refresh_from_db()
        self.assertEqual(self.dca.management_ip, '10.20.30.42')
        self.assertEqual(self.dca.management_hostname, '')

    def test_clean_mgmt_ip_when_mgmt_hostname_is_not_empty_should_not_pass(self):  # noqa
        IPAddressFactory(
            is_management=True, address='10.20.30.41',
            ethernet__base_object=self.dca,
        )
        data = self._get_initial_data()
        data.update({
            'management_ip': '',
            'management_hostname': 'qwerty.mydc.net',
        })
        response = self.client.post(self.dca.get_absolute_url(), data)
        self.assertEqual(response.status_code, 200)
        self.assertIn(
            'Management IP could not be empty when management hostname is passed',  # noqa
            response.context['errors'][0]
        )

    def test_delete_mgmt(self):
        ip = IPAddressFactory(
            is_management=True, address='10.20.30.41',
            hostname='qwerty.mydc.net',
            ethernet__base_object=self.dca,
        )
        eth = ip.ethernet
        ip_count = IPAddress.objects.count()
        data = self._get_initial_data()
        data.update({
            'management_ip': '',
            'management_hostname': '',
        })
        response = self.client.post(self.dca.get_absolute_url(), data)
        self.assertEqual(response.status_code, 302)
        self.dca.refresh_from_db()
        self.assertEqual(self.dca.management_ip, '')
        self.assertEqual(self.dca.management_hostname, '')
        self.assertEqual(IPAddress.objects.count(), ip_count - 1)
        self.assertEqual(len(IPAddress.objects.filter(pk=ip.pk)), 0)
        self.assertEqual(len(Ethernet.objects.filter(pk=eth.pk)), 0)

    def test_create_new_data_center_asset_with_management(self):
        data = self._get_initial_data()
        data.update({
            'barcode': '1234',
            'sn': '321',
            'management_ip': '10.20.30.44',
            'management_hostname': 'qwerty.mydc.net',
        })
        response = self.client.post(
            reverse('admin:data_center_datacenterasset_add'), data
        )
        self.assertEqual(response.status_code, 302)
        dca = DataCenterAsset.objects.get(barcode='1234')
        self.assertEqual(dca.management_ip, '10.20.30.44')
        self.assertEqual(dca.management_hostname, 'qwerty.mydc.net')

    def test_create_new_data_center_asset_without_management(self):
        data = self._get_initial_data()
        data.update({
            'barcode': '1234',
            'sn': '321',
            'management_ip': '',
            'management_hostname': '',
        })
        ip_count = IPAddress.objects.count()
        response = self.client.post(
            reverse('admin:data_center_datacenterasset_add'), data
        )
        self.assertEqual(response.status_code, 302)
        dca = DataCenterAsset.objects.get(barcode='1234')
        self.assertEqual(dca.management_ip, '')
        self.assertEqual(dca.management_hostname, '')
        self.assertEqual(IPAddress.objects.count(), ip_count)

    def test_get_add_form(self):
        response = self.client.get(
            reverse('admin:data_center_datacenterasset_add'),
        )
        self.assertEqual(response.status_code, 200)

    def test_get_add_details_form(self):
        response = self.client.get(self.dca.get_absolute_url())
        self.assertEqual(response.status_code, 200)

    def test_get_add_details_form_with_management_ip(self):
        self.dca.management_ip = '10.20.30.40'
        self.dca.management_hostname = 'qwerty.mydc.net'
        response = self.client.get(self.dca.get_absolute_url())
        self.assertEqual(response.status_code, 200)

    def test_model_asset_type_data_center_shall_pass(self):
        data_center_model = DataCenterAssetModelFactory(
            type=ObjectModelType.from_name('data_center')
        )
        data = self._get_initial_data()
        data.update({
            'model': data_center_model.pk
        })
        response = self.client.post(
            self.dca.get_absolute_url(), data
        )
        self.dca.refresh_from_db()
        self.assertEqual(response.status_code, 302)
        self.assertEqual(self.dca.model, data_center_model)

    def test_model_asset_type_back_office_asset_shall_not_pass(self):
        back_office_model = DataCenterAssetModelFactory(
            type=ObjectModelType.from_name('back_office')
        )
        data = self._get_initial_data()
        data.update({
            'model': back_office_model.pk
        })
        response = self.client.post(
            self.dca.get_absolute_url(), data
        )
        self.dca.refresh_from_db()
        self.assertIn(
            'Model must be of',
            response.content.decode('utf-8')
        )
        self.assertNotEqual(self.dca.model, back_office_model)
        self.assertEqual(response.status_code, 200)
Beispiel #2
0
class DataCenterAssetAdminTest(TransactionTestCase):
    def setUp(self):
        self.user = get_user_model().objects.create_superuser(
            username='******', password='******', email='*****@*****.**')
        result = self.client.login(username='******', password='******')
        self.assertEqual(result, True)
        self.factory = RequestFactory()
        self.dca = DataCenterAssetFactory(hostname='ralph1.allegro.pl',
                                          rack=RackFactory(),
                                          position=1)
        self.custom_fields_inline_prefix = 'custom_fields-customfieldvalue-content_type-object_id-'  # noqa
        self.custom_field_str = CustomField.objects.create(
            name='test_str', type=CustomFieldTypes.STRING, default_value='xyz')
        self.custom_field_choices = CustomField.objects.create(
            name='test_choice',
            type=CustomFieldTypes.CHOICE,
            choices='qwerty|asdfgh|zxcvbn',
            default_value='zxcvbn',
            use_as_configuration_variable=True,
        )

    def _update_dca(self, dca_data=None, inline_data=None):
        data = {
            'id': self.dca.id,
            'sn': self.dca.sn,
            'barcode': self.dca.barcode,
            'hostname': self.dca.hostname,
            'model': self.dca.model_id,
            'orientation': self.dca.orientation,
            'rack': self.dca.rack.pk,
            'position': self.dca.position,
            'service_env': self.dca.service_env_id,
            'status': self.dca.status,
            'depreciation_rate': self.dca.depreciation_rate,
        }
        data.update(dca_data or {})
        if inline_data:
            data.update(self._prepare_inline_data(inline_data))
        response = self.client.post(self.dca.get_absolute_url(), data)
        self.assertEqual(
            response.status_code, 302,
            (repr(response.context['form'].errors)
             if response.context and 'form' in response.context else ''))

    def _prepare_inline_data(self, d):
        return {
            '{}{}'.format(self.custom_fields_inline_prefix, k): v
            for (k, v) in d.items()
        }

    def test_if_mail_notification_is_send_when_dca_is_updated_through_gui(
            self):
        old_service = ServiceFactory(name='test')
        new_service = ServiceFactory(name='prod')
        old_service.business_owners.add(UserFactory(email='*****@*****.**'))
        new_service.business_owners.add(UserFactory(email='*****@*****.**'))
        old_service_env = ServiceEnvironmentFactory(service=old_service)
        new_service_env = ServiceEnvironmentFactory(service=new_service)
        # update without triggering signals
        DataCenterAsset.objects.filter(pk=self.dca.pk).update(
            service_env=old_service_env)

        data_custom_fields = {
            'TOTAL_FORMS': 3,
            'INITIAL_FORMS': 0,
        }
        self._update_dca(dca_data={'service_env': new_service_env.id},
                         inline_data=data_custom_fields)

        self.dca.refresh_from_db()

        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(
            'Device has been assigned to Service: {} ({})'.format(
                new_service, self.dca), mail.outbox[0].subject)
        self.assertCountEqual(mail.outbox[0].to,
                              ['*****@*****.**', '*****@*****.**'])

    @override_settings(HERMES_HOST_UPDATE_TOPIC_NAME='ralph.host_update')
    @mock.patch('ralph.data_center.publishers.publish')
    def test_if_host_update_is_published_to_hermes_when_dca_is_updated_through_gui(  # noqa: E501
            self, publish_mock):
        self.cfv1 = CustomFieldValue.objects.create(
            object=self.dca,
            custom_field=self.custom_field_str,
            value='sample_value',
        )
        new_service = ServiceFactory(name='service1', uid='sc-44444')
        new_service_env = ServiceEnvironmentFactory(service=new_service,
                                                    environment__name='dev')

        data_custom_fields = {
            'TOTAL_FORMS': 3,
            'INITIAL_FORMS': 1,
            '0-id': self.cfv1.id,
            '0-custom_field': self.custom_field_str.id,
            '0-value': 'sample_value22',
            '1-id': '',
            '1-custom_field': self.custom_field_choices.id,
            '1-value': 'qwerty',
        }
        with transaction.atomic():
            self._update_dca(dca_data={
                'service_env': new_service_env.id,
                'hostname': 'my-host.mydc.net',
            },
                             inline_data=data_custom_fields)
            # DCA is saved twice
            self.assertGreater(len(connection.run_on_commit), 0)

        self.dca.refresh_from_db()
        publish_data = publish_mock.call_args[0][1]
        publish_data.pop('modified')
        publish_data.pop('created')
        self.assertEqual(
            publish_data, {
                '__str__': 'data center asset: ' + str(self.dca),
                'configuration_path': None,
                'configuration_variables': {
                    'test_choice': 'qwerty',
                },
                'custom_fields': {
                    'test_str': 'sample_value22',
                    'test_choice': 'qwerty'
                },
                'ethernet': [],
                'hostname': 'my-host.mydc.net',
                'id': self.dca.id,
                'ipaddresses': [],
                'object_type': 'datacenterasset',
                'parent': None,
                'remarks': '',
                'service_env': {
                    'id': new_service_env.id,
                    'service': 'service1',
                    'environment': 'dev',
                    'service_uid': 'sc-44444',
                    'ui_url': ''
                },
                'tags': [],
                'securityscan': None,
                '_previous_state': {
                    'hostname': 'ralph1.allegro.pl'
                },
            })
        # Despite `save` is called twice, publish update data is called only
        # once
        self.assertEqual(publish_mock.call_count, 1)
        # check if on_commit callbacks are removed from current db connections
        self.assertEqual(connection.run_on_commit, [])
Beispiel #3
0
class TestRestAssetInfoPerRack(TestCase):

    def setUp(self):
        get_user_model().objects.create_superuser(
            'test', '*****@*****.**', 'test'
        )

        self.client = APIClient()
        self.client.login(username='******', password='******')

        environment = EnvironmentFactory()
        service = ServiceFactory(name='Service1')
        service_env = ServiceEnvironment.objects.create(
            service=service,
            environment=environment
        )
        asset_model = DataCenterAssetModelFactory(
            type=ObjectModelType.data_center
        )
        self.server_room = ServerRoomFactory()

        self.accesory_1 = AccessoryFactory()

        self.rack_1 = RackFactory(
            server_room=self.server_room,
            max_u_height=3
        )

        self.asset_1 = DataCenterAssetFactory(
            service_env=service_env,
            position=1,
            slot_no='',
            force_depreciation=False,
            model=asset_model,
            rack=self.rack_1,
        )
        self.asset_1.management_ip = '10.15.25.45'

        self.pdu_1 = DataCenterAssetFactory(
            service_env=service_env,
            rack=self.rack_1,
            orientation=Orientation.left,
            force_depreciation=False,
            model=asset_model,
            position=0,
        )
        self.rack1_accessory = RackAccessoryFactory(
            rack=self.rack_1,
            orientation=Orientation.front,
            accessory=self.accesory_1,
            position=1
        )

    def tearDown(self):
        self.client.logout()

    def test_get(self):
        returned_json = json.loads(
            self.client.get(
                '/api/rack/{0}/'.format(self.rack_1.id)
            ).content.decode()
        )
        self.maxDiff = None
        expected_json = {
            'info': {
                'id': self.rack_1.id,
                'name': self.rack_1.name,
                'server_room': self.rack_1.server_room.id,
                'max_u_height': self.rack_1.max_u_height,
                'visualization_col': self.rack_1.visualization_col,
                'visualization_row': self.rack_1.visualization_row,
                'free_u': self.rack_1.get_free_u(),
                'description': '{}'.format(self.rack_1.description),
                'orientation': '{}'.format(self.rack_1.get_orientation_desc()),
                'rack_admin_url': self.rack_1.get_absolute_url(),
                'reverse_ordering': self.rack_1.reverse_ordering
            },
            'devices':
            [
                {
                    '_type': TYPE_ASSET,
                    'id': self.asset_1.id,
                    'hostname': self.asset_1.hostname,
                    'category': self.asset_1.model.category.name,
                    'barcode': self.asset_1.barcode,
                    'sn': self.asset_1.sn,
                    'height': float(self.asset_1.model.height_of_device),
                    'position': self.asset_1.position,
                    'model': self.asset_1.model.name,
                    'children': [],
                    'front_layout': '',
                    'back_layout': '',
                    'management_ip': self.asset_1.management_ip,
                    'orientation': 'front',
                    'remarks': '',
                    'service': 'Service1',
                    'url': self.asset_1.get_absolute_url()
                },
                {
                    '_type': TYPE_ACCESSORY,
                    'orientation': 'front',
                    'position': self.rack1_accessory.position,
                    'remarks': self.rack1_accessory.remarks,
                    'type': self.rack1_accessory.accessory.name,
                    'url': self.rack1_accessory.get_absolute_url(),
                },
            ],
            'pdus': [
                {
                    'model': self.pdu_1.model.name,
                    'orientation': 'left',
                    'sn': self.pdu_1.sn,
                    'url': self.pdu_1.get_absolute_url()
                },
            ]
        }
        self.assertEqual(returned_json, expected_json)