Pendatic fix for comments

- one day I'll make up my mind on style
parent 46c5a592
Pipeline #1105 passed with stage
in 1 minute and 1 second
...@@ -11,7 +11,7 @@ from go.models import URL, RegisteredUser ...@@ -11,7 +11,7 @@ from go.models import URL, RegisteredUser
class URLAdmin(admin.ModelAdmin): class URLAdmin(admin.ModelAdmin):
""" """
Define what attributes display in the URL Admin Define what attributes display in the URL Admin
""" """
list_display = ("target", "short", "owner", "clicks", "date_created", "expires") list_display = ("target", "short", "owner", "clicks", "date_created", "expires")
...@@ -21,7 +21,7 @@ admin.site.register(URL, URLAdmin) ...@@ -21,7 +21,7 @@ admin.site.register(URL, URLAdmin)
class RegisteredUserInline(admin.StackedInline): class RegisteredUserInline(admin.StackedInline):
""" """
Define an inline admin descriptor for User model Define an inline admin descriptor for User model
""" """
model = RegisteredUser model = RegisteredUser
...@@ -29,7 +29,7 @@ class RegisteredUserInline(admin.StackedInline): ...@@ -29,7 +29,7 @@ class RegisteredUserInline(admin.StackedInline):
class UserAdmin(UserAdmin): class UserAdmin(UserAdmin):
""" """
Define a new User admin Define a new User admin
""" """
# see above class that we defined # see above class that we defined
......
...@@ -5,13 +5,14 @@ from __future__ import unicode_literals, absolute_import, print_function, divisi ...@@ -5,13 +5,14 @@ from __future__ import unicode_literals, absolute_import, print_function, divisi
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.conf import settings from django.conf import settings
# third party imports # Other Imports
import requests import requests
"""
parse what peoplefinder sends back to us and make a list out of it
"""
def pfparse(pf_name_result): def pfparse(pf_name_result):
"""
Parse what peoplefinder sends back to us and make a list out of it
"""
# name comes in format of Anderson, Nicholas J # name comes in format of Anderson, Nicholas J
name_list = pf_name_result.split(',') name_list = pf_name_result.split(',')
# there's random whitespace with the first name # there's random whitespace with the first name
...@@ -27,10 +28,11 @@ def pfparse(pf_name_result): ...@@ -27,10 +28,11 @@ def pfparse(pf_name_result):
new_name_list = [first_name, name_list[0]] new_name_list = [first_name, name_list[0]]
return new_name_list return new_name_list
"""
get information from peoplefinder
"""
def pfinfo(uname): def pfinfo(uname):
"""
Get information from peoplefinder
"""
base_url = settings.PF_URL base_url = settings.PF_URL
url = base_url + "basic/all/" + str(uname) url = base_url + "basic/all/" + str(uname)
try: try:
...@@ -65,16 +67,16 @@ def pfinfo(uname): ...@@ -65,16 +67,16 @@ def pfinfo(uname):
# if the name is not in peoplefinder, return empty first and last name # if the name is not in peoplefinder, return empty first and last name
except IndexError as ex: except IndexError as ex:
print("Name not found in peoplefinder.") print("Name not found in peoplefinder.")
return ['',''] return ['', '']
except Exception as ex: except Exception as ex:
print("Unknown peoplefinder error:", ex) print("Unknown peoplefinder error:", ex)
print("Returning empty user info tuple.") print("Returning empty user info tuple.")
return ['', ''] return ['', '']
"""
create a django user based off of the peoplefinder info we parsed earlier
"""
def create_user(tree): def create_user(tree):
"""
Create a django user based off of the peoplefinder info we parsed earlier
"""
print("Parsing CAS information.") print("Parsing CAS information.")
try: try:
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
from __future__ import unicode_literals, absolute_import, print_function, division from __future__ import unicode_literals, absolute_import, print_function, division
# Python stdlib Imports # Python stdlib Imports
from datetime import date, datetime, timedelta from datetime import datetime, timedelta
from six.moves import urllib from six.moves import urllib
# Django Imports # Django Imports
...@@ -22,11 +22,16 @@ from bootstrap3_datetime.widgets import DateTimePicker ...@@ -22,11 +22,16 @@ from bootstrap3_datetime.widgets import DateTimePicker
class URLForm(forms.ModelForm): class URLForm(forms.ModelForm):
""" """
The form that is used in URL creation. The form that is used in URL creation.
""" """
# Prevent redirect loop links # target -------------------------------------------------------------------
def clean_target(self): def clean_target(self):
"""
Prevent redirect loop links
"""
# get the entered target link # get the entered target link
target = self.cleaned_data.get('target') target = self.cleaned_data.get('target')
try: try:
...@@ -57,13 +62,19 @@ class URLForm(forms.ModelForm): ...@@ -57,13 +62,19 @@ class URLForm(forms.ModelForm):
}) })
) )
# Check to make sure the short url has not been used # short --------------------------------------------------------------------
def unique_short(value): def unique_short(value):
"""
Check to make sure the short url has not been used
"""
try: try:
# if we're able to get a URL with the same short url # if we're able to get a URL with the same short url
URL.objects.get(short__iexact=value) URL.objects.get(short__iexact=value)
except URL.DoesNotExist as ex: except URL.DoesNotExist as ex:
return return
# then raise a ValidationError # then raise a ValidationError
raise ValidationError('Short url already exists.') raise ValidationError('Short url already exists.')
...@@ -77,14 +88,16 @@ class URLForm(forms.ModelForm): ...@@ -77,14 +88,16 @@ class URLForm(forms.ModelForm):
min_length=3, min_length=3,
) )
# define some string date standards # expires ------------------------------------------------------------------
# Define some string date standards
DAY = '1 Day' DAY = '1 Day'
WEEK = '1 Week' WEEK = '1 Week'
MONTH = '1 Month' MONTH = '1 Month'
CUSTOM = 'Custom Date' CUSTOM = 'Custom Date'
NEVER = 'Never' NEVER = 'Never'
# define a tuple of string date standards to be used as our date choices # Define a tuple of string date standards to be used as our date choices
EXPIRATION_CHOICES = ( EXPIRATION_CHOICES = (
(DAY, DAY), (DAY, DAY),
(WEEK, WEEK), (WEEK, WEEK),
...@@ -102,8 +115,11 @@ class URLForm(forms.ModelForm): ...@@ -102,8 +115,11 @@ class URLForm(forms.ModelForm):
widget=forms.RadioSelect(), widget=forms.RadioSelect(),
) )
# Check if the selected date is a valid date
def valid_date(value): def valid_date(value):
"""
Check if the selected date is a valid date
"""
# a valid date is one that is greater than today # a valid date is one that is greater than today
if value > timezone.now(): if value > timezone.now():
return return
...@@ -130,8 +146,11 @@ class URLForm(forms.ModelForm): ...@@ -130,8 +146,11 @@ class URLForm(forms.ModelForm):
) )
) )
# on initialization of the form, crispy forms renders this layout
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
"""
On initialization of the form, crispy forms renders this layout
"""
# Grab that host info # Grab that host info
self.host = kwargs.pop('host', None) self.host = kwargs.pop('host', None)
super(URLForm, self).__init__(*args, **kwargs) super(URLForm, self).__init__(*args, **kwargs)
...@@ -191,8 +210,11 @@ class URLForm(forms.ModelForm): ...@@ -191,8 +210,11 @@ class URLForm(forms.ModelForm):
<br />"""), <br />"""),
StrictButton('Shorten', css_class="btn btn-primary btn-md col-md-4", type='submit'))) StrictButton('Shorten', css_class="btn btn-primary btn-md col-md-4", type='submit')))
# metadata about this ModelForm
class Meta: class Meta:
"""
Metadata about this ModelForm
"""
# what model this form is for # what model this form is for
model = URL model = URL
# what attributes are included # what attributes are included
...@@ -200,7 +222,7 @@ class URLForm(forms.ModelForm): ...@@ -200,7 +222,7 @@ class URLForm(forms.ModelForm):
class SignupForm(forms.ModelForm): class SignupForm(forms.ModelForm):
""" """
The form that is used when a user is signing up to be a RegisteredUser The form that is used when a user is signing up to be a RegisteredUser
""" """
# The full name of the RegisteredUser # The full name of the RegisteredUser
...@@ -230,15 +252,20 @@ class SignupForm(forms.ModelForm): ...@@ -230,15 +252,20 @@ class SignupForm(forms.ModelForm):
# A user becomes registered when they agree to the TOS # A user becomes registered when they agree to the TOS
registered = forms.BooleanField( registered = forms.BooleanField(
required=True, required=True,
# ***Need to replace lower url with production URL*** ie. go.gmu.edu/about#terms # ***Need to replace lower url with production URL***
# ie. go.gmu.edu/about#terms
label=mark_safe( label=mark_safe(
'Do you accept the <a href="http://127.0.0.1:8000/about#terms">Terms of Service</a>?' 'Do you accept the <a href="http://127.0.0.1:8000/about#terms">Terms of Service</a>?'
), ),
) )
# on initialization of the form, crispy forms renders this layout
def __init__(self, request, *args, **kwargs): def __init__(self, request, *args, **kwargs):
# Necessary to call request in forms.py, is otherwise restricted to views.py and models.py """
On initialization of the form, crispy forms renders this layout
"""
# Necessary to call request in forms.py, is otherwise restricted to
# views.py and models.py
self.request = request self.request = request
super(SignupForm, self).__init__(*args, **kwargs) super(SignupForm, self).__init__(*args, **kwargs)
self.helper = FormHelper() self.helper = FormHelper()
...@@ -261,8 +288,11 @@ class SignupForm(forms.ModelForm): ...@@ -261,8 +288,11 @@ class SignupForm(forms.ModelForm):
StrictButton('Submit',css_class='btn btn-primary btn-md col-md-4', type='submit'), StrictButton('Submit',css_class='btn btn-primary btn-md col-md-4', type='submit'),
css_class='col-md-6'))) css_class='col-md-6')))
# metadata about this ModelForm
class Meta: class Meta:
"""
Metadata about this ModelForm
"""
# what model this form is for # what model this form is for
model = RegisteredUser model = RegisteredUser
# what attributes are included # what attributes are included
......
...@@ -22,8 +22,8 @@ hashids = Hashids(salt="srct.gmu.edu", alphabet=(string.ascii_lowercase + string ...@@ -22,8 +22,8 @@ hashids = Hashids(salt="srct.gmu.edu", alphabet=(string.ascii_lowercase + string
@python_2_unicode_compatible @python_2_unicode_compatible
class RegisteredUser(models.Model): class RegisteredUser(models.Model):
""" """
This is simply a wrapper model for the user object which, if an object This is simply a wrapper model for the user object which, if an object
exists, indicates that that user is registered. exists, indicates that that user is registered.
""" """
# Let's associate a User to this RegisteredUser # Let's associate a User to this RegisteredUser
...@@ -53,15 +53,21 @@ class RegisteredUser(models.Model): ...@@ -53,15 +53,21 @@ class RegisteredUser(models.Model):
# Is this User Blocked? # Is this User Blocked?
blocked = models.BooleanField(default=False) blocked = models.BooleanField(default=False)
# str(RegisteredUser)
def __str__(self): def __str__(self):
"""
str(RegisteredUser)
"""
return '<Registered User: %s - Approval Status: %s>' % (self.user, self.approved) return '<Registered User: %s - Approval Status: %s>' % (self.user, self.approved)
# When a post_save is called on a User object (and it is newly created), this is
# called to create an associated RegisteredUser
@receiver(post_save, sender=User) @receiver(post_save, sender=User)
def handle_regUser_creation(sender, instance, created, **kwargs): def handle_regUser_creation(sender, instance, created, **kwargs):
"""
When a post_save is called on a User object (and it is newly created), this
is called to create an associated RegisteredUser
"""
if created: if created:
RegisteredUser.objects.create(user=instance) RegisteredUser.objects.create(user=instance)
...@@ -69,9 +75,9 @@ def handle_regUser_creation(sender, instance, created, **kwargs): ...@@ -69,9 +75,9 @@ def handle_regUser_creation(sender, instance, created, **kwargs):
@python_2_unicode_compatible @python_2_unicode_compatible
class URL(models.Model): class URL(models.Model):
""" """
This model represents a stored URL redirection rule. Each URL has an This model represents a stored URL redirection rule. Each URL has an
owner, target url, short identifier, click counter, and expiration owner, target url, short identifier, click counter, and expiration
date. date.
""" """
# Who is the owner of this Go link # Who is the owner of this Go link
...@@ -94,19 +100,27 @@ class URL(models.Model): ...@@ -94,19 +100,27 @@ class URL(models.Model):
# does this Go link expire on a certain date # does this Go link expire on a certain date
expires = models.DateTimeField(blank=True, null=True) expires = models.DateTimeField(blank=True, null=True)
# print(URL)
def __str__(self): def __str__(self):
"""
print(URL)
"""
return '<Owner: %s - Target URL: %s>' % (self.owner.user, self.target) return '<Owner: %s - Target URL: %s>' % (self.owner.user, self.target)
# metadata for URL's
class Meta: class Meta:
"""
metadata for URLs
"""
# they should be ordered by their short links # they should be ordered by their short links
ordering = ['short'] ordering = ['short']
# legacy method to ensure that generated short URL's are valid
# should be updated to be simpler
@staticmethod @staticmethod
def generate_valid_short(): def generate_valid_short():
"""
legacy method to ensure that generated short URL's are valid
should be updated to be simpler
"""
if cache.get("hashids_counter") is None: if cache.get("hashids_counter") is None:
cache.set("hashids_counter", URL.objects.count()) cache.set("hashids_counter", URL.objects.count())
cache.incr("hashids_counter") cache.incr("hashids_counter")
......
...@@ -5,17 +5,17 @@ from __future__ import unicode_literals, absolute_import, print_function, divisi ...@@ -5,17 +5,17 @@ from __future__ import unicode_literals, absolute_import, print_function, divisi
from django.test import TestCase from django.test import TestCase
# App Imports # App Imports
from go.cas_callbacks import pfparse, pfinfo, create_user from go.cas_callbacks import pfparse, pfinfo
class CasCallbacksTest(TestCase): class CasCallbacksTest(TestCase):
""" """
Test cases for the functions in call_callbacks. Test cases for the functions in call_callbacks.
""" """
def test_pf_peoplefinder_method(self): def test_pf_peoplefinder_method(self):
""" """
Presently enrolled student who has been added to peoplefinder Presently enrolled student who has been added to peoplefinder
""" """
actual = pfinfo('dhaynes3') actual = pfinfo('dhaynes3')
...@@ -24,8 +24,8 @@ class CasCallbacksTest(TestCase): ...@@ -24,8 +24,8 @@ class CasCallbacksTest(TestCase):
def test_pfparse_peoplefinder_method(self): def test_pfparse_peoplefinder_method(self):
""" """
Test the parsing method to ensure that first and last names are seperated Test the parsing method to ensure that first and last names are seperated
accordingly and correctly. accordingly and correctly.
""" """
actual = pfparse("Haynes, David M") actual = pfparse("Haynes, David M")
...@@ -34,7 +34,7 @@ class CasCallbacksTest(TestCase): ...@@ -34,7 +34,7 @@ class CasCallbacksTest(TestCase):
def test_pfinfo_ldap_method(self): def test_pfinfo_ldap_method(self):
""" """
student no longer in peoplefinder, or who hasn't yet been added student no longer in peoplefinder, or who hasn't yet been added
""" """
actual = pfinfo('lfaraone') actual = pfinfo('lfaraone')
...@@ -43,7 +43,7 @@ class CasCallbacksTest(TestCase): ...@@ -43,7 +43,7 @@ class CasCallbacksTest(TestCase):
def test_pfinfo_employee_method(self): def test_pfinfo_employee_method(self):
""" """
student employees will have their staff info return before their student info student employees will have their staff info return before their student info
""" """
actual = pfinfo('nander13') actual = pfinfo('nander13')
...@@ -52,7 +52,7 @@ class CasCallbacksTest(TestCase): ...@@ -52,7 +52,7 @@ class CasCallbacksTest(TestCase):
def test_pfinfo_dne(self): def test_pfinfo_dne(self):
""" """
a name not found for either (should never happen, but gracefully handle anyway) a name not found for either (should never happen, but gracefully handle anyway)
""" """
actual = pfinfo('bobama') actual = pfinfo('bobama')
......
...@@ -5,28 +5,28 @@ from __future__ import unicode_literals, absolute_import, print_function, divisi ...@@ -5,28 +5,28 @@ from __future__ import unicode_literals, absolute_import, print_function, divisi
from django.test import TestCase from django.test import TestCase
# App Imports # App Imports
from go.forms import * from go.forms import URLForm, SignupForm
class URLFormTest(TestCase): class URLFormTest(TestCase):
""" """
Test cases for the URL form Test cases for the URL form
""" """
def test_django_test(self): def test_django_test(self):
""" """
Default test case, does not actually test anything Default test case, does not actually test anything
""" """
self.assertEqual("Hello World!", "Hello World!") self.assertEqual("Hello World!", "Hello World!")
class SignupForm(TestCase): class SignupForm(TestCase):
""" """
Test cases for the Signup form Test cases for the Signup form
""" """
def test_django_test(self): def test_django_test(self):
""" """
Default test case, does not actually test anything Default test case, does not actually test anything
""" """
self.assertEqual("Hello World!", "Hello World!") self.assertEqual("Hello World!", "Hello World!")
...@@ -12,13 +12,13 @@ from go.models import URL, RegisteredUser ...@@ -12,13 +12,13 @@ from go.models import URL, RegisteredUser
class RegisteredUserTest(TestCase): class RegisteredUserTest(TestCase):
""" """
Test cases for the RegisteredUser Model Test cases for the RegisteredUser Model
""" """
def setUp(self): def setUp(self):
""" """
Set up any variables such as dummy objects that will be utilised in Set up any variables such as dummy objects that will be utilised in
testing methods testing methods
""" """
User.objects.create(username='dhaynes', password='password') User.objects.create(username='dhaynes', password='password')
...@@ -27,7 +27,7 @@ class RegisteredUserTest(TestCase): ...@@ -27,7 +27,7 @@ class RegisteredUserTest(TestCase):
def test_registereduser_creation(self): def test_registereduser_creation(self):
""" """
check if RegisteredUsers are actually made check if RegisteredUsers are actually made
""" """
get_user = User.objects.get(username='dhaynes') get_user = User.objects.get(username='dhaynes')
...@@ -38,7 +38,7 @@ class RegisteredUserTest(TestCase): ...@@ -38,7 +38,7 @@ class RegisteredUserTest(TestCase):
def test_full_name(self): def test_full_name(self):
""" """
check if full_name char field functions as intentioned check if full_name char field functions as intentioned
""" """
get_user = User.objects.get(username='dhaynes') get_user = User.objects.get(username='dhaynes')
...@@ -50,7 +50,7 @@ class RegisteredUserTest(TestCase): ...@@ -50,7 +50,7 @@ class RegisteredUserTest(TestCase):
def test_full_name_length(self): def test_full_name_length(self):
""" """
check if full_name char field functions as intentioned check if full_name char field functions as intentioned
""" """
get_user = User.objects.get(username='dhaynes') get_user = User.objects.get(username='dhaynes')
...@@ -74,7 +74,7 @@ class RegisteredUserTest(TestCase): ...@@ -74,7 +74,7 @@ class RegisteredUserTest(TestCase):
def test_organization(self): def test_organization(self):
""" """
check if organization char field functions as intentioned check if organization char field functions as intentioned
""" """
get_user = User.objects.get(username='dhaynes') get_user = User.objects.get(username='dhaynes')
...@@ -86,7 +86,7 @@ class RegisteredUserTest(TestCase): ...@@ -86,7 +86,7 @@ class RegisteredUserTest(TestCase):
def test_organization_length(self): def test_organization_length(self):
""" """
check if organization char field functions as intentioned check if organization char field functions as intentioned
""" """