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
...@@ -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
...@@ -25,8 +25,13 @@ class URLForm(forms.ModelForm): ...@@ -25,8 +25,13 @@ 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
...@@ -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
......
...@@ -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)
...@@ -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,7 +5,7 @@ from __future__ import unicode_literals, absolute_import, print_function, divisi ...@@ -5,7 +5,7 @@ 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):
""" """
......
...@@ -5,7 +5,7 @@ from __future__ import unicode_literals, absolute_import, print_function, divisi ...@@ -5,7 +5,7 @@ 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):
""" """
......
...@@ -5,7 +5,7 @@ from __future__ import unicode_literals, absolute_import, print_function, divisi ...@@ -5,7 +5,7 @@ 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.views import * from go.views import index, view, my_links, delete, signup, redirection, useradmin
class IndexTest(TestCase): class IndexTest(TestCase):
""" """
......
# Future Imports # Future Imports
from __future__ import unicode_literals, absolute_import, print_function, division from __future__ import unicode_literals, absolute_import, print_function, division
# Python stdlib imports
from datetime import timedelta
# Django Imports # Django Imports
from django.conf import settings from django.conf import settings
from django.http import HttpResponseServerError # Http404 from django.http import HttpResponseServerError # Http404
...@@ -12,15 +15,14 @@ from django.contrib.auth import REDIRECT_FIELD_NAME ...@@ -12,15 +15,14 @@ from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.contrib.auth.decorators import user_passes_test, login_required from django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import render, get_object_or_404, redirect from django.shortcuts import render, get_object_or_404, redirect
# Other imports
from ratelimit.decorators import ratelimit from ratelimit.decorators import ratelimit
# App Imports # App Imports
from go.models import URL, RegisteredUser from go.models import URL, RegisteredUser
from go.forms import URLForm, SignupForm from go.forms import URLForm, SignupForm
# Other Imports
from datetime import timedelta
def index(request): def index(request):
""" """
This view handles the homepage that the user is presented with when This view handles the homepage that the user is presented with when
...@@ -79,12 +81,12 @@ def index(request): ...@@ -79,12 +81,12 @@ def index(request):
'form': url_form, 'form': url_form,
}) })
#rate limits are completely arbitrary # Rate limits are completely arbitrary
@ratelimit(key='user', rate='3/m', method='POST', block=True) @ratelimit(key='user', rate='3/m', method='POST', block=True)
@ratelimit(key='user', rate='25/d', method='POST', block=True) @ratelimit(key='user', rate='25/d', method='POST', block=True)
def post(request, url_form): def post(request, url_form):
""" """
function that handles POST requests for the URL creation ProcessLookupError Function that handles POST requests for the URL creation ProcessLookupError
""" """
# We don't commit the url object yet because we need to add its # We don't commit the url object yet because we need to add its
......
...@@ -3,157 +3,174 @@ from __future__ import unicode_literals, absolute_import, print_function, divisi ...@@ -3,157 +3,174 @@ from __future__ import unicode_literals, absolute_import, print_function, divisi
# Django Imports # Django Imports
from django.test import TestCase from django.test import TestCase
from django.urls import reverse, resolve from django.urls import reverse
# App Imports
from .urls import *
# https://stackoverflow.com/questions/18987051/how-do-i-unit-test-django-urls # https://stackoverflow.com/questions/18987051/how-do-i-unit-test-django-urls
"""
Test cases for the urls
"""
class UrlsTest(TestCase): class UrlsTest(TestCase):
"""
Test cases for the urls
"""
def test_index_reverse(self):
""" """
/ - Homepage url. / - Homepage url.
""" """
def test_index_reverse(self):
url = reverse('index') url = reverse('index')
self.assertEqual(url, '/') self.assertEqual(url, '/')
def test_view_reverse_chars(self):
""" """
/view/<short> - View URL data. /view/<short> - View URL data.
""" """
def test_view_reverse_chars(self):
url = reverse('view', args=['dhaynes']) url = reverse('view', args=['dhaynes'])
self.assertEqual(url, '/view/dhaynes') self.assertEqual(url, '/view/dhaynes')
def test_view_reverse_ints(self):
""" """
/view/<short> - View URL data. /view/<short> - View URL data.
""" """
def test_view_reverse_ints(self):
url = reverse('view', args=['123456789']) url = reverse('view', args=['123456789'])
self.assertEqual(url, '/view/123456789') self.assertEqual(url, '/view/123456789')
def test_view_reverse_chars_ints(self):
""" """
/view/<short> - View URL data. /view/<short> - View URL data.
""" """
def test_view_reverse_chars_ints(self):
url = reverse('view', args=['dhaynes123']) url = reverse('view', args=['dhaynes123'])
self.assertEqual(url, '/view/dhaynes123') self.assertEqual(url, '/view/dhaynes123')
def test_view_reverse_full_slug(self):
""" """
/view/<short> - View URL data. /view/<short> - View URL data.
""" """
def test_view_reverse_full_slug(self):
url = reverse('view', args=['dhaynes123_-']) url = reverse('view', args=['dhaynes123_-'])
self.assertEqual(url, '/view/dhaynes123_-') self.assertEqual(url, '/view/dhaynes123_-')
def test_about_reverse(self):
""" """
/about - About page. /about - About page.
""" """
def test_about_reverse(self):
url = reverse('about') url = reverse('about')
self.assertEqual(url, '/about') self.assertEqual(url, '/about')
def test_signup_reverse(self):
""" """
/signup - Signup page for access. /signup - Signup page for access.
""" """
def test_signup_reverse(self):
url = reverse('signup') url = reverse('signup')
self.assertEqual(url, '/signup') self.assertEqual(url, '/signup')
def test_my_links_reverse(self):
""" """
/myLinks - My-Links page, view and review links. /myLinks - My-Links page, view and review links.
""" """
def test_my_links_reverse(self):
url = reverse('my_links') url = reverse('my_links')
self.assertEqual(url, '/myLinks') self.assertEqual(url, '/myLinks')
def test_delete_reverse_chars(self):
""" """
/delete/<short> - Delete a link, no content display. /delete/<short> - Delete a link, no content display.
""" """
def test_delete_reverse_chars(self):
url = reverse('delete', args=['dhaynes']) url = reverse('delete', args=['dhaynes'])
self.assertEqual(url, '/delete/dhaynes') self.assertEqual(url, '/delete/dhaynes')
def test_delete_reverse_ints(self):
""" """
/delete/<short> - Delete a link, no content display. /delete/<short> - Delete a link, no content display.
""" """
def test_delete_reverse_ints(self):
url = reverse('delete', args=['123456789']) url = reverse('delete', args=['123456789'])
self.assertEqual(url, '/delete/123456789') self.assertEqual(url, '/delete/123456789')
def test_delete_reverse_chars_ints(self):
""" """
/delete/<short> - Delete a link, no content display. /delete/<short> - Delete a link, no content display.
""" """
def test_delete_reverse_chars_ints(self):
url = reverse('delete', args=['dhaynes123']) url = reverse('delete', args=['dhaynes123'])
self.assertEqual(url, '/delete/dhaynes123') self.assertEqual(url, '/delete/dhaynes123')
def test_delete_reverse_full_slug(self):
""" """
/delete/<short> - Delete a link, no content display. /delete/<short> - Delete a link, no content display.
""" """
def test_delete_reverse_full_slug(self):
url = reverse('delete', args=['dhaynes123_-']) url = reverse('delete', args=['dhaynes123_-'])
self.assertEqual(url, '/delete/dhaynes123_-') self.assertEqual(url, '/delete/dhaynes123_-')
def test_registered_reverse(self):
""" """
/registered - registration complete page /registered - registration complete page
""" """