1# Simple test suite for http/cookies.py
2
3import copy
4from test.support import run_unittest, run_doctest
5import unittest
6from http import cookies
7import pickle
8
9
10class CookieTests(unittest.TestCase):
11
12    def test_basic(self):
13        cases = [
14            {'data': 'chips=ahoy; vienna=finger',
15             'dict': {'chips':'ahoy', 'vienna':'finger'},
16             'repr': "<SimpleCookie: chips='ahoy' vienna='finger'>",
17             'output': 'Set-Cookie: chips=ahoy\nSet-Cookie: vienna=finger'},
18
19            {'data': 'keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"',
20             'dict': {'keebler' : 'E=mc2; L="Loves"; fudge=\012;'},
21             'repr': '''<SimpleCookie: keebler='E=mc2; L="Loves"; fudge=\\n;'>''',
22             'output': 'Set-Cookie: keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"'},
23
24            # Check illegal cookies that have an '=' char in an unquoted value
25            {'data': 'keebler=E=mc2',
26             'dict': {'keebler' : 'E=mc2'},
27             'repr': "<SimpleCookie: keebler='E=mc2'>",
28             'output': 'Set-Cookie: keebler=E=mc2'},
29
30            # Cookies with ':' character in their name. Though not mentioned in
31            # RFC, servers / browsers allow it.
32
33             {'data': 'key:term=value:term',
34             'dict': {'key:term' : 'value:term'},
35             'repr': "<SimpleCookie: key:term='value:term'>",
36             'output': 'Set-Cookie: key:term=value:term'},
37
38            # issue22931 - Adding '[' and ']' as valid characters in cookie
39            # values as defined in RFC 6265
40            {
41                'data': 'a=b; c=[; d=r; f=h',
42                'dict': {'a':'b', 'c':'[', 'd':'r', 'f':'h'},
43                'repr': "<SimpleCookie: a='b' c='[' d='r' f='h'>",
44                'output': '\n'.join((
45                    'Set-Cookie: a=b',
46                    'Set-Cookie: c=[',
47                    'Set-Cookie: d=r',
48                    'Set-Cookie: f=h'
49                ))
50            }
51        ]
52
53        for case in cases:
54            C = cookies.SimpleCookie()
55            C.load(case['data'])
56            self.assertEqual(repr(C), case['repr'])
57            self.assertEqual(C.output(sep='\n'), case['output'])
58            for k, v in sorted(case['dict'].items()):
59                self.assertEqual(C[k].value, v)
60
61    def test_load(self):
62        C = cookies.SimpleCookie()
63        C.load('Customer="WILE_E_COYOTE"; Version=1; Path=/acme')
64
65        self.assertEqual(C['Customer'].value, 'WILE_E_COYOTE')
66        self.assertEqual(C['Customer']['version'], '1')
67        self.assertEqual(C['Customer']['path'], '/acme')
68
69        self.assertEqual(C.output(['path']),
70            'Set-Cookie: Customer="WILE_E_COYOTE"; Path=/acme')
71        self.assertEqual(C.js_output(), r"""
72        <script type="text/javascript">
73        <!-- begin hiding
74        document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme; Version=1";
75        // end hiding -->
76        </script>
77        """)
78        self.assertEqual(C.js_output(['path']), r"""
79        <script type="text/javascript">
80        <!-- begin hiding
81        document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme";
82        // end hiding -->
83        </script>
84        """)
85
86    def test_extended_encode(self):
87        # Issue 9824: some browsers don't follow the standard; we now
88        # encode , and ; to keep them from tripping up.
89        C = cookies.SimpleCookie()
90        C['val'] = "some,funky;stuff"
91        self.assertEqual(C.output(['val']),
92            'Set-Cookie: val="some\\054funky\\073stuff"')
93
94    def test_special_attrs(self):
95        # 'expires'
96        C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"')
97        C['Customer']['expires'] = 0
98        # can't test exact output, it always depends on current date/time
99        self.assertTrue(C.output().endswith('GMT'))
100
101        # loading 'expires'
102        C = cookies.SimpleCookie()
103        C.load('Customer="W"; expires=Wed, 01 Jan 2010 00:00:00 GMT')
104        self.assertEqual(C['Customer']['expires'],
105                         'Wed, 01 Jan 2010 00:00:00 GMT')
106        C = cookies.SimpleCookie()
107        C.load('Customer="W"; expires=Wed, 01 Jan 98 00:00:00 GMT')
108        self.assertEqual(C['Customer']['expires'],
109                         'Wed, 01 Jan 98 00:00:00 GMT')
110
111        # 'max-age'
112        C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"')
113        C['Customer']['max-age'] = 10
114        self.assertEqual(C.output(),
115                         'Set-Cookie: Customer="WILE_E_COYOTE"; Max-Age=10')
116
117    def test_set_secure_httponly_attrs(self):
118        C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"')
119        C['Customer']['secure'] = True
120        C['Customer']['httponly'] = True
121        self.assertEqual(C.output(),
122            'Set-Cookie: Customer="WILE_E_COYOTE"; HttpOnly; Secure')
123
124    def test_samesite_attrs(self):
125        samesite_values = ['Strict', 'Lax', 'strict', 'lax']
126        for val in samesite_values:
127            with self.subTest(val=val):
128                C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"')
129                C['Customer']['samesite'] = val
130                self.assertEqual(C.output(),
131                    'Set-Cookie: Customer="WILE_E_COYOTE"; SameSite=%s' % val)
132
133                C = cookies.SimpleCookie()
134                C.load('Customer="WILL_E_COYOTE"; SameSite=%s' % val)
135                self.assertEqual(C['Customer']['samesite'], val)
136
137    def test_secure_httponly_false_if_not_present(self):
138        C = cookies.SimpleCookie()
139        C.load('eggs=scrambled; Path=/bacon')
140        self.assertFalse(C['eggs']['httponly'])
141        self.assertFalse(C['eggs']['secure'])
142
143    def test_secure_httponly_true_if_present(self):
144        # Issue 16611
145        C = cookies.SimpleCookie()
146        C.load('eggs=scrambled; httponly; secure; Path=/bacon')
147        self.assertTrue(C['eggs']['httponly'])
148        self.assertTrue(C['eggs']['secure'])
149
150    def test_secure_httponly_true_if_have_value(self):
151        # This isn't really valid, but demonstrates what the current code
152        # is expected to do in this case.
153        C = cookies.SimpleCookie()
154        C.load('eggs=scrambled; httponly=foo; secure=bar; Path=/bacon')
155        self.assertTrue(C['eggs']['httponly'])
156        self.assertTrue(C['eggs']['secure'])
157        # Here is what it actually does; don't depend on this behavior.  These
158        # checks are testing backward compatibility for issue 16611.
159        self.assertEqual(C['eggs']['httponly'], 'foo')
160        self.assertEqual(C['eggs']['secure'], 'bar')
161
162    def test_extra_spaces(self):
163        C = cookies.SimpleCookie()
164        C.load('eggs  =  scrambled  ;  secure  ;  path  =  bar   ; foo=foo   ')
165        self.assertEqual(C.output(),
166            'Set-Cookie: eggs=scrambled; Path=bar; Secure\r\nSet-Cookie: foo=foo')
167
168    def test_quoted_meta(self):
169        # Try cookie with quoted meta-data
170        C = cookies.SimpleCookie()
171        C.load('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"')
172        self.assertEqual(C['Customer'].value, 'WILE_E_COYOTE')
173        self.assertEqual(C['Customer']['version'], '1')
174        self.assertEqual(C['Customer']['path'], '/acme')
175
176        self.assertEqual(C.output(['path']),
177                         'Set-Cookie: Customer="WILE_E_COYOTE"; Path=/acme')
178        self.assertEqual(C.js_output(), r"""
179        <script type="text/javascript">
180        <!-- begin hiding
181        document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme; Version=1";
182        // end hiding -->
183        </script>
184        """)
185        self.assertEqual(C.js_output(['path']), r"""
186        <script type="text/javascript">
187        <!-- begin hiding
188        document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme";
189        // end hiding -->
190        </script>
191        """)
192
193    def test_invalid_cookies(self):
194        # Accepting these could be a security issue
195        C = cookies.SimpleCookie()
196        for s in (']foo=x', '[foo=x', 'blah]foo=x', 'blah[foo=x',
197                  'Set-Cookie: foo=bar', 'Set-Cookie: foo',
198                  'foo=bar; baz', 'baz; foo=bar',
199                  'secure;foo=bar', 'Version=1;foo=bar'):
200            C.load(s)
201            self.assertEqual(dict(C), {})
202            self.assertEqual(C.output(), '')
203
204    def test_pickle(self):
205        rawdata = 'Customer="WILE_E_COYOTE"; Path=/acme; Version=1'
206        expected_output = 'Set-Cookie: %s' % rawdata
207
208        C = cookies.SimpleCookie()
209        C.load(rawdata)
210        self.assertEqual(C.output(), expected_output)
211
212        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
213            with self.subTest(proto=proto):
214                C1 = pickle.loads(pickle.dumps(C, protocol=proto))
215                self.assertEqual(C1.output(), expected_output)
216
217    def test_illegal_chars(self):
218        rawdata = "a=b; c,d=e"
219        C = cookies.SimpleCookie()
220        with self.assertRaises(cookies.CookieError):
221            C.load(rawdata)
222
223    def test_comment_quoting(self):
224        c = cookies.SimpleCookie()
225        c['foo'] = '\N{COPYRIGHT SIGN}'
226        self.assertEqual(str(c['foo']), 'Set-Cookie: foo="\\251"')
227        c['foo']['comment'] = 'comment \N{COPYRIGHT SIGN}'
228        self.assertEqual(
229            str(c['foo']),
230            'Set-Cookie: foo="\\251"; Comment="comment \\251"'
231        )
232
233
234class MorselTests(unittest.TestCase):
235    """Tests for the Morsel object."""
236
237    def test_defaults(self):
238        morsel = cookies.Morsel()
239        self.assertIsNone(morsel.key)
240        self.assertIsNone(morsel.value)
241        self.assertIsNone(morsel.coded_value)
242        self.assertEqual(morsel.keys(), cookies.Morsel._reserved.keys())
243        for key, val in morsel.items():
244            self.assertEqual(val, '', key)
245
246    def test_reserved_keys(self):
247        M = cookies.Morsel()
248        # tests valid and invalid reserved keys for Morsels
249        for i in M._reserved:
250            # Test that all valid keys are reported as reserved and set them
251            self.assertTrue(M.isReservedKey(i))
252            M[i] = '%s_value' % i
253        for i in M._reserved:
254            # Test that valid key values come out fine
255            self.assertEqual(M[i], '%s_value' % i)
256        for i in "the holy hand grenade".split():
257            # Test that invalid keys raise CookieError
258            self.assertRaises(cookies.CookieError,
259                              M.__setitem__, i, '%s_value' % i)
260
261    def test_setter(self):
262        M = cookies.Morsel()
263        # tests the .set method to set keys and their values
264        for i in M._reserved:
265            # Makes sure that all reserved keys can't be set this way
266            self.assertRaises(cookies.CookieError,
267                              M.set, i, '%s_value' % i, '%s_value' % i)
268        for i in "thou cast _the- !holy! ^hand| +*grenade~".split():
269            # Try typical use case. Setting decent values.
270            # Check output and js_output.
271            M['path'] = '/foo' # Try a reserved key as well
272            M.set(i, "%s_val" % i, "%s_coded_val" % i)
273            self.assertEqual(M.key, i)
274            self.assertEqual(M.value, "%s_val" % i)
275            self.assertEqual(M.coded_value, "%s_coded_val" % i)
276            self.assertEqual(
277                M.output(),
278                "Set-Cookie: %s=%s; Path=/foo" % (i, "%s_coded_val" % i))
279            expected_js_output = """
280        <script type="text/javascript">
281        <!-- begin hiding
282        document.cookie = "%s=%s; Path=/foo";
283        // end hiding -->
284        </script>
285        """ % (i, "%s_coded_val" % i)
286            self.assertEqual(M.js_output(), expected_js_output)
287        for i in ["foo bar", "foo@bar"]:
288            # Try some illegal characters
289            self.assertRaises(cookies.CookieError,
290                              M.set, i, '%s_value' % i, '%s_value' % i)
291
292    def test_set_properties(self):
293        morsel = cookies.Morsel()
294        with self.assertRaises(AttributeError):
295            morsel.key = ''
296        with self.assertRaises(AttributeError):
297            morsel.value = ''
298        with self.assertRaises(AttributeError):
299            morsel.coded_value = ''
300
301    def test_eq(self):
302        base_case = ('key', 'value', '"value"')
303        attribs = {
304            'path': '/',
305            'comment': 'foo',
306            'domain': 'example.com',
307            'version': 2,
308        }
309        morsel_a = cookies.Morsel()
310        morsel_a.update(attribs)
311        morsel_a.set(*base_case)
312        morsel_b = cookies.Morsel()
313        morsel_b.update(attribs)
314        morsel_b.set(*base_case)
315        self.assertTrue(morsel_a == morsel_b)
316        self.assertFalse(morsel_a != morsel_b)
317        cases = (
318            ('key', 'value', 'mismatch'),
319            ('key', 'mismatch', '"value"'),
320            ('mismatch', 'value', '"value"'),
321        )
322        for case_b in cases:
323            with self.subTest(case_b):
324                morsel_b = cookies.Morsel()
325                morsel_b.update(attribs)
326                morsel_b.set(*case_b)
327                self.assertFalse(morsel_a == morsel_b)
328                self.assertTrue(morsel_a != morsel_b)
329
330        morsel_b = cookies.Morsel()
331        morsel_b.update(attribs)
332        morsel_b.set(*base_case)
333        morsel_b['comment'] = 'bar'
334        self.assertFalse(morsel_a == morsel_b)
335        self.assertTrue(morsel_a != morsel_b)
336
337        # test mismatched types
338        self.assertFalse(cookies.Morsel() == 1)
339        self.assertTrue(cookies.Morsel() != 1)
340        self.assertFalse(cookies.Morsel() == '')
341        self.assertTrue(cookies.Morsel() != '')
342        items = list(cookies.Morsel().items())
343        self.assertFalse(cookies.Morsel() == items)
344        self.assertTrue(cookies.Morsel() != items)
345
346        # morsel/dict
347        morsel = cookies.Morsel()
348        morsel.set(*base_case)
349        morsel.update(attribs)
350        self.assertTrue(morsel == dict(morsel))
351        self.assertFalse(morsel != dict(morsel))
352
353    def test_copy(self):
354        morsel_a = cookies.Morsel()
355        morsel_a.set('foo', 'bar', 'baz')
356        morsel_a.update({
357            'version': 2,
358            'comment': 'foo',
359        })
360        morsel_b = morsel_a.copy()
361        self.assertIsInstance(morsel_b, cookies.Morsel)
362        self.assertIsNot(morsel_a, morsel_b)
363        self.assertEqual(morsel_a, morsel_b)
364
365        morsel_b = copy.copy(morsel_a)
366        self.assertIsInstance(morsel_b, cookies.Morsel)
367        self.assertIsNot(morsel_a, morsel_b)
368        self.assertEqual(morsel_a, morsel_b)
369
370    def test_setitem(self):
371        morsel = cookies.Morsel()
372        morsel['expires'] = 0
373        self.assertEqual(morsel['expires'], 0)
374        morsel['Version'] = 2
375        self.assertEqual(morsel['version'], 2)
376        morsel['DOMAIN'] = 'example.com'
377        self.assertEqual(morsel['domain'], 'example.com')
378
379        with self.assertRaises(cookies.CookieError):
380            morsel['invalid'] = 'value'
381        self.assertNotIn('invalid', morsel)
382
383    def test_setdefault(self):
384        morsel = cookies.Morsel()
385        morsel.update({
386            'domain': 'example.com',
387            'version': 2,
388        })
389        # this shouldn't override the default value
390        self.assertEqual(morsel.setdefault('expires', 'value'), '')
391        self.assertEqual(morsel['expires'], '')
392        self.assertEqual(morsel.setdefault('Version', 1), 2)
393        self.assertEqual(morsel['version'], 2)
394        self.assertEqual(morsel.setdefault('DOMAIN', 'value'), 'example.com')
395        self.assertEqual(morsel['domain'], 'example.com')
396
397        with self.assertRaises(cookies.CookieError):
398            morsel.setdefault('invalid', 'value')
399        self.assertNotIn('invalid', morsel)
400
401    def test_update(self):
402        attribs = {'expires': 1, 'Version': 2, 'DOMAIN': 'example.com'}
403        # test dict update
404        morsel = cookies.Morsel()
405        morsel.update(attribs)
406        self.assertEqual(morsel['expires'], 1)
407        self.assertEqual(morsel['version'], 2)
408        self.assertEqual(morsel['domain'], 'example.com')
409        # test iterable update
410        morsel = cookies.Morsel()
411        morsel.update(list(attribs.items()))
412        self.assertEqual(morsel['expires'], 1)
413        self.assertEqual(morsel['version'], 2)
414        self.assertEqual(morsel['domain'], 'example.com')
415        # test iterator update
416        morsel = cookies.Morsel()
417        morsel.update((k, v) for k, v in attribs.items())
418        self.assertEqual(morsel['expires'], 1)
419        self.assertEqual(morsel['version'], 2)
420        self.assertEqual(morsel['domain'], 'example.com')
421
422        with self.assertRaises(cookies.CookieError):
423            morsel.update({'invalid': 'value'})
424        self.assertNotIn('invalid', morsel)
425        self.assertRaises(TypeError, morsel.update)
426        self.assertRaises(TypeError, morsel.update, 0)
427
428    def test_pickle(self):
429        morsel_a = cookies.Morsel()
430        morsel_a.set('foo', 'bar', 'baz')
431        morsel_a.update({
432            'version': 2,
433            'comment': 'foo',
434        })
435        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
436            with self.subTest(proto=proto):
437                morsel_b = pickle.loads(pickle.dumps(morsel_a, proto))
438                self.assertIsInstance(morsel_b, cookies.Morsel)
439                self.assertEqual(morsel_b, morsel_a)
440                self.assertEqual(str(morsel_b), str(morsel_a))
441
442    def test_repr(self):
443        morsel = cookies.Morsel()
444        self.assertEqual(repr(morsel), '<Morsel: None=None>')
445        self.assertEqual(str(morsel), 'Set-Cookie: None=None')
446        morsel.set('key', 'val', 'coded_val')
447        self.assertEqual(repr(morsel), '<Morsel: key=coded_val>')
448        self.assertEqual(str(morsel), 'Set-Cookie: key=coded_val')
449        morsel.update({
450            'path': '/',
451            'comment': 'foo',
452            'domain': 'example.com',
453            'max-age': 0,
454            'secure': 0,
455            'version': 1,
456        })
457        self.assertEqual(repr(morsel),
458                '<Morsel: key=coded_val; Comment=foo; Domain=example.com; '
459                'Max-Age=0; Path=/; Version=1>')
460        self.assertEqual(str(morsel),
461                'Set-Cookie: key=coded_val; Comment=foo; Domain=example.com; '
462                'Max-Age=0; Path=/; Version=1')
463        morsel['secure'] = True
464        morsel['httponly'] = 1
465        self.assertEqual(repr(morsel),
466                '<Morsel: key=coded_val; Comment=foo; Domain=example.com; '
467                'HttpOnly; Max-Age=0; Path=/; Secure; Version=1>')
468        self.assertEqual(str(morsel),
469                'Set-Cookie: key=coded_val; Comment=foo; Domain=example.com; '
470                'HttpOnly; Max-Age=0; Path=/; Secure; Version=1')
471
472        morsel = cookies.Morsel()
473        morsel.set('key', 'val', 'coded_val')
474        morsel['expires'] = 0
475        self.assertRegex(repr(morsel),
476                r'<Morsel: key=coded_val; '
477                r'expires=\w+, \d+ \w+ \d+ \d+:\d+:\d+ \w+>')
478        self.assertRegex(str(morsel),
479                r'Set-Cookie: key=coded_val; '
480                r'expires=\w+, \d+ \w+ \d+ \d+:\d+:\d+ \w+')
481
482def test_main():
483    run_unittest(CookieTests, MorselTests)
484    run_doctest(cookies)
485
486if __name__ == '__main__':
487    test_main()
488