#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 , 6 months ago
Cc: | added |
---|---|
Resolution: | → invalid |
Status: | new → closed |
comment:2 by , 6 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.
That's not true, it generates a request instances.
Why not?
As far as I'm aware, the current examples work fine.