How can I mock an imported dependency from my function file?

55 Views Asked by At

I'm attempting to mock a config that is being imported in my security file here:

import aiohttp
from fastapi import Header, HTTPException
from .util.config import config 

async def get_user_profile_details(
        user_profile_id: str, ..., ...
):
    user_profile_url = f"{config.entity.ENTITY_BASE_URL}/.../..."
    async with aiohttp.ClientSession() as session: 
      async with session.get(user_profile_url, headers=auth_header) as ...
    ....

here is my test setup:

import unittest
from unittest.mock import patch
from aioresponses import aioresponses
from my_module.security import get_user_profile_details

    @patch('my_module.util.config.es', autospec=True)
    async def test_get_user_profile_details_success(self, mock_config):
        mock_config.entity.ENTITY_BASE_URL = "http://mocked-entity-url"

        user_profile_id = "123"
        ... 
        ...
 

my test is failing even before it gets to this test function. It imports that get_user_profile_details, goes down its imports from .util.config import config , importing the config and failing when its trying to get an es instance(also in the config setup)


class Config(BaseSettings):
   ... 
   ...   
   es = ElasticsearchConfig() #this is what I'm trying to mock
   entity = EntityAPIConfig() 
... 
config: Config = Config()

I've tried several ways.

  • mocking the config like you see now

  • @patch('my_module.util.config.config', autospec=True)

  • @patch('my_module.util.Config', autospec=True)

  • tried using a:


     async def asyncSetUp(self):
       self.aiohttp_mock = aioresponses()

and mocking the request:

 self.aiohttp_mock.get(...

Here is the error:

    es = ElasticsearchConfig()



E   google.api_core.exceptions.PermissionDenied: 403 Permission denied on resource project test.
  

What is the correct way to mock that config?

0

There are 0 best solutions below