简体   繁体   中英

How to mock a python library using patch in python regardless where it is used?

In the following question the function that uses the ftplib is defined in the same file, which makes it trivial to patch ('ftplib.FTP')

Mocking ftplib.FTP for unit testing Python code

My question is: How should I proceed if, in my test, I would like to make an instance of a class (let's call it 'A') that uses the ftplib somewhere (ie: the class A has an instance of a class B and B has an FTP object which calls connect()) ?

import unittest
from mock import patch

class TestClass(unittest.TestCase):

  @patch(???)
  def test_1(self, mock_ftp_constructor):
      mock_ftp = mock_ftp_constructor.return_value
      a = A()
      self.assertTrue(mock_ftp.connect.called)


if __name__ == "__main__":
  unittest.main()

If I use the solution given in the other question, I find that the ftplib is called instead of the mock. How could I know the correct path of ftplib.FTP ?

When dealing with imports to mock a class, it matters the way how the file (where the class is) has imported the lib.

To make the patch it is necessary to know the name of the context where the lib is called. If __name__ is 'A.B' , patch would be: @patch('ABftplib.FTP') if B imports FTP as import ftplib . If B imports the lib as from ftplib import FTP , it would be: @patch('ABFTP')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM