|
| 1 | +import io |
| 2 | +import os |
| 3 | +from contextlib import redirect_stdout |
| 4 | + |
| 5 | +import mock |
| 6 | +from django.conf import settings |
| 7 | +from django.test import TestCase |
| 8 | +from mockssh import Server |
| 9 | + |
| 10 | +from .base import CreateConnectionsMixin |
| 11 | + |
| 12 | + |
| 13 | +class TestSsh(CreateConnectionsMixin, TestCase): |
| 14 | + @classmethod |
| 15 | + def setUpClass(cls): |
| 16 | + super().setUpClass() |
| 17 | + cls.mock_ssh_server = Server({'root': cls._TEST_RSA_PRIVATE_KEY_PATH}).__enter__() |
| 18 | + cls.ssh_server.port = cls.mock_ssh_server.port |
| 19 | + |
| 20 | + @classmethod |
| 21 | + def tearDownClass(cls): |
| 22 | + cls.mock_ssh_server.__exit__() |
| 23 | + |
| 24 | + def test_connection_connect(self): |
| 25 | + ckey = self._create_credentials_with_key(port=self.ssh_server.port) |
| 26 | + dc = self._create_device_connection(credentials=ckey) |
| 27 | + dc.connector_instance.connect() |
| 28 | + stdout = io.StringIO() |
| 29 | + with redirect_stdout(stdout): |
| 30 | + dc.connector_instance.exec_command('echo test') |
| 31 | + output = stdout.getvalue() |
| 32 | + self.assertIn('$:> echo test\ntest', output) |
| 33 | + |
| 34 | + def test_connection_failed_command(self): |
| 35 | + ckey = self._create_credentials_with_key(port=self.ssh_server.port) |
| 36 | + dc = self._create_device_connection(credentials=ckey) |
| 37 | + dc.connector_instance.connect() |
| 38 | + stdout = io.StringIO() |
| 39 | + with redirect_stdout(stdout): |
| 40 | + with self.assertRaises(Exception): |
| 41 | + dc.connector_instance.exec_command('wrongcommand') |
| 42 | + output = stdout.getvalue() |
| 43 | + self.assertIn('/bin/sh: 1: wrongcommand: not found', output) |
| 44 | + self.assertIn('# Previus command failed, aborting...', output) |
| 45 | + |
| 46 | + @mock.patch('scp.SCPClient.putfo') |
| 47 | + def test_connection_upload(self, putfo_mocked): |
| 48 | + ckey = self._create_credentials_with_key(port=self.ssh_server.port) |
| 49 | + dc = self._create_device_connection(credentials=ckey) |
| 50 | + dc.connector_instance.connect() |
| 51 | + # needs a binary file to test all lines |
| 52 | + fl = open(os.path.join(settings.BASE_DIR, '../media/floorplan.jpg'), 'rb') |
| 53 | + dc.connector_instance.upload(fl, '/tmp/test') |
| 54 | + putfo_mocked.assert_called_once() |
0 commit comments