Ticket #9089: urlencode-multivaluedict.2.diff

File urlencode-multivaluedict.2.diff, 2.5 KB (added by Oliver Beattie, 14 years ago)

Updated patch with better tests

  • django/utils/http.py

    diff --git a/django/utils/http.py b/django/utils/http.py
    index c93a338..4b43e58 100644
    a b import urllib  
    66import urlparse
    77from email.Utils import formatdate
    88
     9from django.utils.datastructures import MultiValueDict
    910from django.utils.encoding import smart_str, force_unicode
    1011from django.utils.functional import allow_lazy
    1112
    def urlencode(query, doseq=0):  
    4950    unicode strings. The parameters are first case to UTF-8 encoded strings and
    5051    then encoded as per normal.
    5152    """
    52     if hasattr(query, 'items'):
     53    if isinstance(query, MultiValueDict):
     54        query = query.lists()
     55    elif hasattr(query, 'items'):
    5356        query = query.items()
    5457    return urllib.urlencode(
    5558        [(smart_str(k),
  • tests/regressiontests/utils/http.py

    diff --git a/tests/regressiontests/utils/http.py b/tests/regressiontests/utils/http.py
    index 83a4a7f..3f3a36c 100644
    a b  
    11from django.utils import http
    22from django.utils import unittest
     3from django.utils.datastructures import MultiValueDict
    34
    45class TestUtilsHttp(unittest.TestCase):
    56
    class TestUtilsHttp(unittest.TestCase):  
    2122        self.assertFalse(http.same_origin('http://foo.com', 'http://foo.com.evil.com'))
    2223        # Different port
    2324        self.assertFalse(http.same_origin('http://foo.com:8000', 'http://foo.com:8001'))
     25
     26    def test_urlencode(self):
     27        # 2-tuples (the norm)
     28        result = http.urlencode((('a', 1), ('b', 2), ('c', 3)))
     29        self.assertEqual(result, 'a=1&b=2&c=3')
     30        # A dictionary
     31        result = http.urlencode({ 'a': 1, 'b': 2, 'c': 3})
     32        acceptable_results = [
     33            # Need to allow all of these as dictionaries have to be treated as
     34            # unordered
     35            'a=1&b=2&c=3',
     36            'a=1&c=3&b=2',
     37            'b=2&a=1&c=3',
     38            'b=2&c=3&a=1',
     39            'c=3&a=1&b=2',
     40            'c=3&b=2&a=1'
     41        ]
     42        self.assertTrue(result in acceptable_results)
     43        # A MultiValueDict
     44        result = http.urlencode(MultiValueDict({
     45            'name': ['Adrian', 'Simon'],
     46            'position': ['Developer']
     47        }), doseq=True)
     48        acceptable_results = [
     49            # MultiValueDicts are similarly unordered
     50            'name=Adrian&name=Simon&position=Developer',
     51            'position=Developer&name=Adrian&name=Simon'
     52        ]
     53        self.assertTrue(result in acceptable_results)
Back to Top