Opened 5 months ago

Closed 5 months ago

Last modified 5 months ago

#35494 closed Cleanup/optimization (invalid)

Testing Class-based Views Clarification

Reported by: Matthew Pava Owned by: nobody
Component: Documentation Version: 5.1
Severity: Normal Keywords: test cbv
Cc: Mariusz Felisiak Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: yes UI/UX: no

Description

We have this code for testing class-based views, and I think we need some clarification in the documentation.
https://docs.djangoproject.com/en/dev/topics/testing/advanced/#testing-class-based-views

from django.test import RequestFactory, TestCase
from .views import HomeView


class HomePageTest(TestCase):
    def test_environment_set_in_context(self):
        request = RequestFactory().get("/")
        view = HomeView()
        view.setup(request)

        context = view.get_context_data()
        self.assertIn("environment", context)

The RequestFactory().get() method returns a response, and not a request.
On top of that TestCase already has access to a RequestFactory object called client.
Lastly, the response object is not a request object that you would pass into the view.setup function. You can access the request object from the client. This is what I have:

from django.test import TestCase
from .views import HomeView


class HomePageTest(TestCase):
    def test_environment_set_in_context(self):
        self.client.get("/")
        view = HomeView()
        view.setup(self.client.request)

        context = view.get_context_data()
        self.assertIn("environment", context)

Change History (2)

comment:1 by Mariusz Felisiak, 5 months ago

Cc: Mariusz Felisiak added
Resolution: invalid
Status: newclosed

The RequestFactory().get() method returns a response, and not a request.

That's not true, it generates a request instances.

Lastly, the response object is not a request object that you would pass into the view.setup function.

Why not?

As far as I'm aware, the current examples work fine.

comment:2 by Matthew Pava, 5 months ago

I got confused with the RequestFactory object. Of course, it makes sense that would return a request. I got so focused on using self.client.get, which does return a response if my understanding is correct.

Even so, the example is inconsistent with the other examples on the webpage, which use self.client.get instead of RequestFactory.get.

I used self.client.get in my test, and it worked just as well.

Note: See TracTickets for help on using tickets.
Back to Top