How can I do mocked reverse_lazy from django.urls?

17 Views Asked by At
# views.py

from django.contrib.auth import get_user_model
from django.urls import reverse_lazy
from django.views import generic

from accounts import forms

User = get_user_model()


class UserRegisterView(generic.FormView):
    model = User
    template_name = 'accounts/register_form.html'
    form_class = forms.UserRegisterForm
    success_url = reverse_lazy('accounts:user-register-first-success')

    def form_valid(self, form):
        form.save()
        return super().form_valid(form)
# test_views.py

from unittest.mock import patch

from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse

User = get_user_model()


class UserRegisterViewTest(TestCase):
    def setUp(self) -> None:
        self.url = reverse('accounts:user-register')
        self.data = {
            'email': '[email protected]',
            'password': 'qwe123!@#',
            'confirmed_password': 'qwe123!@#',
        }
    @patch('accounts.views.reverse_lazy', return_value='mock_url')
    def test_view_redirects_to_correct_page_POST(self, mock):

        response = self.client.post(self.url, self.data)

        self.assertRedirects(response, mock('accounts:user-register-first-success'))

    @patch('django.urls.reverse_lazy', return_value='mock_url')
    def test_view_redirects_to_correct_page_POST_(self, mock):
        response = self.client.post(self.url, self.data)

        self.assertRedirects(response, mock('accounts:user-register-first-success'))

  File "/home/branya/Документи/My Projects/Django/hotel/venv/lib/python3.10/site-packages/django/urls/resolvers.py", line 848, in _reverse_with_prefix
    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'user-register-first-success' not found. 'user-register-first-success' is not a valid view function or pattern name.

I don't understand why mock isn't work on reverse_lazy. I need it work without the made view with the url by name "user-register-first-success". Help me to find a solution.

I used @patch('accounts.views.reverse_lazy', return_value='mock_url') and @patch('django.urls.reverse_lazy', return_value='mock_url'). I try to find a solution with chatGPT, but its answers raised that error.

Temporarily the problem is solved like this:

# test_views.py

def test_view(request):
    return HttpResponse(request)

urlpatterns.append(
    path('url/', test_view, name='user-register-first-success')
)
0

There are 0 best solutions below