test_cookielib.py 71 KB

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