blob: 712a4ae6398042aa25ed632b30b591944e4ecf81 [file] [log] [blame]
Georg Brandl24420152008-05-26 16:32:26 +00001"""Tests for http/cookiejar.py."""
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00002
Gregory P. Smith41e6c3d2010-07-19 23:17:22 +00003import os
4import re
5import test.support
6import time
7import unittest
8import urllib.request
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00009
Gregory P. Smith41e6c3d2010-07-19 23:17:22 +000010from http.cookiejar import (time2isoz, http2time, time2netscape,
11 parse_ns_headers, join_header_words, split_header_words, Cookie,
12 CookieJar, DefaultCookiePolicy, LWPCookieJar, MozillaCookieJar,
13 LoadError, lwp_cookie_str, DEFAULT_HTTP_PORT, escape_path,
14 reach, is_HDN, domain_match, user_domain_match, request_path,
15 request_port, request_host)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +000016
Georg Brandl24420152008-05-26 16:32:26 +000017
Gregory P. Smith41e6c3d2010-07-19 23:17:22 +000018class DateTimeTests(unittest.TestCase):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +000019
20 def test_time2isoz(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +000021 base = 1019227000
22 day = 24*3600
Ezio Melottib3aedd42010-11-20 19:04:17 +000023 self.assertEqual(time2isoz(base), "2002-04-19 14:36:40Z")
24 self.assertEqual(time2isoz(base+day), "2002-04-20 14:36:40Z")
25 self.assertEqual(time2isoz(base+2*day), "2002-04-21 14:36:40Z")
26 self.assertEqual(time2isoz(base+3*day), "2002-04-22 14:36:40Z")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +000027
28 az = time2isoz()
29 bz = time2isoz(500000)
30 for text in (az, bz):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000031 self.assertTrue(re.search(r"^\d{4}-\d\d-\d\d \d\d:\d\d:\d\dZ$", text),
Ezio Melottib3aedd42010-11-20 19:04:17 +000032 "bad time2isoz format: %s %s" % (az, bz))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +000033
34 def test_http2time(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +000035 def parse_date(text):
36 return time.gmtime(http2time(text))[:6]
37
Ezio Melottib3aedd42010-11-20 19:04:17 +000038 self.assertEqual(parse_date("01 Jan 2001"), (2001, 1, 1, 0, 0, 0.0))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +000039
40 # this test will break around year 2070
Ezio Melottib3aedd42010-11-20 19:04:17 +000041 self.assertEqual(parse_date("03-Feb-20"), (2020, 2, 3, 0, 0, 0.0))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +000042
43 # this test will break around year 2048
Ezio Melottib3aedd42010-11-20 19:04:17 +000044 self.assertEqual(parse_date("03-Feb-98"), (1998, 2, 3, 0, 0, 0.0))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +000045
46 def test_http2time_formats(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +000047 # test http2time for supported dates. Test cases with 2 digit year
48 # will probably break in year 2044.
49 tests = [
50 'Thu, 03 Feb 1994 00:00:00 GMT', # proposed new HTTP format
51 'Thursday, 03-Feb-94 00:00:00 GMT', # old rfc850 HTTP format
52 'Thursday, 03-Feb-1994 00:00:00 GMT', # broken rfc850 HTTP format
53
54 '03 Feb 1994 00:00:00 GMT', # HTTP format (no weekday)
55 '03-Feb-94 00:00:00 GMT', # old rfc850 (no weekday)
56 '03-Feb-1994 00:00:00 GMT', # broken rfc850 (no weekday)
57 '03-Feb-1994 00:00 GMT', # broken rfc850 (no weekday, no seconds)
58 '03-Feb-1994 00:00', # broken rfc850 (no weekday, no seconds, no tz)
59
60 '03-Feb-94', # old rfc850 HTTP format (no weekday, no time)
61 '03-Feb-1994', # broken rfc850 HTTP format (no weekday, no time)
62 '03 Feb 1994', # proposed new HTTP format (no weekday, no time)
63
64 # A few tests with extra space at various places
65 ' 03 Feb 1994 0:00 ',
66 ' 03-Feb-1994 ',
67 ]
68
69 test_t = 760233600 # assume broken POSIX counting of seconds
70 result = time2isoz(test_t)
71 expected = "1994-02-03 00:00:00Z"
Ezio Melottib3aedd42010-11-20 19:04:17 +000072 self.assertEqual(result, expected,
73 "%s => '%s' (%s)" % (test_t, result, expected))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +000074
75 for s in tests:
76 t = http2time(s)
77 t2 = http2time(s.lower())
78 t3 = http2time(s.upper())
79
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000080 self.assertTrue(t == t2 == t3 == test_t,
Martin v. Löwis2a6ba902004-05-31 18:22:40 +000081 "'%s' => %s, %s, %s (%s)" % (s, t, t2, t3, test_t))
82
83 def test_http2time_garbage(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +000084 for test in [
85 '',
86 'Garbage',
87 'Mandag 16. September 1996',
88 '01-00-1980',
89 '01-13-1980',
90 '00-01-1980',
91 '32-01-1980',
92 '01-01-1980 25:00:00',
93 '01-01-1980 00:61:00',
94 '01-01-1980 00:00:62',
95 ]:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000096 self.assertTrue(http2time(test) is None,
Martin v. Löwis2a6ba902004-05-31 18:22:40 +000097 "http2time(%s) is not None\n"
98 "http2time(test) %s" % (test, http2time(test))
99 )
100
101
Gregory P. Smith41e6c3d2010-07-19 23:17:22 +0000102class HeaderTests(unittest.TestCase):
Benjamin Peterson3e5cd1d2010-06-27 21:45:24 +0000103
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000104 def test_parse_ns_headers(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000105 # quotes should be stripped
Guido van Rossume2a383d2007-01-15 16:59:06 +0000106 expected = [[('foo', 'bar'), ('expires', 2209069412), ('version', '0')]]
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000107 for hdr in [
Martin v. Löwis4ea3ead2005-03-03 10:48:12 +0000108 'foo=bar; expires=01 Jan 2040 22:23:32 GMT',
109 'foo=bar; expires="01 Jan 2040 22:23:32 GMT"',
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000110 ]:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000111 self.assertEqual(parse_ns_headers([hdr]), expected)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000112
Benjamin Peterson3e5cd1d2010-06-27 21:45:24 +0000113 def test_parse_ns_headers_version(self):
114
115 # quotes should be stripped
116 expected = [[('foo', 'bar'), ('version', '1')]]
117 for hdr in [
118 'foo=bar; version="1"',
119 'foo=bar; Version="1"',
120 ]:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000121 self.assertEqual(parse_ns_headers([hdr]), expected)
Benjamin Peterson3e5cd1d2010-06-27 21:45:24 +0000122
Martin v. Löwis4ea3ead2005-03-03 10:48:12 +0000123 def test_parse_ns_headers_special_names(self):
124 # names such as 'expires' are not special in first name=value pair
125 # of Set-Cookie: header
Martin v. Löwis4ea3ead2005-03-03 10:48:12 +0000126 # Cookie with name 'expires'
127 hdr = 'expires=01 Jan 2040 22:23:32 GMT'
128 expected = [[("expires", "01 Jan 2040 22:23:32 GMT"), ("version", "0")]]
Ezio Melottib3aedd42010-11-20 19:04:17 +0000129 self.assertEqual(parse_ns_headers([hdr]), expected)
Martin v. Löwis4ea3ead2005-03-03 10:48:12 +0000130
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000131 def test_join_header_words(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000132 joined = join_header_words([[("foo", None), ("bar", "baz")]])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000133 self.assertEqual(joined, "foo; bar=baz")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000134
Ezio Melottib3aedd42010-11-20 19:04:17 +0000135 self.assertEqual(join_header_words([[]]), "")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000136
137 def test_split_header_words(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000138 tests = [
139 ("foo", [[("foo", None)]]),
140 ("foo=bar", [[("foo", "bar")]]),
141 (" foo ", [[("foo", None)]]),
142 (" foo= ", [[("foo", "")]]),
143 (" foo=", [[("foo", "")]]),
144 (" foo= ; ", [[("foo", "")]]),
145 (" foo= ; bar= baz ", [[("foo", ""), ("bar", "baz")]]),
146 ("foo=bar bar=baz", [[("foo", "bar"), ("bar", "baz")]]),
147 # doesn't really matter if this next fails, but it works ATM
148 ("foo= bar=baz", [[("foo", "bar=baz")]]),
149 ("foo=bar;bar=baz", [[("foo", "bar"), ("bar", "baz")]]),
150 ('foo bar baz', [[("foo", None), ("bar", None), ("baz", None)]]),
151 ("a, b, c", [[("a", None)], [("b", None)], [("c", None)]]),
152 (r'foo; bar=baz, spam=, foo="\,\;\"", bar= ',
153 [[("foo", None), ("bar", "baz")],
154 [("spam", "")], [("foo", ',;"')], [("bar", "")]]),
155 ]
156
157 for arg, expect in tests:
158 try:
159 result = split_header_words([arg])
160 except:
Guido van Rossum34d19282007-08-09 01:03:29 +0000161 import traceback, io
162 f = io.StringIO()
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000163 traceback.print_exc(None, f)
164 result = "(error -- traceback follows)\n\n%s" % f.getvalue()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000165 self.assertEqual(result, expect, """
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000166When parsing: '%s'
167Expected: '%s'
168Got: '%s'
169""" % (arg, expect, result))
170
171 def test_roundtrip(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000172 tests = [
173 ("foo", "foo"),
174 ("foo=bar", "foo=bar"),
175 (" foo ", "foo"),
176 ("foo=", 'foo=""'),
177 ("foo=bar bar=baz", "foo=bar; bar=baz"),
178 ("foo=bar;bar=baz", "foo=bar; bar=baz"),
179 ('foo bar baz', "foo; bar; baz"),
180 (r'foo="\"" bar="\\"', r'foo="\""; bar="\\"'),
181 ('foo,,,bar', 'foo, bar'),
182 ('foo=bar,bar=baz', 'foo=bar, bar=baz'),
183
184 ('text/html; charset=iso-8859-1',
185 'text/html; charset="iso-8859-1"'),
186
187 ('foo="bar"; port="80,81"; discard, bar=baz',
188 'foo=bar; port="80,81"; discard, bar=baz'),
189
190 (r'Basic realm="\"foo\\\\bar\""',
191 r'Basic; realm="\"foo\\\\bar\""')
192 ]
193
194 for arg, expect in tests:
195 input = split_header_words([arg])
196 res = join_header_words(input)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000197 self.assertEqual(res, expect, """
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000198When parsing: '%s'
199Expected: '%s'
200Got: '%s'
201Input was: '%s'
202""" % (arg, expect, res, input))
203
204
205class FakeResponse:
206 def __init__(self, headers=[], url=None):
207 """
208 headers: list of RFC822-style 'Key: value' strings
209 """
Barry Warsaw820c1202008-06-12 04:06:45 +0000210 import email
211 self._headers = email.message_from_string("\n".join(headers))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000212 self._url = url
213 def info(self): return self._headers
214
215def interact_2965(cookiejar, url, *set_cookie_hdrs):
216 return _interact(cookiejar, url, set_cookie_hdrs, "Set-Cookie2")
217
218def interact_netscape(cookiejar, url, *set_cookie_hdrs):
219 return _interact(cookiejar, url, set_cookie_hdrs, "Set-Cookie")
220
221def _interact(cookiejar, url, set_cookie_hdrs, hdr_name):
222 """Perform a single request / response cycle, returning Cookie: header."""
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000223 req = urllib.request.Request(url)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000224 cookiejar.add_cookie_header(req)
225 cookie_hdr = req.get_header("Cookie", "")
226 headers = []
227 for hdr in set_cookie_hdrs:
228 headers.append("%s: %s" % (hdr_name, hdr))
229 res = FakeResponse(headers, url)
230 cookiejar.extract_cookies(res, req)
231 return cookie_hdr
232
233
Gregory P. Smith41e6c3d2010-07-19 23:17:22 +0000234class FileCookieJarTests(unittest.TestCase):
Martin v. Löwisc5574e82005-03-03 10:57:37 +0000235 def test_lwp_valueless_cookie(self):
236 # cookies with no value should be saved and loaded consistently
Gregory P. Smith41e6c3d2010-07-19 23:17:22 +0000237 filename = test.support.TESTFN
Martin v. Löwisc5574e82005-03-03 10:57:37 +0000238 c = LWPCookieJar()
239 interact_netscape(c, "http://www.acme.com/", 'boo')
240 self.assertEqual(c._cookies["www.acme.com"]["/"]["boo"].value, None)
241 try:
242 c.save(filename, ignore_discard=True)
243 c = LWPCookieJar()
244 c.load(filename, ignore_discard=True)
245 finally:
246 try: os.unlink(filename)
247 except OSError: pass
248 self.assertEqual(c._cookies["www.acme.com"]["/"]["boo"].value, None)
249
Neal Norwitz3e7de592005-12-23 21:24:35 +0000250 def test_bad_magic(self):
Neal Norwitz3e7de592005-12-23 21:24:35 +0000251 # IOErrors (eg. file doesn't exist) are allowed to propagate
Gregory P. Smith41e6c3d2010-07-19 23:17:22 +0000252 filename = test.support.TESTFN
Neal Norwitz3e7de592005-12-23 21:24:35 +0000253 for cookiejar_class in LWPCookieJar, MozillaCookieJar:
254 c = cookiejar_class()
255 try:
256 c.load(filename="for this test to work, a file with this "
257 "filename should not exist")
Guido van Rossumb940e112007-01-10 16:19:56 +0000258 except IOError as exc:
Neal Norwitz3e7de592005-12-23 21:24:35 +0000259 # exactly IOError, not LoadError
260 self.assertEqual(exc.__class__, IOError)
261 else:
262 self.fail("expected IOError for invalid filename")
263 # Invalid contents of cookies file (eg. bad magic string)
264 # causes a LoadError.
265 try:
Brett Cannon7f462fc2010-10-29 23:27:39 +0000266 with open(filename, "w") as f:
267 f.write("oops\n")
268 for cookiejar_class in LWPCookieJar, MozillaCookieJar:
269 c = cookiejar_class()
270 self.assertRaises(LoadError, c.load, filename)
Neal Norwitz3e7de592005-12-23 21:24:35 +0000271 finally:
272 try: os.unlink(filename)
273 except OSError: pass
Martin v. Löwisc5574e82005-03-03 10:57:37 +0000274
Gregory P. Smith41e6c3d2010-07-19 23:17:22 +0000275class CookieTests(unittest.TestCase):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000276 # XXX
277 # Get rid of string comparisons where not actually testing str / repr.
278 # .clear() etc.
279 # IP addresses like 50 (single number, no dot) and domain-matching
280 # functions (and is_HDN)? See draft RFC 2965 errata.
281 # Strictness switches
282 # is_third_party()
283 # unverifiability / third-party blocking
284 # Netscape cookies work the same as RFC 2965 with regard to port.
285 # Set-Cookie with negative max age.
286 # If turn RFC 2965 handling off, Set-Cookie2 cookies should not clobber
287 # Set-Cookie cookies.
288 # Cookie2 should be sent if *any* cookies are not V1 (ie. V0 OR V2 etc.).
289 # Cookies (V1 and V0) with no expiry date should be set to be discarded.
290 # RFC 2965 Quoting:
291 # Should accept unquoted cookie-attribute values? check errata draft.
292 # Which are required on the way in and out?
293 # Should always return quoted cookie-attribute values?
294 # Proper testing of when RFC 2965 clobbers Netscape (waiting for errata).
295 # Path-match on return (same for V0 and V1).
296 # RFC 2965 acceptance and returning rules
297 # Set-Cookie2 without version attribute is rejected.
298
299 # Netscape peculiarities list from Ronald Tschalar.
300 # The first two still need tests, the rest are covered.
301## - Quoting: only quotes around the expires value are recognized as such
302## (and yes, some folks quote the expires value); quotes around any other
303## value are treated as part of the value.
304## - White space: white space around names and values is ignored
305## - Default path: if no path parameter is given, the path defaults to the
306## path in the request-uri up to, but not including, the last '/'. Note
307## that this is entirely different from what the spec says.
308## - Commas and other delimiters: Netscape just parses until the next ';'.
309## This means it will allow commas etc inside values (and yes, both
310## commas and equals are commonly appear in the cookie value). This also
311## means that if you fold multiple Set-Cookie header fields into one,
312## comma-separated list, it'll be a headache to parse (at least my head
313## starts hurting everytime I think of that code).
314## - Expires: You'll get all sorts of date formats in the expires,
315## including emtpy expires attributes ("expires="). Be as flexible as you
316## can, and certainly don't expect the weekday to be there; if you can't
317## parse it, just ignore it and pretend it's a session cookie.
318## - Domain-matching: Netscape uses the 2-dot rule for _all_ domains, not
319## just the 7 special TLD's listed in their spec. And folks rely on
320## that...
321
322 def test_domain_return_ok(self):
323 # test optimization: .domain_return_ok() should filter out most
324 # domains in the CookieJar before we try to access them (because that
325 # may require disk access -- in particular, with MSIECookieJar)
326 # This is only a rough check for performance reasons, so it's not too
327 # critical as long as it's sufficiently liberal.
Georg Brandl24420152008-05-26 16:32:26 +0000328 pol = DefaultCookiePolicy()
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000329 for url, domain, ok in [
330 ("http://foo.bar.com/", "blah.com", False),
331 ("http://foo.bar.com/", "rhubarb.blah.com", False),
332 ("http://foo.bar.com/", "rhubarb.foo.bar.com", False),
333 ("http://foo.bar.com/", ".foo.bar.com", True),
334 ("http://foo.bar.com/", "foo.bar.com", True),
335 ("http://foo.bar.com/", ".bar.com", True),
336 ("http://foo.bar.com/", "com", True),
337 ("http://foo.com/", "rhubarb.foo.com", False),
338 ("http://foo.com/", ".foo.com", True),
339 ("http://foo.com/", "foo.com", True),
340 ("http://foo.com/", "com", True),
341 ("http://foo/", "rhubarb.foo", False),
342 ("http://foo/", ".foo", True),
343 ("http://foo/", "foo", True),
344 ("http://foo/", "foo.local", True),
345 ("http://foo/", ".local", True),
346 ]:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000347 request = urllib.request.Request(url)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000348 r = pol.domain_return_ok(domain, request)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000349 if ok: self.assertTrue(r)
350 else: self.assertTrue(not r)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000351
352 def test_missing_value(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000353 # missing = sign in Cookie: header is regarded by Mozilla as a missing
Georg Brandl24420152008-05-26 16:32:26 +0000354 # name, and by http.cookiejar as a missing value
Gregory P. Smith41e6c3d2010-07-19 23:17:22 +0000355 filename = test.support.TESTFN
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000356 c = MozillaCookieJar(filename)
357 interact_netscape(c, "http://www.acme.com/", 'eggs')
358 interact_netscape(c, "http://www.acme.com/", '"spam"; path=/foo/')
359 cookie = c._cookies["www.acme.com"]["/"]["eggs"]
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000360 self.assertTrue(cookie.value is None)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000361 self.assertEqual(cookie.name, "eggs")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000362 cookie = c._cookies["www.acme.com"]['/foo/']['"spam"']
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000363 self.assertTrue(cookie.value is None)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000364 self.assertEqual(cookie.name, '"spam"')
365 self.assertEqual(lwp_cookie_str(cookie), (
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000366 r'"spam"; path="/foo/"; domain="www.acme.com"; '
367 'path_spec; discard; version=0'))
368 old_str = repr(c)
369 c.save(ignore_expires=True, ignore_discard=True)
370 try:
371 c = MozillaCookieJar(filename)
372 c.revert(ignore_expires=True, ignore_discard=True)
373 finally:
374 os.unlink(c.filename)
375 # cookies unchanged apart from lost info re. whether path was specified
Ezio Melottib3aedd42010-11-20 19:04:17 +0000376 self.assertEqual(
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000377 repr(c),
378 re.sub("path_specified=%s" % True, "path_specified=%s" % False,
379 old_str)
380 )
Ezio Melottib3aedd42010-11-20 19:04:17 +0000381 self.assertEqual(interact_netscape(c, "http://www.acme.com/foo/"),
382 '"spam"; eggs')
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000383
Neal Norwitz71dad722005-12-23 21:43:48 +0000384 def test_rfc2109_handling(self):
385 # RFC 2109 cookies are handled as RFC 2965 or Netscape cookies,
386 # dependent on policy settings
Neal Norwitz71dad722005-12-23 21:43:48 +0000387 for rfc2109_as_netscape, rfc2965, version in [
388 # default according to rfc2965 if not explicitly specified
389 (None, False, 0),
390 (None, True, 1),
391 # explicit rfc2109_as_netscape
392 (False, False, None), # version None here means no cookie stored
393 (False, True, 1),
394 (True, False, 0),
395 (True, True, 0),
396 ]:
397 policy = DefaultCookiePolicy(
398 rfc2109_as_netscape=rfc2109_as_netscape,
399 rfc2965=rfc2965)
400 c = CookieJar(policy)
401 interact_netscape(c, "http://www.example.com/", "ni=ni; Version=1")
402 try:
403 cookie = c._cookies["www.example.com"]["/"]["ni"]
404 except KeyError:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000405 self.assertTrue(version is None) # didn't expect a stored cookie
Neal Norwitz71dad722005-12-23 21:43:48 +0000406 else:
407 self.assertEqual(cookie.version, version)
408 # 2965 cookies are unaffected
409 interact_2965(c, "http://www.example.com/",
410 "foo=bar; Version=1")
411 if rfc2965:
412 cookie2965 = c._cookies["www.example.com"]["/"]["foo"]
413 self.assertEqual(cookie2965.version, 1)
414
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000415 def test_ns_parser(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000416 c = CookieJar()
417 interact_netscape(c, "http://www.acme.com/",
418 'spam=eggs; DoMain=.acme.com; port; blArgh="feep"')
419 interact_netscape(c, "http://www.acme.com/", 'ni=ni; port=80,8080')
420 interact_netscape(c, "http://www.acme.com:80/", 'nini=ni')
421 interact_netscape(c, "http://www.acme.com:80/", 'foo=bar; expires=')
422 interact_netscape(c, "http://www.acme.com:80/", 'spam=eggs; '
423 'expires="Foo Bar 25 33:22:11 3022"')
424
425 cookie = c._cookies[".acme.com"]["/"]["spam"]
Ezio Melottib3aedd42010-11-20 19:04:17 +0000426 self.assertEqual(cookie.domain, ".acme.com")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000427 self.assertTrue(cookie.domain_specified)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000428 self.assertEqual(cookie.port, DEFAULT_HTTP_PORT)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000429 self.assertTrue(not cookie.port_specified)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000430 # case is preserved
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000431 self.assertTrue(cookie.has_nonstandard_attr("blArgh") and
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000432 not cookie.has_nonstandard_attr("blargh"))
433
434 cookie = c._cookies["www.acme.com"]["/"]["ni"]
Ezio Melottib3aedd42010-11-20 19:04:17 +0000435 self.assertEqual(cookie.domain, "www.acme.com")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000436 self.assertTrue(not cookie.domain_specified)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000437 self.assertEqual(cookie.port, "80,8080")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000438 self.assertTrue(cookie.port_specified)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000439
440 cookie = c._cookies["www.acme.com"]["/"]["nini"]
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000441 self.assertTrue(cookie.port is None)
442 self.assertTrue(not cookie.port_specified)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000443
444 # invalid expires should not cause cookie to be dropped
445 foo = c._cookies["www.acme.com"]["/"]["foo"]
446 spam = c._cookies["www.acme.com"]["/"]["foo"]
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000447 self.assertTrue(foo.expires is None)
448 self.assertTrue(spam.expires is None)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000449
Martin v. Löwis4ea3ead2005-03-03 10:48:12 +0000450 def test_ns_parser_special_names(self):
451 # names such as 'expires' are not special in first name=value pair
452 # of Set-Cookie: header
Martin v. Löwis4ea3ead2005-03-03 10:48:12 +0000453 c = CookieJar()
454 interact_netscape(c, "http://www.acme.com/", 'expires=eggs')
455 interact_netscape(c, "http://www.acme.com/", 'version=eggs; spam=eggs')
456
457 cookies = c._cookies["www.acme.com"]["/"]
Benjamin Peterson577473f2010-01-19 00:09:57 +0000458 self.assertIn('expires', cookies)
459 self.assertIn('version', cookies)
Martin v. Löwis4ea3ead2005-03-03 10:48:12 +0000460
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000461 def test_expires(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000462 # if expires is in future, keep cookie...
463 c = CookieJar()
464 future = time2netscape(time.time()+3600)
465 interact_netscape(c, "http://www.acme.com/", 'spam="bar"; expires=%s' %
466 future)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000467 self.assertEqual(len(c), 1)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000468 now = time2netscape(time.time()-1)
469 # ... and if in past or present, discard it
470 interact_netscape(c, "http://www.acme.com/", 'foo="eggs"; expires=%s' %
471 now)
472 h = interact_netscape(c, "http://www.acme.com/")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000473 self.assertEqual(len(c), 1)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000474 self.assertIn('spam="bar"', h)
475 self.assertNotIn("foo", h)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000476
477 # max-age takes precedence over expires, and zero max-age is request to
478 # delete both new cookie and any old matching cookie
479 interact_netscape(c, "http://www.acme.com/", 'eggs="bar"; expires=%s' %
480 future)
481 interact_netscape(c, "http://www.acme.com/", 'bar="bar"; expires=%s' %
482 future)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000483 self.assertEqual(len(c), 3)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000484 interact_netscape(c, "http://www.acme.com/", 'eggs="bar"; '
485 'expires=%s; max-age=0' % future)
486 interact_netscape(c, "http://www.acme.com/", 'bar="bar"; '
487 'max-age=0; expires=%s' % future)
488 h = interact_netscape(c, "http://www.acme.com/")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000489 self.assertEqual(len(c), 1)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000490
491 # test expiry at end of session for cookies with no expires attribute
492 interact_netscape(c, "http://www.rhubarb.net/", 'whum="fizz"')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000493 self.assertEqual(len(c), 2)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000494 c.clear_session_cookies()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000495 self.assertEqual(len(c), 1)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000496 self.assertIn('spam="bar"', h)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000497
498 # XXX RFC 2965 expiry rules (some apply to V0 too)
499
500 def test_default_path(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000501 # RFC 2965
502 pol = DefaultCookiePolicy(rfc2965=True)
503
504 c = CookieJar(pol)
505 interact_2965(c, "http://www.acme.com/", 'spam="bar"; Version="1"')
Benjamin Peterson577473f2010-01-19 00:09:57 +0000506 self.assertIn("/", c._cookies["www.acme.com"])
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000507
508 c = CookieJar(pol)
509 interact_2965(c, "http://www.acme.com/blah", 'eggs="bar"; Version="1"')
Benjamin Peterson577473f2010-01-19 00:09:57 +0000510 self.assertIn("/", c._cookies["www.acme.com"])
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000511
512 c = CookieJar(pol)
513 interact_2965(c, "http://www.acme.com/blah/rhubarb",
514 'eggs="bar"; Version="1"')
Benjamin Peterson577473f2010-01-19 00:09:57 +0000515 self.assertIn("/blah/", c._cookies["www.acme.com"])
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000516
517 c = CookieJar(pol)
518 interact_2965(c, "http://www.acme.com/blah/rhubarb/",
519 'eggs="bar"; Version="1"')
Benjamin Peterson577473f2010-01-19 00:09:57 +0000520 self.assertIn("/blah/rhubarb/", c._cookies["www.acme.com"])
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000521
522 # Netscape
523
524 c = CookieJar()
525 interact_netscape(c, "http://www.acme.com/", 'spam="bar"')
Benjamin Peterson577473f2010-01-19 00:09:57 +0000526 self.assertIn("/", c._cookies["www.acme.com"])
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000527
528 c = CookieJar()
529 interact_netscape(c, "http://www.acme.com/blah", 'eggs="bar"')
Benjamin Peterson577473f2010-01-19 00:09:57 +0000530 self.assertIn("/", c._cookies["www.acme.com"])
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000531
532 c = CookieJar()
533 interact_netscape(c, "http://www.acme.com/blah/rhubarb", 'eggs="bar"')
Benjamin Peterson577473f2010-01-19 00:09:57 +0000534 self.assertIn("/blah", c._cookies["www.acme.com"])
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000535
536 c = CookieJar()
537 interact_netscape(c, "http://www.acme.com/blah/rhubarb/", 'eggs="bar"')
Benjamin Peterson577473f2010-01-19 00:09:57 +0000538 self.assertIn("/blah/rhubarb", c._cookies["www.acme.com"])
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000539
Gregory P. Smith41e6c3d2010-07-19 23:17:22 +0000540 def test_default_path_with_query(self):
541 cj = CookieJar()
542 uri = "http://example.com/?spam/eggs"
543 value = 'eggs="bar"'
544 interact_netscape(cj, uri, value)
545 # Default path does not include query, so is "/", not "/?spam".
546 self.assertIn("/", cj._cookies["example.com"])
547 # Cookie is sent back to the same URI.
Ezio Melottib3aedd42010-11-20 19:04:17 +0000548 self.assertEqual(interact_netscape(cj, uri), value)
Gregory P. Smith41e6c3d2010-07-19 23:17:22 +0000549
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000550 def test_escape_path(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000551 cases = [
552 # quoted safe
553 ("/foo%2f/bar", "/foo%2F/bar"),
554 ("/foo%2F/bar", "/foo%2F/bar"),
555 # quoted %
556 ("/foo%%/bar", "/foo%%/bar"),
557 # quoted unsafe
558 ("/fo%19o/bar", "/fo%19o/bar"),
559 ("/fo%7do/bar", "/fo%7Do/bar"),
560 # unquoted safe
561 ("/foo/bar&", "/foo/bar&"),
562 ("/foo//bar", "/foo//bar"),
563 ("\176/foo/bar", "\176/foo/bar"),
564 # unquoted unsafe
565 ("/foo\031/bar", "/foo%19/bar"),
566 ("/\175foo/bar", "/%7Dfoo/bar"),
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000567 # unicode, latin-1 range
568 ("/foo/bar\u00fc", "/foo/bar%C3%BC"), # UTF-8 encoded
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000569 # unicode
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000570 ("/foo/bar\uabcd", "/foo/bar%EA%AF%8D"), # UTF-8 encoded
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000571 ]
572 for arg, result in cases:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000573 self.assertEqual(escape_path(arg), result)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000574
575 def test_request_path(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000576 # with parameters
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000577 req = urllib.request.Request(
Gregory P. Smith41e6c3d2010-07-19 23:17:22 +0000578 "http://www.example.com/rheum/rhaponticum;"
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000579 "foo=bar;sing=song?apples=pears&spam=eggs#ni")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000580 self.assertEqual(request_path(req),
581 "/rheum/rhaponticum;foo=bar;sing=song")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000582 # without parameters
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000583 req = urllib.request.Request(
Gregory P. Smith41e6c3d2010-07-19 23:17:22 +0000584 "http://www.example.com/rheum/rhaponticum?"
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000585 "apples=pears&spam=eggs#ni")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000586 self.assertEqual(request_path(req), "/rheum/rhaponticum")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000587 # missing final slash
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000588 req = urllib.request.Request("http://www.example.com")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000589 self.assertEqual(request_path(req), "/")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000590
591 def test_request_port(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000592 req = urllib.request.Request("http://www.acme.com:1234/",
593 headers={"Host": "www.acme.com:4321"})
Ezio Melottib3aedd42010-11-20 19:04:17 +0000594 self.assertEqual(request_port(req), "1234")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000595 req = urllib.request.Request("http://www.acme.com/",
596 headers={"Host": "www.acme.com:4321"})
Ezio Melottib3aedd42010-11-20 19:04:17 +0000597 self.assertEqual(request_port(req), DEFAULT_HTTP_PORT)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000598
599 def test_request_host(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000600 # this request is illegal (RFC2616, 14.2.3)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000601 req = urllib.request.Request("http://1.1.1.1/",
602 headers={"Host": "www.acme.com:80"})
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000603 # libwww-perl wants this response, but that seems wrong (RFC 2616,
604 # section 5.2, point 1., and RFC 2965 section 1, paragraph 3)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000605 #self.assertEqual(request_host(req), "www.acme.com")
606 self.assertEqual(request_host(req), "1.1.1.1")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000607 req = urllib.request.Request("http://www.acme.com/",
608 headers={"Host": "irrelevant.com"})
Ezio Melottib3aedd42010-11-20 19:04:17 +0000609 self.assertEqual(request_host(req), "www.acme.com")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000610 # port shouldn't be in request-host
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000611 req = urllib.request.Request("http://www.acme.com:2345/resource.html",
612 headers={"Host": "www.acme.com:5432"})
Ezio Melottib3aedd42010-11-20 19:04:17 +0000613 self.assertEqual(request_host(req), "www.acme.com")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000614
615 def test_is_HDN(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000616 self.assertTrue(is_HDN("foo.bar.com"))
617 self.assertTrue(is_HDN("1foo2.3bar4.5com"))
618 self.assertTrue(not is_HDN("192.168.1.1"))
619 self.assertTrue(not is_HDN(""))
620 self.assertTrue(not is_HDN("."))
621 self.assertTrue(not is_HDN(".foo.bar.com"))
622 self.assertTrue(not is_HDN("..foo"))
623 self.assertTrue(not is_HDN("foo."))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000624
625 def test_reach(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000626 self.assertEqual(reach("www.acme.com"), ".acme.com")
627 self.assertEqual(reach("acme.com"), "acme.com")
628 self.assertEqual(reach("acme.local"), ".local")
629 self.assertEqual(reach(".local"), ".local")
630 self.assertEqual(reach(".com"), ".com")
631 self.assertEqual(reach("."), ".")
632 self.assertEqual(reach(""), "")
633 self.assertEqual(reach("192.168.0.1"), "192.168.0.1")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000634
635 def test_domain_match(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000636 self.assertTrue(domain_match("192.168.1.1", "192.168.1.1"))
637 self.assertTrue(not domain_match("192.168.1.1", ".168.1.1"))
638 self.assertTrue(domain_match("x.y.com", "x.Y.com"))
639 self.assertTrue(domain_match("x.y.com", ".Y.com"))
640 self.assertTrue(not domain_match("x.y.com", "Y.com"))
641 self.assertTrue(domain_match("a.b.c.com", ".c.com"))
642 self.assertTrue(not domain_match(".c.com", "a.b.c.com"))
643 self.assertTrue(domain_match("example.local", ".local"))
644 self.assertTrue(not domain_match("blah.blah", ""))
645 self.assertTrue(not domain_match("", ".rhubarb.rhubarb"))
646 self.assertTrue(domain_match("", ""))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000647
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000648 self.assertTrue(user_domain_match("acme.com", "acme.com"))
649 self.assertTrue(not user_domain_match("acme.com", ".acme.com"))
650 self.assertTrue(user_domain_match("rhubarb.acme.com", ".acme.com"))
651 self.assertTrue(user_domain_match("www.rhubarb.acme.com", ".acme.com"))
652 self.assertTrue(user_domain_match("x.y.com", "x.Y.com"))
653 self.assertTrue(user_domain_match("x.y.com", ".Y.com"))
654 self.assertTrue(not user_domain_match("x.y.com", "Y.com"))
655 self.assertTrue(user_domain_match("y.com", "Y.com"))
656 self.assertTrue(not user_domain_match(".y.com", "Y.com"))
657 self.assertTrue(user_domain_match(".y.com", ".Y.com"))
658 self.assertTrue(user_domain_match("x.y.com", ".com"))
659 self.assertTrue(not user_domain_match("x.y.com", "com"))
660 self.assertTrue(not user_domain_match("x.y.com", "m"))
661 self.assertTrue(not user_domain_match("x.y.com", ".m"))
662 self.assertTrue(not user_domain_match("x.y.com", ""))
663 self.assertTrue(not user_domain_match("x.y.com", "."))
664 self.assertTrue(user_domain_match("192.168.1.1", "192.168.1.1"))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000665 # not both HDNs, so must string-compare equal to match
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000666 self.assertTrue(not user_domain_match("192.168.1.1", ".168.1.1"))
667 self.assertTrue(not user_domain_match("192.168.1.1", "."))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000668 # empty string is a special case
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000669 self.assertTrue(not user_domain_match("192.168.1.1", ""))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000670
671 def test_wrong_domain(self):
672 # Cookies whose effective request-host name does not domain-match the
673 # domain are rejected.
674
675 # XXX far from complete
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000676 c = CookieJar()
677 interact_2965(c, "http://www.nasty.com/",
678 'foo=bar; domain=friendly.org; Version="1"')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000679 self.assertEqual(len(c), 0)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000680
Thomas Wouters477c8d52006-05-27 19:21:47 +0000681 def test_strict_domain(self):
682 # Cookies whose domain is a country-code tld like .co.uk should
683 # not be set if CookiePolicy.strict_domain is true.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000684 cp = DefaultCookiePolicy(strict_domain=True)
685 cj = CookieJar(policy=cp)
686 interact_netscape(cj, "http://example.co.uk/", 'no=problemo')
687 interact_netscape(cj, "http://example.co.uk/",
688 'okey=dokey; Domain=.example.co.uk')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000689 self.assertEqual(len(cj), 2)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000690 for pseudo_tld in [".co.uk", ".org.za", ".tx.us", ".name.us"]:
691 interact_netscape(cj, "http://example.%s/" % pseudo_tld,
692 'spam=eggs; Domain=.co.uk')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000693 self.assertEqual(len(cj), 2)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000694
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000695 def test_two_component_domain_ns(self):
696 # Netscape: .www.bar.com, www.bar.com, .bar.com, bar.com, no domain
697 # should all get accepted, as should .acme.com, acme.com and no domain
698 # for 2-component domains like acme.com.
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000699 c = CookieJar()
700
701 # two-component V0 domain is OK
702 interact_netscape(c, "http://foo.net/", 'ns=bar')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000703 self.assertEqual(len(c), 1)
704 self.assertEqual(c._cookies["foo.net"]["/"]["ns"].value, "bar")
705 self.assertEqual(interact_netscape(c, "http://foo.net/"), "ns=bar")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000706 # *will* be returned to any other domain (unlike RFC 2965)...
Ezio Melottib3aedd42010-11-20 19:04:17 +0000707 self.assertEqual(interact_netscape(c, "http://www.foo.net/"),
708 "ns=bar")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000709 # ...unless requested otherwise
710 pol = DefaultCookiePolicy(
711 strict_ns_domain=DefaultCookiePolicy.DomainStrictNonDomain)
712 c.set_policy(pol)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000713 self.assertEqual(interact_netscape(c, "http://www.foo.net/"), "")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000714
715 # unlike RFC 2965, even explicit two-component domain is OK,
716 # because .foo.net matches foo.net
717 interact_netscape(c, "http://foo.net/foo/",
718 'spam1=eggs; domain=foo.net')
719 # even if starts with a dot -- in NS rules, .foo.net matches foo.net!
720 interact_netscape(c, "http://foo.net/foo/bar/",
721 'spam2=eggs; domain=.foo.net')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000722 self.assertEqual(len(c), 3)
723 self.assertEqual(c._cookies[".foo.net"]["/foo"]["spam1"].value,
724 "eggs")
725 self.assertEqual(c._cookies[".foo.net"]["/foo/bar"]["spam2"].value,
726 "eggs")
727 self.assertEqual(interact_netscape(c, "http://foo.net/foo/bar/"),
728 "spam2=eggs; spam1=eggs; ns=bar")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000729
730 # top-level domain is too general
731 interact_netscape(c, "http://foo.net/", 'nini="ni"; domain=.net')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000732 self.assertEqual(len(c), 3)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000733
734## # Netscape protocol doesn't allow non-special top level domains (such
735## # as co.uk) in the domain attribute unless there are at least three
736## # dots in it.
737 # Oh yes it does! Real implementations don't check this, and real
738 # cookies (of course) rely on that behaviour.
739 interact_netscape(c, "http://foo.co.uk", 'nasty=trick; domain=.co.uk')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000740## self.assertEqual(len(c), 2)
741 self.assertEqual(len(c), 4)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000742
743 def test_two_component_domain_rfc2965(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000744 pol = DefaultCookiePolicy(rfc2965=True)
745 c = CookieJar(pol)
746
747 # two-component V1 domain is OK
748 interact_2965(c, "http://foo.net/", 'foo=bar; Version="1"')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000749 self.assertEqual(len(c), 1)
750 self.assertEqual(c._cookies["foo.net"]["/"]["foo"].value, "bar")
751 self.assertEqual(interact_2965(c, "http://foo.net/"),
752 "$Version=1; foo=bar")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000753 # won't be returned to any other domain (because domain was implied)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000754 self.assertEqual(interact_2965(c, "http://www.foo.net/"), "")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000755
756 # unless domain is given explicitly, because then it must be
757 # rewritten to start with a dot: foo.net --> .foo.net, which does
758 # not domain-match foo.net
759 interact_2965(c, "http://foo.net/foo",
760 'spam=eggs; domain=foo.net; path=/foo; Version="1"')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000761 self.assertEqual(len(c), 1)
762 self.assertEqual(interact_2965(c, "http://foo.net/foo"),
763 "$Version=1; foo=bar")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000764
765 # explicit foo.net from three-component domain www.foo.net *does* get
766 # set, because .foo.net domain-matches .foo.net
767 interact_2965(c, "http://www.foo.net/foo/",
768 'spam=eggs; domain=foo.net; Version="1"')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000769 self.assertEqual(c._cookies[".foo.net"]["/foo/"]["spam"].value,
770 "eggs")
771 self.assertEqual(len(c), 2)
772 self.assertEqual(interact_2965(c, "http://foo.net/foo/"),
773 "$Version=1; foo=bar")
774 self.assertEqual(interact_2965(c, "http://www.foo.net/foo/"),
775 '$Version=1; spam=eggs; $Domain="foo.net"')
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000776
777 # top-level domain is too general
778 interact_2965(c, "http://foo.net/",
779 'ni="ni"; domain=".net"; Version="1"')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000780 self.assertEqual(len(c), 2)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000781
782 # RFC 2965 doesn't require blocking this
783 interact_2965(c, "http://foo.co.uk/",
784 'nasty=trick; domain=.co.uk; Version="1"')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000785 self.assertEqual(len(c), 3)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000786
787 def test_domain_allow(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000788 c = CookieJar(policy=DefaultCookiePolicy(
789 blocked_domains=["acme.com"],
790 allowed_domains=["www.acme.com"]))
791
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000792 req = urllib.request.Request("http://acme.com/")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000793 headers = ["Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/"]
794 res = FakeResponse(headers, "http://acme.com/")
795 c.extract_cookies(res, req)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000796 self.assertEqual(len(c), 0)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000797
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000798 req = urllib.request.Request("http://www.acme.com/")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000799 res = FakeResponse(headers, "http://www.acme.com/")
800 c.extract_cookies(res, req)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000801 self.assertEqual(len(c), 1)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000802
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000803 req = urllib.request.Request("http://www.coyote.com/")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000804 res = FakeResponse(headers, "http://www.coyote.com/")
805 c.extract_cookies(res, req)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000806 self.assertEqual(len(c), 1)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000807
808 # set a cookie with non-allowed domain...
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000809 req = urllib.request.Request("http://www.coyote.com/")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000810 res = FakeResponse(headers, "http://www.coyote.com/")
811 cookies = c.make_cookies(res, req)
812 c.set_cookie(cookies[0])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000813 self.assertEqual(len(c), 2)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000814 # ... and check is doesn't get returned
815 c.add_cookie_header(req)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000816 self.assertTrue(not req.has_header("Cookie"))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000817
818 def test_domain_block(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000819 pol = DefaultCookiePolicy(
820 rfc2965=True, blocked_domains=[".acme.com"])
821 c = CookieJar(policy=pol)
822 headers = ["Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/"]
823
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000824 req = urllib.request.Request("http://www.acme.com/")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000825 res = FakeResponse(headers, "http://www.acme.com/")
826 c.extract_cookies(res, req)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000827 self.assertEqual(len(c), 0)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000828
829 p = pol.set_blocked_domains(["acme.com"])
830 c.extract_cookies(res, req)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000831 self.assertEqual(len(c), 1)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000832
833 c.clear()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000834 req = urllib.request.Request("http://www.roadrunner.net/")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000835 res = FakeResponse(headers, "http://www.roadrunner.net/")
836 c.extract_cookies(res, req)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000837 self.assertEqual(len(c), 1)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000838 req = urllib.request.Request("http://www.roadrunner.net/")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000839 c.add_cookie_header(req)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000840 self.assertTrue((req.has_header("Cookie") and
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000841 req.has_header("Cookie2")))
842
843 c.clear()
844 pol.set_blocked_domains([".acme.com"])
845 c.extract_cookies(res, req)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000846 self.assertEqual(len(c), 1)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000847
848 # set a cookie with blocked domain...
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000849 req = urllib.request.Request("http://www.acme.com/")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000850 res = FakeResponse(headers, "http://www.acme.com/")
851 cookies = c.make_cookies(res, req)
852 c.set_cookie(cookies[0])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000853 self.assertEqual(len(c), 2)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000854 # ... and check is doesn't get returned
855 c.add_cookie_header(req)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000856 self.assertTrue(not req.has_header("Cookie"))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000857
858 def test_secure(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000859 for ns in True, False:
860 for whitespace in " ", "":
861 c = CookieJar()
862 if ns:
863 pol = DefaultCookiePolicy(rfc2965=False)
864 int = interact_netscape
865 vs = ""
866 else:
867 pol = DefaultCookiePolicy(rfc2965=True)
868 int = interact_2965
869 vs = "; Version=1"
870 c.set_policy(pol)
871 url = "http://www.acme.com/"
872 int(c, url, "foo1=bar%s%s" % (vs, whitespace))
873 int(c, url, "foo2=bar%s; secure%s" % (vs, whitespace))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000874 self.assertTrue(
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000875 not c._cookies["www.acme.com"]["/"]["foo1"].secure,
876 "non-secure cookie registered secure")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000877 self.assertTrue(
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000878 c._cookies["www.acme.com"]["/"]["foo2"].secure,
879 "secure cookie registered non-secure")
880
881 def test_quote_cookie_value(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000882 c = CookieJar(policy=DefaultCookiePolicy(rfc2965=True))
883 interact_2965(c, "http://www.acme.com/", r'foo=\b"a"r; Version=1')
884 h = interact_2965(c, "http://www.acme.com/")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000885 self.assertEqual(h, r'$Version=1; foo=\\b\"a\"r')
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000886
887 def test_missing_final_slash(self):
888 # Missing slash from request URL's abs_path should be assumed present.
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000889 url = "http://www.acme.com"
890 c = CookieJar(DefaultCookiePolicy(rfc2965=True))
891 interact_2965(c, url, "foo=bar; Version=1")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000892 req = urllib.request.Request(url)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000893 self.assertEqual(len(c), 1)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000894 c.add_cookie_header(req)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000895 self.assertTrue(req.has_header("Cookie"))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000896
897 def test_domain_mirror(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000898 pol = DefaultCookiePolicy(rfc2965=True)
899
900 c = CookieJar(pol)
901 url = "http://foo.bar.com/"
902 interact_2965(c, url, "spam=eggs; Version=1")
903 h = interact_2965(c, url)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000904 self.assertNotIn("Domain", h,
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000905 "absent domain returned with domain present")
906
907 c = CookieJar(pol)
908 url = "http://foo.bar.com/"
909 interact_2965(c, url, 'spam=eggs; Version=1; Domain=.bar.com')
910 h = interact_2965(c, url)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000911 self.assertIn('$Domain=".bar.com"', h, "domain not returned")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000912
913 c = CookieJar(pol)
914 url = "http://foo.bar.com/"
915 # note missing initial dot in Domain
916 interact_2965(c, url, 'spam=eggs; Version=1; Domain=bar.com')
917 h = interact_2965(c, url)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000918 self.assertIn('$Domain="bar.com"', h, "domain not returned")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000919
920 def test_path_mirror(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000921 pol = DefaultCookiePolicy(rfc2965=True)
922
923 c = CookieJar(pol)
924 url = "http://foo.bar.com/"
925 interact_2965(c, url, "spam=eggs; Version=1")
926 h = interact_2965(c, url)
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000927 self.assertNotIn("Path", h, "absent path returned with path present")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000928
929 c = CookieJar(pol)
930 url = "http://foo.bar.com/"
931 interact_2965(c, url, 'spam=eggs; Version=1; Path=/')
932 h = interact_2965(c, url)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000933 self.assertIn('$Path="/"', h, "path not returned")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000934
935 def test_port_mirror(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000936 pol = DefaultCookiePolicy(rfc2965=True)
937
938 c = CookieJar(pol)
939 url = "http://foo.bar.com/"
940 interact_2965(c, url, "spam=eggs; Version=1")
941 h = interact_2965(c, url)
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000942 self.assertNotIn("Port", h, "absent port returned with port present")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000943
944 c = CookieJar(pol)
945 url = "http://foo.bar.com/"
946 interact_2965(c, url, "spam=eggs; Version=1; Port")
947 h = interact_2965(c, url)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000948 self.assertTrue(re.search("\$Port([^=]|$)", h),
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000949 "port with no value not returned with no value")
950
951 c = CookieJar(pol)
952 url = "http://foo.bar.com/"
953 interact_2965(c, url, 'spam=eggs; Version=1; Port="80"')
954 h = interact_2965(c, url)
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000955 self.assertIn('$Port="80"', h,
956 "port with single value not returned with single value")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000957
958 c = CookieJar(pol)
959 url = "http://foo.bar.com/"
960 interact_2965(c, url, 'spam=eggs; Version=1; Port="80,8080"')
961 h = interact_2965(c, url)
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000962 self.assertIn('$Port="80,8080"', h,
963 "port with multiple values not returned with multiple "
964 "values")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000965
966 def test_no_return_comment(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000967 c = CookieJar(DefaultCookiePolicy(rfc2965=True))
968 url = "http://foo.bar.com/"
969 interact_2965(c, url, 'spam=eggs; Version=1; '
970 'Comment="does anybody read these?"; '
971 'CommentURL="http://foo.bar.net/comment.html"')
972 h = interact_2965(c, url)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000973 self.assertTrue(
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000974 "Comment" not in h,
975 "Comment or CommentURL cookie-attributes returned to server")
976
977 def test_Cookie_iterator(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000978 cs = CookieJar(DefaultCookiePolicy(rfc2965=True))
979 # add some random cookies
980 interact_2965(cs, "http://blah.spam.org/", 'foo=eggs; Version=1; '
981 'Comment="does anybody read these?"; '
982 'CommentURL="http://foo.bar.net/comment.html"')
983 interact_netscape(cs, "http://www.acme.com/blah/", "spam=bar; secure")
984 interact_2965(cs, "http://www.acme.com/blah/",
985 "foo=bar; secure; Version=1")
986 interact_2965(cs, "http://www.acme.com/blah/",
987 "foo=bar; path=/; Version=1")
988 interact_2965(cs, "http://www.sol.no",
989 r'bang=wallop; version=1; domain=".sol.no"; '
990 r'port="90,100, 80,8080"; '
991 r'max-age=100; Comment = "Just kidding! (\"|\\\\) "')
992
993 versions = [1, 1, 1, 0, 1]
994 names = ["bang", "foo", "foo", "spam", "foo"]
995 domains = [".sol.no", "blah.spam.org", "www.acme.com",
996 "www.acme.com", "www.acme.com"]
997 paths = ["/", "/", "/", "/blah", "/blah/"]
998
999 for i in range(4):
1000 i = 0
1001 for c in cs:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001002 self.assertTrue(isinstance(c, Cookie))
Ezio Melottib3aedd42010-11-20 19:04:17 +00001003 self.assertEqual(c.version, versions[i])
1004 self.assertEqual(c.name, names[i])
1005 self.assertEqual(c.domain, domains[i])
1006 self.assertEqual(c.path, paths[i])
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001007 i = i + 1
1008
1009 def test_parse_ns_headers(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001010 # missing domain value (invalid cookie)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001011 self.assertEqual(
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001012 parse_ns_headers(["foo=bar; path=/; domain"]),
1013 [[("foo", "bar"),
1014 ("path", "/"), ("domain", None), ("version", "0")]]
1015 )
1016 # invalid expires value
Ezio Melottib3aedd42010-11-20 19:04:17 +00001017 self.assertEqual(
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001018 parse_ns_headers(["foo=bar; expires=Foo Bar 12 33:22:11 2000"]),
1019 [[("foo", "bar"), ("expires", None), ("version", "0")]]
1020 )
1021 # missing cookie value (valid cookie)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001022 self.assertEqual(
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001023 parse_ns_headers(["foo"]),
1024 [[("foo", None), ("version", "0")]]
1025 )
1026 # shouldn't add version if header is empty
Ezio Melottib3aedd42010-11-20 19:04:17 +00001027 self.assertEqual(parse_ns_headers([""]), [])
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001028
1029 def test_bad_cookie_header(self):
1030
1031 def cookiejar_from_cookie_headers(headers):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001032 c = CookieJar()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001033 req = urllib.request.Request("http://www.example.com/")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001034 r = FakeResponse(headers, "http://www.example.com/")
1035 c.extract_cookies(r, req)
1036 return c
1037
1038 # none of these bad headers should cause an exception to be raised
1039 for headers in [
1040 ["Set-Cookie: "], # actually, nothing wrong with this
1041 ["Set-Cookie2: "], # ditto
1042 # missing domain value
1043 ["Set-Cookie2: a=foo; path=/; Version=1; domain"],
1044 # bad max-age
1045 ["Set-Cookie: b=foo; max-age=oops"],
Benjamin Peterson3e5cd1d2010-06-27 21:45:24 +00001046 # bad version
1047 ["Set-Cookie: b=foo; version=spam"],
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001048 ]:
1049 c = cookiejar_from_cookie_headers(headers)
1050 # these bad cookies shouldn't be set
Ezio Melottib3aedd42010-11-20 19:04:17 +00001051 self.assertEqual(len(c), 0)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001052
1053 # cookie with invalid expires is treated as session cookie
1054 headers = ["Set-Cookie: c=foo; expires=Foo Bar 12 33:22:11 2000"]
1055 c = cookiejar_from_cookie_headers(headers)
1056 cookie = c._cookies["www.example.com"]["/"]["c"]
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001057 self.assertTrue(cookie.expires is None)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001058
1059
Gregory P. Smith41e6c3d2010-07-19 23:17:22 +00001060class LWPCookieTests(unittest.TestCase):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001061 # Tests taken from libwww-perl, with a few modifications and additions.
1062
1063 def test_netscape_example_1(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001064 #-------------------------------------------------------------------
1065 # First we check that it works for the original example at
1066 # http://www.netscape.com/newsref/std/cookie_spec.html
1067
1068 # Client requests a document, and receives in the response:
1069 #
1070 # Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/; expires=Wednesday, 09-Nov-99 23:12:40 GMT
1071 #
1072 # When client requests a URL in path "/" on this server, it sends:
1073 #
1074 # Cookie: CUSTOMER=WILE_E_COYOTE
1075 #
1076 # Client requests a document, and receives in the response:
1077 #
1078 # Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/
1079 #
1080 # When client requests a URL in path "/" on this server, it sends:
1081 #
1082 # Cookie: CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001
1083 #
1084 # Client receives:
1085 #
1086 # Set-Cookie: SHIPPING=FEDEX; path=/fo
1087 #
1088 # When client requests a URL in path "/" on this server, it sends:
1089 #
1090 # Cookie: CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001
1091 #
1092 # When client requests a URL in path "/foo" on this server, it sends:
1093 #
1094 # Cookie: CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001; SHIPPING=FEDEX
1095 #
1096 # The last Cookie is buggy, because both specifications say that the
1097 # most specific cookie must be sent first. SHIPPING=FEDEX is the
1098 # most specific and should thus be first.
1099
1100 year_plus_one = time.localtime()[0] + 1
1101
1102 headers = []
1103
1104 c = CookieJar(DefaultCookiePolicy(rfc2965 = True))
1105
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001106 #req = urllib.request.Request("http://1.1.1.1/",
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001107 # headers={"Host": "www.acme.com:80"})
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001108 req = urllib.request.Request("http://www.acme.com:80/",
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001109 headers={"Host": "www.acme.com:80"})
1110
1111 headers.append(
1112 "Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/ ; "
1113 "expires=Wednesday, 09-Nov-%d 23:12:40 GMT" % year_plus_one)
1114 res = FakeResponse(headers, "http://www.acme.com/")
1115 c.extract_cookies(res, req)
1116
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001117 req = urllib.request.Request("http://www.acme.com/")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001118 c.add_cookie_header(req)
1119
1120 self.assertEqual(req.get_header("Cookie"), "CUSTOMER=WILE_E_COYOTE")
1121 self.assertEqual(req.get_header("Cookie2"), '$Version="1"')
1122
1123 headers.append("Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/")
1124 res = FakeResponse(headers, "http://www.acme.com/")
1125 c.extract_cookies(res, req)
1126
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001127 req = urllib.request.Request("http://www.acme.com/foo/bar")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001128 c.add_cookie_header(req)
1129
1130 h = req.get_header("Cookie")
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001131 self.assertIn("PART_NUMBER=ROCKET_LAUNCHER_0001", h)
1132 self.assertIn("CUSTOMER=WILE_E_COYOTE", h)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001133
1134 headers.append('Set-Cookie: SHIPPING=FEDEX; path=/foo')
1135 res = FakeResponse(headers, "http://www.acme.com")
1136 c.extract_cookies(res, req)
1137
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001138 req = urllib.request.Request("http://www.acme.com/")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001139 c.add_cookie_header(req)
1140
1141 h = req.get_header("Cookie")
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001142 self.assertIn("PART_NUMBER=ROCKET_LAUNCHER_0001", h)
1143 self.assertIn("CUSTOMER=WILE_E_COYOTE", h)
1144 self.assertNotIn("SHIPPING=FEDEX", h)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001145
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001146 req = urllib.request.Request("http://www.acme.com/foo/")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001147 c.add_cookie_header(req)
1148
1149 h = req.get_header("Cookie")
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001150 self.assertIn("PART_NUMBER=ROCKET_LAUNCHER_0001", h)
1151 self.assertIn("CUSTOMER=WILE_E_COYOTE", h)
1152 self.assertTrue(h.startswith("SHIPPING=FEDEX;"))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001153
1154 def test_netscape_example_2(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001155 # Second Example transaction sequence:
1156 #
1157 # Assume all mappings from above have been cleared.
1158 #
1159 # Client receives:
1160 #
1161 # Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/
1162 #
1163 # When client requests a URL in path "/" on this server, it sends:
1164 #
1165 # Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001
1166 #
1167 # Client receives:
1168 #
1169 # Set-Cookie: PART_NUMBER=RIDING_ROCKET_0023; path=/ammo
1170 #
1171 # When client requests a URL in path "/ammo" on this server, it sends:
1172 #
1173 # Cookie: PART_NUMBER=RIDING_ROCKET_0023; PART_NUMBER=ROCKET_LAUNCHER_0001
1174 #
1175 # NOTE: There are two name/value pairs named "PART_NUMBER" due to
1176 # the inheritance of the "/" mapping in addition to the "/ammo" mapping.
1177
1178 c = CookieJar()
1179 headers = []
1180
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001181 req = urllib.request.Request("http://www.acme.com/")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001182 headers.append("Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/")
1183 res = FakeResponse(headers, "http://www.acme.com/")
1184
1185 c.extract_cookies(res, req)
1186
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001187 req = urllib.request.Request("http://www.acme.com/")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001188 c.add_cookie_header(req)
1189
Ezio Melottib3aedd42010-11-20 19:04:17 +00001190 self.assertEqual(req.get_header("Cookie"),
1191 "PART_NUMBER=ROCKET_LAUNCHER_0001")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001192
1193 headers.append(
1194 "Set-Cookie: PART_NUMBER=RIDING_ROCKET_0023; path=/ammo")
1195 res = FakeResponse(headers, "http://www.acme.com/")
1196 c.extract_cookies(res, req)
1197
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001198 req = urllib.request.Request("http://www.acme.com/ammo")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001199 c.add_cookie_header(req)
1200
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001201 self.assertTrue(re.search(r"PART_NUMBER=RIDING_ROCKET_0023;\s*"
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001202 "PART_NUMBER=ROCKET_LAUNCHER_0001",
1203 req.get_header("Cookie")))
1204
1205 def test_ietf_example_1(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001206 #-------------------------------------------------------------------
1207 # Then we test with the examples from draft-ietf-http-state-man-mec-03.txt
1208 #
1209 # 5. EXAMPLES
1210
1211 c = CookieJar(DefaultCookiePolicy(rfc2965=True))
1212
1213 #
1214 # 5.1 Example 1
1215 #
1216 # Most detail of request and response headers has been omitted. Assume
1217 # the user agent has no stored cookies.
1218 #
1219 # 1. User Agent -> Server
1220 #
1221 # POST /acme/login HTTP/1.1
1222 # [form data]
1223 #
1224 # User identifies self via a form.
1225 #
1226 # 2. Server -> User Agent
1227 #
1228 # HTTP/1.1 200 OK
1229 # Set-Cookie2: Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"
1230 #
1231 # Cookie reflects user's identity.
1232
1233 cookie = interact_2965(
1234 c, 'http://www.acme.com/acme/login',
1235 'Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001236 self.assertTrue(not cookie)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001237
1238 #
1239 # 3. User Agent -> Server
1240 #
1241 # POST /acme/pickitem HTTP/1.1
1242 # Cookie: $Version="1"; Customer="WILE_E_COYOTE"; $Path="/acme"
1243 # [form data]
1244 #
1245 # User selects an item for ``shopping basket.''
1246 #
1247 # 4. Server -> User Agent
1248 #
1249 # HTTP/1.1 200 OK
1250 # Set-Cookie2: Part_Number="Rocket_Launcher_0001"; Version="1";
1251 # Path="/acme"
1252 #
1253 # Shopping basket contains an item.
1254
1255 cookie = interact_2965(c, 'http://www.acme.com/acme/pickitem',
1256 'Part_Number="Rocket_Launcher_0001"; '
1257 'Version="1"; Path="/acme"');
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001258 self.assertTrue(re.search(
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001259 r'^\$Version="?1"?; Customer="?WILE_E_COYOTE"?; \$Path="/acme"$',
1260 cookie))
1261
1262 #
1263 # 5. User Agent -> Server
1264 #
1265 # POST /acme/shipping HTTP/1.1
1266 # Cookie: $Version="1";
1267 # Customer="WILE_E_COYOTE"; $Path="/acme";
1268 # Part_Number="Rocket_Launcher_0001"; $Path="/acme"
1269 # [form data]
1270 #
1271 # User selects shipping method from form.
1272 #
1273 # 6. Server -> User Agent
1274 #
1275 # HTTP/1.1 200 OK
1276 # Set-Cookie2: Shipping="FedEx"; Version="1"; Path="/acme"
1277 #
1278 # New cookie reflects shipping method.
1279
1280 cookie = interact_2965(c, "http://www.acme.com/acme/shipping",
1281 'Shipping="FedEx"; Version="1"; Path="/acme"')
1282
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001283 self.assertTrue(re.search(r'^\$Version="?1"?;', cookie))
1284 self.assertTrue(re.search(r'Part_Number="?Rocket_Launcher_0001"?;'
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001285 '\s*\$Path="\/acme"', cookie))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001286 self.assertTrue(re.search(r'Customer="?WILE_E_COYOTE"?;\s*\$Path="\/acme"',
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001287 cookie))
1288
1289 #
1290 # 7. User Agent -> Server
1291 #
1292 # POST /acme/process HTTP/1.1
1293 # Cookie: $Version="1";
1294 # Customer="WILE_E_COYOTE"; $Path="/acme";
1295 # Part_Number="Rocket_Launcher_0001"; $Path="/acme";
1296 # Shipping="FedEx"; $Path="/acme"
1297 # [form data]
1298 #
1299 # User chooses to process order.
1300 #
1301 # 8. Server -> User Agent
1302 #
1303 # HTTP/1.1 200 OK
1304 #
1305 # Transaction is complete.
1306
1307 cookie = interact_2965(c, "http://www.acme.com/acme/process")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001308 self.assertTrue(
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001309 re.search(r'Shipping="?FedEx"?;\s*\$Path="\/acme"', cookie) and
1310 "WILE_E_COYOTE" in cookie)
1311
1312 #
1313 # The user agent makes a series of requests on the origin server, after
1314 # each of which it receives a new cookie. All the cookies have the same
1315 # Path attribute and (default) domain. Because the request URLs all have
1316 # /acme as a prefix, and that matches the Path attribute, each request
1317 # contains all the cookies received so far.
1318
1319 def test_ietf_example_2(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001320 # 5.2 Example 2
1321 #
1322 # This example illustrates the effect of the Path attribute. All detail
1323 # of request and response headers has been omitted. Assume the user agent
1324 # has no stored cookies.
1325
1326 c = CookieJar(DefaultCookiePolicy(rfc2965=True))
1327
1328 # Imagine the user agent has received, in response to earlier requests,
1329 # the response headers
1330 #
1331 # Set-Cookie2: Part_Number="Rocket_Launcher_0001"; Version="1";
1332 # Path="/acme"
1333 #
1334 # and
1335 #
1336 # Set-Cookie2: Part_Number="Riding_Rocket_0023"; Version="1";
1337 # Path="/acme/ammo"
1338
1339 interact_2965(
1340 c, "http://www.acme.com/acme/ammo/specific",
1341 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"',
1342 'Part_Number="Riding_Rocket_0023"; Version="1"; Path="/acme/ammo"')
1343
1344 # A subsequent request by the user agent to the (same) server for URLs of
1345 # the form /acme/ammo/... would include the following request header:
1346 #
1347 # Cookie: $Version="1";
1348 # Part_Number="Riding_Rocket_0023"; $Path="/acme/ammo";
1349 # Part_Number="Rocket_Launcher_0001"; $Path="/acme"
1350 #
1351 # Note that the NAME=VALUE pair for the cookie with the more specific Path
1352 # attribute, /acme/ammo, comes before the one with the less specific Path
1353 # attribute, /acme. Further note that the same cookie name appears more
1354 # than once.
1355
1356 cookie = interact_2965(c, "http://www.acme.com/acme/ammo/...")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001357 self.assertTrue(
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001358 re.search(r"Riding_Rocket_0023.*Rocket_Launcher_0001", cookie))
1359
1360 # A subsequent request by the user agent to the (same) server for a URL of
1361 # the form /acme/parts/ would include the following request header:
1362 #
1363 # Cookie: $Version="1"; Part_Number="Rocket_Launcher_0001"; $Path="/acme"
1364 #
1365 # Here, the second cookie's Path attribute /acme/ammo is not a prefix of
1366 # the request URL, /acme/parts/, so the cookie does not get forwarded to
1367 # the server.
1368
1369 cookie = interact_2965(c, "http://www.acme.com/acme/parts/")
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001370 self.assertIn("Rocket_Launcher_0001", cookie)
1371 self.assertNotIn("Riding_Rocket_0023", cookie)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001372
1373 def test_rejection(self):
1374 # Test rejection of Set-Cookie2 responses based on domain, path, port.
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001375 pol = DefaultCookiePolicy(rfc2965=True)
1376
1377 c = LWPCookieJar(policy=pol)
1378
1379 max_age = "max-age=3600"
1380
1381 # illegal domain (no embedded dots)
1382 cookie = interact_2965(c, "http://www.acme.com",
1383 'foo=bar; domain=".com"; version=1')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001384 self.assertTrue(not c)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001385
1386 # legal domain
1387 cookie = interact_2965(c, "http://www.acme.com",
1388 'ping=pong; domain="acme.com"; version=1')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001389 self.assertEqual(len(c), 1)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001390
1391 # illegal domain (host prefix "www.a" contains a dot)
1392 cookie = interact_2965(c, "http://www.a.acme.com",
1393 'whiz=bang; domain="acme.com"; version=1')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001394 self.assertEqual(len(c), 1)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001395
1396 # legal domain
1397 cookie = interact_2965(c, "http://www.a.acme.com",
1398 'wow=flutter; domain=".a.acme.com"; version=1')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001399 self.assertEqual(len(c), 2)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001400
1401 # can't partially match an IP-address
1402 cookie = interact_2965(c, "http://125.125.125.125",
1403 'zzzz=ping; domain="125.125.125"; version=1')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001404 self.assertEqual(len(c), 2)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001405
1406 # illegal path (must be prefix of request path)
1407 cookie = interact_2965(c, "http://www.sol.no",
1408 'blah=rhubarb; domain=".sol.no"; path="/foo"; '
1409 'version=1')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001410 self.assertEqual(len(c), 2)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001411
1412 # legal path
1413 cookie = interact_2965(c, "http://www.sol.no/foo/bar",
1414 'bing=bong; domain=".sol.no"; path="/foo"; '
1415 'version=1')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001416 self.assertEqual(len(c), 3)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001417
1418 # illegal port (request-port not in list)
1419 cookie = interact_2965(c, "http://www.sol.no",
1420 'whiz=ffft; domain=".sol.no"; port="90,100"; '
1421 'version=1')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001422 self.assertEqual(len(c), 3)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001423
1424 # legal port
1425 cookie = interact_2965(
1426 c, "http://www.sol.no",
1427 r'bang=wallop; version=1; domain=".sol.no"; '
1428 r'port="90,100, 80,8080"; '
1429 r'max-age=100; Comment = "Just kidding! (\"|\\\\) "')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001430 self.assertEqual(len(c), 4)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001431
1432 # port attribute without any value (current port)
1433 cookie = interact_2965(c, "http://www.sol.no",
1434 'foo9=bar; version=1; domain=".sol.no"; port; '
1435 'max-age=100;')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001436 self.assertEqual(len(c), 5)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001437
1438 # encoded path
1439 # LWP has this test, but unescaping allowed path characters seems
1440 # like a bad idea, so I think this should fail:
1441## cookie = interact_2965(c, "http://www.sol.no/foo/",
1442## r'foo8=bar; version=1; path="/%66oo"')
1443 # but this is OK, because '<' is not an allowed HTTP URL path
1444 # character:
1445 cookie = interact_2965(c, "http://www.sol.no/<oo/",
1446 r'foo8=bar; version=1; path="/%3coo"')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001447 self.assertEqual(len(c), 6)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001448
1449 # save and restore
Gregory P. Smith41e6c3d2010-07-19 23:17:22 +00001450 filename = test.support.TESTFN
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001451
1452 try:
1453 c.save(filename, ignore_discard=True)
1454 old = repr(c)
1455
1456 c = LWPCookieJar(policy=pol)
1457 c.load(filename, ignore_discard=True)
1458 finally:
1459 try: os.unlink(filename)
1460 except OSError: pass
1461
Ezio Melottib3aedd42010-11-20 19:04:17 +00001462 self.assertEqual(old, repr(c))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001463
1464 def test_url_encoding(self):
1465 # Try some URL encodings of the PATHs.
1466 # (the behaviour here has changed from libwww-perl)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001467 c = CookieJar(DefaultCookiePolicy(rfc2965=True))
Guido van Rossum52dbbb92008-08-18 21:44:30 +00001468 interact_2965(c, "http://www.acme.com/foo%2f%25/"
1469 "%3c%3c%0Anew%C3%A5/%C3%A5",
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001470 "foo = bar; version = 1")
1471
1472 cookie = interact_2965(
Guido van Rossumf520c052007-07-23 03:46:37 +00001473 c, "http://www.acme.com/foo%2f%25/<<%0anew\345/\346\370\345",
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001474 'bar=baz; path="/foo/"; version=1');
1475 version_re = re.compile(r'^\$version=\"?1\"?', re.I)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001476 self.assertIn("foo=bar", cookie)
1477 self.assertTrue(version_re.search(cookie))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001478
1479 cookie = interact_2965(
Guido van Rossumf520c052007-07-23 03:46:37 +00001480 c, "http://www.acme.com/foo/%25/<<%0anew\345/\346\370\345")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001481 self.assertTrue(not cookie)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001482
1483 # unicode URL doesn't raise exception
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001484 cookie = interact_2965(c, "http://www.acme.com/\xfc")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001485
1486 def test_mozilla(self):
1487 # Save / load Mozilla/Netscape cookie file format.
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001488 year_plus_one = time.localtime()[0] + 1
1489
Gregory P. Smith41e6c3d2010-07-19 23:17:22 +00001490 filename = test.support.TESTFN
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001491
1492 c = MozillaCookieJar(filename,
1493 policy=DefaultCookiePolicy(rfc2965=True))
1494 interact_2965(c, "http://www.acme.com/",
1495 "foo1=bar; max-age=100; Version=1")
1496 interact_2965(c, "http://www.acme.com/",
1497 'foo2=bar; port="80"; max-age=100; Discard; Version=1')
1498 interact_2965(c, "http://www.acme.com/", "foo3=bar; secure; Version=1")
1499
1500 expires = "expires=09-Nov-%d 23:12:40 GMT" % (year_plus_one,)
1501 interact_netscape(c, "http://www.foo.com/",
1502 "fooa=bar; %s" % expires)
1503 interact_netscape(c, "http://www.foo.com/",
1504 "foob=bar; Domain=.foo.com; %s" % expires)
1505 interact_netscape(c, "http://www.foo.com/",
1506 "fooc=bar; Domain=www.foo.com; %s" % expires)
1507
1508 def save_and_restore(cj, ignore_discard):
1509 try:
1510 cj.save(ignore_discard=ignore_discard)
1511 new_c = MozillaCookieJar(filename,
1512 DefaultCookiePolicy(rfc2965=True))
1513 new_c.load(ignore_discard=ignore_discard)
1514 finally:
1515 try: os.unlink(filename)
1516 except OSError: pass
1517 return new_c
1518
1519 new_c = save_and_restore(c, True)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001520 self.assertEqual(len(new_c), 6) # none discarded
Benjamin Peterson577473f2010-01-19 00:09:57 +00001521 self.assertIn("name='foo1', value='bar'", repr(new_c))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001522
1523 new_c = save_and_restore(c, False)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001524 self.assertEqual(len(new_c), 4) # 2 of them discarded on save
Benjamin Peterson577473f2010-01-19 00:09:57 +00001525 self.assertIn("name='foo1', value='bar'", repr(new_c))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001526
1527 def test_netscape_misc(self):
1528 # Some additional Netscape cookies tests.
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001529 c = CookieJar()
1530 headers = []
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001531 req = urllib.request.Request("http://foo.bar.acme.com/foo")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001532
1533 # Netscape allows a host part that contains dots
1534 headers.append("Set-Cookie: Customer=WILE_E_COYOTE; domain=.acme.com")
1535 res = FakeResponse(headers, "http://www.acme.com/foo")
1536 c.extract_cookies(res, req)
1537
1538 # and that the domain is the same as the host without adding a leading
1539 # dot to the domain. Should not quote even if strange chars are used
1540 # in the cookie value.
1541 headers.append("Set-Cookie: PART_NUMBER=3,4; domain=foo.bar.acme.com")
1542 res = FakeResponse(headers, "http://www.acme.com/foo")
1543 c.extract_cookies(res, req)
1544
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001545 req = urllib.request.Request("http://foo.bar.acme.com/foo")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001546 c.add_cookie_header(req)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001547 self.assertIn("PART_NUMBER=3,4", req.get_header("Cookie"))
1548 self.assertIn("Customer=WILE_E_COYOTE",req.get_header("Cookie"))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001549
1550 def test_intranet_domains_2965(self):
1551 # Test handling of local intranet hostnames without a dot.
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001552 c = CookieJar(DefaultCookiePolicy(rfc2965=True))
1553 interact_2965(c, "http://example/",
1554 "foo1=bar; PORT; Discard; Version=1;")
1555 cookie = interact_2965(c, "http://example/",
1556 'foo2=bar; domain=".local"; Version=1')
Benjamin Peterson577473f2010-01-19 00:09:57 +00001557 self.assertIn("foo1=bar", cookie)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001558
1559 interact_2965(c, "http://example/", 'foo3=bar; Version=1')
1560 cookie = interact_2965(c, "http://example/")
Benjamin Peterson577473f2010-01-19 00:09:57 +00001561 self.assertIn("foo2=bar", cookie)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001562 self.assertEqual(len(c), 3)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001563
1564 def test_intranet_domains_ns(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001565 c = CookieJar(DefaultCookiePolicy(rfc2965 = False))
1566 interact_netscape(c, "http://example/", "foo1=bar")
1567 cookie = interact_netscape(c, "http://example/",
1568 'foo2=bar; domain=.local')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001569 self.assertEqual(len(c), 2)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001570 self.assertIn("foo1=bar", cookie)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001571
1572 cookie = interact_netscape(c, "http://example/")
Benjamin Peterson577473f2010-01-19 00:09:57 +00001573 self.assertIn("foo2=bar", cookie)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001574 self.assertEqual(len(c), 2)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001575
1576 def test_empty_path(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001577 # Test for empty path
1578 # Broken web-server ORION/1.3.38 returns to the client response like
1579 #
1580 # Set-Cookie: JSESSIONID=ABCDERANDOM123; Path=
1581 #
1582 # ie. with Path set to nothing.
1583 # In this case, extract_cookies() must set cookie to / (root)
1584 c = CookieJar(DefaultCookiePolicy(rfc2965 = True))
1585 headers = []
1586
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001587 req = urllib.request.Request("http://www.ants.com/")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001588 headers.append("Set-Cookie: JSESSIONID=ABCDERANDOM123; Path=")
1589 res = FakeResponse(headers, "http://www.ants.com/")
1590 c.extract_cookies(res, req)
1591
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001592 req = urllib.request.Request("http://www.ants.com/")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001593 c.add_cookie_header(req)
1594
Ezio Melottib3aedd42010-11-20 19:04:17 +00001595 self.assertEqual(req.get_header("Cookie"),
1596 "JSESSIONID=ABCDERANDOM123")
1597 self.assertEqual(req.get_header("Cookie2"), '$Version="1"')
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001598
1599 # missing path in the request URI
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001600 req = urllib.request.Request("http://www.ants.com:8080")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001601 c.add_cookie_header(req)
1602
Ezio Melottib3aedd42010-11-20 19:04:17 +00001603 self.assertEqual(req.get_header("Cookie"),
1604 "JSESSIONID=ABCDERANDOM123")
1605 self.assertEqual(req.get_header("Cookie2"), '$Version="1"')
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001606
1607 def test_session_cookies(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001608 year_plus_one = time.localtime()[0] + 1
1609
1610 # Check session cookies are deleted properly by
1611 # CookieJar.clear_session_cookies method
1612
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001613 req = urllib.request.Request('http://www.perlmeister.com/scripts')
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001614 headers = []
1615 headers.append("Set-Cookie: s1=session;Path=/scripts")
1616 headers.append("Set-Cookie: p1=perm; Domain=.perlmeister.com;"
1617 "Path=/;expires=Fri, 02-Feb-%d 23:24:20 GMT" %
1618 year_plus_one)
1619 headers.append("Set-Cookie: p2=perm;Path=/;expires=Fri, "
1620 "02-Feb-%d 23:24:20 GMT" % year_plus_one)
1621 headers.append("Set-Cookie: s2=session;Path=/scripts;"
1622 "Domain=.perlmeister.com")
1623 headers.append('Set-Cookie2: s3=session;Version=1;Discard;Path="/"')
1624 res = FakeResponse(headers, 'http://www.perlmeister.com/scripts')
1625
1626 c = CookieJar()
1627 c.extract_cookies(res, req)
1628 # How many session/permanent cookies do we have?
1629 counter = {"session_after": 0,
1630 "perm_after": 0,
1631 "session_before": 0,
1632 "perm_before": 0}
1633 for cookie in c:
1634 key = "%s_before" % cookie.value
1635 counter[key] = counter[key] + 1
1636 c.clear_session_cookies()
1637 # How many now?
1638 for cookie in c:
1639 key = "%s_after" % cookie.value
1640 counter[key] = counter[key] + 1
1641
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001642 self.assertTrue(not (
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001643 # a permanent cookie got lost accidently
1644 counter["perm_after"] != counter["perm_before"] or
1645 # a session cookie hasn't been cleared
1646 counter["session_after"] != 0 or
1647 # we didn't have session cookies in the first place
1648 counter["session_before"] == 0))
1649
1650
1651def test_main(verbose=None):
Gregory P. Smith41e6c3d2010-07-19 23:17:22 +00001652 test.support.run_unittest(
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001653 DateTimeTests,
1654 HeaderTests,
1655 CookieTests,
Martin v. Löwisc5574e82005-03-03 10:57:37 +00001656 FileCookieJarTests,
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001657 LWPCookieTests,
1658 )
1659
1660if __name__ == "__main__":
1661 test_main(verbose=True)