Stephen Thracian
Stephen Thracian

Reputation: 41

Test an SFTP Connection in Python

I previously asked a question about mocks and testing and it helped me to get all but one aspect of testing sorted. How to test an SFTP connection.

I have a method:

def _transfer_file(self, my_file):
  try:
    with pysftp.Connection(‘host’, username=username, password=password) as sftp:
      sftp.put(my_file)
      sftp.close()
      return True

   except Exception as e:
      # log an error with exception
      return None

My issue is how do I test that specific method? I think it would be sufficient to simple verify that the connection can be successfully opened but how do I do this? My test would end up sending “my_file” which I do not really want to do.

I suspect I will need to use @mock.patch(something) to fake a connection? I’m not really sure. Does anyone have any suggestions on how to test this situation?

Upvotes: 2

Views: 5674

Answers (1)

Stephen Thracian
Stephen Thracian

Reputation: 41

My solution was to not mock anything and rather change my method to be as follows:

try:
    with pysftp.Connection(‘host’, username=username, password=password) as sftp:
      if(my_file):
        sftp.put(my_file)
      sftp.close()
      return True

Then in the test I simply provide 'None' for the my_file value. This opens the connection and then closes it without doing anything but lets me test the success of that opening.

Upvotes: 1

Related Questions