blob: b008e0ff2a50dd0306129395fb3a731e4001b0e7 [file] [log] [blame]
Georg Brandl24420152008-05-26 16:32:26 +00001# Simple test suite for http/cookies.py
Andrew M. Kuchlingcdec8c72000-08-19 15:21:12 +00002
Brett Cannond3791ed2010-03-20 21:51:10 +00003from test.support import run_unittest, run_doctest, check_warnings
Thomas Wouters89f507f2006-12-13 04:49:30 +00004import unittest
Georg Brandl24420152008-05-26 16:32:26 +00005from http import cookies
Andrew M. Kuchlingcdec8c72000-08-19 15:21:12 +00006
Andrew M. Kuchling44644322002-12-29 16:45:06 +00007import warnings
Andrew M. Kuchling44644322002-12-29 16:45:06 +00008
Thomas Wouters89f507f2006-12-13 04:49:30 +00009class CookieTests(unittest.TestCase):
Brett Cannond3791ed2010-03-20 21:51:10 +000010
11 def setUp(self):
12 self._warnings_manager = check_warnings()
13 self._warnings_manager.__enter__()
14 warnings.filterwarnings("ignore", ".* class is insecure.*",
15 DeprecationWarning)
16
17 def tearDown(self):
18 self._warnings_manager.__exit__(None, None, None)
19
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 def test_basic(self):
21 cases = [
Georg Brandl76e155a2010-07-31 21:04:00 +000022 {'data': 'chips=ahoy; vienna=finger',
23 'dict': {'chips':'ahoy', 'vienna':'finger'},
24 'repr': "<SimpleCookie: chips='ahoy' vienna='finger'>",
25 'output': 'Set-Cookie: chips=ahoy\nSet-Cookie: vienna=finger'},
Andrew M. Kuchlingcdec8c72000-08-19 15:21:12 +000026
Georg Brandl76e155a2010-07-31 21:04:00 +000027 {'data': 'keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"',
28 'dict': {'keebler' : 'E=mc2; L="Loves"; fudge=\012;'},
29 'repr': '''<SimpleCookie: keebler='E=mc2; L="Loves"; fudge=\\n;'>''',
30 'output': 'Set-Cookie: keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"'},
Andrew M. Kuchling8b94b1c2001-02-21 01:17:54 +000031
Thomas Wouters89f507f2006-12-13 04:49:30 +000032 # Check illegal cookies that have an '=' char in an unquoted value
Georg Brandl76e155a2010-07-31 21:04:00 +000033 {'data': 'keebler=E=mc2',
34 'dict': {'keebler' : 'E=mc2'},
35 'repr': "<SimpleCookie: keebler='E=mc2'>",
36 'output': 'Set-Cookie: keebler=E=mc2'},
Thomas Wouters89f507f2006-12-13 04:49:30 +000037 ]
Andrew M. Kuchlingcdec8c72000-08-19 15:21:12 +000038
Thomas Wouters89f507f2006-12-13 04:49:30 +000039 for case in cases:
Georg Brandl24420152008-05-26 16:32:26 +000040 C = cookies.SimpleCookie()
Thomas Wouters89f507f2006-12-13 04:49:30 +000041 C.load(case['data'])
42 self.assertEqual(repr(C), case['repr'])
43 self.assertEqual(C.output(sep='\n'), case['output'])
Guido van Rossumcc2b0162007-02-11 06:12:03 +000044 for k, v in sorted(case['dict'].items()):
Thomas Wouters89f507f2006-12-13 04:49:30 +000045 self.assertEqual(C[k].value, v)
Andrew M. Kuchlingcdec8c72000-08-19 15:21:12 +000046
Thomas Wouters89f507f2006-12-13 04:49:30 +000047 def test_load(self):
Georg Brandl24420152008-05-26 16:32:26 +000048 C = cookies.SimpleCookie()
Thomas Wouters89f507f2006-12-13 04:49:30 +000049 C.load('Customer="WILE_E_COYOTE"; Version=1; Path=/acme')
Andrew M. Kuchlingcdec8c72000-08-19 15:21:12 +000050
Thomas Wouters89f507f2006-12-13 04:49:30 +000051 self.assertEqual(C['Customer'].value, 'WILE_E_COYOTE')
52 self.assertEqual(C['Customer']['version'], '1')
53 self.assertEqual(C['Customer']['path'], '/acme')
Moshe Zadka514a1022000-08-19 15:57:33 +000054
Thomas Wouters89f507f2006-12-13 04:49:30 +000055 self.assertEqual(C.output(['path']),
56 'Set-Cookie: Customer="WILE_E_COYOTE"; Path=/acme')
Senthil Kumaran3e2ea792009-04-02 03:02:03 +000057 self.assertEqual(C.js_output(), r"""
Thomas Wouters89f507f2006-12-13 04:49:30 +000058 <script type="text/javascript">
59 <!-- begin hiding
Senthil Kumaran3e2ea792009-04-02 03:02:03 +000060 document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme; Version=1";
Thomas Wouters89f507f2006-12-13 04:49:30 +000061 // end hiding -->
62 </script>
63 """)
Senthil Kumaran3e2ea792009-04-02 03:02:03 +000064 self.assertEqual(C.js_output(['path']), r"""
Thomas Wouters89f507f2006-12-13 04:49:30 +000065 <script type="text/javascript">
66 <!-- begin hiding
Senthil Kumaran3e2ea792009-04-02 03:02:03 +000067 document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme";
Thomas Wouters89f507f2006-12-13 04:49:30 +000068 // end hiding -->
69 </script>
70 """)
Moshe Zadka514a1022000-08-19 15:57:33 +000071
Georg Brandl76e155a2010-07-31 21:04:00 +000072 def test_special_attrs(self):
73 # 'expires'
74 C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"')
75 C['Customer']['expires'] = 0
76 # can't test exact output, it always depends on current date/time
77 self.assertTrue(C.output().endswith('GMT'))
78
Georg Brandlb16e38b2010-08-01 09:06:34 +000079 # loading 'expires'
80 C = cookies.SimpleCookie()
81 C.load('Customer="W"; expires=Wed, 01-Jan-2010 00:00:00 GMT')
82 self.assertEqual(C['Customer']['expires'],
83 'Wed, 01-Jan-2010 00:00:00 GMT')
84 C = cookies.SimpleCookie()
85 C.load('Customer="W"; expires=Wed, 01-Jan-98 00:00:00 GMT')
86 self.assertEqual(C['Customer']['expires'],
87 'Wed, 01-Jan-98 00:00:00 GMT')
88
Georg Brandl76e155a2010-07-31 21:04:00 +000089 # 'max-age'
90 C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"')
91 C['Customer']['max-age'] = 10
92 self.assertEqual(C.output(),
93 'Set-Cookie: Customer="WILE_E_COYOTE"; Max-Age=10')
94
95 # others
96 C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"')
97 C['Customer']['secure'] = True
98 C['Customer']['httponly'] = True
99 self.assertEqual(C.output(),
100 'Set-Cookie: Customer="WILE_E_COYOTE"; httponly; secure')
101
Thomas Wouters89f507f2006-12-13 04:49:30 +0000102 def test_quoted_meta(self):
103 # Try cookie with quoted meta-data
Georg Brandl24420152008-05-26 16:32:26 +0000104 C = cookies.SimpleCookie()
Thomas Wouters89f507f2006-12-13 04:49:30 +0000105 C.load('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"')
106 self.assertEqual(C['Customer'].value, 'WILE_E_COYOTE')
107 self.assertEqual(C['Customer']['version'], '1')
108 self.assertEqual(C['Customer']['path'], '/acme')
Tim Peterseb26f952001-04-06 21:20:58 +0000109
Georg Brandl76e155a2010-07-31 21:04:00 +0000110 self.assertEqual(C.output(['path']),
111 'Set-Cookie: Customer="WILE_E_COYOTE"; Path=/acme')
112 self.assertEqual(C.js_output(), r"""
113 <script type="text/javascript">
114 <!-- begin hiding
115 document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme; Version=1";
116 // end hiding -->
117 </script>
118 """)
119 self.assertEqual(C.js_output(['path']), r"""
120 <script type="text/javascript">
121 <!-- begin hiding
122 document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme";
123 // end hiding -->
124 </script>
125 """)
126
127class MorselTests(unittest.TestCase):
128 """Tests for the Morsel object."""
129
130 def test_reserved_keys(self):
131 M = cookies.Morsel()
132 # tests valid and invalid reserved keys for Morsels
133 for i in M._reserved:
134 # Test that all valid keys are reported as reserved and set them
135 self.assertTrue(M.isReservedKey(i))
136 M[i] = '%s_value' % i
137 for i in M._reserved:
138 # Test that valid key values come out fine
139 self.assertEqual(M[i], '%s_value' % i)
140 for i in "the holy hand grenade".split():
141 # Test that invalid keys raise CookieError
142 self.assertRaises(cookies.CookieError,
143 M.__setitem__, i, '%s_value' % i)
144
145 def test_setter(self):
146 M = cookies.Morsel()
147 # tests the .set method to set keys and their values
148 for i in M._reserved:
149 # Makes sure that all reserved keys can't be set this way
150 self.assertRaises(cookies.CookieError,
151 M.set, i, '%s_value' % i, '%s_value' % i)
152 for i in "thou cast _the- !holy! ^hand| +*grenade~".split():
153 # Try typical use case. Setting decent values.
154 # Check output and js_output.
155 M['path'] = '/foo' # Try a reserved key as well
156 M.set(i, "%s_val" % i, "%s_coded_val" % i)
157 self.assertEqual(
158 M.output(),
159 "Set-Cookie: %s=%s; Path=/foo" % (i, "%s_coded_val" % i))
160 expected_js_output = """
161 <script type="text/javascript">
162 <!-- begin hiding
163 document.cookie = "%s=%s; Path=/foo";
164 // end hiding -->
165 </script>
166 """ % (i, "%s_coded_val" % i)
167 self.assertEqual(M.js_output(), expected_js_output)
168 for i in ["foo bar", "foo@bar"]:
169 # Try some illegal characters
170 self.assertRaises(cookies.CookieError,
171 M.set, i, '%s_value' % i, '%s_value' % i)
172
173
Thomas Wouters89f507f2006-12-13 04:49:30 +0000174def test_main():
Georg Brandl76e155a2010-07-31 21:04:00 +0000175 run_unittest(CookieTests, MorselTests)
Georg Brandl24420152008-05-26 16:32:26 +0000176 run_doctest(cookies)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000177
178if __name__ == '__main__':
179 test_main()