Search code examples
pythontestingpatchtestcase

How to patch ftplib.FTP in a Python testcase with fake login credentials?


There is a python module which follows as x.y.z in which a function is present :-

from ftplib import FTP

def connect(host,user,pass) :
    ftp = FTP(host, user, pass)

Test case is follows :-

classs testClass(unittest.TestCase)

@patch(x.y.z.FTP)
def test_connect(self,MOCKFTP) :
    mock_ftp_obj = MOCKFTP()
    connect('fakehost','fakeuser','fakepass')

Running the test case gives - 530 login incorrect !

Am I missing something.


Solution

  • The issue is incorrect path value x.y.z.FTP FTP is actually present in ftplib package.

    Following works as expected:

    x.y.z.py:

    import ftplib
    
    
    def connect(host, user, pass1):
        ftp = ftplib.FTP(host=host, user=user, passwd=pass1)
    

    testz.py:

    import unittest
    from unittest.mock import patch
    
    from x.y.z import connect
    
    
    class testClass(unittest.TestCase):
    
        @patch('ftplib.FTP', autospec=True)
        def test_download_file(self, mock_ftp):
            connect('fakehost','fakeuser','fakepass')
            mock_ftp.assert_called_with('fakehost','fakeuser','fakepass')
    

    Please let me know if it helps.