Skip to content

Commit

Permalink
Increases the strictness of Landscapes checks and improve the code st…
Browse files Browse the repository at this point in the history
…yle.
  • Loading branch information
Dunedan committed Jun 18, 2015
1 parent 5091544 commit be5c50f
Show file tree
Hide file tree
Showing 8 changed files with 61 additions and 60 deletions.
2 changes: 1 addition & 1 deletion .landscape.yml
@@ -1,4 +1,4 @@
strictness: high
strictness: veryhigh
doc-warnings: yes
test-warnings: yes
uses:
Expand Down
2 changes: 1 addition & 1 deletion lockdown/decorators.py
Expand Up @@ -3,7 +3,7 @@


def lockdown(*args, **kwargs):
"""Defines a decorator based on the LockdownMiddleware
"""Define a decorator based on the LockdownMiddleware.
This decorator takes the same arguments as the middleware, but allows a
more granular locking than the middleware.
Expand Down
12 changes: 6 additions & 6 deletions lockdown/forms.py
Expand Up @@ -7,12 +7,12 @@

class LockdownForm(forms.Form):

"""Defines a form to enter a password for accessing locked down content"""
"""Defines a form to enter a password for accessing locked down content."""

password = forms.CharField(widget=forms.PasswordInput(render_value=False))

def __init__(self, passwords=None, *args, **kwargs):
"""Initialize the form by setting the valid passwords"""
"""Initialize the form by setting the valid passwords."""
super(LockdownForm, self).__init__(*args, **kwargs)
if passwords is None:
passwords = settings.PASSWORDS
Expand Down Expand Up @@ -48,15 +48,15 @@ def show_form(self):

class AuthForm(AuthenticationForm):

"""Defines a form using Djangos authentication to access locked content
"""Defines a form using Djangos authentication to access locked content.
This form is a sample implementation of how to use a custom form to provide
access to locked down content.
"""

def __init__(self, staff_only=None, superusers_only=None, *args,
**kwargs):
"""Initialize the form by setting permissions needed for access"""
"""Initialize the form by setting permissions needed for access."""
from django.conf import settings as django_settings
super(AuthForm, self).__init__(*args, **kwargs)
if staff_only is None:
Expand All @@ -70,7 +70,7 @@ def __init__(self, staff_only=None, superusers_only=None, *args,
self.superusers_only = superusers_only

def clean(self):
"""When receiving the filled out form, check for valid access"""
"""When receiving the filled out form, check for valid access."""
cleaned_data = super(AuthForm, self).clean()
user = self.get_user()
if self.staff_only and (not user or not user.is_staff):
Expand Down Expand Up @@ -102,5 +102,5 @@ def authenticate(self, token_value):
return bool(backend.get_user(user_id))

def show_form(self):
"""Determine whether or not the form should be shown on locked pages."""
"""Determine if the form should be shown on locked pages."""
return True
12 changes: 6 additions & 6 deletions lockdown/middleware.py
Expand Up @@ -11,7 +11,7 @@


def compile_url_exceptions(url_exceptions):
"""Returns a list of compiled regex objects, containing the url exceptions
"""Return a list of compiled regex objects, containing the url exceptions.
All URLs in that list returned won't be considered as locked.
"""
Expand All @@ -21,7 +21,7 @@ def compile_url_exceptions(url_exceptions):


def get_lockdown_form(form_path):
"""Given a string pointing to a lockdown form, return a proper form class"""
"""Return a form class for a given string pointing to a lockdown form."""
if not form_path:
raise ImproperlyConfigured('No LOCKDOWN_FORM specified.')
form_path_list = form_path.split(".")
Expand All @@ -46,12 +46,12 @@ def get_lockdown_form(form_path):

class LockdownMiddleware(object):

"""Middleware to lock down a whole Django site"""
"""Middleware to lock down a whole Django site."""

def __init__(self, form=None, until_date=None, after_date=None,
logout_key=None, session_key=None, url_exceptions=None,
**form_kwargs):
"""Initialize the middleware, by setting the configuration values"""
"""Initialize the middleware, by setting the configuration values."""
if logout_key is None:
logout_key = settings.LOGOUT_KEY
if session_key is None:
Expand All @@ -65,7 +65,7 @@ def __init__(self, form=None, until_date=None, after_date=None,
self.url_exceptions = url_exceptions

def process_request(self, request):
"""Checks if each request is allowed to access the current resource"""
"""Check if each request is allowed to access the current resource."""
try:
session = request.session
except AttributeError:
Expand Down Expand Up @@ -148,7 +148,7 @@ def process_request(self, request):
context_instance=RequestContext(request))

def redirect(self, request):
"""Utility method to handle redirects"""
"""Utility method to handle redirects."""
url = request.path
querystring = request.GET.copy()
if self.logout_key and self.logout_key in request.GET:
Expand Down
4 changes: 2 additions & 2 deletions lockdown/tests/forms.py
Expand Up @@ -3,12 +3,12 @@

class CustomLockdownForm(forms.Form):

"""A form to test the behavior of using custom forms for authentication"""
"""A form to test the behavior of using custom forms for authentication."""

answer = forms.IntegerField()

def clean_answer(self):
"""Cleaning of the answer field, by checking it's value"""
"""Cleaning of the answer field, by checking it's value."""
if self.cleaned_data['answer'] == 42:
return 42
raise forms.ValidationError('Wrong answer.')
3 changes: 2 additions & 1 deletion lockdown/tests/test_settings.py
Expand Up @@ -6,7 +6,8 @@
}
}

SECRET_KEY = ''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)')
SECRET_KEY = ''.join([choice('abcdefghijklmnopqrstuvwxyz'
'0123456789!@#$%^&*(-_=+)')
for i in range(64)])

MIDDLEWARE_CLASSES = ('django.contrib.sessions.middleware.SessionMiddleware',
Expand Down
62 changes: 31 additions & 31 deletions lockdown/tests/tests.py
Expand Up @@ -12,12 +12,12 @@

class LockdownTestCase(TestCase):

"""Base class for the other tests, setting up a proper test environment"""
"""Base class for the other tests, setting up a proper test environment."""

urls = 'lockdown.tests.urls'

def setUp(self):
"""Basic setup for all tests"""
"""Basic setup for all tests."""
self._old_pw = settings.PASSWORDS
settings.PASSWORDS = ('letmein',)

Expand All @@ -26,15 +26,15 @@ 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"""
"""Tearing down all settings made for the tests after running them."""
settings.PASSWORDS = self._old_pw
settings.FORM = self._old_form
middleware._default_form = middleware.get_lockdown_form(settings.FORM)


class BaseTests(LockdownTestCase):

"""Base tests for lockdown functionality
"""Base tests for lockdown functionality.
These base tests are used for testing lockdowns decorator and middleware
functionality.
Expand All @@ -44,18 +44,18 @@ class BaseTests(LockdownTestCase):
"""

def test_lockdown_template_used(self):
"""Test if the login form template is used on locked pages"""
"""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"""
"""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"""
"""Test that a page isn't locked when LOCKDOWN_ENABLED=False."""
_old_enabled = settings.ENABLED
settings.ENABLED = False
try:
Expand All @@ -65,7 +65,7 @@ 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
"""Test that a page isn't locked when its URL is in the exception list.
The excepted URLs are determinated by the
LOCKDOWN_URL_EXCEPTIONS setting.
Expand All @@ -84,18 +84,18 @@ 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"""
"""Test that access to locked content works with a correct password."""
response = self.client.post(self.locked_url, {'password': 'letmein'},
follow=True)
self.assertEqual(response.content, self.locked_contents)

def test_submit_wrong_password(self):
"""Test access to locked content is denied for wrong passwords"""
"""Test access to locked content is denied for 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"""
"""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 @@ -110,7 +110,7 @@ def test_custom_form(self):
settings.FORM)

def test_invalid_custom_form(self):
"""Test that pointing to an invalid form properly produces an error"""
"""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 @@ -125,7 +125,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"""
"""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 @@ -142,7 +142,7 @@ def test_locked_until(self):
settings.UNTIL_DATE = _old_until_date

def test_locked_after(self):
"""Test locking starting at a certain date"""
"""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 @@ -159,7 +159,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"""
"""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 @@ -185,7 +185,7 @@ def test_locked_until_and_after(self):
settings.AFTER_DATE = _old_after_date

def test_missing_session_middleware(self):
"""Test behavior with missing session middleware
"""Test behavior with missing session middleware.
When the session middleware isn't present an ImproperlyConfigured error
is expected.
Expand Down Expand Up @@ -214,13 +214,13 @@ def test_missing_session_middleware(self):

class DecoratorTests(BaseTests):

"""Tests for using lockdown via decorators"""
"""Tests for using lockdown via decorators."""

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

def test_overridden_password(self):
"""Test that locking works when overriding the password"""
"""Test that locking works when overriding the password."""
url = '/overridden/locked/view/'

response = self.client.post(url, {'password': 'letmein'}, follow=True)
Expand All @@ -231,7 +231,7 @@ def test_overridden_password(self):
self.assertEqual(response.content, self.locked_contents)

def test_overridden_url_exceptions(self):
"""Test that locking works when overriding the url exceptions"""
"""Test that locking works when overriding the url exceptions."""
url = '/locked/view/with/exception1/'
response = self.client.post(url, follow=True)
self.assertTemplateUsed(response, 'lockdown/form.html')
Expand All @@ -242,7 +242,7 @@ def test_overridden_url_exceptions(self):
self.assertEqual(response.content, self.locked_contents)

def test_overridden_until_date(self):
"""Test that locking works when overriding the until date"""
"""Test that locking works when overriding the until date."""
url = '/locked/view/until/yesterday/'
response = self.client.post(url, follow=True)
self.assertTemplateNotUsed(response, 'lockdown/form.html')
Expand All @@ -253,7 +253,7 @@ def test_overridden_until_date(self):
self.assertTemplateUsed(response, 'lockdown/form.html')

def test_overridden_after_date(self):
"""Test that locking works when overriding the after date"""
"""Test that locking works when overriding the after date."""
url = '/locked/view/after/yesterday/'
response = self.client.post(url, follow=True)
self.assertTemplateUsed(response, 'lockdown/form.html')
Expand All @@ -264,7 +264,7 @@ def test_overridden_after_date(self):
self.assertEqual(response.content, self.locked_contents)

def test_overridden_both_dates(self):
"""Test that locking works when overriding the after date"""
"""Test that locking works when overriding the after date."""
url = '/locked/view/until/and/after/'
response = self.client.post(url, follow=True)
self.assertTemplateNotUsed(response, 'lockdown/form.html')
Expand All @@ -273,21 +273,21 @@ def test_overridden_both_dates(self):

class MiddlewareTests(BaseTests):

"""Tests for using lockdown via its middleware"""
"""Tests for using lockdown via its middleware."""

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

def setUp(self):
"""Additional setup for middleware tests"""
"""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"""
"""Additional tear down for middleware tests."""
django_settings.MIDDLEWARE_CLASSES = self._old_middleware_classes
super(MiddlewareTests, self).tearDown()

Expand All @@ -297,10 +297,10 @@ def tearDown(self):

class AuthFormTests(LockdownTestCase):

"""Tests for using the auth form for previewing locked pages"""
"""Tests for using the auth form for previewing locked pages."""

def test_using_form(self):
"""Test unauthorized access to locked page
"""Test unauthorized access to locked page.
Unauthorized access to a to locked page should show the auth form
"""
Expand All @@ -312,14 +312,14 @@ 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"""
"""Add 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"""
"""Test access to a locked page which requires authorization."""
url = '/auth/user/locked/view/'
self.add_user()

Expand All @@ -334,7 +334,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"""
"""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 @@ -355,7 +355,7 @@ def test_staff(self):
self.assertTemplateNotUsed(response, 'lockdown/form.html')

def test_superuser(self):
"""Test access to a locked page which requires a superuser"""
"""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',
Expand Down

0 comments on commit be5c50f

Please sign in to comment.