'django testing class based view

I have a Class based view defined as:

class Myview(LoginRequiredMixin, View):

    def post():
      #.......

to test this view i tried this

class MyViewTest(TestCase):
    def setUp(self):
        self.factory = RequestFactory()
        self.user = User.objects.create_user(
            username='jacob', email='[email protected]', password='vvggtt')

    def view_test(self):
        # Create an instance of a POST request.
        request = self.factory.post('/my-url/')
        request.user = self.user

        response = MyView(request)
        print (response,"**")
        self.assertEqual(response.status_code, 200)

But this gives this error.

    response = MyView(request)
TypeError: __init__() takes 1 positional argument but 2 were given

I understand why this error is coming (cinstructor of MyView has 2 ars) but how do i remove it? i couldnt get the details on searching.



Solution 1:[1]

we can use django test client

from django.test import Client

class MyViewTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.user = User.objects.create_user(
            username='jacob', email='[email protected]', password='vvggtt')

    def view_test(self):
        # Create an instance of a POST request.
        self.client.login(username="jacob", password="vvggtt")
        data = {'name': 'test name'}
        res = self.client.post('/my-url/', data)
        print(res)
        self.assertEqual(res.status_code, 200)

Solution 2:[2]

From the docs:

# Use this syntax for class-based views.
response = MyView.as_view()(request)

Solution 3:[3]

Try

response = MyView(request=request)

Solution 4:[4]

There's a section of the Django docs called Testing Class Based Views which addresses this:

In order to test class-based views outside of the request/response cycle you must ensure that they are configured correctly, by calling setup() after instantiation.

So in your case this looks something like:

    def view_test(self):
        # Create an instance of a POST request.
        request = self.factory.post('/my-url/')
        request.user = self.user

        my_view = MyView()
        my_view.setup(request)
        response = my_view.post(request)

        self.assertEqual(response.status_code, 200)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 anjaneyulubatta505
Solution 2 n_moen
Solution 3 Dasith
Solution 4 Nexus