Search code examples
djangodjango-testingdjango-tests

How can I test the URLS for my Class Based Views in Django?


I'm trying to test the URL resolutions for my first Django project- I have successfully tested my function-based views, however I am having trouble testing my Class Based Views.

I'm getting the below error when I run the test on my CBV:

AssertionError: <function UpdateHealth at 0x7f538f023e50> != <HealthHub.views.UpdateHealth object at 0x7f538d7aec10>

Tests.py (CBV test in question):

   def test_health_hub_update_url_is_resolved(self):
        url = reverse('HealthHub:health_hub_update')
        self.assertEqual(resolve(url).func, views.UpdateHealth())

views.py (view in question):

class UpdateHealth(View):
    '''View for the Update Health page.

    Uses StatUpdateForm to allow the user to update their stats.'''

    def get(self, request, *args, **kwargs):

        stats = HealthStats
        update_form = StatUpdateForm
             
        context = {
            'stats': stats,
            'update_form': update_form,
            'user': stats.user,
            'weight': stats.weight,
            'date': stats.date,
        }
        return render(request, 'health_hub_update.html', context)
    
    def post(self, request, *args, **kwargs):

        update_form = StatUpdateForm(data=request.POST)

        if update_form.is_valid():
            obj = update_form.save(commit=False)
            obj.user = request.user
            obj.save()
            
        return redirect("HealthHub:health_hub")

Urls.py:

path('MyHealth/update', views.UpdateHealth.as_view(), name='health_hub_update'),

Any help would be much appreciated, as I seem to have hit a dead-end.


Solution

  • You can check with the .view_class attribute attached to the function:

    def test_health_hub_update_url_is_resolved(self):
        url = reverse('HealthHub:health_hub_update')
        self.assertEqual(resolve(url).func.view_class, views.UpdateHealth)