Search code examples
pythonpytestpytest-mock

mocking a class instance in pytest


am trying to mock a class instance while testing a method something like below

source
    main_proc.py
    devinstance.py
    prodinstance.py
    requirements.txt
    host.json

main_proc.py

def get_instance(self)
    ins = None
    env = os.getenv('env', 'dev')
    if env == 'dev':
        ins = DevInstance()
    else:
        ins = ProdInstance()
    return ins

Sample DevInstance class devinstance.py

class DevInstance:
    def __init__(self):
        self.eh_client = dict()
        self.initialize()

        def initialize(self):
        try:
            
                client = EventHubProducerClient.from_connection_string(conn_str=self.secrets_dict[value],
                                                                       eventhub_name=names[i], http_proxy=HTTP_PROXY)
                
        except Exception as e:
            logging.error(e)
            raise e
    

testing the get instance like below as my intension is to mock the entire DevInstance class obj. both files are in the same module.

@mock.patch("devinstance.DevInstance")
def test_get_instance(self, devins):
    
        # Act
        devins.return_value = MagicMock()

        result = get_instance()

        # Assert
        assert result is not None

Can anyone help me how this can be acheived?


Solution

  • You need to patch where the object is being looked up (see the Where to patch documentation).

    If you're testing get_instance in main_proc, then you need to patch where DevInstance is imported in main_proc.

    For example, if you're importing it with from devinstance import DevInstance, then you need to patch it with @mock.patch("main_proc.DevInstance").

    Otherwise, if you're importing it with import devinstance, then you need to patch it with @mock.patch("main_proc.devinstance.DevInstance").