| 1 |
import sys |
| 2 |
|
| 3 |
try: |
| 4 |
import unittest2 as unittest |
| 5 |
except ImportError: |
| 6 |
import unittest |
| 7 |
import nose2 |
| 8 |
from unittest.mock import MagicMock, patch |
| 9 |
from jnpr.junos.transport.tty_telnet import Telnet |
| 10 |
import six |
| 11 |
|
| 12 |
|
| 13 |
class TestTTYTelnet(unittest.TestCase): |
| 14 |
@patch("jnpr.junos.transport.tty_telnet.telnetlib.Telnet") |
| 15 |
def setUp(self, mpock_telnet): |
| 16 |
self.tel_conn = Telnet( |
| 17 |
host="1.1.1.1", user="test", password="password123", port=23, timeout=30 |
| 18 |
) |
| 19 |
|
| 20 |
def test_open(self): |
| 21 |
self.tel_conn._tty_open() |
| 22 |
self.tel_conn._tn.open.assert_called() |
| 23 |
|
| 24 |
def test_open_exception(self): |
| 25 |
self.tel_conn._tn.open.side_effect = Exception |
| 26 |
Telnet.RETRY_OPEN = 1 |
| 27 |
Telnet.RETRY_BACKOFF = 0.1 |
| 28 |
self.assertRaises(RuntimeError, self.tel_conn._tty_open) |
| 29 |
# reset |
| 30 |
Telnet.RETRY_OPEN = 3 |
| 31 |
Telnet.RETRY_BACKOFF = 2 |
| 32 |
|
| 33 |
def test_close(self): |
| 34 |
self.tel_conn._tty_close() |
| 35 |
self.tel_conn._tn.close.assert_called() |
| 36 |
|
| 37 |
def test_read(self): |
| 38 |
self.tel_conn.read() |
| 39 |
self.tel_conn._tn.read_until.assert_called() |
| 40 |
|
| 41 |
@patch("jnpr.junos.transport.tty_telnet.telnetlib.Telnet") |
| 42 |
def test_tty_telnet_baud(self, mock_telnet): |
| 43 |
tel_conn = Telnet( |
| 44 |
host="1.1.1.1", |
| 45 |
user="test", |
| 46 |
password="password123", |
| 47 |
port=23, |
| 48 |
timeout=30, |
| 49 |
baud=0, |
| 50 |
) |
| 51 |
tel_conn._tty_open() |
| 52 |
tel_conn.rawwrite("<rpc>") |
| 53 |
tel_conn._tn.write.assert_called_with("<rpc>") |
| 54 |
|
| 55 |
def test_read_prompt_RuntimeError(self): |
| 56 |
self.tel_conn.expect = MagicMock() |
| 57 |
self.tel_conn.expect = (None, None, "port already in use") |
| 58 |
self.assertRaises(RuntimeError, self.tel_conn._login_state_machine) |
| 59 |
|
| 60 |
def test_read_prompt_in_use_RuntimeError(self): |
| 61 |
self.tel_conn.expect = MagicMock() |
| 62 |
self.tel_conn._tn.expect.return_value = ( |
| 63 |
None, |
| 64 |
None, |
| 65 |
six.b("port already in use"), |
| 66 |
) |
| 67 |
self.assertRaises(RuntimeError, self.tel_conn._login_state_machine) |
| 68 |
|
| 69 |
def test_tty_telnet_rawwrite_sys_py3(self): |
| 70 |
with patch.object(sys.modules["sys"], "version", "3.x") as mock_sys: |
| 71 |
self.tel_conn._tty_open() |
| 72 |
content = MagicMock() |
| 73 |
self.tel_conn.rawwrite(content) |
| 74 |
content.decode.assert_called_with("utf-8") |