0

I need to mock a function(this_function()), that is called inside another function(receive()), inside a function blueprint, inside a class A. How can I do it? I create a mock for this_function() in the file where i have all tests.

class A: 
       def blueprint(): 
           @route("/", method = ["POST"])
           async def receive(): 
                  ....
              test = await this_function()

I created a mock function in the same file as my test:

def mock_this_function(): 
   return ..

class Tests(unittest.TestCase): 
   @patch("path.to.classA.this_function")
    def test(mock_this_function):

This_function is defined in a helper.py module.

I'm not able to connect/use mock_this_function. It always connect me with this_function... Any solution? any Tips how to properly mock it?

ylvi-bux
  • 37
  • 6
  • I think it is pretty hard to replicate your example and give you proper answer. What is the project structure? Where is the `this_function` function defined? If I had to to guess you probably have trouble with understand *where* to mock. This might help you: https://docs.python.org/3/library/unittest.mock.html#where-to-patch – Haller Patrick Jun 08 '21 at 16:02

1 Answers1

1

Try this path in your mock: "path.to.classA.this_function" instead, you are probably having the wrong path. I mean, it doesnt matter how nested your function is. If it is imported, then you just need to refer to the mock path properly, which is very well described in the link provided by @HallerPatrick.

mleger45
  • 348
  • 1
  • 2
  • 11
  • Thanks, I got it , but since the function is async I'm getting an error: TypeError: object MagicMock can't be used in 'await' expression – ylvi-bux Jun 10 '21 at 08:42
  • oh so in that case I think this could help you: https://stackoverflow.com/questions/51394411/python-object-magicmock-cant-be-used-in-await-expression – mleger45 Jun 23 '21 at 03:21