Django is fairly easy to test, but I'm addicted to a simple access test on a page that requires authentication this time, so I'll write it down.
test.py
from django.test import TestCase, RequestFactory
from django.contrib.auth.models import User
from .views import SomeGenericView
class TestSomeView(TestCase):
def test_some_auth_page(self):
user = User.objects.create_user(...) #Create login user
rf = RequestFactory()
request = rf.get("/some/auth/page")
request.user = user
res = SomeGenericView.as_view()(request)
self.assertEqual(res.status_code, 200)
It was a way to create a request object with RequestFactory ()
and poke the user who wants to authenticate to it.
Click here for documentation Advanced testing topics | Django documentation | Django
Is there a way that is a little easier to do ...
By the way, when you want to POST
test_post.py
class TestSomeView2(TestCase):
def test_some_auth_page_post(self):
user = ... #Same as above
rf = RequestFactory()
req = rf.post("/some/post/url", data={"edit": "value"}) #Only here is different
req.user = user #Push the user
res = SomeGenericView.as_view()(req)
self.assertEqual(res.status_code, 302)
I think I can go there.
Recommended Posts