1
# -*- coding: utf-8 -*-
2
"""Tests for ClientCookie._ClientCookie."""
4
import urllib2, re, os, string, StringIO, mimetools, time
5
from time import localtime
6
from unittest import TestCase
8
from ClientCookie._Util import startswith
16
## l = logging.getLogger("ClientCookie")
17
## l.setLevel(logging.DEBUG)
20
def __init__(self, headers=[], url=None):
22
headers: list of RFC822-style 'Key: value' strings
24
f = StringIO.StringIO(string.join(headers, "\n"))
25
self._headers = mimetools.Message(f)
27
def info(self): return self._headers
28
def url(): return self._url
30
def interact_2965(cookiejar, url, *set_cookie_hdrs):
31
return _interact(cookiejar, url, set_cookie_hdrs, "Set-Cookie2")
33
def interact_netscape(cookiejar, url, *set_cookie_hdrs):
34
return _interact(cookiejar, url, set_cookie_hdrs, "Set-Cookie")
36
def _interact(cookiejar, url, set_cookie_hdrs, hdr_name):
37
"""Perform a single request / response cycle, returning Cookie: header."""
38
from ClientCookie import Request
40
cookiejar.add_cookie_header(req)
41
cookie_hdr = req.get_header("Cookie", "")
43
for hdr in set_cookie_hdrs:
44
headers.append("%s: %s" % (hdr_name, hdr))
45
res = FakeResponse(headers, url)
46
cookiejar.extract_cookies(res, req)
50
class CookieTests(TestCase):
52
# IP addresses like 50 (single number, no dot) and domain-matching
53
# functions (and is_HDN)? See draft RFC 2965 errata.
56
# unverifiability / third_party blocking
57
# Netscape cookies work the same as RFC 2965 with regard to port.
58
# Set-Cookie with negative max age.
59
# If turn RFC 2965 handling off, Set-Cookie2 cookies should not clobber
61
# Cookie2 should be sent if *any* cookies are not V1 (ie. V0 OR V2 etc.).
62
# Cookies (V1 and V0) with no expiry date should be set to be discarded.
64
# Should accept unquoted cookie-attribute values? check errata draft.
65
# Which are required on the way in and out?
66
# Should always return quoted cookie-attribute values?
67
# Proper testing of when RFC 2965 clobbers Netscape (waiting for errata).
68
# Path-match on return (same for V0 and V1).
69
# RFC 2965 acceptance and returning rules
70
# Set-Cookie2 without version attribute is rejected.
72
# Netscape peculiarities list from Ronald Tschalar.
73
# The first two still need tests, the rest are covered.
74
## - Quoting: only quotes around the expires value are recognized as such
75
## (and yes, some folks quote the expires value); quotes around any other
76
## value are treated as part of the value.
77
## - White space: white space around names and values is ignored
78
## - Default path: if no path parameter is given, the path defaults to the
79
## path in the request-uri up to, but not including, the last '/'. Note
80
## that this is entirely different from what the spec says.
81
## - Commas and other delimiters: Netscape just parses until the next ';'.
82
## This means it will allow commas etc inside values (and yes, both
83
## commas and equals are commonly appear in the cookie value). This also
84
## means that if you fold multiple Set-Cookie header fields into one,
85
## comma-separated list, it'll be a headache to parse (at least my head
86
## starts hurting everytime I think of that code).
87
## - Expires: You'll get all sorts of date formats in the expires,
88
## including emtpy expires attributes ("expires="). Be as flexible as you
89
## can, and certainly don't expect the weekday to be there; if you can't
90
## parse it, just ignore it and pretend it's a session cookie.
91
## - Domain-matching: Netscape uses the 2-dot rule for _all_ domains, not
92
## just the 7 special TLD's listed in their spec. And folks rely on
95
def test_missing_name(self):
96
from ClientCookie import MozillaCookieJar, lwp_cookie_str
98
# missing = sign in Cookie: header is regarded by Mozilla as a missing
99
# name, and accepted as an anonymous cookie.
100
filename = os.path.abspath("cookies2.txt")
101
c = MozillaCookieJar(filename)
102
interact_netscape(c, "http://www.acme.com/", 'eggs')
103
interact_netscape(c, "http://www.acme.com/", '"spam"; path=/foo/')
104
cookie = c.cookies["www.acme.com"]["/"][None]
105
assert cookie.name is None
106
assert cookie.value == "eggs"
107
cookie = c.cookies["www.acme.com"]['/foo/'][None]
108
assert cookie.name is None
109
assert cookie.value == '"spam"'
110
assert lwp_cookie_str(cookie) == (
111
r'"\"spam\""; path="/foo/"; domain="www.acme.com"; '
112
'path_spec; discard; version=0')
113
old_str = c.as_lwp_str()
114
c.save(ignore_expires=True, ignore_discard=True)
116
c = MozillaCookieJar(filename)
117
c.revert(ignore_expires=True, ignore_discard=True)
119
os.unlink(c.filename)
120
# cookies unchanged apart from lost info re. whether path was specified
121
assert c.as_lwp_str() == re.sub("; path_spec", "", old_str)
122
assert interact_netscape(c, "http://www.acme.com/foo/") == \
125
def test_ns_parser(self):
126
from ClientCookie import CookieJar
127
from ClientCookie._ClientCookie import DEFAULT_HTTP_PORT
130
interact_netscape(c, "http://www.acme.com/",
131
'spam=eggs; DoMain=.acme.com; port; blArgh="feep"')
132
interact_netscape(c, "http://www.acme.com/", 'ni=ni; port=80,8080')
133
interact_netscape(c, "http://www.acme.com:80/", 'nini=ni')
134
interact_netscape(c, "http://www.acme.com:80/", 'foo=bar; expires=')
135
interact_netscape(c, "http://www.acme.com:80/", 'spam=eggs; '
136
'expires="Foo Bar 25 33:22:11 3022"')
138
cookie = c.cookies[".acme.com"]["/"]["spam"]
139
assert cookie.domain == ".acme.com"
140
assert cookie.domain_specified
141
assert cookie.port == DEFAULT_HTTP_PORT
142
assert not cookie.port_specified
144
assert cookie.rest.has_key("blArgh") and not cookie.rest.has_key("blargh")
146
cookie = c.cookies["www.acme.com"]["/"]["ni"]
147
assert cookie.domain == "www.acme.com"
148
assert not cookie.domain_specified
149
assert cookie.port == "80,8080"
150
assert cookie.port_specified
152
cookie = c.cookies["www.acme.com"]["/"]["nini"]
153
assert cookie.port is None
154
assert not cookie.port_specified
156
# invalid expires should not cause cookie to be dropped
157
foo = c.cookies["www.acme.com"]["/"]["foo"]
158
spam = c.cookies["www.acme.com"]["/"]["foo"]
159
assert foo.expires is None
160
assert spam.expires is None
162
def test_expires(self):
163
from ClientCookie._Util import time2netscape
164
from ClientCookie import CookieJar
166
# if expires is in future, keep cookie...
168
future = time2netscape(time.time()+3600)
169
interact_netscape(c, "http://www.acme.com/", 'spam="bar"; expires=%s' %
172
now = time2netscape(time.time()-1)
173
# ... and if in past or present, discard it
174
interact_netscape(c, "http://www.acme.com/", 'foo="eggs"; expires=%s' %
176
h = interact_netscape(c, "http://www.acme.com/")
178
assert string.find(h, 'spam="bar"') != -1 and string.find(h, "foo") == -1
180
# max-age takes precedence over expires, and zero max-age is request to
181
# delete both new cookie and any old matching cookie
182
interact_netscape(c, "http://www.acme.com/", 'eggs="bar"; expires=%s' %
184
interact_netscape(c, "http://www.acme.com/", 'bar="bar"; expires=%s' %
187
interact_netscape(c, "http://www.acme.com/", 'eggs="bar"; '
188
'expires=%s; max-age=0' % future)
189
interact_netscape(c, "http://www.acme.com/", 'bar="bar"; '
190
'max-age=0; expires=%s' % future)
191
h = interact_netscape(c, "http://www.acme.com/")
194
# test expiry at end of session for cookies with no expires attribute
195
interact_netscape(c, "http://www.rhubarb.net/", 'whum="fizz"')
197
c.clear_session_cookies()
199
assert string.find(h, 'spam="bar"') != -1
201
# XXX RFC 2965 expiry rules (some apply to V0 too)
203
def test_default_path(self):
204
from ClientCookie import CookieJar
209
interact_2965(c, "http://www.acme.com/", 'spam="bar"; Version="1"')
210
assert c.cookies["www.acme.com"].has_key("/")
213
interact_2965(c, "http://www.acme.com/blah", 'eggs="bar"; Version="1"')
214
assert c.cookies["www.acme.com"].has_key("/")
217
interact_2965(c, "http://www.acme.com/blah/rhubarb",
218
'eggs="bar"; Version="1"')
219
assert c.cookies["www.acme.com"].has_key("/blah/")
222
interact_2965(c, "http://www.acme.com/blah/rhubarb/",
223
'eggs="bar"; Version="1"')
224
assert c.cookies["www.acme.com"].has_key("/blah/rhubarb/")
229
interact_netscape(c, "http://www.acme.com/", 'spam="bar"')
230
assert c.cookies["www.acme.com"].has_key("/")
233
interact_netscape(c, "http://www.acme.com/blah", 'eggs="bar"')
234
assert c.cookies["www.acme.com"].has_key("/")
237
interact_netscape(c, "http://www.acme.com/blah/rhubarb", 'eggs="bar"')
238
assert c.cookies["www.acme.com"].has_key("/blah")
241
interact_netscape(c, "http://www.acme.com/blah/rhubarb/", 'eggs="bar"')
242
assert c.cookies["www.acme.com"].has_key("/blah/rhubarb")
244
def test_escape_path(self):
245
from ClientCookie._ClientCookie import escape_path
248
("/foo%2f/bar", "/foo%2F/bar"),
249
("/foo%2F/bar", "/foo%2F/bar"),
251
("/foo%%/bar", "/foo%%/bar"),
253
("/fo%19o/bar", "/fo%19o/bar"),
254
("/fo%7do/bar", "/fo%7Do/bar"),
256
("/foo/bar&", "/foo/bar&"),
257
("/foo//bar", "/foo//bar"),
258
("\176/foo/bar", "\176/foo/bar"),
260
("/foo\031/bar", "/foo%19/bar"),
261
("/\175foo/bar", "/%7Dfoo/bar"),
263
# XXXX causes SyntaxError with 1.5.2
271
## (u"/foo/bar\uabcd", "/foo/bar%EA%AF%8D") # UTF-8 encoded
273
for arg, result in cases:
274
self.assert_(escape_path(arg) == result)
276
def test_request_path(self):
277
from urllib2 import Request
278
from ClientCookie._ClientCookie import request_path
280
req = Request("http://www.example.com/rheum/rhaponicum;"
281
"foo=bar;sing=song?apples=pears&spam=eggs#ni")
282
self.assert_(request_path(req) == "/rheum/rhaponicum;"
283
"foo=bar;sing=song?apples=pears&spam=eggs#ni")
285
req = Request("http://www.example.com/rheum/rhaponicum?"
286
"apples=pears&spam=eggs#ni")
287
self.assert_(request_path(req) == "/rheum/rhaponicum?"
288
"apples=pears&spam=eggs#ni")
289
# missing final slash
290
req = Request("http://www.example.com")
291
self.assert_(request_path(req) == "/")
293
def test_request_port(self):
294
from ClientCookie import Request
295
from ClientCookie._ClientCookie import request_port, DEFAULT_HTTP_PORT
296
req = Request("http://www.acme.com:1234/",
297
headers={"Host": "www.acme.com:4321"})
298
assert request_port(req) == "1234"
299
req = Request("http://www.acme.com/",
300
headers={"Host": "www.acme.com:4321"})
301
assert request_port(req) == DEFAULT_HTTP_PORT
303
def test_request_host(self):
304
from ClientCookie import Request
305
from ClientCookie._ClientCookie import request_host
306
# this request is illegal (RFC2616, 14.2.3)
307
req = Request("http://1.1.1.1/",
308
headers={"Host": "www.acme.com:80"})
309
# libwww-perl wants this response, but that seems wrong (RFC 2616,
310
# section 5.2, point 1., and RFC 2965 section 1, paragraph 3)
311
#assert request_host(req) == "www.acme.com"
312
assert request_host(req) == "1.1.1.1"
313
req = Request("http://www.acme.com/",
314
headers={"Host": "irrelevant.com"})
315
assert request_host(req) == "www.acme.com"
316
# not actually sure this one is valid Request object, so maybe should
317
# remove test for no host in url in request_host function?
318
req = Request("/resource.html",
319
headers={"Host": "www.acme.com"})
320
assert request_host(req) == "www.acme.com"
321
# port shouldn't be in request-host
322
req = Request("http://www.acme.com:2345/resource.html",
323
headers={"Host": "www.acme.com:5432"})
324
assert request_host(req) == "www.acme.com"
326
def test_is_HDN(self):
327
from ClientCookie._ClientCookie import is_HDN
328
assert is_HDN("foo.bar.com")
329
assert is_HDN("1foo2.3bar4.5com")
330
assert not is_HDN("192.168.1.1")
331
assert not is_HDN("")
332
assert not is_HDN(".")
333
assert not is_HDN(".foo.bar.com")
334
assert not is_HDN("..foo")
335
assert not is_HDN("foo.")
337
def test_reach(self):
338
from ClientCookie._ClientCookie import reach
339
assert reach("www.acme.com") == ".acme.com"
340
assert reach("acme.com") == "acme.com"
341
assert reach("acme.local") == ".local"
342
assert reach(".local") == ".local"
343
assert reach(".com") == ".com"
344
assert reach(".") == "."
345
assert reach("") == ""
346
assert reach("192.168.0.1") == "192.168.0.1"
348
def test_domain_match(self):
349
from ClientCookie._ClientCookie import domain_match, user_domain_match
350
assert domain_match("192.168.1.1", "192.168.1.1")
351
assert not domain_match("192.168.1.1", ".168.1.1")
352
assert domain_match("x.y.com", "x.Y.com")
353
assert domain_match("x.y.com", ".Y.com")
354
assert not domain_match("x.y.com", "Y.com")
355
assert domain_match("a.b.c.com", ".c.com")
356
assert not domain_match(".c.com", "a.b.c.com")
357
assert domain_match("example.local", ".local")
358
assert not domain_match("blah.blah", "")
359
assert not domain_match("", ".rhubarb.rhubarb")
360
assert domain_match("", "")
362
assert user_domain_match("acme.com", "acme.com")
363
assert not user_domain_match("acme.com", ".acme.com")
364
assert user_domain_match("rhubarb.acme.com", ".acme.com")
365
assert user_domain_match("www.rhubarb.acme.com", ".acme.com")
366
assert user_domain_match("x.y.com", "x.Y.com")
367
assert user_domain_match("x.y.com", ".Y.com")
368
assert not user_domain_match("x.y.com", "Y.com")
369
assert user_domain_match("y.com", "Y.com")
370
assert not user_domain_match(".y.com", "Y.com")
371
assert user_domain_match(".y.com", ".Y.com")
372
assert user_domain_match("x.y.com", ".com")
373
assert not user_domain_match("x.y.com", "com")
374
assert not user_domain_match("x.y.com", "m")
375
assert not user_domain_match("x.y.com", ".m")
376
assert not user_domain_match("x.y.com", "")
377
assert not user_domain_match("x.y.com", ".")
378
assert user_domain_match("192.168.1.1", "192.168.1.1")
379
# not both HDNs, so must string-compare equal to match
380
assert not user_domain_match("192.168.1.1", ".168.1.1")
381
assert not user_domain_match("192.168.1.1", ".")
382
# empty string is a special case
383
assert not user_domain_match("192.168.1.1", "")
385
def test_wrong_domain(self):
386
"""Cookies whose ERH does not domain-match the domain are rejected.
388
ERH = effective request-host.
391
# XXX far from complete
392
from ClientCookie import CookieJar
394
interact_2965(c, "http://www.nasty.com/", 'foo=bar; domain=friendly.org; Version="1"')
397
def test_two_component_domain_ns(self):
398
# Netscape: .www.bar.com, www.bar.com, .bar.com, bar.com, no domain should
399
# all get accepted, as should .acme.com, acme.com and no domain for
400
# 2-component domains like acme.com.
401
from ClientCookie import CookieJar, DefaultCookiePolicy
405
# two-component V0 domain is OK
406
interact_netscape(c, "http://foo.net/", 'ns=bar')
408
assert c.cookies["foo.net"]["/"]["ns"].value == "bar"
409
assert interact_netscape(c, "http://foo.net/") == "ns=bar"
410
# *will* be returned to any other domain (unlike RFC 2965)...
411
assert interact_netscape(c, "http://www.foo.net/") == "ns=bar"
412
# ...unless requested otherwise
413
c.policy.strict_ns_domain = DefaultCookiePolicy.DomainStrictNonDomain
414
assert interact_netscape(c, "http://www.foo.net/") == ""
416
# unlike RFC 2965, even explicit two-component domain is OK,
417
# because .foo.net matches foo.net
418
interact_netscape(c, "http://foo.net/foo/",
419
'spam1=eggs; domain=foo.net')
420
# even if starts with a dot -- in NS rules, .foo.net matches foo.net!
421
interact_netscape(c, "http://foo.net/foo/bar/",
422
'spam2=eggs; domain=.foo.net')
424
assert c.cookies[".foo.net"]["/foo"]["spam1"].value == "eggs"
425
assert c.cookies[".foo.net"]["/foo/bar"]["spam2"].value == "eggs"
426
assert interact_netscape(c, "http://foo.net/foo/bar/") == \
427
"spam2=eggs; spam1=eggs; ns=bar"
429
# top-level domain is too general
430
interact_netscape(c, "http://foo.net/", 'nini="ni"; domain=.net')
433
## # Netscape protocol doesn't allow non-special top level domains (such
434
## # as co.uk) in the domain attribute unless there are at least three
436
# Oh yes it does! Real implementations don't check this, and real
437
# cookies (of course) rely on that behaviour.
438
interact_netscape(c, "http://foo.co.uk", 'nasty=trick; domain=.co.uk')
439
## assert len(c) == 2
442
def test_two_component_domain_rfc2965(self):
443
from ClientCookie import CookieJar
447
# two-component V1 domain is OK
448
interact_2965(c, "http://foo.net/", 'foo=bar; Version="1"')
450
assert c.cookies["foo.net"]["/"]["foo"].value == "bar"
451
assert interact_2965(c, "http://foo.net/") == "$Version=1; foo=bar"
452
# won't be returned to any other domain (because domain was implied)
453
assert interact_2965(c, "http://www.foo.net/") == ""
455
# unless domain is given explicitly, because then it must be
456
# rewritten to start with a dot: foo.net --> .foo.net, which does
457
# not domain-match foo.net
458
interact_2965(c, "http://foo.net/foo",
459
'spam=eggs; domain=foo.net; path=/foo; Version="1"')
461
assert interact_2965(c, "http://foo.net/foo") == "$Version=1; foo=bar"
463
# explicit foo.net from three-component domain www.foo.net *does* get
464
# set, because .foo.net domain-matches .foo.net
465
interact_2965(c, "http://www.foo.net/foo/",
466
'spam=eggs; domain=foo.net; Version="1"')
467
assert c.cookies[".foo.net"]["/foo/"]["spam"].value == "eggs"
469
assert interact_2965(c, "http://foo.net/foo/") == "$Version=1; foo=bar"
470
assert interact_2965(c, "http://www.foo.net/foo/") == \
471
'$Version=1; spam=eggs; $Domain="foo.net"'
473
# top-level domain is too general
474
interact_2965(c, "http://foo.net/",
475
'ni="ni"; domain=".net"; Version="1"')
478
# RFC 2965 doesn't require blocking this
479
interact_2965(c, "http://foo.co.uk/",
480
'nasty=trick; domain=.co.uk; Version="1"')
483
def test_domain_allow(self):
484
from ClientCookie import CookieJar, DefaultCookiePolicy, Request
486
c = CookieJar(policy=DefaultCookiePolicy(
487
blocked_domains=["acme.com"],
488
allowed_domains=["www.acme.com"]))
490
req = Request("http://acme.com/")
491
headers = ["Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/"]
492
res = FakeResponse(headers, "http://acme.com/")
493
c.extract_cookies(res, req)
496
req = Request("http://www.acme.com/")
497
res = FakeResponse(headers, "http://www.acme.com/")
498
c.extract_cookies(res, req)
501
req = Request("http://www.coyote.com/")
502
res = FakeResponse(headers, "http://www.coyote.com/")
503
c.extract_cookies(res, req)
506
# set a cookie with non-allowed domain...
507
req = Request("http://www.coyote.com/")
508
res = FakeResponse(headers, "http://www.coyote.com/")
509
cookies = c.make_cookies(res, req)
510
c.set_cookie(cookies[0])
512
# ... and check is doesn't get returned
513
c.add_cookie_header(req)
514
assert not req.has_header("Cookie")
516
def test_domain_block(self):
517
from ClientCookie import CookieJar, DefaultCookiePolicy, Request
519
c = CookieJar(policy=DefaultCookiePolicy(
520
blocked_domains=[".acme.com"]))
521
headers = ["Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/"]
523
req = Request("http://www.acme.com/")
524
res = FakeResponse(headers, "http://www.acme.com/")
525
c.extract_cookies(res, req)
528
c.policy.set_blocked_domains(["acme.com"])
529
c.extract_cookies(res, req)
533
req = Request("http://www.roadrunner.net/")
534
res = FakeResponse(headers, "http://www.roadrunner.net/")
535
c.extract_cookies(res, req)
537
req = Request("http://www.roadrunner.net/")
538
c.add_cookie_header(req)
539
assert (req.has_header("Cookie") and
540
req.has_header("Cookie2"))
543
c.policy.set_blocked_domains([".acme.com"])
544
c.extract_cookies(res, req)
547
# set a cookie with blocked domain...
548
req = Request("http://www.acme.com/")
549
res = FakeResponse(headers, "http://www.acme.com/")
550
cookies = c.make_cookies(res, req)
551
c.set_cookie(cookies[0])
553
# ... and check is doesn't get returned
554
c.add_cookie_header(req)
555
assert not req.has_header("Cookie")
557
def test_secure(self):
558
from ClientCookie import CookieJar, DefaultCookiePolicy
560
for ns in True, False:
561
for whitespace in " ", "":
564
c.policy.rfc2965 = False
565
int = interact_netscape
568
c.policy.rfc2965 = True
571
url = "http://www.acme.com/"
572
int(c, url, "foo1=bar%s%s" % (vs, whitespace))
573
int(c, url, "foo2=bar%s; secure%s" % (vs, whitespace))
574
assert not c.cookies["www.acme.com"]["/"]["foo1"].secure, \
575
"non-secure cookie registered secure"
576
assert c.cookies["www.acme.com"]["/"]["foo2"].secure, \
577
"secure cookie registered non-secure"
579
def test_quote_cookie_value(self):
580
from ClientCookie import CookieJar
582
interact_2965(c, "http://www.acme.com/", r'foo=\b"a"r; Version=1')
583
h = interact_2965(c, "http://www.acme.com/")
584
assert h == r'$Version=1; foo=\\b\"a\"r'
586
def test_missing_final_slash(self):
587
# Missing slash from request URL's abs_path should be assumed present.
588
from ClientCookie import CookieJar, Request
589
url = "http://www.acme.com"
591
interact_2965(c, url, "foo=bar; Version=1")
594
c.add_cookie_header(req)
595
assert req.has_header("Cookie")
597
def test_domain_mirror(self):
598
from ClientCookie import CookieJar
601
url = "http://foo.bar.com/"
602
interact_2965(c, url, "spam=eggs; Version=1")
603
h = interact_2965(c, url)
604
assert string.find("Domain", h) == -1, \
605
"absent domain returned with domain present"
608
url = "http://foo.bar.com/"
609
interact_2965(c, url, 'spam=eggs; Version=1; Domain=.bar.com')
610
h = interact_2965(c, url)
611
assert string.find(h, '$Domain=".bar.com"') != -1, \
612
"domain not returned"
615
url = "http://foo.bar.com/"
616
# note missing initial dot in Domain
617
interact_2965(c, url, 'spam=eggs; Version=1; Domain=bar.com')
618
h = interact_2965(c, url)
619
assert string.find(h, '$Domain="bar.com"') != -1, \
620
"domain not returned"
622
def test_path_mirror(self):
623
from ClientCookie import CookieJar
626
url = "http://foo.bar.com/"
627
interact_2965(c, url, "spam=eggs; Version=1")
628
h = interact_2965(c, url)
629
assert string.find("Path", h) == -1, \
630
"absent path returned with path present"
633
url = "http://foo.bar.com/"
634
interact_2965(c, url, 'spam=eggs; Version=1; Path=/')
635
h = interact_2965(c, url)
636
assert string.find(h, '$Path="/"') != -1, "path not returned"
638
def test_port_mirror(self):
639
from ClientCookie import CookieJar
642
url = "http://foo.bar.com/"
643
interact_2965(c, url, "spam=eggs; Version=1")
644
h = interact_2965(c, url)
645
assert string.find("Port", h) == -1, \
646
"absent port returned with port present"
649
url = "http://foo.bar.com/"
650
interact_2965(c, url, "spam=eggs; Version=1; Port")
651
h = interact_2965(c, url)
652
assert re.search("\$Port([^=]|$)", h), \
653
"port with no value not returned with no value"
656
url = "http://foo.bar.com/"
657
interact_2965(c, url, 'spam=eggs; Version=1; Port="80"')
658
h = interact_2965(c, url)
659
assert string.find(h, '$Port="80"') != -1, \
660
"port with single value not returned with single value"
663
url = "http://foo.bar.com/"
664
interact_2965(c, url, 'spam=eggs; Version=1; Port="80,8080"')
665
h = interact_2965(c, url)
666
assert string.find(h, '$Port="80,8080"') != -1, \
667
"port with multiple values not returned with multiple values"
669
def test_no_return_comment(self):
670
from ClientCookie import CookieJar
673
url = "http://foo.bar.com/"
674
interact_2965(c, url, 'spam=eggs; Version=1; '
675
'Comment="does anybody read these?"; '
676
'CommentURL="http://foo.bar.net/comment.html"')
677
h = interact_2965(c, url)
678
assert string.find("Comment", h) == -1, \
679
"Comment or CommentURL cookie-attributes returned to server"
681
# just pondering security here -- this isn't really a test (yet)
682
## def test_hack(self):
683
## from ClientCookie import CookieJar
686
## interact_netscape(c, "http://victim.mall.com/",
688
## interact_netscape(c, "http://cracker.mall.com/",
689
## 'prefs="bar"; Domain=.mall.com')
690
## interact_netscape(c, "http://cracker.mall.com/",
691
## '$Version="1"; Domain=.mall.com')
692
## h = interact_netscape(c, "http://victim.mall.com/")
695
def test_Cookie_iterator(self):
696
from ClientCookie import CookieJar, Cookie
699
# add some random cookies
700
interact_2965(cs, "http://blah.spam.org/", 'foo=eggs; Version=1; '
701
'Comment="does anybody read these?"; '
702
'CommentURL="http://foo.bar.net/comment.html"')
703
interact_netscape(cs, "http://www.acme.com/blah/", "spam=bar; secure")
704
interact_2965(cs, "http://www.acme.com/blah/", "foo=bar; secure; Version=1")
705
interact_2965(cs, "http://www.acme.com/blah/", "foo=bar; path=/; Version=1")
706
interact_2965(cs, "http://www.sol.no",
707
r'bang=wallop; version=1; domain=".sol.no"; '
708
r'port="90,100, 80,8080"; '
709
r'max-age=100; Comment = "Just kidding! (\"|\\\\) "')
711
versions = [1, 1, 1, 0, 1, 1]
712
names = ["bang", "foo", "foo", "spam", "foo"]
713
domains = [".sol.no", "blah.spam.org", "www.acme.com",
714
"www.acme.com", "www.acme.com"]
715
paths = ["/", "/", "/", "/blah", "/blah/", "/"]
717
# sequential iteration
721
assert isinstance(c, Cookie)
722
assert c.version == versions[i]
723
assert c.name == names[i]
724
assert c.domain == domains[i]
725
assert c.path == paths[i]
728
self.assertRaises(IndexError, lambda cs=cs : cs[5])
733
self.assertRaises(IndexError, lambda cs=cs : cs[3])
739
self.assertRaises(IndexError, lambda cs=cs : cs[1])
741
def test_parse_ns_headers(self):
742
from ClientCookie._HeadersUtil import parse_ns_headers
744
# missing domain value (invalid cookie)
745
assert parse_ns_headers(["foo=bar; path=/; domain"]) == [
747
("path", "/"), ("domain", None), ("version", "0")]]
748
# invalid expires value
749
assert parse_ns_headers(
750
["foo=bar; expires=Foo Bar 12 33:22:11 2000"]) == \
751
[[("foo", "bar"), ("expires", None), ("version", "0")]]
752
# missing cookie name (valid cookie)
753
assert parse_ns_headers(["foo"]) == [[(None, "foo"), ("version", "0")]]
754
# shouldn't add version if header is empty
755
assert parse_ns_headers([""]) == []
757
def test_bad_cookie_header(self):
759
def cookiejar_from_cookie_headers(headers):
760
from ClientCookie import CookieJar, Request
762
req = Request("http://www.example.com/")
763
r = FakeResponse(headers, "http://www.example.com/")
764
c.extract_cookies(r, req)
767
# none of these bad headers should cause an exception to be raised
769
["Set-Cookie: "], # actually, nothing wrong with this
770
["Set-Cookie2: "], # ditto
771
# missing domain value
772
["Set-Cookie2: a=foo; path=/; Version=1; domain"],
774
["Set-Cookie: b=foo; max-age=oops"],
776
c = cookiejar_from_cookie_headers(headers)
777
# these bad cookies shouldn't be set
780
# cookie with invalid expires is treated as session cookie
781
headers = ["Set-Cookie: c=foo; expires=Foo Bar 12 33:22:11 2000"]
782
c = cookiejar_from_cookie_headers(headers)
783
cookie = c.cookies["www.example.com"]["/"]["c"]
784
assert cookie.expires is None
787
class LWPCookieTests(TestCase):
788
# Tests taken from libwww-perl, with a few modifications.
790
def test_netscape_example_1(self):
791
from ClientCookie import CookieJar, Request
793
#-------------------------------------------------------------------
794
# First we check that it works for the original example at
795
# http://www.netscape.com/newsref/std/cookie_spec.html
797
# Client requests a document, and receives in the response:
799
# Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/; expires=Wednesday, 09-Nov-99 23:12:40 GMT
801
# When client requests a URL in path "/" on this server, it sends:
803
# Cookie: CUSTOMER=WILE_E_COYOTE
805
# Client requests a document, and receives in the response:
807
# Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/
809
# When client requests a URL in path "/" on this server, it sends:
811
# Cookie: CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001
815
# Set-Cookie: SHIPPING=FEDEX; path=/fo
817
# When client requests a URL in path "/" on this server, it sends:
819
# Cookie: CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001
821
# When client requests a URL in path "/foo" on this server, it sends:
823
# Cookie: CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001; SHIPPING=FEDEX
825
# The last Cookie is buggy, because both specifications say that the
826
# most specific cookie must be sent first. SHIPPING=FEDEX is the
827
# most specific and should thus be first.
829
year_plus_one = localtime(time.time())[0] + 1
835
#req = Request("http://1.1.1.1/",
836
# headers={"Host": "www.acme.com:80"})
837
req = Request("http://www.acme.com:80/",
838
headers={"Host": "www.acme.com:80"})
841
"Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/ ; "
842
"expires=Wednesday, 09-Nov-%d 23:12:40 GMT" % year_plus_one)
843
res = FakeResponse(headers, "http://www.acme.com/")
844
c.extract_cookies(res, req)
846
req = Request("http://www.acme.com/")
847
c.add_cookie_header(req)
849
assert (req.get_header("Cookie") == "CUSTOMER=WILE_E_COYOTE" and
850
req.get_header("Cookie2") == '$Version="1"')
852
headers.append("Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/")
853
res = FakeResponse(headers, "http://www.acme.com/")
854
c.extract_cookies(res, req)
856
req = Request("http://www.acme.com/foo/bar")
857
c.add_cookie_header(req)
859
h = req.get_header("Cookie")
860
assert (string.find(h, "PART_NUMBER=ROCKET_LAUNCHER_0001") != -1 and
861
string.find(h, "CUSTOMER=WILE_E_COYOTE") != -1)
864
headers.append('Set-Cookie: SHIPPING=FEDEX; path=/foo')
865
res = FakeResponse(headers, "http://www.acme.com")
866
c.extract_cookies(res, req)
868
req = Request("http://www.acme.com/")
869
c.add_cookie_header(req)
871
h = req.get_header("Cookie")
872
assert (string.find(h, "PART_NUMBER=ROCKET_LAUNCHER_0001") != -1 and
873
string.find(h, "CUSTOMER=WILE_E_COYOTE") != -1 and
874
not string.find(h, "SHIPPING=FEDEX") != -1)
877
req = Request("http://www.acme.com/foo/")
878
c.add_cookie_header(req)
880
h = req.get_header("Cookie")
881
assert (string.find(h, "PART_NUMBER=ROCKET_LAUNCHER_0001") != -1 and
882
string.find(h, "CUSTOMER=WILE_E_COYOTE") != -1 and
883
startswith(h, "SHIPPING=FEDEX;"))
885
def test_netscape_example_2(self):
886
from ClientCookie import CookieJar, Request
888
# Second Example transaction sequence:
890
# Assume all mappings from above have been cleared.
894
# Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/
896
# When client requests a URL in path "/" on this server, it sends:
898
# Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001
902
# Set-Cookie: PART_NUMBER=RIDING_ROCKET_0023; path=/ammo
904
# When client requests a URL in path "/ammo" on this server, it sends:
906
# Cookie: PART_NUMBER=RIDING_ROCKET_0023; PART_NUMBER=ROCKET_LAUNCHER_0001
908
# NOTE: There are two name/value pairs named "PART_NUMBER" due to
909
# the inheritance of the "/" mapping in addition to the "/ammo" mapping.
914
req = Request("http://www.acme.com/")
915
headers.append("Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/")
916
res = FakeResponse(headers, "http://www.acme.com/")
918
c.extract_cookies(res, req)
920
req = Request("http://www.acme.com/")
921
c.add_cookie_header(req)
923
assert (req.get_header("Cookie") == "PART_NUMBER=ROCKET_LAUNCHER_0001")
926
"Set-Cookie: PART_NUMBER=RIDING_ROCKET_0023; path=/ammo")
927
res = FakeResponse(headers, "http://www.acme.com/")
928
c.extract_cookies(res, req)
930
req = Request("http://www.acme.com/ammo")
931
c.add_cookie_header(req)
933
assert re.search(r"PART_NUMBER=RIDING_ROCKET_0023;\s*"
934
"PART_NUMBER=ROCKET_LAUNCHER_0001",
935
req.get_header("Cookie"))
937
def test_ietf_example_1(self):
938
from ClientCookie import CookieJar
939
#-------------------------------------------------------------------
940
# Then we test with the examples from draft-ietf-http-state-man-mec-03.txt
949
# Most detail of request and response headers has been omitted. Assume
950
# the user agent has no stored cookies.
952
# 1. User Agent -> Server
954
# POST /acme/login HTTP/1.1
957
# User identifies self via a form.
959
# 2. Server -> User Agent
962
# Set-Cookie2: Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"
964
# Cookie reflects user's identity.
966
cookie = interact_2965(
967
c, 'http://www.acme.com/acme/login',
968
'Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"')
972
# 3. User Agent -> Server
974
# POST /acme/pickitem HTTP/1.1
975
# Cookie: $Version="1"; Customer="WILE_E_COYOTE"; $Path="/acme"
978
# User selects an item for ``shopping basket.''
980
# 4. Server -> User Agent
983
# Set-Cookie2: Part_Number="Rocket_Launcher_0001"; Version="1";
986
# Shopping basket contains an item.
988
cookie = interact_2965(c, 'http://www.acme.com/acme/pickitem',
989
'Part_Number="Rocket_Launcher_0001"; '
990
'Version="1"; Path="/acme"');
992
r'^\$Version="?1"?; Customer="?WILE_E_COYOTE"?; \$Path="/acme"$',
996
# 5. User Agent -> Server
998
# POST /acme/shipping HTTP/1.1
999
# Cookie: $Version="1";
1000
# Customer="WILE_E_COYOTE"; $Path="/acme";
1001
# Part_Number="Rocket_Launcher_0001"; $Path="/acme"
1004
# User selects shipping method from form.
1006
# 6. Server -> User Agent
1009
# Set-Cookie2: Shipping="FedEx"; Version="1"; Path="/acme"
1011
# New cookie reflects shipping method.
1013
cookie = interact_2965(c, "http://www.acme.com/acme/shipping",
1014
'Shipping="FedEx"; Version="1"; Path="/acme"')
1016
assert (re.search(r'^\$Version="?1"?;', cookie) and
1017
re.search(r'Part_Number="?Rocket_Launcher_0001"?;'
1018
'\s*\$Path="\/acme"', cookie) and
1019
re.search(r'Customer="?WILE_E_COYOTE"?;\s*\$Path="\/acme"',
1023
# 7. User Agent -> Server
1025
# POST /acme/process HTTP/1.1
1026
# Cookie: $Version="1";
1027
# Customer="WILE_E_COYOTE"; $Path="/acme";
1028
# Part_Number="Rocket_Launcher_0001"; $Path="/acme";
1029
# Shipping="FedEx"; $Path="/acme"
1032
# User chooses to process order.
1034
# 8. Server -> User Agent
1038
# Transaction is complete.
1040
cookie = interact_2965(c, "http://www.acme.com/acme/process")
1041
assert (re.search(r'Shipping="?FedEx"?;\s*\$Path="\/acme"', cookie) and
1042
string.find(cookie, "WILE_E_COYOTE") != -1)
1045
# The user agent makes a series of requests on the origin server, after
1046
# each of which it receives a new cookie. All the cookies have the same
1047
# Path attribute and (default) domain. Because the request URLs all have
1048
# /acme as a prefix, and that matches the Path attribute, each request
1049
# contains all the cookies received so far.
1051
def test_ietf_example_2(self):
1052
from ClientCookie import CookieJar
1056
# This example illustrates the effect of the Path attribute. All detail
1057
# of request and response headers has been omitted. Assume the user agent
1058
# has no stored cookies.
1062
# Imagine the user agent has received, in response to earlier requests,
1063
# the response headers
1065
# Set-Cookie2: Part_Number="Rocket_Launcher_0001"; Version="1";
1070
# Set-Cookie2: Part_Number="Riding_Rocket_0023"; Version="1";
1074
c, "http://www.acme.com/acme/ammo/specific",
1075
'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"',
1076
'Part_Number="Riding_Rocket_0023"; Version="1"; Path="/acme/ammo"')
1078
# A subsequent request by the user agent to the (same) server for URLs of
1079
# the form /acme/ammo/... would include the following request header:
1081
# Cookie: $Version="1";
1082
# Part_Number="Riding_Rocket_0023"; $Path="/acme/ammo";
1083
# Part_Number="Rocket_Launcher_0001"; $Path="/acme"
1085
# Note that the NAME=VALUE pair for the cookie with the more specific Path
1086
# attribute, /acme/ammo, comes before the one with the less specific Path
1087
# attribute, /acme. Further note that the same cookie name appears more
1090
cookie = interact_2965(c, "http://www.acme.com/acme/ammo/...")
1091
assert re.search(r"Riding_Rocket_0023.*Rocket_Launcher_0001", cookie)
1093
# A subsequent request by the user agent to the (same) server for a URL of
1094
# the form /acme/parts/ would include the following request header:
1096
# Cookie: $Version="1"; Part_Number="Rocket_Launcher_0001"; $Path="/acme"
1098
# Here, the second cookie's Path attribute /acme/ammo is not a prefix of
1099
# the request URL, /acme/parts/, so the cookie does not get forwarded to
1102
cookie = interact_2965(c, "http://www.acme.com/acme/parts/")
1103
assert (string.find(cookie, "Rocket_Launcher_0001") != -1 and
1104
not string.find(cookie, "Riding_Rocket_0023") != -1)
1106
def test_rejection(self):
1107
# Test rejection of Set-Cookie2 responses based on domain, path, port.
1108
from ClientCookie import CookieJar
1112
max_age = "max-age=3600"
1114
# illegal domain (no embedded dots)
1115
cookie = interact_2965(c, "http://www.acme.com",
1116
'foo=bar; domain=".com"; version=1')
1120
cookie = interact_2965(c, "http://www.acme.com",
1121
'ping=pong; domain="acme.com"; version=1')
1124
# illegal domain (host prefix "www.a" contains a dot)
1125
cookie = interact_2965(c, "http://www.a.acme.com",
1126
'whiz=bang; domain="acme.com"; version=1')
1130
cookie = interact_2965(c, "http://www.a.acme.com",
1131
'wow=flutter; domain=".a.acme.com"; version=1')
1134
# can't partially match an IP-address
1135
cookie = interact_2965(c, "http://125.125.125.125",
1136
'zzzz=ping; domain="125.125.125"; version=1')
1139
# illegal path (must be prefix of request path)
1140
cookie = interact_2965(c, "http://www.sol.no",
1141
'blah=rhubarb; domain=".sol.no"; path="/foo"; '
1146
cookie = interact_2965(c, "http://www.sol.no/foo/bar",
1147
'bing=bong; domain=".sol.no"; path="/foo"; '
1151
# illegal port (request-port not in list)
1152
cookie = interact_2965(c, "http://www.sol.no",
1153
'whiz=ffft; domain=".sol.no"; port="90,100"; '
1158
cookie = interact_2965(
1159
c, "http://www.sol.no",
1160
r'bang=wallop; version=1; domain=".sol.no"; '
1161
r'port="90,100, 80,8080"; '
1162
r'max-age=100; Comment = "Just kidding! (\"|\\\\) "')
1165
# port attribute without any value (current port)
1166
cookie = interact_2965(c, "http://www.sol.no",
1167
'foo9=bar; version=1; domain=".sol.no"; port; '
1172
# LWP has this test, but unescaping allowed path characters seems
1173
# like a bad idea, so I think this should fail:
1174
## cookie = interact_2965(c, "http://www.sol.no/foo/",
1175
## r'foo8=bar; version=1; path="/%66oo"')
1176
# but this is OK, because '<' is not an allowed HTTP URL path
1178
cookie = interact_2965(c, "http://www.sol.no/<oo/",
1179
r'foo8=bar; version=1; path="/%3coo"')
1183
filename = "lwp-cookies.txt"
1186
c.save(filename, ignore_discard=True)
1190
c.load(filename, ignore_discard=True)
1192
try: os.unlink(filename)
1193
except OSError: pass
1195
assert old == repr(c)
1197
def test_url_encoding(self):
1198
# Try some URL encodings of the PATHs.
1199
# (the behaviour here has changed from libwww-perl)
1200
from ClientCookie import CookieJar
1203
## interact_2965(c, "http://www.acme.com/foo%2f%25/%40%40%0Anew%E5/%E5",
1204
## "foo = bar; version = 1")
1206
## cookie = interact_2965(c, "http://www.acme.com/foo%2f%25/@@%0anew�/���",
1207
## 'bar=baz; path="/foo/"; version=1');
1208
interact_2965(c, "http://www.acme.com/foo%2f%25/%3c%3c%0Anew%E5/%E5",
1209
"foo = bar; version = 1")
1211
cookie = interact_2965(
1212
c, "http://www.acme.com/foo%2f%25/<<%0anew�/���",
1213
'bar=baz; path="/foo/"; version=1');
1214
version_re = re.compile(r'^\$version=\"?1\"?', re.I)
1215
assert (string.find(cookie, "foo=bar") != -1 and
1216
version_re.search(cookie))
1218
## cookie = interact_2965(c, "http://www.acme.com/foo/%25/@@%0anew�/���")
1219
cookie = interact_2965(
1220
c, "http://www.acme.com/foo/%25/<<%0anew�/���")
1223
# unicode URL doesn't raise exception, as it used to!
1224
# XXXX 1.5.2 SyntaxError
1225
#cookie = interact_2965(c, u"http://www.acme.com/\xfc")
1227
def test_mozilla(self):
1228
# Save / load Mozilla/Netscape cookie file format.
1229
from ClientCookie import MozillaCookieJar
1231
year_plus_one = localtime(time.time())[0] + 1
1233
filename = "cookies.txt"
1235
c = MozillaCookieJar(filename)
1236
interact_2965(c, "http://www.acme.com/",
1237
"foo1=bar; max-age=100; Version=1")
1238
interact_2965(c, "http://www.acme.com/",
1239
'foo2=bar; port="80"; max-age=100; Discard; Version=1')
1240
interact_2965(c, "http://www.acme.com/", "foo3=bar; secure; Version=1")
1242
expires = "expires=09-Nov-%d 23:12:40 GMT" % (year_plus_one,)
1243
interact_netscape(c, "http://www.foo.com/",
1244
"fooa=bar; %s" % expires)
1245
interact_netscape(c, "http://www.foo.com/",
1246
"foob=bar; Domain=.foo.com; %s" % expires)
1247
interact_netscape(c, "http://www.foo.com/",
1248
"fooc=bar; Domain=www.foo.com; %s" % expires)
1250
def save_and_restore(cj, ignore_discard, filename=filename):
1251
from ClientCookie import MozillaCookieJar
1253
cj.save(ignore_discard=ignore_discard)
1254
new_c = MozillaCookieJar(filename)
1255
new_c.load(ignore_discard=ignore_discard)
1257
try: os.unlink(filename)
1258
except OSError: pass
1261
new_c = save_and_restore(c, True)
1262
assert len(new_c) == 6 # none discarded
1263
assert string.find(new_c.as_lwp_str(), "foo1=bar") != -1
1265
new_c = save_and_restore(c, False)
1266
assert len(new_c) == 4 # 2 of them discarded on save
1267
assert string.find(new_c.as_lwp_str(), "foo1=bar") != -1
1269
def test_netscape_misc(self):
1270
# Some additional Netscape cookies tests.
1271
from ClientCookie import CookieJar, Request
1275
req = Request("http://foo.bar.acme.com/foo")
1277
# Netscape allows a host part that contains dots
1278
headers.append("Set-Cookie: Customer=WILE_E_COYOTE; domain=.acme.com")
1279
res = FakeResponse(headers, "http://www.acme.com/foo")
1280
c.extract_cookies(res, req)
1282
# and that the domain is the same as the host without adding a leading
1283
# dot to the domain. Should not quote even if strange chars are used
1284
# in the cookie value.
1285
headers.append("Set-Cookie: PART_NUMBER=3,4; domain=foo.bar.acme.com")
1286
res = FakeResponse(headers, "http://www.acme.com/foo")
1287
c.extract_cookies(res, req)
1289
req = Request("http://foo.bar.acme.com/foo")
1290
c.add_cookie_header(req)
1292
string.find(req.get_header("Cookie"), "PART_NUMBER=3,4") != -1 and
1293
string.find(req.get_header("Cookie"), "Customer=WILE_E_COYOTE") != -1)
1295
def test_intranet_domains(self):
1296
# Test handling of local intranet hostnames without a dot.
1297
from ClientCookie import CookieJar
1300
interact_2965(c, "http://example/",
1301
"foo1=bar; PORT; Discard; Version=1;")
1302
cookie = interact_2965(c, "http://example/",
1303
'foo2=bar; domain=".local"; Version=1')
1304
assert not (string.find(cookie, "foo1=bar") == -1)
1306
interact_2965(c, "http://example/", 'foo3=bar; Version=1')
1307
cookie = interact_2965(c, "http://example/")
1308
assert not (string.find(cookie, "foo2=bar") == -1 or len(c) != 3)
1310
def test_empty_path(self):
1311
from ClientCookie import CookieJar, Request
1313
# Test for empty path
1314
# Broken web-server ORION/1.3.38 returns to the client response like
1316
# Set-Cookie: JSESSIONID=ABCDERANDOM123; Path=
1318
# ie. with Path set to nothing.
1319
# In this case, extract_cookies() must set cookie to / (root)
1323
req = Request("http://www.ants.com/")
1324
headers.append("Set-Cookie: JSESSIONID=ABCDERANDOM123; Path=")
1325
res = FakeResponse(headers, "http://www.ants.com/")
1326
c.extract_cookies(res, req)
1328
req = Request("http://www.ants.com/")
1329
c.add_cookie_header(req)
1331
assert (req.get_header("Cookie") == "JSESSIONID=ABCDERANDOM123" and
1332
req.get_header("Cookie2") == '$Version="1"')
1334
# missing path in the request URI
1335
req = Request("http://www.ants.com:8080")
1336
c.add_cookie_header(req)
1338
assert (req.get_header("Cookie") == "JSESSIONID=ABCDERANDOM123" and
1339
req.get_header("Cookie2") == '$Version="1"')
1341
# The correctness of this test is undefined, in the absence of RFC 2965 errata.
1342
## def test_netscape_rfc2965_interop(self):
1343
## # Test mixing of Set-Cookie and Set-Cookie2 headers.
1344
## from ClientCookie import CookieJar
1346
## # Example from http://www.trip.com/trs/trip/flighttracker/flight_tracker_home.xsl
1347
## # which gives up these headers:
1349
## # HTTP/1.1 200 OK
1350
## # Connection: close
1351
## # Date: Fri, 20 Jul 2001 19:54:58 GMT
1352
## # Server: Apache/1.3.19 (Unix) ApacheJServ/1.1.2
1353
## # Content-Type: text/html
1354
## # Content-Type: text/html; charset=iso-8859-1
1355
## # Link: </trip/stylesheet.css>; rel="stylesheet"; type="text/css"
1356
## # 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.)
1357
## # Set-Cookie: trip.appServer=1111-0000-x-024;Domain=.trip.com;Path=/
1358
## # Set-Cookie: JSESSIONID=fkumjm7nt1.JS24;Path=/trs
1359
## # Set-Cookie2: JSESSIONID=fkumjm7nt1.JS24;Version=1;Discard;Path="/trs"
1360
## # Title: TRIP.com Travel - FlightTRACKER
1361
## # X-Meta-Description: Trip.com privacy policy
1362
## # X-Meta-Keywords: privacy policy
1365
## 'http://www.trip.com/trs/trip/flighttracker/flight_tracker_home.xsl')
1367
## headers.append("Set-Cookie: trip.appServer=1111-0000-x-024;Domain=.trip.com;Path=/")
1368
## headers.append("Set-Cookie: JSESSIONID=fkumjm7nt1.JS24;Path=/trs")
1369
## headers.append('Set-Cookie2: JSESSIONID=fkumjm7nt1.JS24;Version=1;Discard;Path="/trs"')
1370
## res = FakeResponse(
1372
## 'http://www.trip.com/trs/trip/flighttracker/flight_tracker_home.xsl')
1376
## c.extract_cookies(res, req)
1379
## print """Set-Cookie3: trip.appServer="1111-0000-x-024"; path="/"; domain=".trip.com"; path_spec; discard; version=0
1380
## Set-Cookie3: JSESSIONID="fkumjm7nt1.JS24"; path="/trs"; domain="www.trip.com"; path_spec; discard; version=1
1382
## assert c.as_lwp_str() == """Set-Cookie3: trip.appServer="1111-0000-x-024"; path="/"; domain=".trip.com"; path_spec; discard; version=0
1383
## Set-Cookie3: JSESSIONID="fkumjm7nt1.JS24"; path="/trs"; domain="www.trip.com"; path_spec; discard; version=1
1386
def test_session_cookies(self):
1387
from ClientCookie import CookieJar, Request
1389
year_plus_one = localtime(time.time())[0] + 1
1391
# Check session cookies are deleted properly by
1392
# CookieJar.clear_session_cookies method
1394
req = Request('http://www.perlmeister.com/scripts')
1396
headers.append("Set-Cookie: s1=session;Path=/scripts")
1397
headers.append("Set-Cookie: p1=perm; Domain=.perlmeister.com;"
1398
"Path=/;expires=Fri, 02-Feb-%d 23:24:20 GMT" %
1400
headers.append("Set-Cookie: p2=perm;Path=/;expires=Fri, "
1401
"02-Feb-%d 23:24:20 GMT" % year_plus_one)
1402
headers.append("Set-Cookie: s2=session;Path=/scripts;"
1403
"Domain=.perlmeister.com")
1404
headers.append('Set-Cookie2: s3=session;Version=1;Discard;Path="/"')
1405
res = FakeResponse(headers, 'http://www.perlmeister.com/scripts')
1408
c.extract_cookies(res, req)
1409
# How many session/permanent cookies do we have?
1410
counter = {"session_after": 0,
1412
"session_before": 0,
1415
key = "%s_before" % cookie.value
1416
counter[key] = counter[key] + 1
1417
c.clear_session_cookies()
1420
key = "%s_after" % cookie.value
1421
counter[key] = counter[key] + 1
1424
# a permanent cookie got lost accidently
1425
counter["perm_after"] != counter["perm_before"] or
1426
# a session cookie hasn't been cleared
1427
counter["session_after"] != 0 or
1428
# we didn't have session cookies in the first place
1429
counter["session_before"] == 0)
1432
if __name__ == "__main__":