diff --git a/django_boost/templatetags/boost_url.py b/django_boost/templatetags/boost_url.py index 68d4a76..dedfd98 100644 --- a/django_boost/templatetags/boost_url.py +++ b/django_boost/templatetags/boost_url.py @@ -4,6 +4,8 @@ from django.template import Library +from django_boost.utils.itertools import chunked + register = Library() @@ -25,8 +27,8 @@ def replace_parameters(request, *args): raise LookupError( "The number of arguments must be odd, but %s was given" % arg_len) url_dict = request.GET.copy() - for i in range(0, arg_len, 2): - url_dict[args[i]] = str(args[i + 1]) + for k, v in chunked(args, 2): + url_dict[k] = str(v) return url_dict.urlencode() diff --git a/tests/tests/test_template_tags.py b/tests/tests/test_template_tags.py index 0191721..645dd62 100644 --- a/tests/tests/test_template_tags.py +++ b/tests/tests/test_template_tags.py @@ -1,3 +1,5 @@ +from django.test.client import RequestFactory + from django_boost.test import TestCase @@ -6,7 +8,57 @@ class TestBoostTemplateTag(TestCase): class TestBoostUrlTemplateTag(TestCase): - pass + + def test_urlencode(self): + from django_boost.templatetags.boost_url import urlencode + cases = [ + ("日本語", "%E6%97%A5%E6%9C%AC%E8%AA%9E"), + ("https://google.com", "https%3A//google.com") + ] + for a, e in cases: + self.assertEqual(urlencode(a), e) + + def test_urldecode(self): + from django_boost.templatetags.boost_url import urldecode + + cases = [ + ("%E6%97%A5%E6%9C%AC%E8%AA%9E", "日本語"), + ("https%3A//google.com", "https://google.com") + ] + for a, e in cases: + self.assertEqual(urldecode(a), e) + + def test_replace_parameters(self): + from django_boost.templatetags.boost_url import replace_parameters + + cases = [ + ("", ('p', 'p'), ("p=p",)), + ("q=q", ('p', 'p'), ("q=q", "p=p")), + ("q=q", ('q', 'x', 'p', 'p'), ("q=x", "p=p")), + ] + factory = RequestFactory() + for qs, args, expected in cases: + request = factory.request(**{'QUERY_STRING': qs}) + actual = replace_parameters(request, *args) + for e in expected: + self.assertIn(e, actual) + + with self.assertRaises(LookupError): + request = factory.request() + replace_parameters(request, 'q') + + def test_get_querystring(self): + from django_boost.templatetags.boost_url import get_querystring + + cases = [ + ("", "q", None), + ("q=q", "q", "q"), + ("q=q&q=j&q=k", "q", "k"), + ] + factory = RequestFactory() + for qs, key, value in cases: + request = factory.request(**{'QUERY_STRING': qs}) + self.assertEqual(get_querystring(request, key), value) class TestBoostQueryTemplateTag(TestCase):