Hi everyone! I have a testing question: How do I m...
# ask-community
f
Hi everyone! I have a testing question: How do I mock method calls inside a Task? This is my current setup: File 1:
Copy code
def do_something_1(params_1):
  (does something)
File 2:
Copy code
from path_to_file.file_1 import do_something_1

class SomethingTask(Task):
  def run(self, params_1):
    do_something_1(params_1)
    do_something_2
File 3:
Copy code
import unittest
from unittest.mock import patch
from path_to_file.file_2.SomethingTask import SomethingTask

@patch('path_to_file.file_1.do_something_1')
class TestSomethingTask(unittest.TestCase):
  def test_1(self, mock_do_something_1):
    task = SomethingTask()
    task.run()
    self.assertTrue(mock_do_something_1.called)
Instead of mocking
do_something_1()
it actually calls
do_something_1()
, and strangely the assertion returns False.
👀 1
k
Hey @Fina Silva-Santisteban, this might not be a Prefect specific behavior. Have you seen this ?
f
@Kevin Kho sorry, what exactly do you mean is not specific Prefect behavior?? 🤔 That’s how I go about mocking any other method call (https://docs.python.org/3/library/unittest.mock.html). So if
SomethingTask
was a regular python class and not a subclass from
Task
, I could mock
do_something_1()
in exactly that way. Could it have to do with the prefect run scope?
k
I think this is related to the code snippet in the StackOverflow where using a named import like
from path_to_file.file_1 import do_something
in file 2 creates a new name for the object so it might be fixed if you do
Copy code
import path_to_file.file_1

class SomethingTask(Task):
  def run(self, params_1):
    path_to_file.file_1.do_something_1(params_1)
    do_something_2
because this will match the patch. You might also be able to get this by patching
@patch('path_to_file.file_2.do_something_1')
instead since it has a new name because of the
from … import …
call, which would be similar logic to this response in the StackOverflow post.
💡 1
f
@Kevin Kho ohhh I see! Thank you for pointing that out! Yes the import path seems to be different when I call it from within the Task. This is what worked for me:
Copy code
@patch('path_to_file.file_2.SomethingTask.do_something_1')
Thanks so much for your help! 🙏
👍 1