def _read_file(self, fname): from ncclient.xml_ import NCElement fpath = os.path.join(os.path.dirname(__file__), 'rpc-reply', fname) with open(fpath) as fp: foo = fp.read() if fname == 'get-rpc-error.xml': # Raise ncclient exception for error raise RPCError(etree.XML(foo)) elif fname == 'get-permission-denied.xml': # Raise ncclient exception for error raise RPCError(etree.XML(foo)) elif (fname == 'get-index-error.xml' or fname == 'get-system-core-dumps.xml' or fname == 'load-configuration-error.xml' or fname == 'show-configuration-interfaces.xml' or fname == 'show-interfaces-terse-asdf.xml'): rpc_reply = NCElement(foo, self.dev._conn._device_handler .transform_reply()) elif (fname == 'show-configuration.xml' or fname == 'show-system-alarms.xml'): rpc_reply = NCElement(foo, self.dev._conn._device_handler .transform_reply())._NCElement__doc elif fname == 'show-interface-terse.json': rpc_reply = json.loads(foo) elif fname == 'get-route-information.json': rpc_reply = NCElement(foo, self.dev._conn._device_handler .transform_reply()) else: rpc_reply = NCElement(foo, self.dev._conn._device_handler .transform_reply())._NCElement__doc[0] return rpc_reply
def test_commit(self): mock_commit = self.c.connection.commit mock_commit.return_value = NCElement(good_reply, self.tr) self.assertTrue(self.c.commit()) # bad reply mock_commit.return_value = NCElement(bad_reply, self.tr) self.assertFalse(self.c.commit()) # RPC error mock_commit.side_effect = RPCError(mock.MagicMock()) self.assertFalse(self.c.commit())
def test_compare(self): mock_compare = self.c.connection.compare_configuration mock_compare.return_value = NCElement(comp_reply, self.tr) self.assertEqual(self.c.compare().replace(" ", ""), "\ntest\n") mock_compare.assert_called_with(0) # ither version self.assertEqual(self.c.compare(10).replace(" ", ""), "\ntest\n") mock_compare.assert_called_with(10) # empty compare mock_compare.return_value = NCElement(empty_comp_reply, self.tr) self.assertEqual(self.c.compare(), None)
def _read_file(self, fname): from ncclient.xml_ import NCElement fpath = os.path.join(os.path.dirname(__file__), 'rpc-reply', fname) foo = open(fpath).read() if fname == 'get-system-users-information.xml': return NCElement(foo, self.dev._conn._device_handler.transform_reply()) rpc_reply = NCElement(foo, self.dev._conn. _device_handler.transform_reply())\ ._NCElement__doc[0] return rpc_reply
def wrapper(self, *args, **kwargs): ignore_warning = kwargs.pop('ignore_warning', False) rsp = None try: rsp = function(self, *args, **kwargs) except RPCError as ex: if hasattr(ex, 'xml') and ignore_warning: if hasattr(ex, 'errors'): for err in ex.errors: if err.severity == 'warning': if ((sys.version < '3' and isinstance(ignore_warning, (str, unicode))) or (sys.version >= '3' and isinstance(ignore_warning, str))): if not re.search(ignore_warning, err.message, re.I): # Message did not match. raise ex elif isinstance(ignore_warning, list): for warn_msg in ignore_warning: if re.search(warn_msg, err.message, re.I): # Warning matches. # Break skips else. break else: # Message didn't match any of the # ignore_warn pattern values. raise ex else: # Not a warning (probably an error). raise ex # Every err was a warning that matched ignore_warning. # Prepare the response which will get returned. # ex.xml contains the raw xml response which was # received. rsp = ex.xml # 1) A normal response has been run through the XSLT # transformation, but ex.xml has not. Do that now. encode = None if sys.version < '3' else 'unicode' rsp = NCElement(etree.tostring(rsp, encoding=encode), self.transform())._NCElement__doc # 2) Now remove all of the <rpc-error> elements from # the response. We've already confirmed they are # all warnings rsp = etree.fromstring( str(JXML.strip_rpc_error_transform(rsp))) else: # Safety net. ex doesn't have an errors attribute. # I can't think of a situation where this would # actually occur. raise ex else: # ignore_warning was false, or an RPCError which doesn't have # an XML attribute. Raise it up for the caller to deal with. raise ex return rsp
def mock_manager(*args, **kwargs): if 'device_params' in kwargs: # open connection device_params = kwargs['device_params'] device_handler = make_device_handler(device_params) session = SSHSession(device_handler) return Manager(session, device_handler) elif args: # rpc request rpc_request = args[0].tag rpc_command = str(args[0].text) rpc_command = rpc_command.strip() rpc_command = rpc_command.replace(" ", "_") if rpc_request in rpc_reply_dict: xml = rpc_reply_dict[rpc_request] elif 'dir' in rpc_reply_dict: fname = os.path.join(rpc_reply_dict['dir'], 'rpc-reply', rpc_command, rpc_request + '.xml') with open(fname, 'r') as f: xml = f.read() else: _rpc_reply_dict['dir'] fname = os.path.join(os.path.dirname(__file__), 'rpc-reply', rpc_command, rpc_request + '.xml') with open(fname, 'r') as f: xml = f.read() rpc_reply = NCElement(xml, dev._conn._device_handler.transform_reply()) return rpc_reply
def remove_namespaces(data): if not HAS_NCCLIENT: raise ImportError( "ncclient is required but does not appear to be installed. " "It can be installed using `pip install ncclient`" ) return NCElement(data, transform_reply()).data_xml
def _read_file(self, fname): from ncclient.xml_ import NCElement fpath = os.path.join(os.path.dirname(__file__), "rpc-reply", fname) with open(fpath) as fp: foo = fp.read() return NCElement(foo, self.dev._conn._device_handler.transform_reply())
def _rpc_reply(self, rpc_cmd_e): encode = None if sys.version < '3' else 'unicode' rpc_cmd = etree.tostring(rpc_cmd_e, encoding=encode) if \ isinstance(rpc_cmd_e, etree._Element) else rpc_cmd_e reply = self._tty.nc.rpc(rpc_cmd) rpc_rsp_e = NCElement(reply, self.junos_dev_handler.transform_reply())._NCElement__doc return rpc_rsp_e
def _read_file(self, fname): from ncclient.xml_ import NCElement fpath = os.path.join(os.path.dirname(__file__), 'rpc-reply', fname) foo = open(fpath).read() rpc_reply = NCElement(foo, self.dev._conn._device_handler.transform_reply())._NCElement__doc[0] return rpc_reply
def cscript_conf(reply): try: device_params = {"name": "junos"} device_handler = manager.make_device_handler(device_params) transform_reply = device_handler.transform_reply() return NCElement(reply, transform_reply)._NCElement__doc except: return None
def _rpc_reply(self, rpc_cmd_e, *args, **kwargs): encode = None if sys.version < "3" else "unicode" rpc_cmd = (etree.tostring(rpc_cmd_e, encoding=encode) if isinstance( rpc_cmd_e, etree._Element) else rpc_cmd_e) reply = self._tty.nc.rpc(rpc_cmd) rpc_rsp_e = NCElement(reply, self.junos_dev_handler.transform_reply(), self._huge_tree)._NCElement__doc return rpc_rsp_e
def remove_namespaces(data): if not HAS_NCCLIENT: raise ImportError( "ncclient is required but does not appear to be installed. " "It can be installed using `pip install ncclient`") return NCElement( to_text(data, errors="surrogate_then_replace").strip(), transform_reply(), ).data_xml
def cscript_conf(reply): try: device_params = {'name': 'junos'} device_handler = manager.make_device_handler(device_params) transform_reply = device_handler.transform_reply() return NCElement(etree.tostring(reply), transform_reply)._NCElement__doc except: return None
def wrapper(self, *args, **kwargs): ignore_warning = kwargs.pop("ignore_warning", False) rsp = None try: rsp = function(self, *args, **kwargs) except RPCError as ex: if hasattr(ex, "xml") and ignore_warning: if hasattr(ex, "errors"): errors = ex.errors else: errors = [ex] for err in errors: if err.severity == "warning": if (sys.version < "3" and isinstance( ignore_warning, (str, unicode))) or (sys.version >= "3" and isinstance( ignore_warning, str)): if not re.search(ignore_warning, err.message, re.I): # Message did not match. raise ex elif isinstance(ignore_warning, list): for warn_msg in ignore_warning: if re.search(warn_msg, err.message, re.I): # Warning matches. # Break skips else. break else: # Message didn't match any of the # ignore_warn pattern values. raise ex else: # Not a warning (probably an error). raise ex # Every err was a warning that matched ignore_warning. # Prepare the response which will get returned. # ex.xml contains the raw xml response which was # received, but might be rooted at an <rpc-error> element. # Set rsp to the root <rpc-reply> element. rsp = ex.xml.getroottree().getroot() # 1) A normal response has been run through the XSLT # transformation, but ex.xml has not. Do that now. encode = None if sys.version < "3" else "unicode" rsp = NCElement(etree.tostring(rsp, encoding=encode), self.transform())._NCElement__doc # 2) Now remove all of the <rpc-error> elements from # the response. We've already confirmed they are # all warnings rsp = etree.fromstring(str( JXML.strip_rpc_error_transform(rsp))) else: # ignore_warning was false, or an RPCError which doesn't have # an XML attribute. Raise it up for the caller to deal with. raise ex return rsp
def _read_file(self, fname): from ncclient.xml_ import NCElement fpath = os.path.join(os.path.dirname(__file__), 'rpc-reply', fname) foo = open(fpath).read() if (fname == 'get-rpc-error.xml' or fname == 'get-index-error.xml' or fname == 'get-system-core-dumps.xml'): rpc_reply = NCElement(foo, self.dev._conn._device_handler .transform_reply()) elif (fname == 'show-configuration.xml' or fname == 'show-system-alarms.xml'): rpc_reply = NCElement(foo, self.dev._conn._device_handler .transform_reply())._NCElement__doc else: rpc_reply = NCElement(foo, self.dev._conn._device_handler .transform_reply())._NCElement__doc[0] return rpc_reply
def _read_file(self, fname): from ncclient.xml_ import NCElement fpath = os.path.join(os.path.dirname(__file__), "rpc-reply", fname) foo = open(fpath).read() if fname == "user.xml": return etree.fromstring(foo) rpc_reply = NCElement(foo, self.dev._conn._device_handler.transform_reply() )._NCElement__doc[0] return rpc_reply
def test_locking(self): # check lock self.c.connection.lock.return_value = NCElement(good_reply, self.tr) self.assertTrue(self.c._locking("lock")) self.assertTrue(self.c._configuration_lock) # check unlock self.c.connection.unlock.return_value = NCElement(good_reply, self.tr) self.assertTrue(self.c._locking("unlock")) self.assertFalse(self.c._configuration_lock) # check other action self.assertTrue(self.c._locking("test")) self.assertTrue(self.c._configuration_lock) # bad RCP reply lock self.c.connection.lock.return_value = NCElement(bad_reply, self.tr) self.assertFalse(self.c._locking("lock")) # bad RCP reply unlock self.c.connection.unlock.return_value = NCElement(bad_reply, self.tr) self.assertFalse(self.c._locking("unlock")) # check RPCError self.c.connection.lock.side_effect = RPCError(mock.MagicMock()) self.assertFalse(self.c._locking("lock")) self.c.connection.unlock.side_effect = RPCError(mock.MagicMock()) self.assertFalse(self.c._locking("unlock"))
def test_cscript_conf_output_tag_child_element(self): xmldata = u"""<rpc-reply message-id="urn:uuid:932d11dc-9ae5-4d25-81fa-8b50ea2d3a03" xmlns:junos="http://xml.juniper.net/junos/19.3R0/junos"> <output> shutdown: [pid 8683] Shutdown NOW! </output> </rpc-reply> """ xmldata_without_ns = u"""<rpc-reply message-id="urn:uuid:932d11dc-9ae5-4d25-81fa-8b50ea2d3a03"> <output> shutdown: [pid 8683] Shutdown NOW! </output> </rpc-reply> """ rpc_reply = NCElement(xmldata, normalize_xslt.encode("UTF-8")) self.assertEqual(str(rpc_reply), xmldata_without_ns)