Mocking ftplib.FTP for unit testing Python code

后端 未结 3 1173
不知归路
不知归路 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条回答
  •  时光说笑
    2021-02-19 19:55

    I suggest using pytest and pytest-mock.

    from pytest_mock import mocker
    
    
    def test_download_file(mocker):
        ftp_constructor_mock = mocker.patch('ftplib.FTP')
        ftp_mock = ftp_constructor_mock.return_value
    
        download_file('ftp.server.local', 'pub/files', 'wanted_file.txt')
    
        ftp_constructor_mock.assert_called_with('ftp.server.local')
        assert ftp_mock.login.called
        ftp_mock.cwd.assert_called_with('pub/files')
    

提交回复
热议问题