class LogicalInterconnects(object): URI = '/rest/logical-interconnects' FIRMWARE_PATH = "/firmware" SNMP_CONFIGURATION_PATH = "/snmp-configuration" PORT_MONITOR_PATH = "/port-monitor" LOCATIONS_PATH = "/locations/interconnects" FORWARDING_INFORMATION_PATH = "/forwarding-information-base" QOS_AGGREGATED_CONFIGURATION = "/qos-aggregated-configuration" locations_uri = "{uri}{locations}".format(uri=URI, locations=LOCATIONS_PATH) def __init__(self, con): self._connection = con self._client = ResourceClient(con, self.URI) def get_all(self, start=0, count=-1, filter='', sort=''): """ Gets a list of logical interconnects based on optional sorting and filtering, and constrained by start and count parameters. Args: start: The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the first available item. count: The number of resources to return. A count of -1 requests all the items. The actual number of items in the response may differ from the requested count if the sum of start and count exceed the total number of items. filter: A general filter/query string to narrow the list of items returned. The default is no filter - all resources are returned. sort: The sort order of the returned data set. By default, the sort order is based on create time, with the oldest entry first. Returns: list: A list of logical interconnects. """ return self._client.get_all(start, count, filter=filter, sort=sort) def get(self, id_or_uri): """ Gets a logical interconnect by ID or by uri Args: id_or_uri: Could be either the logical interconnect id or the logical interconnect uri Returns: dict: The logical interconnect """ return self._client.get(id_or_uri) def get_by_name(self, name): """ Gets a logical interconnect by name. Args: name: Name of the logical interconnect Returns: Logical Interconnect """ logical_interconnects = self._client.get_all() result = [x for x in logical_interconnects if x['name'] == name] return result[0] if result else None def update_compliance(self, id_or_uri, timeout=-1): """ Returns logical interconnects to a consistent state. The current logical interconnect state is compared to the associated logical interconnect group. Any differences identified are corrected, bringing the logical interconnect back to a consistent state. Changes are asynchronously applied to all managed interconnects. Note that if the changes detected involve differences in the interconnect map between the logical interconnect group and the logical interconnect, the process of bringing the logical interconnect back to a consistent state may involve automatically removing existing interconnects from management and/or adding new interconnects for management. Args: id_or_uri: Could be either the resource id or the resource uri timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: Logical Interconnect """ uri = self._client.build_uri(id_or_uri) + "/compliance" return self._client.update_with_zero_body(uri, timeout=timeout) def update_ethernet_settings(self, id_or_uri, configuration, force=False, timeout=-1): """ Updates the Ethernet interconnect settings for the logical interconnect. Args: id_or_uri: Could be either the resource id or the resource uri configuration: Ethernet interconnect settings. force: If set to true the operation completes despite any problems with network connectivity or errors on the resource itself. The default is false. timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: Logical Interconnect """ uri = self._client.build_uri(id_or_uri) + "/ethernetSettings" return self._client.update(configuration, uri=uri, force=force, timeout=timeout) def update_internal_networks(self, id_or_uri, network_uri_list, force=False, timeout=-1): """ Updates internal networks on the logical interconnect. Args: id_or_uri: Could be either the resource id or the resource uri network_uri_list: List of Ethernet network uris. force: If set to true the operation completes despite any problems with network connectivity or errors on the resource itself. The default is false. timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: Logical Interconnect """ uri = self._client.build_uri(id_or_uri) + "/internalNetworks" return self._client.update(network_uri_list, uri=uri, force=force, timeout=timeout) def get_internal_vlans(self, id_or_uri): """ Gets the internal VLAN IDs for the provisioned networks on a logical interconnect. Args: id_or_uri: Could be either the logical interconnect group id or the logical interconnect group uri Returns: dict: Collection of URIs """ uri = self._client.build_uri(id_or_uri) + "/internalVlans" return self._client.get_collection(uri) def update_settings(self, id_or_uri, settings, force=False, timeout=-1): """ Updates interconnect settings on the logical interconnect. Changes to interconnect settings are asynchronously applied to all managed interconnects. Args: id_or_uri: Could be either the resource id or the resource uri settings: Interconnect settings force: If set to true the operation completes despite any problems with network connectivity or errors on the resource itself. The default is false. timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: Logical Interconnect """ data = settings.copy() if 'type' not in data: data['type'] = 'InterconnectSettingsV3' if 'ethernetSettings' in data and 'type' not in data[ 'ethernetSettings']: data['ethernetSettings']['type'] = 'EthernetInterconnectSettingsV3' uri = self._client.build_uri(id_or_uri) + "/settings" return self._client.update(data, uri=uri, force=force, timeout=timeout) def update_configuration(self, id_or_uri, timeout=-1): """ Asynchronously applies or re-applies the logical interconnect configuration to all managed interconnects. Args: id_or_uri: Could be either the resource id or the resource uri timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: Logical Interconnect """ uri = self._client.build_uri(id_or_uri) + "/configuration" return self._client.update_with_zero_body(uri=uri, timeout=timeout) def get_snmp_configuration(self, id_or_uri): """ Gets the SNMP configuration for a logical interconnect. Args: id_or_uri: Could be either the logical interconnect group id or the logical interconnect group uri Returns: dict: SNMP configuration """ uri = self._client.build_uri(id_or_uri) + self.SNMP_CONFIGURATION_PATH return self._client.get(uri) def update_snmp_configuration(self, id_or_uri, configuration, timeout=-1): """ Updates the SNMP configuration of a logical interconnect. Changes to the SNMP configuration are asynchronously applied to all managed interconnects. Args: id_or_uri: Could be either the logical interconnect id or the logical interconnect uri configuration: snmp configuration Returns: dict: snmp configuration """ data = configuration.copy() if 'type' not in data: data['type'] = 'snmp-configuration' uri = self._client.build_uri(id_or_uri) + self.SNMP_CONFIGURATION_PATH return self._client.update(data, uri=uri, timeout=timeout) def get_unassigned_uplink_ports(self, id_or_uri): """ Gets a collection of uplink ports from the member interconnects which are eligible for assignment to an analyzer port. To be eligible a port must be a valid uplink, must not be a member of an existing uplink set and must not currently be used for stacking. Args: id_or_uri: Could be either the logical interconnect group id or the logical interconnect group uri Returns: dict: Collection of uplink ports """ uri = self._client.build_uri( id_or_uri) + "/unassignedUplinkPortsForPortMonitor" return self._client.get_collection(uri) def get_port_monitor(self, id_or_uri): """ Gets the port monitor configuration of a logical interconnect. Args: id_or_uri: Could be either the logical interconnect id or the logical interconnect uri Returns: dict: port monitor configuration """ uri = self._client.build_uri(id_or_uri) + self.PORT_MONITOR_PATH return self._client.get(uri) def update_port_monitor(self, id_or_uri, resource, timeout=-1): """ Updates the port monitor configuration of a logical interconnect. Args: id_or_uri: Could be either the logical interconnect id or the logical interconnect uri resource: port monitor configuration Returns: dict: port monitor configuration """ data = resource.copy() if 'type' not in data: data['type'] = 'port-monitor' uri = self._client.build_uri(id_or_uri) + self.PORT_MONITOR_PATH return self._client.update(data, uri=uri, timeout=timeout) def get_telemetry_configuration(self, telemetry_configuration_uri): """ Gets the telemetry configuration of a logical interconnect. Args: telemetry_configuration_uri: Telemetry Configuration URI Returns: dict: Telemetry configuration """ return self._client.get(telemetry_configuration_uri) def create_interconnect(self, location_entries, timeout=-1): """ Creates an interconnect at the given location. WARN: It does not create the LOGICAL INTERCONNECT itself. It will fail if no interconnect is already present on the specified position. Args: location_entries: dictionary with location entries timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: Created interconnect. """ return self._client.create(location_entries, uri=self.locations_uri, timeout=timeout) def delete_interconnect(self, enclosure_uri, bay, timeout=-1): """ Deletes an interconnect from a location. WARN: This won't delete the LOGICAL INTERCONNECT itself, and may cause inconsistency between the enclosure and Logical Interconnect Group. Args: enclosure_uri: URI of the Enclosure bay: Bay timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: bool: indicating if the interconnect was successfully deleted. """ uri = "{locations_uri}?location=Enclosure:{enclosure_uri},Bay:{bay}".format( locations_uri=self.locations_uri, enclosure_uri=enclosure_uri, bay=bay) return self._client.delete(uri, timeout=timeout) def get_firmware(self, id_or_uri): """ Gets the installed firmware for a logical interconnect. Args: id_or_uri: Could be either the logical interconnect id or the logical interconnect uri Returns: dict: LIFirmware """ firmware_uri = self.__build_firmware_uri(id_or_uri) return self._client.get(firmware_uri) def install_firmware(self, firmware_information, id_or_uri): """ Installs firmware to a logical interconnect. The three operations that are supported for the firmware update are Stage (uploads firmware to the interconnect), Activate (installs firmware on the interconnect) and Update (which does a Stage and Activate in a sequential manner). Returns: dict: """ firmware_uri = self.__build_firmware_uri(id_or_uri) return self._client.update(firmware_information, firmware_uri) def get_forwarding_information_base(self, id_or_uri, filter=''): """ Gets the forwarding information base data for a logical interconnect. Maximum of 100 entries is returned. Optional filtering criteria may be specified. Args: id_or_uri: Could be either the logical interconnect id or the logical interconnect uri. filter: Filtering criteria may be specified using supported attributes: interconnectUri, macAddress, internalVlan, externalVlan, and supported relation = (Equals). macAddress is 12 hexadecimal digits with a colon between each pair of digits.(upper or lower case). The default is no filter - all resources are returned. Returns: list: A set of interconnect MAC address entries. """ uri = self._client.build_uri( id_or_uri) + self.FORWARDING_INFORMATION_PATH return self._client.get_collection(uri, filter=filter) def create_forwarding_information_base(self, id_or_uri, timeout=-1): """ Generates the forwarding information base dump file for a logical interconnect. Args: id_or_uri: Could be either the logical interconnect id or the logical interconnect uri. timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: Interconnect Forwarding Information Base DataInfo """ uri = self._client.build_uri( id_or_uri) + self.FORWARDING_INFORMATION_PATH return self._client.create_with_zero_body(uri=uri, timeout=timeout) def get_qos_aggregated_configuration(self, id_or_uri): """ Gets the QoS aggregated configuration for the logical interconnect. Args: id_or_uri: Could be either the logical interconnect id or the logical interconnect uri. Returns: dict: QoS Configuration """ uri = self._client.build_uri( id_or_uri) + self.QOS_AGGREGATED_CONFIGURATION return self._client.get(uri) def update_qos_aggregated_configuration(self, id_or_uri, qos_configuration, timeout=-1): """ Updates the QoS aggregated configuration for the logical interconnect. Args: id_or_uri: Could be either the logical interconnect id or the logical interconnect uri. qos_configuration: QOS configuration. Returns: dict: Logical Interconnect """ uri = self._client.build_uri( id_or_uri) + self.QOS_AGGREGATED_CONFIGURATION return self._client.update(qos_configuration, uri=uri, timeout=timeout) def __build_firmware_uri(self, id_or_uri): return self._client.build_uri(id_or_uri) + self.FIRMWARE_PATH
class ManagedSANs(object): """ Managed SANs API client. """ URI = '/rest/fc-sans/managed-sans' def __init__(self, con): self._connection = con self._client = ResourceClient(con, self.URI) def get_all(self, start=0, count=-1, query='', sort=''): """ Retrieves the list of registered Managed SANs Args: start: The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the first available item. count: The number of resources to return. A count of -1 requests all items. The actual number of items in the response may differ from the requested count if the sum of start and count exceed the total number of items. query: A general query string to narrow the list of resources returned. The default is no query - all resources are returned. sort: The sort order of the returned data set. By default, the sort order is based on create time with the oldest entry first. Returns: list: A list of Managed SANs """ return self._client.get_all(start=start, count=count, query=query, sort=sort) def get_by_name(self, name): """ Gets a Managed SAN by name. Args: name: Name of the Managed SAN Returns: dict: Managed SAN. """ managed_sans = self._client.get_all() result = [x for x in managed_sans if x['name'] == name] return result[0] if result else None def get(self, id_or_uri): """ Retrieves a single Managed SAN by ID or URI. Args: id_or_uri: Can be either the Managed SAN resource ID or URI. Returns: dict: The Managed SAN resource. """ return self._client.get(id_or_uri=id_or_uri) def update(self, id_or_uri, data, timeout=-1): """ Updates a Managed SAN. It's possible to: - Refresh the Managed SAN. - Update the Managed SAN's publicAttributes. - Update the Managed SAN's policy. Args: id_or_uri: Can be either the Managed SAN resource ID or URI. data: dict object to update timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stop waiting for its completion. Returns: dict: SanResponse """ uri = self._client.build_uri(id_or_uri) return self._client.update(data, uri=uri, timeout=timeout) def get_endpoints(self, managed_san_id_or_uri, start=0, count=-1, filter='', sort=''): """ Gets a list of endpoints in a SAN identified by ID. Args: managed_san_id_or_uri: Can be either the Managed SAN ID or URI. start: The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the first available item. count: The number of resources to return. A count of -1 requests all items. The actual number of items in the response might differ from the requested count if the sum of start and count exceeds the total number of items. filter (list or str): A general filter/query string to narrow the list of items returned. The default is no filter; all resources are returned. sort: The sort order of the returned data set. By default, the sort order is based on create time with the oldest entry first. Returns: list: A list of endpoints. """ uri = self._client.build_uri(managed_san_id_or_uri) + "/endpoints/" return self._client.get_all(start, count, filter=filter, sort=sort, uri=uri) def create_endpoints_csv_file(self, managed_san_id_or_uri, timeout=-1): """ Creates an endpoints CSV file for a SAN. Args: managed_san_id_or_uri: Can be either the Managed SAN ID or URI. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: dict: Endpoint CSV File Response. """ uri = self._client.build_uri(managed_san_id_or_uri) + '/endpoints/' return self._client.create_with_zero_body(uri=uri, timeout=timeout) def create_issues_report(self, managed_san_id_or_uri, timeout=-1): """ Creates an unexpected zoning report for a SAN. Args: managed_san_id_or_uri: Can be either the Managed SAN ID or URI. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: list: A list of FCIssueResponse dict. """ uri = self._client.build_uri(managed_san_id_or_uri) + '/issues/' return self._client.create_report(uri=uri, timeout=timeout) def get_wwn(self, wwn): """ Retrieves a list of associations between provided WWNs and the SANs (if any) on which they reside. Note: This method is available for API version 300 or later. Args: wwn (str): The WWN that may be associated with the SAN. Returns: list: Associations between provided WWNs and the SANs """ uri = '/rest/fc-sans/managed-sans?locate=' + wwn return self._client.get(uri)
class ResourceTest(unittest.TestCase): URI = "/rest/testuri" def setUp(self): super(ResourceTest, self).setUp() self.host = '127.0.0.1' self.connection = connection(self.host) self.resource_client = ResourceClient(self.connection, self.URI) self.task = {"task": "task"} self.response_body = {"body": "body"} self.custom_headers = {'Accept-Language': 'en_US'} @mock.patch.object(connection, 'get') def test_get_all_called_once(self, mock_get): filter = "'name'='OneViewSDK \"Test FC Network'" sort = 'name:ascending' query = "name NE 'WrongName'" view = '"{view-name}"' mock_get.return_value = {"members": [{"member": "member"}]} result = self.resource_client.get_all( 1, 500, filter, query, sort, view, 'name,owner,modified') uri = '{resource_uri}?start=1' \ '&count=500' \ '&filter=%27name%27%3D%27OneViewSDK%20%22Test%20FC%20Network%27' \ '&query=name%20NE%20%27WrongName%27' \ '&sort=name%3Aascending' \ '&view=%22%7Bview-name%7D%22' \ '&fields=name%2Cowner%2Cmodified'.format(resource_uri=self.URI) self.assertEqual([{'member': 'member'}], result) mock_get.assert_called_once_with(uri) @mock.patch.object(connection, 'get') def test_get_all_with_defaults(self, mock_get): self.resource_client.get_all() uri = "{resource_uri}?start=0&count=-1".format(resource_uri=self.URI) mock_get.assert_called_once_with(uri) @mock.patch.object(connection, 'get') def test_get_all_with_custom_uri(self, mock_get): self.resource_client.get_all(uri='/rest/testuri/12467836/subresources') uri = "/rest/testuri/12467836/subresources?start=0&count=-1" mock_get.assert_called_once_with(uri) @mock.patch.object(connection, 'get') def test_get_all_with_different_resource_uri_should_fail(self, mock_get): try: self.resource_client.get_all(uri='/rest/other/resource/12467836/subresources') except HPOneViewUnknownType as e: self.assertEqual(UNRECOGNIZED_URI, e.args[0]) else: self.fail('Expected Exception was not raised') @mock.patch.object(connection, 'get') def test_get_all_should_do_multi_requests_when_response_paginated(self, mock_get): uri_list = ['/rest/testuri?start=0&count=-1', '/rest/testuri?start=3&count=3', '/rest/testuri?start=6&count=3'] results = [{'nextPageUri': uri_list[1], 'members': [{'id': '1'}, {'id': '2'}, {'id': '3'}]}, {'nextPageUri': uri_list[2], 'members': [{'id': '4'}, {'id': '5'}, {'id': '6'}]}, {'nextPageUri': None, 'members': [{'id': '7'}, {'id': '8'}]}] mock_get.side_effect = results self.resource_client.get_all() expected_calls = [call(uri_list[0]), call(uri_list[1]), call(uri_list[2])] self.assertEqual(mock_get.call_args_list, expected_calls) @mock.patch.object(connection, 'get') def test_get_all_with_count_should_do_multi_requests_when_response_paginated(self, mock_get): uri_list = ['/rest/testuri?start=0&count=15', '/rest/testuri?start=3&count=3', '/rest/testuri?start=6&count=3'] results = [{'nextPageUri': uri_list[1], 'members': [{'id': '1'}, {'id': '2'}, {'id': '3'}]}, {'nextPageUri': uri_list[2], 'members': [{'id': '4'}, {'id': '5'}, {'id': '6'}]}, {'nextPageUri': None, 'members': [{'id': '7'}, {'id': '8'}]}] mock_get.side_effect = results self.resource_client.get_all(count=15) expected_calls = [call(uri_list[0]), call(uri_list[1]), call(uri_list[2])] self.assertEqual(mock_get.call_args_list, expected_calls) @mock.patch.object(connection, 'get') def test_get_all_should_return_all_items_when_response_paginated(self, mock_get): uri_list = ['/rest/testuri?start=0&count=-1', '/rest/testuri?start=3&count=3', '/rest/testuri?start=6&count=1'] results = [{'nextPageUri': uri_list[1], 'members': [{'id': '1'}, {'id': '2'}, {'id': '3'}]}, {'nextPageUri': uri_list[2], 'members': [{'id': '4'}, {'id': '5'}, {'id': '6'}]}, {'nextPageUri': None, 'members': [{'id': '7'}]}] mock_get.side_effect = results result = self.resource_client.get_all() expected_items = [{'id': '1'}, {'id': '2'}, {'id': '3'}, {'id': '4'}, {'id': '5'}, {'id': '6'}, {'id': '7'}] self.assertSequenceEqual(result, expected_items) @mock.patch.object(connection, 'get') def test_get_all_with_count_should_return_all_items_when_response_paginated(self, mock_get): uri_list = ['/rest/testuri?start=0&count=15', '/rest/testuri?start=3&count=3', '/rest/testuri?start=6&count=1'] results = [{'nextPageUri': uri_list[1], 'members': [{'id': '1'}, {'id': '2'}, {'id': '3'}]}, {'nextPageUri': uri_list[2], 'members': [{'id': '4'}, {'id': '5'}, {'id': '6'}]}, {'nextPageUri': None, 'members': [{'id': '7'}]}] mock_get.side_effect = results result = self.resource_client.get_all(count=15) expected_items = [{'id': '1'}, {'id': '2'}, {'id': '3'}, {'id': '4'}, {'id': '5'}, {'id': '6'}, {'id': '7'}] self.assertSequenceEqual(result, expected_items) @mock.patch.object(connection, 'get') def test_get_all_should_return_empty_list_when_response_has_no_items(self, mock_get): mock_get.return_value = {'nextPageUri': None, 'members': []} result = self.resource_client.get_all() self.assertEqual(result, []) @mock.patch.object(connection, 'delete') @mock.patch.object(TaskMonitor, 'wait_for_task') def test_delete_by_id_called_once(self, mock_wait4task, mock_delete): mock_delete.return_value = self.task, self.response_body mock_wait4task.return_value = self.task delete_task = self.resource_client.delete('1', force=True, timeout=-1) self.assertEqual(self.task, delete_task) mock_delete.assert_called_once_with(self.URI + "/1?force=True", custom_headers=None) @mock.patch.object(connection, 'delete') @mock.patch.object(TaskMonitor, 'wait_for_task') def test_delete_with_custom_headers(self, mock_wait4task, mock_delete): mock_delete.return_value = self.task, self.response_body mock_wait4task.return_value = self.task self.resource_client.delete('1', custom_headers=self.custom_headers) mock_delete.assert_called_once_with(mock.ANY, custom_headers={'Accept-Language': 'en_US'}) def test_delete_dict_invalid_uri(self): dict_to_delete = {"task": "task", "uri": ""} try: self.resource_client.delete(dict_to_delete, False, -1) except HPOneViewUnknownType as e: self.assertEqual("Unknown object type", e.args[0]) else: self.fail() @mock.patch.object(connection, 'get') def test_get_schema_uri(self, mock_get): self.resource_client.get_schema() mock_get.assert_called_once_with(self.URI + "/schema") @mock.patch.object(connection, 'get') def test_get_by_id_uri(self, mock_get): self.resource_client.get('12345') mock_get.assert_called_once_with(self.URI + "/12345") @mock.patch.object(ResourceClient, 'get_by') def test_get_by_name_with_result(self, mock_get_by): mock_get_by.return_value = [{"name": "value"}] response = self.resource_client.get_by_name('Resource Name,') self.assertEqual(response, {"name": "value"}) mock_get_by.assert_called_once_with("name", 'Resource Name,') @mock.patch.object(ResourceClient, 'get_by') def test_get_by_name_without_result(self, mock_get_by): mock_get_by.return_value = [] response = self.resource_client.get_by_name('Resource Name,') self.assertIsNone(response) mock_get_by.assert_called_once_with("name", 'Resource Name,') @mock.patch.object(connection, 'get') def test_get_collection_uri(self, mock_get): mock_get.return_value = {"members": [{"key": "value"}, {"key": "value"}]} self.resource_client.get_collection('12345') mock_get.assert_called_once_with(self.URI + "/12345") @mock.patch.object(connection, 'get') def test_get_collection_with_filter(self, mock_get): mock_get.return_value = {} self.resource_client.get_collection('12345', 'name=name') mock_get.assert_called_once_with(self.URI + "/12345?filter=name%3Dname") @mock.patch.object(connection, 'get') def test_get_collection_should_return_list(self, mock_get): mock_get.return_value = {"members": [{"key": "value"}, {"key": "value"}]} collection = self.resource_client.get_collection('12345') self.assertEqual(len(collection), 2) @mock.patch.object(ResourceClient, 'get_all') def test_get_by_property(self, mock_get_all): self.resource_client.get_by('name', 'MyFibreNetwork') mock_get_all.assert_called_once_with(filter="\"'name'='MyFibreNetwork'\"", uri='/rest/testuri') @mock.patch.object(ResourceClient, 'get_all') def test_get_by_property_with_uri(self, mock_get_all): self.resource_client.get_by('name', 'MyFibreNetwork', uri='/rest/testuri/5435534/sub') mock_get_all.assert_called_once_with(filter="\"'name'='MyFibreNetwork'\"", uri='/rest/testuri/5435534/sub') @mock.patch.object(ResourceClient, 'get_all') def test_get_by_property_with__invalid_uri(self, mock_get_all): try: self.resource_client.get_by('name', 'MyFibreNetwork', uri='/rest/other/5435534/sub') except HPOneViewUnknownType as e: self.assertEqual('Unrecognized URI for this resource', e.args[0]) else: self.fail() @mock.patch.object(connection, 'put') @mock.patch.object(TaskMonitor, 'wait_for_task') def test_update_with_zero_body_called_once(self, mock_wait4task, mock_update): mock_update.return_value = self.task, self.task mock_wait4task.return_value = self.task self.resource_client.update_with_zero_body('/rest/enclosures/09USE133E5H4/configuration', timeout=-1) mock_update.assert_called_once_with( "/rest/enclosures/09USE133E5H4/configuration", None, custom_headers=None) @mock.patch.object(connection, 'put') @mock.patch.object(TaskMonitor, 'wait_for_task') def test_update_with_zero_body_and_custom_headers(self, mock_wait4task, mock_update): mock_update.return_value = self.task, self.task mock_wait4task.return_value = self.task self.resource_client.update_with_zero_body('1', custom_headers=self.custom_headers) mock_update.assert_called_once_with(mock.ANY, mock.ANY, custom_headers={'Accept-Language': 'en_US'}) @mock.patch.object(connection, 'put') @mock.patch.object(TaskMonitor, 'wait_for_task') def test_update_with_zero_body_return_entity(self, mock_wait4task, mock_put): response_body = {"resource_name": "name"} mock_put.return_value = self.task, self.task mock_wait4task.return_value = response_body result = self.resource_client.update_with_zero_body( '/rest/enclosures/09USE133E5H4/configuration', timeout=-1) self.assertEqual(result, response_body) @mock.patch.object(connection, 'put') def test_update_with_zero_body_without_task(self, mock_put): mock_put.return_value = None, self.response_body result = self.resource_client.update_with_zero_body( '/rest/enclosures/09USE133E5H4/configuration', timeout=-1) self.assertEqual(result, self.response_body) @mock.patch.object(connection, 'put') def test_update_with_uri_called_once(self, mock_put): dict_to_update = {"name": "test"} uri = "/rest/resource/test" mock_put.return_value = None, self.response_body response = self.resource_client.update(dict_to_update, uri=uri) self.assertEqual(self.response_body, response) mock_put.assert_called_once_with(uri, dict_to_update, custom_headers=None) @mock.patch.object(connection, 'put') def test_update_with_custom_headers(self, mock_put): dict_to_update = {"name": "test"} mock_put.return_value = None, self.response_body self.resource_client.update(dict_to_update, uri="/path", custom_headers=self.custom_headers) mock_put.assert_called_once_with(mock.ANY, mock.ANY, custom_headers={'Accept-Language': 'en_US'}) @mock.patch.object(connection, 'put') def test_update_with_force(self, mock_put): dict_to_update = {"name": "test"} uri = "/rest/resource/test" mock_put.return_value = None, self.response_body self.resource_client.update(dict_to_update, uri=uri, force=True) expected_uri = "/rest/resource/test?force=True" mock_put.assert_called_once_with(expected_uri, dict_to_update, custom_headers=None) @mock.patch.object(connection, 'put') @mock.patch.object(TaskMonitor, 'wait_for_task') def test_update_uri(self, mock_wait4task, mock_update): dict_to_update = {"resource_data": "resource_data", "uri": "a_uri"} mock_update.return_value = self.task, self.response_body mock_wait4task.return_value = self.task update_task = self.resource_client.update(dict_to_update, False) self.assertEqual(self.task, update_task) mock_update.assert_called_once_with("a_uri", dict_to_update, custom_headers=None) @mock.patch.object(connection, 'put') @mock.patch.object(TaskMonitor, 'wait_for_task') def test_update_return_entity(self, mock_wait4task, mock_put): dict_to_update = { "resource_name": "a name", "uri": "a_uri", } mock_put.return_value = self.task, {} mock_wait4task.return_value = dict_to_update result = self.resource_client.update(dict_to_update, timeout=-1) self.assertEqual(result, dict_to_update) @mock.patch.object(connection, 'post') @mock.patch.object(TaskMonitor, 'wait_for_task') def test_create_with_zero_body_called_once(self, mock_wait4task, mock_post): mock_post.return_value = self.task, self.task mock_wait4task.return_value = self.task self.resource_client.create_with_zero_body('/rest/enclosures/09USE133E5H4/configuration', timeout=-1) mock_post.assert_called_once_with( "/rest/enclosures/09USE133E5H4/configuration", None, custom_headers=None) @mock.patch.object(connection, 'post') @mock.patch.object(TaskMonitor, 'wait_for_task') def test_create_with_zero_body_and_custom_headers(self, mock_wait4task, mock_post): mock_post.return_value = self.task, self.task mock_wait4task.return_value = self.task self.resource_client.create_with_zero_body('1', custom_headers=self.custom_headers) mock_post.assert_called_once_with(mock.ANY, mock.ANY, custom_headers={'Accept-Language': 'en_US'}) @mock.patch.object(connection, 'post') @mock.patch.object(TaskMonitor, 'wait_for_task') def test_create_with_zero_body_return_entity(self, mock_wait4task, mock_post): response_body = {"resource_name": "name"} mock_post.return_value = self.task, self.task mock_wait4task.return_value = response_body result = self.resource_client.create_with_zero_body( '/rest/enclosures/09USE133E5H4/configuration', timeout=-1) self.assertEqual(result, response_body) @mock.patch.object(connection, 'post') def test_create_with_zero_body_without_task(self, mock_post): mock_post.return_value = None, self.response_body result = self.resource_client.create_with_zero_body( '/rest/enclosures/09USE133E5H4/configuration', timeout=-1) self.assertEqual(result, self.response_body) @mock.patch.object(connection, 'post') def test_create_uri(self, mock_post): dict_to_create = {"resource_name": "a name"} mock_post.return_value = {}, {} self.resource_client.create(dict_to_create, timeout=-1) mock_post.assert_called_once_with(self.URI, dict_to_create, custom_headers=None) @mock.patch.object(connection, 'post') def test_create_with_custom_headers(self, mock_post): dict_to_create = {"resource_name": "a name"} mock_post.return_value = {}, {} self.resource_client.create(dict_to_create, custom_headers=self.custom_headers) mock_post.assert_called_once_with(mock.ANY, mock.ANY, custom_headers={'Accept-Language': 'en_US'}) @mock.patch.object(connection, 'post') @mock.patch.object(TaskMonitor, 'wait_for_task') def test_create_return_entity(self, mock_wait4task, mock_post): dict_to_create = { "resource_name": "a name", } created_resource = { "resource_id": "123", "resource_name": "a name", } mock_post.return_value = self.task, {} mock_wait4task.return_value = created_resource result = self.resource_client.create(dict_to_create, -1) self.assertEqual(result, created_resource) @mock.patch.object(connection, 'post') @mock.patch.object(TaskMonitor, 'wait_for_task') def test_wait_for_activity_on_create(self, mock_wait4task, mock_post): mock_post.return_value = self.task, {} mock_wait4task.return_value = self.task self.resource_client.create({"test": "test"}, timeout=60) mock_wait4task.assert_called_once_with({"task": "task"}, 60) @mock.patch.object(connection, 'patch') def test_patch_request_when_id_is_provided(self, mock_patch): request_body = [{ 'op': 'replace', 'path': '/name', 'value': 'new_name', }] mock_patch.return_value = {}, {} self.resource_client.patch( '123a53cz', 'replace', '/name', 'new_name', 70) mock_patch.assert_called_once_with( '/rest/testuri/123a53cz', request_body, custom_headers=None) @mock.patch.object(connection, 'patch') def test_patch_request_when_uri_is_provided(self, mock_patch): request_body = [{ 'op': 'replace', 'path': '/name', 'value': 'new_name', }] mock_patch.return_value = {}, {} self.resource_client.patch( '/rest/testuri/123a53cz', 'replace', '/name', 'new_name', 60) mock_patch.assert_called_once_with( '/rest/testuri/123a53cz', request_body, custom_headers=None) @mock.patch.object(connection, 'patch') def test_patch_with_custom_headers(self, mock_patch): mock_patch.return_value = {}, {} self.resource_client.patch('/rest/testuri/123', 'operation', '/field', 'value', custom_headers=self.custom_headers) mock_patch.assert_called_once_with(mock.ANY, mock.ANY, custom_headers={'Accept-Language': 'en_US'}) @mock.patch.object(connection, 'patch') @mock.patch.object(TaskMonitor, 'wait_for_task') def test_patch_return_entity(self, mock_wait4task, mock_patch): entity = {"resource_id": "123a53cz"} mock_patch.return_value = self.task, self.task mock_wait4task.return_value = entity result = self.resource_client.patch( '123a53cz', 'replace', '/name', 'new_name', -1) self.assertEqual(result, entity) @mock.patch.object(connection, 'patch') @mock.patch.object(TaskMonitor, 'wait_for_task') def test_wait_for_activity_on_patch(self, mock_wait4task, mock_patch): entity = {"resource_id": "123a53cz"} mock_patch.return_value = self.task, self.task mock_wait4task.return_value = entity self.resource_client.patch( '123a53cz', 'replace', '/name', 'new_name', -1) mock_wait4task.assert_called_once_with({"task": "task"}, mock.ANY) def test_delete_with_none(self): try: self.resource_client.delete(None) except ValueError as e: self.assertTrue("Resource" in e.args[0]) else: self.fail() @mock.patch.object(connection, 'delete') def test_delete_with_dict_uri(self, mock_delete): resource = {"uri": "uri"} mock_delete.return_value = {}, {} delete_result = self.resource_client.delete(resource) self.assertTrue(delete_result) mock_delete.assert_called_once_with("uri", custom_headers=None) def test_delete_with_empty_dict(self): try: self.resource_client.delete({}) except ValueError as e: self.assertTrue("Resource" in e.args[0]) else: self.fail() def test_get_with_none(self): try: self.resource_client.get(None) except ValueError as e: self.assertTrue("id" in e.args[0]) else: self.fail() def test_get_collection_with_none(self): try: self.resource_client.get_collection(None) except ValueError as e: self.assertTrue("id" in e.args[0]) else: self.fail() def test_create_with_none(self): try: self.resource_client.create(None) except ValueError as e: self.assertTrue("Resource" in e.args[0]) else: self.fail() def test_create_with_empty_dict(self): try: self.resource_client.create({}) except ValueError as e: self.assertTrue("Resource" in e.args[0]) else: self.fail() def test_update_with_none(self): try: self.resource_client.update(None) except ValueError as e: self.assertTrue("Resource" in e.args[0]) else: self.fail() def test_update_with_empty_dict(self): try: self.resource_client.update({}) except ValueError as e: self.assertTrue("Resource" in e.args[0]) else: self.fail() def test_get_by_with_name_none(self): try: self.resource_client.get_by(None, None) except ValueError as e: self.assertTrue("field" in e.args[0]) else: self.fail() @mock.patch.object(connection, 'get') def test_get_with_uri_should_work(self, mock_get): mock_get.return_value = {} uri = self.URI + "/ad28cf21-8b15-4f92-bdcf-51cb2042db32" self.resource_client.get(uri) mock_get.assert_called_once_with(uri) def test_get_with_uri_with_incompatible_url_shoud_fail(self): message = "Unrecognized URI for this resource" uri = "/rest/interconnects/ad28cf21-8b15-4f92-bdcf-51cb2042db32" try: self.resource_client.get(uri) except HPOneViewUnknownType as exception: self.assertEqual(message, exception.args[0]) else: self.fail("Expected Exception was not raised") def test_get_with_uri_from_another_resource_with_incompatible_url_shoud_fail(self): message = "Unrecognized URI for this resource" uri = "/rest/interconnects/ad28cf21-8b15-4f92-bdcf-51cb2042db32" fake_resource = FakeResource(None) try: fake_resource.get_fake(uri) except HPOneViewUnknownType as exception: self.assertEqual(message, exception.args[0]) else: self.fail("Expected Exception was not raised") @mock.patch.object(connection, 'get') def test_get_utilization_with_args(self, mock_get): self.resource_client.get_utilization('09USE7335NW3', fields='AmbientTemperature,AveragePower,PeakPower', filter='startDate=2016-05-30T03:29:42.361Z', refresh=True, view='day') expected_uri = '/rest/testuri/09USE7335NW3/utilization' \ '?filter=startDate%3D2016-05-30T03%3A29%3A42.361Z' \ '&fields=AmbientTemperature%2CAveragePower%2CPeakPower' \ '&refresh=true' \ '&view=day' mock_get.assert_called_once_with(expected_uri) @mock.patch.object(connection, 'get') def test_get_utilization_with_multiple_filters(self, mock_get): self.resource_client.get_utilization( '09USE7335NW3', fields='AmbientTemperature,AveragePower,PeakPower', filter='startDate=2016-05-30T03:29:42.361Z,endDate=2016-05-31T03:29:42.361Z', refresh=True, view='day') expected_uri = '/rest/testuri/09USE7335NW3/utilization' \ '?filter=startDate%3D2016-05-30T03%3A29%3A42.361Z' \ '&filter=endDate%3D2016-05-31T03%3A29%3A42.361Z' \ '&fields=AmbientTemperature%2CAveragePower%2CPeakPower' \ '&refresh=true' \ '&view=day' mock_get.assert_called_once_with(expected_uri) @mock.patch.object(connection, 'get') def test_get_utilization_by_id_with_defaults(self, mock_get): self.resource_client.get_utilization('09USE7335NW3') expected_uri = '/rest/testuri/09USE7335NW3/utilization' mock_get.assert_called_once_with(expected_uri) @mock.patch.object(connection, 'get') def test_get_utilization_by_uri_with_defaults(self, mock_get): self.resource_client.get_utilization('/rest/testuri/09USE7335NW3') expected_uri = '/rest/testuri/09USE7335NW3/utilization' mock_get.assert_called_once_with(expected_uri) def test_get_utilization_with_empty(self): try: self.resource_client.get_utilization('') except ValueError as exception: self.assertEqual(RESOURCE_CLIENT_INVALID_ID, exception.args[0]) else: self.fail("Expected Exception was not raised") def test_build_uri_with_id_should_work(self): input = '09USE7335NW35' expected_output = '/rest/testuri/09USE7335NW35' result = self.resource_client.build_uri(input) self.assertEqual(expected_output, result) def test_build_uri_with_uri_should_work(self): input = '/rest/testuri/09USE7335NW3' expected_output = '/rest/testuri/09USE7335NW3' result = self.resource_client.build_uri(input) self.assertEqual(expected_output, result) def test_build_uri_with_none_should_raise_exception(self): try: self.resource_client.build_uri(None) except ValueError as exception: self.assertEqual(RESOURCE_CLIENT_INVALID_ID, exception.args[0]) else: self.fail("Expected Exception was not raised") def test_build_uri_with_empty_str_should_raise_exception(self): try: self.resource_client.build_uri('') except ValueError as exception: self.assertEqual(RESOURCE_CLIENT_INVALID_ID, exception.args[0]) else: self.fail("Expected Exception was not raised") def test_build_uri_with_different_resource_uri_should_raise_exception(self): try: self.resource_client.build_uri( '/rest/test/another/resource/uri/09USE7335NW3') except HPOneViewUnknownType as exception: self.assertEqual(UNRECOGNIZED_URI, exception.args[0]) else: self.fail("Expected Exception was not raised") def test_build_uri_with_incomplete_uri_should_raise_exception(self): try: self.resource_client.build_uri('/rest/') except HPOneViewUnknownType as exception: self.assertEqual(UNRECOGNIZED_URI, exception.args[0]) else: self.fail("Expected Exception was not raised")
class Backups(object): """ Backups API client. """ URI = '/rest/backups' def __init__(self, con): self._client = ResourceClient(con, self.URI) def get_all(self): """ Retrieves the details for any current appliance backup. Only one backup file is present on the appliance at any time. Returns: list: A list of Backups. """ return self._client.get_collection(self.URI) def get(self, id_or_uri): """ Gets the details of the specified backup. Args: id_or_uri: ID or URI of the backup Returns: dict: Details of the specified backup. """ return self._client.get(id_or_uri) def create(self, timeout=-1): """ Starts backing up the appliance. After completion, the backup file must be downloaded and saved off-appliance. Appliance backups can be started at any time, and do not require any special setup to prepare the appliance for the backup. Args: timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stop waiting for its completion. Returns: dict: Details of the created backup. """ return self._client.create_with_zero_body(timeout=timeout) def download(self, id_or_uri, file_path): """ Downloads a backup archive previously created on the appliance. Uploaded backup files cannot be downloaded. Args: id_or_uri: ID or URI of the Artifact Bundle. file_path(str): Destination file path. Returns: bool: Successfully downloaded. """ return self._client.download(id_or_uri, file_path) def upload(self, file_path): """ Uploads an appliance backup file in preparation of a restore. Any existing backup on the appliance is removed. After the backup file is uploaded and validated, its details are returned. The URI of the backup can be used to start a restore. Args: file_path (str): The local backup filepath Returns: dict: Details of the uploaded backup. """ return self._client.upload(file_path) def get_config(self): """ Retrieves the details of the backup configuration for the remote server and automatic backup schedule. Args: id_or_uri: ID or URI of the backup Returns: dict: Details of the backup configuration for the remote server and automatic backup schedule. """ return self._client.get('config') def update_config(self, config, timeout=-1): """ Updates the remote server configuration and the automatic backup schedule for backup. Args: config (dict): Object to update. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stop waiting for its completion. Returns: dict: Backup details. """ return self._client.update(config, uri=self.URI + "/config", timeout=timeout) def update_remote_archive(self, save_uri, timeout=-1): """ Saves a backup of the appliance to a previously-configured remote location. Args: save_uri (dict): The URI for saving the backup to a previously configured location. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stop waiting for its completion. Returns: dict: Backup details. """ return self._client.update_with_zero_body(uri=save_uri, timeout=timeout)
class Users(object): """ Users API client. """ URI = '/rest/users' DEFAULT_VALUES = { '200': { 'type': 'UserAndRoles' }, '300': { 'type': 'UserAndRoles' }, '500': { 'type': 'UserAndRoles' } } def __init__(self, con): self._connection = con self._client = ResourceClient(con, self.URI) def get_all(self, start=0, count=-1, filter='', sort=''): """ Gets a paginated collection of Users. The collection is based on optional sorting and filtering and is constrained by start and count parameters. Args: start: The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the first available item. count: The number of resources to return. A count of -1 requests all items. The actual number of items in the response might differ from the requested count if the sum of start and count exceeds the total number of items. filter (list or str): A general filter/query string to narrow the list of items returned. The default is no filter; all resources are returned. sort: The sort order of the returned data set. By default, the sort order is based on create time with the oldest entry first. Returns: list: A list of Users. """ return self._client.get_all(start, count, filter=filter, sort=sort) def delete(self, resource, force=False, timeout=-1): """ Deletes a User. Args: resource: dict object to delete force: If set to true, the operation completes despite any problems with network connectivity or errors on the resource itself. The default is false. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; it just stops waiting for its completion. Returns: bool: Indicates if the resource was successfully deleted. """ return self._client.delete(resource, force=force, timeout=timeout) def create(self, resource, timeout=-1): """ Creates a User. Args: resource (dict): Object to create. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stop waiting for its completion. Returns: dict: Created resource. """ return self._client.create(resource, timeout=timeout, default_values=self.DEFAULT_VALUES) def update(self, resource, timeout=-1): """ Updates a User. Args: resource (dict): Object to update. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stop waiting for its completion. Returns: dict: Updated resource. """ return self._client.update(resource, timeout=timeout, default_values=self.DEFAULT_VALUES, uri=self.URI) def get_by(self, field, value): """ Gets all Users that match the filter. The search is case-insensitive. Args: field: Field name to filter. Accepted values: 'name', 'userName', 'role' value: Value to filter. Returns: list: A list of Users. """ if field == 'userName' or field == 'name': return self._client.get(self.URI + '/' + value) elif field == 'role': value = value.replace(" ", "%20") return self._client.get(self.URI + '/roles/users/' + value)['members'] else: raise HPOneViewException( 'Only userName, name and role can be queried for this resource.' ) def validate_user_name(self, user_name, timeout=-1): """ Verifies if a userName is already in use. Args: user_name: The userName to be verified. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: True if user name is in use, False if it is not. """ uri = self.URI + '/validateLoginName/' + user_name return self._client.create_with_zero_body(uri=uri, timeout=timeout) def validate_full_name(self, full_name, timeout=-1): """ Verifies if a fullName is already in use. Args: full_name: The fullName to be verified. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: True if full name is in use, False if it is not. """ uri = self.URI + '/validateUserName/' + full_name return self._client.create_with_zero_body(uri=uri, timeout=timeout)
class LogicalInterconnects(object): URI = '/rest/logical-interconnects' FIRMWARE_PATH = "/firmware" SNMP_CONFIGURATION_PATH = "/snmp-configuration" PORT_MONITOR_PATH = "/port-monitor" LOCATIONS_PATH = "/locations/interconnects" FORWARDING_INFORMATION_PATH = "/forwarding-information-base" QOS_AGGREGATED_CONFIGURATION = "/qos-aggregated-configuration" locations_uri = "{uri}{locations}".format(uri=URI, locations=LOCATIONS_PATH) def __init__(self, con): self._connection = con self._client = ResourceClient(con, self.URI) def get_all(self, start=0, count=-1, filter='', sort=''): """ Gets a list of logical interconnects based on optional sorting and filtering, and constrained by start and count parameters. Args: start: The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the first available item. count: The number of resources to return. A count of -1 requests all the items. The actual number of items in the response may differ from the requested count if the sum of start and count exceed the total number of items. filter: A general filter/query string to narrow the list of items returned. The default is no filter - all resources are returned. sort: The sort order of the returned data set. By default, the sort order is based on create time, with the oldest entry first. Returns: list: A list of logical interconnects. """ return self._client.get_all(start, count, filter=filter, sort=sort) def get(self, id_or_uri): """ Gets a logical interconnect by ID or by uri Args: id_or_uri: Could be either the logical interconnect id or the logical interconnect uri Returns: dict: The logical interconnect """ return self._client.get(id_or_uri) def get_by_name(self, name): """ Gets a logical interconnect by name. Args: name: Name of the logical interconnect Returns: Logical Interconnect """ logical_interconnects = self._client.get_all() result = [x for x in logical_interconnects if x['name'] == name] return result[0] if result else None def update_compliance(self, id_or_uri, timeout=-1): """ Returns logical interconnects to a consistent state. The current logical interconnect state is compared to the associated logical interconnect group. Any differences identified are corrected, bringing the logical interconnect back to a consistent state. Changes are asynchronously applied to all managed interconnects. Note that if the changes detected involve differences in the interconnect map between the logical interconnect group and the logical interconnect, the process of bringing the logical interconnect back to a consistent state may involve automatically removing existing interconnects from management and/or adding new interconnects for management. Args: id_or_uri: Could be either the resource id or the resource uri timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: Logical Interconnect """ uri = self._client.build_uri(id_or_uri) + "/compliance" return self._client.update_with_zero_body(uri, timeout=timeout) def update_ethernet_settings(self, id_or_uri, configuration, force=False, timeout=-1): """ Updates the Ethernet interconnect settings for the logical interconnect. Args: id_or_uri: Could be either the resource id or the resource uri configuration: Ethernet interconnect settings. force: If set to true the operation completes despite any problems with network connectivity or errors on the resource itself. The default is false. timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: Logical Interconnect """ uri = self._client.build_uri(id_or_uri) + "/ethernetSettings" return self._client.update(configuration, uri=uri, force=force, timeout=timeout) def update_internal_networks(self, id_or_uri, network_uri_list, force=False, timeout=-1): """ Updates internal networks on the logical interconnect. Args: id_or_uri: Could be either the resource id or the resource uri network_uri_list: List of Ethernet network uris. force: If set to true the operation completes despite any problems with network connectivity or errors on the resource itself. The default is false. timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: Logical Interconnect """ uri = self._client.build_uri(id_or_uri) + "/internalNetworks" return self._client.update(network_uri_list, uri=uri, force=force, timeout=timeout) def get_internal_vlans(self, id_or_uri): """ Gets the internal VLAN IDs for the provisioned networks on a logical interconnect. Args: id_or_uri: Could be either the logical interconnect group id or the logical interconnect group uri Returns: dict: Collection of URIs """ uri = self._client.build_uri(id_or_uri) + "/internalVlans" return self._client.get_collection(uri) def update_settings(self, id_or_uri, settings, force=False, timeout=-1): """ Updates interconnect settings on the logical interconnect. Changes to interconnect settings are asynchronously applied to all managed interconnects. Args: id_or_uri: Could be either the resource id or the resource uri settings: Interconnect settings force: If set to true the operation completes despite any problems with network connectivity or errors on the resource itself. The default is false. timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: Logical Interconnect """ data = settings.copy() if 'type' not in data: data['type'] = 'InterconnectSettingsV3' if 'ethernetSettings' in data and 'type' not in data['ethernetSettings']: data['ethernetSettings']['type'] = 'EthernetInterconnectSettingsV3' uri = self._client.build_uri(id_or_uri) + "/settings" return self._client.update(data, uri=uri, force=force, timeout=timeout) def update_configuration(self, id_or_uri, timeout=-1): """ Asynchronously applies or re-applies the logical interconnect configuration to all managed interconnects. Args: id_or_uri: Could be either the resource id or the resource uri timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: Logical Interconnect """ uri = self._client.build_uri(id_or_uri) + "/configuration" return self._client.update_with_zero_body(uri=uri, timeout=timeout) def get_snmp_configuration(self, id_or_uri): """ Gets the SNMP configuration for a logical interconnect. Args: id_or_uri: Could be either the logical interconnect group id or the logical interconnect group uri Returns: dict: SNMP configuration """ uri = self._client.build_uri(id_or_uri) + self.SNMP_CONFIGURATION_PATH return self._client.get(uri) def update_snmp_configuration(self, id_or_uri, configuration, timeout=-1): """ Updates the SNMP configuration of a logical interconnect. Changes to the SNMP configuration are asynchronously applied to all managed interconnects. Args: id_or_uri: Could be either the logical interconnect id or the logical interconnect uri configuration: snmp configuration Returns: dict: snmp configuration """ data = configuration.copy() if 'type' not in data: data['type'] = 'snmp-configuration' uri = self._client.build_uri(id_or_uri) + self.SNMP_CONFIGURATION_PATH return self._client.update(data, uri=uri, timeout=timeout) def get_unassigned_uplink_ports(self, id_or_uri): """ Gets a collection of uplink ports from the member interconnects which are eligible for assignment to an analyzer port. To be eligible a port must be a valid uplink, must not be a member of an existing uplink set and must not currently be used for stacking. Args: id_or_uri: Could be either the logical interconnect group id or the logical interconnect group uri Returns: dict: Collection of uplink ports """ uri = self._client.build_uri(id_or_uri) + "/unassignedUplinkPortsForPortMonitor" return self._client.get_collection(uri) def get_port_monitor(self, id_or_uri): """ Gets the port monitor configuration of a logical interconnect. Args: id_or_uri: Could be either the logical interconnect id or the logical interconnect uri Returns: dict: port monitor configuration """ uri = self._client.build_uri(id_or_uri) + self.PORT_MONITOR_PATH return self._client.get(uri) def update_port_monitor(self, id_or_uri, resource, timeout=-1): """ Updates the port monitor configuration of a logical interconnect. Args: id_or_uri: Could be either the logical interconnect id or the logical interconnect uri resource: port monitor configuration Returns: dict: port monitor configuration """ data = resource.copy() if 'type' not in data: data['type'] = 'port-monitor' uri = self._client.build_uri(id_or_uri) + self.PORT_MONITOR_PATH return self._client.update(data, uri=uri, timeout=timeout) def get_telemetry_configuration(self, telemetry_configuration_uri): """ Gets the telemetry configuration of a logical interconnect. Args: telemetry_configuration_uri: Telemetry Configuration URI Returns: dict: Telemetry configuration """ return self._client.get(telemetry_configuration_uri) def create_interconnect(self, location_entries, timeout=-1): """ Creates an interconnect at the given location. WARN: It does not create the LOGICAL INTERCONNECT itself. It will fail if no interconnect is already present on the specified position. Args: location_entries: dictionary with location entries timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: Created interconnect. """ return self._client.create(location_entries, uri=self.locations_uri, timeout=timeout) def delete_interconnect(self, enclosure_uri, bay, timeout=-1): """ Deletes an interconnect from a location. WARN: This won't delete the LOGICAL INTERCONNECT itself, and may cause inconsistency between the enclosure and Logical Interconnect Group. Args: enclosure_uri: URI of the Enclosure bay: Bay timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: bool: indicating if the interconnect was successfully deleted. """ uri = "{path}?location=Enclosure:{enclosure_uri},Bay:{bay}".format(path=self.LOCATIONS_PATH, enclosure_uri=enclosure_uri, bay=bay) return self._client.delete(uri, timeout=timeout) def get_firmware(self, id_or_uri): """ Gets the installed firmware for a logical interconnect. Args: id_or_uri: Could be either the logical interconnect id or the logical interconnect uri Returns: dict: LIFirmware """ firmware_uri = self.__build_firmware_uri(id_or_uri) return self._client.get(firmware_uri) def install_firmware(self, firmware_information, id_or_uri): """ Installs firmware to a logical interconnect. The three operations that are supported for the firmware update are Stage (uploads firmware to the interconnect), Activate (installs firmware on the interconnect) and Update (which does a Stage and Activate in a sequential manner). Returns: dict: """ firmware_uri = self.__build_firmware_uri(id_or_uri) return self._client.update(firmware_information, firmware_uri) def get_forwarding_information_base(self, id_or_uri, filter=''): """ Gets the forwarding information base data for a logical interconnect. Maximum of 100 entries is returned. Optional filtering criteria may be specified. Args: id_or_uri: Could be either the logical interconnect id or the logical interconnect uri. filter: Filtering criteria may be specified using supported attributes: interconnectUri, macAddress, internalVlan, externalVlan, and supported relation = (Equals). macAddress is 12 hexadecimal digits with a colon between each pair of digits.(upper or lower case). The default is no filter - all resources are returned. Returns: list: A set of interconnect MAC address entries. """ uri = self._client.build_uri(id_or_uri) + self.FORWARDING_INFORMATION_PATH return self._client.get_collection(uri, filter=filter) def create_forwarding_information_base(self, id_or_uri, timeout=-1): """ Generates the forwarding information base dump file for a logical interconnect. Args: id_or_uri: Could be either the logical interconnect id or the logical interconnect uri. timeout: Timeout in seconds. Wait task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: Interconnect Forwarding Information Base DataInfo """ uri = self._client.build_uri(id_or_uri) + self.FORWARDING_INFORMATION_PATH return self._client.create_with_zero_body(uri=uri, timeout=timeout) def get_qos_aggregated_configuration(self, id_or_uri): """ Gets the QoS aggregated configuration for the logical interconnect. Args: id_or_uri: Could be either the logical interconnect id or the logical interconnect uri. Returns: dict: QoS Configuration """ uri = self._client.build_uri(id_or_uri) + self.QOS_AGGREGATED_CONFIGURATION return self._client.get(uri) def update_qos_aggregated_configuration(self, id_or_uri, qos_configuration, timeout=-1): """ Updates the QoS aggregated configuration for the logical interconnect. Args: id_or_uri: Could be either the logical interconnect id or the logical interconnect uri. qos_configuration: QOS configuration. Returns: dict: Logical Interconnect """ uri = self._client.build_uri(id_or_uri) + self.QOS_AGGREGATED_CONFIGURATION return self._client.update(qos_configuration, uri=uri, timeout=timeout) def __build_firmware_uri(self, id_or_uri): return self._client.build_uri(id_or_uri) + self.FIRMWARE_PATH
class ResourceTest(unittest.TestCase): URI = "/rest/testuri" def setUp(self): super(ResourceTest, self).setUp() self.host = '127.0.0.1' self.connection = connection(self.host) self.resource_client = ResourceClient(self.connection, self.URI) self.task = {"task": "task"} self.response_body = {"body": "body"} self.custom_headers = {'Accept-Language': 'en_US'} @mock.patch.object(connection, 'get') def test_get_all_called_once(self, mock_get): filter = "'name'='OneViewSDK \"Test FC Network'" sort = 'name:ascending' query = "name NE 'WrongName'" view = '"{view-name}"' mock_get.return_value = {"members": [{"member": "member"}]} result = self.resource_client.get_all(1, 500, filter, query, sort, view, 'name,owner,modified') uri = '{resource_uri}?start=1' \ '&count=500' \ '&filter=%27name%27%3D%27OneViewSDK%20%22Test%20FC%20Network%27' \ '&query=name%20NE%20%27WrongName%27' \ '&sort=name%3Aascending' \ '&view=%22%7Bview-name%7D%22' \ '&fields=name%2Cowner%2Cmodified'.format(resource_uri=self.URI) self.assertEqual([{'member': 'member'}], result) mock_get.assert_called_once_with(uri) @mock.patch.object(connection, 'get') def test_get_all_with_defaults(self, mock_get): self.resource_client.get_all() uri = "{resource_uri}?start=0&count=-1".format(resource_uri=self.URI) mock_get.assert_called_once_with(uri) @mock.patch.object(connection, 'get') def test_get_all_with_custom_uri(self, mock_get): self.resource_client.get_all(uri='/rest/testuri/12467836/subresources') uri = "/rest/testuri/12467836/subresources?start=0&count=-1" mock_get.assert_called_once_with(uri) @mock.patch.object(connection, 'get') def test_get_all_with_different_resource_uri_should_fail(self, mock_get): try: self.resource_client.get_all( uri='/rest/other/resource/12467836/subresources') except HPOneViewUnknownType as e: self.assertEqual(UNRECOGNIZED_URI, e.args[0]) else: self.fail('Expected Exception was not raised') @mock.patch.object(connection, 'get') def test_get_all_should_do_multi_requests_when_response_paginated( self, mock_get): uri_list = [ '/rest/testuri?start=0&count=-1', '/rest/testuri?start=3&count=3', '/rest/testuri?start=6&count=3' ] results = [{ 'nextPageUri': uri_list[1], 'members': [{ 'id': '1' }, { 'id': '2' }, { 'id': '3' }] }, { 'nextPageUri': uri_list[2], 'members': [{ 'id': '4' }, { 'id': '5' }, { 'id': '6' }] }, { 'nextPageUri': None, 'members': [{ 'id': '7' }, { 'id': '8' }] }] mock_get.side_effect = results self.resource_client.get_all() expected_calls = [ call(uri_list[0]), call(uri_list[1]), call(uri_list[2]) ] self.assertEqual(mock_get.call_args_list, expected_calls) @mock.patch.object(connection, 'get') def test_get_all_with_count_should_do_multi_requests_when_response_paginated( self, mock_get): uri_list = [ '/rest/testuri?start=0&count=15', '/rest/testuri?start=3&count=3', '/rest/testuri?start=6&count=3' ] results = [{ 'nextPageUri': uri_list[1], 'members': [{ 'id': '1' }, { 'id': '2' }, { 'id': '3' }] }, { 'nextPageUri': uri_list[2], 'members': [{ 'id': '4' }, { 'id': '5' }, { 'id': '6' }] }, { 'nextPageUri': None, 'members': [{ 'id': '7' }, { 'id': '8' }] }] mock_get.side_effect = results self.resource_client.get_all(count=15) expected_calls = [ call(uri_list[0]), call(uri_list[1]), call(uri_list[2]) ] self.assertEqual(mock_get.call_args_list, expected_calls) @mock.patch.object(connection, 'get') def test_get_all_should_return_all_items_when_response_paginated( self, mock_get): uri_list = [ '/rest/testuri?start=0&count=-1', '/rest/testuri?start=3&count=3', '/rest/testuri?start=6&count=1' ] results = [{ 'nextPageUri': uri_list[1], 'members': [{ 'id': '1' }, { 'id': '2' }, { 'id': '3' }] }, { 'nextPageUri': uri_list[2], 'members': [{ 'id': '4' }, { 'id': '5' }, { 'id': '6' }] }, { 'nextPageUri': None, 'members': [{ 'id': '7' }] }] mock_get.side_effect = results result = self.resource_client.get_all() expected_items = [{ 'id': '1' }, { 'id': '2' }, { 'id': '3' }, { 'id': '4' }, { 'id': '5' }, { 'id': '6' }, { 'id': '7' }] self.assertSequenceEqual(result, expected_items) @mock.patch.object(connection, 'get') def test_get_all_with_count_should_return_all_items_when_response_paginated( self, mock_get): uri_list = [ '/rest/testuri?start=0&count=15', '/rest/testuri?start=3&count=3', '/rest/testuri?start=6&count=1' ] results = [{ 'nextPageUri': uri_list[1], 'members': [{ 'id': '1' }, { 'id': '2' }, { 'id': '3' }] }, { 'nextPageUri': uri_list[2], 'members': [{ 'id': '4' }, { 'id': '5' }, { 'id': '6' }] }, { 'nextPageUri': None, 'members': [{ 'id': '7' }] }] mock_get.side_effect = results result = self.resource_client.get_all(count=15) expected_items = [{ 'id': '1' }, { 'id': '2' }, { 'id': '3' }, { 'id': '4' }, { 'id': '5' }, { 'id': '6' }, { 'id': '7' }] self.assertSequenceEqual(result, expected_items) @mock.patch.object(connection, 'get') def test_get_all_should_return_empty_list_when_response_has_no_items( self, mock_get): mock_get.return_value = {'nextPageUri': None, 'members': []} result = self.resource_client.get_all() self.assertEqual(result, []) @mock.patch.object(connection, 'delete') @mock.patch.object(TaskMonitor, 'wait_for_task') def test_delete_by_id_called_once(self, mock_wait4task, mock_delete): mock_delete.return_value = self.task, self.response_body mock_wait4task.return_value = self.task delete_task = self.resource_client.delete('1', force=True, timeout=-1) self.assertEqual(self.task, delete_task) mock_delete.assert_called_once_with(self.URI + "/1?force=True", custom_headers=None) @mock.patch.object(connection, 'delete') @mock.patch.object(TaskMonitor, 'wait_for_task') def test_delete_with_custom_headers(self, mock_wait4task, mock_delete): mock_delete.return_value = self.task, self.response_body mock_wait4task.return_value = self.task self.resource_client.delete('1', custom_headers=self.custom_headers) mock_delete.assert_called_once_with( mock.ANY, custom_headers={'Accept-Language': 'en_US'}) def test_delete_dict_invalid_uri(self): dict_to_delete = {"task": "task", "uri": ""} try: self.resource_client.delete(dict_to_delete, False, -1) except HPOneViewUnknownType as e: self.assertEqual("Unknown object type", e.args[0]) else: self.fail() @mock.patch.object(connection, 'get') def test_get_schema_uri(self, mock_get): self.resource_client.get_schema() mock_get.assert_called_once_with(self.URI + "/schema") @mock.patch.object(connection, 'get') def test_get_by_id_uri(self, mock_get): self.resource_client.get('12345') mock_get.assert_called_once_with(self.URI + "/12345") @mock.patch.object(ResourceClient, 'get_by') def test_get_by_name_with_result(self, mock_get_by): mock_get_by.return_value = [{"name": "value"}] response = self.resource_client.get_by_name('Resource Name,') self.assertEqual(response, {"name": "value"}) mock_get_by.assert_called_once_with("name", 'Resource Name,') @mock.patch.object(ResourceClient, 'get_by') def test_get_by_name_without_result(self, mock_get_by): mock_get_by.return_value = [] response = self.resource_client.get_by_name('Resource Name,') self.assertIsNone(response) mock_get_by.assert_called_once_with("name", 'Resource Name,') @mock.patch.object(connection, 'get') def test_get_collection_uri(self, mock_get): mock_get.return_value = { "members": [{ "key": "value" }, { "key": "value" }] } self.resource_client.get_collection('12345') mock_get.assert_called_once_with(self.URI + "/12345") @mock.patch.object(connection, 'get') def test_get_collection_with_filter(self, mock_get): mock_get.return_value = {} self.resource_client.get_collection('12345', 'name=name') mock_get.assert_called_once_with(self.URI + "/12345?filter=name%3Dname") @mock.patch.object(connection, 'get') def test_get_collection_should_return_list(self, mock_get): mock_get.return_value = { "members": [{ "key": "value" }, { "key": "value" }] } collection = self.resource_client.get_collection('12345') self.assertEqual(len(collection), 2) @mock.patch.object(ResourceClient, 'get_all') def test_get_by_property(self, mock_get_all): self.resource_client.get_by('name', 'MyFibreNetwork') mock_get_all.assert_called_once_with( filter="\"'name'='MyFibreNetwork'\"", uri='/rest/testuri') @mock.patch.object(ResourceClient, 'get_all') def test_get_by_property_with_uri(self, mock_get_all): self.resource_client.get_by('name', 'MyFibreNetwork', uri='/rest/testuri/5435534/sub') mock_get_all.assert_called_once_with( filter="\"'name'='MyFibreNetwork'\"", uri='/rest/testuri/5435534/sub') @mock.patch.object(ResourceClient, 'get_all') def test_get_by_property_with__invalid_uri(self, mock_get_all): try: self.resource_client.get_by('name', 'MyFibreNetwork', uri='/rest/other/5435534/sub') except HPOneViewUnknownType as e: self.assertEqual('Unrecognized URI for this resource', e.args[0]) else: self.fail() @mock.patch.object(connection, 'put') @mock.patch.object(TaskMonitor, 'wait_for_task') def test_update_with_zero_body_called_once(self, mock_wait4task, mock_update): mock_update.return_value = self.task, self.task mock_wait4task.return_value = self.task self.resource_client.update_with_zero_body( '/rest/enclosures/09USE133E5H4/configuration', timeout=-1) mock_update.assert_called_once_with( "/rest/enclosures/09USE133E5H4/configuration", None, custom_headers=None) @mock.patch.object(connection, 'put') @mock.patch.object(TaskMonitor, 'wait_for_task') def test_update_with_zero_body_and_custom_headers(self, mock_wait4task, mock_update): mock_update.return_value = self.task, self.task mock_wait4task.return_value = self.task self.resource_client.update_with_zero_body( '1', custom_headers=self.custom_headers) mock_update.assert_called_once_with( mock.ANY, mock.ANY, custom_headers={'Accept-Language': 'en_US'}) @mock.patch.object(connection, 'put') @mock.patch.object(TaskMonitor, 'wait_for_task') def test_update_with_zero_body_return_entity(self, mock_wait4task, mock_put): response_body = {"resource_name": "name"} mock_put.return_value = self.task, self.task mock_wait4task.return_value = response_body result = self.resource_client.update_with_zero_body( '/rest/enclosures/09USE133E5H4/configuration', timeout=-1) self.assertEqual(result, response_body) @mock.patch.object(connection, 'put') def test_update_with_zero_body_without_task(self, mock_put): mock_put.return_value = None, self.response_body result = self.resource_client.update_with_zero_body( '/rest/enclosures/09USE133E5H4/configuration', timeout=-1) self.assertEqual(result, self.response_body) @mock.patch.object(connection, 'put') def test_update_with_uri_called_once(self, mock_put): dict_to_update = {"name": "test"} uri = "/rest/resource/test" mock_put.return_value = None, self.response_body response = self.resource_client.update(dict_to_update, uri=uri) self.assertEqual(self.response_body, response) mock_put.assert_called_once_with(uri, dict_to_update, custom_headers=None) @mock.patch.object(connection, 'put') def test_update_with_custom_headers(self, mock_put): dict_to_update = {"name": "test"} mock_put.return_value = None, self.response_body self.resource_client.update(dict_to_update, uri="/path", custom_headers=self.custom_headers) mock_put.assert_called_once_with( mock.ANY, mock.ANY, custom_headers={'Accept-Language': 'en_US'}) @mock.patch.object(connection, 'put') def test_update_with_force(self, mock_put): dict_to_update = {"name": "test"} uri = "/rest/resource/test" mock_put.return_value = None, self.response_body self.resource_client.update(dict_to_update, uri=uri, force=True) expected_uri = "/rest/resource/test?force=True" mock_put.assert_called_once_with(expected_uri, dict_to_update, custom_headers=None) @mock.patch.object(connection, 'put') @mock.patch.object(TaskMonitor, 'wait_for_task') def test_update_uri(self, mock_wait4task, mock_update): dict_to_update = {"resource_data": "resource_data", "uri": "a_uri"} mock_update.return_value = self.task, self.response_body mock_wait4task.return_value = self.task update_task = self.resource_client.update(dict_to_update, False) self.assertEqual(self.task, update_task) mock_update.assert_called_once_with("a_uri", dict_to_update, custom_headers=None) @mock.patch.object(connection, 'put') @mock.patch.object(TaskMonitor, 'wait_for_task') def test_update_return_entity(self, mock_wait4task, mock_put): dict_to_update = { "resource_name": "a name", "uri": "a_uri", } mock_put.return_value = self.task, {} mock_wait4task.return_value = dict_to_update result = self.resource_client.update(dict_to_update, timeout=-1) self.assertEqual(result, dict_to_update) @mock.patch.object(connection, 'post') @mock.patch.object(TaskMonitor, 'wait_for_task') def test_create_with_zero_body_called_once(self, mock_wait4task, mock_post): mock_post.return_value = self.task, self.task mock_wait4task.return_value = self.task self.resource_client.create_with_zero_body( '/rest/enclosures/09USE133E5H4/configuration', timeout=-1) mock_post.assert_called_once_with( "/rest/enclosures/09USE133E5H4/configuration", None, custom_headers=None) @mock.patch.object(connection, 'post') @mock.patch.object(TaskMonitor, 'wait_for_task') def test_create_with_zero_body_and_custom_headers(self, mock_wait4task, mock_post): mock_post.return_value = self.task, self.task mock_wait4task.return_value = self.task self.resource_client.create_with_zero_body( '1', custom_headers=self.custom_headers) mock_post.assert_called_once_with( mock.ANY, mock.ANY, custom_headers={'Accept-Language': 'en_US'}) @mock.patch.object(connection, 'post') @mock.patch.object(TaskMonitor, 'wait_for_task') def test_create_with_zero_body_return_entity(self, mock_wait4task, mock_post): response_body = {"resource_name": "name"} mock_post.return_value = self.task, self.task mock_wait4task.return_value = response_body result = self.resource_client.create_with_zero_body( '/rest/enclosures/09USE133E5H4/configuration', timeout=-1) self.assertEqual(result, response_body) @mock.patch.object(connection, 'post') def test_create_with_zero_body_without_task(self, mock_post): mock_post.return_value = None, self.response_body result = self.resource_client.create_with_zero_body( '/rest/enclosures/09USE133E5H4/configuration', timeout=-1) self.assertEqual(result, self.response_body) @mock.patch.object(connection, 'post') def test_create_uri(self, mock_post): dict_to_create = {"resource_name": "a name"} mock_post.return_value = {}, {} self.resource_client.create(dict_to_create, timeout=-1) mock_post.assert_called_once_with(self.URI, dict_to_create, custom_headers=None) @mock.patch.object(connection, 'post') def test_create_with_custom_headers(self, mock_post): dict_to_create = {"resource_name": "a name"} mock_post.return_value = {}, {} self.resource_client.create(dict_to_create, custom_headers=self.custom_headers) mock_post.assert_called_once_with( mock.ANY, mock.ANY, custom_headers={'Accept-Language': 'en_US'}) @mock.patch.object(connection, 'post') @mock.patch.object(TaskMonitor, 'wait_for_task') def test_create_return_entity(self, mock_wait4task, mock_post): dict_to_create = { "resource_name": "a name", } created_resource = { "resource_id": "123", "resource_name": "a name", } mock_post.return_value = self.task, {} mock_wait4task.return_value = created_resource result = self.resource_client.create(dict_to_create, -1) self.assertEqual(result, created_resource) @mock.patch.object(connection, 'post') @mock.patch.object(TaskMonitor, 'wait_for_task') def test_wait_for_activity_on_create(self, mock_wait4task, mock_post): mock_post.return_value = self.task, {} mock_wait4task.return_value = self.task self.resource_client.create({"test": "test"}, timeout=60) mock_wait4task.assert_called_once_with({"task": "task"}, 60) @mock.patch.object(connection, 'patch') def test_patch_request_when_id_is_provided(self, mock_patch): request_body = [{ 'op': 'replace', 'path': '/name', 'value': 'new_name', }] mock_patch.return_value = {}, {} self.resource_client.patch('123a53cz', 'replace', '/name', 'new_name', 70) mock_patch.assert_called_once_with('/rest/testuri/123a53cz', request_body, custom_headers=None) @mock.patch.object(connection, 'patch') def test_patch_request_when_uri_is_provided(self, mock_patch): request_body = [{ 'op': 'replace', 'path': '/name', 'value': 'new_name', }] mock_patch.return_value = {}, {} self.resource_client.patch('/rest/testuri/123a53cz', 'replace', '/name', 'new_name', 60) mock_patch.assert_called_once_with('/rest/testuri/123a53cz', request_body, custom_headers=None) @mock.patch.object(connection, 'patch') def test_patch_with_custom_headers(self, mock_patch): mock_patch.return_value = {}, {} self.resource_client.patch('/rest/testuri/123', 'operation', '/field', 'value', custom_headers=self.custom_headers) mock_patch.assert_called_once_with( mock.ANY, mock.ANY, custom_headers={'Accept-Language': 'en_US'}) @mock.patch.object(connection, 'patch') @mock.patch.object(TaskMonitor, 'wait_for_task') def test_patch_return_entity(self, mock_wait4task, mock_patch): entity = {"resource_id": "123a53cz"} mock_patch.return_value = self.task, self.task mock_wait4task.return_value = entity result = self.resource_client.patch('123a53cz', 'replace', '/name', 'new_name', -1) self.assertEqual(result, entity) @mock.patch.object(connection, 'patch') @mock.patch.object(TaskMonitor, 'wait_for_task') def test_wait_for_activity_on_patch(self, mock_wait4task, mock_patch): entity = {"resource_id": "123a53cz"} mock_patch.return_value = self.task, self.task mock_wait4task.return_value = entity self.resource_client.patch('123a53cz', 'replace', '/name', 'new_name', -1) mock_wait4task.assert_called_once_with({"task": "task"}, mock.ANY) def test_delete_with_none(self): try: self.resource_client.delete(None) except ValueError as e: self.assertTrue("Resource" in e.args[0]) else: self.fail() @mock.patch.object(connection, 'delete') def test_delete_with_dict_uri(self, mock_delete): resource = {"uri": "uri"} mock_delete.return_value = {}, {} delete_result = self.resource_client.delete(resource) self.assertTrue(delete_result) mock_delete.assert_called_once_with("uri", custom_headers=None) def test_delete_with_empty_dict(self): try: self.resource_client.delete({}) except ValueError as e: self.assertTrue("Resource" in e.args[0]) else: self.fail() def test_get_with_none(self): try: self.resource_client.get(None) except ValueError as e: self.assertTrue("id" in e.args[0]) else: self.fail() def test_get_collection_with_none(self): try: self.resource_client.get_collection(None) except ValueError as e: self.assertTrue("id" in e.args[0]) else: self.fail() def test_create_with_none(self): try: self.resource_client.create(None) except ValueError as e: self.assertTrue("Resource" in e.args[0]) else: self.fail() def test_create_with_empty_dict(self): try: self.resource_client.create({}) except ValueError as e: self.assertTrue("Resource" in e.args[0]) else: self.fail() def test_update_with_none(self): try: self.resource_client.update(None) except ValueError as e: self.assertTrue("Resource" in e.args[0]) else: self.fail() def test_update_with_empty_dict(self): try: self.resource_client.update({}) except ValueError as e: self.assertTrue("Resource" in e.args[0]) else: self.fail() def test_get_by_with_name_none(self): try: self.resource_client.get_by(None, None) except ValueError as e: self.assertTrue("field" in e.args[0]) else: self.fail() @mock.patch.object(connection, 'get') def test_get_with_uri_should_work(self, mock_get): mock_get.return_value = {} uri = self.URI + "/ad28cf21-8b15-4f92-bdcf-51cb2042db32" self.resource_client.get(uri) mock_get.assert_called_once_with(uri) def test_get_with_uri_with_incompatible_url_shoud_fail(self): message = "Unrecognized URI for this resource" uri = "/rest/interconnects/ad28cf21-8b15-4f92-bdcf-51cb2042db32" try: self.resource_client.get(uri) except HPOneViewUnknownType as exception: self.assertEqual(message, exception.args[0]) else: self.fail("Expected Exception was not raised") def test_get_with_uri_from_another_resource_with_incompatible_url_shoud_fail( self): message = "Unrecognized URI for this resource" uri = "/rest/interconnects/ad28cf21-8b15-4f92-bdcf-51cb2042db32" fake_resource = FakeResource(None) try: fake_resource.get_fake(uri) except HPOneViewUnknownType as exception: self.assertEqual(message, exception.args[0]) else: self.fail("Expected Exception was not raised") @mock.patch.object(connection, 'get') def test_get_utilization_with_args(self, mock_get): self.resource_client.get_utilization( '09USE7335NW3', fields='AmbientTemperature,AveragePower,PeakPower', filter='startDate=2016-05-30T03:29:42.361Z', refresh=True, view='day') expected_uri = '/rest/testuri/09USE7335NW3/utilization' \ '?filter=startDate%3D2016-05-30T03%3A29%3A42.361Z' \ '&fields=AmbientTemperature%2CAveragePower%2CPeakPower' \ '&refresh=true' \ '&view=day' mock_get.assert_called_once_with(expected_uri) @mock.patch.object(connection, 'get') def test_get_utilization_with_multiple_filters(self, mock_get): self.resource_client.get_utilization( '09USE7335NW3', fields='AmbientTemperature,AveragePower,PeakPower', filter= 'startDate=2016-05-30T03:29:42.361Z,endDate=2016-05-31T03:29:42.361Z', refresh=True, view='day') expected_uri = '/rest/testuri/09USE7335NW3/utilization' \ '?filter=startDate%3D2016-05-30T03%3A29%3A42.361Z' \ '&filter=endDate%3D2016-05-31T03%3A29%3A42.361Z' \ '&fields=AmbientTemperature%2CAveragePower%2CPeakPower' \ '&refresh=true' \ '&view=day' mock_get.assert_called_once_with(expected_uri) @mock.patch.object(connection, 'get') def test_get_utilization_by_id_with_defaults(self, mock_get): self.resource_client.get_utilization('09USE7335NW3') expected_uri = '/rest/testuri/09USE7335NW3/utilization' mock_get.assert_called_once_with(expected_uri) @mock.patch.object(connection, 'get') def test_get_utilization_by_uri_with_defaults(self, mock_get): self.resource_client.get_utilization('/rest/testuri/09USE7335NW3') expected_uri = '/rest/testuri/09USE7335NW3/utilization' mock_get.assert_called_once_with(expected_uri) def test_get_utilization_with_empty(self): try: self.resource_client.get_utilization('') except ValueError as exception: self.assertEqual(RESOURCE_CLIENT_INVALID_ID, exception.args[0]) else: self.fail("Expected Exception was not raised") def test_build_uri_with_id_should_work(self): input = '09USE7335NW35' expected_output = '/rest/testuri/09USE7335NW35' result = self.resource_client.build_uri(input) self.assertEqual(expected_output, result) def test_build_uri_with_uri_should_work(self): input = '/rest/testuri/09USE7335NW3' expected_output = '/rest/testuri/09USE7335NW3' result = self.resource_client.build_uri(input) self.assertEqual(expected_output, result) def test_build_uri_with_none_should_raise_exception(self): try: self.resource_client.build_uri(None) except ValueError as exception: self.assertEqual(RESOURCE_CLIENT_INVALID_ID, exception.args[0]) else: self.fail("Expected Exception was not raised") def test_build_uri_with_empty_str_should_raise_exception(self): try: self.resource_client.build_uri('') except ValueError as exception: self.assertEqual(RESOURCE_CLIENT_INVALID_ID, exception.args[0]) else: self.fail("Expected Exception was not raised") def test_build_uri_with_different_resource_uri_should_raise_exception( self): try: self.resource_client.build_uri( '/rest/test/another/resource/uri/09USE7335NW3') except HPOneViewUnknownType as exception: self.assertEqual(UNRECOGNIZED_URI, exception.args[0]) else: self.fail("Expected Exception was not raised") def test_build_uri_with_incomplete_uri_should_raise_exception(self): try: self.resource_client.build_uri('/rest/') except HPOneViewUnknownType as exception: self.assertEqual(UNRECOGNIZED_URI, exception.args[0]) else: self.fail("Expected Exception was not raised")
class Backups(object): """ Backups API client. """ URI = '/rest/backups' def __init__(self, con): self._client = ResourceClient(con, self.URI) def get_all(self): """ Retrieves the details for any current appliance backup. Only one backup file is present on the appliance at any time. Returns: list: A list of Backups. """ return self._client.get_collection(self.URI) def get(self, id_or_uri): """ Gets the details of the specified backup. Args: id_or_uri: ID or URI of the backup Returns: dict: Details of the specified backup. """ return self._client.get(id_or_uri) def create(self, timeout=-1): """ Starts backing up the appliance. After completion, the backup file must be downloaded and saved off-appliance. Appliance backups can be started at any time, and do not require any special setup to prepare the appliance for the backup. Args: timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stop waiting for its completion. Returns: dict: Details of the created backup. """ return self._client.create_with_zero_body(timeout=timeout) def download(self, id_or_uri, file_path): """ Downloads a backup archive previously created on the appliance. Uploaded backup files cannot be downloaded. Args: id_or_uri: ID or URI of the Artifact Bundle. file_path(str): Destination file path. Returns: bool: Successfully downloaded. """ return self._client.download(id_or_uri, file_path) def upload(self, file_path): """ Uploads an appliance backup file in preparation of a restore. Any existing backup on the appliance is removed. After the backup file is uploaded and validated, its details are returned. The URI of the backup can be used to start a restore. Args: file_path (str): The local backup filepath Returns: dict: Details of the uploaded backup. """ return self._client.upload(file_path) def get_config(self): """ Retrieves the details of the backup configuration for the remote server and automatic backup schedule. Args: id_or_uri: ID or URI of the backup Returns: dict: Details of the backup configuration for the remote server and automatic backup schedule. """ return self._client.get('config') def update_config(self, config, timeout=-1): """ Updates the remote server configuration and the automatic backup schedule for backup. Args: config (dict): Object to update. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stop waiting for its completion. Returns: dict: Backup details. """ return self._client.update(config, uri=self.URI + "/config", timeout=timeout) def update_remote_archive(self, save_uri, timeout=-1): """ Saves a backup of the appliance to a previously-configured remote location. Args: save_uri (dict): The URI for saving the backup to a previously configured location. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stop waiting for its completion. Returns: dict: Backup details. """ return self._client.update_with_zero_body(uri=save_uri, timeout=timeout)
class ManagedSANs(object): """ Managed SANs API client. """ URI = '/rest/fc-sans/managed-sans' def __init__(self, con): self._connection = con self._client = ResourceClient(con, self.URI) def get_all(self, start=0, count=-1, query='', sort=''): """ Retrieves the list of registered Managed SANs Args: start: The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the first available item. count: The number of resources to return. A count of -1 requests all items. The actual number of items in the response may differ from the requested count if the sum of start and count exceed the total number of items. query: A general query string to narrow the list of resources returned. The default is no query - all resources are returned. sort: The sort order of the returned data set. By default, the sort order is based on create time with the oldest entry first. Returns: list: A list of Managed SANs """ return self._client.get_all(start=start, count=count, query=query, sort=sort) def get_by_name(self, name): """ Gets a Managed SAN by name. Args: name: Name of the Managed SAN Returns: dict: Managed SAN. """ managed_sans = self._client.get_all() result = [x for x in managed_sans if x['name'] == name] return result[0] if result else None def get(self, id_or_uri): """ Retrieves a single Managed SAN by ID or URI. Args: id_or_uri: Can be either the Managed SAN resource ID or URI. Returns: dict: The Managed SAN resource. """ return self._client.get(id_or_uri=id_or_uri) def update(self, id_or_uri, data, timeout=-1): """ Updates a Managed SAN. It's possible to: - Refresh the Managed SAN. - Update the Managed SAN's publicAttributes. - Update the Managed SAN's policy. Args: id_or_uri: Can be either the Managed SAN resource ID or URI. data: dict object to update timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stop waiting for its completion. Returns: dict: SanResponse """ uri = self._client.build_uri(id_or_uri) return self._client.update(data, uri=uri, timeout=timeout) def get_endpoints(self, managed_san_id_or_uri, start=0, count=-1, filter='', sort=''): """ Gets a list of endpoints in a SAN identified by ID. Args: managed_san_id_or_uri: Can be either the Managed SAN ID or URI. start: The first item to return, using 0-based indexing. If not specified, the default is 0 - start with the first available item. count: The number of resources to return. A count of -1 requests all items. The actual number of items in the response might differ from the requested count if the sum of start and count exceeds the total number of items. filter (list or str): A general filter/query string to narrow the list of items returned. The default is no filter; all resources are returned. sort: The sort order of the returned data set. By default, the sort order is based on create time with the oldest entry first. Returns: list: A list of endpoints. """ uri = self._client.build_uri(managed_san_id_or_uri) + "/endpoints/" return self._client.get_all(start, count, filter=filter, sort=sort, uri=uri) def create_endpoints_csv_file(self, managed_san_id_or_uri, timeout=-1): """ Creates an endpoints CSV file for a SAN. Args: managed_san_id_or_uri: Can be either the Managed SAN ID or URI. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: dict: Endpoint CSV File Response. """ uri = self._client.build_uri(managed_san_id_or_uri) + '/endpoints/' return self._client.create_with_zero_body(uri=uri, timeout=timeout) def create_issues_report(self, managed_san_id_or_uri, timeout=-1): """ Creates an unexpected zoning report for a SAN. Args: managed_san_id_or_uri: Can be either the Managed SAN ID or URI. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: list: A list of FCIssueResponse dict. """ uri = self._client.build_uri(managed_san_id_or_uri) + '/issues/' return self._client.create_report(uri=uri, timeout=timeout) def get_wwn(self, wwn): """ Retrieves a list of associations between provided WWNs and the SANs (if any) on which they reside. Note: This method is available for API version 300 or later. Args: wwn (str): The WWN that may be associated with the SAN. Returns: list: Associations between provided WWNs and the SANs """ uri = '/rest/fc-sans/managed-sans?locate=' + wwn return self._client.get(uri)