blob: f9a98c4ae1427107f4872a3b29a5b0a24ecb3637 [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
R. David Murraye05ca2a2010-12-28 18:54:13 +000072 def test_extended_encode(self):
73 # Issue 9824: some browsers don't follow the standard; we now
74 # encode , and ; to keep them from tripping up.
75 C = cookies.SimpleCookie()
76 C['val'] = "some,funky;stuff"
77 self.assertEqual(C.output(['val']),
78 'Set-Cookie: val="some\\054funky\\073stuff"')
79
Georg Brandl76e155a2010-07-31 21:04:00 +000080 def test_special_attrs(self):
81 # 'expires'
82 C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"')
83 C['Customer']['expires'] = 0
84 # can't test exact output, it always depends on current date/time
85 self.assertTrue(C.output().endswith('GMT'))
86
Georg Brandlb16e38b2010-08-01 09:06:34 +000087 # loading 'expires'
88 C = cookies.SimpleCookie()
89 C.load('Customer="W"; expires=Wed, 01-Jan-2010 00:00:00 GMT')
90 self.assertEqual(C['Customer']['expires'],
91 'Wed, 01-Jan-2010 00:00:00 GMT')
92 C = cookies.SimpleCookie()
93 C.load('Customer="W"; expires=Wed, 01-Jan-98 00:00:00 GMT')
94 self.assertEqual(C['Customer']['expires'],
95 'Wed, 01-Jan-98 00:00:00 GMT')
96
Georg Brandl76e155a2010-07-31 21:04:00 +000097 # 'max-age'
98 C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"')
99 C['Customer']['max-age'] = 10
100 self.assertEqual(C.output(),
101 'Set-Cookie: Customer="WILE_E_COYOTE"; Max-Age=10')
102
103 # others
104 C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"')
105 C['Customer']['secure'] = True
106 C['Customer']['httponly'] = True
107 self.assertEqual(C.output(),
108 'Set-Cookie: Customer="WILE_E_COYOTE"; httponly; secure')
109
Thomas Wouters89f507f2006-12-13 04:49:30 +0000110 def test_quoted_meta(self):
111 # Try cookie with quoted meta-data
Georg Brandl24420152008-05-26 16:32:26 +0000112 C = cookies.SimpleCookie()
Thomas Wouters89f507f2006-12-13 04:49:30 +0000113 C.load('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"')
114 self.assertEqual(C['Customer'].value, 'WILE_E_COYOTE')
115 self.assertEqual(C['Customer']['version'], '1')
116 self.assertEqual(C['Customer']['path'], '/acme')
Tim Peterseb26f952001-04-06 21:20:58 +0000117
Georg Brandl76e155a2010-07-31 21:04:00 +0000118 self.assertEqual(C.output(['path']),
119 'Set-Cookie: Customer="WILE_E_COYOTE"; Path=/acme')
120 self.assertEqual(C.js_output(), r"""
121 <script type="text/javascript">
122 <!-- begin hiding
123 document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme; Version=1";
124 // end hiding -->
125 </script>
126 """)
127 self.assertEqual(C.js_output(['path']), r"""
128 <script type="text/javascript">
129 <!-- begin hiding
130 document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme";
131 // end hiding -->
132 </script>
133 """)
134
135class MorselTests(unittest.TestCase):
136 """Tests for the Morsel object."""
137
138 def test_reserved_keys(self):
139 M = cookies.Morsel()
140 # tests valid and invalid reserved keys for Morsels
141 for i in M._reserved:
142 # Test that all valid keys are reported as reserved and set them
143 self.assertTrue(M.isReservedKey(i))
144 M[i] = '%s_value' % i
145 for i in M._reserved:
146 # Test that valid key values come out fine
147 self.assertEqual(M[i], '%s_value' % i)
148 for i in "the holy hand grenade".split():
149 # Test that invalid keys raise CookieError
150 self.assertRaises(cookies.CookieError,
151 M.__setitem__, i, '%s_value' % i)
152
153 def test_setter(self):
154 M = cookies.Morsel()
155 # tests the .set method to set keys and their values
156 for i in M._reserved:
157 # Makes sure that all reserved keys can't be set this way
158 self.assertRaises(cookies.CookieError,
159 M.set, i, '%s_value' % i, '%s_value' % i)
160 for i in "thou cast _the- !holy! ^hand| +*grenade~".split():
161 # Try typical use case. Setting decent values.
162 # Check output and js_output.
163 M['path'] = '/foo' # Try a reserved key as well
164 M.set(i, "%s_val" % i, "%s_coded_val" % i)
165 self.assertEqual(
166 M.output(),
167 "Set-Cookie: %s=%s; Path=/foo" % (i, "%s_coded_val" % i))
168 expected_js_output = """
169 <script type="text/javascript">
170 <!-- begin hiding
171 document.cookie = "%s=%s; Path=/foo";
172 // end hiding -->
173 </script>
174 """ % (i, "%s_coded_val" % i)
175 self.assertEqual(M.js_output(), expected_js_output)
176 for i in ["foo bar", "foo@bar"]:
177 # Try some illegal characters
178 self.assertRaises(cookies.CookieError,
179 M.set, i, '%s_value' % i, '%s_value' % i)
180
181
Thomas Wouters89f507f2006-12-13 04:49:30 +0000182def test_main():
Georg Brandl76e155a2010-07-31 21:04:00 +0000183 run_unittest(CookieTests, MorselTests)
Georg Brandl24420152008-05-26 16:32:26 +0000184 run_doctest(cookies)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000185
186if __name__ == '__main__':
187 test_main()