I am writing some functions, using paramiko, to execute commands and create files on a remote host. I would like to write some unit tests for them, but I don't know what would be the simplest way to achieve this? This is what I envisage as being an example outline of my code:
import os
import paramiko
import pytest
def my_function(hostname, relpath='.', **kwargs):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname, **kwargs)
sftp = ssh.open_sftp()
sftp.chdir(relpath)
stdin, stdout, stderr = ssh.exec_command("echo hallo > test.txt")
@pytest.fixture("module")
def mock_remote_host():
# start a remote host here with a local test path
try:
yield hostname, testpath, {"username":"bob", "password":"1234"}
finally:
# delete the test path
# close the remote host
def test_my_function(mock_remote_host):
hostname, dirpath, kwargs = mock_remote_host
my_function(hostname, **kwargs)
filepath = os.path.join(dirpath, 'test.txt')
assert os.path.exists(filepath)
I have had a look at the paramiko test modules, but they seem quite complex for my use case and I'm not sure how to go about simplifying them.
I think what you really need to mock is paramiko.SSHClient
object. You are unittesting your function my_function
, you can assume paramiko
module works correctly and the only thing you need to unit test is if my_function
calls methods of this paramiko.SSHClient
in correct way.
To mock paramiko.SSH
module you can use unittest.mock and decorate your test_my_function
function with @mock.patch.object(paramiko.SSHClient, sshclientmock)
. You have to define sshclientmock
as some kind of Mock
or MagicMock
first.
Also in python 2.7 there is some equivalent of unittest.mock
but I dont remember where to find it exactly.
EDIT: As @chepner mentioned in comment. For python 2.7 you can find mock
module in pypi and install it using pip install mock
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With