Mocking ftplib.FTP for unit testing Python code

后端 未结 3 1177
不知归路
不知归路 2021-02-19 19:07

I don\'t know why I\'m just not getting this, but I want to use mock in Python to test that my functions are calling functions in ftplib.FTP correctly. I\'ve simplified everythi

3条回答
  •  梦毁少年i
    2021-02-19 19:57

    When you do patch(ftplib.FTP) you are patching FTP constructor. dowload_file() use it to build ftp object so your ftp object on which you call login() and cmd() will be mock_ftp.return_value instead of mock_ftp.

    Your test code should be follow:

    class TestDownloader(unittest.TestCase):
    
        @patch('ftplib.FTP', autospec=True)
        def test_download_file(self, mock_ftp_constructor):
            mock_ftp = mock_ftp_constructor.return_value
            download_file('ftp.server.local', 'pub/files', 'wanted_file.txt')
            mock_ftp_constructor.assert_called_with('ftp.server.local')
            self.assertTrue(mock_ftp.login.called)
            mock_ftp.cwd.assert_called_with('pub/files')
    

    I added all checks and autospec=True just because is a good practice

提交回复
热议问题