'Python mock.patch() not mocking imported class module

I have a some code that looks like this (abridged):

## ./module_1/lambda_function.py

from shared.graphql_helpers import GraphQLClient

gql_client = GraphQLClient('http://host_url.test/')

post_event_to_consumer(event):
   response = gql_client.make_query(mutation, { 'data': event, {})

lambda_hanbdler(event, context):
   post_event_to_consumer(event['detail']

The module imported is such:

## ./shared/graphql_helpers.py

import requests

class GraphQLClient:
    def __init__(self, url):
      self.host_url = url

    def make_query(self, query, variables, headers):
        request = requests.post(self.host_url, json={'query': query, 'variables': variables}, headers=headers)
        if request.status_code != 200:
            raise Exception()
        elif request.json()['errors']:
            raise Exception()
        else:
            return request.json()['data']

The project structure is such:

module_1
    __init__.py
    lambda_function.py
    lambda_function_test.py
shared
    __init__.py
    graphql_helpers.py

My problem is that I am trying to patch GraphQLClient in lambda_function_test.py but it does not seem to be working.

My unit test looks like this:

## ./module_1/lambda_function_test.py

import os
from unittest import mock, TestCase

class TestLambdaFunction(TestCase):

    @mock.patch('module_1.lambda_function.GraphQLClient')
    def test_post_event_to_compplex(self, mock_gql_client):
        mock_gql_client = mock.Mock()
        mock_gql_client.make_query.return_value = {}

        result = post_event_to_consumer(json_data['detail'])

        assert result == None

From what I read online, patch mocks the import in the SUT's namespace, however, when I run the test, it imports the original GraphQLClient and throws a ConnectionError. I also tried removing module_1 from the path but that didn't work either.

Not sure what's incorrect here, but any help would be appreciated.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source