PageRenderTime 57ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/tests/regressiontests/httpwrappers/tests.py

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