Debian Codegraph @

Lib/test/test_http_cookies.py

raw
1 # Simple test suite for http/cookies.py
2
3 import copy
4 import unittest
5 import doctest
6 from http import cookies
7 import pickle
8 from test import support
9 from test.support.testcase import ExtraAssertions
10
11
12 class CookieTests(unittest.TestCase, ExtraAssertions):
13
14 def test_basic(self):
15 cases = [
16 {'data': 'chips=ahoy; vienna=finger',
17 'dict': {'chips':'ahoy', 'vienna':'finger'},
18 'repr': "<SimpleCookie: chips='ahoy' vienna='finger'>",
19 'output': 'Set-Cookie: chips=ahoy\nSet-Cookie: vienna=finger'},
20
21 {'data': 'keebler="E=mc2; L=\\"Loves\\"; fudge=;"',
22 'dict': {'keebler' : 'E=mc2; L="Loves"; fudge=;'},
23 'repr': '''<SimpleCookie: keebler='E=mc2; L="Loves"; fudge=;'>''',
24 'output': 'Set-Cookie: keebler="E=mc2; L=\\"Loves\\"; fudge=;"'},
25
26 # Check illegal cookies that have an '=' char in an unquoted value
27 {'data': 'keebler=E=mc2',
28 'dict': {'keebler' : 'E=mc2'},
29 'repr': "<SimpleCookie: keebler='E=mc2'>",
30 'output': 'Set-Cookie: keebler=E=mc2'},
31
32 # Cookies with ':' character in their name. Though not mentioned in
33 # RFC, servers / browsers allow it.
34
35 {'data': 'key:term=value:term',
36 'dict': {'key:term' : 'value:term'},
37 'repr': "<SimpleCookie: key:term='value:term'>",
38 'output': 'Set-Cookie: key:term=value:term'},
39
40 # issue22931 - Adding '[' and ']' as valid characters in cookie
41 # values as defined in RFC 6265
42 {
43 'data': 'a=b; c=[; d=r; f=h',
44 'dict': {'a':'b', 'c':'[', 'd':'r', 'f':'h'},
45 'repr': "<SimpleCookie: a='b' c='[' d='r' f='h'>",
46 'output': '\n'.join((
47 'Set-Cookie: a=b',
48 'Set-Cookie: c=[',
49 'Set-Cookie: d=r',
50 'Set-Cookie: f=h'
51 ))
52 }
53 ]
54
55 for case in cases:
56 C = cookies.SimpleCookie()
57 C.load(case['data'])
58 self.assertEqual(repr(C), case['repr'])
59 self.assertEqual(C.output(sep='\n'), case['output'])
60 for k, v in sorted(case['dict'].items()):
61 self.assertEqual(C[k].value, v)
62
63 def test_obsolete_rfc850_date_format(self):
64 # Test cases with different days and dates in obsolete RFC 850 format
65 test_cases = [
66 # from RFC 850, change EST to GMT
67 # https://datatracker.ietf.org/doc/html/rfc850#section-2
68 {
69 'data': 'key=value; expires=Saturday, 01-Jan-83 00:00:00 GMT',
70 'output': 'Saturday, 01-Jan-83 00:00:00 GMT'
71 },
72 {
73 'data': 'key=value; expires=Friday, 19-Nov-82 16:59:30 GMT',
74 'output': 'Friday, 19-Nov-82 16:59:30 GMT'
75 },
76 # from RFC 9110
77 # https://www.rfc-editor.org/rfc/rfc9110.html#section-5.6.7-6
78 {
79 'data': 'key=value; expires=Sunday, 06-Nov-94 08:49:37 GMT',
80 'output': 'Sunday, 06-Nov-94 08:49:37 GMT'
81 },
82 # other test cases
83 {
84 'data': 'key=value; expires=Wednesday, 09-Nov-94 08:49:37 GMT',
85 'output': 'Wednesday, 09-Nov-94 08:49:37 GMT'
86 },
87 {
88 'data': 'key=value; expires=Friday, 11-Nov-94 08:49:37 GMT',
89 'output': 'Friday, 11-Nov-94 08:49:37 GMT'
90 },
91 {
92 'data': 'key=value; expires=Monday, 14-Nov-94 08:49:37 GMT',
93 'output': 'Monday, 14-Nov-94 08:49:37 GMT'
94 },
95 ]
96
97 for case in test_cases:
98 with self.subTest(data=case['data']):
99 C = cookies.SimpleCookie()
100 C.load(case['data'])
101
102 # Extract the cookie name from the data string
103 cookie_name = case['data'].split('=')[0]
104
105 # Check if the cookie is loaded correctly
106 self.assertIn(cookie_name, C)
107 self.assertEqual(C[cookie_name].get('expires'), case['output'])
108
109 def test_unquote(self):
110 cases = [
111 (r'a="b=\""', 'b="'),
112 (r'a="b=\\"', 'b=\\'),
113 (r'a="b=\="', 'b=='),
114 (r'a="b=\n"', 'b=n'),
115 (r'a="b=\042"', 'b="'),
116 (r'a="b=\134"', 'b=\\'),
117 (r'a="b=\377"', 'b=\xff'),
118 (r'a="b=\400"', 'b=400'),
119 (r'a="b=\42"', 'b=42'),
120 (r'a="b=\\042"', 'b=\\042'),
121 (r'a="b=\\134"', 'b=\\134'),
122 (r'a="b=\\\""', 'b=\\"'),
123 (r'a="b=\\\042"', 'b=\\"'),
124 (r'a="b=\134\""', 'b=\\"'),
125 (r'a="b=\134\042"', 'b=\\"'),
126 ]
127 for encoded, decoded in cases:
128 with self.subTest(encoded):
129 C = cookies.SimpleCookie()
130 C.load(encoded)
131 self.assertEqual(C['a'].value, decoded)
132
133 @support.requires_resource('cpu')
134 def test_unquote_large(self):
135 n = 10**6
136 for encoded in r'\\', r'\134':
137 with self.subTest(encoded):
138 data = 'a="b=' + encoded*n + ';"'
139 C = cookies.SimpleCookie()
140 C.load(data)
141 value = C['a'].value
142 self.assertEqual(value[:3], 'b=\\')
143 self.assertEqual(value[-2:], '\\;')
144 self.assertEqual(len(value), n + 3)
145
146 def test_load(self):
147 C = cookies.SimpleCookie()
148 C.load('Customer="WILE_E_COYOTE"; Version=1; Path=/acme')
149
150 self.assertEqual(C['Customer'].value, 'WILE_E_COYOTE')
151 self.assertEqual(C['Customer']['version'], '1')
152 self.assertEqual(C['Customer']['path'], '/acme')
153
154 self.assertEqual(C.output(['path']),
155 'Set-Cookie: Customer="WILE_E_COYOTE"; Path=/acme')
156 self.assertEqual(C.js_output(), r"""
157 <script type="text/javascript">
158 <!-- begin hiding
159 document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme; Version=1";
160 // end hiding -->
161 </script>
162 """)
163 self.assertEqual(C.js_output(['path']), r"""
164 <script type="text/javascript">
165 <!-- begin hiding
166 document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme";
167 // end hiding -->
168 </script>
169 """)
170
171 def test_extended_encode(self):
172 # Issue 9824: some browsers don't follow the standard; we now
173 # encode , and ; to keep them from tripping up.
174 C = cookies.SimpleCookie()
175 C['val'] = "some,funky;stuff"
176 self.assertEqual(C.output(['val']),
177 'Set-Cookie: val="some\\054funky\\073stuff"')
178
179 def test_special_attrs(self):
180 # 'expires'
181 C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"')
182 C['Customer']['expires'] = 0
183 # can't test exact output, it always depends on current date/time
184 self.assertEndsWith(C.output(), 'GMT')
185
186 # loading 'expires'
187 C = cookies.SimpleCookie()
188 C.load('Customer="W"; expires=Wed, 01 Jan 2010 00:00:00 GMT')
189 self.assertEqual(C['Customer']['expires'],
190 'Wed, 01 Jan 2010 00:00:00 GMT')
191 C = cookies.SimpleCookie()
192 C.load('Customer="W"; expires=Wed, 01 Jan 98 00:00:00 GMT')
193 self.assertEqual(C['Customer']['expires'],
194 'Wed, 01 Jan 98 00:00:00 GMT')
195
196 # 'max-age'
197 C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"')
198 C['Customer']['max-age'] = 10
199 self.assertEqual(C.output(),
200 'Set-Cookie: Customer="WILE_E_COYOTE"; Max-Age=10')
201
202 def test_set_secure_httponly_attrs(self):
203 C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"')
204 C['Customer']['secure'] = True
205 C['Customer']['httponly'] = True
206 self.assertEqual(C.output(),
207 'Set-Cookie: Customer="WILE_E_COYOTE"; HttpOnly; Secure')
208
209 def test_samesite_attrs(self):
210 samesite_values = ['Strict', 'Lax', 'strict', 'lax']
211 for val in samesite_values:
212 with self.subTest(val=val):
213 C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"')
214 C['Customer']['samesite'] = val
215 self.assertEqual(C.output(),
216 'Set-Cookie: Customer="WILE_E_COYOTE"; SameSite=%s' % val)
217
218 C = cookies.SimpleCookie()
219 C.load('Customer="WILL_E_COYOTE"; SameSite=%s' % val)
220 self.assertEqual(C['Customer']['samesite'], val)
221
222 def test_secure_httponly_false_if_not_present(self):
223 C = cookies.SimpleCookie()
224 C.load('eggs=scrambled; Path=/bacon')
225 self.assertFalse(C['eggs']['httponly'])
226 self.assertFalse(C['eggs']['secure'])
227
228 def test_secure_httponly_true_if_present(self):
229 # Issue 16611
230 C = cookies.SimpleCookie()
231 C.load('eggs=scrambled; httponly; secure; Path=/bacon')
232 self.assertTrue(C['eggs']['httponly'])
233 self.assertTrue(C['eggs']['secure'])
234
235 def test_secure_httponly_true_if_have_value(self):
236 # This isn't really valid, but demonstrates what the current code
237 # is expected to do in this case.
238 C = cookies.SimpleCookie()
239 C.load('eggs=scrambled; httponly=foo; secure=bar; Path=/bacon')
240 self.assertTrue(C['eggs']['httponly'])
241 self.assertTrue(C['eggs']['secure'])
242 # Here is what it actually does; don't depend on this behavior. These
243 # checks are testing backward compatibility for issue 16611.
244 self.assertEqual(C['eggs']['httponly'], 'foo')
245 self.assertEqual(C['eggs']['secure'], 'bar')
246
247 def test_extra_spaces(self):
248 C = cookies.SimpleCookie()
249 C.load('eggs = scrambled ; secure ; path = bar ; foo=foo ')
250 self.assertEqual(C.output(),
251 'Set-Cookie: eggs=scrambled; Path=bar; Secure\r\nSet-Cookie: foo=foo')
252
253 def test_quoted_meta(self):
254 # Try cookie with quoted meta-data
255 C = cookies.SimpleCookie()
256 C.load('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"')
257 self.assertEqual(C['Customer'].value, 'WILE_E_COYOTE')
258 self.assertEqual(C['Customer']['version'], '1')
259 self.assertEqual(C['Customer']['path'], '/acme')
260
261 self.assertEqual(C.output(['path']),
262 'Set-Cookie: Customer="WILE_E_COYOTE"; Path=/acme')
263 self.assertEqual(C.js_output(), r"""
264 <script type="text/javascript">
265 <!-- begin hiding
266 document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme; Version=1";
267 // end hiding -->
268 </script>
269 """)
270 self.assertEqual(C.js_output(['path']), r"""
271 <script type="text/javascript">
272 <!-- begin hiding
273 document.cookie = "Customer=\"WILE_E_COYOTE\"; Path=/acme";
274 // end hiding -->
275 </script>
276 """)
277
278 def test_invalid_cookies(self):
279 # Accepting these could be a security issue
280 C = cookies.SimpleCookie()
281 for s in (']foo=x', '[foo=x', 'blah]foo=x', 'blah[foo=x',
282 'Set-Cookie: foo=bar', 'Set-Cookie: foo',
283 'foo=bar; baz', 'baz; foo=bar',
284 'secure;foo=bar', 'Version=1;foo=bar'):
285 C.load(s)
286 self.assertEqual(dict(C), {})
287 self.assertEqual(C.output(), '')
288
289 def test_pickle(self):
290 rawdata = 'Customer="WILE_E_COYOTE"; Path=/acme; Version=1'
291 expected_output = 'Set-Cookie: %s' % rawdata
292
293 C = cookies.SimpleCookie()
294 C.load(rawdata)
295 self.assertEqual(C.output(), expected_output)
296
297 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
298 with self.subTest(proto=proto):
299 C1 = pickle.loads(pickle.dumps(C, protocol=proto))
300 self.assertEqual(C1.output(), expected_output)
301
302 def test_illegal_chars(self):
303 rawdata = "a=b; c,d=e"
304 C = cookies.SimpleCookie()
305 with self.assertRaises(cookies.CookieError):
306 C.load(rawdata)
307
308 def test_comment_quoting(self):
309 c = cookies.SimpleCookie()
310 c['foo'] = '\N{COPYRIGHT SIGN}'
311 self.assertEqual(str(c['foo']), 'Set-Cookie: foo="\\251"')
312 c['foo']['comment'] = 'comment \N{COPYRIGHT SIGN}'
313 self.assertEqual(
314 str(c['foo']),
315 'Set-Cookie: foo="\\251"; Comment="comment \\251"'
316 )
317
318
319 class MorselTests(unittest.TestCase):
320 """Tests for the Morsel object."""
321
322 def test_defaults(self):
323 morsel = cookies.Morsel()
324 self.assertIsNone(morsel.key)
325 self.assertIsNone(morsel.value)
326 self.assertIsNone(morsel.coded_value)
327 self.assertEqual(morsel.keys(), cookies.Morsel._reserved.keys())
328 for key, val in morsel.items():
329 self.assertEqual(val, '', key)
330
331 def test_reserved_keys(self):
332 M = cookies.Morsel()
333 # tests valid and invalid reserved keys for Morsels
334 for i in M._reserved:
335 # Test that all valid keys are reported as reserved and set them
336 self.assertTrue(M.isReservedKey(i))
337 M[i] = '%s_value' % i
338 for i in M._reserved:
339 # Test that valid key values come out fine
340 self.assertEqual(M[i], '%s_value' % i)
341 for i in "the holy hand grenade".split():
342 # Test that invalid keys raise CookieError
343 self.assertRaises(cookies.CookieError,
344 M.__setitem__, i, '%s_value' % i)
345
346 def test_setter(self):
347 M = cookies.Morsel()
348 # tests the .set method to set keys and their values
349 for i in M._reserved:
350 # Makes sure that all reserved keys can't be set this way
351 self.assertRaises(cookies.CookieError,
352 M.set, i, '%s_value' % i, '%s_value' % i)
353 for i in "thou cast _the- !holy! ^hand| +*grenade~".split():
354 # Try typical use case. Setting decent values.
355 # Check output and js_output.
356 M['path'] = '/foo' # Try a reserved key as well
357 M.set(i, "%s_val" % i, "%s_coded_val" % i)
358 self.assertEqual(M.key, i)
359 self.assertEqual(M.value, "%s_val" % i)
360 self.assertEqual(M.coded_value, "%s_coded_val" % i)
361 self.assertEqual(
362 M.output(),
363 "Set-Cookie: %s=%s; Path=/foo" % (i, "%s_coded_val" % i))
364 expected_js_output = """
365 <script type="text/javascript">
366 <!-- begin hiding
367 document.cookie = "%s=%s; Path=/foo";
368 // end hiding -->
369 </script>
370 """ % (i, "%s_coded_val" % i)
371 self.assertEqual(M.js_output(), expected_js_output)
372 for i in ["foo bar", "foo@bar"]:
373 # Try some illegal characters
374 self.assertRaises(cookies.CookieError,
375 M.set, i, '%s_value' % i, '%s_value' % i)
376
377 def test_set_properties(self):
378 morsel = cookies.Morsel()
379 with self.assertRaises(AttributeError):
380 morsel.key = ''
381 with self.assertRaises(AttributeError):
382 morsel.value = ''
383 with self.assertRaises(AttributeError):
384 morsel.coded_value = ''
385
386 def test_eq(self):
387 base_case = ('key', 'value', '"value"')
388 attribs = {
389 'path': '/',
390 'comment': 'foo',
391 'domain': 'example.com',
392 'version': 2,
393 }
394 morsel_a = cookies.Morsel()
395 morsel_a.update(attribs)
396 morsel_a.set(*base_case)
397 morsel_b = cookies.Morsel()
398 morsel_b.update(attribs)
399 morsel_b.set(*base_case)
400 self.assertTrue(morsel_a == morsel_b)
401 self.assertFalse(morsel_a != morsel_b)
402 cases = (
403 ('key', 'value', 'mismatch'),
404 ('key', 'mismatch', '"value"'),
405 ('mismatch', 'value', '"value"'),
406 )
407 for case_b in cases:
408 with self.subTest(case_b):
409 morsel_b = cookies.Morsel()
410 morsel_b.update(attribs)
411 morsel_b.set(*case_b)
412 self.assertFalse(morsel_a == morsel_b)
413 self.assertTrue(morsel_a != morsel_b)
414
415 morsel_b = cookies.Morsel()
416 morsel_b.update(attribs)
417 morsel_b.set(*base_case)
418 morsel_b['comment'] = 'bar'
419 self.assertFalse(morsel_a == morsel_b)
420 self.assertTrue(morsel_a != morsel_b)
421
422 # test mismatched types
423 self.assertFalse(cookies.Morsel() == 1)
424 self.assertTrue(cookies.Morsel() != 1)
425 self.assertFalse(cookies.Morsel() == '')
426 self.assertTrue(cookies.Morsel() != '')
427 items = list(cookies.Morsel().items())
428 self.assertFalse(cookies.Morsel() == items)
429 self.assertTrue(cookies.Morsel() != items)
430
431 # morsel/dict
432 morsel = cookies.Morsel()
433 morsel.set(*base_case)
434 morsel.update(attribs)
435 self.assertTrue(morsel == dict(morsel))
436 self.assertFalse(morsel != dict(morsel))
437
438 def test_copy(self):
439 morsel_a = cookies.Morsel()
440 morsel_a.set('foo', 'bar', 'baz')
441 morsel_a.update({
442 'version': 2,
443 'comment': 'foo',
444 })
445 morsel_b = morsel_a.copy()
446 self.assertIsInstance(morsel_b, cookies.Morsel)
447 self.assertIsNot(morsel_a, morsel_b)
448 self.assertEqual(morsel_a, morsel_b)
449
450 morsel_b = copy.copy(morsel_a)
451 self.assertIsInstance(morsel_b, cookies.Morsel)
452 self.assertIsNot(morsel_a, morsel_b)
453 self.assertEqual(morsel_a, morsel_b)
454
455 def test_setitem(self):
456 morsel = cookies.Morsel()
457 morsel['expires'] = 0
458 self.assertEqual(morsel['expires'], 0)
459 morsel['Version'] = 2
460 self.assertEqual(morsel['version'], 2)
461 morsel['DOMAIN'] = 'example.com'
462 self.assertEqual(morsel['domain'], 'example.com')
463
464 with self.assertRaises(cookies.CookieError):
465 morsel['invalid'] = 'value'
466 self.assertNotIn('invalid', morsel)
467
468 def test_setdefault(self):
469 morsel = cookies.Morsel()
470 morsel.update({
471 'domain': 'example.com',
472 'version': 2,
473 })
474 # this shouldn't override the default value
475 self.assertEqual(morsel.setdefault('expires', 'value'), '')
476 self.assertEqual(morsel['expires'], '')
477 self.assertEqual(morsel.setdefault('Version', 1), 2)
478 self.assertEqual(morsel['version'], 2)
479 self.assertEqual(morsel.setdefault('DOMAIN', 'value'), 'example.com')
480 self.assertEqual(morsel['domain'], 'example.com')
481
482 with self.assertRaises(cookies.CookieError):
483 morsel.setdefault('invalid', 'value')
484 self.assertNotIn('invalid', morsel)
485
486 def test_update(self):
487 attribs = {'expires': 1, 'Version': 2, 'DOMAIN': 'example.com'}
488 # test dict update
489 morsel = cookies.Morsel()
490 morsel.update(attribs)
491 self.assertEqual(morsel['expires'], 1)
492 self.assertEqual(morsel['version'], 2)
493 self.assertEqual(morsel['domain'], 'example.com')
494 # test iterable update
495 morsel = cookies.Morsel()
496 morsel.update(list(attribs.items()))
497 self.assertEqual(morsel['expires'], 1)
498 self.assertEqual(morsel['version'], 2)
499 self.assertEqual(morsel['domain'], 'example.com')
500 # test iterator update
501 morsel = cookies.Morsel()
502 morsel.update((k, v) for k, v in attribs.items())
503 self.assertEqual(morsel['expires'], 1)
504 self.assertEqual(morsel['version'], 2)
505 self.assertEqual(morsel['domain'], 'example.com')
506
507 with self.assertRaises(cookies.CookieError):
508 morsel.update({'invalid': 'value'})
509 self.assertNotIn('invalid', morsel)
510 self.assertRaises(TypeError, morsel.update)
511 self.assertRaises(TypeError, morsel.update, 0)
512
513 def test_pickle(self):
514 morsel_a = cookies.Morsel()
515 morsel_a.set('foo', 'bar', 'baz')
516 morsel_a.update({
517 'version': 2,
518 'comment': 'foo',
519 })
520 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
521 with self.subTest(proto=proto):
522 morsel_b = pickle.loads(pickle.dumps(morsel_a, proto))
523 self.assertIsInstance(morsel_b, cookies.Morsel)
524 self.assertEqual(morsel_b, morsel_a)
525 self.assertEqual(str(morsel_b), str(morsel_a))
526
527 def test_repr(self):
528 morsel = cookies.Morsel()
529 self.assertEqual(repr(morsel), '<Morsel: None=None>')
530 self.assertEqual(str(morsel), 'Set-Cookie: None=None')
531 morsel.set('key', 'val', 'coded_val')
532 self.assertEqual(repr(morsel), '<Morsel: key=coded_val>')
533 self.assertEqual(str(morsel), 'Set-Cookie: key=coded_val')
534 morsel.update({
535 'path': '/',
536 'comment': 'foo',
537 'domain': 'example.com',
538 'max-age': 0,
539 'secure': 0,
540 'version': 1,
541 })
542 self.assertEqual(repr(morsel),
543 '<Morsel: key=coded_val; Comment=foo; Domain=example.com; '
544 'Max-Age=0; Path=/; Version=1>')
545 self.assertEqual(str(morsel),
546 'Set-Cookie: key=coded_val; Comment=foo; Domain=example.com; '
547 'Max-Age=0; Path=/; Version=1')
548 morsel['secure'] = True
549 morsel['httponly'] = 1
550 self.assertEqual(repr(morsel),
551 '<Morsel: key=coded_val; Comment=foo; Domain=example.com; '
552 'HttpOnly; Max-Age=0; Path=/; Secure; Version=1>')
553 self.assertEqual(str(morsel),
554 'Set-Cookie: key=coded_val; Comment=foo; Domain=example.com; '
555 'HttpOnly; Max-Age=0; Path=/; Secure; Version=1')
556
557 morsel = cookies.Morsel()
558 morsel.set('key', 'val', 'coded_val')
559 morsel['expires'] = 0
560 self.assertRegex(repr(morsel),
561 r'<Morsel: key=coded_val; '
562 r'expires=\w+, \d+ \w+ \d+ \d+:\d+:\d+ \w+>')
563 self.assertRegex(str(morsel),
564 r'Set-Cookie: key=coded_val; '
565 r'expires=\w+, \d+ \w+ \d+ \d+:\d+:\d+ \w+')
566
567 def test_control_characters(self):
568 for c0 in support.control_characters_c0():
569 morsel = cookies.Morsel()
570
571 # .__setitem__()
572 with self.assertRaises(cookies.CookieError):
573 morsel[c0] = "val"
574 with self.assertRaises(cookies.CookieError):
575 morsel["path"] = c0
576
577 # .setdefault()
578 with self.assertRaises(cookies.CookieError):
579 morsel.setdefault("path", c0)
580 with self.assertRaises(cookies.CookieError):
581 morsel.setdefault(c0, "val")
582
583 # .set()
584 with self.assertRaises(cookies.CookieError):
585 morsel.set(c0, "val", "coded-value")
586 with self.assertRaises(cookies.CookieError):
587 morsel.set("path", c0, "coded-value")
588 with self.assertRaises(cookies.CookieError):
589 morsel.set("path", "val", c0)
590
591 def test_control_characters_output(self):
592 # Tests that even if the internals of Morsel are modified
593 # that a call to .output() has control character safeguards.
594 for c0 in support.control_characters_c0():
595 morsel = cookies.Morsel()
596 morsel.set("key", "value", "coded-value")
597 morsel._key = c0 # Override private variable.
598 cookie = cookies.SimpleCookie()
599 cookie["cookie"] = morsel
600 with self.assertRaises(cookies.CookieError):
601 cookie.output()
602
603 morsel = cookies.Morsel()
604 morsel.set("key", "value", "coded-value")
605 morsel._coded_value = c0 # Override private variable.
606 cookie = cookies.SimpleCookie()
607 cookie["cookie"] = morsel
608 with self.assertRaises(cookies.CookieError):
609 cookie.output()
610
611
612 def load_tests(loader, tests, pattern):
613 tests.addTest(doctest.DocTestSuite(cookies))
614 return tests
615
616
617 if __name__ == '__main__':
618 unittest.main()