1

I have a Django view that I want to unit test it but the problem is in some line of the function it calls another function which has a send email function and this send email function has a celery task inside it. I don't know what to do to surpass this function call because when the debugger hits the send email function it stops and does nothing which I think is because of the celery task. Due to this problem, my unit test can't run completely.
So I would be happy if someone could tell me what to do then. My own solution was to mock the sending email function but it doesn't work. I don't know what to do now.
here is the code example of what happens during the view function.

view_funtion():
...
function_a is called here
function_a():
...
send_email_function is called here
send_email_function():
some code here and initialization of the email template
celery_task.delay()

please let me know if I should add more detail. Thanks.
Update:
this is the unit test function

@patch('path_to_send_email_function')
    def test_view_function(self, mock_send_email):
       mock_send_email.return_value = None
       ...

I also use the API request factory which is for the Django rest framework for testing the view. The execution steps are in the body of the test the view function is called and it executes until function_a is called and then send_email_function is called in the body of function_a.

Hamed Fathi
  • 65
  • 3
  • 11
  • You can mock the function. – JPG Oct 19 '20 at 07:54
  • How did you try to mock the `send_email_function`? Note that [unittest.mock.patch()](https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch) does not work if the module - in this case module of `send_email_function` - is already loaded. – Attila Viniczai Oct 19 '20 at 07:55
  • I try to mock the function but nothing happens and the debugger still get stuck when reaching that line @ArakkalAbu – Hamed Fathi Oct 19 '20 at 08:05
  • 1
    @AttilaViniczai I use the patch but I don't why it doesn't work as I expected. let me update the question to show the unit test function. – Hamed Fathi Oct 19 '20 at 08:07
  • 1
    I recommend taking a look at the workarounds listed in this question: https://stackoverflow.com/questions/5286390/mocking-functions-using-python-mock My recommendation is the following: in the module where you want to use the `send_email_function` import the module of `send_email_function`, not the function itself. So instead of `from module_of_send_email_fn import send_email_function` use `import module_of_send_email_fn`. This should make mocking work as expected. – Attila Viniczai Oct 19 '20 at 08:37
  • 1
    @AttilaViniczai I will try your solution and tell result here in case anybody else wants to use this solution – Hamed Fathi Oct 19 '20 at 08:56

0 Answers0