Ejemplo n.º 1
0
 def setUp(self):
     super().setUp()
     self.cf = CustomField.objects.create(
         name='test_cf', use_as_configuration_variable=True)
     # is should be skipped in API
     self.bo_asset = BackOfficeAssetFactory(barcode='12345',
                                            hostname='host1')
     self.conf_module_1 = ConfigurationModuleFactory()
     self.conf_module_2 = ConfigurationModuleFactory(
         parent=self.conf_module_1, name='ralph')
     self.conf_class_1 = ConfigurationClassFactory(
         module=self.conf_module_2, class_name='cls1')
     self.dc_asset = DataCenterAssetFullFactory(
         service_env__service__name='test-service',
         service_env__service__uid='sc-123',
         service_env__environment__name='prod',
         configuration_path=self.conf_class_1,
     )
     self.dc_asset.update_custom_field('test_cf', 'abc')
     self.virtual = VirtualServerFullFactory(
         parent=self.dc_asset,
         configuration_path__module__name='ralph2',
         service_env__service__uid='sc-222',
         service_env__environment__name='some_env',
     )
     self.virtual.update_custom_field('test_cf', 'def')
     se = ServiceEnvironmentFactory(service__uid='sc-333')
     self.cloud_host = CloudHostFullFactory(
         configuration_path__module__name='ralph3',
         service_env=se,
         parent__service_env=se,
         hostname='aaaa',
         hypervisor=self.dc_asset)
     self.cloud_host.ip_addresses = ['10.20.30.40']
     self.cloud_host.update_custom_field('test_cf', 'xyz')
Ejemplo n.º 2
0
 def _init(self, num=10):
     self.data_center_assets = DataCenterAssetFullFactory.create_batch(num)
     self.data_center_assets_map = {}
     for i, dca in enumerate(self.data_center_assets, start=num * 2):
         dca.parent = DataCenterAssetFullFactory()
         dca.parent.management_ip = '10.20.30.{}'.format(i)
         dca.save()
         self.data_center_assets_map[dca.id] = dca
         self.data_center_assets_map[dca.parent.id] = dca.parent
Ejemplo n.º 3
0
 def test_changelist_view(self):
     DataCenterAssetFullFactory.create_batch(5)
     VirtualServerFullFactory.create_batch(5)
     CloudHostFullFactory.create_batch(4)
     ClusterFactory.create_batch(4)
     with self.assertNumQueries(19):
         result = self.client.get(
             reverse('admin:data_center_dchost_changelist'), )
     # DCAssets - 5
     # VirtualServer + hypervisors - 10
     # Cluster - 4
     # CloudHost + hypervisors - 8
     self.assertEqual(result.context_data['cl'].result_count, 27)
Ejemplo n.º 4
0
    def test_filtering_queryset_with_additional_filters(self):
        service_env_a = ServiceEnvironmentFactory(service__name='ServiceA')
        DataCenterAssetFullFactory.create_batch(2,
                                                service_env=service_env_a,
                                                scmstatuscheck=None)
        DataCenterAssetFullFactory.create_batch(
            3,
            service_env=service_env_a,
            scmstatuscheck__check_result=SCMCheckResult.scm_error)
        DataCenterAssetFullFactory.create_batch(4,
                                                service_env=service_env_a,
                                                scmstatuscheck__ok=True)
        DataCenterAssetFullFactory.create_batch(
            1,
            service_env__service__name='ServiceB',
        )
        DataCenterAssetFullFactory.create_batch(
            3,
            service_env__service__name='ServiceC',
        )
        ServiceEnvironmentFactory.create(service__name='ServiceD')

        graph = GraphFactory(
            aggregate_type=AggregateType.aggregate_sum_bool_negated_values.id,
            params={
                'series': 'id',
                'labels': 'service__name',
                'target': {
                    'model': 'DataCenterAsset',
                    'filter': 'service_env__service__name__in',
                    'value': 'service__name',
                    'additional_filters': {
                        'scmstatuscheck__ok': False
                    },
                }
            },
            model=ContentType.objects.get_for_model(ServiceEnvironment),
        )

        dca_qs = DataCenterAsset.objects.all()
        filtered_qs = graph.get_queryset_for_filter(
            dca_qs, {'service__name': 'ServiceA'})
        self.assertEqual(filtered_qs.count(), 3)
        self.assertEqual(
            list(
                filtered_qs.values_list('service_env__service__name',
                                        'scmstatuscheck__ok')),
            [('ServiceA', False)] * 3)
Ejemplo n.º 5
0
 def setUp(self):
     self.login_as_user()
     self.asset = DataCenterAssetFullFactory(
         rack__name='Rack #1',
         rack__server_room__name='SR1',
         rack__server_room__data_center__name='DC1',
     )
Ejemplo n.º 6
0
    def test_get_available_networks(self):
        rack, nets = self._generate_rack_with_networks()

        host = CloudHostFactory(hypervisor=DataCenterAssetFullFactory(
            rack=rack))

        self.assertNetworksTheSame(nets, host._get_available_networks())
Ejemplo n.º 7
0
    def test_get_available_networks_cloud_host(self):
        rack, nets = self._generate_rack_with_networks()

        vm = VirtualServerFullFactory(parent=CloudHostFactory(
            hypervisor=DataCenterAssetFullFactory(rack=rack)))

        self.assertNetworksTheSame(nets, vm._get_available_networks())
Ejemplo n.º 8
0
    def test_get_available_networks_dc_asset(self):
        rack, nets = self._generate_rack_with_networks()

        vm = VirtualServerFullFactory(parent=DataCenterAssetFullFactory(
            rack=rack))

        self.assertNetworksTheSame(nets, vm._get_available_networks())
Ejemplo n.º 9
0
    def test_dnsaas_returns_empty_json(self):
        cluster = ClusterFactory()

        IPAddressFactory(ethernet__base_object=cluster)

        cluster.baseobjectcluster_set.create(
            is_master=True,
            base_object=DataCenterAssetFullFactory(
                rack__name='Rack #1',
                rack__server_room__name='SR1',
                rack__server_room__data_center__name='DC1',
            ))

        httpretty.register_uri(httpretty.GET,
                               "http://100.200.250.251/api/v2/records/",
                               body={})
        req = RequestFactory().get("/")  # url doesn't matter (I hope)
        req.user = self.user
        mesgs = MagicMock()
        v = DNSView(object=cluster)
        with patch("ralph.dns.views.messages", mesgs):
            v.get_forms(req)

        mesgs.error.assert_called()
        msgtext = mesgs.error.call_args[0][1]
        expected = str(_("Invalid response from DNSaaS:"))
        assert msgtext.startswith(expected),\
            "%s not in %s" % (expected, msgtext)
Ejemplo n.º 10
0
    def test_key_sort_sorts_records_descending_when_minus_present(self):
        self.data_center_assets = DataCenterAssetFullFactory.create_batch(10)
        graph = GraphFactory(
            params=self._get_graph_params({'sort': '-barcode'})
        )

        qs = graph.build_queryset()

        self.assertTrue(qs.first()['barcode'] > qs.last()['barcode'])
Ejemplo n.º 11
0
 def test_changelist_datacenterasset_location(self):
     DataCenterAssetFullFactory(
         rack__name='Rack #1',
         rack__server_room__name='SR1',
         rack__server_room__data_center__name='DC1',
     )
     result = self.client.get(
         reverse('admin:data_center_dchost_changelist'), )
     self.assertContains(result, 'DC1 / SR1 / Rack #1')
Ejemplo n.º 12
0
 def test_changelist_cloudhost_location(self):
     CloudHostFullFactory(hypervisor=DataCenterAssetFullFactory(
         rack__name='Rack #1',
         rack__server_room__name='SR1',
         rack__server_room__data_center__name='DC1',
         hostname='s12345.mydc.net',
     ))
     result = self.client.get(
         reverse('admin:data_center_dchost_changelist'), )
     self.assertContains(result, 'DC1 / SR1 / Rack #1 / s12345.mydc.net')
Ejemplo n.º 13
0
    def test_key_limit_limits_records_when_present(self):
        limit = 5
        self.data_center_assets = DataCenterAssetFullFactory.create_batch(
            2 * limit
        )
        graph = GraphFactory(params=self._get_graph_params({'limit': limit}))

        qs = graph.build_queryset()

        self.assertEqual(qs.count(), limit)
Ejemplo n.º 14
0
 def setUp(self):
     super().setUp()
     self.service_env = ServiceEnvironmentFactory()
     self.model = DataCenterAssetModelFactory()
     self.rack = RackFactory()
     self.dc_asset = DataCenterAssetFullFactory(
         rack=self.rack,
         position=10,
         model=self.model,
         service_env__environment__name='some_env'
     )
     self.dc_asset.service_env.service.business_owners = [self.user1]
     self.dc_asset.service_env.service.technical_owners = [self.user2]
     self.dc_asset.service_env.save()
     self.ip = IPAddressFactory(
         ethernet=EthernetFactory(base_object=self.dc_asset)
     )
     self.dc_asset.tags.add('db', 'test')
     self.dc_asset_2 = DataCenterAssetFullFactory()
Ejemplo n.º 15
0
 def test_get_data_center_asset_details_related_hosts(self):
     dc_asset_3 = DataCenterAssetFullFactory()
     cloud_host = CloudHostFactory(
         hypervisor=dc_asset_3
     )
     virtual_server = VirtualServerFactory(
         parent=dc_asset_3
     )
     virtual_server_2 = VirtualServerFactory(
         parent=dc_asset_3,
         hostname='random_test_hostname'
     )
     dc_asset_4 = DataCenterAssetFullFactory(
         parent=dc_asset_3
     )
     url = reverse('datacenterasset-detail', args=(dc_asset_3.id,))
     response = self.client.get(url, format='json')
     self.assertEqual(
         len(response.data['related_hosts']['cloud_hosts']), 1
     )
     self.assertEqual(
         len(response.data['related_hosts']['virtual_servers']), 2
     )
     self.assertIn(
         response.data['related_hosts']['virtual_servers'][0]['hostname'],
         (virtual_server.hostname, virtual_server_2.hostname)
     )
     self.assertIn(
         response.data['related_hosts']['virtual_servers'][1]['hostname'],
         (virtual_server.hostname, virtual_server_2.hostname)
     )
     self.assertEqual(
         response.data['related_hosts']['cloud_hosts'][0]['hostname'],
         cloud_host.hostname
     )
     self.assertEqual(
         len(response.data['related_hosts']['physical_servers']), 1
     )
     self.assertEqual(
         response.data['related_hosts']['physical_servers'][0]['hostname'],
         dc_asset_4.hostname
     )
Ejemplo n.º 16
0
 def test_changelist_cluster_location(self):
     cluster = ClusterFactory()
     cluster.baseobjectcluster_set.create(
         is_master=True,
         base_object=DataCenterAssetFullFactory(
             rack__name='Rack #1',
             rack__server_room__name='SR1',
             rack__server_room__data_center__name='DC1',
         ))
     result = self.client.get(
         reverse('admin:data_center_dchost_changelist'), )
     self.assertContains(result, 'DC1 / SR1 / Rack #1')
Ejemplo n.º 17
0
    def test_filtering_queryset(self):
        DataCenterAssetFullFactory.create_batch(
            2,
            service_env__service__name='ServiceA',
        )
        DataCenterAssetFullFactory.create_batch(
            1,
            service_env__service__name='ServiceB',
        )
        DataCenterAssetFullFactory.create_batch(
            3,
            service_env__service__name='ServiceC',
        )
        ServiceEnvironmentFactory.create(service__name='ServiceD')

        graph = GraphFactory(
            aggregate_type=AggregateType.aggregate_count.id,
            params={
                'series': 'id',
                'labels': 'service_env__service__name',
            },
        )

        dca_qs = DataCenterAsset.objects.all()
        filtered_qs = graph.get_queryset_for_filter(
            dca_qs, {
                'service_env__service__name': 'ServiceA',
            })

        self.assertEqual(filtered_qs.count(), 2)
        self.assertEqual(
            list(
                filtered_qs.values_list('service_env__service__name',
                                        flat=True)), ['ServiceA', 'ServiceA'])
Ejemplo n.º 18
0
    def setUp(self):
        self.login_as_user()
        self.asset_no_vuls = DataCenterAssetFullFactory(
            rack__name='Rack #1',
            rack__server_room__name='SR1',
            rack__server_room__data_center__name='DC1',
        )
        self.scan_no_vuls = SecurityScanFactory(
            base_object=self.asset_no_vuls.baseobject_ptr,
            vulnerabilities=[],
        )

        self.today = datetime.now()
        self.yesterday = self.today + timedelta(days=-1)
        self.tomorrow = self.today + timedelta(days=1)

        self.asset_with_today_vul = DataCenterAssetFullFactory(
            rack__name='Rack #1',
            rack__server_room__name='SR1',
            rack__server_room__data_center__name='DC1',
        )
        self.scan_with_vuls2 = SecurityScanFactory(
            base_object=self.asset_with_today_vul.baseobject_ptr,
            vulnerabilities=[
                VulnerabilityFactory(patch_deadline=self.today, )
            ])

        self.asset_vuls2 = DataCenterAssetFullFactory(
            rack__name='Rack #1',
            rack__server_room__name='SR1',
            rack__server_room__data_center__name='DC1',
        )
        self.scan_with_vuls2 = SecurityScanFactory(
            base_object=self.asset_vuls2.baseobject_ptr,
            vulnerabilities=[
                VulnerabilityFactory(patch_deadline=self.today +
                                     timedelta(days=30))
            ])
Ejemplo n.º 19
0
 def test_changelist_view(self):
     self.login_as_user()
     DataCenterAssetFullFactory.create_batch(10)
     with self.assertNumQueries(18):
         self.client.get(
             reverse('admin:data_center_datacenterasset_changelist'), )
Ejemplo n.º 20
0
class DCHostAPITests(RalphAPITestCase):
    def setUp(self):
        super().setUp()
        self.cf = CustomField.objects.create(
            name='test_cf', use_as_configuration_variable=True)
        # is should be skipped in API
        self.bo_asset = BackOfficeAssetFactory(barcode='12345',
                                               hostname='host1')
        self.conf_module_1 = ConfigurationModuleFactory()
        self.conf_module_2 = ConfigurationModuleFactory(
            parent=self.conf_module_1, name='ralph')
        self.conf_class_1 = ConfigurationClassFactory(
            module=self.conf_module_2, class_name='cls1')
        self.dc_asset = DataCenterAssetFullFactory(
            service_env__service__name='test-service',
            service_env__service__uid='sc-123',
            service_env__environment__name='prod',
            configuration_path=self.conf_class_1,
        )
        self.dc_asset.update_custom_field('test_cf', 'abc')
        self.virtual = VirtualServerFullFactory(
            parent=self.dc_asset,
            configuration_path__module__name='ralph2',
            service_env__service__uid='sc-222',
            service_env__environment__name='some_env',
        )
        self.virtual.update_custom_field('test_cf', 'def')
        se = ServiceEnvironmentFactory(service__uid='sc-333')
        self.cloud_host = CloudHostFullFactory(
            configuration_path__module__name='ralph3',
            service_env=se,
            parent__service_env=se,
            hostname='aaaa',
            hypervisor=self.dc_asset)
        self.cloud_host.ip_addresses = ['10.20.30.40']
        self.cloud_host.update_custom_field('test_cf', 'xyz')

    def test_get_dc_hosts_list(self):
        url = reverse('dchost-list')
        with self.assertNumQueries(12):
            response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['count'], 3)

    def test_filter_by_type_dc_asset(self):
        url = '{}?{}'.format(reverse('dchost-list'),
                             urlencode({'object_type': 'datacenterasset'}))
        response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['count'], 1)
        dca = response.data['results'][0]
        self.assertEqual(dca['hostname'], self.dc_asset.hostname)
        self.assertEqual(len(dca['ethernet']), 3)
        self.assertEqual(len(dca['ipaddresses']), 2)
        self.assertCountEqual(dca['tags'], ['abc, cde', 'xyz'])
        self.assertEqual(dca['configuration_path']['module']['name'], 'ralph')
        self.assertEqual(dca['service_env']['service_uid'], 'sc-123')
        self.assertEqual(dca['object_type'], 'datacenterasset')
        self.assertEqual(dca['custom_fields'], {'test_cf': 'abc'})
        self.assertEqual(dca['configuration_variables'], {'test_cf': 'abc'})

    def test_filter_by_type_virtual(self):
        url = '{}?{}'.format(reverse('dchost-list'),
                             urlencode({'object_type': 'virtualserver'}))
        response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['count'], 1)
        virt = response.data['results'][0]
        self.assertEqual(virt['hostname'], self.virtual.hostname)
        self.assertEqual(len(virt['ethernet']), 2)
        self.assertEqual(len(virt['ipaddresses']), 1)
        self.assertCountEqual(virt['tags'], ['abc, cde', 'xyz'])
        self.assertEqual(virt['configuration_path']['module']['name'],
                         'ralph2')
        self.assertEqual(virt['service_env']['service_uid'], 'sc-222')
        self.assertEqual(virt['object_type'], 'virtualserver')
        self.assertEqual(virt['custom_fields'], {'test_cf': 'def'})
        self.assertEqual(virt['configuration_variables'], {'test_cf': 'def'})

    def test_filter_by_type_cloudhost(self):
        url = '{}?{}'.format(reverse('dchost-list'),
                             urlencode({'object_type': 'cloudhost'}))
        response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['count'], 1)
        cloud = response.data['results'][0]
        self.assertEqual(cloud['hostname'], self.cloud_host.hostname)
        self.assertCountEqual(cloud['tags'], ['abc, cde', 'xyz'])
        self.assertEqual(cloud['configuration_path']['module']['name'],
                         'ralph3')
        self.assertEqual(cloud['service_env']['service_uid'], 'sc-333')
        self.assertEqual(cloud['object_type'], 'cloudhost')
        self.assertEqual(len(cloud['ethernet']), 1)
        self.assertEqual(len(cloud['ipaddresses']), 1)
        self.assertEqual(cloud['custom_fields'], {'test_cf': 'xyz'})
        self.assertEqual(cloud['configuration_variables'], {'test_cf': 'xyz'})

    def test_filter_by_hostname(self):
        url = '{}?{}'.format(reverse('dchost-list'),
                             urlencode({'hostname': 'aaaa'}))
        response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['count'], 1)

    def test_filter_by_name(self):
        url = '{}?{}'.format(reverse('dchost-list'),
                             urlencode({'name': 'aaaa'}))
        response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['count'], 1)

    def test_filter_by_service_uid(self):
        url = '{}?{}'.format(reverse('dchost-list'),
                             urlencode({'service': 'sc-222'}))
        response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['count'], 1)

    def test_filter_by_ip(self):
        url = '{}?{}'.format(reverse('dchost-list'),
                             urlencode({'ip': '10.20.30.40'}))
        response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['count'], 1)

    def test_filter_by_configuration_path(self):
        url = '{}?{}'.format(reverse('dchost-list'),
                             urlencode({'configuration_path': 'ralph/cls1'}))
        response = self.client.get(url, format='json')
        self.assertEqual(len(response.data['results']), 1)
        self.assertEqual(response.data['results'][0]['id'], self.dc_asset.id)

    def test_filter_by_configuration_path_module_name(self):
        url = '{}?{}'.format(
            reverse('dchost-list'),
            urlencode({'configuration_path__module__name': 'ralph'}))
        response = self.client.get(url, format='json')
        self.assertEqual(len(response.data['results']), 1)
        self.assertEqual(response.data['results'][0]['id'], self.dc_asset.id)

    def test_filter_by_env_name(self):
        url = '{}?{}'.format(reverse('dchost-list'),
                             urlencode({'env': 'some_env'}))
        response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['count'], 1)
Ejemplo n.º 21
0
def _get_deployment():
    obj = DataCenterAssetFullFactory()
    return Deployment(obj=obj)
Ejemplo n.º 22
0
 def setUp(self):
     self.cloud_host = CloudHostFullFactory()
     self.dc_asset = DataCenterAssetFullFactory()
     self.virtual_server = VirtualServerFactory()
Ejemplo n.º 23
0
    def test_get_data_for_choices_field_returns_names(self):
        test_data = {
            SCMCheckResult.scm_ok: 3,
            SCMCheckResult.check_failed: 2,
            SCMCheckResult.scm_error: 1
        }

        data_center_assets = DataCenterAssetFullFactory.create_batch(
            10, scmstatuscheck=None
        )
        scm_checks = []

        dca_number = 0
        for check_result in test_data:
            for i in range(test_data[check_result]):
                scm_checks.append(
                    SCMStatusCheckFactory(
                        check_result=check_result,
                        base_object=data_center_assets[dca_number]
                    )
                )
                dca_number += 1

        graph = GraphFactory(
            params=self._get_graph_params(
                {
                    "filters": {},
                    "labels": "scmstatuscheck__check_result",
                    "series": "id",
                    "sort": "series"
                }
            )
        )

        for check_result in test_data:
            encoded_params = encode_params({
                'pk': graph.pk,
                'filters': {'scmstatuscheck__check_result': check_result.id}
            })
            graph_filter = ByGraphFilter(
                None,
                {'graph-query': encoded_params},
                DataCenterAsset,
                DataCenterAdmin
            )
            qs = graph_filter.queryset(None, DataCenterAsset.objects.all())

            self.assertEqual(len(qs), test_data[check_result])

        encoded_params = encode_params({
            'pk': graph.pk,
            'filters': {'scmstatuscheck__check_result': None}
        })
        graph_filter = ByGraphFilter(
            None,
            {'graph-query': encoded_params},
            DataCenterAsset,
            DataCenterAdmin
        )
        qs = graph_filter.queryset(None, DataCenterAsset.objects.all())

        self.assertEqual(len(qs), len(data_center_assets) - dca_number)
Ejemplo n.º 24
0
class DataCenterAssetAPITests(RalphAPITestCase):
    def setUp(self):
        super().setUp()
        self.service_env = ServiceEnvironmentFactory()
        self.model = DataCenterAssetModelFactory()
        self.rack = RackFactory()
        self.dc_asset = DataCenterAssetFullFactory(
            rack=self.rack,
            position=10,
            model=self.model,
            service_env__environment__name='some_env'
        )
        self.dc_asset.service_env.service.business_owners = [self.user1]
        self.dc_asset.service_env.service.technical_owners = [self.user2]
        self.dc_asset.service_env.save()
        self.ip = IPAddressFactory(
            ethernet=EthernetFactory(base_object=self.dc_asset)
        )
        self.dc_asset.tags.add('db', 'test')
        self.dc_asset_2 = DataCenterAssetFullFactory()

    def test_get_data_center_assets_list(self):
        url = reverse('datacenterasset-list')
        with self.assertNumQueries(17):
            response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(
            response.data['count'], DataCenterAsset.objects.count()
        )

    def test_get_data_center_asset_details(self):
        url = reverse('datacenterasset-detail', args=(self.dc_asset.id,))
        response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['hostname'], self.dc_asset.hostname)
        self.assertEqual(
            response.data['rack']['id'], self.dc_asset.rack.id
        )
        self.assertEqual(
            response.data['model']['id'], self.dc_asset.model.id
        )
        self.assertEqual(len(response.data['ethernet']), 4)
        self.assertIn(self.ip.address, [
            eth['ipaddress']['address'] for eth in response.data['ethernet']
            if eth['ipaddress']
        ])
        self.assertEqual(len(response.data['memory']), 2)
        self.assertEqual(response.data['memory'][0]['speed'], 1600)
        self.assertEqual(response.data['memory'][0]['size'], 8192)
        self.assertEqual(
            response.data['business_owners'][0]['username'], 'user1'
        )
        self.assertEqual(
            response.data['technical_owners'][0]['username'], 'user2'
        )

    def test_get_data_center_asset_details_related_hosts(self):
        dc_asset_3 = DataCenterAssetFullFactory()
        cloud_host = CloudHostFactory(
            hypervisor=dc_asset_3
        )
        virtual_server = VirtualServerFactory(
            parent=dc_asset_3
        )
        virtual_server_2 = VirtualServerFactory(
            parent=dc_asset_3,
            hostname='random_test_hostname'
        )
        dc_asset_4 = DataCenterAssetFullFactory(
            parent=dc_asset_3
        )
        url = reverse('datacenterasset-detail', args=(dc_asset_3.id,))
        response = self.client.get(url, format='json')
        self.assertEqual(
            len(response.data['related_hosts']['cloud_hosts']), 1
        )
        self.assertEqual(
            len(response.data['related_hosts']['virtual_servers']), 2
        )
        self.assertIn(
            response.data['related_hosts']['virtual_servers'][0]['hostname'],
            (virtual_server.hostname, virtual_server_2.hostname)
        )
        self.assertIn(
            response.data['related_hosts']['virtual_servers'][1]['hostname'],
            (virtual_server.hostname, virtual_server_2.hostname)
        )
        self.assertEqual(
            response.data['related_hosts']['cloud_hosts'][0]['hostname'],
            cloud_host.hostname
        )
        self.assertEqual(
            len(response.data['related_hosts']['physical_servers']), 1
        )
        self.assertEqual(
            response.data['related_hosts']['physical_servers'][0]['hostname'],
            dc_asset_4.hostname
        )

    def test_create_data_center_asset(self):
        url = reverse('datacenterasset-list')
        data = {
            'hostname': '12345',
            'barcode': '12345',
            'model': self.model.id,
            'rack': self.rack.id,
            'position': 12,
            'service_env': self.service_env.id,
            'force_depreciation': False,
        }
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        dc_asset = DataCenterAsset.objects.get(pk=response.data['id'])
        self.assertEqual(dc_asset.hostname, '12345')
        self.assertEqual(dc_asset.service_env, self.service_env)
        self.assertEqual(dc_asset.rack, self.rack)

    def test_create_data_center_asset_without_rack(self):
        url = reverse('datacenterasset-list')
        data = {
            'hostname': '12345',
            'barcode': '12345',
            'model': self.model.id,
            'position': 12,
            'service_env': self.service_env.id,
            'force_depreciation': False,
        }
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(response.data, {
            'rack': ['This field is required.'],
        })

    def test_create_data_center_asset_with_rack_null(self):
        url = reverse('datacenterasset-list')
        data = {
            'hostname': '12345',
            'barcode': '12345',
            'rack': None,
            'model': self.model.id,
            'position': 12,
            'service_env': self.service_env.id,
            'force_depreciation': False,
        }
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(response.data, {
            'rack': ['This field may not be null.'],
        })

    def test_create_data_center_with_tags(self):
        url = reverse('datacenterasset-list')
        data = {
            'hostname': '12345',
            'barcode': '12345',
            'model': self.model.id,
            'rack': self.rack.id,
            'position': 12,
            'service_env': self.service_env.id,
            'force_depreciation': False,
            'tags': ['prod', 'db']
        }
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        dc_asset = DataCenterAsset.objects.get(pk=response.data['id'])
        self.assertEqual(dc_asset.hostname, '12345')
        self.assertEqual(dc_asset.service_env, self.service_env)
        self.assertEqual(dc_asset.rack, self.rack)
        self.assertEqual(dc_asset.tags.count(), 2)

    def test_create_data_center_without_barcode_and_sn(self):
        url = reverse('datacenterasset-list')
        data = {
            'hostname': '12345',
            'model': self.model.id,
            'rack': self.rack.id,
            'position': 12,
            'service_env': self.service_env.id,
            'force_depreciation': False,
            'tags': ['prod', 'db']
        }
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(response.data, {
            'sn': ['SN or BARCODE field is required'],
            'barcode': ['SN or BARCODE field is required'],
        })

    def test_patch_data_center_asset(self):
        url = reverse('datacenterasset-detail', args=(self.dc_asset.id,))
        data = {
            'hostname': '54321',
            'force_depreciation': True,
            'tags': ['net']
        }
        response = self.client.patch(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.dc_asset.refresh_from_db()
        self.assertEqual(self.dc_asset.hostname, '54321')
        self.assertTrue(self.dc_asset.force_depreciation)
        self.assertEqual(self.dc_asset.tags.count(), 1)

    def test_filter_by_configuration_path(self):
        url = reverse('datacenterasset-list') + '?configuration_path={}'.format(
            self.dc_asset.configuration_path.path,
        )
        response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(
            response.data['count'], 1
        )

    def test_filter_by_hostname(self):
        url = reverse('datacenterasset-list') + '?hostname={}'.format(
            self.dc_asset.hostname,
        )
        response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(
            response.data['count'], 1
        )

    def test_filter_by_ip_address(self):
        url = reverse('datacenterasset-list') + '?ip={}'.format(
            self.ip.address,
        )
        response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(
            response.data['count'], 1
        )

    def test_filter_by_service_uid(self):
        url = reverse('datacenterasset-list') + '?service={}'.format(
            self.dc_asset.service_env.service.uid,
        )
        response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(
            response.data['count'], 1
        )

    def test_filter_by_service_uid2(self):
        url = (
            reverse('datacenterasset-list') +
            '?service_env__service__uid={}'.format(
                self.dc_asset.service_env.service.uid,
            )
        )
        response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(
            response.data['count'], 1
        )

    def test_filter_by_service_id(self):
        url = (
            reverse('datacenterasset-list') +
            '?service_env__service__id={}'.format(
                self.dc_asset.service_env.service.id,
            )
        )
        response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(
            response.data['count'], 1
        )

    def test_filter_by_service_name(self):
        url = reverse('datacenterasset-list') + '?service={}'.format(
            self.dc_asset.service_env.service.name,
        )
        response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(
            response.data['count'], 1
        )

    def test_filter_by_service_name2(self):
        url = (
            reverse('datacenterasset-list') +
            '?service_env__service__name={}'.format(
                self.dc_asset.service_env.service.name,
            )
        )
        response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(
            response.data['count'], 1
        )

    def test_filter_by_env_name(self):
        url = reverse('datacenterasset-list') + '?env=some_env'
        response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(
            response.data['count'], 1
        )