Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

fixed pylint and pep8 warnings

  • Loading branch information...
commit c5521721d18621708e217cb7342c95c09670475d 1 parent 2d3b9e6
@trey0 trey0 authored
Showing with 734 additions and 670 deletions.
  1. +2 −0  .gitignore
  2. +2 −0  doc_src/conf.py
  3. +1 −3 example/urls.py
  4. +3 −3 example/views.py
  5. +3 −2 geocamMemo/__init__.py
  6. +6 −6 geocamMemo/admin.py
  7. +1 −1  geocamMemo/authentication_example.py
  8. +11 −6 geocamMemo/forms.py
  9. +25 −25 geocamMemo/management/commands/randommemo.py
  10. 0  geocamMemo/media/geocamMemo/placeholder.txt
  11. +32 −28 geocamMemo/models.py
  12. 0  geocamMemo/{media/geocamMemo → static/external}/07-map-marker.png
  13. 0  geocamMemo/{media/geocamMemo → static/external}/103-map.png
  14. 0  geocamMemo/{media/geocamMemo → static/external}/css/jquery.mobile.css
  15. 0  geocamMemo/{media/geocamMemo → static/external}/edit_item.png
  16. 0  geocamMemo/{media/geocamMemo → static/external}/js/jquery-1.5.min.js
  17. 0  geocamMemo/{media/geocamMemo → static/external}/map.png
  18. 0  geocamMemo/{media/geocamMemo/css/site.css → static/geocamMemo/css/geocamMemo.css}
  19. +3 −0  geocamMemo/tests/__init__.py
  20. +66 −64 geocamMemo/tests/functional.py
  21. +40 −39 geocamMemo/tests/unit.py
  22. +32 −32 geocamMemo/tests/urls.py
  23. +73 −69 geocamMemo/tests/views.py
  24. +9 −9 geocamMemo/urls.py
  25. +39 −30 geocamMemo/views.py
  26. +3 −2 geocamTalk/__init__.py
  27. +6 −6 geocamTalk/admin.py
  28. +11 −6 geocamTalk/forms.py
  29. +27 −26 geocamTalk/management/commands/randomtalk.py
  30. +68 −64 geocamTalk/models.py
  31. +3 −0  geocamTalk/tests/__init__.py
  32. +16 −16 geocamTalk/tests/functional.py
  33. +56 −52 geocamTalk/tests/unit.py
  34. +36 −33 geocamTalk/tests/urls.py
  35. +105 −104 geocamTalk/tests/views.py
  36. +5 −5 geocamTalk/urls.py
  37. +50 −39 geocamTalk/views.py
View
2  .gitignore
@@ -16,3 +16,5 @@ media/css/*.r*.css
.settings
geocamMemo/authentication.py
example/media/*
+\#.*\#
+.\#*
View
2  doc_src/conf.py
@@ -44,6 +44,8 @@
# The master toctree document.
master_doc = 'index'
+# pylint: disable=W0622
+
# General information about the project.
project = u'geocamMemoWeb'
copyright = u'2008-2010 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. All Rights Reserved'
View
4 example/urls.py
@@ -4,10 +4,8 @@
# All Rights Reserved.
# __END_LICENSE__
-from django.conf.urls.defaults import *
+from django.conf.urls.defaults import * # pylint: disable=W0401
from django.conf import settings
-import geocamMemo
-import geocamTalk
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
View
6 example/views.py
@@ -5,10 +5,9 @@
# __END_LICENSE__
from django.shortcuts import render_to_response
-from django.http import HttpResponseRedirect, HttpResponseForbidden, Http404
+from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.contrib.auth import authenticate, login, logout
-from django.shortcuts import render_to_response
from django import forms
def logout_view(request):
@@ -37,4 +36,5 @@ def login_view(request):
class LoginForm(forms.Form):
username = forms.CharField(label=(u'Username'))
- password = forms.CharField(label=(u'Password'),widget=forms.PasswordInput(render_value=False))
+ password = forms.CharField(label=(u'Password'),
+ widget=forms.PasswordInput(render_value=False))
View
5 geocamMemo/__init__.py
@@ -16,12 +16,13 @@
'serial': 1
}
+
def get_version():
"""
Return the formatted version information
"""
vers = ["%(major)i.%(minor)i" % __version_info__, ]
-
+
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final':
@@ -35,7 +36,7 @@ def get_version():
from geocamUtil.MultiSettings import MultiSettings
except ImportError:
import sys
- print >>sys.stderr, "warning: geocamUtil not installed, can't load defaultSettings.py"
+ print >> sys.stderr, "warning: geocamUtil not installed, can't load defaultSettings.py"
if MultiSettings:
import django.conf
View
12 geocamMemo/admin.py
@@ -5,21 +5,21 @@
# __END_LICENSE__
from django.contrib import admin
+
from geocamMemo.models import MemoMessage
-from django.contrib import admin
+
class MemoMessageAdmin(admin.ModelAdmin):
- list_display = ('author',
+ list_display = ('author',
'content',
- 'content_timestamp',
- 'latitude',
+ 'content_timestamp',
+ 'latitude',
'longitude',
'altitude',
'accuracy',
'heading',
'speed',
- 'position_timestamp' )
+ 'position_timestamp')
list_filter = ['author']
admin.site.register(MemoMessage, MemoMessageAdmin)
-
View
2  geocamMemo/authentication_example.py
@@ -4,7 +4,7 @@
# All Rights Reserved.
# __END_LICENSE__
-GOOGLE_TOKEN = "blahblahblah" #copy paste your token
+GOOGLE_TOKEN = "blahblahblah" # copy paste your token
#SID=DQAAAK4AAABnT14QB__UrAs3MtBH-6jBOPl4jMtBEZNPvneo7wAClyUmgQCSm-_CIcjBGuQxRxWNKY1S4fC17lZbGhObYVmHPT9LnHXCiqwX8WSr2mK-sFSt0k9HSVBeelAlgEWmttPcatEVOJc_Y5v_7Kj9vg4vIPA2CY6UdJkbMW0w2F5r-xSbVH5v5UUw-wnKb-PSPhLIru9DRJIqbBQ_yz4DB6d3vJ7Z-VNrhibGm49XGoV85Q
#LSID=DQAAALAAAACeW15pZqyexp0R9ir_Cuq5dLWKCumwmhHZVcMrcTgGvAhsD8eMl237RJNcvo5nMOCjD388sRH_Vj1x7osIFT1DFAjeppjqGWu9Wq8hQJv0yz-fvHiJMk_vJDst6NyFGItSO6hiQEv-IXCjB8OUxuY2UdLSTyMrLuyoTf_7G5r4MlYDdd5pxz5iwRdkvZrm3zqOV4ugdAWaZLDRoqLznClgYUDEJhEbP8WYuHSeeu70wg
View
17 geocamMemo/forms.py
@@ -4,17 +4,20 @@
# All Rights Reserved.
# __END_LICENSE__
+import re
+from datetime import datetime
+
from django import forms
from revisions.admin import AutoRevisionForm
+
from geocamMemo.models import MemoMessage
-from datetime import datetime
-import re
+
class GeolocationTimestampDateTimeFormField(forms.DateTimeField):
def clean(self, value):
- """ datetime from geolocation timestamp
+ """ datetime from geolocation timestamp
ex: Sat Feb 19 2011 15:37:53 GMT-0800 (PST)"""
-
+
try:
if value is not None:
m = re.match(r"(\S+ \S+ \d+ \d+ \d+\:\d+\:\d+)", value)
@@ -25,11 +28,13 @@ def clean(self, value):
else:
return None
else:
- return None
+ return None
except:
raise forms.ValidationError
-
+
+
class MemoMessageForm(AutoRevisionForm):
position_timestamp = GeolocationTimestampDateTimeFormField()
+
class Meta:
model = MemoMessage
View
50 geocamMemo/management/commands/randommemo.py
@@ -4,51 +4,51 @@
# All Rights Reserved.
# __END_LICENSE__
-from django.core.management.base import BaseCommand, CommandError
-from geocamMemo.models import MemoMessage
-from django.contrib.auth.models import User
from datetime import datetime
import random
+from django.core.management.base import BaseCommand
+from django.contrib.auth.models import User
+
+from geocamMemo.models import MemoMessage
+
+
class Command(BaseCommand):
args = '<usrname(optional)> msgText'
help = 'Generates a random memo message'
def handle(self, *args, **options):
username = None
- if(len(args)):
- username = args[0]
-
+ if args:
+ username = args[0]
+
try:
- user = User.objects.get(username = username)
+ user = User.objects.get(username=username)
args = args[1:]
- except:
+ except: # pylint: disable=W0702
users = User.objects.all()
- user = users[random.randrange(0,len(users)-1)]
-
+ user = users[random.randrange(0, len(users) - 1)]
+
messageContent = " ".join(args)
-
- if(len(args) > 0):
- messageContent
- else:
+
+ if not args:
messageContent = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec elit erat, porttitor sed tempor id, eleifend et diam. Mauris quam libero, tristique non fringilla nec, suscipit ac mauris. Curabitur sed lacus et ipsum vestibulum suscipit sed a neque. Nullam sed ipsum vitae nisi imperdiet egestas nec a nisi. Mauris pulvinar massa in felis dapibus tempus. Donec in nulla tellus, vel venenatis augue. Duis nisi tellus, vehicula at egestas et, laoreet vitae quam. Ut ullamcorper fermentum facilisis. Sed dapibus odio a mi congue interdum dapibus urna placerat. Vestibulum faucibus metus sed justo convallis mollis. Mauris lorem mauris, blandit eget faucibus nec, feugiat non risus.".split()
random.shuffle(messageContent)
messageContent = " ".join(messageContent[0:random.randrange(10, 30)])
-
+
contenttimestamp = datetime.now()
msg = MemoMessage()
msg.content_timestamp = contenttimestamp
msg.content = messageContent
msg.author = user
-
- cmusvlat = 37.41029;
- cmusvlon = -122.05944;
-
- msg.latitude = cmusvlat + (random.random()-0.5)*0.02
- msg.longitude = cmusvlon + (random.random()-0.5)*0.02
- msg.accuracy = random.randrange(0,120)
-
+
+ cmusvlat = 37.41029
+ cmusvlon = -122.05944
+
+ msg.latitude = cmusvlat + (random.random() - 0.5) * 0.02
+ msg.longitude = cmusvlon + (random.random() - 0.5) * 0.02
+ msg.accuracy = random.randrange(0, 120)
+
msg.save()
-
+
print msg
-
View
0  geocamMemo/media/geocamMemo/placeholder.txt
No changes.
View
60 geocamMemo/models.py
@@ -4,20 +4,25 @@
# All Rights Reserved.
# __END_LICENSE__
+# suppress messages about defining attributes outside constructor
+# pylint: disable=W0201
+
+import time
+import datetime
+
from django.db import models
from django.contrib.auth.models import User
-import geocamUtil.anyjson as json
-import time, datetime
# from geocamMemo import authentication
+
class GeocamMessage(models.Model):
class Meta:
abstract = True
-
- server_timestamp = models.DateTimeField(auto_now_add = True)
+
+ server_timestamp = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(User, related_name="%(app_label)s_%(class)s_set")
content = models.TextField(max_length=1024)
- # removed auto_add_now from content_timestamp since revisions are also instances in the
+ # removed auto_add_now from content_timestamp since revisions are also instances in the
# same table and we don't overwrite this timestamp on an edit
content_timestamp = models.DateTimeField(blank=True)
latitude = models.FloatField(null=True, blank=True)
@@ -27,79 +32,78 @@ class Meta:
heading = models.FloatField(null=True, blank=True)
speed = models.FloatField(null=True, blank=True)
position_timestamp = models.DateTimeField(null=True, blank=True)
-
+
def get_date_string(self):
return self.content_timestamp.strftime("%m/%d/%y %H:%M:%S")
-
+
def get_date_timestamp(self):
- return int(time.mktime(self.content_timestamp.timetuple())) * 1000 # * 1000 for java timestamp
-
+ return int(time.mktime(self.content_timestamp.timetuple())) * 1000 # * 1000 for java timestamp
+
def get_author_string(self):
return get_user_string(self.author)
-
+
def title(self):
return self.content[:16] + "..." if len(self.content) > 19 else self.content
-
+
def has_geolocation(self):
return bool(self.latitude != None and self.longitude != None)
- pass
class MemoMessage(GeocamMessage):
def __unicode__(self):
return "Memo from %s on %s: %s" % (self.author.username, self.content_timestamp, self.content)
-
+
def getJson(self):
return dict(
messageId=self.pk,
userId=self.author.pk,
authorUsername=self.author.username,
- authorFullname=self.get_author_string(),
+ authorFullname=self.get_author_string(),
content=self.content,
contentTimestamp=self.get_date_timestamp(),
latitude=self.latitude,
longitude=self.longitude,
accuracy=self.accuracy,
- hasGeolocation=bool(self.has_geolocation()) )
-
+ hasGeolocation=bool(self.has_geolocation()))
+
@staticmethod
def fromJson(messageDict):
- message = MemoMessage()
+ message = MemoMessage()
if "content" in messageDict:
- message.content = messageDict["content"]
+ message.content = messageDict["content"]
if "contentTimestamp" in messageDict:
- message.content_timestamp = datetime.datetime.fromtimestamp(float(messageDict["contentTimestamp"]) / 1000)
+ message.content_timestamp = datetime.datetime.fromtimestamp(float(messageDict["contentTimestamp"]) / 1000)
if "latitude" in messageDict:
message.latitude = messageDict["latitude"]
if "longitude" in messageDict:
message.longitude = messageDict["longitude"]
if "accuracy" in messageDict:
- message.accuracy = messageDict["accuracy"]
+ message.accuracy = messageDict["accuracy"]
if "userId" in messageDict:
- message.author_id = messageDict["userId"]
- return message
-
+ message.author_id = messageDict["userId"]
+ return message
+
@staticmethod
def getMessages(author=None):
""" Message Listing Rules:
-
+
If no author is specified: all messages are displayed (latest revisions)
If author is specified: all messages are displayed from author
"""
-
+
if (author is None):
# all messages are displayed
messages = MemoMessage.objects.all()
else:
# messages displayed are from author:
- messages = MemoMessage.objects.filter(author__username=author.username)
+ messages = MemoMessage.objects.filter(author__username=author.username)
return messages.order_by('-content_timestamp')
+
def get_user_string(user):
if user.first_name and user.last_name:
return (user.first_name + " " + user.last_name)
else:
return (user.username)
-User.full_name = property(lambda u: get_user_string(u))
-
+User.full_name = property(lambda u: get_user_string(u)) # pylint: disable=W0108
View
0  geocamMemo/media/geocamMemo/07-map-marker.png → geocamMemo/static/external/07-map-marker.png
File renamed without changes
View
0  geocamMemo/media/geocamMemo/103-map.png → geocamMemo/static/external/103-map.png
File renamed without changes
View
0  geocamMemo/media/geocamMemo/css/jquery.mobile.css → geocamMemo/static/external/css/jquery.mobile.css
File renamed without changes
View
0  geocamMemo/media/geocamMemo/edit_item.png → geocamMemo/static/external/edit_item.png
File renamed without changes
View
0  geocamMemo/media/geocamMemo/js/jquery-1.5.min.js → geocamMemo/static/external/js/jquery-1.5.min.js
File renamed without changes
View
0  geocamMemo/media/geocamMemo/map.png → geocamMemo/static/external/map.png
File renamed without changes
View
0  geocamMemo/media/geocamMemo/css/site.css → geocamMemo/static/geocamMemo/css/geocamMemo.css
File renamed without changes
View
3  geocamMemo/tests/__init__.py
@@ -4,6 +4,9 @@
# All Rights Reserved.
# __END_LICENSE__
+# wildcard imports ok
+# pylint: disable=W0401
+
from geocamMemo.tests.unit import *
from geocamMemo.tests.views import *
from geocamMemo.tests.functional import *
View
130 geocamMemo/tests/functional.py
@@ -4,6 +4,9 @@
# All Rights Reserved.
# __END_LICENSE__
+# suppress bogus errors about missing class members
+# pylint: disable=E1101
+
from django.test import TestCase
from django.contrib.auth.models import User
from datetime import datetime
@@ -13,26 +16,24 @@
class GeocamMemoListViewTest(TestCase):
fixtures = ['demoUsers.json', 'demoMemoMessages.json']
-
+
def setUp(self):
self.now = datetime.now()
- pass
-
+
def tearDown(self):
pass
-
def testMessageListSizeAndOrder(self):
u = User.objects.all()[0]
self.client.login(username=u.username, password='geocam')
-
+
response = self.get_messages_response()
-
- displayedmessages = response.context['gc_msg'] # get the data object sent to the template
+
+ displayedmessages = response.context['gc_msg'] # get the data object sent to the template
displayed_message_ids = [m.pk for m in displayedmessages]
-
- messages = MemoMessage.getMessages() #descending (newest at top)
- message_ids = [m.pk for m in messages]
+
+ messages = MemoMessage.getMessages() # descending (newest at top)
+ message_ids = [m.pk for m in messages]
self.assertEqual(displayed_message_ids, message_ids, "Order should be the same")
@@ -41,100 +42,100 @@ def testMessageListDateFormat(self):
response = self.get_messages_response()
for m in messages:
self.assertContains(response, m.content_timestamp.strftime("%m/%d/%y %H:%M:%S"), None, 200)
-
+
def testMessageListAuthorFormat(self):
messages = MemoMessage.latest.all()
response = self.get_messages_response()
-
+
for m in messages:
if m.author.first_name:
- self.assertContains(response, m.author.first_name + " " + m.author.last_name)
+ self.assertContains(response, m.author.first_name + " " + m.author.last_name)
else:
- self.assertContains(response, m.author.username)
-
+ self.assertContains(response, m.author.username)
+
def testMessageListContentFormat(self):
-
+
messages = MemoMessage.latest.all()
response = self.get_messages_response()
for m in messages:
self.assertContains(response, m.content)
-
+
def testMessageListGeoLocationPresent(self):
# arrange
response = self.get_messages_response()
# act
geocount = MemoMessage.latest.exclude(latitude=None, longitude=None).count()
-
+
# assert
self.assertContains(response, "data-icon=\"geoCam-map\"", geocount)
self.assertContains(response, 'data-rel="dialog"', geocount)
-
+
def testEnsureMessagesAreFilteredByUser(self):
# arrange
user = User.objects.all()[1]
messages = MemoMessage.objects.filter(author=user.pk)
-
+
notUserMessages = MemoMessage.objects.exclude(author=user.pk)
-
+
# act
response = self.get_messages_response_filtered(user)
-
+
# assert
self.assertEqual(200, response.status_code)
for m in messages:
self.assertContains(response, m.content)
for m in notUserMessages:
- self.assertNotContains(response, m.content)
-
- def testEnsureFilteredMessageListSizeAndOrder(self):
+ self.assertNotContains(response, m.content)
+
+ def testEnsureFilteredMessageListSizeAndOrder(self):
#arrange
- u = User.objects.all()[1]
-
+ u = User.objects.all()[1]
+
#descending (newest at top)
- messages = MemoMessage.getMessages(u)
- message_ids = [m.pk for m in messages]
-
+ messages = MemoMessage.getMessages(u)
+ message_ids = [m.pk for m in messages]
+
#act
response = self.get_messages_response_filtered(u)
#Looks at last parameter of context. Denoted by -1
- displayedmessages = response.context[-1]['gc_msg'] # get the data object sent to the template
- displayed_message_ids = [m.pk for m in displayedmessages]
-
+ displayedmessages = response.context[-1]['gc_msg'] # get the data object sent to the template
+ displayed_message_ids = [m.pk for m in displayedmessages]
+
#assert
self.assertEqual(displayed_message_ids, message_ids, "Order should be the same")
-
+
def testEnsureMessageListAuthorLinksPresent(self):
- #arrange
+ #arrange
messages = MemoMessage.latest.all()
-
+
#act
response = self.get_messages_response()
-
+
#assert
- for m in messages:
+ for m in messages:
self.assertContains(response, 'href="' + reverse("memo_message_list_user", args=[m.author.username]))
-
+
def testEnsureListAuthorPresent(self):
#arrange
u = User.objects.all()[1]
-
+
#act
response = self.get_messages_response_filtered(u)
- #assert
+ #assert
self.assertContains(response, 'Memos by ' + get_user_string(u))
-
+
def testEnsureGetUserStringReturnsFullNameWhenFullNameExist(self):
#arrange
u = User(username="johndoe", password="geocam", first_name="John", last_name="Doe")
-
+
#assert
self.assertEqual('John Doe', get_user_string(u))
-
+
def testEnsureGetUserStringReturnsUserNameWhenFullNameDoesntExist(self):
#arrange
- u = User(username="johndoe", password="geocam")
+ u = User(username="johndoe", password="geocam")
#assert
self.assertEqual('johndoe', get_user_string(u))
@@ -142,28 +143,28 @@ def testEnsureGeolocationDetectionIsNotUsedOnFilteredList(self):
#arrange
u = User.objects.all()[1]
response = self.get_messages_response_filtered(u)
- self.assertNotContains(response, "navigator.geolocation.getCurrentPosition(success, failure)")
-
+ self.assertNotContains(response, "navigator.geolocation.getCurrentPosition(success, failure)")
+
def get_messages_response_filtered(self, user):
self.client.login(username=user.username, password='geocam')
response = self.client.get(reverse("memo_message_list_user", args=[user.username]))
return response
-
+
def get_messages_response(self):
u = User.objects.all()[0]
self.client.login(username=u.username, password='geocam')
response = self.client.get(reverse("memo_message_list_all"))
return response
+
class GeocamMemoMapViewTest(TestCase):
fixtures = ['demoUsers.json', 'demoMemoMessages.json']
-
def testEnsureMapCentersOnLatestMessageWithGeolocation(self):
# arrange
- MemoMessage.objects.create(content="testing",
- author = User.objects.all()[0],
- content_timestamp=datetime.now()) # newest timestamp
+ MemoMessage.objects.create(content="testing",
+ author=User.objects.all()[0],
+ content_timestamp=datetime.now()) # newest timestamp
# act
response = self.get_map_response()
@@ -175,48 +176,49 @@ def testEnsureMapDisplaysAllMessagesWithGeolocationByAllUsers(self):
#arrange
messages = MemoMessage.getMessages()
assert not messages[0].has_geolocation(), "Fixtures should have a non-geolocated message as latest"
-
- #let's find the first message that has a geoloction and ensure the map is centered on it
+
+ #let's find the first message that has a geoloction and ensure the map is centered on it
message = None
for m in messages:
if m.has_geolocation():
message = m
- break
-
+ break
+
lat = message.latitude
lon = message.longitude
#act
response = self.get_map_response()
-
+
#assert
- self.assertContains(response, "createMap("+str(lat)+","+str(lon)+")")
+ self.assertContains(response, "createMap(" + str(lat) + "," + str(lon) + ")")
self.assertContains(response, "<section id=\"map_canvas\"")
for m in messages:
if m.has_geolocation():
- self.assertContains(response, "latitude:"+str(m.latitude))
+ self.assertContains(response, "latitude:" + str(m.latitude))
else:
- self.assertNotContains(response, "google.maps.LatLng("+str(m.latitude)+","+str(m.longitude)+")")
-
+ self.assertNotContains(response, "google.maps.LatLng(" + str(m.latitude) + "," + str(m.longitude) + ")")
+
def get_map_response(self):
u = User.objects.all()[0]
self.client.login(username=u.username, password='geocam')
response = self.client.get(reverse("memo_message_map"))
return response
+
class GeocamMemoSingleMessageViewTest(TestCase):
fixtures = ['demoUsers.json', 'demoMemoMessages.json']
def testEnsureProperFieldsAreDisplayed(self):
# arrange
m = MemoMessage.latest.all()[0]
-
+
u = User.objects.all()[0]
self.client.login(username=u.username, password='geocam')
-
+
# act
response = self.client.get(reverse("memo_message_details", args=[m.pk]))
-
+
# assert
self.assertContains(response, str(m.latitude))
self.assertContains(response, str(m.longitude))
View
79 geocamMemo/tests/unit.py
@@ -8,85 +8,86 @@
from django.contrib.auth.models import User
from datetime import datetime
import time
-from geocamMemo.models import MemoMessage, get_user_string
+from geocamMemo.models import MemoMessage
+
class GeocamMemoUnitTest(TestCase):
fixtures = ['demoMemoMessages.json', "demoUsers.json"]
-
+
def setUp(self):
self.now = datetime.now()
-
+
def testEnsureMessageTitleFormatIsCorrect(self):
# arrange
message = MemoMessage.objects.create(
content="012345678901234567890123456789", content_timestamp=self.now, author_id=1)
-
+
# act
title = message.title()
-
+
# assert
self.assertEquals(19, len(title))
self.assertEquals(message.content[:16] + "...", title)
-
+
def testEnsureAuthorStringFormat(self):
#arrange
userwithoutrealname = User.objects.create(username="userwithoutrealname", password="geocam")
userwithfirstname = User.objects.create(username="userwithfirstname", password="geocam", first_name="First")
userwithlastname = User.objects.create(username="userwithlastname", password="geocam", last_name="Last")
userwithfullname = User.objects.create(username="userwithfullname", password="geocam", first_name="First", last_name="Last")
-
- messagewithoutrealname = MemoMessage.objects.create(content="userwithoutrealname",
- author=userwithoutrealname,
- content_timestamp=self.now)
- messagewithfirstname = MemoMessage.objects.create(content="userwithfirstname",
- author=userwithfirstname,
+
+ messagewithoutrealname = MemoMessage.objects.create(content="userwithoutrealname",
+ author=userwithoutrealname,
content_timestamp=self.now)
- messagewithlastname = MemoMessage.objects.create(content="userwithlastname",
- author=userwithlastname,
- content_timestamp=self.now)
- messagewithfullname = MemoMessage.objects.create(content="userwithfullname",
- author=userwithfullname,
- content_timestamp=self.now)
-
+ messagewithfirstname = MemoMessage.objects.create(content="userwithfirstname",
+ author=userwithfirstname,
+ content_timestamp=self.now)
+ messagewithlastname = MemoMessage.objects.create(content="userwithlastname",
+ author=userwithlastname,
+ content_timestamp=self.now)
+ messagewithfullname = MemoMessage.objects.create(content="userwithfullname",
+ author=userwithfullname,
+ content_timestamp=self.now)
+
#act
#assert
- self.assertEqual("userwithoutrealname", messagewithoutrealname.get_author_string())
- self.assertEqual("userwithfirstname", messagewithfirstname.get_author_string())
- self.assertEqual("userwithlastname", messagewithlastname.get_author_string())
- self.assertEqual("First Last", messagewithfullname.get_author_string())
-
+ self.assertEqual("userwithoutrealname", messagewithoutrealname.get_author_string())
+ self.assertEqual("userwithfirstname", messagewithfirstname.get_author_string())
+ self.assertEqual("userwithlastname", messagewithlastname.get_author_string())
+ self.assertEqual("First Last", messagewithfullname.get_author_string())
+
def testEnsureHasGeoLocation(self):
#arange
- nogeomessage = MemoMessage.objects.create(content="no geolocation here!",
- author_id=1,
- content_timestamp=self.now)
- geomessage = MemoMessage.objects.create(content="geolocation here!",
- author_id=1,
- latitude=0.0,
- longitude=1.0,
- content_timestamp=self.now) #one value is zero as 0 = false
-
+ nogeomessage = MemoMessage.objects.create(content="no geolocation here!",
+ author_id=1,
+ content_timestamp=self.now)
+ geomessage = MemoMessage.objects.create(content="geolocation here!",
+ author_id=1,
+ latitude=0.0,
+ longitude=1.0,
+ content_timestamp=self.now) # one value is zero as 0 = false
+
#act
#assert
assert(not nogeomessage.has_geolocation())
assert(geomessage.has_geolocation())
- def testEnsureFromJsonCreatesMessag(self):
+ def testEnsureFromJsonCreatesMessag(self):
#arrange
timestamp = datetime(2011, 04, 03, 14, 30, 00)
-
- message = dict(
+
+ message = dict(
userId=User.objects.all()[0].pk,
content="Sting!!!",
contentTimestamp=time.mktime(timestamp.timetuple()) * 1000,
latitude=1.1,
longitude=222.2,
- accuracy=60 )
-
+ accuracy=60)
+
#act
memoMessage = MemoMessage.fromJson(message)
memoMessage.save()
-
+
#assert
self.assertEqual(memoMessage.author.pk, User.objects.all()[0].pk)
self.assertEqual(memoMessage.content, "Sting!!!")
View
64 geocamMemo/tests/urls.py
@@ -4,43 +4,46 @@
# All Rights Reserved.
# __END_LICENSE__
+# suppress bogus messages about missing class members
+# pylint: disable=E1101
+
from django.test import TestCase
-from django.contrib.auth.models import User
-from datetime import datetime
-from geocamMemo.models import MemoMessage, get_user_string
+
+from geocamMemo.models import MemoMessage
+
class GeocamMemoUrls(TestCase):
fixtures = ['demoUsers.json', 'demoMemoMessages.json']
-
+
def testMessageListUrl(self):
#arrange
- path = "/memo/messages/"
+ path = "/memo/messages/"
template = "geocamMemo/message_list.html"
#act
self.assertPathRequiresLoginAndUsesTemplate(path, template)
-
+
def testMessagesJsonListUrl(self):
#arrange
path = "/memo/messages.json"
-
+
#act
guestResponse = self.getResponse(path)
-
+
#assert
self.assertEqual(403, guestResponse.status_code, "should display list. period")
-
+
def testMessageJsonListUrl(self):
#arrange
pk = str(MemoMessage.latest.all()[0].pk)
path = "/memo/messages/details/" + pk + ".json"
-
+
#act
guestResponse = self.getResponse(path)
-
+
#assert
- self.assertEqual(200, guestResponse.status_code, "should display single message")
-
+ self.assertEqual(200, guestResponse.status_code, "should display single message")
+
def testMessageDetailsUrl(self):
#arrange
message = MemoMessage.latest.all()[0]
@@ -58,7 +61,7 @@ def testMessageEditUrl(self):
#act
self.assertPathRequiresLoginAndUsesTemplate(path, template)
-
+
def testMessageCreateUrl(self):
#arrange
path = "/memo/messages/create"
@@ -73,18 +76,18 @@ def testMessageCreateJSONFeed(self):
#act
guestResponse = self.client.post(path, {})
-
- #assert
+
+ #assert
self.assertEqual(403, guestResponse.status_code, "Unauthorized access if not logged in")
-
+
def testMessageListFilteredByUserUrl(self):
#arrange
path = "/memo/messages/root"
template = "geocamMemo/message_list.html"
-
+
#act
self.assertPathRequiresLoginAndUsesTemplate(path, template)
-
+
def testMessageDeleteUrl(self):
#arrange
message = MemoMessage.latest.all()[0]
@@ -92,37 +95,34 @@ def testMessageDeleteUrl(self):
#act
guestResponse = self.getResponse(path)
- self.login();
+ self.login()
memberResponse = self.getResponse(path)
-
+
#assert
self.assertEqual(302, guestResponse.status_code, "should redirect if not logged in")
self.assertEqual(302, memberResponse.status_code, "should redirect upon deletion")
-
+
def testMapViewUrl(self):
#arrange
- path = "/memo/map"
+ path = "/memo/map"
template = "geocamMemo/map.html"
#act
- self.assertPathRequiresLoginAndUsesTemplate(path, template)
-
-
+ self.assertPathRequiresLoginAndUsesTemplate(path, template)
-
-
def assertPathRequiresLoginAndUsesTemplate(self, path, template):
#act
guestResponse = self.getResponse(path)
- self.login();
+ self.login()
memberResponse = self.getResponse(path)
-
+
#assert
self.assertEqual(302, guestResponse.status_code, "should redirect if not logged in")
self.assertEqual(200, memberResponse.status_code, "should display if logged in")
self.assertTemplateUsed(memberResponse, template)
-
+
def getResponse(self, path):
return self.client.get(path)
+
def login(self):
- return self.client.login(username = "root", password = "geocam")
+ return self.client.login(username="root", password="geocam")
View
142 geocamMemo/tests/views.py
@@ -4,63 +4,68 @@
# All Rights Reserved.
# __END_LICENSE__
-from django.test import TestCase
-from django.contrib.auth.models import User
-from datetime import datetime
-from geocamMemo.models import MemoMessage, get_user_string
+# suppress bogus messages about missing class members
+# pylint: disable=E1101
+
import json
import time
+from datetime import datetime
+
+from django.test import TestCase
+from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
+from geocamMemo.models import MemoMessage
+
+
class GeocamMemoMessageSaveTest(TestCase):
fixtures = ['demoUsers.json', 'demoMemoMessages.json']
cmusv_lat = 37.41029
cmusv_lon = -122.05944
-
+
def setUp(self):
self.now = datetime.now()
- pass
-
+
def tearDown(self):
pass
def test_createMessage(self):
""" Create Geocam Message """
-
+
msgCnt = MemoMessage.latest.all().count()
-
+
content = "This is a message"
author = User.objects.get(username="rhornsby")
-
+
MemoMessage.objects.create(content=content,
latitude=GeocamMemoMessageSaveTest.cmusv_lat,
longitude=GeocamMemoMessageSaveTest.cmusv_lon,
author=author,
content_timestamp=self.now)
- newMsgCnt = MemoMessage.objects.all().count()
+ newMsgCnt = MemoMessage.objects.all().count()
self.assertEqual(msgCnt + 1, newMsgCnt, "Creating a Message Failed.")
-
+
def test_deleteMessage(self):
""" Delete Geocam Message """
-
+
msgCnt = MemoMessage.latest.all().count()
msg = MemoMessage.latest.all()[1]
# delete the first message and all it's revisions:
msg.delete()
- newMsgCnt = MemoMessage.latest.all().count()
+ newMsgCnt = MemoMessage.latest.all().count()
self.assertEqual(newMsgCnt + 1, msgCnt, "Deleting a Message Failed.")
-
+
def test_submitFormToCreateMessage(self):
-
+
content = "Whoa man, that burning building almost collapsed on me!"
author = User.objects.get(username="rhornsby")
self.client.login(username=author.username, password='geocam')
-
+
response = self.client.post(reverse("memo_create_message"),
- data={"content":content,
- "latitude":GeocamMemoMessageSaveTest.cmusv_lat,
- "longitude":GeocamMemoMessageSaveTest.cmusv_lon})
+ data={"content": content,
+ "latitude": GeocamMemoMessageSaveTest.cmusv_lat,
+ "longitude": GeocamMemoMessageSaveTest.cmusv_lon})
self.assertEqual(response.status_code, 200, "submitFormToCreateMessage Failed")
def test_submitFormToCreateMessageJSON(self):
@@ -68,44 +73,44 @@ def test_submitFormToCreateMessageJSON(self):
content = "Whoa man, that burning building almost collapsed on me!"
timestamp = self.now
author = User.objects.get(username="rhornsby")
- self.client.login(username=author.username, password='geocam')
+ self.client.login(username=author.username, password='geocam')
response = self.client.post(reverse("memo_create_message_json"),
- data={"message":json.dumps({
+ data={"message": json.dumps({
"content": content,
- "contentTimestamp":time.mktime(timestamp.timetuple()),
- "latitude":GeocamMemoMessageSaveTest.cmusv_lat,
- "longitude":GeocamMemoMessageSaveTest.cmusv_lon})})
- newMsgCnt = MemoMessage.latest.all().count()
+ "contentTimestamp": time.mktime(timestamp.timetuple()),
+ "latitude": GeocamMemoMessageSaveTest.cmusv_lat,
+ "longitude": GeocamMemoMessageSaveTest.cmusv_lon})})
+ newMsgCnt = MemoMessage.latest.all().count()
self.assertEqual(response.status_code, 200, "submitFormToCreateMessageJSON Failed")
- self.assertEqual(newMsgCnt, msgCnt+1)
-
+ self.assertEqual(newMsgCnt, msgCnt + 1)
+
def test_MessagesJsonFeed(self):
ordered_messages = MemoMessage.getMessages()
# yes the order of this dict does matter... unfortunately
- stringified_msg_list = json.dumps([msg.getJson() for msg in ordered_messages ])
+ stringified_msg_list = json.dumps([msg.getJson() for msg in ordered_messages])
self.client.login(username="rhornsby", password='geocam')
response = self.client.get(reverse("memo_message_list_all_json"))
-
- self.assertContains(response,stringified_msg_list)
-
+
+ self.assertContains(response, stringified_msg_list)
+
def test_MessageJsonFeed(self):
# arrange
msg = MemoMessage.latest.all().reverse()[0]
stringified_msg = json.dumps(msg.getJson())
-
+
#self.client.login(username="root", password='geocam')
-
+
# act
response = self.client.get(reverse("memo_message_details_json", args=[msg.pk]))
-
+
# assert
- self.assertContains(response,stringified_msg)
-
+ self.assertContains(response, stringified_msg)
+
def test_index(self):
""" Test that we are forced to login to view webroot """
-
+
response = self.client.get(reverse("memo_message_list_all"))
# expect redirect to the login page:
self.assertEqual(response.status_code, 302, "We didnt have to login to see the index page")
@@ -113,72 +118,72 @@ def test_index(self):
password='geocam'))
response = self.client.get(reverse("memo_message_list_all"))
# expect success because we are logged in:
- self.assertEqual(response.status_code, 200, "Logged in user cant see index page")
-
+ self.assertEqual(response.status_code, 200, "Logged in user cant see index page")
+
def test_login(self):
""" Make sure all users can login """
-
+
for u in User.objects.all():
self.assertTrue(self.client.login(username=u.username, password='geocam'))
+
class GeocamMemoMessageEditAndDeleteTest(TestCase):
fixtures = ['demoUsers.json', 'demoMemoMessages.json']
-
+
def loginUser(self, author_pk):
user = User.objects.get(pk=author_pk)
self.client.login(username=user.username, password='geocam')
def test_ensureEditByNonAuthorForbidden(self):
original_msg = MemoMessage.getMessages()[0]
-
+
for user in User.objects.all():
if user.username != original_msg.author.username and not user.is_superuser:
self.loginUser(user.pk)
- break
+ break
modified_content = "The content has been modified"
response = self.client.post(reverse("memo_edit_message", args=[original_msg.pk]),
- data={"content":modified_content,
- "author":original_msg.author.pk})
- self.assertEqual(response.status_code, 302, "ensureEditByNonAuthorForbidden Failed")
-
+ data={"content": modified_content,
+ "author": original_msg.author.pk})
+ self.assertEqual(response.status_code, 302, "ensureEditByNonAuthorForbidden Failed")
+
new_msg = MemoMessage.getMessages()[0]
# should be redirected when form post is successful:
self.assertEquals(new_msg.content, original_msg.content, "ensureEditByNonAuthorForbidden Failed")
self.assertNotEqual(modified_content, new_msg.content, "ensureEditByNonAuthorForbidden Failed")
- self.assertEqual(new_msg.content_timestamp, original_msg.content_timestamp, "ensureEditByNonAuthorForbidden Failed")
- self.assertEqual(new_msg.latitude, original_msg.latitude, "ensureEditByNonAuthorForbidden Failed")
- self.assertEqual(new_msg.longitude, original_msg.longitude, "ensureEditByNonAuthorForbidden Failed")
-
- def test_submitFormToEditMessage(self):
+ self.assertEqual(new_msg.content_timestamp, original_msg.content_timestamp, "ensureEditByNonAuthorForbidden Failed")
+ self.assertEqual(new_msg.latitude, original_msg.latitude, "ensureEditByNonAuthorForbidden Failed")
+ self.assertEqual(new_msg.longitude, original_msg.longitude, "ensureEditByNonAuthorForbidden Failed")
+
+ def test_submitFormToEditMessage(self):
""" submit the Memo Message through the form """
original_msg = MemoMessage.getMessages()[0]
- original_content = original_msg.content
+ original_content = original_msg.content
self.loginUser(original_msg.author.pk)
modified_content = "The content has been modified"
- response = self.client.post("/memo/messages/edit/%s"% original_msg.pk,
- data={"content":modified_content,
- "author":original_msg.author.pk})
- self.assertEqual(response.status_code, 302, "submitFormToEditMessage Failed")
-
+ response = self.client.post("/memo/messages/edit/%s" % original_msg.pk,
+ data={"content": modified_content,
+ "author": original_msg.author.pk})
+ self.assertEqual(response.status_code, 302, "submitFormToEditMessage Failed")
+
new_msg = MemoMessage.getMessages()[0]
self.assertNotEquals(new_msg.content, original_content, "submitFormToEditMessage Failed")
self.assertEqual(modified_content, new_msg.content, "submitFormToEditMessage Failed")
- self.assertEqual(new_msg.content_timestamp, original_msg.content_timestamp, "submitFormToEditMessage Failed")
- self.assertEqual(new_msg.latitude, original_msg.latitude, "submitFormToEditMessage Failed")
- self.assertEqual(new_msg.longitude, original_msg.longitude, "submitFormToEditMessage Failed")
-
+ self.assertEqual(new_msg.content_timestamp, original_msg.content_timestamp, "submitFormToEditMessage Failed")
+ self.assertEqual(new_msg.latitude, original_msg.latitude, "submitFormToEditMessage Failed")
+ self.assertEqual(new_msg.longitude, original_msg.longitude, "submitFormToEditMessage Failed")
def test_ensureDeleteByNonAuthorForbidden(self):
m = MemoMessage.latest.all()[0]
msgCnt = MemoMessage.latest.all().count()
-
+
for user in User.objects.all():
if user.pk != m.author.pk and not user.is_superuser:
self.loginUser(user.pk)
- break
- response = self.client.post("/memo/messages/delete/%s"% m.pk)
- self.assertEqual(response.status_code, 302, "ensureDeleteByNonAuthorForbidden Failed")
+ break
+ response = self.client.post("/memo/messages/delete/%s" % m.pk)
+ self.assertEqual(response.status_code, 302, "ensureDeleteByNonAuthorForbidden Failed")
newMsgCnt = MemoMessage.latest.all().count()
self.assertEqual(msgCnt, newMsgCnt, "ensureDeleteByNonAuthorForbidden Failed")
@@ -187,8 +192,7 @@ def test_deleteMessage(self):
m = MemoMessage.latest.all()[0]
msgCnt = MemoMessage.latest.all().count()
self.loginUser(m.author.pk)
- response = self.client.post("/memo/messages/delete/%s"% m.pk)
+ response = self.client.post("/memo/messages/delete/%s" % m.pk)
self.assertEqual(response.status_code, 302, "deleteMessage Failed")
newMsgCnt = MemoMessage.latest.all().count()
self.assertEqual(msgCnt - 1, newMsgCnt, "deleteMessage Failed")
-
View
18 geocamMemo/urls.py
@@ -4,27 +4,27 @@
# All Rights Reserved.
# __END_LICENSE__
-from django.conf.urls.defaults import *
+from django.conf.urls.defaults import * # pylint: disable=W0401
urlpatterns = patterns('geocamMemo.views',
url(r'messages/create.json', 'create_message_json',
name='memo_create_message_json'),
url(r'messages/create', 'create_message',
name='memo_create_message'),
- url(r'messages/edit/(?P<message_id>\d+)', 'edit_message',
+ url(r'messages/edit/(?P<message_id>\d+)', 'edit_message',
name='memo_edit_message'),
- url(r'messages/delete/(?P<message_id>\d+)', 'delete_message',
+ url(r'messages/delete/(?P<message_id>\d+)', 'delete_message',
name='memo_delete_message'),
- url(r'messages/details/(?P<message_id>\d+).json$', 'message_details_json',
+ url(r'messages/details/(?P<message_id>\d+).json$', 'message_details_json',
name="memo_message_details_json"),
- url(r'messages/details/(?P<message_id>\d+)$', 'message_details',
+ url(r'messages/details/(?P<message_id>\d+)$', 'message_details',
name="memo_message_details"),
- url(r'messages/(?P<author_username>[a-zA-Z][a-zA-Z0-9@+.\-]*[a-zA-Z0-9])', 'message_list',
+ url(r'messages/(?P<author_username>[a-zA-Z][a-zA-Z0-9@+.\-]*[a-zA-Z0-9])', 'message_list',
name="memo_message_list_user"),
- url(r'messages.json','message_list_json',
+ url(r'messages.json', 'message_list_json',
name="memo_message_list_all_json"),
- url(r'messages', 'message_list',
+ url(r'messages', 'message_list',
name="memo_message_list_all"),
- url(r'map', 'message_map',
+ url(r'map', 'message_map',
name="memo_message_map"),
)
View
69 geocamMemo/views.py
@@ -4,30 +4,29 @@
# All Rights Reserved.
# __END_LICENSE__
-from django.http import HttpResponseRedirect, Http404, HttpResponse, HttpResponseForbidden, HttpResponseServerError
+from datetime import datetime
+import json
+
+from django.http import HttpResponseRedirect, HttpResponse, HttpResponseForbidden, HttpResponseServerError
from django.template import RequestContext
-from django.utils.translation import ugettext, ugettext_lazy as _
-from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
-from django.core import serializers
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404, render_to_response
-from django.views.generic.simple import redirect_to
-from django import forms
-from geocamMemo.models import MemoMessage, get_user_string
+
+from geocamMemo.models import MemoMessage
from geocamMemo.forms import MemoMessageForm
-from datetime import datetime
-import json
+
def get_first_geolocation(messages):
""" return the first geotagged message lat and long as tuple """
-
+
try:
return [(m.latitude, m.longitude) for m in messages if m.has_geolocation()][0]
- except:
+ except: # pylint: disable=W0702
return ()
+
@login_required
def message_map(request):
messages = MemoMessage.getMessages()
@@ -36,41 +35,48 @@ def message_map(request):
first_geolocation=get_first_geolocation(messages)),
context_instance=RequestContext(request))
+
@login_required
def message_list(request, author_username=None):
if author_username is not None:
author = get_object_or_404(User, username=author_username)
else:
- author = None
- return render_to_response('geocamMemo/message_list.html',
+ author = None
+ return render_to_response('geocamMemo/message_list.html',
dict(gc_msg=MemoMessage.getMessages(author),
- author=author),
+ author=author),
context_instance=RequestContext(request))
+
# manual not logged in response
def message_list_json(request):
- if request.user.is_authenticated():
+ if request.user.is_authenticated():
messages = MemoMessage.getMessages()
return HttpResponse(json.dumps([msg.getJson() for msg in messages]))
else:
return HttpResponseForbidden()
+
@login_required
def index(request):
return HttpResponseRedirect(reverse('memo_message_list_all'))
-
+
+
@login_required
def message_details(request, message_id):
message = get_object_or_404(MemoMessage, pk=message_id)
-
+
return render_to_response('geocamMemo/details.html',
- {'message':message},
+ {'message': message},
context_instance=RequestContext(request))
+
+
# login not yet required
def message_details_json(request, message_id):
message = get_object_or_404(MemoMessage, pk=message_id)
return HttpResponse(json.dumps(message.getJson()))
+
@login_required
def create_message(request):
if request.method == 'POST':
@@ -89,10 +95,11 @@ def create_message(request):
else:
form = MemoMessageForm()
return render_to_response('geocamMemo/message_form.html',
- dict(form=form),
+ dict(form=form),
context_instance=RequestContext(request))
-def create_message_json(request):
+
+def create_message_json(request):
if request.user.is_authenticated():
if request.method == 'POST':
jsonstring = request.POST["message"]
@@ -101,22 +108,23 @@ def create_message_json(request):
message = MemoMessage.fromJson(messageDict)
try:
message.save()
- return HttpResponse("", 200)
- except:
+ return HttpResponse("", 200)
+ except: # pylint: disable=W0702
return HttpResponseServerError()
else:
- return HttpResponseServerError()
+ return HttpResponseServerError()
else:
return HttpResponseForbidden()
-
+
+
@login_required
def edit_message(request, message_id):
message = MemoMessage.objects.get(pk=message_id)
if message.author.username != request.user.username and not request.user.is_superuser:
- return HttpResponseRedirect(reverse('memo_message_list_all')) # you get the boot!
+ return HttpResponseRedirect(reverse('memo_message_list_all')) # you get the boot!
if request.method == 'POST':
message.content = request.POST['content']
- form = MemoMessageForm(request.POST)
+ form = MemoMessageForm(request.POST)
if form.is_valid():
message.save()
return HttpResponseRedirect(reverse('memo_message_list_all'))
@@ -124,13 +132,14 @@ def edit_message(request, message_id):
return render_to_response('geocamMemo/edit_message_form.html',
dict(form=form,
message=message),
- context_instance=RequestContext(request))
+ context_instance=RequestContext(request))
else:
form = MemoMessageForm(instance=message)
- return render_to_response('geocamMemo/edit_message_form.html',
+ return render_to_response('geocamMemo/edit_message_form.html',
dict(form=form,
- message=message),
- context_instance=RequestContext(request))\
+ message=message),
+ context_instance=RequestContext(request))
+
@login_required
def delete_message(request, message_id):
View
5 geocamTalk/__init__.py
@@ -16,12 +16,13 @@
'serial': 1
}
+
def get_version():
"""
Return the formatted version information
"""
vers = ["%(major)i.%(minor)i" % __version_info__, ]
-
+
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final':
@@ -35,7 +36,7 @@ def get_version():
from geocamUtil.MultiSettings import MultiSettings
except ImportError:
import sys
- print >>sys.stderr, "warning: geocamUtil not installed, can't load defaultSettings.py"
+ print >> sys.stderr, "warning: geocamUtil not installed, can't load defaultSettings.py"
if MultiSettings:
import django.conf
View
12 geocamTalk/admin.py
@@ -5,23 +5,23 @@
# __END_LICENSE__
from django.contrib import admin
+
from geocamTalk.models import TalkMessage
from geocamTalk.models import TalkUserProfile
-from django.contrib import admin
+
class TalkMessageAdmin(admin.ModelAdmin):
- list_display = ('author',
+ list_display = ('author',
'content',
- 'content_timestamp',
- 'latitude',
+ 'content_timestamp',
+ 'latitude',
'longitude',
'altitude',
'accuracy',
'heading',
'speed',
- 'position_timestamp' )
+ 'position_timestamp')
list_filter = ['author']
admin.site.register(TalkMessage, TalkMessageAdmin)
admin.site.register(TalkUserProfile)
-
View
17 geocamTalk/forms.py
@@ -4,16 +4,19 @@
# All Rights Reserved.
# __END_LICENSE__
-from django import forms
-from geocamTalk.models import TalkMessage
from datetime import datetime
import re
+from django import forms
+
+from geocamTalk.models import TalkMessage
+
+
class GeolocationTimestampDateTimeFormField(forms.DateTimeField):
def clean(self, value):
- """ datetime from geolocation timestamp
+ """ datetime from geolocation timestamp
ex: Sat Feb 19 2011 15:37:53 GMT-0800 (PST)"""
-
+
try:
if value is not None:
m = re.match(r"(\S+ \S+ \d+ \d+ \d+\:\d+\:\d+)", value)
@@ -24,11 +27,13 @@ def clean(self, value):
else:
return None
else:
- return None
+ return None
except:
raise forms.ValidationError
-
+
+
class GeocamTalkForm(forms.ModelForm):
position_timestamp = GeolocationTimestampDateTimeFormField()
+
class Meta:
model = TalkMessage
View
53 geocamTalk/management/commands/randomtalk.py
@@ -4,12 +4,16 @@
# All Rights Reserved.
# __END_LICENSE__
-from django.core.management.base import BaseCommand, CommandError
+# suppress bogus messages about missing class members
+# pylint: disable=E1101
+
+from django.core.management.base import BaseCommand
from geocamTalk.models import TalkMessage
from django.contrib.auth.models import User
from datetime import datetime
import random
+
class Command(BaseCommand):
args = '<author username:optional> <recipient usernames(comma sep, no spaces):optional> text'
help = 'Generates a random talk message'
@@ -18,52 +22,49 @@ def handle(self, *args, **options):
username = None
if(len(args)):
username = args[0]
-
+
user = None
recipients = []
unames = None
try:
- user = User.objects.get(username = username)
+ user = User.objects.get(username=username)
args = args[1:]
- if(len(args)):
- unames = args[1].split(",");
+ if args:
+ unames = args[1].split(",")
for uname in unames:
- recipients.push(User.objects.get(username=uname))
- except:
+ recipients.push(User.objects.get(username=uname))
+ except: # pylint: disable=W0702
users = User.objects.all()
- user = users[random.randrange(0,len(users)-1)]
-
+ user = users[random.randrange(0, len(users) - 1)]
+
if(not unames):
recipients = list(User.objects.all())
random.shuffle(recipients)
- recipients = recipients[0:random.randrange(0,len(recipients)-1)]
-
+ recipients = recipients[0:random.randrange(0, len(recipients) - 1)]
+
messageContent = " ".join(args)
-
- if(len(args) > 0):
- messageContent
- else:
+
+ if not args:
messageContent = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec elit erat, porttitor sed tempor id, eleifend et diam. Mauris quam libero, tristique non fringilla nec, suscipit ac mauris. Curabitur sed lacus et ipsum vestibulum suscipit sed a neque. Nullam sed ipsum vitae nisi imperdiet egestas nec a nisi. Mauris pulvinar massa in felis dapibus tempus. Donec in nulla tellus, vel venenatis augue. Duis nisi tellus, vehicula at egestas et, laoreet vitae quam. Ut ullamcorper fermentum facilisis. Sed dapibus odio a mi congue interdum dapibus urna placerat. Vestibulum faucibus metus sed justo convallis mollis. Mauris lorem mauris, blandit eget faucibus nec, feugiat non risus.".split()
random.shuffle(messageContent)
messageContent = " ".join(messageContent[0:random.randrange(10, 30)])
-
+
contenttimestamp = datetime.now()
msg = TalkMessage()
msg.content_timestamp = contenttimestamp
msg.content = messageContent
msg.author = user
- cmusvlat = 37.41029;
- cmusvlon = -122.05944;
-
- msg.latitude = cmusvlat + (random.random()-0.5)*0.02
- msg.longitude = cmusvlon + (random.random()-0.5)*0.02
- msg.accuracy = random.randrange(0,120)
-
+ cmusvlat = 37.41029
+ cmusvlon = -122.05944
+
+ msg.latitude = cmusvlat + (random.random() - 0.5) * 0.02
+ msg.longitude = cmusvlon + (random.random() - 0.5) * 0.02
+ msg.accuracy = random.randrange(0, 120)
+
msg.save()
msg.recipients = recipients
-
+
msg.push_to_phone(True)
-
+
print msg
-
View
132 geocamTalk/models.py
@@ -4,31 +4,37 @@
# All Rights Reserved.
# __END_LICENSE__
+# suppress bogus messages about missing class members
+# suppress messages about defining class members outside constructor
+# pylint: disable=E1101,W0201
+
+import httplib
+import urllib
+import datetime
+
from django.db import models
-from geocamMemo.models import GeocamMessage, get_user_string
from django.contrib.auth.models import User
-from django.core.files.base import ContentFile
-import datetime
-import time, sys
from django.db.models import Q, Count
-import httplib
-import urllib
-from geocamMemo.authentication import GOOGLE_TOKEN
+
+from geocamMemo.models import GeocamMessage
+from geocamMemo import settings
+
class TalkUserProfile(models.Model):
user = models.ForeignKey(User, related_name='profile')
last_viewed_mymessages = models.IntegerField(default=0)
registration_id = models.CharField(max_length=128)
-
+
def getUnreadMessageCount(self):
return TalkMessage.getMessages(self.user).filter(
pk__gt=self.last_viewed_mymessages).count()
User.profile = property(lambda u: TalkUserProfile.objects.get_or_create(user=u)[0])
+
class TalkMessage(GeocamMessage):
- """ This is the data model for Memo application messages
-
+ """ This is the data model for Memo application messages
+
Some of the Versioned Model API:
VersionedModel.get_latest_revision()
VersionedModel.get_revisions()
@@ -36,109 +42,107 @@ class TalkMessage(GeocamMessage):
VersionedModel.revert_to(criterion)
VersionedModel.save(new_revision=True, *vargs, **kwargs)
VersionedModel.show_diff_to(to, field)
- complete API and docs are here:
+ complete API and docs are here:
http://stdbrouw.github.com/django-revisions/
"""
- #TODO - add time to filename location
- audio_file = models.FileField(null=True, blank=True, upload_to='geocamTalk/audio/%Y/%m/%d') #"%s-audio" % (GeocamMessage.author))
-
+ # TODO - add time to filename location
+ audio_file = models.FileField(null=True, blank=True, upload_to='geocamTalk/audio/%Y/%m/%d') # "%s-audio" % (GeocamMessage.author))
+
def __unicode__(self):
try:
- str = "Talk message from %s to %s on %s: %s" % (self.author.username, self.recipients.all(), self.content_timestamp, self.content)
- except:
- str = "Talk message from %s on %s: %s" % (self.author.username, self.content_timestamp, self.content)
- return str
-
+ s = "Talk message from %s to %s on %s: %s" % (self.author.username, self.recipients.all(), self.content_timestamp, self.content)
+ except: # pylint: disable=W0702
+ s = "Talk message from %s on %s: %s" % (self.author.username, self.content_timestamp, self.content)
+ return s
+
recipients = models.ManyToManyField(User, null=True, blank=True, related_name="received_messages")
-
+
def getJson(self):
- return dict(messageId=self.pk,
- userId=self.author.pk,
- authorUsername=self.author.username,
- authorFullname=self.get_author_string(),
- recipients=[r.username for r in self.recipients.all()],
- content=self.content,
- contentTimestamp=self.get_date_timestamp(),
- latitude=self.latitude,
- longitude=self.longitude,
- accuracy=self.accuracy,
- audioUrl=self.get_audio_url(),
- hasGeolocation=bool(self.has_geolocation()) )
-
+ return dict(messageId=self.pk,
+ userId=self.author.pk,
+ authorUsername=self.author.username,
+ authorFullname=self.get_author_string(),
+ recipients=[r.username for r in self.recipients.all()],
+ content=self.content,
+ contentTimestamp=self.get_date_timestamp(),
+ latitude=self.latitude,
+ longitude=self.longitude,
+ accuracy=self.accuracy,
+ audioUrl=self.get_audio_url(),
+ hasGeolocation=bool(self.has_geolocation()))
+
@staticmethod
def fromJson(messageDict):
- message = TalkMessage()
+ message = TalkMessage()
if "content" in messageDict:
- message.content = messageDict["content"]
+ message.content = messageDict["content"]
if "contentTimestamp" in messageDict:
- message.content_timestamp = datetime.datetime.fromtimestamp(float(messageDict["contentTimestamp"]) / 1000)
+ message.content_timestamp = datetime.datetime.fromtimestamp(float(messageDict["contentTimestamp"]) / 1000)
if "latitude" in messageDict:
message.latitude = messageDict["latitude"]
if "longitude" in messageDict:
message.longitude = messageDict["longitude"]
if "accuracy" in messageDict:
- message.accuracy = messageDict["accuracy"]
+ message.accuracy = messageDict["accuracy"]
if "userId" in messageDict:
- message.author_id = messageDict["userId"]
- return message
-
+ message.author_id = messageDict["userId"]
+ return message
+
@staticmethod
def getMessages(recipient=None, author=None):
""" Message Listing Rules:
-
+
If no users are specified: all messages are displayed (latest revisions)
If only author is specified: all messages are displayed from author
If only recipient is specified: messages displayed are broadcast + from OR to recipient
If both recipient AND author are specified: messages displayed are braodcast + from author AND to recipient
-
+
Note: a broadcast message is a message with no recipients
"""
if (recipient is None and author is None):
- # all messages are displayed (latest revisions)
+ # all messages are displayed (latest revisions)
messages = TalkMessage.latest.all()
elif (recipient is None and author is not None):
# messages displayed are from author:
- messages = TalkMessage.latest.filter(author__username=author.username)
+ messages = TalkMessage.latest.filter(author__username=author.username)
elif (recipient is not None and author is None):
# messages displayed are broadcast + from OR to recipient:
- messages = TalkMessage.latest.annotate(num_recipients=Count('recipients')).filter(Q(num_recipients=0) | Q(recipients__username=recipient.username) | Q(author__username=recipient.username)).distinct()
- else:
+ messages = TalkMessage.latest.annotate(num_recipients=Count('recipients')).filter(Q(num_recipients=0) | Q(recipients__username=recipient.username) | Q(author__username=recipient.username)).distinct()
+ else:
# messages displayed are braodcast + from author AND to recipient
- messages = TalkMessage.latest.annotate(num_recipients=Count('recipients')).filter(Q(num_recipients=0) | Q(recipients__username=recipient.username)).filter(author__username=author.username).distinct()
+ messages = TalkMessage.latest.annotate(num_recipients=Count('recipients')).filter(Q(num_recipients=0) | Q(recipients__username=recipient.username)).filter(author__username=author.username).distinct()
return messages.order_by('-content_timestamp')
-
+
@staticmethod
def getLargestMessageId():
return TalkMessage.objects.all().order_by('-pk')[0].pk
-
+
def has_audio(self):
- return bool(self.audio_file != '')
-
- def push_to_phone(self, pushToSender = True):
-
-
+ return bool(self.audio_file != '')
+
+ def push_to_phone(self, pushToSender=True):
push_recipients = self.recipients.all()
if(push_recipients.count() == 0):
- push_recipients = User.objects.all();
-
+ push_recipients = User.objects.all()
+
for user in push_recipients:
if(user.profile.registration_id):
if(pushToSender == True or user.pk != self.author.pk):
# we need the following params set per http://code.google.com/android/c2dm/index.html#push
params = urllib.urlencode({
'registration_id': user.profile.registration_id,
- 'collapse_key': "message"+str(self.pk),
+ 'collapse_key': "message" + str(self.pk),
'data.message_id': str(self.pk),
- 'delay_when_idle':'TRUE',
+ 'delay_when_idle': 'TRUE',
})
-
+
# need the following headers set per http://code.google.com/android/c2dm/index.html#push
- headers = { "Content-Type":"application/x-www-form-urlencoded",
- "Content-Length":len(params),
- "Authorization":"GoogleLogin auth=" + GOOGLE_TOKEN # TOKEN set manually in authentication.py
- }
-
+ headers = {"Content-Type": "application/x-www-form-urlencoded",
+ "Content-Length": len(params),
+ "Authorization": "GoogleLogin auth=" + settings.GEOCAM_MEMO_GOOGLE_C2DM_TOKEN
+ }
+
# NOW SEND THE REQUEST TO GOOGLE SERVERS
# first we need an https connection that ignores the certificate (for now)
httpsconnection = httplib.HTTPSConnection("android.apis.google.com", 443)
View
3  geocamTalk/tests/__init__.py
@@ -4,6 +4,9 @@
# All Rights Reserved.
# __END_LICENSE__
+# wildcard imports ok
+# pylint: disable=W0401
+
from geocamTalk.tests.unit import *
from geocamTalk.tests.views import *
from geocamTalk.tests.functional import *
View
32 geocamTalk/tests/functional.py
@@ -7,52 +7,52 @@
from django.test import TestCase
from django.contrib.auth.models import User
from geocamTalk.models import TalkMessage
-from django.db.models import Q, Count
-
+
+
class GeocamTalkListViewTest(TestCase):
fixtures = ['demoUsers.json', 'demoTalkMessages.json']
-
+
def testEnsureMyMessagesAreFilteredByAuthor(self):
# arrange
author = User.objects.all()[0]
recipient = User.objects.all()[2]
- recipient_messages_from_author_or_broadcast = TalkMessage.getMessages(recipient,author)
-
+ recipient_messages_from_author_or_broadcast = TalkMessage.getMessages(recipient, author)
+
# act
response = self.get_recipient_messages_response_filtered_by_author(recipient, author)
-
+
# assert
self.assertEqual(200, response.status_code)
for m in recipient_messages_from_author_or_broadcast:
self.assertContains(response, m.content)
-
+
def testEnsureMyMessageListAuthorLinksPresent(self):
author = User.objects.all()[2]
recipient = User.objects.all()[1]
#arrange
- recipient_messages = TalkMessage.getMessages(recipient,author)
+ recipient_messages = TalkMessage.getMessages(recipient, author)
#act
response = self.get_recipient_messages_response(recipient)
-
+
#assert
- for m in recipient_messages:
+ for _ in recipient_messages:
link_to_recipient_msgs_from_author = 'href="/talk/messages/%s/%s"' % (recipient.username, author.username)
- #print 'didnt find %s in %s' % (link_to_recipient_msgs_from_author, response)
+ #print 'didnt find %s in %s' % (link_to_recipient_msgs_from_author, response)
self.assertContains(response, link_to_recipient_msgs_from_author)
-
+
def get_recipient_messages_response_filtered_by_author(self, recipient, author):
self.client.login(username=recipient.username, password='geocam')
response = self.client.get('/talk/messages/%s/%s' % (recipient.username, author.username))
- return response
-
+ return response
+
def get_recipient_messages_response(self, recipient):
self.client.login(username=recipient.username, password='geocam')
response = self.client.get('/talk/messages/' + recipient.username)
return response
-
+
def testMessageListAudioPresent(self):
# arrange
- author = User.objects.all()[2]
+ _author = User.objects.all()[2]
recipient = User.objects.all()[1]
response = self.get_recipient_messages_response(recipient)
recipient_messages = TalkMessage.getMessages(recipient)
View
108 geocamTalk/tests/unit.py
@@ -4,22 +4,29 @@
# All Rights Reserved.
# __END_LICENSE__
+# suppress bogus messages about missing class members
+# pylint: disable=E1101
+
+import array
+import os
+import random
+import string
+import time
+from datetime import datetime
+
from django.test import TestCase
from django.contrib.auth.models import User
-from datetime import datetime
-from geocamTalk.models import TalkMessage
from django.core.files.base import ContentFile
-import array, os, random
-import string
-import time
+
+from geocamTalk.models import TalkMessage
class GeocamTalkUnitTest(TestCase):
fixtures = ['demoTalkMessages.json', 'demoUsers.json']
-
+
def setUp(self):
self.now = datetime.now()
-
+
def testEnsureRecipientsCanBeAddedToAMessage(self):
# arrange
sender = User.objects.all()[0]
@@ -28,99 +35,97 @@ def testEnsureRecipientsCanBeAddedToAMessage(self):
# act
message = TalkMessage.objects.create(
- content="012345678901234567890123456789",
- content_timestamp=self.now,
+ content="012345678901234567890123456789",
+ content_timestamp=self.now,
author=sender)
-
+
message.recipients.add(recipienta)
message.recipients.add(recipientb)
-
+
# assert
self.assertEquals(2, len(message.recipients.all()), "All recipients should be added to the message")
-
+
def testCanStoreAudioMessage(self):
#arrange
sender = User.objects.all()[0]
-
+
#act
no_audio_message = TalkMessage.objects.create(
- content="012345678901234567890123456789",
+ content="012345678901234567890123456789",
content_timestamp=self.now,
- audio_file='',
+ audio_file='',
author=sender)
-
-
-
+
audio_message = TalkMessage.objects.create(
audio_file="audiofile.mp4",
- content_timestamp=self.now,
+ content_timestamp=self.now,
author=sender)
-
+
#assert
self.assertFalse(no_audio_message.has_audio())
self.assertTrue(audio_message.has_audio())
-
+
class TalkUserProfileUnitTest(TestCase):
fixtures = ['demoTalkMessages.json', 'demoUsers.json']
-
+
def testEnsureLastViewedMyMessages(self):
# arrange
user = User.objects.all()[0]
latestmsgId = TalkMessage.getLargestMessageId()
profile = user.profile
-
+
# act