def test_instance_info(self): inst_info = vm.InstanceInfo(self.apt, 'inst') self.get_pvm_uuid.assert_called_once_with('inst') # Test the static properties self.assertEqual(inst_info.id, self.get_pvm_uuid.return_value) # Check that we raise an exception if the instance is gone. self.apt.read.side_effect = pvm_exc.HttpError( mock.MagicMock(status=404)) self.assertRaises(exception.InstanceNotFound, inst_info.__getattribute__, 'state') # Reset the test inst_info inst_info = vm.InstanceInfo(self.apt, 'inst') class FakeResp2(object): def __init__(self, body): self.body = '"%s"' % body resp = FakeResp2('running') def return_resp(*args, **kwds): return resp self.apt.read.side_effect = return_resp self.assertEqual(inst_info.state, power_state.RUNNING) # Check the __eq__ method self.get_pvm_uuid.return_value = 'pvm-uuid1' inst_info1 = vm.InstanceInfo(self.apt, 'inst') inst_info2 = vm.InstanceInfo(self.apt, 'inst') self.assertEqual(inst_info1, inst_info2) self.get_pvm_uuid.return_value = 'pvm-uuid2' inst_info2 = vm.InstanceInfo(self.apt, 'inst2') self.assertNotEqual(inst_info1, inst_info2)
def test_plug_raises(self, mock_vif_drv): """HttpError is converted to VirtualInterfacePlugException.""" vif_drv = mock.Mock(plug=mock.Mock(side_effect=pvm_ex.HttpError( resp=mock.Mock(status='status', reqmethod='method', reqpath='path', reason='reason')))) mock_vif_drv.return_value = vif_drv mock_slot_mgr = mock.Mock() mock_vif = {'address': 'vifaddr'} self.assertRaises(exception.VirtualInterfacePlugException, vif.plug, 'adap', 'huuid', 'inst', mock_vif, mock_slot_mgr, new_vif='new_vif') mock_vif_drv.assert_called_once_with('adap', 'huuid', 'inst', mock_vif) vif_drv.plug.assert_called_once_with( mock_vif, mock_slot_mgr.build_map.get_vnet_slot.return_value, new_vif='new_vif') mock_slot_mgr.build_map.get_vnet_slot.assert_called_once_with( 'vifaddr')
def test_crt_lpar(self, mock_vld, mock_vmbldr): self.inst.flavor.extra_specs = {'powervm:dedicated_proc': 'true'} mock_bldr = mock.Mock(spec=lpar_bld.LPARBuilder) mock_vmbldr.return_value.lpar_builder.return_value = mock_bldr mock_pend_lpar = mock.create_autospec(pvm_lpar.LPAR, instance=True) mock_bldr.build.return_value = mock_pend_lpar vm.create_lpar(self.apt, 'host', self.inst) mock_vmbldr.assert_called_once_with('host', self.apt) mock_vmbldr.return_value.lpar_builder.assert_called_once_with( self.inst) mock_bldr.build.assert_called_once_with() mock_vld.assert_called_once_with(mock_pend_lpar, 'host') mock_vld.return_value.validate_all.assert_called_once_with() mock_pend_lpar.create.assert_called_once_with(parent='host') # Test to verify the LPAR Creation with invalid name specification mock_vmbldr.side_effect = lpar_bld.LPARBuilderException("Invalid Name") self.assertRaises(exception.BuildAbortException, vm.create_lpar, self.apt, 'host', self.inst) # HttpError mock_vmbldr.side_effect = pvm_exc.HttpError(mock.Mock()) self.assertRaises(exception.PowerVMAPIFailed, vm.create_lpar, self.apt, 'host', self.inst)
def test_add_auth_key(self): # Test adding a key ('4') to an existing list ('1', '2', '3') self.cons_w.ssh_authorized_keys = ('1', '2', '3') mc_task.add_authorized_key(mock.Mock(), '4') self.assertEqual(['1', '2', '3', '4'], self.cons_w.ssh_authorized_keys) self.cons_w.update.assert_called_once_with() # Test we don't call update when not needed. self.cons_w.reset_mock() mc_task.add_authorized_key(mock.Mock(), '2') self.assertEqual(0, self.cons_w.update.called) # Test the transaction retry self.cons_w.reset_mock() resp = mock.Mock(status=const.HTTPStatus.ETAG_MISMATCH) self.cons_w.update.side_effect = exc.HttpError(resp) # When the transaction decorator refreshes the mgmt console wrapper # then we know it's retrying so just raise an exception and bail self.cons_w.refresh.side_effect = ValueError() self.assertRaises(ValueError, mc_task.add_authorized_key, mock.Mock(), '5') # Ensure it really was refresh that caused the exception self.assertEqual(1, self.cons_w.refresh.call_count) # And that our update was called self.assertEqual(1, self.cons_w.update.call_count)
def test_instance_info(self): inst_info = vm.InstanceInfo(self.apt, 'inst_name', '1234') # Test the static properties self.assertEqual(inst_info.id, '1234') self.assertEqual(inst_info.cpu_time_ns, 0) # Check that we raise an exception if the instance is gone. self.apt.read.side_effect = pvm_exc.HttpError( mock.MagicMock(status=404)) self.assertRaises(exception.InstanceNotFound, inst_info.__getattribute__, 'state') # Reset the test inst_info inst_info = vm.InstanceInfo(self.apt, 'inst_name', '1234') class FakeResp2(object): def __init__(self, body): self.body = '"%s"' % body resp = FakeResp2('running') def return_resp(*args, **kwds): return resp self.apt.read.side_effect = return_resp self.assertEqual(inst_info.state, power_state.RUNNING) # Check the __eq__ method inst_info1 = vm.InstanceInfo(self.apt, 'inst_name', '1234') inst_info2 = vm.InstanceInfo(self.apt, 'inst_name', '1234') self.assertEqual(inst_info1, inst_info2) inst_info2 = vm.InstanceInfo(self.apt, 'name', '4321') self.assertNotEqual(inst_info1, inst_info2)
def retry_twice(wrapper, tracker, logger): # Force a couple of retries tracker.counter += 1 logger.log('update %d' % tracker.counter) if tracker.counter < 3: raise ex.HttpError(mock.Mock(status=c.HTTPStatus.ETAG_MISMATCH)) return wrapper
def func_except_method(x, y): global called_count called_count += 1 resp = adpt.Response('reqmethod', 'reqpath', c.HTTPStatus.ETAG_MISMATCH, 'reason', 'headers', None) http_exc = pvm_exc.HttpError(resp) raise http_exc
def test_update_cna_pvid(self): """Validates the update_cna_pvid method.""" def build_mock(): # Need to rebuild. Since it returns itself a standard reset will # recurse infinitely. cna = mock.MagicMock() cna.refresh.return_value = cna return cna self._mock_feed(self.vios_feed_resp) # Attempt happy path cna = build_mock() utils.update_cna_pvid(cna, 5) self.assertEqual(5, cna.pvid) self.assertEqual(1, cna.update.call_count) # Raise an error 3 times and make sure it eventually re-raises the root # etag exception cna = build_mock() err_resp = mock.MagicMock() err_resp.status = pvm_const.HTTPStatus.ETAG_MISMATCH error = pvm_exc.HttpError(err_resp) cna.update.side_effect = [error, error, error] self.assertRaises(pvm_exc.HttpError, utils.update_cna_pvid, cna, 5) self.assertEqual(3, cna.update.call_count) self.assertEqual(2, cna.refresh.call_count) # Raise an error 2 times and then eventually works cna = build_mock() cna.update.side_effect = [error, error, None] utils.update_cna_pvid(cna, 5) self.assertEqual(3, cna.update.call_count) self.assertEqual(2, cna.refresh.call_count) # Immediate re-raise of different type of exception cna = build_mock() err_resp.status = pvm_const.HTTPStatus.UNAUTHORIZED cna.update.side_effect = pvm_exc.HttpError(err_resp) self.assertRaises(pvm_exc.HttpError, utils.update_cna_pvid, cna, 5) self.assertEqual(1, cna.update.call_count) self.assertEqual(0, cna.refresh.call_count)
def test_crt_lpar(self, mock_vld_all, mock_bld, mock_stdz, mock_ibmi): instance = objects.Instance(**powervm.TEST_INSTANCE) flavor = instance.get_flavor() flavor.extra_specs = {'powervm:dedicated_proc': 'true'} host_wrapper = mock.Mock() lparw = pvm_lpar.LPAR.wrap(self.resp.feed.entries[0]) mock_bld.return_value = lparw self.apt.create.return_value = lparw.entry vm.crt_lpar(self.apt, host_wrapper, instance, flavor, nvram='data') self.apt.create.assert_called_once_with( lparw, host_wrapper.schema_type, child_type='LogicalPartition', root_id=host_wrapper.uuid, service='uom', timeout=-1) mock_stdz.assert_called_once_with(host_wrapper, uncapped_weight=64, proc_units_factor=0.1) self.assertEqual(lparw.nvram, 'data') self.assertTrue(mock_vld_all.called) # Test srr and slot_mgr self.apt.reset_mock() mock_vld_all.reset_mock() mock_stdz.reset_mock() flavor.extra_specs = {'powervm:srr_capability': 'true'} self.apt.create.return_value = lparw.entry mock_slot_mgr = mock.Mock(build_map=mock.Mock( get_max_vslots=mock.Mock(return_value=123))) vm.crt_lpar(self.apt, host_wrapper, instance, flavor, slot_mgr=mock_slot_mgr) self.assertTrue(self.apt.create.called) self.assertTrue(mock_vld_all.called) self.assertTrue(lparw.srr_enabled) mock_stdz.assert_called_once_with(host_wrapper, uncapped_weight=64, proc_units_factor=0.1, max_slots=123) # The save is called with the LPAR's actual value, which in this mock # setup comes from lparw mock_slot_mgr.register_max_vslots.assert_called_with( lparw.io_config.max_virtual_slots) # Test to verify the LPAR Creation with invalid name specification mock_bld.side_effect = lpar_bld.LPARBuilderException("Invalid Name") host_wrapper = mock.Mock() self.assertRaises(exception.BuildAbortException, vm.crt_lpar, self.apt, host_wrapper, instance, flavor) resp = mock.Mock(status=202, method='fake', path='/dev/', reason='Failure') mock_bld.side_effect = pvm_exc.HttpError(resp) try: vm.crt_lpar(self.apt, host_wrapper, instance, flavor) except nvex.PowerVMAPIFailed as e: self.assertEqual(e.kwargs['inst_name'], instance.name) self.assertEqual(e.kwargs['reason'], mock_bld.side_effect) flavor.extra_specs = {'powervm:BADATTR': 'true'} host_wrapper = mock.Mock() self.assertRaises(exception.InvalidAttribute, vm.crt_lpar, self.apt, host_wrapper, instance, flavor)
def test_store_with_not_found_exc(self, mock_get_inst, mock_log): mock_resp = mock.Mock() mock_resp.status = 404 mock_resp.reqpath = ( '/rest/api/uom/ManagedSystem/c5d782c7-44e4-3086-ad15-' 'b16fb039d63b/LogicalPartition/1B5FB633-16D1-4E10-A14' '5-E6FB905161A3?group=None') mock_get_inst.side_effect = pvm_exc.HttpError(mock_resp) mgr = manager.NvramManager(self.fake_store, mock.Mock(), mock.Mock()) mgr.store(powervm.TEST_INST1) mock_log.assert_not_called()
def test_store_with_exception(self, mock_get_inst, mock_log): mock_resp = mock.Mock() mock_resp.status = 410 mock_resp.reqpath = ( '/rest/api/uom/ManagedSystem/c5d782c7-44e4-3086-ad15-' 'b16fb039d63b/LogicalPartition/1B5FB633-16D1-4E10-A14' '5-E6FB905161A3?group=None') mock_get_inst.side_effect = pvm_exc.HttpError(mock_resp) mgr = manager.NvramManager(self.fake_store, mock.Mock(), mock.Mock()) mgr.store(powervm.TEST_INST1) mock_log.assert_called_once_with(u'Unable to store the NVRAM for ' u'instance: %s', powervm.TEST_INST1.name)
def test_plug_raises(self, mock_vif_drv): """HttpError is converted to VirtualInterfacePlugException.""" vif_drv = mock.Mock(plug=mock.Mock(side_effect=pvm_ex.HttpError( resp=mock.Mock()))) mock_vif_drv.return_value = vif_drv mock_vif = {'address': 'vifaddr'} self.assertRaises(exception.VirtualInterfacePlugException, vif.plug, 'adap', 'inst', mock_vif, new_vif='new_vif') mock_vif_drv.assert_called_once_with('adap', 'inst', mock_vif) vif_drv.plug.assert_called_once_with(mock_vif, new_vif='new_vif')
def test_get_vm_qp(self, mock_loads): self.apt.helpers = ['helper1', pvm_log.log_helper, 'helper3'] # Defaults self.assertEqual(mock_loads.return_value, vm.get_vm_qp(self.apt, 'lpar_uuid')) self.apt.read.assert_called_once_with('LogicalPartition', root_id='lpar_uuid', suffix_type='quick', suffix_parm=None) mock_loads.assert_called_once_with(self.apt.read.return_value.body) self.apt.read.reset_mock() mock_loads.reset_mock() # Specific qprop, no logging errors self.assertEqual( mock_loads.return_value, vm.get_vm_qp(self.apt, 'lpar_uuid', qprop='Prop', log_errors=False)) self.apt.read.assert_called_once_with('LogicalPartition', root_id='lpar_uuid', suffix_type='quick', suffix_parm='Prop', helpers=['helper1', 'helper3']) resp = mock.MagicMock() resp.status = 404 self.apt.read.side_effect = pvm_exc.HttpError(resp) self.assertRaises(exception.InstanceNotFound, vm.get_vm_qp, self.apt, 'lpar_uuid', log_errors=False) self.apt.read.side_effect = pvm_exc.Error("message", response=None) self.assertRaises(pvm_exc.Error, vm.get_vm_qp, self.apt, 'lpar_uuid', log_errors=False) resp.status = 500 self.apt.read.side_effect = pvm_exc.Error("message", response=resp) self.assertRaises(pvm_exc.Error, vm.get_vm_qp, self.apt, 'lpar_uuid', log_errors=False)
def test_get_vnc_console(self, mock_vterm): # Success mock_vterm.return_value = '10' resp = self.drv.get_vnc_console(mock.ANY, self.inst) self.assertEqual('127.0.0.1', resp.host) self.assertEqual('10', resp.port) self.assertEqual('uuid', resp.internal_access_path) mock_vterm.assert_called_once_with( mock.ANY, 'uuid', mock.ANY, vnc_path='uuid') # VNC failure - exception is raised directly mock_vterm.side_effect = pvm_exc.VNCBasedTerminalFailedToOpen(err='xx') self.assertRaises(pvm_exc.VNCBasedTerminalFailedToOpen, self.drv.get_vnc_console, mock.ANY, self.inst) # 404 mock_vterm.side_effect = pvm_exc.HttpError(mock.Mock(status=404)) self.assertRaises(exception.InstanceNotFound, self.drv.get_vnc_console, mock.ANY, self.inst)
def _powervm_update(parm): global called_count called_count += 1 if called_count == 1: # etag mismatch resp = adpt.Response('reqmethod', 'reqpath', c.HTTPStatus.ETAG_MISMATCH, 'reason', 'headers') http_exc = pvm_exc.HttpError(resp) raise http_exc if called_count == 2: # Pretend we got a valid response, but the VIOS is busy return 'VIOS IS BUSY' if called_count == 3: # Pretend we got a good response return parm return None
def raiseRetryException(): """Used for other tests wishing to raise an exception to a force retry.""" resp = adpt.Response('reqmethod', 'reqpath', c.HTTPStatus.ETAG_MISMATCH, 'reason', 'headers') http_exc = pvm_exc.HttpError(resp) raise http_exc
def test_dlt_lpar(self, mock_vterm): """Performs a delete LPAR test.""" vm.dlt_lpar(self.apt, '12345') self.assertEqual(1, self.apt.delete.call_count) self.assertEqual(1, mock_vterm.call_count) # Test Failure Path # build a mock response body with the expected HSCL msg resp = mock.Mock() resp.body = 'error msg: HSCL151B more text' self.apt.delete.side_effect = pvm_exc.Error( 'Mock Error Message', response=resp) # Reset counters self.apt.reset_mock() mock_vterm.reset_mock() self.assertRaises(pvm_exc.Error, vm.dlt_lpar, self.apt, '12345') self.assertEqual(1, mock_vterm.call_count) self.assertEqual(1, self.apt.delete.call_count) # Test HttpError 404 self.apt.reset_mock() mock_vterm.reset_mock() resp.status = 404 self.apt.delete.side_effect = pvm_exc.HttpError(resp=resp) vm.dlt_lpar(self.apt, '54321') self.assertEqual(1, mock_vterm.call_count) self.assertEqual(1, self.apt.delete.call_count) # Test Other HttpError self.apt.reset_mock() mock_vterm.reset_mock() resp.status = 111 self.apt.delete.side_effect = pvm_exc.HttpError(resp=resp) self.assertRaises(pvm_exc.HttpError, vm.dlt_lpar, self.apt, '11111') self.assertEqual(1, mock_vterm.call_count) self.assertEqual(1, self.apt.delete.call_count) # Test HttpError 404 closing vterm self.apt.reset_mock() mock_vterm.reset_mock() resp.status = 404 mock_vterm.side_effect = pvm_exc.HttpError(resp=resp) vm.dlt_lpar(self.apt, '55555') self.assertEqual(1, mock_vterm.call_count) self.assertEqual(0, self.apt.delete.call_count) # Test Other HttpError closing vterm self.apt.reset_mock() mock_vterm.reset_mock() resp.status = 111 mock_vterm.side_effect = pvm_exc.HttpError(resp=resp) self.assertRaises(pvm_exc.HttpError, vm.dlt_lpar, self.apt, '33333') self.assertEqual(1, mock_vterm.call_count) self.assertEqual(0, self.apt.delete.call_count)
def test_dlt_lpar(self, mock_vterm): """Performs a delete LPAR test.""" vm.delete_lpar(self.apt, 'inst') self.get_pvm_uuid.assert_called_once_with('inst') self.apt.delete.assert_called_once_with( pvm_lpar.LPAR.schema_type, root_id=self.get_pvm_uuid.return_value) self.assertEqual(1, mock_vterm.call_count) # Test Failure Path # build a mock response body with the expected HSCL msg resp = mock.Mock() resp.body = 'error msg: HSCL151B more text' self.apt.delete.side_effect = pvm_exc.Error('Mock Error Message', response=resp) # Reset counters self.apt.reset_mock() mock_vterm.reset_mock() self.assertRaises(pvm_exc.Error, vm.delete_lpar, self.apt, 'inst') self.assertEqual(1, mock_vterm.call_count) self.assertEqual(1, self.apt.delete.call_count) self.apt.reset_mock() mock_vterm.reset_mock() # Test HttpError 404 resp.status = 404 self.apt.delete.side_effect = pvm_exc.HttpError(resp=resp) vm.delete_lpar(self.apt, 'inst') self.assertEqual(1, mock_vterm.call_count) self.assertEqual(1, self.apt.delete.call_count) self.apt.reset_mock() mock_vterm.reset_mock() # Test Other HttpError resp.status = 111 self.apt.delete.side_effect = pvm_exc.HttpError(resp=resp) self.assertRaises(pvm_exc.HttpError, vm.delete_lpar, self.apt, 'inst') self.assertEqual(1, mock_vterm.call_count) self.assertEqual(1, self.apt.delete.call_count) self.apt.reset_mock() mock_vterm.reset_mock() # Test HttpError 404 closing vterm resp.status = 404 mock_vterm.side_effect = pvm_exc.HttpError(resp=resp) vm.delete_lpar(self.apt, 'inst') self.assertEqual(1, mock_vterm.call_count) self.assertEqual(0, self.apt.delete.call_count) self.apt.reset_mock() mock_vterm.reset_mock() # Test Other HttpError closing vterm resp.status = 111 mock_vterm.side_effect = pvm_exc.HttpError(resp=resp) self.assertRaises(pvm_exc.HttpError, vm.delete_lpar, self.apt, 'inst') self.assertEqual(1, mock_vterm.call_count) self.assertEqual(0, self.apt.delete.call_count)
def test_get_vm_qp(self): def adapter_read(root_type, root_id=None, suffix_type=None, suffix_parm=None, helpers=None): json_str = (u'{"IsVirtualServiceAttentionLEDOn":"false","Migration' u'State":"Not_Migrating","CurrentProcessingUnits":0.1,' u'"ProgressState":null,"PartitionType":"AIX/Linux","Pa' u'rtitionID":1,"AllocatedVirtualProcessors":1,"Partiti' u'onState":"not activated","RemoteRestartState":"Inval' u'id","OperatingSystemVersion":"Unknown","AssociatedMa' u'nagedSystem":"https://9.1.2.3:12443/rest/api/uom/Man' u'agedSystem/98498bed-c78a-3a4f-b90a-4b715418fcb6","RM' u'CState":"inactive","PowerManagementMode":null,"Parti' u'tionName":"lpar-1-06674231-lpar","HasDedicatedProces' u'sors":"false","ResourceMonitoringIPAddress":null,"Re' u'ferenceCode":"00000000","CurrentProcessors":null,"Cu' u'rrentMemory":512,"SharingMode":"uncapped"}') self.assertEqual('LogicalPartition', root_type) self.assertEqual('lpar_uuid', root_id) self.assertEqual('quick', suffix_type) resp = mock.MagicMock() if suffix_parm is None: resp.body = json_str elif suffix_parm == 'PartitionID': resp.body = '1' elif suffix_parm == 'CurrentProcessingUnits': resp.body = '0.1' elif suffix_parm == 'AssociatedManagedSystem': # The double quotes are important resp.body = ('"https://9.1.2.3:12443/rest/api/uom/ManagedSyste' 'm/98498bed-c78a-3a4f-b90a-4b715418fcb6"') else: self.fail('Unhandled quick property key %s' % suffix_parm) return resp def adpt_read_no_log(*args, **kwds): helpers = kwds['helpers'] try: helpers.index(pvm_log.log_helper) except ValueError: # Successful path since the logger shouldn't be there return adapter_read(*args, **kwds) self.fail('Log helper was found when it should not be') ms_href = ('https://9.1.2.3:12443/rest/api/uom/ManagedSystem/98498bed-' 'c78a-3a4f-b90a-4b715418fcb6') self.apt.read.side_effect = adapter_read self.assertEqual(1, vm.get_vm_id(self.apt, 'lpar_uuid')) self.assertEqual(ms_href, vm.get_vm_qp(self.apt, 'lpar_uuid', 'AssociatedManagedSystem')) self.apt.read.side_effect = adpt_read_no_log self.assertEqual(0.1, vm.get_vm_qp(self.apt, 'lpar_uuid', 'CurrentProcessingUnits', log_errors=False)) qp_dict = vm.get_vm_qp(self.apt, 'lpar_uuid', log_errors=False) self.assertEqual(ms_href, qp_dict['AssociatedManagedSystem']) self.assertEqual(1, qp_dict['PartitionID']) self.assertEqual(0.1, qp_dict['CurrentProcessingUnits']) resp = mock.MagicMock() resp.status = 404 self.apt.read.side_effect = pvm_exc.HttpError(resp) self.assertRaises(exception.InstanceNotFound, vm.get_vm_qp, self.apt, 'lpar_uuid', log_errors=False) self.apt.read.side_effect = pvm_exc.Error("message", response=None) self.assertRaises(pvm_exc.Error, vm.get_vm_qp, self.apt, 'lpar_uuid', log_errors=False) resp.status = 500 self.apt.read.side_effect = pvm_exc.Error("message", response=resp) self.assertRaises(pvm_exc.Error, vm.get_vm_qp, self.apt, 'lpar_uuid', log_errors=False)
def test_log_helper(self, mock_log): helpers = log_hlp.log_helper response = adp.Response('GET', '/some/path', 200, 'OK', ['headers']) self.sess.request.return_value = response adpt = adp.Adapter(self.sess, helpers=helpers) # Test that we get the response we expect passed back unharmed self.assertEqual(response, adpt._request('method', 'path', body='the body')) # Should be 1 req/resp in the log now, which would be 4 info messages mock_log.reset_mock() log_hlp._write_thread_log() self.assertEqual(mock_log.info.call_count, 4) # Should be empty now mock_log.reset_mock() log_hlp._write_thread_log() self.assertEqual(mock_log.info.call_count, 0) # Test that we limit the number of entries mock_log.reset_mock() for x in range(0, 30): adpt._request('method1', 'path', body='the body %d' % x) log_hlp._write_thread_log() # Each req/resp pair is 2 log entries but headers and body # are logged separately, so with maxlogs=3, it's 3 * 2 * 2. self.assertEqual(mock_log.info.call_count, (3 * 2 * 2)) mock_log.reset_mock() # Add a few records adpt._request('method1', 'path', body='the body') # Ensure a 412 (special case) doesn't dump, but does raise self.sess.request.side_effect = pvmex.HttpError( mock.Mock(status=c.HTTPStatus.ETAG_MISMATCH)) self.assertRaises(pvmex.HttpError, adpt._request, 'method2', 'path', body='the body') self.assertEqual(0, mock_log.info.call_count) # Ensure a non-412 exception dumps the logs and is then raised self.sess.request.side_effect = pvmex.HttpError( mock.Mock(status=c.HTTPStatus.INTERNAL_ERROR)) mock_log.reset_mock() self.assertRaises(pvmex.Error, adpt._request, 'method', 'path', body='the body') # Should be 10 entries. 4 * 2 req/resp, 2 for this req. self.assertEqual(mock_log.info.call_count, 10) # Ensure the log storage is initialized correctly, and we can change # the default value hlp_size = functools.partial(log_hlp.log_helper, max_logs=12) adpt1 = adp.Adapter(self.sess, helpers=hlp_size) self.sess.request.side_effect = None with mock.patch('pypowervm.helpers.log_helper.' '_init_thread_stg') as mock_init: adpt1._request('method1', 'path', body='the body') # Should be called with 24 since 12 * 2 entries. self.assertEqual(mock_init.call_args_list, [mock.call(max_entries=24)])
def test_dlt_lpar(self, mock_vterm, mock_pvm_uuid): """Performs a delete LPAR test.""" mock_pvm_uuid.return_value = 'pvm_uuid' vm.delete_lpar(self.apt, 'inst') mock_pvm_uuid.assert_called_once_with('inst') mock_vterm.assert_called_once_with(self.apt, 'pvm_uuid') self.apt.delete.assert_called_once_with('LogicalPartition', root_id='pvm_uuid') # Test Failure Path # build a mock response body with the expected HSCL msg resp = mock.Mock(body='error msg: HSCL151B more text') self.apt.delete.side_effect = pvm_exc.Error('Mock Error Message', response=resp) # Reset counters mock_pvm_uuid.reset_mock() self.apt.reset_mock() mock_vterm.reset_mock() self.assertRaises(pvm_exc.Error, vm.delete_lpar, self.apt, 'inst') mock_pvm_uuid.assert_called_once_with('inst') mock_vterm.assert_called_once_with(self.apt, 'pvm_uuid') self.apt.delete.assert_called_once_with('LogicalPartition', root_id='pvm_uuid') # Test HttpNotFound - exception not raised mock_pvm_uuid.reset_mock() self.apt.reset_mock() mock_vterm.reset_mock() resp.status = 404 self.apt.delete.side_effect = pvm_exc.HttpNotFound(resp=resp) vm.delete_lpar(self.apt, 'inst') mock_pvm_uuid.assert_called_once_with('inst') mock_vterm.assert_called_once_with(self.apt, 'pvm_uuid') self.apt.delete.assert_called_once_with('LogicalPartition', root_id='pvm_uuid') # Test Other HttpError mock_pvm_uuid.reset_mock() self.apt.reset_mock() mock_vterm.reset_mock() resp.status = 111 self.apt.delete.side_effect = pvm_exc.HttpError(resp=resp) self.assertRaises(pvm_exc.HttpError, vm.delete_lpar, self.apt, 'inst') mock_pvm_uuid.assert_called_once_with('inst') mock_vterm.assert_called_once_with(self.apt, 'pvm_uuid') self.apt.delete.assert_called_once_with('LogicalPartition', root_id='pvm_uuid') # Test HttpNotFound closing vterm mock_pvm_uuid.reset_mock() self.apt.reset_mock() mock_vterm.reset_mock() resp.status = 404 mock_vterm.side_effect = pvm_exc.HttpNotFound(resp=resp) vm.delete_lpar(self.apt, 'inst') mock_pvm_uuid.assert_called_once_with('inst') mock_vterm.assert_called_once_with(self.apt, 'pvm_uuid') self.apt.delete.assert_not_called() # Test Other HttpError closing vterm mock_pvm_uuid.reset_mock() self.apt.reset_mock() mock_vterm.reset_mock() resp.status = 111 mock_vterm.side_effect = pvm_exc.HttpError(resp=resp) self.assertRaises(pvm_exc.HttpError, vm.delete_lpar, self.apt, 'inst') mock_pvm_uuid.assert_called_once_with('inst') mock_vterm.assert_called_once_with(self.apt, 'pvm_uuid') self.apt.delete.assert_not_called()
def test_store_with_exception(self, mock_get_inst, mock_log): mock_get_inst.side_effect = pvm_exc.HttpError(mock.Mock()) mgr = manager.NvramManager(self.fake_store, mock.Mock(), mock.Mock()) mgr.store(powervm.TEST_INST1.uuid) self.assertEqual(1, mock_log.call_count)