Search code examples
djangopython-3.xdjango-viewsdjango-testingdjango-tests

Set Django's RequestFactory() method to equal 'POST'


Example view function:

def example_view(request):
    if request.method == "POST":

        print(request.session['Key'])

        return HttpResponse("Success")

Test case to test view:

from django.contrib.sessions.backends.db import SessionStore
from django.test import RequestFactory, TestCase
from website.views import example_view

class ExampleTestCase(TestCase):

    def test_example(self):

        # Create request and session
        request = RequestFactory()
        request.session = SessionStore()

        request.session['Key'] = "Value"

        response = example_view(request)

        self.assertEquals(response.status_code, 200)

urls.py file in case anyone asks for it:

urlpatterns = [    
    path('example', views.example_view, name="example_view"),
]

Error Response:

AttributeError: 'RequestFactory' object has no attribute 'method'

Without:

if request.method == 'POST':

this works as expected.

How do I set the request.method equal to post?


Solution

  • RequestFactory gives you a factory, not a request, to get the request you must call the factory as you'd do with the Django testing client:

    factory = RequestFactory()
    request = factory.post('/your/view/url')
    response = example_view(request)