Search code examples
djangodjango-testing

Django: Testing LoginView throwing AssertionError


Quesiton I'm building a testing suite for my login process and immediately ran into a hiccup. I believe the issue is that LoginView is a 'class' while the code is testing it as a function. What is the proper way to assert that the URL resolved to the LoginView?

urls.py

from . import views
from users.views import *

from django.urls import path
from django.contrib.auth.views import LoginView, LogoutView
from users.forms import LoginForm


urlpatterns = [
     path('', views.user_home_view, name='user_home'),
     path('sign_up', views.SignUpView.as_view()),
     path('login', LoginView.as_view(authentication_form=LoginForm), name='login'),
     path('logout', LogoutView.as_view(), name='logout')
]

tests.py

from django.test import SimpleTestCase
from django.urls import reverse, resolve
from django.contrib.auth.views import LoginView, LogoutView
from users.forms import LoginForm
from users.views import *

# Create your tests here.

class UrlTestCase(SimpleTestCase):

    def test_login_url_resolved(self):
        url = reverse('login')
        self.assertEquals(resolve(url).func, LoginView)

Testing Results (./manage.py test)

AssertionError: <function LoginView at 0x7f970ca05320> != <class 'django.contrib.auth.views.LoginView'>


Solution

  • This is because you are not getting back instance of LoginView class but appropriate method through as_view() entry point method

    You can access class through attribute view_class which is set in as_view() method as documented

    The returned view has view_class and view_initkwargs attributes.