[Answered ]-How to write get and post test methods for views in django?

1👍

Don’t let the concept of views confuse you!! Essentially there is a python function that you need to exercise certain conditionals of.

It looks like there are 4 main branches:

  • GET not in session
  • GET in session
  • POST exists
  • POST does not exist

so there should probably be at least 4 different tests. I’ll post the first one because it is pretty straightforward:

def ForgetPasswordRegistry(self, request):
forgetpassword = True
if request.method == 'GET':
    if 'UserID' in request.session:
        forgetpassword = False
    return request, forgetpassword

def test_forget_get_user_id_in_session(self):
    request = Mock(session={'UserID': 'here'}, method='GET')
    # instantiate your view class
    yourview = YourView()
    sefl.assertEqual(yourview.ForgetPasswordRegistry(request), (request, False))

The post user exists branch is a little more complicated because there are more things that the test needs to account for, and potentially provide stub implementations for:

  • SendEmail
  • GetUser
  • models.ForgetPasswordRegistry()

1👍

Use Django’s test client: https://docs.djangoproject.com/en/stable/topics/testing/tools/#the-test-client

Example:

from django.test import Client, TestCase


class ViewTestCase(TestCase):
    def test_post_creation(self):
        c = Client()  # instantiate the Django test client
        response = c.get('/forgetpassword/')
        self.assertEqual(response.status, 200)

Leave a comment