Alex Lungu
Alex Lungu

Reputation: 1114

python: How to mock helper method?

Can you please help me out to figure what I did wrong? I have the following unit test for a python lambdas

class Tests(unittest.TestCase):
    def setUp(self):
        //some setup

    @mock.patch('functions.tested_class.requests.get')
    @mock.patch('functions.helper_class.get_auth_token')
    def test_tested_class(self, mock_auth, mock_get):

        mock_get.side_effect = [self.mock_response]
        mock_auth.return_value = "some id token"

        response = get_xml(self.event, None)

        self.assertEqual(response['statusCode'], 200)

The problem is that when I run this code, I get the following error for get_auth_token:

 Invalid URL '': No schema supplied. Perhaps you meant http://?

I debugged it, and it doesn't look like I patched it correctly. The Authorization helper file is in the same folder "functions" as the tested class.

EDIT: In the tested_class I was importing get_auth_token like this:

from functions import helper_class
from functions.helper_class import get_auth_token
...
def get_xml(event, context):
    ...
    response_token = get_auth_token()

After changing to this, it started to work fine

import functions.helper_class
...
def get_xml(event, context):
    ...
    response_token = functions.helper_class.get_auth_token()

I still don't fully understand why though

Upvotes: 4

Views: 3403

Answers (2)

Gang
Gang

Reputation: 2778

  • In your first scenario

in tested_class.py, get_auth_token is imported

from functions.helper_class import get_auth_token

The patch should be exactly the get_auth_token at tested_class

@mock.patch('functions.tested_class.get_auth_token')
  • Second scenario

With the following usage

 response_token = functions.helper_class.get_auth_token()

The only way to patch is this

@mock.patch('functions.helper_class.get_auth_token')
  • alternative

With import like this in tested_class

from functions import helper_class
helper_class.get_auth_token()

patch could be like this:

@mock.patch('functions.tested_class.helper_class.get_auth_token')

Upvotes: 4

Harshavardhan Reddy
Harshavardhan Reddy

Reputation: 101

patch() works by (temporarily) changing the object that a name points to with another one. There can be many names pointing to any individual object, so for patching to work, you must ensure that you patch the name used by the system under test.

The basic principle is that you patch where an object is looked up, which is not necessarily the same place as where it is defined.

Python documentation has a very good example. where to patch

Upvotes: 0

Related Questions