test_cookie.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. # Simple test suite for Cookie.py
  2. from test.test_support import run_unittest, run_doctest, check_warnings
  3. import unittest
  4. import Cookie
  5. import pickle
  6. class CookieTests(unittest.TestCase):
  7. # Currently this only tests SimpleCookie
  8. def test_basic(self):
  9. cases = [
  10. { 'data': 'chips=ahoy; vienna=finger',
  11. 'dict': {'chips':'ahoy', 'vienna':'finger'},
  12. 'repr': "<SimpleCookie: chips='ahoy' vienna='finger'>",
  13. 'output': 'Set-Cookie: chips=ahoy\nSet-Cookie: vienna=finger',
  14. },
  15. { 'data': 'keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"',
  16. 'dict': {'keebler' : 'E=mc2; L="Loves"; fudge=\012;'},
  17. 'repr': '''<SimpleCookie: keebler='E=mc2; L="Loves"; fudge=\\n;'>''',
  18. 'output': 'Set-Cookie: keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"',
  19. },
  20. # Check illegal cookies that have an '=' char in an unquoted value
  21. { 'data': 'keebler=E=mc2',
  22. 'dict': {'keebler' : 'E=mc2'},
  23. 'repr': "<SimpleCookie: keebler='E=mc2'>",
  24. 'output': 'Set-Cookie: keebler=E=mc2',
  25. },
  26. # issue22931 - Adding '[' and ']' as valid characters in cookie
  27. # values as defined in RFC 6265
  28. {
  29. 'data': 'a=b; c=[; d=r; f=h',
  30. 'dict': {'a':'b', 'c':'[', 'd':'r', 'f':'h'},
  31. 'repr': "<SimpleCookie: a='b' c='[' d='r' f='h'>",
  32. 'output': '\n'.join((
  33. 'Set-Cookie: a=b',
  34. 'Set-Cookie: c=[',
  35. 'Set-Cookie: d=r',
  36. 'Set-Cookie: f=h'
  37. ))
  38. }
  39. ]
  40. for case in cases:
  41. C = Cookie.SimpleCookie()
  42. C.load(case['data'])
  43. self.assertEqual(repr(C), case['repr'])
  44. self.assertEqual(C.output(sep='\n'), case['output'])
  45. for k, v in sorted(case['dict'].iteritems()):
  46. self.assertEqual(C[k].value, v)
  47. def test_load(self):
  48. C = Cookie.SimpleCookie()
  49. C.load('Customer="WILE_E_COYOTE"; Version=1; Path=/acme')
  50. self.assertEqual(C['Customer'].value, 'WILE_E_COYOTE')
  51. self.assertEqual(C['Customer']['version'], '1')
  52. self.assertEqual(C['Customer']['path'], '/acme')
  53. self.assertEqual(C.output(['path']),
  54. 'Set-Cookie: Customer="WILE_E_COYOTE"; Path=/acme')
  55. self.assertEqual(C.js_output(), r"""
  56. <script type="text/javascript">
  57. <!-- begin hiding
  58. document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme; Version=1";
  59. // end hiding -->
  60. </script>
  61. """)
  62. self.assertEqual(C.js_output(['path']), r"""
  63. <script type="text/javascript">
  64. <!-- begin hiding
  65. document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme";
  66. // end hiding -->
  67. </script>
  68. """)
  69. # loading 'expires'
  70. C = Cookie.SimpleCookie()
  71. C.load('Customer="W"; expires=Wed, 01 Jan 2010 00:00:00 GMT')
  72. self.assertEqual(C['Customer']['expires'],
  73. 'Wed, 01 Jan 2010 00:00:00 GMT')
  74. C = Cookie.SimpleCookie()
  75. C.load('Customer="W"; expires=Wed, 01 Jan 98 00:00:00 GMT')
  76. self.assertEqual(C['Customer']['expires'],
  77. 'Wed, 01 Jan 98 00:00:00 GMT')
  78. def test_extended_encode(self):
  79. # Issue 9824: some browsers don't follow the standard; we now
  80. # encode , and ; to keep them from tripping up.
  81. C = Cookie.SimpleCookie()
  82. C['val'] = "some,funky;stuff"
  83. self.assertEqual(C.output(['val']),
  84. 'Set-Cookie: val="some\\054funky\\073stuff"')
  85. def test_set_secure_httponly_attrs(self):
  86. C = Cookie.SimpleCookie('Customer="WILE_E_COYOTE"')
  87. C['Customer']['secure'] = True
  88. C['Customer']['httponly'] = True
  89. self.assertEqual(C.output(),
  90. 'Set-Cookie: Customer="WILE_E_COYOTE"; httponly; secure')
  91. def test_secure_httponly_false_if_not_present(self):
  92. C = Cookie.SimpleCookie()
  93. C.load('eggs=scrambled; Path=/bacon')
  94. self.assertFalse(C['eggs']['httponly'])
  95. self.assertFalse(C['eggs']['secure'])
  96. def test_secure_httponly_true_if_present(self):
  97. # Issue 16611
  98. C = Cookie.SimpleCookie()
  99. C.load('eggs=scrambled; httponly; secure; Path=/bacon')
  100. self.assertTrue(C['eggs']['httponly'])
  101. self.assertTrue(C['eggs']['secure'])
  102. def test_secure_httponly_true_if_have_value(self):
  103. # This isn't really valid, but demonstrates what the current code
  104. # is expected to do in this case.
  105. C = Cookie.SimpleCookie()
  106. C.load('eggs=scrambled; httponly=foo; secure=bar; Path=/bacon')
  107. self.assertTrue(C['eggs']['httponly'])
  108. self.assertTrue(C['eggs']['secure'])
  109. # Here is what it actually does; don't depend on this behavior. These
  110. # checks are testing backward compatibility for issue 16611.
  111. self.assertEqual(C['eggs']['httponly'], 'foo')
  112. self.assertEqual(C['eggs']['secure'], 'bar')
  113. def test_bad_attrs(self):
  114. # Issue 16611: make sure we don't break backward compatibility.
  115. C = Cookie.SimpleCookie()
  116. C.load('cookie=with; invalid; version; second=cookie;')
  117. self.assertEqual(C.output(),
  118. 'Set-Cookie: cookie=with\r\nSet-Cookie: second=cookie')
  119. def test_extra_spaces(self):
  120. C = Cookie.SimpleCookie()
  121. C.load('eggs = scrambled ; secure ; path = bar ; foo=foo ')
  122. self.assertEqual(C.output(),
  123. 'Set-Cookie: eggs=scrambled; Path=bar; secure\r\nSet-Cookie: foo=foo')
  124. def test_quoted_meta(self):
  125. # Try cookie with quoted meta-data
  126. C = Cookie.SimpleCookie()
  127. C.load('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"')
  128. self.assertEqual(C['Customer'].value, 'WILE_E_COYOTE')
  129. self.assertEqual(C['Customer']['version'], '1')
  130. self.assertEqual(C['Customer']['path'], '/acme')
  131. def test_invalid_cookies(self):
  132. # Accepting these could be a security issue
  133. C = Cookie.SimpleCookie()
  134. for s in (']foo=x', '[foo=x', 'blah]foo=x', 'blah[foo=x'):
  135. C.load(s)
  136. self.assertEqual(dict(C), {})
  137. self.assertEqual(C.output(), '')
  138. def test_pickle(self):
  139. rawdata = 'Customer="WILE_E_COYOTE"; Path=/acme; Version=1'
  140. expected_output = 'Set-Cookie: %s' % rawdata
  141. C = Cookie.SimpleCookie()
  142. C.load(rawdata)
  143. self.assertEqual(C.output(), expected_output)
  144. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  145. C1 = pickle.loads(pickle.dumps(C, protocol=proto))
  146. self.assertEqual(C1.output(), expected_output)
  147. def test_main():
  148. run_unittest(CookieTests)
  149. if Cookie.__doc__ is not None:
  150. with check_warnings(('.+Cookie class is insecure; do not use it',
  151. DeprecationWarning)):
  152. run_doctest(Cookie)
  153. if __name__ == '__main__':
  154. test_main()