Mocking Python Class In Unit Test And Verifying An Instance
I'm trying to unit test an SFTP helper class that makes some calls to the pysftp module. I want to mock the actual network calls from pysftp so there are no side effects, and just
Solution 1:
You could configure the mock to return a new mock object with __enter__
and __exit__
methods defined. For example:
@mock.patch.object(
target=pysftp,
attribute='Connection',
autospec=True,
return_value=mock.Mock(
spec=pysftp.Connection,
__enter__=lambda self: self,
__exit__=lambda *args: None)
)deftest_list_files(self, mock_connection):
# (contents of test case)
In addition, you may want to use:
mock_connection.return_value.listdir.assert_called_with('/some/files/dir')
instead of:
mock_connection.listdir.assert_called_with('/some/files/dir')
As a side note, you could also replace both uses of assert_called_with
in your example with assert_called_once_with
.
The end result:
$ python -m unittest test_sftp_helper.TestSFTPHelper.test_list_files
.
----------------------------------------------------------------------
Ran 1 test in 0.017s
OK
Post a Comment for "Mocking Python Class In Unit Test And Verifying An Instance"