Debian Codegraph @

test/test_cookies.py

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