I have some code with a testcase for it. It works fine.
import pysftp
from unittest import mock
remote_file_name = 'remote_file_name'
local_path = 'local/path/to/file'
def open_sftp_connection(hostname):
return pysftp.Connection(hostname, username='usr', password='pswd')
def sftp_upload_try(local_path, dest_file_name):
sftp_conn = None
try:
sftp_conn = open_sftp_connection('sftp-host')
sftp_conn.put(local_path, remotepath=dest_file_name)
finally:
if sftp_conn:
sftp_conn.close()
def test_sftp_try():
conn_mock = mock.MagicMock()
with mock.patch('test_sftp.open_sftp_connection', return_value=conn_mock):
sftp_upload_try(local_path, remote_file_name)
print(conn_mock.mock_calls)
assert 1 == conn_mock.put.call_count
assert remote_file_name == conn_mock.put.call_args.kwargs['remotepath']
assert 1 == conn_mock.close.call_count
print(conn_mock.mock_calls)
prints:
[call.put('local/path/to/file', remotepath='remote_file_name'),
call.__bool__(),
call.close()]
Instead of try-finally
, I would like to use with
:
def sftp_upload_with(local_path, dest_file_name):
with open_sftp_connection('sftp-host') as sftp_conn:
sftp_conn.put(f'${local_path}', remotepath=dest_file_name)
def test_sftp_with():
conn_mock = mock.MagicMock()
with mock.patch('test_sftp.open_sftp_connection', return_value=conn_mock):
sftp_upload_with(local_path, remote_file_name)
print(conn_mock.mock_calls)
put_call = next(c for c in conn_mock.mock_calls if '__enter__().put' == c[0])
assert put_call
assert remote_file_name == put_call.kwargs['remotepath']
This time print(conn_mock.mock_calls)
prints:
[call.__enter__(),
call.__enter__().put('$local/path/to/file', remotepath='remote_file_name'),
call.__exit__(None, None, None)]
So question is, is there some elegant way to assert calls when using with
? Or do I have to do something ugly like '__enter__().put' == c[0]
?