Elad Benda
Elad Benda

Reputation: 36672

How to mock my non injected dependencies coming from imports

I want to unit-test with pytest library and not unittests library. But my class under test imports uses a non injected depepndency.

My class under tests imports a config.py module which imports logging and auth:

config module:

import logging
import google.cloud.logging as gcp_logging
from utils.logging import logger
import utils.auth as auth



.
.
.

self.project_id = auth.get_project_id()
logger = logging.getLogger('NAME')
client = gcp_logging.Client()

...

How can I mock this not-injected (but imported) dependency?

import pytest

def test_create_asset_ids_for_yt_video_ids_for_empty_input(

        self, mocked_gads_mgr):

    assert mocked_gads_mgr.create_asset_ids_for_yt_video_ids([]) == {}

I've tried this setup @pytest.fixture in my unit-tests, but my mocks are not replacing the original logger/auth libraries.

 @pytest.fixture
    def mocked_gads_mgr(self, mocker: pytest_mock.MockerFixture, mocked_config):
.        ...
        mocker.patch('logging.basicConfig', return_value=None)
        mock_client = mocker.patch('google.cloud.logging.Client')
        mock_client.return_value = MagicMock()
        return gads.GoogleAdsManager.from_config(mocked_config)

Error:

../../config.py:22: in <module>

    from utils.logging import logger

../../utils/logging.py:32: in <module>

    client = gcp_logging.Client()

raise exceptions.DefaultCredentialsError(_CLOUD_SDK_MISSING_CREDENTIALS)

E       google.auth.exceptions.DefaultCredentialsError: Your default credentials were not found. To set up Application Default Credentials, see https://cloud.google.com/docs/authentication/external/set-up-adc for more information.

Upvotes: 1

Views: 29

Answers (0)

Related Questions