PageRenderTime 44ms CodeModel.GetById 2ms app.highlight 37ms RepoModel.GetById 1ms app.codeStats 0ms

/tests/regressiontests/httpwrappers/tests.py

https://code.google.com/p/mango-py/
Python | 298 lines | 284 code | 4 blank | 10 comment | 5 complexity | 325916362e34419706601a21abd5df39 MD5 | raw file
  1import copy
  2import pickle
  3
  4from django.core.exceptions import SuspiciousOperation
  5from django.http import (QueryDict, HttpResponse, HttpResponseRedirect,
  6                         HttpResponsePermanentRedirect,
  7                         SimpleCookie, BadHeaderError,
  8                         parse_cookie)
  9from django.utils import unittest
 10
 11class QueryDictTests(unittest.TestCase):
 12    def test_missing_key(self):
 13        q = QueryDict('')
 14        self.assertRaises(KeyError, q.__getitem__, 'foo')
 15
 16    def test_immutability(self):
 17        q = QueryDict('')
 18        self.assertRaises(AttributeError, q.__setitem__, 'something', 'bar')
 19        self.assertRaises(AttributeError, q.setlist, 'foo', ['bar'])
 20        self.assertRaises(AttributeError, q.appendlist, 'foo', ['bar'])
 21        self.assertRaises(AttributeError, q.update, {'foo': 'bar'})
 22        self.assertRaises(AttributeError, q.pop, 'foo')
 23        self.assertRaises(AttributeError, q.popitem)
 24        self.assertRaises(AttributeError, q.clear)
 25
 26    def test_immutable_get_with_default(self):
 27        q = QueryDict('')
 28        self.assertEqual(q.get('foo', 'default'), 'default')
 29
 30    def test_immutable_basic_operations(self):
 31        q = QueryDict('')
 32        self.assertEqual(q.getlist('foo'), [])
 33        self.assertEqual(q.has_key('foo'), False)
 34        self.assertEqual('foo' in q, False)
 35        self.assertEqual(q.items(), [])
 36        self.assertEqual(q.lists(), [])
 37        self.assertEqual(q.items(), [])
 38        self.assertEqual(q.keys(), [])
 39        self.assertEqual(q.values(), [])
 40        self.assertEqual(len(q), 0)
 41        self.assertEqual(q.urlencode(), '')
 42
 43    def test_single_key_value(self):
 44        """Test QueryDict with one key/value pair"""
 45
 46        q = QueryDict('foo=bar')
 47        self.assertEqual(q['foo'], 'bar')
 48        self.assertRaises(KeyError, q.__getitem__, 'bar')
 49        self.assertRaises(AttributeError, q.__setitem__, 'something', 'bar')
 50
 51        self.assertEqual(q.get('foo', 'default'), 'bar')
 52        self.assertEqual(q.get('bar', 'default'), 'default')
 53        self.assertEqual(q.getlist('foo'), ['bar'])
 54        self.assertEqual(q.getlist('bar'), [])
 55
 56        self.assertRaises(AttributeError, q.setlist, 'foo', ['bar'])
 57        self.assertRaises(AttributeError, q.appendlist, 'foo', ['bar'])
 58
 59        self.assertTrue(q.has_key('foo'))
 60        self.assertTrue('foo' in q)
 61        self.assertFalse(q.has_key('bar'))
 62        self.assertFalse('bar' in q)
 63
 64        self.assertEqual(q.items(), [(u'foo', u'bar')])
 65        self.assertEqual(q.lists(), [(u'foo', [u'bar'])])
 66        self.assertEqual(q.keys(), ['foo'])
 67        self.assertEqual(q.values(), ['bar'])
 68        self.assertEqual(len(q), 1)
 69
 70        self.assertRaises(AttributeError, q.update, {'foo': 'bar'})
 71        self.assertRaises(AttributeError, q.pop, 'foo')
 72        self.assertRaises(AttributeError, q.popitem)
 73        self.assertRaises(AttributeError, q.clear)
 74        self.assertRaises(AttributeError, q.setdefault, 'foo', 'bar')
 75
 76        self.assertEqual(q.urlencode(), 'foo=bar')
 77
 78    def test_urlencode(self):
 79        q = QueryDict('', mutable=True)
 80        q['next'] = '/a&b/'
 81        self.assertEqual(q.urlencode(), 'next=%2Fa%26b%2F')
 82        self.assertEqual(q.urlencode(safe='/'), 'next=/a%26b/')
 83        q = QueryDict('', mutable=True)
 84        q['next'] = u'/t\xebst&key/'
 85        self.assertEqual(q.urlencode(), 'next=%2Ft%C3%ABst%26key%2F')
 86        self.assertEqual(q.urlencode(safe='/'), 'next=/t%C3%ABst%26key/')
 87
 88    def test_mutable_copy(self):
 89        """A copy of a QueryDict is mutable."""
 90        q = QueryDict('').copy()
 91        self.assertRaises(KeyError, q.__getitem__, "foo")
 92        q['name'] = 'john'
 93        self.assertEqual(q['name'], 'john')
 94
 95    def test_mutable_delete(self):
 96        q = QueryDict('').copy()
 97        q['name'] = 'john'
 98        del q['name']
 99        self.assertFalse('name' in q)
100
101    def test_basic_mutable_operations(self):
102        q = QueryDict('').copy()
103        q['name'] = 'john'
104        self.assertEqual(q.get('foo', 'default'), 'default')
105        self.assertEqual(q.get('name', 'default'), 'john')
106        self.assertEqual(q.getlist('name'), ['john'])
107        self.assertEqual(q.getlist('foo'), [])
108
109        q.setlist('foo', ['bar', 'baz'])
110        self.assertEqual(q.get('foo', 'default'), 'baz')
111        self.assertEqual(q.getlist('foo'), ['bar', 'baz'])
112
113        q.appendlist('foo', 'another')
114        self.assertEqual(q.getlist('foo'), ['bar', 'baz', 'another'])
115        self.assertEqual(q['foo'], 'another')
116        self.assertTrue(q.has_key('foo'))
117        self.assertTrue('foo' in q)
118
119        self.assertEqual(q.items(),  [(u'foo', u'another'), (u'name', u'john')])
120        self.assertEqual(q.lists(), [(u'foo', [u'bar', u'baz', u'another']), (u'name', [u'john'])])
121        self.assertEqual(q.keys(), [u'foo', u'name'])
122        self.assertEqual(q.values(), [u'another', u'john'])
123        self.assertEqual(len(q), 2)
124
125        q.update({'foo': 'hello'})
126        self.assertEqual(q['foo'], 'hello')
127        self.assertEqual(q.get('foo', 'not available'), 'hello')
128        self.assertEqual(q.getlist('foo'), [u'bar', u'baz', u'another', u'hello'])
129        self.assertEqual(q.pop('foo'), [u'bar', u'baz', u'another', u'hello'])
130        self.assertEqual(q.pop('foo', 'not there'), 'not there')
131        self.assertEqual(q.get('foo', 'not there'), 'not there')
132        self.assertEqual(q.setdefault('foo', 'bar'), 'bar')
133        self.assertEqual(q['foo'], 'bar')
134        self.assertEqual(q.getlist('foo'), ['bar'])
135        self.assertEqual(q.urlencode(), 'foo=bar&name=john')
136
137        q.clear()
138        self.assertEqual(len(q), 0)
139
140    def test_multiple_keys(self):
141        """Test QueryDict with two key/value pairs with same keys."""
142
143        q = QueryDict('vote=yes&vote=no')
144
145        self.assertEqual(q['vote'], u'no')
146        self.assertRaises(AttributeError, q.__setitem__, 'something', 'bar')
147
148        self.assertEqual(q.get('vote', 'default'), u'no')
149        self.assertEqual(q.get('foo', 'default'), 'default')
150        self.assertEqual(q.getlist('vote'), [u'yes', u'no'])
151        self.assertEqual(q.getlist('foo'), [])
152
153        self.assertRaises(AttributeError, q.setlist, 'foo', ['bar', 'baz'])
154        self.assertRaises(AttributeError, q.setlist, 'foo', ['bar', 'baz'])
155        self.assertRaises(AttributeError, q.appendlist, 'foo', ['bar'])
156
157        self.assertEqual(q.has_key('vote'), True)
158        self.assertEqual('vote' in q, True)
159        self.assertEqual(q.has_key('foo'), False)
160        self.assertEqual('foo' in q, False)
161        self.assertEqual(q.items(), [(u'vote', u'no')])
162        self.assertEqual(q.lists(), [(u'vote', [u'yes', u'no'])])
163        self.assertEqual(q.keys(), [u'vote'])
164        self.assertEqual(q.values(), [u'no'])
165        self.assertEqual(len(q), 1)
166
167        self.assertRaises(AttributeError, q.update, {'foo': 'bar'})
168        self.assertRaises(AttributeError, q.pop, 'foo')
169        self.assertRaises(AttributeError, q.popitem)
170        self.assertRaises(AttributeError, q.clear)
171        self.assertRaises(AttributeError, q.setdefault, 'foo', 'bar')
172        self.assertRaises(AttributeError, q.__delitem__, 'vote')
173
174    def test_invalid_input_encoding(self):
175        """
176        QueryDicts must be able to handle invalid input encoding (in this
177        case, bad UTF-8 encoding).
178        """
179        q = QueryDict('foo=bar&foo=\xff')
180        self.assertEqual(q['foo'], u'\ufffd')
181        self.assertEqual(q.getlist('foo'), [u'bar', u'\ufffd'])
182
183    def test_pickle(self):
184        q = QueryDict('')
185        q1 = pickle.loads(pickle.dumps(q, 2))
186        self.assertEqual(q == q1, True)
187        q = QueryDict('a=b&c=d')
188        q1 = pickle.loads(pickle.dumps(q, 2))
189        self.assertEqual(q == q1, True)
190        q = QueryDict('a=b&c=d&a=1')
191        q1 = pickle.loads(pickle.dumps(q, 2))
192        self.assertEqual(q == q1 , True)
193
194    def test_update_from_querydict(self):
195        """Regression test for #8278: QueryDict.update(QueryDict)"""
196        x = QueryDict("a=1&a=2", mutable=True)
197        y = QueryDict("a=3&a=4")
198        x.update(y)
199        self.assertEqual(x.getlist('a'), [u'1', u'2', u'3', u'4'])
200
201    def test_non_default_encoding(self):
202        """#13572 - QueryDict with a non-default encoding"""
203        q = QueryDict('sbb=one', encoding='rot_13')
204        self.assertEqual(q.encoding , 'rot_13' )
205        self.assertEqual(q.items() , [(u'foo', u'bar')] )
206        self.assertEqual(q.urlencode() , 'sbb=one' )
207        q = q.copy()
208        self.assertEqual(q.encoding , 'rot_13' )
209        self.assertEqual(q.items() , [(u'foo', u'bar')] )
210        self.assertEqual(q.urlencode() , 'sbb=one' )
211        self.assertEqual(copy.copy(q).encoding , 'rot_13' )
212        self.assertEqual(copy.deepcopy(q).encoding , 'rot_13')
213
214class HttpResponseTests(unittest.TestCase):
215    def test_unicode_headers(self):
216        r = HttpResponse()
217
218        # If we insert a unicode value it will be converted to an ascii
219        r['value'] = u'test value'
220        self.assertTrue(isinstance(r['value'], str))
221
222        # An error is raised ~hen a unicode object with non-ascii is assigned.
223        self.assertRaises(UnicodeEncodeError, r.__setitem__, 'value', u't\xebst value')
224
225        # An error is raised when  a unicode object with non-ASCII format is
226        # passed as initial mimetype or content_type.
227        self.assertRaises(UnicodeEncodeError, HttpResponse,
228                mimetype=u't\xebst value')
229
230        # HttpResponse headers must be convertible to ASCII.
231        self.assertRaises(UnicodeEncodeError, HttpResponse,
232                content_type=u't\xebst value')
233
234        # The response also converts unicode keys to strings.)
235        r[u'test'] = 'testing key'
236        l = list(r.items())
237        l.sort()
238        self.assertEqual(l[1], ('test', 'testing key'))
239
240        # It will also raise errors for keys with non-ascii data.
241        self.assertRaises(UnicodeEncodeError, r.__setitem__, u't\xebst key', 'value')
242
243    def test_newlines_in_headers(self):
244        # Bug #10188: Do not allow newlines in headers (CR or LF)
245        r = HttpResponse()
246        self.assertRaises(BadHeaderError, r.__setitem__, 'test\rstr', 'test')
247        self.assertRaises(BadHeaderError, r.__setitem__, 'test\nstr', 'test')
248
249    def test_unsafe_redirects(self):
250        bad_urls = [
251            'data:text/html,<script>window.alert("xss")</script>',
252            'mailto:test@example.com',
253            'file:///etc/passwd',
254        ]
255        for url in bad_urls:
256            self.assertRaises(SuspiciousOperation,
257                              HttpResponseRedirect, url)
258            self.assertRaises(SuspiciousOperation,
259                              HttpResponsePermanentRedirect, url)
260
261class CookieTests(unittest.TestCase):
262    def test_encode(self):
263        """
264        Test that we don't output tricky characters in encoded value
265        """
266        # Python 2.4 compatibility note: Python 2.4's cookie implementation
267        # always returns Set-Cookie headers terminating in semi-colons.
268        # That's not the bug this test is looking for, so ignore it.
269        c = SimpleCookie()
270        c['test'] = "An,awkward;value"
271        self.assertTrue(";" not in c.output().rstrip(';')) # IE compat
272        self.assertTrue("," not in c.output().rstrip(';')) # Safari compat
273
274    def test_decode(self):
275        """
276        Test that we can still preserve semi-colons and commas
277        """
278        c = SimpleCookie()
279        c['test'] = "An,awkward;value"
280        c2 = SimpleCookie()
281        c2.load(c.output())
282        self.assertEqual(c['test'].value, c2['test'].value)
283
284    def test_decode_2(self):
285        """
286        Test that we haven't broken normal encoding
287        """
288        c = SimpleCookie()
289        c['test'] = "\xf0"
290        c2 = SimpleCookie()
291        c2.load(c.output())
292        self.assertEqual(c['test'].value, c2['test'].value)
293
294    def test_nonstandard_keys(self):
295        """
296        Test that a single non-standard cookie name doesn't affect all cookies. Ticket #13007.
297        """
298        self.assertTrue('good_cookie' in parse_cookie('good_cookie=yes;bad:cookie=yes').keys())