def test_sample_helper(self, mock_sleep): helpers = smpl_hlp.sample_retry_helper fake_resp1 = adp.Response('GET', '/some/path', 200, 'OK', ['headers'], body='Some Text HSCL3205 More Text') self.sess.request.side_effect = pvmex.Error('yo', response=fake_resp1) adpt = adp.Adapter(self.sess, helpers=helpers) self.assertRaises(pvmex.Error, adpt._request, 'method', 'path', body='the body') # Test that the request method was called twice and sleep was called self.assertEqual(self.sess.request.call_count, 2) mock_sleep.assert_called_once_with(5 * 1) hlp = functools.partial(smpl_hlp.sample_retry_helper, max_retries=5) self.sess.reset_mock() try: adpt._request('method', 'path', body='the body', helpers=hlp) except Exception: # Should have tried 6 times total self.assertEqual(self.sess.request.call_count, 6)
def test_find_or_create_vnet(self): """Tests that the virtual network can be found/created.""" self.adpt.read.return_value = self.resp fake_vs = mock.Mock() fake_vs.switch_id = 0 fake_vs.name = 'ETHERNET0' fake_vs.related_href = ('https://9.1.2.3:12443/rest/api/uom/' 'ManagedSystem/' '67dca605-3923-34da-bd8f-26a378fc817f/' 'VirtualSwitch/' 'ec8aaa54-9837-3c23-a541-a4e4be3ae489') # This should find a vnet. vnet_resp = cna._find_or_create_vnet(self.adpt, '2227', fake_vs) self.assertIsNotNone(vnet_resp) # Now flip to a CNA that requires a create... resp = adp.Response('reqmethod', 'reqpath', 'status', 'reason', {}) resp.entry = ewrap.EntryWrapper._bld(self.adpt, tag='VirtualNetwork').entry self.adpt.create.return_value = resp vnet_resp = cna._find_or_create_vnet(self.adpt, '2228', fake_vs) self.assertIsNotNone(vnet_resp) self.assertEqual(1, self.adpt.create.call_count)
def __init__(self, file_name=None, pvmfile=None, adapter=None): """Initialize this PVMResp by loading a file or pulling a PVMFile. :param file_name: Name of a file to load. :param pvmfile: An existing PVMFile instance. This PVMResp will use its attributes. If both file_name and pvmfile are specified, the file will be reloaded into the passed-in PVMFile. This is probably not what you intended. :param adapter: A pypowervm.adapter.Adapter, used for traits, etc. """ super(PVMResp, self).__init__() # Legacy no-arg constructor - allow caller to set fields manually if pvmfile is None and file_name is None: return if pvmfile is None: self.load_file(file_name) else: # Use pvmfile if file_name is not None: pvmfile.load_file(file_name) # Copy in attrs from pvmfile self.comment = pvmfile.comment self.path = pvmfile.path self.reason = pvmfile.reason self.status = pvmfile.status self.headers = pvmfile.headers self.body = pvmfile.body self.response = adp.Response(reqmethod=None, reqpath=None, status=self.status, reason=self.reason, headers=self.headers, body=self.body) self.response.adapter = adapter self.response._unmarshal_atom()
def _setup_reassign_arbitrary_vid(self): vsw_p = mock.patch('pypowervm.wrappers.network.VSwitch.search') self.mock_vsw = vsw_p.start() self.addCleanup(vsw_p.stop) vnet = pvm_net.VNet._bld(self.adpt).entry resp1 = adpt.Response('reqmethod', 'reqpath', 'status', 'reason', {}) resp1.feed = ent.Feed({}, [vnet]) self.adpt.read.return_value = resp1 self.adpt.read_by_href.return_value = vnet nb = pvm_net.NetBridge.wrap(self.mgr_nbr_resp)[0] resp2 = adpt.Response('reqmethod', 'reqpath', 'status', 'reason', {}) resp2.entry = nb.entry self.adpt.update.return_value = resp2 vsw = pvm_net.VSwitch.wrap(self.mgr_vsw_resp)[0] self.mock_vsw.return_value = vsw return nb
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 _mock_update_by_path(ssp, etag, path, timeout=-1): # Spoof adding UDID and defaulting thinness for lu in ssp.logical_units: if not lu.udid: lu._udid('udid_' + lu.name) if lu.is_thin is None: lu._is_thin(True) if lu.lu_type is None: lu._lu_type(stor.LUType.DISK) resp = adp.Response('meth', 'path', 200, 'reason', {'etag': 'after'}) resp.entry = ssp.entry return resp
def validate_in(*args, **kwargs): # Validate that the element is built properly wrap = args[0] self.assertEqual('chk', wrap._get_val_str(vf._FILE_CHKSUM)) self.assertEqual(50, wrap.expected_file_size) self.assertEqual('f_name', wrap.file_name) self.assertEqual('application/octet-stream', wrap.internet_media_type) self.assertEqual('f_type', wrap.enum_type) self.assertEqual('v_uuid', wrap.vios_uuid) self.assertEqual('tdev_uuid', wrap.tdev_udid) ret = adp.Response('reqmethod', 'reqpath', 'status', 'reason', {}) ret.entry = ewrap.EntryWrapper._bld(self.adpt, tag='File').entry return ret
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 test_find_or_create_vnet(self): """Validates that a vnet is created (and deleted) as part of find.""" # Load the data vnets = pvm_net.VNet.wrap(self.mgr_vnet_resp) vsw = pvm_net.VSwitch.wrap(self.mgr_vsw_resp)[0] # Set up the mock create resp = pvm_net.VNet.bld(self.adpt, 'FakeName', 4094, vsw.href, True) mock_resp = adpt.Response('rm', 'rp', 200, 'reason', {}) mock_resp.entry = resp.entry self.adpt.create.return_value = mock_resp # Run the code bridger = net_br.NetworkBridgerVNET(self.adpt, self.host_uuid) ret_val = bridger._find_or_create_vnet(vnets, 4094, vsw) # Equality check self.assertEqual(4094, ret_val.vlan) self.assertTrue(ret_val.tagged) # Make sure the delete was called self.assertEqual(1, self.adpt.delete_by_href.call_count)
def _bld_resp(self, status=200, entry_or_list=None): """Build a pypowervm.adapter.Response for mocking Adapter.search/read. :param status: HTTP status of the Response. :param entry_or_list: pypowervm.entity.Entry or list thereof. If None, the Response has no content. If an Entry, the Response looks like it got back <entry/>. If a list of Entry, the Response looks like it got back <feed/>. :return: pypowervm.adapter.Response suitable for mocking pypowervm.adapter.Adapter.search or read. """ resp = pvm_adp.Response('meth', 'path', status, 'reason', {}) resp.entry = None resp.feed = None if entry_or_list is None: resp.feed = pvm_ent.Feed({}, []) else: if isinstance(entry_or_list, list): resp.feed = pvm_ent.Feed({}, entry_or_list) else: resp.entry = entry_or_list return resp
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 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