Test Django views that require login using RequestFactory

EMP picture EMP · Apr 25, 2011 · Viewed 11.9k times · Source

I'm new to Django and I'd like to unit test a view that requires the user to be logged in (@login_requred). Django kindly provides the RequestFactory, which I can theoretically use to call the view directly:

factory = RequestFactory()
request = factory.get("/my/home/url")
response = views.home(request)

However, the call fails with

AttributeError: 'WSGIRequest' object has no attribute 'session'

Apparently, this is intentional, but where does that leave me? How do I test views that require authentication (which in my case is all of them)? Or am I taking the wrong approach entirely?

I'm using Django 1.3 and Python 2.7.

Answer

bmihelac picture bmihelac · Jun 12, 2011

When using RequestFactory, you are testing view with exactly known inputs.

That allows isolating tests from the impact of the additional processing performed by various installed middleware components and thus more precisely testing.

You can setup request with any additional data that view function expect, ie:

    request.user = AnonymousUser()
    request.session = {}

My personal recommendation is to use TestClient to do integration testing (ie: entire user checkout process in shop which includes many steps) and RequestFactory to test independent view functions behavior and their output (ie. adding product to cart).