Skip to content

Commit

Permalink
Style and docstring fixes.
Browse files Browse the repository at this point in the history
  • Loading branch information
Dunedan committed Apr 6, 2015
1 parent e434299 commit 25d8c9c
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 11 deletions.
4 changes: 2 additions & 2 deletions lockdown/middleware.py
@@ -1,10 +1,10 @@
import datetime
import re

from django.core.exceptions import ImproperlyConfigured
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module

from lockdown import settings
Expand All @@ -24,7 +24,7 @@ def get_lockdown_form(form_path):
attr = form_path_list[-1]
try:
mod = import_module(module)
except (ImportError, ValueError) as exc:
except (ImportError, ValueError):
raise ImproperlyConfigured('Module configured in LOCKDOWN_FORM (%s) to'
' contain the form class couldn\'t be '
'found.' % module)
Expand Down
7 changes: 4 additions & 3 deletions lockdown/tests/test_settings.py
Expand Up @@ -9,10 +9,11 @@
SECRET_KEY = ''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)')
for i in range(64)])

MIDDLEWARE_CLASSES = ('django.middleware.common.CommonMiddleware',
MIDDLEWARE_CLASSES = ('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware')
'django.contrib.auth.middleware.AuthenticationMiddleware'
)

INSTALLED_APPS = (
'django.contrib.sessions',
Expand Down
46 changes: 41 additions & 5 deletions lockdown/tests/tests.py
Expand Up @@ -12,9 +12,12 @@


class LockdownTestCase(TestCase):
"""Base class for the other tests, setting up a proper test environment"""

urls = 'lockdown.tests.urls'

def setUp(self):
"""Basic setup for all tests"""
self._old_middleware_classes = django_settings.MIDDLEWARE_CLASSES

self._old_template_dirs = django_settings.TEMPLATE_DIRS
Expand All @@ -29,6 +32,7 @@ def setUp(self):
middleware._default_form = middleware.get_lockdown_form(settings.FORM)

def tearDown(self):
"""Tearing down all settings made for the tests after running them"""
django_settings.MIDDLEWARE_CLASSES = self._old_middleware_classes
django_settings.TEMPLATE_DIRS = self._old_template_dirs
settings.PASSWORDS = self._old_pw
Expand All @@ -37,24 +41,28 @@ def tearDown(self):


class BaseTests(LockdownTestCase):
"""
Base tests for lockdown functionality (whether via a decorator or
middleware).
"""Base tests for lockdown functionality
These base tests are used for testing lockdowns decorator and middleware
functionality.
Subclasses should provide ``locked_url`` and ``locked_contents``
attributes.
"""

def test_lockdown_template_used(self):
"""Test if the login form template is used on locked pages"""
response = self.client.get(self.locked_url)
self.assertTemplateUsed(response, 'lockdown/form.html')

def test_form_in_context(self):
"""Test if the login form contains a proper password field"""
response = self.client.get(self.locked_url)
form = response.context['form']
self.failUnless('password' in form.fields)

def test_global_disable(self):
"""Test that a page isn't locked when LOCKDOWN_ENABLED=False"""
_old_enabled = settings.ENABLED
settings.ENABLED = False
try:
Expand All @@ -64,6 +72,11 @@ def test_global_disable(self):
settings.ENABLED = _old_enabled

def test_url_exceptions(self):
"""Test that a page isn't locked when it's URL is in the exception list
The excepted URLs are determinated by the
LOCKDOWN_URL_EXCEPTIONS setting.
"""
_old_url_exceptions = settings.URL_EXCEPTIONS
settings.URL_EXCEPTIONS = (r'/view/$',)
middleware._default_url_exceptions = \
Expand All @@ -78,15 +91,19 @@ def test_url_exceptions(self):
middleware.compile_url_exceptions(settings.URL_EXCEPTIONS)

def test_submit_password(self):
"""Test that access to locked content works with the correct password"""
response = self.client.post(self.locked_url, {'password': 'letmein'},
follow=True)
self.assertContains(response, self.locked_contents)

def test_submit_wrong_password(self):
"""Test that access to locked content doesn't work with wrong passwords
"""
response = self.client.post(self.locked_url, {'password': 'imacrook'})
self.assertContains(response, 'Incorrect password.')

def test_custom_form(self):
"""Test if access using a custom lockdown form works"""
_old_form = settings.FORM
settings.FORM = 'lockdown.tests.forms.CustomLockdownForm'
middleware._default_form = middleware.get_lockdown_form(settings.FORM)
Expand All @@ -102,7 +119,6 @@ def test_custom_form(self):

def test_invalid_custom_form(self):
"""Test that pointing to an invalid form properly produces an error"""

# no form configured at all
self.assertRaises(ImproperlyConfigured,
middleware.get_lockdown_form, None)
Expand All @@ -117,6 +133,7 @@ def test_invalid_custom_form(self):
middleware.get_lockdown_form, 'lockdown.forms.foo')

def test_locked_until(self):
"""Test locking until a certain date"""
_old_until_date = settings.UNTIL_DATE
yesterday = datetime.datetime.now() - datetime.timedelta(days=1)
tomorrow = datetime.datetime.now() + datetime.timedelta(days=1)
Expand All @@ -133,6 +150,7 @@ def test_locked_until(self):
settings.UNTIL_DATE = _old_until_date

def test_locked_after(self):
"""Test locking starting at a certain date"""
_old_after_date = settings.AFTER_DATE
yesterday = datetime.datetime.now() - datetime.timedelta(days=1)
tomorrow = datetime.datetime.now() + datetime.timedelta(days=1)
Expand All @@ -149,6 +167,7 @@ def test_locked_after(self):
settings.AFTER_DATE = _old_after_date

def test_locked_until_and_after(self):
"""Test locking until a certain date and starting at another date"""
_old_until_date = settings.UNTIL_DATE
_old_after_date = settings.AFTER_DATE
yesterday = datetime.datetime.now() - datetime.timedelta(days=1)
Expand All @@ -175,10 +194,13 @@ def test_locked_until_and_after(self):


class DecoratorTests(BaseTests):
"""Tests for using lockdown via decorators"""

locked_url = '/locked/view/'
locked_contents = 'A locked view.'

def test_overridden_settings(self):
"""Test that locking works when overriding decorator arguments"""
url = '/overridden/locked/view/'

response = self.client.post(url, {'password': 'letmein'}, follow=True)
Expand All @@ -189,17 +211,21 @@ def test_overridden_settings(self):


class MiddlewareTests(BaseTests):
"""Tests for using lockdown via its middleware"""

locked_url = '/a/view/'
locked_contents = 'A view.'

def setUp(self):
"""Additional setup for middleware tests"""
super(MiddlewareTests, self).setUp()
self._old_middleware_classes = django_settings.MIDDLEWARE_CLASSES
django_settings.MIDDLEWARE_CLASSES += (
'lockdown.middleware.LockdownMiddleware',
)

def tearDown(self):
"""Additional tear down for middleware tests"""
django_settings.MIDDLEWARE_CLASSES = self._old_middleware_classes
super(MiddlewareTests, self).tearDown()

Expand All @@ -208,8 +234,11 @@ def tearDown(self):
__all__.append('AuthFormTests')

class AuthFormTests(LockdownTestCase):
"""Tests for using the auth form for previewing locked pages"""

def test_using_form(self):
"""Test if unauthorized access to a locked page shows the auth form
"""
url = '/auth/user/locked/view/'
response = self.client.get(url)

Expand All @@ -219,12 +248,15 @@ def test_using_form(self):
self.failUnless(isinstance(form, AuthForm))

def add_user(self, username='test', password='pw', **kwargs):
"""Adds a user used for testing the auth form"""
from django.contrib.auth.models import User
user = User(username=username, **kwargs)
user.set_password(password)
user.save()

def test_user(self):
"""Test access to a locked page which requires an authorized user
"""
url = '/auth/user/locked/view/'
self.add_user()

Expand All @@ -239,6 +271,7 @@ def test_user(self):
self.assertTemplateNotUsed(response, 'lockdown/form.html')

def test_staff(self):
"""Test access to a locked page which requires a staff user"""
url = '/auth/staff/locked/view/'
self.add_user(username='user')
self.add_user(username='staff', is_staff=True)
Expand All @@ -259,9 +292,12 @@ def test_staff(self):
self.assertTemplateNotUsed(response, 'lockdown/form.html')

def test_superuser(self):
"""Test access to a locked page which requires a superuser"""
url = '/auth/superuser/locked/view/'
self.add_user(username='staff', is_staff=True)
self.add_user(username='superuser', is_staff=True, is_superuser=True)
self.add_user(username='superuser',
is_staff=True,
is_superuser=True)

# Non-superuser.
post_data = {'username': 'staff', 'password': 'pw'}
Expand Down
2 changes: 1 addition & 1 deletion lockdown/tests/urls.py
Expand Up @@ -12,4 +12,4 @@
(r'^auth/staff/locked/view/$', 'staff_locked_view'),
(r'^auth/superuser/locked/view/$',
'superuser_locked_view'),
)
)
9 changes: 9 additions & 0 deletions lockdown/tests/views.py
Expand Up @@ -5,29 +5,38 @@


def a_view(request):
"""Regular unlocked view"""
return HttpResponse('A view.')


@lockdown()
def locked_view(request):
"""View, locked by the default lockdown decorator"""
return HttpResponse('A locked view.')


@lockdown(passwords=('squirrel',))
def overridden_locked_view(request):
"""View, locked by the lockdown decorator with a custom password"""
return HttpResponse('A locked view.')


@lockdown(form=AuthForm, staff_only=False)
def user_locked_view(request):
"""View, locked by the lockdown decorator with access for known users only
"""
return HttpResponse('A locked view.')


@lockdown(form=AuthForm)
def staff_locked_view(request):
"""View, locked by the lockdown decorator with access for staff users only
"""
return HttpResponse('A locked view.')


@lockdown(form=AuthForm, superusers_only=True)
def superuser_locked_view(request):
"""View, locked by the lockdown decorator with access for superusers only
"""
return HttpResponse('A locked view.')

0 comments on commit 25d8c9c

Please sign in to comment.