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.
The request factory The RequestFactory shares the same API as the test client. However, instead of behaving like a browser, the RequestFactory provides a way to generate a request instance that can be used as the first argument to any view.
With Django's Test Runner. If you're using manage.py test , you need to change the way you run it. You need to wrap it with three coverage commands like so: $ coverage erase # Remove any coverage data from previous runs $ coverage run manage.py test # Run the full test suite Creating test database for alias 'default'.. ...
self. client , is the built-in Django test client. This isn't a real browser, and doesn't even make real requests. It just constructs a Django HttpRequest object and passes it through the request/response process - middleware, URL resolver, view, template - and returns whatever Django produces.
Writing testsDjango's unit tests use a Python standard library module: unittest . This module defines tests using a class-based approach. When you run your tests, the default behavior of the test utility is to find all the test cases (that is, subclasses of unittest.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With