def setUp(self): """Create test case setup.""" self.cred = Credential(name='cred1', cred_type=Credential.SATELLITE_CRED_TYPE, username='******', password='******', become_password=None, become_method=None, become_user=None, ssh_keyfile=None) self.cred.save() self.source = Source(name='source1', port=443, hosts='["1.2.3.4"]') self.source.save() self.source.credentials.add(self.cred) self.scan_task = ScanTask(scan_type=ScanTask.SCAN_TYPE_CONNECT, source=self.source, sequence_number=1) self.scan_task.save() self.scan_job = ScanJob(scan_type=ScanTask.SCAN_TYPE_CONNECT) self.scan_job.save() self.scan_job.tasks.add(self.scan_task) self.conn_results = JobConnectionResult() self.conn_results.save() self.scan_job.connection_results = self.conn_results self.scan_job.save() self.conn_result = TaskConnectionResult(scan_task=self.scan_task, source=self.source) self.conn_result.save()
def __init__(self, scan_job, scan_task): """Set context for task execution. :param scan_job: the scan job that contains this task :param scan_task: the scan task model for this task :param prerequisite_tasks: An array of scan task model objects that were execute prior to running this task. """ super().__init__(scan_job, scan_task) self.source = scan_task.source conn_results = self.scan_job.connection_results with transaction.atomic(): conn_result = conn_results.results.filter( source__id=self.source.id).first() if conn_result is None: conn_result = TaskConnectionResult(scan_task=scan_task, source=self.source) conn_result.save() conn_results.results.add(conn_result) conn_results.save() self.conn_result = conn_result # If we're restarting the scan after a pause, systems that # were previously up might be down. So we throw out any # partial results and start over. conn_result.systems.all().delete()
def setUp(self): """Create test case setup.""" self.cred = Credential(name='cred1', cred_type=Credential.SATELLITE_CRED_TYPE, username='******', password='******', become_password=None, become_method=None, become_user=None, ssh_keyfile=None) self.cred.save() self.source = Source(name='source1', port=443, hosts='["1.2.3.4"]') self.source.save() self.source.credentials.add(self.cred) self.scan_job, self.scan_task = create_scan_job( self.source, ScanTask.SCAN_TYPE_INSPECT) self.api = SatelliteFive(self.scan_job, self.scan_task) connection_results = TaskConnectionResult() connection_results.save() self.api.connect_scan_task.connection_result = connection_results self.api.connect_scan_task.connection_result.save() sys_result = SystemConnectionResult( name='sys1_1', status=SystemInspectionResult.SUCCESS) sys_result.save() self.api.connect_scan_task.connection_result.systems.add(sys_result) self.api.connect_scan_task.connection_result.save() self.api.connect_scan_task.save()
def test_get_result(self): """Test get result method when results exist.""" conn_result = TaskConnectionResult(source=self.source, scan_task=self.scan_task) conn_result.save() self.conn_results.results.add(conn_result) self.conn_results.save() results = self.runner.get_result() self.assertEqual(results, conn_result)
def setUp(self): """Create test case setup.""" self.cred = Credential( name='cred1', cred_type=Credential.SATELLITE_CRED_TYPE, username='******', password='******') self.cred.save() self.source = Source( name='source1', port=443, hosts='["1.2.3.4"]') self.source.save() self.source.credentials.add(self.cred) self.scan_task = ScanTask(scan_type=ScanTask.SCAN_TYPE_INSPECT, source=self.source, sequence_number=2, start_time=datetime.utcnow()) self.scan_task.save() self.scan_task.update_stats('TEST_SAT.', sys_scanned=0) self.scan_job = ScanJob(scan_type=ScanTask.SCAN_TYPE_CONNECT) self.scan_job.save() self.scan_job.tasks.add(self.scan_task) self.conn_results = JobConnectionResult() self.conn_results.save() self.scan_job.connection_results = self.conn_results self.conn_result = TaskConnectionResult( scan_task=self.scan_task, source=self.source) self.conn_result.save() conn_task = ScanTask(scan_type=ScanTask.SCAN_TYPE_CONNECT, source=self.source, sequence_number=1, start_time=datetime.utcnow()) conn_task.complete() self.scan_task.prerequisites.add(conn_task) self.inspect_results = JobInspectionResult() self.inspect_results.save() self.scan_job.inspection_results = self.inspect_results self.scan_job.save()
def test_hosts_facts(self, mock_pool): """Test the hosts_facts method.""" scan_options = ScanOptions(max_concurrency=10) scan_options.save() scan_job, scan_task = create_scan_job(self.source, ScanTask.SCAN_TYPE_INSPECT, scan_name='test_62', scan_options=scan_options) scan_task.update_stats('TEST_SAT.', sys_scanned=0) api = SatelliteSixV2(scan_job, scan_task) job_conn_result = JobConnectionResult() job_conn_result.save() connection_results = TaskConnectionResult( job_connection_result=job_conn_result) connection_results.save() api.connect_scan_task.connection_result = connection_results api.connect_scan_task.connection_result.save() sys_result = SystemConnectionResult( name='sys1_1', status=SystemInspectionResult.SUCCESS, task_connection_result=api.connect_scan_task.connection_result) sys_result.save() api.connect_scan_task.save() hosts_url = 'https://{sat_host}:{port}/api/v2/hosts' with requests_mock.Mocker() as mocker: url = construct_url(url=hosts_url, sat_host='1.2.3.4') jsonresult = { 'total': 1, 'subtotal': 1, 'page': 1, 'per_page': 100, 'results': [{ 'id': 10, 'name': 'sys10' }] } # noqa mocker.get(url, status_code=200, json=jsonresult) api.hosts_facts(Value('i', ScanJob.JOB_RUN)) inspect_result = scan_task.inspection_result self.assertEqual(len(inspect_result.systems.all()), 1)
def test_expand_sys_conn_result(self): """Test view expand_sys_conn_result.""" scan_job = ScanJob(scan_type=ScanTask.SCAN_TYPE_CONNECT) scan_job.save() scan_job.sources.add(self.source) # Job in created state self.assertEqual(scan_job.status, ScanTask.CREATED) tasks = scan_job.tasks.all() self.assertEqual(len(tasks), 0) # Queue job to run scan_job.queue() conn_task = scan_job.tasks.first() conn_result = TaskConnectionResult(source=conn_task.source, scan_task=conn_task) conn_result.save() sys_result = SystemConnectionResult( name='Foo', credential=self.cred, status=SystemConnectionResult.SUCCESS) sys_result.save() conn_result.systems.add(sys_result) conn_result.save() result = expand_sys_conn_result(conn_result) self.assertEqual(result[0]['credential']['name'], 'cred1')
def setUp(self): """Create test case setup.""" self.cred = Credential(name='cred1', cred_type=Credential.SATELLITE_CRED_TYPE, username='******', password='******', become_password=None, become_method=None, become_user=None, ssh_keyfile=None) self.cred.save() self.source = Source(name='source1', port=443, hosts='["1.2.3.4"]') self.source.save() self.source.credentials.add(self.cred) self.scan_task = ScanTask(scan_type=ScanTask.SCAN_TYPE_CONNECT, source=self.source, sequence_number=1, start_time=datetime.utcnow()) self.scan_task.save() self.scan_task.update_stats('TEST_SAT.', sys_scanned=0) self.scan_job = ScanJob(scan_type=ScanTask.SCAN_TYPE_CONNECT) self.scan_job.save() self.scan_job.tasks.add(self.scan_task) self.conn_results = JobConnectionResult() self.conn_results.save() self.scan_job.connection_results = self.conn_results self.scan_job.save() self.conn_result = TaskConnectionResult(scan_task=self.scan_task, source=self.source) self.conn_result.save() self.inspect_result = TaskInspectionResult(scan_task=self.scan_task, source=self.source) self.inspect_result.save() self.api = SatelliteSixV2(self.scan_task, self.conn_result, self.inspect_result)
def __init__(self, scan_task, conn_results): """Get the unique TaskConnectionResult object for this scan.""" self.scan_task = scan_task self.conn_results = conn_results source = scan_task.source with transaction.atomic(): conn_result = conn_results.results.filter( source__id=source.id).first() if conn_result is None: conn_result = TaskConnectionResult(scan_task=scan_task, source=source) conn_result.save() conn_results.results.add(conn_result) conn_results.save() self.conn_result = conn_result # If we're restarting the scan after a pause, systems that # were previously up might be down. So we throw out any # partial results and start over. conn_result.systems.all().delete() # Sources can contain patterns that describe multiple hosts, # like '1.2.3.[4:6]'. Expand the patterns so hosts is a list # of single hosts we can try to connect to. hosts = [] hosts_list = source.get_hosts() for host in hosts_list: hosts.extend(expand_hostpattern(host)) self._remaining_hosts = set(hosts) if scan_task.systems_count is None: scan_task.update_stats('INITIAL NETWORK CONNECT STATS.', sys_count=len(hosts), sys_scanned=0, sys_failed=0)
def test_expand_conn_results(self): """Test view expand_conn_results.""" scan_job = ScanJob(scan_type=ScanTask.SCAN_TYPE_CONNECT) scan_job.save() scan_job.sources.add(self.source) # Job in created state self.assertEqual(scan_job.status, ScanTask.CREATED) tasks = scan_job.tasks.all() self.assertEqual(len(tasks), 0) # Queue job to run scan_job.queue() conn_task = scan_job.tasks.first() conn_results = JobConnectionResult() conn_results.save() scan_job.connection_results = conn_results scan_job.save() conn_result = TaskConnectionResult(source=conn_task.source, scan_task=conn_task) conn_result.save() conn_results.results.add(conn_result) conn_results.save() sys_result = SystemConnectionResult( name='Foo', credential=self.cred, status=SystemConnectionResult.SUCCESS) sys_result.save() conn_result.systems.add(sys_result) conn_result.save() conn_results_json = {'results': [{}]} expand_conn_results(conn_results, conn_results_json) self.assertEqual(conn_results_json['results'][0]['systems'][0]['name'], 'Foo')
def _store_connect_data(self, connected, credential): # Update the scan counts self.scan_task.update_stats('INITIAL VCENTER CONNECT STATS.', sys_count=len(connected)) conn_result = TaskConnectionResult(source=self.scan_task.source, scan_task=self.scan_task) conn_result.save() for system in connected: sys_result = SystemConnectionResult( name=system, status=SystemConnectionResult.SUCCESS, credential=credential) sys_result.save() conn_result.systems.add(sys_result) self.scan_task.increment_stats(sys_result.name, increment_sys_scanned=True) conn_result.save() self.scan_job.connection_results.results.add(conn_result) self.scan_job.connection_results.save()
class NetworkInspectScannerTest(TestCase): """Tests network inspect scan task class.""" # pylint: disable=too-many-instance-attributes, protected-access def setUp(self): """Create test case setup.""" self.cred = Credential( name='cred1', username='******', password='******', ssh_keyfile=None, become_method=None, become_user=None, become_password=None) self.cred.save() hc_serializer = CredentialSerializer(self.cred) self.cred_data = hc_serializer.data self.source = Source( name='source1', port=22, hosts='["1.2.3.4"]') self.source.save() self.source.credentials.add(self.cred) self.host_list = [('1.2.3.4', self.cred_data)] self.connect_scan_task = ScanTask(source=self.source, scan_type=ScanTask.SCAN_TYPE_CONNECT, status=ScanTask.COMPLETED, start_time=datetime.utcnow()) self.connect_scan_task.update_stats( 'TEST NETWORK CONNECT.', sys_failed=0) self.inspect_scan_task = ScanTask(source=self.source, scan_type=ScanTask.SCAN_TYPE_INSPECT, start_time=datetime.utcnow()) self.inspect_scan_task.update_stats( 'TEST NETWORK INSPECT.', sys_failed=0) self.inspect_scan_task.prerequisites.add(self.connect_scan_task) self.inspect_scan_task.save() self.scan_job = ScanJob(scan_type=ScanTask.SCAN_TYPE_INSPECT) self.scan_job.save() self.scan_job.tasks.add(self.connect_scan_task) self.scan_job.tasks.add(self.inspect_scan_task) scan_options = ScanOptions() scan_options.disable_optional_products = {'jboss_eap': False, 'jboss_fuse': False, 'jboss_brms': False} scan_options.save() self.scan_job.options = scan_options self.scan_job.save() self.fact_endpoint = 'http://testserver' + reverse('facts-list') self.conn_results = JobConnectionResult() self.conn_results.save() self.scan_job.connection_results = self.conn_results self.conn_result = TaskConnectionResult( scan_task=self.connect_scan_task, source=self.source) self.conn_result.save() success_sys = SystemConnectionResult( name='1.2.3.4', credential=self.cred, status=SystemConnectionResult.SUCCESS) success_sys.save() failed_sys = SystemConnectionResult( name='1.1.1.2', status=SystemConnectionResult.FAILED) failed_sys.save() self.conn_result.systems.add(success_sys) self.conn_result.systems.add(failed_sys) self.conn_result.save() self.conn_results.results.add(self.conn_result) self.conn_results.save() self.scan_job.connection_results = self.conn_results self.inspect_results = JobInspectionResult() self.inspect_results.save() self.scan_job.inspection_results = self.inspect_results self.scan_job.save() def test_scan_inventory(self): """Test construct ansible inventory dictionary.""" serializer = SourceSerializer(self.source) source = serializer.data connection_port = source['port'] inventory_dict = _construct_scan_inventory(self.host_list, connection_port, 50) expected = { 'all': { 'children': { 'group_0': { 'hosts': { '1.2.3.4': { 'ansible_user': '******', 'ansible_ssh_pass': '******', 'ansible_host': '1.2.3.4'} } } }, 'vars': { 'ansible_port': 22} } } self.assertEqual(inventory_dict[1], expected) def test_scan_inventory_grouping(self): """Test construct ansible inventory dictionary.""" serializer = SourceSerializer(self.source) source = serializer.data connection_port = source['port'] hc_serializer = CredentialSerializer(self.cred) cred = hc_serializer.data inventory_dict = _construct_scan_inventory( [ ('1.2.3.1', cred), ('1.2.3.2', cred), ('1.2.3.3', cred), ('1.2.3.4', cred) ], connection_port, 1) expected = { 'all': { 'children': { 'group_0': { 'hosts': { '1.2.3.1': { 'ansible_user': '******', 'ansible_ssh_pass': '******', 'ansible_host': '1.2.3.1'} } }, 'group_1': { 'hosts': { '1.2.3.2': { 'ansible_user': '******', 'ansible_ssh_pass': '******', 'ansible_host': '1.2.3.2'} } }, 'group_2': { 'hosts': { '1.2.3.3': { 'ansible_user': '******', 'ansible_ssh_pass': '******', 'ansible_host': '1.2.3.3'} } }, 'group_3': { 'hosts': { '1.2.3.4': { 'ansible_user': '******', 'ansible_ssh_pass': '******', 'ansible_host': '1.2.3.4'} } } }, 'vars': { 'ansible_port': 22} } } self.assertEqual(inventory_dict[1], expected) @patch('scanner.network.utils.TaskQueueManager.run', side_effect=mock_run_failed) def test_inspect_scan_failure(self, mock_run): """Test scan flow with mocked manager and failure.""" scanner = InspectTaskRunner( self.scan_job, self.inspect_scan_task) # Init for unit test as run is not called scanner.connect_scan_task = self.connect_scan_task with self.assertRaises(AnsibleError): scanner._inspect_scan(self.host_list) mock_run.assert_called() @patch('scanner.network.inspect.InspectTaskRunner._inspect_scan', side_effect=mock_scan_error) def test_inspect_scan_error(self, mock_scan): """Test scan flow with mocked manager and failure.""" scanner = InspectTaskRunner( self.scan_job, self.inspect_scan_task) scan_task_status = scanner.run() mock_scan.assert_called_with(self.host_list) self.assertEqual(scan_task_status[1], ScanTask.FAILED) @patch('scanner.network.utils.TaskQueueManager.run', side_effect=mock_run_success) def test_inspect_scan_fail_no_facts(self, mock_run): """Test running a inspect scan with mocked connection.""" expected = ([('1.2.3.4', {'name': 'cred1'})], []) mock_run.return_value = expected with requests_mock.Mocker() as mocker: mocker.post(self.fact_endpoint, status_code=201, json={'id': 1}) scanner = InspectTaskRunner( self.scan_job, self.inspect_scan_task) scan_task_status = scanner.run() mock_run.assert_called_with(ANY) self.assertEqual(scan_task_status[1], ScanTask.FAILED) def test_populate_callback(self): """Test the population of the callback object for inspect scan.""" callback = InspectResultCallback( scan_task=self.inspect_scan_task, inspect_results=self.inspect_results) host = Mock() host.name = '1.2.3.4' result = Mock(_host=host, _results={'rc': 3}) callback.v2_runner_on_unreachable(result) def test_ssh_crash(self): """Simulate an ssh crash.""" scanner = InspectTaskRunner( self.scan_job, self.inspect_scan_task) path = os.path.abspath( os.path.join(os.path.dirname(__file__), '../../../test_util/crash.py')) _, result = scanner._inspect_scan( self.host_list, base_ssh_executable=path) self.assertEqual(result, ScanTask.FAILED) def test_ssh_hang(self): """Simulate an ssh hang.""" scanner = InspectTaskRunner( self.scan_job, self.inspect_scan_task) path = os.path.abspath( os.path.join(os.path.dirname(__file__), '../../../test_util/hang.py')) scanner._inspect_scan( self.host_list, roles=['redhat_release'], base_ssh_executable=path, ssh_timeout='0.1s')
class SatelliteSixV2Test(TestCase): """Tests Satellite 6 v2 functions.""" def setUp(self): """Create test case setup.""" self.cred = Credential(name='cred1', cred_type=Credential.SATELLITE_CRED_TYPE, username='******', password='******', become_password=None, become_method=None, become_user=None, ssh_keyfile=None) self.cred.save() self.source = Source(name='source1', port=443, hosts='["1.2.3.4"]') self.source.save() self.source.credentials.add(self.cred) self.scan_task = ScanTask(scan_type=ScanTask.SCAN_TYPE_CONNECT, source=self.source, sequence_number=1, start_time=datetime.utcnow()) self.scan_task.save() self.scan_task.update_stats('TEST_SAT.', sys_scanned=0) self.scan_job = ScanJob(scan_type=ScanTask.SCAN_TYPE_CONNECT) self.scan_job.save() self.scan_job.tasks.add(self.scan_task) self.conn_results = JobConnectionResult() self.conn_results.save() self.scan_job.connection_results = self.conn_results self.scan_job.save() self.conn_result = TaskConnectionResult(scan_task=self.scan_task, source=self.source) self.conn_result.save() self.inspect_result = TaskInspectionResult(scan_task=self.scan_task, source=self.source) self.inspect_result.save() self.api = SatelliteSixV2(self.scan_task, self.conn_result, self.inspect_result) def tearDown(self): """Cleanup test case setup.""" pass def test_host_count(self): """Test the method host_count.""" hosts_url = 'https://{sat_host}:{port}/api/v2/hosts' with requests_mock.Mocker() as mocker: url = construct_url(url=hosts_url, sat_host='1.2.3.4', org_id=1) jsonresult = { 'results': [{ 'name': 'sys1' }, { 'name': 'sys2' }, { 'name': 'sys3' }], 'per_page': 100, 'total': 3 } mocker.get(url, status_code=200, json=jsonresult) systems_count = self.api.host_count() self.assertEqual(systems_count, 3) def test_host_count_with_err(self): """Test the method host_count with error.""" hosts_url = 'https://{sat_host}:{port}/api/v2/hosts' with requests_mock.Mocker() as mocker: url = construct_url(url=hosts_url, sat_host='1.2.3.4', org_id=1) jsonresult = { 'results': [{ 'name': 'sys1' }, { 'name': 'sys2' }, { 'name': 'sys3' }], 'per_page': 100, 'total': 3 } mocker.get(url, status_code=500, json=jsonresult) with self.assertRaises(SatelliteException): self.api.host_count() def test_hosts(self): """Test the method hosts.""" hosts_url = 'https://{sat_host}:{port}/api/v2/hosts' with requests_mock.Mocker() as mocker: url = construct_url(url=hosts_url, sat_host='1.2.3.4', org_id=1) jsonresult = { 'results': [{ 'name': 'sys1' }, { 'name': 'sys2' }, { 'name': 'sys3' }], 'per_page': 100, 'total': 3 } mocker.get(url, status_code=200, json=jsonresult) systems_count = self.api.host_count() hosts = self.api.hosts() self.assertEqual(systems_count, 3) self.assertEqual(len(hosts), 3) self.assertEqual(hosts, ['sys1', 'sys2', 'sys3']) def test_hosts_with_err(self): """Test the method hosts with error.""" hosts_url = 'https://{sat_host}:{port}/api/v2/hosts' with requests_mock.Mocker() as mocker: url = construct_url(url=hosts_url, sat_host='1.2.3.4', org_id=1) jsonresult = { 'results': [{ 'name': 'sys1' }, { 'name': 'sys2' }, { 'name': 'sys3' }], 'per_page': 100, 'total': 3 } mocker.get(url, status_code=500, json=jsonresult) with self.assertRaises(SatelliteException): self.api.hosts() def test_host_fields_with_err(self): """Test the method host_fields with error.""" host_field_url = 'https://{sat_host}:{port}/api/v2/hosts/{host_id}' with requests_mock.Mocker() as mocker: url = construct_url(url=host_field_url, sat_host='1.2.3.4', host_id=1) mocker.get(url, status_code=500) with self.assertRaises(SatelliteException): host_fields(self.scan_task, 2, host_field_url, None, 1) def test_host_fields(self): """Test the method host_fields.""" host_field_url = 'https://{sat_host}:{port}/api/v2/hosts/{host_id}' with requests_mock.Mocker() as mocker: url = construct_url(url=host_field_url, sat_host='1.2.3.4', host_id=1) jsonresult = { 'architecture_id': 1, 'architecture_name': 'x86_64', 'operatingsystem_name': 'RedHat 7.4', 'uuid': None, 'created_at': '2017-12-04 13:19:57 UTC', 'updated_at': '2017-12-04 13:21:47 UTC', 'organization_name': 'ACME', 'location_name': 'Raleigh', 'name': 'mac52540071bafe.prov.lan', 'virtual_host': { 'uuid': '100', 'name': 'vhost1' }, 'virtual_guests': [{ 'name': 'foo' }], 'content_facet_attributes': { 'id': 11, 'katello_agent_installed': False }, 'subscription_facet_attributes': { 'uuid': '00c7a108-48ec-4a97-835c-aa3369777f64', 'last_checkin': '2018-01-04 17:36:07 UTC', 'registered_at': '2017-12-04 13:33:52 UTC', 'registered_by': 'sat-r220-07.lab.eng.rdu2.redhat.com', 'virtual_host': { 'uuid': '100', 'name': 'vhost1' }, 'virtual_guests': [{ 'name': 'foo' }], }, 'facts': { 'memorysize_mb': '992.45', 'memorysize': '992.45 MB', 'hostname': 'fdi', 'type': 'Other', 'architecture': 'x86_64', 'is_virtual': 'true', 'virtual': 'kvm', 'net::interface::ipv4_address': '192.168.99.123', 'net::interface::mac_address': 'fe80::5054:ff:fe24:946e', }, } mocker.get(url, status_code=200, json=jsonresult) host_info = host_fields(self.scan_task, 2, host_field_url, None, 1) expected = { 'uuid': '00c7a108-48ec-4a97-835c-aa3369777f64', 'hostname': 'mac52540071bafe.prov.lan', 'registered_by': 'sat-r220-07.lab.eng.rdu2.redhat.com', 'registration_time': '2017-12-04 13:33:52 UTC', 'last_checkin_time': '2018-01-04 17:36:07 UTC', 'katello_agent_installed': False, 'os_release': 'RedHat 7.4', 'organization': 'ACME', 'virtual_host': '100', 'virtual_host_name': 'vhost1', 'virt_type': None, 'kernel_version': None, 'architecture': None, 'is_virtualized': None, 'cores': None, 'num_sockets': None, 'num_virtual_guests': 1, 'virtual': 'hypervisor', 'location': 'Raleigh', 'ip_addresses': ['192.168.99.123'], 'mac_addresses': ['fe80::5054:ff:fe24:946e'], 'os_name': 'RedHat', 'os_version': '7.4' } self.assertEqual(host_info, expected) def test_host_subs_with_err(self): """Test the host subscriptons method with bad status code.""" sub_url = 'https://{sat_host}:{port}/' \ 'api/v2/hosts/{host_id}/subscriptions' with requests_mock.Mocker() as mocker: url = construct_url(url=sub_url, sat_host='1.2.3.4', host_id=1) mocker.get(url, status_code=500) with self.assertRaises(SatelliteException): host_subscriptions(self.scan_task, sub_url, None, 1) def test_host_subs_err_nojson(self): """Test the host subscriptons method with bad code and not json.""" sub_url = 'https://{sat_host}:{port}/' \ 'api/v2/hosts/{host_id}/subscriptions' with requests_mock.Mocker() as mocker: url = construct_url(url=sub_url, sat_host='1.2.3.4', host_id=1) mocker.get(url, status_code=404, text='error message') subs = host_subscriptions(self.scan_task, sub_url, None, 1) self.assertEqual(subs, {'entitlements': []}) def test_host_not_subscribed(self): """Test the host subscriptons method for not subscribed error.""" sub_url = 'https://{sat_host}:{port}/' \ 'api/v2/hosts/{host_id}/subscriptions' with requests_mock.Mocker() as mocker: url = construct_url(url=sub_url, sat_host='1.2.3.4', host_id=1) err_msg = { 'displayMessage': 'Host has not been registered ' 'with subscription-manager', 'errors': ['Host has not been registered' ' with subscription-manager'] } # noqa mocker.get(url, status_code=400, json=err_msg) subs = host_subscriptions(self.scan_task, sub_url, None, 1) self.assertEqual(subs, {'entitlements': []}) def test_host_subscriptons(self): """Test the host subscriptons method.""" sub_url = 'https://{sat_host}:{port}/' \ 'api/v2/hosts/{host_id}/subscriptions' with requests_mock.Mocker() as mocker: url = construct_url(url=sub_url, sat_host='1.2.3.4', host_id=1) jsonresult = { 'results': [{ 'amount': 1, 'name': 'Satellite Tools 6.3', 'start_date': '2017-12-01 14:50:59 UTC', 'end_date': '2047-11-24 14:50:59 UTC', 'product_name': 'Satellite Tools 6.3', }, { 'quantity_consumed': 1, 'name': 'Employee SKU', 'start_date': '2016-03-24 04:00:00 UTC', 'end_date': '2022-01-01 04:59:59 UTC', 'account_number': 1212729, 'contract_number': 10913844, 'type': 'ENTITLEMENT_DERIVED', 'product_name': 'Employee SKU', }] } mocker.get(url, status_code=200, json=jsonresult) subs = host_subscriptions(self.scan_task, sub_url, None, 1) expected = { 'entitlements': [{ 'derived_entitlement': False, 'name': 'Satellite Tools 6.3', 'amount': 1, 'account_number': None, 'contract_number': None, 'start_date': '2017-12-01 14:50:59 UTC', 'end_date': '2047-11-24 14:50:59 UTC' }, { 'derived_entitlement': True, 'name': 'Employee SKU', 'amount': 1, 'account_number': 1212729, 'contract_number': 10913844, 'start_date': '2016-03-24 04:00:00 UTC', 'end_date': '2022-01-01 04:59:59 UTC' }] } self.assertEqual(subs, expected) def test_host_details(self): """Test host_details method with mock data.""" fields_return_value = { 'uuid': '00c7a108-48ec-4a97-835c-aa3369777f64', 'hostname': 'mac52540071bafe.prov.lan', 'registered_by': 'sat-r220-07.lab.eng.rdu2.redhat.com', 'registration_time': '2017-12-04 13:33:52 UTC', 'last_checkin_time': '2018-01-04 17:36:07 UTC', 'katello_agent_installed': False, 'os_name': 'RedHat 7.4', 'organization': 'ACME', 'virtual_host': '100', 'virtual_host_name': 'vhost1', 'virt_type': None, 'kernel_version': None, 'architecture': None, 'is_virtualized': None, 'cores': None, 'num_sockets': None, 'num_virtual_guests': 1, 'virtual': 'hypervisor', 'location': 'Raleigh', 'ip_addresses': ['192.168.99.123'], 'ipv6_addresses': ['fe80::5054:ff:fe24:946e'] } subs_return_value = { 'entitlements': [{ 'derived_entitlement': False, 'name': 'Satellite Tools 6.3', 'amount': 1, 'account_number': None, 'contract_number': None, 'start_date': '2017-12-01 14:50:59 UTC', 'end_date': '2047-11-24 14:50:59 UTC' }, { 'derived_entitlement': True, 'name': 'Employee SKU', 'amount': 1, 'account_number': 1212729, 'contract_number': 10913844, 'start_date': '2016-03-24 04:00:00 UTC', 'end_date': '2022-01-01 04:59:59 UTC' }] } expected = { 'uuid': '00c7a108-48ec-4a97-835c-aa3369777f64', 'hostname': 'mac52540071bafe.prov.lan', 'registered_by': 'sat-r220-07.lab.eng.rdu2.redhat.com', 'registration_time': '2017-12-04 13:33:52 UTC', 'last_checkin_time': '2018-01-04 17:36:07 UTC', 'katello_agent_installed': False, 'os_name': 'RedHat 7.4', 'organization': 'ACME', 'virtual_host': '100', 'virtual_host_name': 'vhost1', 'virt_type': None, 'kernel_version': None, 'architecture': None, 'is_virtualized': None, 'cores': None, 'num_sockets': None, 'num_virtual_guests': 1, 'virtual': 'hypervisor', 'location': 'Raleigh', 'ip_addresses': ['192.168.99.123'], 'ipv6_addresses': ['fe80::5054:ff:fe24:946e'], 'entitlements': [{ 'derived_entitlement': False, 'name': 'Satellite Tools 6.3', 'amount': 1, 'account_number': None, 'contract_number': None, 'start_date': '2017-12-01 14:50:59 UTC', 'end_date': '2047-11-24 14:50:59 UTC' }, { 'derived_entitlement': True, 'name': 'Employee SKU', 'amount': 1, 'account_number': 1212729, 'contract_number': 10913844, 'start_date': '2016-03-24 04:00:00 UTC', 'end_date': '2022-01-01 04:59:59 UTC' }] } with patch('scanner.satellite.six.host_fields', return_value=fields_return_value) as mock_fields: with patch('scanner.satellite.six.host_subscriptions', return_value=subs_return_value) as mock_subs: details = self.api.host_details(host_id=1, host_name='sys1') self.assertEqual(details, expected) mock_fields.assert_called_once_with(ANY, ANY, ANY, ANY, ANY) mock_subs.assert_called_once_with(ANY, ANY, ANY, ANY) def test_host_details_skip(self): """Test host_details method for already captured data.""" sys_result = SystemInspectionResult( name='sys1', status=SystemInspectionResult.SUCCESS) sys_result.save() self.inspect_result.systems.add(sys_result) self.inspect_result.save() detail = self.api.host_details(1, 'sys1') self.assertEqual(len(self.inspect_result.systems.all()), 1) self.assertEqual(detail, {}) def test_hosts_facts_with_err(self): """Test the hosts_facts method.""" hosts_url = 'https://{sat_host}:{port}/api/v2/hosts' with requests_mock.Mocker() as mocker: url = construct_url(url=hosts_url, sat_host='1.2.3.4') mocker.get(url, status_code=500) with self.assertRaises(SatelliteException): self.api.hosts_facts() def test_hosts_facts(self): """Test the hosts_facts method.""" hosts_url = 'https://{sat_host}:{port}/api/v2/hosts' with requests_mock.Mocker() as mocker: url = construct_url(url=hosts_url, sat_host='1.2.3.4') jsonresult = { 'total': 1, 'subtotal': 1, 'page': 1, 'per_page': 100, 'results': [{ 'id': 10, 'name': 'sys10' }] } # noqa mocker.get(url, status_code=200, json=jsonresult) detail_return_value = {} with patch.object(SatelliteSixV2, 'host_details', return_value=detail_return_value) as mock_detail: self.api.hosts_facts() mock_detail.assert_called_once_with(ANY, ANY)
class InspectTaskRunnerTest(TestCase): """Tests Satellite connect capabilities.""" def setUp(self): """Create test case setup.""" self.cred = Credential( name='cred1', cred_type=Credential.SATELLITE_CRED_TYPE, username='******', password='******') self.cred.save() self.source = Source( name='source1', port=443, hosts='["1.2.3.4"]') self.source.save() self.source.credentials.add(self.cred) self.scan_task = ScanTask(scan_type=ScanTask.SCAN_TYPE_INSPECT, source=self.source, sequence_number=2, start_time=datetime.utcnow()) self.scan_task.save() self.scan_task.update_stats('TEST_SAT.', sys_scanned=0) self.scan_job = ScanJob(scan_type=ScanTask.SCAN_TYPE_CONNECT) self.scan_job.save() self.scan_job.tasks.add(self.scan_task) self.conn_results = JobConnectionResult() self.conn_results.save() self.scan_job.connection_results = self.conn_results self.conn_result = TaskConnectionResult( scan_task=self.scan_task, source=self.source) self.conn_result.save() conn_task = ScanTask(scan_type=ScanTask.SCAN_TYPE_CONNECT, source=self.source, sequence_number=1, start_time=datetime.utcnow()) conn_task.complete() self.scan_task.prerequisites.add(conn_task) self.inspect_results = JobInspectionResult() self.inspect_results.save() self.scan_job.inspection_results = self.inspect_results self.scan_job.save() def tearDown(self): """Cleanup test case setup.""" pass def test_run_failed_prereq(self): """Test the running connect task with no source options.""" self.scan_task.prerequisites.all().delete() conn_task = ScanTask(scan_type=ScanTask.SCAN_TYPE_CONNECT, source=self.source, sequence_number=1) conn_task.status = ScanTask.FAILED conn_task.save() self.scan_task.prerequisites.add(conn_task) task = InspectTaskRunner(self.scan_job, self.scan_task) status = task.run() self.assertEqual(status[1], ScanTask.FAILED) def test_run_no_source_options(self): """Test the running connect task with no source options.""" task = InspectTaskRunner(self.scan_job, self.scan_task) status = task.run() self.assertEqual(status[1], ScanTask.FAILED) def test_run_sat5_bad_status(self): """Test the running connect task for Satellite 5.""" options = SourceOptions( satellite_version=SourceOptions.SATELLITE_VERSION_5) options.save() self.source.options = options self.source.save() task = InspectTaskRunner(self.scan_job, self.scan_task) with patch('scanner.satellite.connect.utils.status', return_value=(401, None)) as mock_sat_status: status = task.run() mock_sat_status.assert_called_once_with(ANY, ANY) self.assertEqual(status[1], ScanTask.FAILED) def test_run_sat6_bad_status(self): """Test the running connect task for Sat 6 with bad status.""" options = SourceOptions( satellite_version=SourceOptions.SATELLITE_VERSION_62) options.save() self.source.options = options self.source.save() task = InspectTaskRunner(self.scan_job, self.scan_task) with patch('scanner.satellite.connect.utils.status', return_value=(401, None)) as mock_sat_status: status = task.run() mock_sat_status.assert_called_once_with(ANY, ANY) self.assertEqual(status[1], ScanTask.FAILED) def test_run_sat6_bad_api_version(self): """Test the running connect task for Sat6 with bad api version.""" options = SourceOptions( satellite_version=SourceOptions.SATELLITE_VERSION_62) options.save() self.source.options = options self.source.save() task = InspectTaskRunner(self.scan_job, self.scan_task) with patch('scanner.satellite.connect.utils.status', return_value=(200, 3)) as mock_sat_status: status = task.run() mock_sat_status.assert_called_once_with(ANY, ANY) self.assertEqual(status[1], ScanTask.FAILED) def test_run_with_conn_err(self): """Test the running connect task with connection error.""" options = SourceOptions( satellite_version=SourceOptions.SATELLITE_VERSION_62) options.save() self.source.options = options self.source.save() task = InspectTaskRunner(self.scan_job, self.scan_task) with patch('scanner.satellite.connect.utils.status', side_effect=mock_conn_exception) as mock_sat_status: status = task.run() mock_sat_status.assert_called_once_with(ANY, ANY) self.assertEqual(status[1], ScanTask.FAILED) def test_run_with_sat_err(self): """Test the running connect task with satellite error.""" options = SourceOptions( satellite_version=SourceOptions.SATELLITE_VERSION_62) options.save() self.source.options = options self.source.save() task = InspectTaskRunner(self.scan_job, self.scan_task) with patch('scanner.satellite.connect.utils.status', side_effect=mock_sat_exception) as mock_sat_status: status = task.run() mock_sat_status.assert_called_once_with(ANY, ANY) self.assertEqual(status[1], ScanTask.FAILED) def test_run_with_timeout(self): """Test the running connect task with timeout error.""" options = SourceOptions( satellite_version=SourceOptions.SATELLITE_VERSION_62) options.save() self.source.options = options self.source.save() task = InspectTaskRunner(self.scan_job, self.scan_task) with patch('scanner.satellite.connect.utils.status', side_effect=mock_timeout_error) as mock_sat_status: status = task.run() mock_sat_status.assert_called_once_with(ANY, ANY) self.assertEqual(status[1], ScanTask.FAILED) def test_run_with_excep(self): """Test the running connect task with general exception.""" options = SourceOptions( satellite_version=SourceOptions.SATELLITE_VERSION_62) options.save() self.source.options = options self.source.save() task = InspectTaskRunner(self.scan_job, self.scan_task) with patch('scanner.satellite.connect.utils.status', side_effect=mock_exception) as mock_sat_status: status = task.run() mock_sat_status.assert_called_once_with(ANY, ANY) self.assertEqual(status[1], ScanTask.FAILED) def test_run_with_sat(self): """Test the running connect task with satellite.""" options = SourceOptions( satellite_version=SourceOptions.SATELLITE_VERSION_62) options.save() self.source.options = options self.source.save() task = InspectTaskRunner(self.scan_job, self.scan_task) with patch('scanner.satellite.connect.utils.status', return_value=(200, 2)) as mock_sat_status: with patch.object(SatelliteSixV2, 'hosts_facts') as mock_facts: status = task.run() mock_sat_status.assert_called_once_with(ANY, ANY) mock_facts.assert_called_once_with() self.assertEqual(status[1], ScanTask.COMPLETED)
class SatelliteFactoryTest(TestCase): """Tests Satellite factory functions.""" def setUp(self): """Create test case setup.""" self.cred = Credential(name='cred1', cred_type=Credential.SATELLITE_CRED_TYPE, username='******', password='******', become_password=None, become_method=None, become_user=None, ssh_keyfile=None) self.cred.save() self.source = Source(name='source1', port=443, hosts='["1.2.3.4"]') self.source.save() self.source.credentials.add(self.cred) self.scan_task = ScanTask(scan_type=ScanTask.SCAN_TYPE_CONNECT, source=self.source, sequence_number=1) self.scan_task.save() self.scan_job = ScanJob(scan_type=ScanTask.SCAN_TYPE_CONNECT) self.scan_job.save() self.scan_job.tasks.add(self.scan_task) self.conn_results = JobConnectionResult() self.conn_results.save() self.scan_job.connection_results = self.conn_results self.scan_job.save() self.conn_result = TaskConnectionResult(scan_task=self.scan_task, source=self.source) self.conn_result.save() def tearDown(self): """Cleanup test case setup.""" pass def test_create_sat_none(self): """Test the method to fail to create a Sat interface.""" satellite_version = None api_version = 1 api = create(satellite_version, api_version, self.scan_task, self.conn_result) self.assertEqual(api, None) def test_create_sat5(self): """Test the method to create a Sat 5 interface.""" satellite_version = SourceOptions.SATELLITE_VERSION_5 api_version = 1 api = create(satellite_version, api_version, self.scan_task, self.conn_result) self.assertEqual(api.__class__, SatelliteFive) def test_create_sat6_v1(self): """Test the method to create a Sat 6 interface.""" satellite_version = SourceOptions.SATELLITE_VERSION_62 api_version = 1 api = create(satellite_version, api_version, self.scan_task, self.conn_result) self.assertEqual(api.__class__, SatelliteSixV1) def test_create_sat6_v2(self): """Test the method to create a Sat 6 interface.""" satellite_version = SourceOptions.SATELLITE_VERSION_62 api_version = 2 api = create(satellite_version, api_version, self.scan_task, self.conn_result) self.assertEqual(api.__class__, SatelliteSixV2) def test_create_sat6_unknown(self): """Test the method to create a Sat 6 interface.""" satellite_version = SourceOptions.SATELLITE_VERSION_62 api_version = 9 api = create(satellite_version, api_version, self.scan_task, self.conn_result) self.assertEqual(api, None)
def setUp(self): """Create test case setup.""" self.cred = Credential( name='cred1', username='******', password='******', ssh_keyfile=None, become_method=None, become_user=None, become_password=None) self.cred.save() hc_serializer = CredentialSerializer(self.cred) self.cred_data = hc_serializer.data self.source = Source( name='source1', port=22, hosts='["1.2.3.4"]') self.source.save() self.source.credentials.add(self.cred) self.host_list = [('1.2.3.4', self.cred_data)] self.connect_scan_task = ScanTask(source=self.source, scan_type=ScanTask.SCAN_TYPE_CONNECT, status=ScanTask.COMPLETED, start_time=datetime.utcnow()) self.connect_scan_task.update_stats( 'TEST NETWORK CONNECT.', sys_failed=0) self.inspect_scan_task = ScanTask(source=self.source, scan_type=ScanTask.SCAN_TYPE_INSPECT, start_time=datetime.utcnow()) self.inspect_scan_task.update_stats( 'TEST NETWORK INSPECT.', sys_failed=0) self.inspect_scan_task.prerequisites.add(self.connect_scan_task) self.inspect_scan_task.save() self.scan_job = ScanJob(scan_type=ScanTask.SCAN_TYPE_INSPECT) self.scan_job.save() self.scan_job.tasks.add(self.connect_scan_task) self.scan_job.tasks.add(self.inspect_scan_task) scan_options = ScanOptions() scan_options.disable_optional_products = {'jboss_eap': False, 'jboss_fuse': False, 'jboss_brms': False} scan_options.save() self.scan_job.options = scan_options self.scan_job.save() self.fact_endpoint = 'http://testserver' + reverse('facts-list') self.conn_results = JobConnectionResult() self.conn_results.save() self.scan_job.connection_results = self.conn_results self.conn_result = TaskConnectionResult( scan_task=self.connect_scan_task, source=self.source) self.conn_result.save() success_sys = SystemConnectionResult( name='1.2.3.4', credential=self.cred, status=SystemConnectionResult.SUCCESS) success_sys.save() failed_sys = SystemConnectionResult( name='1.1.1.2', status=SystemConnectionResult.FAILED) failed_sys.save() self.conn_result.systems.add(success_sys) self.conn_result.systems.add(failed_sys) self.conn_result.save() self.conn_results.results.add(self.conn_result) self.conn_results.save() self.scan_job.connection_results = self.conn_results self.inspect_results = JobInspectionResult() self.inspect_results.save() self.scan_job.inspection_results = self.inspect_results self.scan_job.save()
def test_details(self, start_scan): """Get ScanJob result details by primary key.""" scan_job = ScanJob(scan_type=ScanTask.SCAN_TYPE_INSPECT) scan_job.save() scan_job.sources.add(self.source) # Job in created state self.assertEqual(scan_job.status, ScanTask.CREATED) tasks = scan_job.tasks.all() self.assertEqual(len(tasks), 0) # Queue job to run scan_job.queue() conn_task = scan_job.tasks.first() conn_results = JobConnectionResult() conn_results.save() scan_job.connection_results = conn_results conn_result = TaskConnectionResult(source=conn_task.source, scan_task=conn_task) conn_result.save() conn_results.results.add(conn_result) conn_results.save() sys_result = SystemConnectionResult( name='Foo', credential=self.cred, status=SystemConnectionResult.SUCCESS) sys_result.save() conn_result.systems.add(sys_result) conn_result.save() inspect_task = scan_job.tasks.all()[1] inspect_results = JobInspectionResult() inspect_results.save() scan_job.inspection_results = inspect_results inspect_result = TaskInspectionResult(source=inspect_task.source, scan_task=inspect_task) inspect_result.save() inspect_results.results.add(inspect_result) inspect_results.save() sys_result = SystemInspectionResult( name='Foo', status=SystemConnectionResult.SUCCESS) sys_result.save() fact = RawFact(name='fact_key', value='"fact_value"') fact.save() sys_result.facts.add(fact) sys_result.save() inspect_result.systems.add(sys_result) inspect_result.save() scan_job.save() url = reverse('scanjob-detail', args=(scan_job.id, )) + 'results/' response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) json_response = response.json() self.assertIn('connection_results', json_response) self.assertIn('inspection_results', json_response) self.assertEqual( json_response, { 'connection_results': { 'results': [{ 'source': { 'id': 1, 'name': 'source1', 'source_type': 'network' }, 'systems': [{ 'name': 'Foo', 'credential': { 'id': 1, 'name': 'cred1' }, 'status': 'success' }] }] }, 'inspection_results': { 'results': [{ 'source': { 'id': 1, 'name': 'source1', 'source_type': 'network' }, 'systems': [{ 'name': 'Foo', 'status': 'success', 'facts': [{ 'name': 'fact_key', 'value': 'fact_value' }] }] }] } })
class SatelliteFiveTest(TestCase): """Tests Satellite 5 functions.""" def setUp(self): """Create test case setup.""" self.cred = Credential( name='cred1', cred_type=Credential.SATELLITE_CRED_TYPE, username='******', password='******', become_password=None, become_method=None, become_user=None, ssh_keyfile=None) self.cred.save() self.source = Source( name='source1', port=443, hosts='["1.2.3.4"]') self.source.save() self.source.credentials.add(self.cred) self.scan_task = ScanTask(scan_type=ScanTask.SCAN_TYPE_CONNECT, source=self.source, sequence_number=1, start_time=datetime.utcnow()) self.scan_task.save() self.scan_task.update_stats('TEST_SAT.', sys_scanned=0) self.scan_job = ScanJob(scan_type=ScanTask.SCAN_TYPE_CONNECT) self.scan_job.save() self.scan_job.tasks.add(self.scan_task) self.conn_results = JobConnectionResult() self.conn_results.save() self.scan_job.connection_results = self.conn_results self.scan_job.save() self.conn_result = TaskConnectionResult( scan_task=self.scan_task, source=self.source) self.conn_result.save() self.inspect_result = TaskInspectionResult(scan_task=self.scan_task, source=self.source) self.inspect_result.save() self.api = SatelliteFive(self.scan_task, self.conn_result, self.inspect_result) def tearDown(self): """Cleanup test case setup.""" pass @patch('xmlrpc.client.ServerProxy') def test_host_count(self, mock_serverproxy): """Test the method host_count.""" client = mock_serverproxy.return_value client.auth.login.return_value = 'key' client.auth.logout.return_value = 'key' client.system.list_user_systems.return_value = ['sys1', 'sys2', 'sys3'] systems_count = self.api.host_count() self.assertEqual(systems_count, 3) @patch('xmlrpc.client.ServerProxy') def test_host_count_with_err(self, mock_serverproxy): """Test the method host_count with error.""" client = mock_serverproxy.return_value client.auth.login.side_effect = mock_xml_fault with self.assertRaises(SatelliteException): self.api.host_count() @patch('xmlrpc.client.ServerProxy') def test_hosts(self, mock_serverproxy): """Test the method hosts.""" systems = [{'name': 'sys1'}, {'name': 'sys2'}, {'name': 'sys3'}] client = mock_serverproxy.return_value client.auth.login.return_value = 'key' client.auth.logout.return_value = 'key' client.system.list_user_systems.return_value = systems systems_count = self.api.host_count() hosts = self.api.hosts() self.assertEqual(systems_count, 3) self.assertEqual(len(hosts), 3) self.assertEqual(hosts, ['sys1', 'sys2', 'sys3']) @patch('xmlrpc.client.ServerProxy') def test_hosts_with_err(self, mock_serverproxy): """Test the method hosts with error.""" client = mock_serverproxy.return_value client.auth.login.side_effect = mock_xml_fault with self.assertRaises(SatelliteException): self.api.hosts() @patch('xmlrpc.client.ServerProxy') def test_host_details_virt_host(self, mock_serverproxy): """Test host_details method with mock data for virt host.""" expected = {'uuid': 1, 'name': 'sys1', 'hostname': 'sys1_hostname', 'last_checkin_time': '', 'registration_time': 'datetime', 'architecture': 'x86', 'kernel_version': 'kernel', 'cores': 2, 'num_sockets': 2, 'os_release': '7server', 'entitlements': [{'name': 'ent1'}], 'ip_addresses': ['1.2.3.4'], 'mac_addresses': ['1:a:2:b:3:c'], 'virtual': 'hypervisor', 'num_virtual_guests': 3, 'is_virtualized': False} client = mock_serverproxy.return_value client.auth.login.return_value = 'key' client.auth.logout.return_value = 'key' client.system.get_uuid.return_value = '' cpu = {'arch': 'x86', 'count': 2, 'socket_count': 2} client.system.get_cpu.return_value = cpu system_details = {'hostname': 'sys1_hostname', 'release': '7server'} client.system.get_details.return_value = system_details client.system.get_running_kernel.return_value = 'kernel' client.system.get_entitlements.return_value = ['ent1'] net_devices = [{'interface': 'eth0', 'ip': '1.2.3.4', 'hardware_address': '1:a:2:b:3:c'}] client.system.get_network_devices.return_value = net_devices client.system.get_registration_date.return_value = 'datetime' virt = {1: {'id': 1, 'num_virtual_guests': 3}} details = self.api.host_details(host_id=1, host_name='sys1', last_checkin='', virtual_hosts=virt, virtual_guests={}) self.assertEqual(details, expected) @patch('xmlrpc.client.ServerProxy') def test_host_details_virt_guest(self, mock_serverproxy): """Test host_details method with mock data for virt guest.""" expected = {'uuid': 1, 'name': 'sys1', 'hostname': 'sys1_hostname', 'last_checkin_time': '', 'registration_time': 'datetime', 'architecture': 'x86', 'kernel_version': 'kernel', 'cores': 2, 'num_sockets': 2, 'os_release': '7server', 'entitlements': [{'name': 'ent1'}], 'ip_addresses': ['1.2.3.4'], 'mac_addresses': ['1:a:2:b:3:c'], 'is_virtualized': True, 'virtual_host': 2, 'virtual_host_name': 'sys2'} client = mock_serverproxy.return_value client.auth.login.return_value = 'key' client.auth.logout.return_value = 'key' client.system.get_uuid.return_value = '' cpu = {'arch': 'x86', 'count': 2, 'socket_count': 2} client.system.get_cpu.return_value = cpu system_details = {'hostname': 'sys1_hostname', 'release': '7server'} client.system.get_details.return_value = system_details client.system.get_running_kernel.return_value = 'kernel' client.system.get_entitlements.return_value = ['ent1'] net_devices = [{'interface': 'eth0', 'ip': '1.2.3.4', 'hardware_address': '1:a:2:b:3:c'}] client.system.get_network_devices.return_value = net_devices client.system.get_registration_date.return_value = 'datetime' virt = {2: {'uuid': 2, 'name': 'sys2', 'num_virtual_guests': 3}} details = self.api.host_details(host_id=1, host_name='sys1', last_checkin='', virtual_hosts=virt, virtual_guests={1: 2}) self.assertEqual(details, expected) def test_host_details_skip(self): """Test host_details method for already captured data.""" sys_result = SystemInspectionResult( name='sys1', status=SystemInspectionResult.SUCCESS) sys_result.save() self.inspect_result.systems.add(sys_result) self.inspect_result.save() virt = {2: {'uuid': 2, 'name': 'sys2', 'num_virtual_guests': 3}} detail = self.api.host_details(host_id=1, host_name='sys1', last_checkin='', virtual_hosts=virt, virtual_guests={1: 2}) self.assertEqual(len(self.inspect_result.systems.all()), 1) self.assertEqual(detail, {}) @patch('xmlrpc.client.ServerProxy') def test_host_details_with_err(self, mock_serverproxy): """Test the host details with an error.""" client = mock_serverproxy.return_value client.auth.login.side_effect = mock_xml_fault with self.assertRaises(SatelliteException): virt = {2: {'uuid': 2, 'name': 'sys2', 'num_virtual_guests': 3}} self.api.host_details(host_id=1, host_name='sys1', last_checkin='', virtual_hosts=virt, virtual_guests={1: 2}) @patch('xmlrpc.client.ServerProxy') def test_virtual_guests_with_err(self, mock_serverproxy): """Test the virtual_guests method with an error.""" client = mock_serverproxy.return_value client.auth.login.side_effect = mock_xml_fault with self.assertRaises(SatelliteException): self.api.virtual_guests(1) @patch('xmlrpc.client.ServerProxy') def test_virtual_guests(self, mock_serverproxy): """Test the virtual_guests method with an error.""" client = mock_serverproxy.return_value client.auth.login.return_value = 'key' client.auth.logout.return_value = 'key' guests = [{'id': 2}] client.system.list_virtual_guests.return_value = guests virt_guests = self.api.virtual_guests(1) self.assertEqual(virt_guests, ({2: 1}, 1)) @patch('xmlrpc.client.ServerProxy') def test_virtual_hosts_with_err(self, mock_serverproxy): """Test the virtual_hosts method with an error.""" client = mock_serverproxy.return_value client.auth.login.side_effect = mock_xml_fault with self.assertRaises(SatelliteException): self.api.virtual_hosts() @patch('xmlrpc.client.ServerProxy') def test_virtual_hosts(self, mock_serverproxy): """Test the virtual_hosts method with an error.""" client = mock_serverproxy.return_value client.auth.login.return_value = 'key' client.auth.logout.return_value = 'key' guests = [{'id': 2}] client.system.list_virtual_guests.return_value = guests hosts = [{'id': 1, 'name': 'host1'}] client.system.list_virtual_hosts.return_value = hosts client.system.get_uuid.return_value = '' virtual_hosts, virtual_guests = self.api.virtual_hosts() virt_host = {1: {'id': 1, 'name': 'host1', 'uuid': 1, 'num_virtual_guests': 1}} virt_guest = {2: 1} self.assertEqual(virtual_hosts, virt_host) self.assertEqual(virtual_guests, virt_guest) @patch('xmlrpc.client.ServerProxy') def test_hosts_facts_with_err(self, mock_serverproxy): """Test the hosts_facts method with an error.""" client = mock_serverproxy.return_value client.auth.login.side_effect = mock_xml_fault with self.assertRaises(SatelliteException): self.api.hosts_facts() @patch('xmlrpc.client.ServerProxy') def test_hosts_facts(self, mock_serverproxy): """Test the hosts_facts method.""" detail_return_value = {} systems = [{'id': 1, 'name': 'sys1'}] client = mock_serverproxy.return_value client.auth.login.return_value = 'key' client.auth.logout.return_value = 'key' client.system.list_user_systems.return_value = systems hosts_return_value = ({}, {}) with patch.object(SatelliteFive, 'virtual_hosts', return_value=hosts_return_value) as mock_hosts: with patch.object(SatelliteFive, 'host_details', return_value=detail_return_value) as mock_detail: self.api.hosts_facts() mock_hosts.assert_called_once_with() mock_detail.assert_called_once_with(ANY, ANY, ANY, ANY, ANY)