ยปCore Development>Code coverage>Lib/test/test_http_cookiejar.py

Python code coverage for Lib/test/test_http_cookiejar.py

#countcontent
1n/a"""Tests for http/cookiejar.py."""
2n/a
3n/aimport os
4n/aimport re
5n/aimport test.support
6n/aimport time
7n/aimport unittest
8n/aimport urllib.request
9n/a
10n/afrom http.cookiejar import (time2isoz, http2time, iso2time, time2netscape,
11n/a parse_ns_headers, join_header_words, split_header_words, Cookie,
12n/a CookieJar, DefaultCookiePolicy, LWPCookieJar, MozillaCookieJar,
13n/a LoadError, lwp_cookie_str, DEFAULT_HTTP_PORT, escape_path,
14n/a reach, is_HDN, domain_match, user_domain_match, request_path,
15n/a request_port, request_host)
16n/a
17n/a
18n/aclass DateTimeTests(unittest.TestCase):
19n/a
20n/a def test_time2isoz(self):
21n/a base = 1019227000
22n/a day = 24*3600
23n/a self.assertEqual(time2isoz(base), "2002-04-19 14:36:40Z")
24n/a self.assertEqual(time2isoz(base+day), "2002-04-20 14:36:40Z")
25n/a self.assertEqual(time2isoz(base+2*day), "2002-04-21 14:36:40Z")
26n/a self.assertEqual(time2isoz(base+3*day), "2002-04-22 14:36:40Z")
27n/a
28n/a az = time2isoz()
29n/a bz = time2isoz(500000)
30n/a for text in (az, bz):
31n/a self.assertRegex(text, r"^\d{4}-\d\d-\d\d \d\d:\d\d:\d\dZ$",
32n/a "bad time2isoz format: %s %s" % (az, bz))
33n/a
34n/a def test_time2netscape(self):
35n/a base = 1019227000
36n/a day = 24*3600
37n/a self.assertEqual(time2netscape(base), "Fri, 19-Apr-2002 14:36:40 GMT")
38n/a self.assertEqual(time2netscape(base+day),
39n/a "Sat, 20-Apr-2002 14:36:40 GMT")
40n/a
41n/a self.assertEqual(time2netscape(base+2*day),
42n/a "Sun, 21-Apr-2002 14:36:40 GMT")
43n/a
44n/a self.assertEqual(time2netscape(base+3*day),
45n/a "Mon, 22-Apr-2002 14:36:40 GMT")
46n/a
47n/a az = time2netscape()
48n/a bz = time2netscape(500000)
49n/a for text in (az, bz):
50n/a # Format "%s, %02d-%s-%04d %02d:%02d:%02d GMT"
51n/a self.assertRegex(
52n/a text,
53n/a r"[a-zA-Z]{3}, \d{2}-[a-zA-Z]{3}-\d{4} \d{2}:\d{2}:\d{2} GMT$",
54n/a "bad time2netscape format: %s %s" % (az, bz))
55n/a
56n/a def test_http2time(self):
57n/a def parse_date(text):
58n/a return time.gmtime(http2time(text))[:6]
59n/a
60n/a self.assertEqual(parse_date("01 Jan 2001"), (2001, 1, 1, 0, 0, 0.0))
61n/a
62n/a # this test will break around year 2070
63n/a self.assertEqual(parse_date("03-Feb-20"), (2020, 2, 3, 0, 0, 0.0))
64n/a
65n/a # this test will break around year 2048
66n/a self.assertEqual(parse_date("03-Feb-98"), (1998, 2, 3, 0, 0, 0.0))
67n/a
68n/a def test_http2time_formats(self):
69n/a # test http2time for supported dates. Test cases with 2 digit year
70n/a # will probably break in year 2044.
71n/a tests = [
72n/a 'Thu, 03 Feb 1994 00:00:00 GMT', # proposed new HTTP format
73n/a 'Thursday, 03-Feb-94 00:00:00 GMT', # old rfc850 HTTP format
74n/a 'Thursday, 03-Feb-1994 00:00:00 GMT', # broken rfc850 HTTP format
75n/a
76n/a '03 Feb 1994 00:00:00 GMT', # HTTP format (no weekday)
77n/a '03-Feb-94 00:00:00 GMT', # old rfc850 (no weekday)
78n/a '03-Feb-1994 00:00:00 GMT', # broken rfc850 (no weekday)
79n/a '03-Feb-1994 00:00 GMT', # broken rfc850 (no weekday, no seconds)
80n/a '03-Feb-1994 00:00', # broken rfc850 (no weekday, no seconds, no tz)
81n/a '02-Feb-1994 24:00', # broken rfc850 (no weekday, no seconds,
82n/a # no tz) using hour 24 with yesterday date
83n/a
84n/a '03-Feb-94', # old rfc850 HTTP format (no weekday, no time)
85n/a '03-Feb-1994', # broken rfc850 HTTP format (no weekday, no time)
86n/a '03 Feb 1994', # proposed new HTTP format (no weekday, no time)
87n/a
88n/a # A few tests with extra space at various places
89n/a ' 03 Feb 1994 0:00 ',
90n/a ' 03-Feb-1994 ',
91n/a ]
92n/a
93n/a test_t = 760233600 # assume broken POSIX counting of seconds
94n/a result = time2isoz(test_t)
95n/a expected = "1994-02-03 00:00:00Z"
96n/a self.assertEqual(result, expected,
97n/a "%s => '%s' (%s)" % (test_t, result, expected))
98n/a
99n/a for s in tests:
100n/a self.assertEqual(http2time(s), test_t, s)
101n/a self.assertEqual(http2time(s.lower()), test_t, s.lower())
102n/a self.assertEqual(http2time(s.upper()), test_t, s.upper())
103n/a
104n/a def test_http2time_garbage(self):
105n/a for test in [
106n/a '',
107n/a 'Garbage',
108n/a 'Mandag 16. September 1996',
109n/a '01-00-1980',
110n/a '01-13-1980',
111n/a '00-01-1980',
112n/a '32-01-1980',
113n/a '01-01-1980 25:00:00',
114n/a '01-01-1980 00:61:00',
115n/a '01-01-1980 00:00:62',
116n/a '08-Oct-3697739',
117n/a '08-01-3697739',
118n/a '09 Feb 19942632 22:23:32 GMT',
119n/a 'Wed, 09 Feb 1994834 22:23:32 GMT',
120n/a ]:
121n/a self.assertIsNone(http2time(test),
122n/a "http2time(%s) is not None\n"
123n/a "http2time(test) %s" % (test, http2time(test)))
124n/a
125n/a def test_iso2time(self):
126n/a def parse_date(text):
127n/a return time.gmtime(iso2time(text))[:6]
128n/a
129n/a # ISO 8601 compact format
130n/a self.assertEqual(parse_date("19940203T141529Z"),
131n/a (1994, 2, 3, 14, 15, 29))
132n/a
133n/a # ISO 8601 with time behind UTC
134n/a self.assertEqual(parse_date("1994-02-03 07:15:29 -0700"),
135n/a (1994, 2, 3, 14, 15, 29))
136n/a
137n/a # ISO 8601 with time ahead of UTC
138n/a self.assertEqual(parse_date("1994-02-03 19:45:29 +0530"),
139n/a (1994, 2, 3, 14, 15, 29))
140n/a
141n/a def test_iso2time_formats(self):
142n/a # test iso2time for supported dates.
143n/a tests = [
144n/a '1994-02-03 00:00:00 -0000', # ISO 8601 format
145n/a '1994-02-03 00:00:00 +0000', # ISO 8601 format
146n/a '1994-02-03 00:00:00', # zone is optional
147n/a '1994-02-03', # only date
148n/a '1994-02-03T00:00:00', # Use T as separator
149n/a '19940203', # only date
150n/a '1994-02-02 24:00:00', # using hour-24 yesterday date
151n/a '19940203T000000Z', # ISO 8601 compact format
152n/a
153n/a # A few tests with extra space at various places
154n/a ' 1994-02-03 ',
155n/a ' 1994-02-03T00:00:00 ',
156n/a ]
157n/a
158n/a test_t = 760233600 # assume broken POSIX counting of seconds
159n/a for s in tests:
160n/a self.assertEqual(iso2time(s), test_t, s)
161n/a self.assertEqual(iso2time(s.lower()), test_t, s.lower())
162n/a self.assertEqual(iso2time(s.upper()), test_t, s.upper())
163n/a
164n/a def test_iso2time_garbage(self):
165n/a for test in [
166n/a '',
167n/a 'Garbage',
168n/a 'Thursday, 03-Feb-94 00:00:00 GMT',
169n/a '1980-00-01',
170n/a '1980-13-01',
171n/a '1980-01-00',
172n/a '1980-01-32',
173n/a '1980-01-01 25:00:00',
174n/a '1980-01-01 00:61:00',
175n/a '01-01-1980 00:00:62',
176n/a '01-01-1980T00:00:62',
177n/a '19800101T250000Z'
178n/a '1980-01-01 00:00:00 -2500',
179n/a ]:
180n/a self.assertIsNone(iso2time(test),
181n/a "iso2time(%s) is not None\n"
182n/a "iso2time(test) %s" % (test, iso2time(test)))
183n/a
184n/a
185n/aclass HeaderTests(unittest.TestCase):
186n/a
187n/a def test_parse_ns_headers(self):
188n/a # quotes should be stripped
189n/a expected = [[('foo', 'bar'), ('expires', 2209069412), ('version', '0')]]
190n/a for hdr in [
191n/a 'foo=bar; expires=01 Jan 2040 22:23:32 GMT',
192n/a 'foo=bar; expires="01 Jan 2040 22:23:32 GMT"',
193n/a ]:
194n/a self.assertEqual(parse_ns_headers([hdr]), expected)
195n/a
196n/a def test_parse_ns_headers_version(self):
197n/a
198n/a # quotes should be stripped
199n/a expected = [[('foo', 'bar'), ('version', '1')]]
200n/a for hdr in [
201n/a 'foo=bar; version="1"',
202n/a 'foo=bar; Version="1"',
203n/a ]:
204n/a self.assertEqual(parse_ns_headers([hdr]), expected)
205n/a
206n/a def test_parse_ns_headers_special_names(self):
207n/a # names such as 'expires' are not special in first name=value pair
208n/a # of Set-Cookie: header
209n/a # Cookie with name 'expires'
210n/a hdr = 'expires=01 Jan 2040 22:23:32 GMT'
211n/a expected = [[("expires", "01 Jan 2040 22:23:32 GMT"), ("version", "0")]]
212n/a self.assertEqual(parse_ns_headers([hdr]), expected)
213n/a
214n/a def test_join_header_words(self):
215n/a joined = join_header_words([[("foo", None), ("bar", "baz")]])
216n/a self.assertEqual(joined, "foo; bar=baz")
217n/a
218n/a self.assertEqual(join_header_words([[]]), "")
219n/a
220n/a def test_split_header_words(self):
221n/a tests = [
222n/a ("foo", [[("foo", None)]]),
223n/a ("foo=bar", [[("foo", "bar")]]),
224n/a (" foo ", [[("foo", None)]]),
225n/a (" foo= ", [[("foo", "")]]),
226n/a (" foo=", [[("foo", "")]]),
227n/a (" foo= ; ", [[("foo", "")]]),
228n/a (" foo= ; bar= baz ", [[("foo", ""), ("bar", "baz")]]),
229n/a ("foo=bar bar=baz", [[("foo", "bar"), ("bar", "baz")]]),
230n/a # doesn't really matter if this next fails, but it works ATM
231n/a ("foo= bar=baz", [[("foo", "bar=baz")]]),
232n/a ("foo=bar;bar=baz", [[("foo", "bar"), ("bar", "baz")]]),
233n/a ('foo bar baz', [[("foo", None), ("bar", None), ("baz", None)]]),
234n/a ("a, b, c", [[("a", None)], [("b", None)], [("c", None)]]),
235n/a (r'foo; bar=baz, spam=, foo="\,\;\"", bar= ',
236n/a [[("foo", None), ("bar", "baz")],
237n/a [("spam", "")], [("foo", ',;"')], [("bar", "")]]),
238n/a ]
239n/a
240n/a for arg, expect in tests:
241n/a try:
242n/a result = split_header_words([arg])
243n/a except:
244n/a import traceback, io
245n/a f = io.StringIO()
246n/a traceback.print_exc(None, f)
247n/a result = "(error -- traceback follows)\n\n%s" % f.getvalue()
248n/a self.assertEqual(result, expect, """
249n/aWhen parsing: '%s'
250n/aExpected: '%s'
251n/aGot: '%s'
252n/a""" % (arg, expect, result))
253n/a
254n/a def test_roundtrip(self):
255n/a tests = [
256n/a ("foo", "foo"),
257n/a ("foo=bar", "foo=bar"),
258n/a (" foo ", "foo"),
259n/a ("foo=", 'foo=""'),
260n/a ("foo=bar bar=baz", "foo=bar; bar=baz"),
261n/a ("foo=bar;bar=baz", "foo=bar; bar=baz"),
262n/a ('foo bar baz', "foo; bar; baz"),
263n/a (r'foo="\"" bar="\\"', r'foo="\""; bar="\\"'),
264n/a ('foo,,,bar', 'foo, bar'),
265n/a ('foo=bar,bar=baz', 'foo=bar, bar=baz'),
266n/a
267n/a ('text/html; charset=iso-8859-1',
268n/a 'text/html; charset="iso-8859-1"'),
269n/a
270n/a ('foo="bar"; port="80,81"; discard, bar=baz',
271n/a 'foo=bar; port="80,81"; discard, bar=baz'),
272n/a
273n/a (r'Basic realm="\"foo\\\\bar\""',
274n/a r'Basic; realm="\"foo\\\\bar\""')
275n/a ]
276n/a
277n/a for arg, expect in tests:
278n/a input = split_header_words([arg])
279n/a res = join_header_words(input)
280n/a self.assertEqual(res, expect, """
281n/aWhen parsing: '%s'
282n/aExpected: '%s'
283n/aGot: '%s'
284n/aInput was: '%s'
285n/a""" % (arg, expect, res, input))
286n/a
287n/a
288n/aclass FakeResponse:
289n/a def __init__(self, headers=[], url=None):
290n/a """
291n/a headers: list of RFC822-style 'Key: value' strings
292n/a """
293n/a import email
294n/a self._headers = email.message_from_string("\n".join(headers))
295n/a self._url = url
296n/a def info(self): return self._headers
297n/a
298n/adef interact_2965(cookiejar, url, *set_cookie_hdrs):
299n/a return _interact(cookiejar, url, set_cookie_hdrs, "Set-Cookie2")
300n/a
301n/adef interact_netscape(cookiejar, url, *set_cookie_hdrs):
302n/a return _interact(cookiejar, url, set_cookie_hdrs, "Set-Cookie")
303n/a
304n/adef _interact(cookiejar, url, set_cookie_hdrs, hdr_name):
305n/a """Perform a single request / response cycle, returning Cookie: header."""
306n/a req = urllib.request.Request(url)
307n/a cookiejar.add_cookie_header(req)
308n/a cookie_hdr = req.get_header("Cookie", "")
309n/a headers = []
310n/a for hdr in set_cookie_hdrs:
311n/a headers.append("%s: %s" % (hdr_name, hdr))
312n/a res = FakeResponse(headers, url)
313n/a cookiejar.extract_cookies(res, req)
314n/a return cookie_hdr
315n/a
316n/a
317n/aclass FileCookieJarTests(unittest.TestCase):
318n/a def test_lwp_valueless_cookie(self):
319n/a # cookies with no value should be saved and loaded consistently
320n/a filename = test.support.TESTFN
321n/a c = LWPCookieJar()
322n/a interact_netscape(c, "http://www.acme.com/", 'boo')
323n/a self.assertEqual(c._cookies["www.acme.com"]["/"]["boo"].value, None)
324n/a try:
325n/a c.save(filename, ignore_discard=True)
326n/a c = LWPCookieJar()
327n/a c.load(filename, ignore_discard=True)
328n/a finally:
329n/a try: os.unlink(filename)
330n/a except OSError: pass
331n/a self.assertEqual(c._cookies["www.acme.com"]["/"]["boo"].value, None)
332n/a
333n/a def test_bad_magic(self):
334n/a # OSErrors (eg. file doesn't exist) are allowed to propagate
335n/a filename = test.support.TESTFN
336n/a for cookiejar_class in LWPCookieJar, MozillaCookieJar:
337n/a c = cookiejar_class()
338n/a try:
339n/a c.load(filename="for this test to work, a file with this "
340n/a "filename should not exist")
341n/a except OSError as exc:
342n/a # an OSError subclass (likely FileNotFoundError), but not
343n/a # LoadError
344n/a self.assertIsNot(exc.__class__, LoadError)
345n/a else:
346n/a self.fail("expected OSError for invalid filename")
347n/a # Invalid contents of cookies file (eg. bad magic string)
348n/a # causes a LoadError.
349n/a try:
350n/a with open(filename, "w") as f:
351n/a f.write("oops\n")
352n/a for cookiejar_class in LWPCookieJar, MozillaCookieJar:
353n/a c = cookiejar_class()
354n/a self.assertRaises(LoadError, c.load, filename)
355n/a finally:
356n/a try: os.unlink(filename)
357n/a except OSError: pass
358n/a
359n/aclass CookieTests(unittest.TestCase):
360n/a # XXX
361n/a # Get rid of string comparisons where not actually testing str / repr.
362n/a # .clear() etc.
363n/a # IP addresses like 50 (single number, no dot) and domain-matching
364n/a # functions (and is_HDN)? See draft RFC 2965 errata.
365n/a # Strictness switches
366n/a # is_third_party()
367n/a # unverifiability / third-party blocking
368n/a # Netscape cookies work the same as RFC 2965 with regard to port.
369n/a # Set-Cookie with negative max age.
370n/a # If turn RFC 2965 handling off, Set-Cookie2 cookies should not clobber
371n/a # Set-Cookie cookies.
372n/a # Cookie2 should be sent if *any* cookies are not V1 (ie. V0 OR V2 etc.).
373n/a # Cookies (V1 and V0) with no expiry date should be set to be discarded.
374n/a # RFC 2965 Quoting:
375n/a # Should accept unquoted cookie-attribute values? check errata draft.
376n/a # Which are required on the way in and out?
377n/a # Should always return quoted cookie-attribute values?
378n/a # Proper testing of when RFC 2965 clobbers Netscape (waiting for errata).
379n/a # Path-match on return (same for V0 and V1).
380n/a # RFC 2965 acceptance and returning rules
381n/a # Set-Cookie2 without version attribute is rejected.
382n/a
383n/a # Netscape peculiarities list from Ronald Tschalar.
384n/a # The first two still need tests, the rest are covered.
385n/a## - Quoting: only quotes around the expires value are recognized as such
386n/a## (and yes, some folks quote the expires value); quotes around any other
387n/a## value are treated as part of the value.
388n/a## - White space: white space around names and values is ignored
389n/a## - Default path: if no path parameter is given, the path defaults to the
390n/a## path in the request-uri up to, but not including, the last '/'. Note
391n/a## that this is entirely different from what the spec says.
392n/a## - Commas and other delimiters: Netscape just parses until the next ';'.
393n/a## This means it will allow commas etc inside values (and yes, both
394n/a## commas and equals are commonly appear in the cookie value). This also
395n/a## means that if you fold multiple Set-Cookie header fields into one,
396n/a## comma-separated list, it'll be a headache to parse (at least my head
397n/a## starts hurting every time I think of that code).
398n/a## - Expires: You'll get all sorts of date formats in the expires,
399n/a## including empty expires attributes ("expires="). Be as flexible as you
400n/a## can, and certainly don't expect the weekday to be there; if you can't
401n/a## parse it, just ignore it and pretend it's a session cookie.
402n/a## - Domain-matching: Netscape uses the 2-dot rule for _all_ domains, not
403n/a## just the 7 special TLD's listed in their spec. And folks rely on
404n/a## that...
405n/a
406n/a def test_domain_return_ok(self):
407n/a # test optimization: .domain_return_ok() should filter out most
408n/a # domains in the CookieJar before we try to access them (because that
409n/a # may require disk access -- in particular, with MSIECookieJar)
410n/a # This is only a rough check for performance reasons, so it's not too
411n/a # critical as long as it's sufficiently liberal.
412n/a pol = DefaultCookiePolicy()
413n/a for url, domain, ok in [
414n/a ("http://foo.bar.com/", "blah.com", False),
415n/a ("http://foo.bar.com/", "rhubarb.blah.com", False),
416n/a ("http://foo.bar.com/", "rhubarb.foo.bar.com", False),
417n/a ("http://foo.bar.com/", ".foo.bar.com", True),
418n/a ("http://foo.bar.com/", "foo.bar.com", True),
419n/a ("http://foo.bar.com/", ".bar.com", True),
420n/a ("http://foo.bar.com/", "com", True),
421n/a ("http://foo.com/", "rhubarb.foo.com", False),
422n/a ("http://foo.com/", ".foo.com", True),
423n/a ("http://foo.com/", "foo.com", True),
424n/a ("http://foo.com/", "com", True),
425n/a ("http://foo/", "rhubarb.foo", False),
426n/a ("http://foo/", ".foo", True),
427n/a ("http://foo/", "foo", True),
428n/a ("http://foo/", "foo.local", True),
429n/a ("http://foo/", ".local", True),
430n/a ]:
431n/a request = urllib.request.Request(url)
432n/a r = pol.domain_return_ok(domain, request)
433n/a if ok: self.assertTrue(r)
434n/a else: self.assertFalse(r)
435n/a
436n/a def test_missing_value(self):
437n/a # missing = sign in Cookie: header is regarded by Mozilla as a missing
438n/a # name, and by http.cookiejar as a missing value
439n/a filename = test.support.TESTFN
440n/a c = MozillaCookieJar(filename)
441n/a interact_netscape(c, "http://www.acme.com/", 'eggs')
442n/a interact_netscape(c, "http://www.acme.com/", '"spam"; path=/foo/')
443n/a cookie = c._cookies["www.acme.com"]["/"]["eggs"]
444n/a self.assertIsNone(cookie.value)
445n/a self.assertEqual(cookie.name, "eggs")
446n/a cookie = c._cookies["www.acme.com"]['/foo/']['"spam"']
447n/a self.assertIsNone(cookie.value)
448n/a self.assertEqual(cookie.name, '"spam"')
449n/a self.assertEqual(lwp_cookie_str(cookie), (
450n/a r'"spam"; path="/foo/"; domain="www.acme.com"; '
451n/a 'path_spec; discard; version=0'))
452n/a old_str = repr(c)
453n/a c.save(ignore_expires=True, ignore_discard=True)
454n/a try:
455n/a c = MozillaCookieJar(filename)
456n/a c.revert(ignore_expires=True, ignore_discard=True)
457n/a finally:
458n/a os.unlink(c.filename)
459n/a # cookies unchanged apart from lost info re. whether path was specified
460n/a self.assertEqual(
461n/a repr(c),
462n/a re.sub("path_specified=%s" % True, "path_specified=%s" % False,
463n/a old_str)
464n/a )
465n/a self.assertEqual(interact_netscape(c, "http://www.acme.com/foo/"),
466n/a '"spam"; eggs')
467n/a
468n/a def test_rfc2109_handling(self):
469n/a # RFC 2109 cookies are handled as RFC 2965 or Netscape cookies,
470n/a # dependent on policy settings
471n/a for rfc2109_as_netscape, rfc2965, version in [
472n/a # default according to rfc2965 if not explicitly specified
473n/a (None, False, 0),
474n/a (None, True, 1),
475n/a # explicit rfc2109_as_netscape
476n/a (False, False, None), # version None here means no cookie stored
477n/a (False, True, 1),
478n/a (True, False, 0),
479n/a (True, True, 0),
480n/a ]:
481n/a policy = DefaultCookiePolicy(
482n/a rfc2109_as_netscape=rfc2109_as_netscape,
483n/a rfc2965=rfc2965)
484n/a c = CookieJar(policy)
485n/a interact_netscape(c, "http://www.example.com/", "ni=ni; Version=1")
486n/a try:
487n/a cookie = c._cookies["www.example.com"]["/"]["ni"]
488n/a except KeyError:
489n/a self.assertIsNone(version) # didn't expect a stored cookie
490n/a else:
491n/a self.assertEqual(cookie.version, version)
492n/a # 2965 cookies are unaffected
493n/a interact_2965(c, "http://www.example.com/",
494n/a "foo=bar; Version=1")
495n/a if rfc2965:
496n/a cookie2965 = c._cookies["www.example.com"]["/"]["foo"]
497n/a self.assertEqual(cookie2965.version, 1)
498n/a
499n/a def test_ns_parser(self):
500n/a c = CookieJar()
501n/a interact_netscape(c, "http://www.acme.com/",
502n/a 'spam=eggs; DoMain=.acme.com; port; blArgh="feep"')
503n/a interact_netscape(c, "http://www.acme.com/", 'ni=ni; port=80,8080')
504n/a interact_netscape(c, "http://www.acme.com:80/", 'nini=ni')
505n/a interact_netscape(c, "http://www.acme.com:80/", 'foo=bar; expires=')
506n/a interact_netscape(c, "http://www.acme.com:80/", 'spam=eggs; '
507n/a 'expires="Foo Bar 25 33:22:11 3022"')
508n/a interact_netscape(c, 'http://www.acme.com/', 'fortytwo=')
509n/a interact_netscape(c, 'http://www.acme.com/', '=unladenswallow')
510n/a interact_netscape(c, 'http://www.acme.com/', 'holyhandgrenade')
511n/a
512n/a cookie = c._cookies[".acme.com"]["/"]["spam"]
513n/a self.assertEqual(cookie.domain, ".acme.com")
514n/a self.assertTrue(cookie.domain_specified)
515n/a self.assertEqual(cookie.port, DEFAULT_HTTP_PORT)
516n/a self.assertFalse(cookie.port_specified)
517n/a # case is preserved
518n/a self.assertTrue(cookie.has_nonstandard_attr("blArgh"))
519n/a self.assertFalse(cookie.has_nonstandard_attr("blargh"))
520n/a
521n/a cookie = c._cookies["www.acme.com"]["/"]["ni"]
522n/a self.assertEqual(cookie.domain, "www.acme.com")
523n/a self.assertFalse(cookie.domain_specified)
524n/a self.assertEqual(cookie.port, "80,8080")
525n/a self.assertTrue(cookie.port_specified)
526n/a
527n/a cookie = c._cookies["www.acme.com"]["/"]["nini"]
528n/a self.assertIsNone(cookie.port)
529n/a self.assertFalse(cookie.port_specified)
530n/a
531n/a # invalid expires should not cause cookie to be dropped
532n/a foo = c._cookies["www.acme.com"]["/"]["foo"]
533n/a spam = c._cookies["www.acme.com"]["/"]["foo"]
534n/a self.assertIsNone(foo.expires)
535n/a self.assertIsNone(spam.expires)
536n/a
537n/a cookie = c._cookies['www.acme.com']['/']['fortytwo']
538n/a self.assertIsNotNone(cookie.value)
539n/a self.assertEqual(cookie.value, '')
540n/a
541n/a # there should be a distinction between a present but empty value
542n/a # (above) and a value that's entirely missing (below)
543n/a
544n/a cookie = c._cookies['www.acme.com']['/']['holyhandgrenade']
545n/a self.assertIsNone(cookie.value)
546n/a
547n/a def test_ns_parser_special_names(self):
548n/a # names such as 'expires' are not special in first name=value pair
549n/a # of Set-Cookie: header
550n/a c = CookieJar()
551n/a interact_netscape(c, "http://www.acme.com/", 'expires=eggs')
552n/a interact_netscape(c, "http://www.acme.com/", 'version=eggs; spam=eggs')
553n/a
554n/a cookies = c._cookies["www.acme.com"]["/"]
555n/a self.assertIn('expires', cookies)
556n/a self.assertIn('version', cookies)
557n/a
558n/a def test_expires(self):
559n/a # if expires is in future, keep cookie...
560n/a c = CookieJar()
561n/a future = time2netscape(time.time()+3600)
562n/a interact_netscape(c, "http://www.acme.com/", 'spam="bar"; expires=%s' %
563n/a future)
564n/a self.assertEqual(len(c), 1)
565n/a now = time2netscape(time.time()-1)
566n/a # ... and if in past or present, discard it
567n/a interact_netscape(c, "http://www.acme.com/", 'foo="eggs"; expires=%s' %
568n/a now)
569n/a h = interact_netscape(c, "http://www.acme.com/")
570n/a self.assertEqual(len(c), 1)
571n/a self.assertIn('spam="bar"', h)
572n/a self.assertNotIn("foo", h)
573n/a
574n/a # max-age takes precedence over expires, and zero max-age is request to
575n/a # delete both new cookie and any old matching cookie
576n/a interact_netscape(c, "http://www.acme.com/", 'eggs="bar"; expires=%s' %
577n/a future)
578n/a interact_netscape(c, "http://www.acme.com/", 'bar="bar"; expires=%s' %
579n/a future)
580n/a self.assertEqual(len(c), 3)
581n/a interact_netscape(c, "http://www.acme.com/", 'eggs="bar"; '
582n/a 'expires=%s; max-age=0' % future)
583n/a interact_netscape(c, "http://www.acme.com/", 'bar="bar"; '
584n/a 'max-age=0; expires=%s' % future)
585n/a h = interact_netscape(c, "http://www.acme.com/")
586n/a self.assertEqual(len(c), 1)
587n/a
588n/a # test expiry at end of session for cookies with no expires attribute
589n/a interact_netscape(c, "http://www.rhubarb.net/", 'whum="fizz"')
590n/a self.assertEqual(len(c), 2)
591n/a c.clear_session_cookies()
592n/a self.assertEqual(len(c), 1)
593n/a self.assertIn('spam="bar"', h)
594n/a
595n/a # test if fractional expiry is accepted
596n/a cookie = Cookie(0, "name", "value",
597n/a None, False, "www.python.org",
598n/a True, False, "/",
599n/a False, False, "1444312383.018307",
600n/a False, None, None,
601n/a {})
602n/a self.assertEqual(cookie.expires, 1444312383)
603n/a
604n/a # XXX RFC 2965 expiry rules (some apply to V0 too)
605n/a
606n/a def test_default_path(self):
607n/a # RFC 2965
608n/a pol = DefaultCookiePolicy(rfc2965=True)
609n/a
610n/a c = CookieJar(pol)
611n/a interact_2965(c, "http://www.acme.com/", 'spam="bar"; Version="1"')
612n/a self.assertIn("/", c._cookies["www.acme.com"])
613n/a
614n/a c = CookieJar(pol)
615n/a interact_2965(c, "http://www.acme.com/blah", 'eggs="bar"; Version="1"')
616n/a self.assertIn("/", c._cookies["www.acme.com"])
617n/a
618n/a c = CookieJar(pol)
619n/a interact_2965(c, "http://www.acme.com/blah/rhubarb",
620n/a 'eggs="bar"; Version="1"')
621n/a self.assertIn("/blah/", c._cookies["www.acme.com"])
622n/a
623n/a c = CookieJar(pol)
624n/a interact_2965(c, "http://www.acme.com/blah/rhubarb/",
625n/a 'eggs="bar"; Version="1"')
626n/a self.assertIn("/blah/rhubarb/", c._cookies["www.acme.com"])
627n/a
628n/a # Netscape
629n/a
630n/a c = CookieJar()
631n/a interact_netscape(c, "http://www.acme.com/", 'spam="bar"')
632n/a self.assertIn("/", c._cookies["www.acme.com"])
633n/a
634n/a c = CookieJar()
635n/a interact_netscape(c, "http://www.acme.com/blah", 'eggs="bar"')
636n/a self.assertIn("/", c._cookies["www.acme.com"])
637n/a
638n/a c = CookieJar()
639n/a interact_netscape(c, "http://www.acme.com/blah/rhubarb", 'eggs="bar"')
640n/a self.assertIn("/blah", c._cookies["www.acme.com"])
641n/a
642n/a c = CookieJar()
643n/a interact_netscape(c, "http://www.acme.com/blah/rhubarb/", 'eggs="bar"')
644n/a self.assertIn("/blah/rhubarb", c._cookies["www.acme.com"])
645n/a
646n/a def test_default_path_with_query(self):
647n/a cj = CookieJar()
648n/a uri = "http://example.com/?spam/eggs"
649n/a value = 'eggs="bar"'
650n/a interact_netscape(cj, uri, value)
651n/a # Default path does not include query, so is "/", not "/?spam".
652n/a self.assertIn("/", cj._cookies["example.com"])
653n/a # Cookie is sent back to the same URI.
654n/a self.assertEqual(interact_netscape(cj, uri), value)
655n/a
656n/a def test_escape_path(self):
657n/a cases = [
658n/a # quoted safe
659n/a ("/foo%2f/bar", "/foo%2F/bar"),
660n/a ("/foo%2F/bar", "/foo%2F/bar"),
661n/a # quoted %
662n/a ("/foo%%/bar", "/foo%%/bar"),
663n/a # quoted unsafe
664n/a ("/fo%19o/bar", "/fo%19o/bar"),
665n/a ("/fo%7do/bar", "/fo%7Do/bar"),
666n/a # unquoted safe
667n/a ("/foo/bar&", "/foo/bar&"),
668n/a ("/foo//bar", "/foo//bar"),
669n/a ("\176/foo/bar", "\176/foo/bar"),
670n/a # unquoted unsafe
671n/a ("/foo\031/bar", "/foo%19/bar"),
672n/a ("/\175foo/bar", "/%7Dfoo/bar"),
673n/a # unicode, latin-1 range
674n/a ("/foo/bar\u00fc", "/foo/bar%C3%BC"), # UTF-8 encoded
675n/a # unicode
676n/a ("/foo/bar\uabcd", "/foo/bar%EA%AF%8D"), # UTF-8 encoded
677n/a ]
678n/a for arg, result in cases:
679n/a self.assertEqual(escape_path(arg), result)
680n/a
681n/a def test_request_path(self):
682n/a # with parameters
683n/a req = urllib.request.Request(
684n/a "http://www.example.com/rheum/rhaponticum;"
685n/a "foo=bar;sing=song?apples=pears&spam=eggs#ni")
686n/a self.assertEqual(request_path(req),
687n/a "/rheum/rhaponticum;foo=bar;sing=song")
688n/a # without parameters
689n/a req = urllib.request.Request(
690n/a "http://www.example.com/rheum/rhaponticum?"
691n/a "apples=pears&spam=eggs#ni")
692n/a self.assertEqual(request_path(req), "/rheum/rhaponticum")
693n/a # missing final slash
694n/a req = urllib.request.Request("http://www.example.com")
695n/a self.assertEqual(request_path(req), "/")
696n/a
697n/a def test_request_port(self):
698n/a req = urllib.request.Request("http://www.acme.com:1234/",
699n/a headers={"Host": "www.acme.com:4321"})
700n/a self.assertEqual(request_port(req), "1234")
701n/a req = urllib.request.Request("http://www.acme.com/",
702n/a headers={"Host": "www.acme.com:4321"})
703n/a self.assertEqual(request_port(req), DEFAULT_HTTP_PORT)
704n/a
705n/a def test_request_host(self):
706n/a # this request is illegal (RFC2616, 14.2.3)
707n/a req = urllib.request.Request("http://1.1.1.1/",
708n/a headers={"Host": "www.acme.com:80"})
709n/a # libwww-perl wants this response, but that seems wrong (RFC 2616,
710n/a # section 5.2, point 1., and RFC 2965 section 1, paragraph 3)
711n/a #self.assertEqual(request_host(req), "www.acme.com")
712n/a self.assertEqual(request_host(req), "1.1.1.1")
713n/a req = urllib.request.Request("http://www.acme.com/",
714n/a headers={"Host": "irrelevant.com"})
715n/a self.assertEqual(request_host(req), "www.acme.com")
716n/a # port shouldn't be in request-host
717n/a req = urllib.request.Request("http://www.acme.com:2345/resource.html",
718n/a headers={"Host": "www.acme.com:5432"})
719n/a self.assertEqual(request_host(req), "www.acme.com")
720n/a
721n/a def test_is_HDN(self):
722n/a self.assertTrue(is_HDN("foo.bar.com"))
723n/a self.assertTrue(is_HDN("1foo2.3bar4.5com"))
724n/a self.assertFalse(is_HDN("192.168.1.1"))
725n/a self.assertFalse(is_HDN(""))
726n/a self.assertFalse(is_HDN("."))
727n/a self.assertFalse(is_HDN(".foo.bar.com"))
728n/a self.assertFalse(is_HDN("..foo"))
729n/a self.assertFalse(is_HDN("foo."))
730n/a
731n/a def test_reach(self):
732n/a self.assertEqual(reach("www.acme.com"), ".acme.com")
733n/a self.assertEqual(reach("acme.com"), "acme.com")
734n/a self.assertEqual(reach("acme.local"), ".local")
735n/a self.assertEqual(reach(".local"), ".local")
736n/a self.assertEqual(reach(".com"), ".com")
737n/a self.assertEqual(reach("."), ".")
738n/a self.assertEqual(reach(""), "")
739n/a self.assertEqual(reach("192.168.0.1"), "192.168.0.1")
740n/a
741n/a def test_domain_match(self):
742n/a self.assertTrue(domain_match("192.168.1.1", "192.168.1.1"))
743n/a self.assertFalse(domain_match("192.168.1.1", ".168.1.1"))
744n/a self.assertTrue(domain_match("x.y.com", "x.Y.com"))
745n/a self.assertTrue(domain_match("x.y.com", ".Y.com"))
746n/a self.assertFalse(domain_match("x.y.com", "Y.com"))
747n/a self.assertTrue(domain_match("a.b.c.com", ".c.com"))
748n/a self.assertFalse(domain_match(".c.com", "a.b.c.com"))
749n/a self.assertTrue(domain_match("example.local", ".local"))
750n/a self.assertFalse(domain_match("blah.blah", ""))
751n/a self.assertFalse(domain_match("", ".rhubarb.rhubarb"))
752n/a self.assertTrue(domain_match("", ""))
753n/a
754n/a self.assertTrue(user_domain_match("acme.com", "acme.com"))
755n/a self.assertFalse(user_domain_match("acme.com", ".acme.com"))
756n/a self.assertTrue(user_domain_match("rhubarb.acme.com", ".acme.com"))
757n/a self.assertTrue(user_domain_match("www.rhubarb.acme.com", ".acme.com"))
758n/a self.assertTrue(user_domain_match("x.y.com", "x.Y.com"))
759n/a self.assertTrue(user_domain_match("x.y.com", ".Y.com"))
760n/a self.assertFalse(user_domain_match("x.y.com", "Y.com"))
761n/a self.assertTrue(user_domain_match("y.com", "Y.com"))
762n/a self.assertFalse(user_domain_match(".y.com", "Y.com"))
763n/a self.assertTrue(user_domain_match(".y.com", ".Y.com"))
764n/a self.assertTrue(user_domain_match("x.y.com", ".com"))
765n/a self.assertFalse(user_domain_match("x.y.com", "com"))
766n/a self.assertFalse(user_domain_match("x.y.com", "m"))
767n/a self.assertFalse(user_domain_match("x.y.com", ".m"))
768n/a self.assertFalse(user_domain_match("x.y.com", ""))
769n/a self.assertFalse(user_domain_match("x.y.com", "."))
770n/a self.assertTrue(user_domain_match("192.168.1.1", "192.168.1.1"))
771n/a # not both HDNs, so must string-compare equal to match
772n/a self.assertFalse(user_domain_match("192.168.1.1", ".168.1.1"))
773n/a self.assertFalse(user_domain_match("192.168.1.1", "."))
774n/a # empty string is a special case
775n/a self.assertFalse(user_domain_match("192.168.1.1", ""))
776n/a
777n/a def test_wrong_domain(self):
778n/a # Cookies whose effective request-host name does not domain-match the
779n/a # domain are rejected.
780n/a
781n/a # XXX far from complete
782n/a c = CookieJar()
783n/a interact_2965(c, "http://www.nasty.com/",
784n/a 'foo=bar; domain=friendly.org; Version="1"')
785n/a self.assertEqual(len(c), 0)
786n/a
787n/a def test_strict_domain(self):
788n/a # Cookies whose domain is a country-code tld like .co.uk should
789n/a # not be set if CookiePolicy.strict_domain is true.
790n/a cp = DefaultCookiePolicy(strict_domain=True)
791n/a cj = CookieJar(policy=cp)
792n/a interact_netscape(cj, "http://example.co.uk/", 'no=problemo')
793n/a interact_netscape(cj, "http://example.co.uk/",
794n/a 'okey=dokey; Domain=.example.co.uk')
795n/a self.assertEqual(len(cj), 2)
796n/a for pseudo_tld in [".co.uk", ".org.za", ".tx.us", ".name.us"]:
797n/a interact_netscape(cj, "http://example.%s/" % pseudo_tld,
798n/a 'spam=eggs; Domain=.co.uk')
799n/a self.assertEqual(len(cj), 2)
800n/a
801n/a def test_two_component_domain_ns(self):
802n/a # Netscape: .www.bar.com, www.bar.com, .bar.com, bar.com, no domain
803n/a # should all get accepted, as should .acme.com, acme.com and no domain
804n/a # for 2-component domains like acme.com.
805n/a c = CookieJar()
806n/a
807n/a # two-component V0 domain is OK
808n/a interact_netscape(c, "http://foo.net/", 'ns=bar')
809n/a self.assertEqual(len(c), 1)
810n/a self.assertEqual(c._cookies["foo.net"]["/"]["ns"].value, "bar")
811n/a self.assertEqual(interact_netscape(c, "http://foo.net/"), "ns=bar")
812n/a # *will* be returned to any other domain (unlike RFC 2965)...
813n/a self.assertEqual(interact_netscape(c, "http://www.foo.net/"),
814n/a "ns=bar")
815n/a # ...unless requested otherwise
816n/a pol = DefaultCookiePolicy(
817n/a strict_ns_domain=DefaultCookiePolicy.DomainStrictNonDomain)
818n/a c.set_policy(pol)
819n/a self.assertEqual(interact_netscape(c, "http://www.foo.net/"), "")
820n/a
821n/a # unlike RFC 2965, even explicit two-component domain is OK,
822n/a # because .foo.net matches foo.net
823n/a interact_netscape(c, "http://foo.net/foo/",
824n/a 'spam1=eggs; domain=foo.net')
825n/a # even if starts with a dot -- in NS rules, .foo.net matches foo.net!
826n/a interact_netscape(c, "http://foo.net/foo/bar/",
827n/a 'spam2=eggs; domain=.foo.net')
828n/a self.assertEqual(len(c), 3)
829n/a self.assertEqual(c._cookies[".foo.net"]["/foo"]["spam1"].value,
830n/a "eggs")
831n/a self.assertEqual(c._cookies[".foo.net"]["/foo/bar"]["spam2"].value,
832n/a "eggs")
833n/a self.assertEqual(interact_netscape(c, "http://foo.net/foo/bar/"),
834n/a "spam2=eggs; spam1=eggs; ns=bar")
835n/a
836n/a # top-level domain is too general
837n/a interact_netscape(c, "http://foo.net/", 'nini="ni"; domain=.net')
838n/a self.assertEqual(len(c), 3)
839n/a
840n/a## # Netscape protocol doesn't allow non-special top level domains (such
841n/a## # as co.uk) in the domain attribute unless there are at least three
842n/a## # dots in it.
843n/a # Oh yes it does! Real implementations don't check this, and real
844n/a # cookies (of course) rely on that behaviour.
845n/a interact_netscape(c, "http://foo.co.uk", 'nasty=trick; domain=.co.uk')
846n/a## self.assertEqual(len(c), 2)
847n/a self.assertEqual(len(c), 4)
848n/a
849n/a def test_two_component_domain_rfc2965(self):
850n/a pol = DefaultCookiePolicy(rfc2965=True)
851n/a c = CookieJar(pol)
852n/a
853n/a # two-component V1 domain is OK
854n/a interact_2965(c, "http://foo.net/", 'foo=bar; Version="1"')
855n/a self.assertEqual(len(c), 1)
856n/a self.assertEqual(c._cookies["foo.net"]["/"]["foo"].value, "bar")
857n/a self.assertEqual(interact_2965(c, "http://foo.net/"),
858n/a "$Version=1; foo=bar")
859n/a # won't be returned to any other domain (because domain was implied)
860n/a self.assertEqual(interact_2965(c, "http://www.foo.net/"), "")
861n/a
862n/a # unless domain is given explicitly, because then it must be
863n/a # rewritten to start with a dot: foo.net --> .foo.net, which does
864n/a # not domain-match foo.net
865n/a interact_2965(c, "http://foo.net/foo",
866n/a 'spam=eggs; domain=foo.net; path=/foo; Version="1"')
867n/a self.assertEqual(len(c), 1)
868n/a self.assertEqual(interact_2965(c, "http://foo.net/foo"),
869n/a "$Version=1; foo=bar")
870n/a
871n/a # explicit foo.net from three-component domain www.foo.net *does* get
872n/a # set, because .foo.net domain-matches .foo.net
873n/a interact_2965(c, "http://www.foo.net/foo/",
874n/a 'spam=eggs; domain=foo.net; Version="1"')
875n/a self.assertEqual(c._cookies[".foo.net"]["/foo/"]["spam"].value,
876n/a "eggs")
877n/a self.assertEqual(len(c), 2)
878n/a self.assertEqual(interact_2965(c, "http://foo.net/foo/"),
879n/a "$Version=1; foo=bar")
880n/a self.assertEqual(interact_2965(c, "http://www.foo.net/foo/"),
881n/a '$Version=1; spam=eggs; $Domain="foo.net"')
882n/a
883n/a # top-level domain is too general
884n/a interact_2965(c, "http://foo.net/",
885n/a 'ni="ni"; domain=".net"; Version="1"')
886n/a self.assertEqual(len(c), 2)
887n/a
888n/a # RFC 2965 doesn't require blocking this
889n/a interact_2965(c, "http://foo.co.uk/",
890n/a 'nasty=trick; domain=.co.uk; Version="1"')
891n/a self.assertEqual(len(c), 3)
892n/a
893n/a def test_domain_allow(self):
894n/a c = CookieJar(policy=DefaultCookiePolicy(
895n/a blocked_domains=["acme.com"],
896n/a allowed_domains=["www.acme.com"]))
897n/a
898n/a req = urllib.request.Request("http://acme.com/")
899n/a headers = ["Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/"]
900n/a res = FakeResponse(headers, "http://acme.com/")
901n/a c.extract_cookies(res, req)
902n/a self.assertEqual(len(c), 0)
903n/a
904n/a req = urllib.request.Request("http://www.acme.com/")
905n/a res = FakeResponse(headers, "http://www.acme.com/")
906n/a c.extract_cookies(res, req)
907n/a self.assertEqual(len(c), 1)
908n/a
909n/a req = urllib.request.Request("http://www.coyote.com/")
910n/a res = FakeResponse(headers, "http://www.coyote.com/")
911n/a c.extract_cookies(res, req)
912n/a self.assertEqual(len(c), 1)
913n/a
914n/a # set a cookie with non-allowed domain...
915n/a req = urllib.request.Request("http://www.coyote.com/")
916n/a res = FakeResponse(headers, "http://www.coyote.com/")
917n/a cookies = c.make_cookies(res, req)
918n/a c.set_cookie(cookies[0])
919n/a self.assertEqual(len(c), 2)
920n/a # ... and check is doesn't get returned
921n/a c.add_cookie_header(req)
922n/a self.assertFalse(req.has_header("Cookie"))
923n/a
924n/a def test_domain_block(self):
925n/a pol = DefaultCookiePolicy(
926n/a rfc2965=True, blocked_domains=[".acme.com"])
927n/a c = CookieJar(policy=pol)
928n/a headers = ["Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/"]
929n/a
930n/a req = urllib.request.Request("http://www.acme.com/")
931n/a res = FakeResponse(headers, "http://www.acme.com/")
932n/a c.extract_cookies(res, req)
933n/a self.assertEqual(len(c), 0)
934n/a
935n/a p = pol.set_blocked_domains(["acme.com"])
936n/a c.extract_cookies(res, req)
937n/a self.assertEqual(len(c), 1)
938n/a
939n/a c.clear()
940n/a req = urllib.request.Request("http://www.roadrunner.net/")
941n/a res = FakeResponse(headers, "http://www.roadrunner.net/")
942n/a c.extract_cookies(res, req)
943n/a self.assertEqual(len(c), 1)
944n/a req = urllib.request.Request("http://www.roadrunner.net/")
945n/a c.add_cookie_header(req)
946n/a self.assertTrue(req.has_header("Cookie"))
947n/a self.assertTrue(req.has_header("Cookie2"))
948n/a
949n/a c.clear()
950n/a pol.set_blocked_domains([".acme.com"])
951n/a c.extract_cookies(res, req)
952n/a self.assertEqual(len(c), 1)
953n/a
954n/a # set a cookie with blocked domain...
955n/a req = urllib.request.Request("http://www.acme.com/")
956n/a res = FakeResponse(headers, "http://www.acme.com/")
957n/a cookies = c.make_cookies(res, req)
958n/a c.set_cookie(cookies[0])
959n/a self.assertEqual(len(c), 2)
960n/a # ... and check is doesn't get returned
961n/a c.add_cookie_header(req)
962n/a self.assertFalse(req.has_header("Cookie"))
963n/a
964n/a def test_secure(self):
965n/a for ns in True, False:
966n/a for whitespace in " ", "":
967n/a c = CookieJar()
968n/a if ns:
969n/a pol = DefaultCookiePolicy(rfc2965=False)
970n/a int = interact_netscape
971n/a vs = ""
972n/a else:
973n/a pol = DefaultCookiePolicy(rfc2965=True)
974n/a int = interact_2965
975n/a vs = "; Version=1"
976n/a c.set_policy(pol)
977n/a url = "http://www.acme.com/"
978n/a int(c, url, "foo1=bar%s%s" % (vs, whitespace))
979n/a int(c, url, "foo2=bar%s; secure%s" % (vs, whitespace))
980n/a self.assertFalse(
981n/a c._cookies["www.acme.com"]["/"]["foo1"].secure,
982n/a "non-secure cookie registered secure")
983n/a self.assertTrue(
984n/a c._cookies["www.acme.com"]["/"]["foo2"].secure,
985n/a "secure cookie registered non-secure")
986n/a
987n/a def test_quote_cookie_value(self):
988n/a c = CookieJar(policy=DefaultCookiePolicy(rfc2965=True))
989n/a interact_2965(c, "http://www.acme.com/", r'foo=\b"a"r; Version=1')
990n/a h = interact_2965(c, "http://www.acme.com/")
991n/a self.assertEqual(h, r'$Version=1; foo=\\b\"a\"r')
992n/a
993n/a def test_missing_final_slash(self):
994n/a # Missing slash from request URL's abs_path should be assumed present.
995n/a url = "http://www.acme.com"
996n/a c = CookieJar(DefaultCookiePolicy(rfc2965=True))
997n/a interact_2965(c, url, "foo=bar; Version=1")
998n/a req = urllib.request.Request(url)
999n/a self.assertEqual(len(c), 1)
1000n/a c.add_cookie_header(req)
1001n/a self.assertTrue(req.has_header("Cookie"))
1002n/a
1003n/a def test_domain_mirror(self):
1004n/a pol = DefaultCookiePolicy(rfc2965=True)
1005n/a
1006n/a c = CookieJar(pol)
1007n/a url = "http://foo.bar.com/"
1008n/a interact_2965(c, url, "spam=eggs; Version=1")
1009n/a h = interact_2965(c, url)
1010n/a self.assertNotIn("Domain", h,
1011n/a "absent domain returned with domain present")
1012n/a
1013n/a c = CookieJar(pol)
1014n/a url = "http://foo.bar.com/"
1015n/a interact_2965(c, url, 'spam=eggs; Version=1; Domain=.bar.com')
1016n/a h = interact_2965(c, url)
1017n/a self.assertIn('$Domain=".bar.com"', h, "domain not returned")
1018n/a
1019n/a c = CookieJar(pol)
1020n/a url = "http://foo.bar.com/"
1021n/a # note missing initial dot in Domain
1022n/a interact_2965(c, url, 'spam=eggs; Version=1; Domain=bar.com')
1023n/a h = interact_2965(c, url)
1024n/a self.assertIn('$Domain="bar.com"', h, "domain not returned")
1025n/a
1026n/a def test_path_mirror(self):
1027n/a pol = DefaultCookiePolicy(rfc2965=True)
1028n/a
1029n/a c = CookieJar(pol)
1030n/a url = "http://foo.bar.com/"
1031n/a interact_2965(c, url, "spam=eggs; Version=1")
1032n/a h = interact_2965(c, url)
1033n/a self.assertNotIn("Path", h, "absent path returned with path present")
1034n/a
1035n/a c = CookieJar(pol)
1036n/a url = "http://foo.bar.com/"
1037n/a interact_2965(c, url, 'spam=eggs; Version=1; Path=/')
1038n/a h = interact_2965(c, url)
1039n/a self.assertIn('$Path="/"', h, "path not returned")
1040n/a
1041n/a def test_port_mirror(self):
1042n/a pol = DefaultCookiePolicy(rfc2965=True)
1043n/a
1044n/a c = CookieJar(pol)
1045n/a url = "http://foo.bar.com/"
1046n/a interact_2965(c, url, "spam=eggs; Version=1")
1047n/a h = interact_2965(c, url)
1048n/a self.assertNotIn("Port", h, "absent port returned with port present")
1049n/a
1050n/a c = CookieJar(pol)
1051n/a url = "http://foo.bar.com/"
1052n/a interact_2965(c, url, "spam=eggs; Version=1; Port")
1053n/a h = interact_2965(c, url)
1054n/a self.assertRegex(h, r"\$Port([^=]|$)",
1055n/a "port with no value not returned with no value")
1056n/a
1057n/a c = CookieJar(pol)
1058n/a url = "http://foo.bar.com/"
1059n/a interact_2965(c, url, 'spam=eggs; Version=1; Port="80"')
1060n/a h = interact_2965(c, url)
1061n/a self.assertIn('$Port="80"', h,
1062n/a "port with single value not returned with single value")
1063n/a
1064n/a c = CookieJar(pol)
1065n/a url = "http://foo.bar.com/"
1066n/a interact_2965(c, url, 'spam=eggs; Version=1; Port="80,8080"')
1067n/a h = interact_2965(c, url)
1068n/a self.assertIn('$Port="80,8080"', h,
1069n/a "port with multiple values not returned with multiple "
1070n/a "values")
1071n/a
1072n/a def test_no_return_comment(self):
1073n/a c = CookieJar(DefaultCookiePolicy(rfc2965=True))
1074n/a url = "http://foo.bar.com/"
1075n/a interact_2965(c, url, 'spam=eggs; Version=1; '
1076n/a 'Comment="does anybody read these?"; '
1077n/a 'CommentURL="http://foo.bar.net/comment.html"')
1078n/a h = interact_2965(c, url)
1079n/a self.assertNotIn("Comment", h,
1080n/a "Comment or CommentURL cookie-attributes returned to server")
1081n/a
1082n/a def test_Cookie_iterator(self):
1083n/a cs = CookieJar(DefaultCookiePolicy(rfc2965=True))
1084n/a # add some random cookies
1085n/a interact_2965(cs, "http://blah.spam.org/", 'foo=eggs; Version=1; '
1086n/a 'Comment="does anybody read these?"; '
1087n/a 'CommentURL="http://foo.bar.net/comment.html"')
1088n/a interact_netscape(cs, "http://www.acme.com/blah/", "spam=bar; secure")
1089n/a interact_2965(cs, "http://www.acme.com/blah/",
1090n/a "foo=bar; secure; Version=1")
1091n/a interact_2965(cs, "http://www.acme.com/blah/",
1092n/a "foo=bar; path=/; Version=1")
1093n/a interact_2965(cs, "http://www.sol.no",
1094n/a r'bang=wallop; version=1; domain=".sol.no"; '
1095n/a r'port="90,100, 80,8080"; '
1096n/a r'max-age=100; Comment = "Just kidding! (\"|\\\\) "')
1097n/a
1098n/a versions = [1, 1, 1, 0, 1]
1099n/a names = ["bang", "foo", "foo", "spam", "foo"]
1100n/a domains = [".sol.no", "blah.spam.org", "www.acme.com",
1101n/a "www.acme.com", "www.acme.com"]
1102n/a paths = ["/", "/", "/", "/blah", "/blah/"]
1103n/a
1104n/a for i in range(4):
1105n/a i = 0
1106n/a for c in cs:
1107n/a self.assertIsInstance(c, Cookie)
1108n/a self.assertEqual(c.version, versions[i])
1109n/a self.assertEqual(c.name, names[i])
1110n/a self.assertEqual(c.domain, domains[i])
1111n/a self.assertEqual(c.path, paths[i])
1112n/a i = i + 1
1113n/a
1114n/a def test_parse_ns_headers(self):
1115n/a # missing domain value (invalid cookie)
1116n/a self.assertEqual(
1117n/a parse_ns_headers(["foo=bar; path=/; domain"]),
1118n/a [[("foo", "bar"),
1119n/a ("path", "/"), ("domain", None), ("version", "0")]]
1120n/a )
1121n/a # invalid expires value
1122n/a self.assertEqual(
1123n/a parse_ns_headers(["foo=bar; expires=Foo Bar 12 33:22:11 2000"]),
1124n/a [[("foo", "bar"), ("expires", None), ("version", "0")]]
1125n/a )
1126n/a # missing cookie value (valid cookie)
1127n/a self.assertEqual(
1128n/a parse_ns_headers(["foo"]),
1129n/a [[("foo", None), ("version", "0")]]
1130n/a )
1131n/a # missing cookie values for parsed attributes
1132n/a self.assertEqual(
1133n/a parse_ns_headers(['foo=bar; expires']),
1134n/a [[('foo', 'bar'), ('expires', None), ('version', '0')]])
1135n/a self.assertEqual(
1136n/a parse_ns_headers(['foo=bar; version']),
1137n/a [[('foo', 'bar'), ('version', None)]])
1138n/a # shouldn't add version if header is empty
1139n/a self.assertEqual(parse_ns_headers([""]), [])
1140n/a
1141n/a def test_bad_cookie_header(self):
1142n/a
1143n/a def cookiejar_from_cookie_headers(headers):
1144n/a c = CookieJar()
1145n/a req = urllib.request.Request("http://www.example.com/")
1146n/a r = FakeResponse(headers, "http://www.example.com/")
1147n/a c.extract_cookies(r, req)
1148n/a return c
1149n/a
1150n/a future = time2netscape(time.time()+3600)
1151n/a
1152n/a # none of these bad headers should cause an exception to be raised
1153n/a for headers in [
1154n/a ["Set-Cookie: "], # actually, nothing wrong with this
1155n/a ["Set-Cookie2: "], # ditto
1156n/a # missing domain value
1157n/a ["Set-Cookie2: a=foo; path=/; Version=1; domain"],
1158n/a # bad max-age
1159n/a ["Set-Cookie: b=foo; max-age=oops"],
1160n/a # bad version
1161n/a ["Set-Cookie: b=foo; version=spam"],
1162n/a ["Set-Cookie:; Expires=%s" % future],
1163n/a ]:
1164n/a c = cookiejar_from_cookie_headers(headers)
1165n/a # these bad cookies shouldn't be set
1166n/a self.assertEqual(len(c), 0)
1167n/a
1168n/a # cookie with invalid expires is treated as session cookie
1169n/a headers = ["Set-Cookie: c=foo; expires=Foo Bar 12 33:22:11 2000"]
1170n/a c = cookiejar_from_cookie_headers(headers)
1171n/a cookie = c._cookies["www.example.com"]["/"]["c"]
1172n/a self.assertIsNone(cookie.expires)
1173n/a
1174n/a
1175n/aclass LWPCookieTests(unittest.TestCase):
1176n/a # Tests taken from libwww-perl, with a few modifications and additions.
1177n/a
1178n/a def test_netscape_example_1(self):
1179n/a #-------------------------------------------------------------------
1180n/a # First we check that it works for the original example at
1181n/a # http://www.netscape.com/newsref/std/cookie_spec.html
1182n/a
1183n/a # Client requests a document, and receives in the response:
1184n/a #
1185n/a # Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/; expires=Wednesday, 09-Nov-99 23:12:40 GMT
1186n/a #
1187n/a # When client requests a URL in path "/" on this server, it sends:
1188n/a #
1189n/a # Cookie: CUSTOMER=WILE_E_COYOTE
1190n/a #
1191n/a # Client requests a document, and receives in the response:
1192n/a #
1193n/a # Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/
1194n/a #
1195n/a # When client requests a URL in path "/" on this server, it sends:
1196n/a #
1197n/a # Cookie: CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001
1198n/a #
1199n/a # Client receives:
1200n/a #
1201n/a # Set-Cookie: SHIPPING=FEDEX; path=/fo
1202n/a #
1203n/a # When client requests a URL in path "/" on this server, it sends:
1204n/a #
1205n/a # Cookie: CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001
1206n/a #
1207n/a # When client requests a URL in path "/foo" on this server, it sends:
1208n/a #
1209n/a # Cookie: CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001; SHIPPING=FEDEX
1210n/a #
1211n/a # The last Cookie is buggy, because both specifications say that the
1212n/a # most specific cookie must be sent first. SHIPPING=FEDEX is the
1213n/a # most specific and should thus be first.
1214n/a
1215n/a year_plus_one = time.localtime()[0] + 1
1216n/a
1217n/a headers = []
1218n/a
1219n/a c = CookieJar(DefaultCookiePolicy(rfc2965 = True))
1220n/a
1221n/a #req = urllib.request.Request("http://1.1.1.1/",
1222n/a # headers={"Host": "www.acme.com:80"})
1223n/a req = urllib.request.Request("http://www.acme.com:80/",
1224n/a headers={"Host": "www.acme.com:80"})
1225n/a
1226n/a headers.append(
1227n/a "Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/ ; "
1228n/a "expires=Wednesday, 09-Nov-%d 23:12:40 GMT" % year_plus_one)
1229n/a res = FakeResponse(headers, "http://www.acme.com/")
1230n/a c.extract_cookies(res, req)
1231n/a
1232n/a req = urllib.request.Request("http://www.acme.com/")
1233n/a c.add_cookie_header(req)
1234n/a
1235n/a self.assertEqual(req.get_header("Cookie"), "CUSTOMER=WILE_E_COYOTE")
1236n/a self.assertEqual(req.get_header("Cookie2"), '$Version="1"')
1237n/a
1238n/a headers.append("Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/")
1239n/a res = FakeResponse(headers, "http://www.acme.com/")
1240n/a c.extract_cookies(res, req)
1241n/a
1242n/a req = urllib.request.Request("http://www.acme.com/foo/bar")
1243n/a c.add_cookie_header(req)
1244n/a
1245n/a h = req.get_header("Cookie")
1246n/a self.assertIn("PART_NUMBER=ROCKET_LAUNCHER_0001", h)
1247n/a self.assertIn("CUSTOMER=WILE_E_COYOTE", h)
1248n/a
1249n/a headers.append('Set-Cookie: SHIPPING=FEDEX; path=/foo')
1250n/a res = FakeResponse(headers, "http://www.acme.com")
1251n/a c.extract_cookies(res, req)
1252n/a
1253n/a req = urllib.request.Request("http://www.acme.com/")
1254n/a c.add_cookie_header(req)
1255n/a
1256n/a h = req.get_header("Cookie")
1257n/a self.assertIn("PART_NUMBER=ROCKET_LAUNCHER_0001", h)
1258n/a self.assertIn("CUSTOMER=WILE_E_COYOTE", h)
1259n/a self.assertNotIn("SHIPPING=FEDEX", h)
1260n/a
1261n/a req = urllib.request.Request("http://www.acme.com/foo/")
1262n/a c.add_cookie_header(req)
1263n/a
1264n/a h = req.get_header("Cookie")
1265n/a self.assertIn("PART_NUMBER=ROCKET_LAUNCHER_0001", h)
1266n/a self.assertIn("CUSTOMER=WILE_E_COYOTE", h)
1267n/a self.assertTrue(h.startswith("SHIPPING=FEDEX;"))
1268n/a
1269n/a def test_netscape_example_2(self):
1270n/a # Second Example transaction sequence:
1271n/a #
1272n/a # Assume all mappings from above have been cleared.
1273n/a #
1274n/a # Client receives:
1275n/a #
1276n/a # Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/
1277n/a #
1278n/a # When client requests a URL in path "/" on this server, it sends:
1279n/a #
1280n/a # Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001
1281n/a #
1282n/a # Client receives:
1283n/a #
1284n/a # Set-Cookie: PART_NUMBER=RIDING_ROCKET_0023; path=/ammo
1285n/a #
1286n/a # When client requests a URL in path "/ammo" on this server, it sends:
1287n/a #
1288n/a # Cookie: PART_NUMBER=RIDING_ROCKET_0023; PART_NUMBER=ROCKET_LAUNCHER_0001
1289n/a #
1290n/a # NOTE: There are two name/value pairs named "PART_NUMBER" due to
1291n/a # the inheritance of the "/" mapping in addition to the "/ammo" mapping.
1292n/a
1293n/a c = CookieJar()
1294n/a headers = []
1295n/a
1296n/a req = urllib.request.Request("http://www.acme.com/")
1297n/a headers.append("Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/")
1298n/a res = FakeResponse(headers, "http://www.acme.com/")
1299n/a
1300n/a c.extract_cookies(res, req)
1301n/a
1302n/a req = urllib.request.Request("http://www.acme.com/")
1303n/a c.add_cookie_header(req)
1304n/a
1305n/a self.assertEqual(req.get_header("Cookie"),
1306n/a "PART_NUMBER=ROCKET_LAUNCHER_0001")
1307n/a
1308n/a headers.append(
1309n/a "Set-Cookie: PART_NUMBER=RIDING_ROCKET_0023; path=/ammo")
1310n/a res = FakeResponse(headers, "http://www.acme.com/")
1311n/a c.extract_cookies(res, req)
1312n/a
1313n/a req = urllib.request.Request("http://www.acme.com/ammo")
1314n/a c.add_cookie_header(req)
1315n/a
1316n/a self.assertRegex(req.get_header("Cookie"),
1317n/a r"PART_NUMBER=RIDING_ROCKET_0023;\s*"
1318n/a "PART_NUMBER=ROCKET_LAUNCHER_0001")
1319n/a
1320n/a def test_ietf_example_1(self):
1321n/a #-------------------------------------------------------------------
1322n/a # Then we test with the examples from draft-ietf-http-state-man-mec-03.txt
1323n/a #
1324n/a # 5. EXAMPLES
1325n/a
1326n/a c = CookieJar(DefaultCookiePolicy(rfc2965=True))
1327n/a
1328n/a #
1329n/a # 5.1 Example 1
1330n/a #
1331n/a # Most detail of request and response headers has been omitted. Assume
1332n/a # the user agent has no stored cookies.
1333n/a #
1334n/a # 1. User Agent -> Server
1335n/a #
1336n/a # POST /acme/login HTTP/1.1
1337n/a # [form data]
1338n/a #
1339n/a # User identifies self via a form.
1340n/a #
1341n/a # 2. Server -> User Agent
1342n/a #
1343n/a # HTTP/1.1 200 OK
1344n/a # Set-Cookie2: Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"
1345n/a #
1346n/a # Cookie reflects user's identity.
1347n/a
1348n/a cookie = interact_2965(
1349n/a c, 'http://www.acme.com/acme/login',
1350n/a 'Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"')
1351n/a self.assertFalse(cookie)
1352n/a
1353n/a #
1354n/a # 3. User Agent -> Server
1355n/a #
1356n/a # POST /acme/pickitem HTTP/1.1
1357n/a # Cookie: $Version="1"; Customer="WILE_E_COYOTE"; $Path="/acme"
1358n/a # [form data]
1359n/a #
1360n/a # User selects an item for ``shopping basket.''
1361n/a #
1362n/a # 4. Server -> User Agent
1363n/a #
1364n/a # HTTP/1.1 200 OK
1365n/a # Set-Cookie2: Part_Number="Rocket_Launcher_0001"; Version="1";
1366n/a # Path="/acme"
1367n/a #
1368n/a # Shopping basket contains an item.
1369n/a
1370n/a cookie = interact_2965(c, 'http://www.acme.com/acme/pickitem',
1371n/a 'Part_Number="Rocket_Launcher_0001"; '
1372n/a 'Version="1"; Path="/acme"');
1373n/a self.assertRegex(cookie,
1374n/a r'^\$Version="?1"?; Customer="?WILE_E_COYOTE"?; \$Path="/acme"$')
1375n/a
1376n/a #
1377n/a # 5. User Agent -> Server
1378n/a #
1379n/a # POST /acme/shipping HTTP/1.1
1380n/a # Cookie: $Version="1";
1381n/a # Customer="WILE_E_COYOTE"; $Path="/acme";
1382n/a # Part_Number="Rocket_Launcher_0001"; $Path="/acme"
1383n/a # [form data]
1384n/a #
1385n/a # User selects shipping method from form.
1386n/a #
1387n/a # 6. Server -> User Agent
1388n/a #
1389n/a # HTTP/1.1 200 OK
1390n/a # Set-Cookie2: Shipping="FedEx"; Version="1"; Path="/acme"
1391n/a #
1392n/a # New cookie reflects shipping method.
1393n/a
1394n/a cookie = interact_2965(c, "http://www.acme.com/acme/shipping",
1395n/a 'Shipping="FedEx"; Version="1"; Path="/acme"')
1396n/a
1397n/a self.assertRegex(cookie, r'^\$Version="?1"?;')
1398n/a self.assertRegex(cookie, r'Part_Number="?Rocket_Launcher_0001"?;'
1399n/a r'\s*\$Path="\/acme"')
1400n/a self.assertRegex(cookie, r'Customer="?WILE_E_COYOTE"?;'
1401n/a r'\s*\$Path="\/acme"')
1402n/a
1403n/a #
1404n/a # 7. User Agent -> Server
1405n/a #
1406n/a # POST /acme/process HTTP/1.1
1407n/a # Cookie: $Version="1";
1408n/a # Customer="WILE_E_COYOTE"; $Path="/acme";
1409n/a # Part_Number="Rocket_Launcher_0001"; $Path="/acme";
1410n/a # Shipping="FedEx"; $Path="/acme"
1411n/a # [form data]
1412n/a #
1413n/a # User chooses to process order.
1414n/a #
1415n/a # 8. Server -> User Agent
1416n/a #
1417n/a # HTTP/1.1 200 OK
1418n/a #
1419n/a # Transaction is complete.
1420n/a
1421n/a cookie = interact_2965(c, "http://www.acme.com/acme/process")
1422n/a self.assertRegex(cookie, r'Shipping="?FedEx"?;\s*\$Path="\/acme"')
1423n/a self.assertIn("WILE_E_COYOTE", cookie)
1424n/a
1425n/a #
1426n/a # The user agent makes a series of requests on the origin server, after
1427n/a # each of which it receives a new cookie. All the cookies have the same
1428n/a # Path attribute and (default) domain. Because the request URLs all have
1429n/a # /acme as a prefix, and that matches the Path attribute, each request
1430n/a # contains all the cookies received so far.
1431n/a
1432n/a def test_ietf_example_2(self):
1433n/a # 5.2 Example 2
1434n/a #
1435n/a # This example illustrates the effect of the Path attribute. All detail
1436n/a # of request and response headers has been omitted. Assume the user agent
1437n/a # has no stored cookies.
1438n/a
1439n/a c = CookieJar(DefaultCookiePolicy(rfc2965=True))
1440n/a
1441n/a # Imagine the user agent has received, in response to earlier requests,
1442n/a # the response headers
1443n/a #
1444n/a # Set-Cookie2: Part_Number="Rocket_Launcher_0001"; Version="1";
1445n/a # Path="/acme"
1446n/a #
1447n/a # and
1448n/a #
1449n/a # Set-Cookie2: Part_Number="Riding_Rocket_0023"; Version="1";
1450n/a # Path="/acme/ammo"
1451n/a
1452n/a interact_2965(
1453n/a c, "http://www.acme.com/acme/ammo/specific",
1454n/a 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"',
1455n/a 'Part_Number="Riding_Rocket_0023"; Version="1"; Path="/acme/ammo"')
1456n/a
1457n/a # A subsequent request by the user agent to the (same) server for URLs of
1458n/a # the form /acme/ammo/... would include the following request header:
1459n/a #
1460n/a # Cookie: $Version="1";
1461n/a # Part_Number="Riding_Rocket_0023"; $Path="/acme/ammo";
1462n/a # Part_Number="Rocket_Launcher_0001"; $Path="/acme"
1463n/a #
1464n/a # Note that the NAME=VALUE pair for the cookie with the more specific Path
1465n/a # attribute, /acme/ammo, comes before the one with the less specific Path
1466n/a # attribute, /acme. Further note that the same cookie name appears more
1467n/a # than once.
1468n/a
1469n/a cookie = interact_2965(c, "http://www.acme.com/acme/ammo/...")
1470n/a self.assertRegex(cookie, r"Riding_Rocket_0023.*Rocket_Launcher_0001")
1471n/a
1472n/a # A subsequent request by the user agent to the (same) server for a URL of
1473n/a # the form /acme/parts/ would include the following request header:
1474n/a #
1475n/a # Cookie: $Version="1"; Part_Number="Rocket_Launcher_0001"; $Path="/acme"
1476n/a #
1477n/a # Here, the second cookie's Path attribute /acme/ammo is not a prefix of
1478n/a # the request URL, /acme/parts/, so the cookie does not get forwarded to
1479n/a # the server.
1480n/a
1481n/a cookie = interact_2965(c, "http://www.acme.com/acme/parts/")
1482n/a self.assertIn("Rocket_Launcher_0001", cookie)
1483n/a self.assertNotIn("Riding_Rocket_0023", cookie)
1484n/a
1485n/a def test_rejection(self):
1486n/a # Test rejection of Set-Cookie2 responses based on domain, path, port.
1487n/a pol = DefaultCookiePolicy(rfc2965=True)
1488n/a
1489n/a c = LWPCookieJar(policy=pol)
1490n/a
1491n/a max_age = "max-age=3600"
1492n/a
1493n/a # illegal domain (no embedded dots)
1494n/a cookie = interact_2965(c, "http://www.acme.com",
1495n/a 'foo=bar; domain=".com"; version=1')
1496n/a self.assertFalse(c)
1497n/a
1498n/a # legal domain
1499n/a cookie = interact_2965(c, "http://www.acme.com",
1500n/a 'ping=pong; domain="acme.com"; version=1')
1501n/a self.assertEqual(len(c), 1)
1502n/a
1503n/a # illegal domain (host prefix "www.a" contains a dot)
1504n/a cookie = interact_2965(c, "http://www.a.acme.com",
1505n/a 'whiz=bang; domain="acme.com"; version=1')
1506n/a self.assertEqual(len(c), 1)
1507n/a
1508n/a # legal domain
1509n/a cookie = interact_2965(c, "http://www.a.acme.com",
1510n/a 'wow=flutter; domain=".a.acme.com"; version=1')
1511n/a self.assertEqual(len(c), 2)
1512n/a
1513n/a # can't partially match an IP-address
1514n/a cookie = interact_2965(c, "http://125.125.125.125",
1515n/a 'zzzz=ping; domain="125.125.125"; version=1')
1516n/a self.assertEqual(len(c), 2)
1517n/a
1518n/a # illegal path (must be prefix of request path)
1519n/a cookie = interact_2965(c, "http://www.sol.no",
1520n/a 'blah=rhubarb; domain=".sol.no"; path="/foo"; '
1521n/a 'version=1')
1522n/a self.assertEqual(len(c), 2)
1523n/a
1524n/a # legal path
1525n/a cookie = interact_2965(c, "http://www.sol.no/foo/bar",
1526n/a 'bing=bong; domain=".sol.no"; path="/foo"; '
1527n/a 'version=1')
1528n/a self.assertEqual(len(c), 3)
1529n/a
1530n/a # illegal port (request-port not in list)
1531n/a cookie = interact_2965(c, "http://www.sol.no",
1532n/a 'whiz=ffft; domain=".sol.no"; port="90,100"; '
1533n/a 'version=1')
1534n/a self.assertEqual(len(c), 3)
1535n/a
1536n/a # legal port
1537n/a cookie = interact_2965(
1538n/a c, "http://www.sol.no",
1539n/a r'bang=wallop; version=1; domain=".sol.no"; '
1540n/a r'port="90,100, 80,8080"; '
1541n/a r'max-age=100; Comment = "Just kidding! (\"|\\\\) "')
1542n/a self.assertEqual(len(c), 4)
1543n/a
1544n/a # port attribute without any value (current port)
1545n/a cookie = interact_2965(c, "http://www.sol.no",
1546n/a 'foo9=bar; version=1; domain=".sol.no"; port; '
1547n/a 'max-age=100;')
1548n/a self.assertEqual(len(c), 5)
1549n/a
1550n/a # encoded path
1551n/a # LWP has this test, but unescaping allowed path characters seems
1552n/a # like a bad idea, so I think this should fail:
1553n/a## cookie = interact_2965(c, "http://www.sol.no/foo/",
1554n/a## r'foo8=bar; version=1; path="/%66oo"')
1555n/a # but this is OK, because '<' is not an allowed HTTP URL path
1556n/a # character:
1557n/a cookie = interact_2965(c, "http://www.sol.no/<oo/",
1558n/a r'foo8=bar; version=1; path="/%3coo"')
1559n/a self.assertEqual(len(c), 6)
1560n/a
1561n/a # save and restore
1562n/a filename = test.support.TESTFN
1563n/a
1564n/a try:
1565n/a c.save(filename, ignore_discard=True)
1566n/a old = repr(c)
1567n/a
1568n/a c = LWPCookieJar(policy=pol)
1569n/a c.load(filename, ignore_discard=True)
1570n/a finally:
1571n/a try: os.unlink(filename)
1572n/a except OSError: pass
1573n/a
1574n/a self.assertEqual(old, repr(c))
1575n/a
1576n/a def test_url_encoding(self):
1577n/a # Try some URL encodings of the PATHs.
1578n/a # (the behaviour here has changed from libwww-perl)
1579n/a c = CookieJar(DefaultCookiePolicy(rfc2965=True))
1580n/a interact_2965(c, "http://www.acme.com/foo%2f%25/"
1581n/a "%3c%3c%0Anew%C3%A5/%C3%A5",
1582n/a "foo = bar; version = 1")
1583n/a
1584n/a cookie = interact_2965(
1585n/a c, "http://www.acme.com/foo%2f%25/<<%0anew\345/\346\370\345",
1586n/a 'bar=baz; path="/foo/"; version=1');
1587n/a version_re = re.compile(r'^\$version=\"?1\"?', re.I)
1588n/a self.assertIn("foo=bar", cookie)
1589n/a self.assertRegex(cookie, version_re)
1590n/a
1591n/a cookie = interact_2965(
1592n/a c, "http://www.acme.com/foo/%25/<<%0anew\345/\346\370\345")
1593n/a self.assertFalse(cookie)
1594n/a
1595n/a # unicode URL doesn't raise exception
1596n/a cookie = interact_2965(c, "http://www.acme.com/\xfc")
1597n/a
1598n/a def test_mozilla(self):
1599n/a # Save / load Mozilla/Netscape cookie file format.
1600n/a year_plus_one = time.localtime()[0] + 1
1601n/a
1602n/a filename = test.support.TESTFN
1603n/a
1604n/a c = MozillaCookieJar(filename,
1605n/a policy=DefaultCookiePolicy(rfc2965=True))
1606n/a interact_2965(c, "http://www.acme.com/",
1607n/a "foo1=bar; max-age=100; Version=1")
1608n/a interact_2965(c, "http://www.acme.com/",
1609n/a 'foo2=bar; port="80"; max-age=100; Discard; Version=1')
1610n/a interact_2965(c, "http://www.acme.com/", "foo3=bar; secure; Version=1")
1611n/a
1612n/a expires = "expires=09-Nov-%d 23:12:40 GMT" % (year_plus_one,)
1613n/a interact_netscape(c, "http://www.foo.com/",
1614n/a "fooa=bar; %s" % expires)
1615n/a interact_netscape(c, "http://www.foo.com/",
1616n/a "foob=bar; Domain=.foo.com; %s" % expires)
1617n/a interact_netscape(c, "http://www.foo.com/",
1618n/a "fooc=bar; Domain=www.foo.com; %s" % expires)
1619n/a
1620n/a def save_and_restore(cj, ignore_discard):
1621n/a try:
1622n/a cj.save(ignore_discard=ignore_discard)
1623n/a new_c = MozillaCookieJar(filename,
1624n/a DefaultCookiePolicy(rfc2965=True))
1625n/a new_c.load(ignore_discard=ignore_discard)
1626n/a finally:
1627n/a try: os.unlink(filename)
1628n/a except OSError: pass
1629n/a return new_c
1630n/a
1631n/a new_c = save_and_restore(c, True)
1632n/a self.assertEqual(len(new_c), 6) # none discarded
1633n/a self.assertIn("name='foo1', value='bar'", repr(new_c))
1634n/a
1635n/a new_c = save_and_restore(c, False)
1636n/a self.assertEqual(len(new_c), 4) # 2 of them discarded on save
1637n/a self.assertIn("name='foo1', value='bar'", repr(new_c))
1638n/a
1639n/a def test_netscape_misc(self):
1640n/a # Some additional Netscape cookies tests.
1641n/a c = CookieJar()
1642n/a headers = []
1643n/a req = urllib.request.Request("http://foo.bar.acme.com/foo")
1644n/a
1645n/a # Netscape allows a host part that contains dots
1646n/a headers.append("Set-Cookie: Customer=WILE_E_COYOTE; domain=.acme.com")
1647n/a res = FakeResponse(headers, "http://www.acme.com/foo")
1648n/a c.extract_cookies(res, req)
1649n/a
1650n/a # and that the domain is the same as the host without adding a leading
1651n/a # dot to the domain. Should not quote even if strange chars are used
1652n/a # in the cookie value.
1653n/a headers.append("Set-Cookie: PART_NUMBER=3,4; domain=foo.bar.acme.com")
1654n/a res = FakeResponse(headers, "http://www.acme.com/foo")
1655n/a c.extract_cookies(res, req)
1656n/a
1657n/a req = urllib.request.Request("http://foo.bar.acme.com/foo")
1658n/a c.add_cookie_header(req)
1659n/a self.assertIn("PART_NUMBER=3,4", req.get_header("Cookie"))
1660n/a self.assertIn("Customer=WILE_E_COYOTE",req.get_header("Cookie"))
1661n/a
1662n/a def test_intranet_domains_2965(self):
1663n/a # Test handling of local intranet hostnames without a dot.
1664n/a c = CookieJar(DefaultCookiePolicy(rfc2965=True))
1665n/a interact_2965(c, "http://example/",
1666n/a "foo1=bar; PORT; Discard; Version=1;")
1667n/a cookie = interact_2965(c, "http://example/",
1668n/a 'foo2=bar; domain=".local"; Version=1')
1669n/a self.assertIn("foo1=bar", cookie)
1670n/a
1671n/a interact_2965(c, "http://example/", 'foo3=bar; Version=1')
1672n/a cookie = interact_2965(c, "http://example/")
1673n/a self.assertIn("foo2=bar", cookie)
1674n/a self.assertEqual(len(c), 3)
1675n/a
1676n/a def test_intranet_domains_ns(self):
1677n/a c = CookieJar(DefaultCookiePolicy(rfc2965 = False))
1678n/a interact_netscape(c, "http://example/", "foo1=bar")
1679n/a cookie = interact_netscape(c, "http://example/",
1680n/a 'foo2=bar; domain=.local')
1681n/a self.assertEqual(len(c), 2)
1682n/a self.assertIn("foo1=bar", cookie)
1683n/a
1684n/a cookie = interact_netscape(c, "http://example/")
1685n/a self.assertIn("foo2=bar", cookie)
1686n/a self.assertEqual(len(c), 2)
1687n/a
1688n/a def test_empty_path(self):
1689n/a # Test for empty path
1690n/a # Broken web-server ORION/1.3.38 returns to the client response like
1691n/a #
1692n/a # Set-Cookie: JSESSIONID=ABCDERANDOM123; Path=
1693n/a #
1694n/a # ie. with Path set to nothing.
1695n/a # In this case, extract_cookies() must set cookie to / (root)
1696n/a c = CookieJar(DefaultCookiePolicy(rfc2965 = True))
1697n/a headers = []
1698n/a
1699n/a req = urllib.request.Request("http://www.ants.com/")
1700n/a headers.append("Set-Cookie: JSESSIONID=ABCDERANDOM123; Path=")
1701n/a res = FakeResponse(headers, "http://www.ants.com/")
1702n/a c.extract_cookies(res, req)
1703n/a
1704n/a req = urllib.request.Request("http://www.ants.com/")
1705n/a c.add_cookie_header(req)
1706n/a
1707n/a self.assertEqual(req.get_header("Cookie"),
1708n/a "JSESSIONID=ABCDERANDOM123")
1709n/a self.assertEqual(req.get_header("Cookie2"), '$Version="1"')
1710n/a
1711n/a # missing path in the request URI
1712n/a req = urllib.request.Request("http://www.ants.com:8080")
1713n/a c.add_cookie_header(req)
1714n/a
1715n/a self.assertEqual(req.get_header("Cookie"),
1716n/a "JSESSIONID=ABCDERANDOM123")
1717n/a self.assertEqual(req.get_header("Cookie2"), '$Version="1"')
1718n/a
1719n/a def test_session_cookies(self):
1720n/a year_plus_one = time.localtime()[0] + 1
1721n/a
1722n/a # Check session cookies are deleted properly by
1723n/a # CookieJar.clear_session_cookies method
1724n/a
1725n/a req = urllib.request.Request('http://www.perlmeister.com/scripts')
1726n/a headers = []
1727n/a headers.append("Set-Cookie: s1=session;Path=/scripts")
1728n/a headers.append("Set-Cookie: p1=perm; Domain=.perlmeister.com;"
1729n/a "Path=/;expires=Fri, 02-Feb-%d 23:24:20 GMT" %
1730n/a year_plus_one)
1731n/a headers.append("Set-Cookie: p2=perm;Path=/;expires=Fri, "
1732n/a "02-Feb-%d 23:24:20 GMT" % year_plus_one)
1733n/a headers.append("Set-Cookie: s2=session;Path=/scripts;"
1734n/a "Domain=.perlmeister.com")
1735n/a headers.append('Set-Cookie2: s3=session;Version=1;Discard;Path="/"')
1736n/a res = FakeResponse(headers, 'http://www.perlmeister.com/scripts')
1737n/a
1738n/a c = CookieJar()
1739n/a c.extract_cookies(res, req)
1740n/a # How many session/permanent cookies do we have?
1741n/a counter = {"session_after": 0,
1742n/a "perm_after": 0,
1743n/a "session_before": 0,
1744n/a "perm_before": 0}
1745n/a for cookie in c:
1746n/a key = "%s_before" % cookie.value
1747n/a counter[key] = counter[key] + 1
1748n/a c.clear_session_cookies()
1749n/a # How many now?
1750n/a for cookie in c:
1751n/a key = "%s_after" % cookie.value
1752n/a counter[key] = counter[key] + 1
1753n/a
1754n/a # a permanent cookie got lost accidentally
1755n/a self.assertEqual(counter["perm_after"], counter["perm_before"])
1756n/a # a session cookie hasn't been cleared
1757n/a self.assertEqual(counter["session_after"], 0)
1758n/a # we didn't have session cookies in the first place
1759n/a self.assertNotEqual(counter["session_before"], 0)
1760n/a
1761n/a
1762n/adef test_main(verbose=None):
1763n/a test.support.run_unittest(
1764n/a DateTimeTests,
1765n/a HeaderTests,
1766n/a CookieTests,
1767n/a FileCookieJarTests,
1768n/a LWPCookieTests,
1769n/a )
1770n/a
1771n/aif __name__ == "__main__":
1772n/a test_main(verbose=True)