How to test if a view is decorated with login_required (Django)

2024/10/10 23:16:00

I'm doing some (isolated) unit test for a view which is decorated with "login_required". Example:

@login_required
def my_view(request):return HttpResponse('test')

Is it possible to test that the "my_view" function is decorated with "login_required"?

I know I can test the behaviour (anonymous user is redirected to login page) with an integration test (using the test client) but I'd like to do it with an isolated test.

Any idea?

Thanks!

Answer

Sure, it must be possible to test it in some way. It's definitely not worth it, though. Writing a fully isolated unit test to check that the decorator is applied will only result in a very complicated test. There is a way higher chance that the test will be wrong than that the tested behaviour is wrong. I would strongly discourage it.

The easiest way to test it is to use Django's Client to fake a request to the associated url, and check for a redirect. If you're using any of Django's testcases as your base class:

class MyTestCase(django.test.TestCase):def test_login_required(self):response = self.client.get(reverse(my_view))self.assertRedirects(response, reverse('login'))

A slightly more complicated, but a bit more isolated test would be to call the view directly using the RequestFactory to create a request object. assertRedirects() won't work in this case, since it depends on attributes set by the Client:

from django.test.client import RequestFactoryclass MyTestCase(django.test.TestCase):@classmethoddef setUpClass(cls):super(MyTestCase, cls).setUpClass()self.rf = RequestFactory()def test_login_required(self):request = self.rf.get('/path/to/view')response = my_view(request, *args, **kwargs)self.assertEqual(response.status_code, 302)self.assertEqual(response['Location'], login_url)...
https://en.xdnf.cn/q/69839.html

Related Q&A

Filter Nested field in Flask Marshmallow

I want to filter the nested field with is_active column as True in Marshmallow 3 Consider following scenario I have 3 tablesusers (id, name) organizations (id, name) organization_user(id, organization_…

Copy signature, forward all arguments from wrapper function

I have two functions in a class, plot() and show(). show(), as convenience method, does nothing else than to add two lines to the code of plot() likedef plot(self,show_this=True,show_that=True,color=k,…

How to fit a line through a 3D pointcloud?

I have a cable I am dropping from moving vehicle onto the ground. Using a camera system I estimate the location where the rope touches the ground in realtime. Movement of the vehicle and inaccuracy in …

Websockets with Django Channels on Heroku

I am trying to deploy my app to heroku. The app has a simple chatting system that uses Websockets and django channels. When I test my app using python manage.py runserver the app behaves just as intend…

How can I get the name/file of the script from sitecustomize.py?

When I run any Python script, I would like to see the scripts filename appear in the Windows command line windows titlebar. For example, if I run a script called "mytest.py", I want to see &q…

Sending Godaddy email via Django using python

I have these settings EMAIL_HOST = smtpout.secureserver.net EMAIL_HOST_USER = [email protected] EMAIL_HOST_PASSWORD = password DEFAULT_FROM_EMAIL = [email protected] SERVER_EMAIL = [email protected] EM…

python math, numpy modules different results?

I get slightly different results calculating the cosine of a value. How can I check that this difference is within machine precision?import math math.cos(60.0/180.0*math.pi) -> 0.5000000000000001im…

How to extract equation from a polynomial fit?

My goal is to fit some data to a polynomial function and obtain the actual equation including the fitted parameter values. I adapted this example to my data and the outcome is as expected. Here is my c…

python dictionary conundrum

On the console I typed in>>> class S(str): pass ... >>> a = hello >>> b = S(hello) >>> d = {a:a, b:b} >>> d {hello: hello} >>> type(d[a]) <class…

Celery 4 not auto-discovering tasks

I have a Django 1.11 and Celery 4.1 project, and Ive configured it according to the setup docs. My celery_init.py looks likefrom __future__ import absolute_importimport osfrom celery import Celery# set…