Fix SSHAction under python3

This patch fixes the bug in string handling in ssh_utils which
prevented SSHAction execution in Python 3 setup.

In Python 3, all strings are unicode by default and byte stream
no longer implicitly convert to str.

Py2: paramiko Channel.recv returns type `str`
Py3: paramiko Channel.recv returns type `byte`

Change-Id: I24971858039f287df24d39c19eccc44916ecf580
Closes-Bug: #1781548
This commit is contained in:
hardikj 2018-09-03 16:03:51 +05:30
parent 38a54260b0
commit f85e57da89
2 changed files with 47 additions and 3 deletions

View File

@ -13,9 +13,12 @@
# under the License.
import json
import mock
from mistral.actions import std_actions as std
from mistral import exceptions as exc
from mistral.tests.unit import base
import mistral.utils.ssh_utils
class SSHActionTest(base.BaseTest):
@ -34,3 +37,43 @@ class SSHActionTest(base.BaseTest):
self.assertIsNone(
params['private_key_filename'],
"private_key_filename is not None.")
@mock.patch.object(mistral.utils.ssh_utils, 'execute_command')
def test_ssh_action(self, mocked_method):
mocked_method.return_value = (0, 'ok')
cmd = "echo -n ok"
host = "localhost"
username = "mistral"
action = std.SSHAction(cmd, host, username)
mock_ctx = None
stdout = action.run(mock_ctx)
self.assertEqual('ok', stdout,
'stdout from SSH command differs from expected')
mocked_method.assert_called_with(
cmd=cmd,
host=host,
username=username,
password='',
private_key_filename=None
)
@mock.patch.object(mistral.utils.ssh_utils, 'execute_command')
def test_ssh_action_with_stderr(self, mocked_method):
mocked_method.return_value = (1, 'Error expected')
cmd = "echo -n ok"
host = "localhost"
username = "mistral"
action = std.SSHAction(cmd, host, username)
mock_ctx = None
self.assertRaisesWithMessageContaining(
exc.ActionException,
"Failed to execute ssh cmd 'echo -n ok' on ['localhost']",
action.run,
mock_ctx
)

View File

@ -27,13 +27,14 @@ LOG = logging.getLogger(__name__)
def _read_paramimko_stream(recv_func):
result = ''
result = b''
buf = recv_func(1024)
while buf != '':
while buf != b'':
result += buf
buf = recv_func(1024)
return result
return result.decode('utf-8')
def _to_paramiko_private_key(private_key_filename, password=None):