uday8486
uday8486

Reputation: 1393

Working with python unit tests, tring to patch a class but is not working

I have code with below functionality

src/client.py

class Client1(object):
    def foo(self, t):
        return f"foo-{t}"

    def get_foo(self, type):
        return self.foo(type)

src/get_foos.py


from .src import Client1

client = Client1()

def get_foo():
    foo = client.get_foo("foo")
    return foo

def get_bar():
    bar = client.get_foo("bar")
    return bar

I am trying to create a unit test for get_foo() and get_bar().

I do following

src/test/test_get_foos.py

from src.get_foos import get_foo

@patch(src.get_store.Client1)
def test_get_store(self,mock_client)
   mock_client.get_foo.return_value = 'myfoo'
   result = get_foo()
   assert result === 'myfoo'

But I observe that the patch does not work and the test fails. I checked all the resources online and everywhere I see the same pattern to mock a class class which is outside a function.

I have more than 6 methods in my actual code and I don't want to make a new instance of Client1 everywhere.

Upvotes: 0

Views: 20

Answers (1)

chepner
chepner

Reputation: 531908

The get_foo you are calling is a direct reference to get_foos.get_foo from before you execute the patch. For the existing patch, you should access the function via the module.

import src.get_foos

@patch(src.get_store.Client1)
def test_get_store(self,mock_client)
   mock_client.get_foo.return_value = 'myfoo'
   result = src.get_foos.get_foo()
   assert result === 'myfoo'

Upvotes: 0

Related Questions