最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

mocking - Working with python unit tests, tring to patch a class but is not working - Stack Overflow

programmeradmin2浏览0评论

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
  • You aren't calling mock_client.get_foo; you're calling test_get_foos.get_foo. Names matter when you are dealing with patching. – chepner Commented Feb 7 at 19:12
Add a comment  | 

1 Answer 1

Reset to default 0

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'
发布评论

评论列表(0)

  1. 暂无评论