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.
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.
Share Improve this question asked Feb 7 at 17:28 uday8486uday8486 1,3933 gold badges13 silver badges25 bronze badges 1 |1 Answer
Reset to default 0The 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'
mock_client.get_foo
; you're callingtest_get_foos.get_foo
. Names matter when you are dealing with patching. – chepner Commented Feb 7 at 19:12