[Answered ]-Django forms which needs the request , makes testing harder?

2👍

Passing request to the form is okay if you need it in the clean() method. You can use a request/session/user in a test like this:

from django.test import TestCase, Client
from django.test.client import RequestFactory
from django.contrib.auth.models import AnonymousUser, User
from .views import my_view
from .forms import MyForm
from django.contrib.sessions.middleware import SessionMiddleware

# If Python >= 3.4
from unittest.mock import patch, MagicMock
# Else
from mock import patch, MagicMock

class SimpleTest(TestCase):
    def setUp(self):
        # Create a RequestFactory accessible by the entire class.
        self.factory = RequestFactory()
        # Create a new user object accessible by the entire class.
        self.user = User.objects.create_user(username='username', 
                                 email='email', password='password')

    def test_my_view(self):
        # Create an instance of a GET request.
        request = self.factory.get('/my-url/')

        # Middleware is not supported so simulate a
        # logged-in user by setting request.user.
        request.user = self.user

        # Or add anonymous user to request.
        request.user = AnonymousUser()

        # Test view() at '/my-url/'
        response = my_view(request)
        self.assertEqual(response.status_code, 200)

    @patch('app.models.ModelName.save', MagicMock(name="save"))
    def test_my_form_view_with_factory(self):
        # Set up form data.
        form_data = {'something': 'something'}

        # Create an instance of a POST request.
        request = self.factory.post('/my-form-url/', form_data)

        # Simulate logged-in user
        request.user = self.user

        # Setup session.
        middleware = SessionMiddleware()
        middleware.process_request(request)
        request.session.save()

        # Or you should just be able to do
        request.session['somekey'] = 'test'
        request.session.save()           

        # Get response from form view, and test passing 
        # request/data to form.
        form = MyForm(request=request, data=form_data)
        response = my_form_view(request)

        self.assertTrue(form.is_valid())
        self.assertEqual(response.status_code, 200)

        # If model form you can do 
        self.assertTrue(ModelName.save.called)

    @patch('app.models.ModelName.save', MagicMock(name="save"))
    def test_my_form_view_with_client(self):
        # Use Client instead of RequestFactory.
        self.client = Client()

        # Login with Client.
        self.client.login(username='username', password='password')

        # Set up form data.
        form_data = {'something': 'something'}

        # Get/set session.
        session = self.client.session
        session['somekey'] = 'test'
        session.save()

        # Get response with Client.
        response = self.client.post('/my-form-url/', form_data)
        self.assertEqual(response.status_code, 200)

        # If model form you can do 
        self.assertTrue(ModelName.save.called)

Should give a general idea of what you can do, not specifically tested.

👤ss7

Leave a comment