def test_get_lun(self, mock_request): mock_request.side_effect = [etree.XML(response_no_lun), etree.XML(response_lun)] ret = self.client._get_first_available_lun_for_host("fakehost") self.assertEqual(1, ret) ret = self.client._get_first_available_lun_for_host("fakehost") self.assertEqual(2, ret)
def test_get_iscsi_portals(self, mock_request): portals = {'10.0.0.12': 'Up', '10.0.0.11': 'Up'} mock_request.side_effect = [etree.XML(response_ports_linear), etree.XML(response_ports_virtual)] ret = self.client.get_active_iscsi_target_portals() self.assertEqual(portals, ret) ret = self.client.get_active_iscsi_target_portals() self.assertEqual(portals, ret)
def test_list_luns_for_host(self, mock_request): mock_request.side_effect = [etree.XML(response_no_lun), etree.XML(response_lun)] self.client._fw = 'T100' self.client.list_luns_for_host('dummy') mock_request.assert_called_with('/show/host-maps', 'dummy') self.client._fw = 'G221' self.client.list_luns_for_host('dummy') mock_request.assert_called_with('/show/maps/initiator', 'dummy')
def test_backend_stats(self, mock_request): stats = {'free_capacity_gb': 1979, 'total_capacity_gb': 1979} linear = etree.XML(response_stats_linear) virtual = etree.XML(response_stats_virtual) mock_request.side_effect = [linear, virtual] self.assertEqual(stats, self.client.backend_stats('OpenStack', 'linear')) self.assertEqual(stats, self.client.backend_stats('A', 'virtual'))
def test_assert_response_ok(self): ok_tree = etree.XML(response_ok) not_ok_tree = etree.XML(response_not_ok) invalid_tree = etree.XML(invalid_xml) ret = self.client._assert_response_ok(ok_tree) self.assertIsNone(ret) self.assertRaises(exception.DotHillRequestError, self.client._assert_response_ok, not_ok_tree) self.assertRaises(exception.DotHillRequestError, self.client._assert_response_ok, invalid_tree)
def test_get_full_xpath(): expected_full_xpath = '/iati-activities/iati-activity/element[1]' activities_xml = etree.XML(XML_NS) activity_xml = activities_xml.getchildren()[0] element_xml = activity_xml.getchildren()[0] assert get_child_full_xpath(activity_xml, element_xml) == expected_full_xpath
def _api_request(self, path, *args, **kargs): """Performs an HTTP request on the device, with locking. Raises a RequestError if the device returned but the status is not 0. The device error message will be used in the exception message. If the status is OK, returns the XML data for further processing. """ url = self._build_request_url(path, *args, **kargs) # Don't log the created URL since it may contain chap secret LOG.debug("Array Request path: %s, args: %s, kargs: %s (session %s)", path, args, strutils.mask_password(kargs), self._session_key) headers = {'dataType': 'api', 'sessionKey': self._session_key} try: xml = requests.get(url, headers=headers, verify=self.ssl_verify, timeout=60) tree = etree.XML(xml.text.encode('utf8')) except Exception as e: message = _("Exception handling URL %(url)s: %(msg)s") % { 'url': url, 'msg': e } raise stx_exception.ConnectionError(message=message) if path == "/show/volumecopy-status": return tree self._assert_response_ok(tree) return tree
async def _wfs_get_features_type( self, wfs_url: Url, ogc_server_name: str, preload: bool = False ) -> Tuple[Optional[etree.Element], Set[str]]: errors = set() wfs_url.add_query( { "SERVICE": "WFS", "VERSION": "1.0.0", "REQUEST": "DescribeFeatureType", "ROLE_IDS": "0", "USER_ID": "0", } ) LOG.debug("WFS DescribeFeatureType for the URL: %s", wfs_url) # forward request to target (without Host Header) headers = dict(self.request.headers) if wfs_url.hostname != "localhost" and "Host" in headers: headers.pop("Host") headers = restrict_headers(headers, self.headers_whitelist, self.headers_blacklist) try: content, _ = await asyncio.get_event_loop().run_in_executor( None, get_http_cached, self.http_options, wfs_url, headers ) except requests.exceptions.RequestException as exception: error = ( f"Unable to get WFS DescribeFeatureType from the URL '{wfs_url.url()}' for " f"OGC server {ogc_server_name}, " + ( f"return the error: {exception.response.status_code} {exception.response.reason}" if exception.response is not None else f"{exception}" ) ) errors.add(error) LOG.exception(error) return None, errors except Exception: error = ( f"Unable to get WFS DescribeFeatureType from the URL {wfs_url} for " f"OGC server {ogc_server_name}" ) errors.add(error) LOG.exception(error) return None, errors if preload: return None, errors try: return lxml.XML(content), errors except Exception as e: errors.add( f"Error '{e!s}' on reading DescribeFeatureType from URL {wfs_url}:\n{content.decode()}" ) return None, errors
def test_get_ports(self, mock_request): mock_request.side_effect = [etree.XML(response_ports)] ret = self.client.get_active_target_ports() self.assertEqual([{'port-type': 'FC', 'target-id': 'id2', 'status': 'Up'}, {'port-type': 'iSCSI', 'target-id': 'id4', 'status': 'Up'}, {'port-type': 'iSCSI', 'target-id': 'id5', 'status': 'Up'}], ret)
def _get_auth_token(self, xml): """Parse an XML authentication reply to extract the session key.""" self._session_key = None try: tree = etree.XML(xml) if (tree.findtext(".//PROPERTY[@name='response-type']") == "success"): self._session_key = ( tree.findtext(".//PROPERTY[@name='response']")) except Exception as e: msg = _("Cannot parse session key: %s") % e.msg raise exception.DotHillConnectionError(message=msg)
def _get_auth_token(self, xml): """Parse an XML authentication reply to extract the session key.""" self._session_key = None try: tree = etree.XML(xml) # The 'return-code' property is not valid in this context, so we # we check value of 'response-type-numeric' (0 => Success) rtn = tree.findtext(".//PROPERTY[@name='response-type-numeric']") session_key = tree.findtext(".//PROPERTY[@name='response']") if rtn == '0': self._session_key = session_key except Exception as e: msg = _("Cannot parse session key: %s") % e.msg raise stx_exception.ConnectionError(message=msg)
async def _wms_get_features_type( self, wfs_url: Url, preload: bool = False) -> Tuple[Optional[etree.Element], Set[str]]: errors = set() wfs_url.add_query({ "SERVICE": "WFS", "VERSION": "1.0.0", "REQUEST": "DescribeFeatureType", "ROLE_ID": "0", "USER_ID": "0", }) LOG.debug("WFS DescribeFeatureType for base URL: %s", wfs_url) # forward request to target (without Host Header) headers = dict(self.request.headers) if wfs_url.hostname != "localhost" and "Host" in headers: headers.pop("Host") try: response = await asyncio.get_event_loop().run_in_executor( None, get_http_cached, self.http_options, wfs_url, headers) except Exception: errors.add("Unable to get DescribeFeatureType from URL {}".format( wfs_url)) return None, errors if not response.ok: errors.add( "DescribeFeatureType from URL {} return the error: {:d} {}". format(wfs_url, response.status_code, response.reason)) return None, errors if preload: return None, errors try: return lxml.XML(response.text.encode("utf-8")), errors except Exception as e: errors.add( "Error '{}' on reading DescribeFeatureType from URL {}:\n{}". format(str(e), wfs_url, response.text)) return None, errors
async def _wms_get_features_type(self, wfs_url, preload=False): errors = set() params = { "SERVICE": "WFS", "VERSION": "1.0.0", "REQUEST": "DescribeFeatureType", "ROLE_ID": "0", "USER_ID": "0", } wfs_url = add_url_params(wfs_url, params) LOG.debug("WFS DescribeFeatureType for base url: %s", wfs_url) # forward request to target (without Host Header) headers = dict(self.request.headers) if urllib.parse.urlsplit( wfs_url).hostname != "localhost" and "Host" in headers: headers.pop("Host") # pragma nocover try: response = await asyncio.get_event_loop().run_in_executor( None, get_http_cached, self.http_options, wfs_url, headers) except Exception: # pragma: no cover errors.add("Unable to get DescribeFeatureType from URL {}".format( wfs_url)) return None, errors if not response.ok: # pragma: no cover errors.add( "DescribeFeatureType from URL {} return the error: {:d} {}". format(wfs_url, response.status_code, response.reason)) return None, errors if preload: return None, errors try: return lxml.XML(response.text.encode("utf-8")), errors except Exception as e: # pragma: no cover errors.add( "Error '{}' on reading DescribeFeatureType from URL {}:\n{}". format(str(e), wfs_url, response.text)) return None, errors
def test_get_xobjects(): activities_xml = etree.XML(XML_NS) activity_xml = activities_xml.getchildren()[0] xobjects = get_xobjects(activity_xml, 'element') assert xobjects[0].attrib.get('id') == 'element1' assert xobjects[1].attrib.get('id') == 'element2'
class Context(): xml = etree.XML(XML_NS).getchildren()[0] feature = Feature()
def _validated_data(data): schema_xml = etree.XML(XML_SCHEMA) schema_tree = lxml.etree.XMLSchema(schema_xml) data_tree = etree.fromstring(data) schema_tree.validate(data_tree) return schema_tree
def test_get_iscsi_iqns(self, mock_request): mock_request.side_effect = [etree.XML(response_ports)] ret = self.client.get_active_iscsi_target_iqns() self.assertEqual(['id4', 'id5'], ret)
def test_get_fc_ports(self, mock_request): mock_request.side_effect = [etree.XML(response_ports)] ret = self.client.get_active_fc_target_ports() self.assertEqual(['id2'], ret)