Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

[Bug 794439] Int safety for page numbers.

Page numbers now use a util function smart_int, that will return a
default value in the case of any problems.
  • Loading branch information...
commit cd9a2d42d06d2ad261c8a28b0c8ae0ac1718ecc7 1 parent dc6268c
@mythmon authored
View
5 fjord/analytics/views.py
@@ -6,6 +6,7 @@
from tower import ugettext as _
from fjord.base.helpers import locale_name
+from fjord.base.util import smart_int
from fjord.feedback.models import SimpleIndex
@@ -77,7 +78,7 @@ def from_map(source, item):
@es_required_or_50x(error_template='analytics/es_down.html')
@mobile_template('analytics/{mobile/}dashboard.html')
def dashboard(request, template):
- page = int(request.GET.get('page', 1))
+ page = smart_int(request.GET.get('page', 1), 1)
search_happy = request.GET.get('happy', None)
search_platform = request.GET.get('platform', None)
search_locale = request.GET.get('locale', None)
@@ -152,7 +153,7 @@ def dashboard(request, template):
# p['time'] is number of milliseconds since the epoch. Which is
# convenient, because that is what the front end wants.
happy_data = [(p['time'], p['count']) for p in histograms['happy']]
- sad_data = [(p['time'], int(p['count'])) for p in histograms['sad']]
+ sad_data = [(p['time'], p['count']) for p in histograms['sad']]
histogram = [
{'label': _('Happy'), 'name': 'happy', 'data': happy_data},
View
22 fjord/base/tests/test__util.py
@@ -1,7 +1,8 @@
# -*- coding: utf-8 -*-
from nose.tools import eq_
-from fjord.base.util import smart_truncate
+from fjord.base.tests import TestCase
+from fjord.base.util import smart_truncate, smart_int
def test_smart_truncate():
@@ -10,3 +11,22 @@ def test_smart_truncate():
eq_(smart_truncate(u'abc def', length=4), u'abc...')
eq_(smart_truncate(u'abcdef', length=4), u'abcd...')
eq_(smart_truncate(u'ééé ééé', length=4), u'ééé...')
+
+
+class SmartIntTestCase(TestCase):
+ def test_sanity(self):
+ eq_(10, smart_int('10'))
+ eq_(10, smart_int('10.5'))
+
+ def test_int(self):
+ eq_(10, smart_int(10))
+
+ def test_invalid_string(self):
+ eq_(0, smart_int('invalid'))
+
+ def test_empty_string(self):
+ eq_(0, smart_int(''))
+
+ def test_wrong_type(self):
+ eq_(0, smart_int(None))
+ eq_(10, smart_int([], 10))
View
8 fjord/base/util.py
@@ -19,3 +19,11 @@ def smart_truncate(content, length=100, suffix='...'):
return content
else:
return content[:length].rsplit(' ', 1)[0] + suffix
+
+
+def smart_int(string, fallback=0):
+ """Convert a string to int, with fallback for invalid strings or types."""
+ try:
+ return int(float(string))
+ except (ValueError, TypeError):
+ return fallback
Please sign in to comment.
Something went wrong with that request. Please try again.