def test_should_log_message(self, mock_logging_error, mock_traceback): message = "test message" exception = HPOneViewException(message) traceback_ex = None handle_exceptions(exception.__class__, exception, traceback_ex, mock_logging_error) log_message = "Uncaught Exception: HPOneViewException with message: test message" mock_logging_error.error.assert_called_once_with(log_message)
def test_login_with_exception_in_put_username_password_sessionID( self, mock_put, mock_get): mock_get.side_effect = [{'minimumVersion': 800, 'currentVersion': 400}] mock_put.side_effect = HPOneViewException("Failed") self.assertRaises(HPOneViewException, self.connection.login, { "userName": "******", "password": "", "sessionID": "123" })
def test_should_print_exception(self, mock_logging_error, mock_traceback): message = "test message" exception = HPOneViewException(message) traceback_ex = None handle_exceptions(exception.__class__, exception, traceback_ex, mock_logging_error) mock_traceback.assert_called_once_with(exception.__class__, exception, traceback_ex)
def test_should_call_fail_json_when_oneview_exception(self): self.mock_ansible_module.params = self._ansible_params self._method_to_fire.side_effect = HPOneViewException( self.error_message) self._testing_class().run() self.mock_ansible_module.fail_json.assert_called_once_with( msg=self.error_message)
def test_should_log_oneview_reponse(self, mock_logging_error, mock_traceback): message = {"msg": "test message"} exception = HPOneViewException(message) traceback_ex = None handle_exceptions(exception.__class__, exception, traceback_ex, mock_logging_error) log_message = "Uncaught Exception: HPOneViewException with message: \n{'msg': 'test message'}" mock_logging_error.error.assert_called_once_with(log_message)
def test_get_processor_collection_server_hardware_not_found(self): self.oneview_client.server_hardware.get_by_id.side_effect = \ HPOneViewException({"errorCode": "RESOURCE_NOT_FOUND"}) response = self.client.get( "/redfish/v1/CompositionService/ResourceBlocks" "/30303437-3034-4D32-3230-313133364752/Systems/1/Processors/") self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code) self.assertEqual("application/json", response.mimetype)
def test_exception_constructor_with_invalid_type(self): exception = HPOneViewException( ['List, item 1', "List, item 2: A message string"]) self.assertEqual(exception.msg, None) self.assertEqual(exception.oneview_response, ['List, item 1', "List, item 2: A message string"]) self.assertEqual(exception.args[0], None) self.assertEqual(exception.args[1], ['List, item 1', "List, item 2: A message string"])
def generate_backup(self, blocking=True, verbose=False): resp, body = self._con.do_http('POST', uri['backups'], None) if resp.status >= 400: raise HPOneViewException(body) taskuri = resp.getheader('Location') task = self._con.get(taskuri) if blocking is True: task = self._activity.wait4task(task, tout=600, verbose=verbose) backupResource = self._activity.get_task_associated_resource(task) backup = self._con.get(backupResource['resourceUri']) return backup
def __do_rest_call(self, http_method, uri, body, custom_headers): resp, body = self.do_http(method=http_method, path=uri, body=json.dumps(body), custom_headers=custom_headers) if resp.status >= 400: raise HPOneViewException(body) elif resp.status == 202: task = self.get(resp.getheader('Location')) return task, body return None, body
def execute_module(self): """ Abstract function, must be implemented by the inheritor. This method is called from the run method. It should contains the module logic Returns: dict: It must return a dictionary with the attributes for the module result, such as ansible_facts, msg and changed. """ raise HPOneViewException("execute_module not implemented")
def test_pickle_HPOneViewException_message(self): message = "test message" exception = HPOneViewException(message) tempf = tempfile.NamedTemporaryFile(delete=False) with tempf as f: pickle.dump(exception, f) with open(tempf.name, 'rb') as f: exception = pickle.load(f) os.remove(tempf.name) self.assertEqual('HPOneViewException', exception.__class__.__name__)
def test_should_create_new_user(self): self.resource.get_by.side_effect = HPOneViewException('FAKE_MSG_ERROR') self.resource.create.return_value = DEFAULT_PARAMS self.mock_ansible_module.params = PARAMS_FOR_PRESENT UserModule().run() self.mock_ansible_module.exit_json.assert_called_once_with( changed=True, msg=UserModule.MSG_CREATED, ansible_facts=dict(user=DEFAULT_PARAMS) )
def upload_spp(self, sppPath, sppName, verbose=False, blocking=True): response, body = self._con.post_multipart(uri['fwUpload'], '', sppPath, sppName, verbose) if response.status >= 400: raise HPOneViewException(body) if response.status == 202 and verbose is True: print('Upload complete. Waiting for processing.') task, spp = self._activity.make_task_entity_tuple(body) if blocking is True: task = self._activity.wait4task(task, tout=600, verbose=verbose) if verbose is True: print('Processing complete.') return spp['resourceId']
def test_remove_computer_system_sp_not_found(self, g): """Tests remove ComputerSystem with ServerProfile not found""" e = HPOneViewException({ 'errorCode': 'RESOURCE_NOT_FOUND', 'message': 'server-profile not found', }) g.oneview_client.server_profiles.delete.side_effect = e response = self.client.delete("/redfish/v1/Systems/" "e7f93fa2-0cb4-11e8-9060-e839359bc36b") self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code) self.assertEqual("application/json", response.mimetype)
def test_get_computer_system_sh_not_found(self, g): """Tests ComputerSystem with ServerHardware Not Found""" e = HPOneViewException({ 'errorCode': 'RESOURCE_NOT_FOUND', 'message': 'server-hardware not found', }) g.oneview_client.server_hardware.get.side_effect = e response = self.client.get( "/redfish/v1/Systems/0303437-3034-4D32-3230-313133364752") self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code) self.assertEqual("application/json", response.mimetype)
def download_to_stream(self, stream_writer, url, body='', method='GET', custom_headers=None): http_headers = self._headers.copy() if custom_headers: http_headers.update(custom_headers) chunk_size = 4096 conn = None successful_connected = False while not successful_connected: try: conn = self.get_connection() conn.request(method, url, body, http_headers) resp = conn.getresponse() if resp.status >= 400: self.__handle_download_error(resp, conn) if resp.status == 302: return self.download_to_stream( stream_writer=stream_writer, url=resp.getheader('Location'), body=body, method=method, custom_headers=http_headers) tempbytes = True while tempbytes: tempbytes = resp.read(chunk_size) if tempbytes: # filter out keep-alive new chunks stream_writer.write(tempbytes) conn.close() successful_connected = True except http.client.BadStatusLine: logger.warning('Bad Status Line. Trying again...') if conn: conn.close() time.sleep(1) continue except http.client.HTTPException: raise HPOneViewException('Failure during login attempt.\n %s' % traceback.format_exc()) return successful_connected
def test_remove_computer_system_exception(self): """Tests remove ComputerSystem with ServerProfile exception""" e = HPOneViewException({ 'errorCode': 'ANOTHER_ERROR', 'message': 'server-profile error', }) ServerProfiles.delete.side_effect = e response = self.client.delete("/redfish/v1/Systems/" "e7f93fa2-0cb4-11e8-9060-e839359bc36b") self.assertEqual(status.HTTP_500_INTERNAL_SERVER_ERROR, response.status_code) self.assertEqual("application/json", response.mimetype)
def test_get_computer_system_sh_exception(self, g): """Tests ComputerSystem with ServerHardware exception""" e = HPOneViewException({ 'errorCode': 'ANOTHER_ERROR', 'message': 'server-hardware error', }) g.oneview_client.server_hardware.get.side_effect = e response = self.client.get( "/redfish/v1/Systems/0303437-3034-4D32-3230-313133364752") self.assertEqual(status.HTTP_500_INTERNAL_SERVER_ERROR, response.status_code) self.assertEqual("application/json", response.mimetype)
def test_get_storage_collection_sh_not_found(self, g): """Tests StorageCollection""" e = HPOneViewException({ 'errorCode': 'RESOURCE_NOT_FOUND', 'message': 'server-hardware not found', }) g.oneview_client.server_hardware.get.side_effect = e # Get StorageCollection response = self.app.get( "/redfish/v1/Systems/30303437-3034-4D32-3230-313133364752/Storage") self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code) self.assertEqual("application/json", response.mimetype)
def setUpClass(self): super(TestResourceBlock, self).setUpClass() self.app.register_blueprint(resource_block.resource_block) with open('oneview_redfish_toolkit/mockups/oneview/ServerHardware.json' ) as f: self.server_hardware = json.load(f) with open('oneview_redfish_toolkit/mockups/oneview' '/ServerProfileTemplate.json') as f: self.server_profile_template = json.load(f) with open('oneview_redfish_toolkit/mockups/oneview/Drive.json') as f: self.drive = json.load(f) with open( 'oneview_redfish_toolkit/mockups/oneview/DriveIndexTrees.json' ) as f: self.drive_index_tree = json.load(f) with open('oneview_redfish_toolkit/mockups/oneview/' 'DriveComposedIndexTrees.json') as f: self.drive_composed_index_tree = json.load(f) with open('oneview_redfish_toolkit/mockups/oneview' '/ServerProfileTemplates.json') as f: self.server_profile_templates = json.load(f) with open( 'oneview_redfish_toolkit/mockups/oneview/LogicalEnclosures.json' ) as f: self.log_encl_list = json.load(f) with open('oneview_redfish_toolkit/mockups/redfish' '/ServerHardwareResourceBlock.json') as f: self.expected_sh_resource_block = json.load(f) with open('oneview_redfish_toolkit/mockups/oneview' '/DriveEnclosureList.json') as f: self.drive_enclosure_list = json.load(f) self.resource_not_found = HPOneViewException({ "errorCode": "RESOURCE_NOT_FOUND", "message": "Any resource not found message" })
def test_get_storage_collection_sh_exception(self, g): """Tests StorageCollection""" e = HPOneViewException({ 'errorCode': 'ANOTHER_ERROR', 'message': 'server-hardware-types error', }) g.oneview_client.server_hardware.get.side_effect = e # Get StorageCollection response = self.app.get( "/redfish/v1/Systems/30303437-3034-4D32-3230-313133364752/Storage") self.assertEqual(status.HTTP_500_INTERNAL_SERVER_ERROR, response.status_code) self.assertEqual("application/json", response.mimetype)
def test_get_ethernet_interface_when_profile_not_found(self): """Tests request EthernetInterface when server profile not found""" e = HPOneViewException({'errorCode': 'RESOURCE_NOT_FOUND'}) self.oneview_client.server_profiles.get.side_effect = e response = self.client.get( "/redfish/v1/Systems/b425802b-a6a5-4941-8885-aab68dfa2ee2/" "EthernetInterfaces/1") self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code) self.assertEqual("application/json", response.mimetype) self.oneview_client.server_profiles.get.assert_called_with( self.server_profile["uuid"]) self.oneview_client.index_resources.get.assert_not_called()
def test_get_storage_collection_when_profile_not_found(self): """Tests StorageCollection""" e = HPOneViewException({ 'errorCode': 'RESOURCE_NOT_FOUND', 'message': 'server-hardware not found', }) self.oneview_client.server_profiles.get_by_id.side_effect = e response = self.client.get( "/redfish/v1/Systems/b425802b-a6a5-4941-8885-aab68dfa2ee2/Storage") self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code) self.assertEqual("application/json", response.mimetype) self.oneview_client.server_profiles.get_by_id.assert_called_with( self.server_profile["uuid"])
def test_service_root_oneview_exception(self, connection): """Tests ServiceROOT with an exception""" e = HPOneViewException({ 'errorCode': 'ANOTHER_ERROR', 'message': 'appliance error', }) connection.request_oneview.side_effect = e response = self.client.get("/redfish/v1/") self.assertEqual(status.HTTP_500_INTERNAL_SERVER_ERROR, response.status_code) self.assertEqual("application/json", response.mimetype)
def get(self, uri): resp, body = self.do_http('GET', uri, '') if resp.status >= 400: raise HPOneViewException(body) if resp.status == 302: body = self.get(resp.getheader('Location')) if type(body) is dict: if 'nextPageUri' in body: self._nextPage = body['nextPageUri'] if 'prevPageUri' in body: self._prevPage = body['prevPageUri'] if 'total' in body: self._numTotalRecords = body['total'] if 'count' in body: self._numDisplayedRecords = body['count'] return body
def create_enet_networks(self, prefix, vid_start, vid_count, bw={}): enet_list = [] try: for vid in range(vid_start, vid_start + vid_count): enet_name = '%s%s' % (prefix, vid) enet_list.append( self.create_enet_network(enet_name, vid, bw=bw)) except http.client.HTTPException: # All or nothing for enet in enet_list: try: self._con.delete(enet['uri']) except http.client.HTTPException: pass raise HPOneViewException('Could not create one or more networks') return enet_list
def __handle_download_error(self, resp, conn): try: tempbytes = resp.read() tempbody = tempbytes.decode('utf-8') try: body = json.loads(tempbody) except ValueError: body = tempbody except UnicodeDecodeError: # Might be binary data body = tempbytes conn.close() if not body: body = "Error " + str(resp.status) conn.close() raise HPOneViewException(body)
def test_get_network_device_function_sh_not_found(self): """Tests NetworkDeviceFunction server hardware not found""" e = HPOneViewException({ 'errorCode': 'RESOURCE_NOT_FOUND', 'message': 'server-hardware not found', }) self.oneview_client.server_hardware.get.side_effect = e # Get NetworkDeviceFunction response = self.client.get( "/redfish/v1/Chassis/30303437-3034-4D32-3230-313133364752/" "NetworkAdapters/3/NetworkDeviceFunctions/1_1_a") self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code) self.assertEqual("application/json", response.mimetype)
def test_get_network_interface_sh_exception(self, g): """Tests NetworkInterface unknown exception""" e = HPOneViewException({ 'errorCode': 'ANOTHER_ERROR', 'message': 'server-hardware error', }) g.oneview_client.server_hardware.get.side_effect = e # Get NetworkInterfaceCollection response = self.client.get( "/redfish/v1/Systems/30303437-3034-4D32-3230-313133364752/" "NetworkInterfaces/3") self.assertEqual(status.HTTP_500_INTERNAL_SERVER_ERROR, response.status_code) self.assertEqual("application/json", response.mimetype)
def test_get_network_device_function_sh_exception(self): """Tests NetworkDeviceFunction unknown exception""" e = HPOneViewException({ 'errorCode': 'ANOTHER_ERROR', 'message': 'server-hardware error', }) self.oneview_client.server_hardware.get.side_effect = e # Get NetworkDeviceFunction response = self.client.get( "/redfish/v1/Chassis/30303437-3034-4D32-3230-313133364752/" "NetworkAdapters/3/NetworkDeviceFunctions/1_1_a") self.assertEqual(status.HTTP_500_INTERNAL_SERVER_ERROR, response.status_code) self.assertEqual("application/json", response.mimetype)