Debian Codegraph @

test/test_cookies.py

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