Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock keeps calling real function

I'm trying to mock a function. When I try to mock the function core.use_cases.add_owner_to_place the mock doesn't work. It keeps printing "Ouch".

I've tried to test mocked_add_owner_to_place.called and it returns False.

Does anyone know why it keeps using the real function even if I mock it?

views.py:

from core.use_cases import add_owner_to_place

class CreatePlace(LoginRequiredMixin, FormView):
template_name = 'place/create_place.html'
form_class = PlaceForm
success_url = reverse_lazy('place_list')

def form_valid(self, form):
    place = form.save()
    add_owner_to_place(place, self.request.user)
    return super(CreatePlace, self).form_valid(form)

tests.py:

from unittest.mock import patch, Mock

@patch('core.use_cases.add_owner_to_place')
@patch('core.forms.PlaceForm.is_valid')
@patch('core.forms.PlaceForm.save')
def test_save_should_be_called(self, mocked_save, mocked_is_valid, mocked_add_owner_to_place):
    self.client.post(reverse('place_create'), data={})
    self.assertTrue(mocked_save.called)

uses_cases.py:

def add_owner_to_place(place, user):
    print('Ouch')
like image 992
Rubico Avatar asked Aug 04 '26 00:08

Rubico


1 Answers

So, searching around and looking some codes on github, I found out that I need to mock from the view even if the function belongs to the use_cases module.

So my code now is:

tests.py

from unittest.mock import patch, Mock

@patch('core.views.add_owner_to_place')
@patch('core.forms.PlaceForm.is_valid')
@patch('core.forms.PlaceForm.save')
def test_save_should_be_called(self, mocked_save, mocked_is_valid, mocked_add_owner_to_place):
    self.client.post(reverse('place_create'), data={})
    self.assertTrue(mocked_save.called)

I know that this works, but now I need to search why it works. I'll explain it when I figure it out.

like image 121
Rubico Avatar answered Aug 05 '26 12:08

Rubico



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!