| 1 |
__author__ = "Nitin Kumar, Rick Sherman" |
| 2 |
__credits__ = "Jeremy Schulman" |
| 3 |
|
| 4 |
import unittest |
| 5 |
import nose2 |
| 6 |
from unittest.mock import patch, MagicMock |
| 7 |
from lxml import etree |
| 8 |
import os |
| 9 |
|
| 10 |
from jnpr.junos import Device |
| 11 |
from jnpr.junos.ofacts.chassis import facts_chassis as chassis |
| 12 |
from jnpr.junos.exception import ConnectNotMasterError |
| 13 |
from jnpr.junos.exception import RpcError |
| 14 |
|
| 15 |
from ncclient.manager import Manager, make_device_handler |
| 16 |
from ncclient.transport import SSHSession |
| 17 |
|
| 18 |
|
| 19 |
class TestChassis(unittest.TestCase): |
| 20 |
@patch("ncclient.manager.connect") |
| 21 |
@patch("jnpr.junos.device.warnings") |
| 22 |
def setUp(self, mock_warnings, mock_connect): |
| 23 |
mock_connect.side_effect = self._mock_manager |
| 24 |
self.dev = Device( |
| 25 |
host="1.1.1.1", |
| 26 |
user="rick", |
| 27 |
password="password123", |
| 28 |
gather_facts=False, |
| 29 |
fact_style="old", |
| 30 |
) |
| 31 |
self.dev.open() |
| 32 |
self.facts = {} |
| 33 |
|
| 34 |
@patch("jnpr.junos.Device.execute") |
| 35 |
def test_2RE_true(self, mock_execute): |
| 36 |
mock_execute.side_effect = self._mock_manager |
| 37 |
chassis(self.dev, self.facts) |
| 38 |
self.assertTrue(self.facts["2RE"]) |
| 39 |
|
| 40 |
def test_chassis_exception_ConnectNotMasterError(self): |
| 41 |
xmldata = etree.XML("<rpc-reply><output>test</output></rpc-reply>") |
| 42 |
self.dev.rpc.get_chassis_inventory = MagicMock(side_effect=xmldata) |
| 43 |
self.assertRaises(ConnectNotMasterError, chassis, self.dev, self.facts) |
| 44 |
|
| 45 |
def test_chassis_exception_RuntimeError(self): |
| 46 |
xmldata = etree.XML("<rpc-reply><error>test</error></rpc-reply>") |
| 47 |
self.dev.rpc.get_chassis_inventory = MagicMock(side_effect=xmldata) |
| 48 |
self.assertRaises(RuntimeError, chassis, self.dev, self.facts) |
| 49 |
|
| 50 |
def test_chassis_exception_RpcError(self): |
| 51 |
xmldata = etree.XML("<rpc-reply><chassis-inventory/></rpc-reply>") |
| 52 |
self.dev.rpc.get_chassis_inventory = MagicMock(side_effect=xmldata) |
| 53 |
self.assertRaises(RpcError, chassis, self.dev, self.facts) |
| 54 |
|
| 55 |
def _read_file(self, fname): |
| 56 |
from ncclient.xml_ import NCElement |
| 57 |
|
| 58 |
fpath = os.path.join(os.path.dirname(__file__), "rpc-reply", fname) |
| 59 |
foo = open(fpath).read() |
| 60 |
|
| 61 |
rpc_reply = NCElement( |
| 62 |
foo, self.dev._conn._device_handler.transform_reply() |
| 63 |
)._NCElement__doc[0] |
| 64 |
return rpc_reply |
| 65 |
|
| 66 |
def _mock_manager(self, *args, **kwargs): |
| 67 |
if kwargs: |
| 68 |
device_params = kwargs["device_params"] |
| 69 |
device_handler = make_device_handler(device_params) |
| 70 |
session = SSHSession(device_handler) |
| 71 |
return Manager(session, device_handler) |
| 72 |
|
| 73 |
if args: |
| 74 |
return self._read_file("chassis_" + args[0].tag + ".xml") |