Best JavaScript code snippet using navalia
test_cookielib.py
Source:test_cookielib.py
...231 return cookie_hdr232233234class FileCookieJarTests(TestCase):235 def test_lwp_valueless_cookie(self):236 # cookies with no value should be saved and loaded consistently237 from cookielib import LWPCookieJar238 filename = test_support.TESTFN239 c = LWPCookieJar()240 interact_netscape(c, "http://www.acme.com/", 'boo')241 self.assertEqual(c._cookies["www.acme.com"]["/"]["boo"].value, None)242 try:243 c.save(filename, ignore_discard=True)244 c = LWPCookieJar()245 c.load(filename, ignore_discard=True)246 finally:247 try: os.unlink(filename)248 except OSError: pass249 self.assertEqual(c._cookies["www.acme.com"]["/"]["boo"].value, None)250251 def test_bad_magic(self):252 from cookielib import LWPCookieJar, MozillaCookieJar, LoadError253 # IOErrors (eg. file doesn't exist) are allowed to propagate254 filename = test_support.TESTFN255 for cookiejar_class in LWPCookieJar, MozillaCookieJar:256 c = cookiejar_class()257 try:258 c.load(filename="for this test to work, a file with this "259 "filename should not exist")260 except IOError, exc:261 # exactly IOError, not LoadError262 self.assertEqual(exc.__class__, IOError)263 else:264 self.fail("expected IOError for invalid filename")265 # Invalid contents of cookies file (eg. bad magic string)266 # causes a LoadError.267 try:268 f = open(filename, "w")269 f.write("oops\n")270 for cookiejar_class in LWPCookieJar, MozillaCookieJar:271 c = cookiejar_class()272 self.assertRaises(LoadError, c.load, filename)273 finally:274 try: os.unlink(filename)275 except OSError: pass276277class CookieTests(TestCase):278 # XXX279 # Get rid of string comparisons where not actually testing str / repr.280 # .clear() etc.281 # IP addresses like 50 (single number, no dot) and domain-matching282 # functions (and is_HDN)? See draft RFC 2965 errata.283 # Strictness switches284 # is_third_party()285 # unverifiability / third-party blocking286 # Netscape cookies work the same as RFC 2965 with regard to port.287 # Set-Cookie with negative max age.288 # If turn RFC 2965 handling off, Set-Cookie2 cookies should not clobber289 # Set-Cookie cookies.290 # Cookie2 should be sent if *any* cookies are not V1 (ie. V0 OR V2 etc.).291 # Cookies (V1 and V0) with no expiry date should be set to be discarded.292 # RFC 2965 Quoting:293 # Should accept unquoted cookie-attribute values? check errata draft.294 # Which are required on the way in and out?295 # Should always return quoted cookie-attribute values?296 # Proper testing of when RFC 2965 clobbers Netscape (waiting for errata).297 # Path-match on return (same for V0 and V1).298 # RFC 2965 acceptance and returning rules299 # Set-Cookie2 without version attribute is rejected.300301 # Netscape peculiarities list from Ronald Tschalar.302 # The first two still need tests, the rest are covered.303## - Quoting: only quotes around the expires value are recognized as such304## (and yes, some folks quote the expires value); quotes around any other305## value are treated as part of the value.306## - White space: white space around names and values is ignored307## - Default path: if no path parameter is given, the path defaults to the308## path in the request-uri up to, but not including, the last '/'. Note309## that this is entirely different from what the spec says.310## - Commas and other delimiters: Netscape just parses until the next ';'.311## This means it will allow commas etc inside values (and yes, both312## commas and equals are commonly appear in the cookie value). This also313## means that if you fold multiple Set-Cookie header fields into one,314## comma-separated list, it'll be a headache to parse (at least my head315## starts hurting everytime I think of that code).316## - Expires: You'll get all sorts of date formats in the expires,317## including emtpy expires attributes ("expires="). Be as flexible as you318## can, and certainly don't expect the weekday to be there; if you can't319## parse it, just ignore it and pretend it's a session cookie.320## - Domain-matching: Netscape uses the 2-dot rule for _all_ domains, not321## just the 7 special TLD's listed in their spec. And folks rely on322## that...323324 def test_domain_return_ok(self):325 # test optimization: .domain_return_ok() should filter out most326 # domains in the CookieJar before we try to access them (because that327 # may require disk access -- in particular, with MSIECookieJar)328 # This is only a rough check for performance reasons, so it's not too329 # critical as long as it's sufficiently liberal.330 import cookielib, urllib2331 pol = cookielib.DefaultCookiePolicy()332 for url, domain, ok in [333 ("http://foo.bar.com/", "blah.com", False),334 ("http://foo.bar.com/", "rhubarb.blah.com", False),335 ("http://foo.bar.com/", "rhubarb.foo.bar.com", False),336 ("http://foo.bar.com/", ".foo.bar.com", True),337 ("http://foo.bar.com/", "foo.bar.com", True),338 ("http://foo.bar.com/", ".bar.com", True),339 ("http://foo.bar.com/", "com", True),340 ("http://foo.com/", "rhubarb.foo.com", False),341 ("http://foo.com/", ".foo.com", True),342 ("http://foo.com/", "foo.com", True),343 ("http://foo.com/", "com", True),344 ("http://foo/", "rhubarb.foo", False),345 ("http://foo/", ".foo", True),346 ("http://foo/", "foo", True),347 ("http://foo/", "foo.local", True),348 ("http://foo/", ".local", True),349 ]:350 request = urllib2.Request(url)351 r = pol.domain_return_ok(domain, request)352 if ok: self.assert_(r)353 else: self.assert_(not r)354355 def test_missing_value(self):356 from cookielib import MozillaCookieJar, lwp_cookie_str357358 # missing = sign in Cookie: header is regarded by Mozilla as a missing359 # name, and by cookielib as a missing value360 filename = test_support.TESTFN361 c = MozillaCookieJar(filename)362 interact_netscape(c, "http://www.acme.com/", 'eggs')363 interact_netscape(c, "http://www.acme.com/", '"spam"; path=/foo/')364 cookie = c._cookies["www.acme.com"]["/"]["eggs"]365 self.assert_(cookie.value is None)366 self.assertEquals(cookie.name, "eggs")367 cookie = c._cookies["www.acme.com"]['/foo/']['"spam"']368 self.assert_(cookie.value is None)369 self.assertEquals(cookie.name, '"spam"')370 self.assertEquals(lwp_cookie_str(cookie), (371 r'"spam"; path="/foo/"; domain="www.acme.com"; '372 'path_spec; discard; version=0'))373 old_str = repr(c)374 c.save(ignore_expires=True, ignore_discard=True)375 try:376 c = MozillaCookieJar(filename)377 c.revert(ignore_expires=True, ignore_discard=True)378 finally:379 os.unlink(c.filename)380 # cookies unchanged apart from lost info re. whether path was specified381 self.assertEquals(382 repr(c),383 re.sub("path_specified=%s" % True, "path_specified=%s" % False,384 old_str)385 )386 self.assertEquals(interact_netscape(c, "http://www.acme.com/foo/"),387 '"spam"; eggs')388389 def test_rfc2109_handling(self):390 # RFC 2109 cookies are handled as RFC 2965 or Netscape cookies,391 # dependent on policy settings392 from cookielib import CookieJar, DefaultCookiePolicy393394 for rfc2109_as_netscape, rfc2965, version in [395 # default according to rfc2965 if not explicitly specified396 (None, False, 0),397 (None, True, 1),398 # explicit rfc2109_as_netscape399 (False, False, None), # version None here means no cookie stored400 (False, True, 1),401 (True, False, 0),402 (True, True, 0),403 ]:404 policy = DefaultCookiePolicy(405 rfc2109_as_netscape=rfc2109_as_netscape,406 rfc2965=rfc2965)407 c = CookieJar(policy)408 interact_netscape(c, "http://www.example.com/", "ni=ni; Version=1")409 try:410 cookie = c._cookies["www.example.com"]["/"]["ni"]411 except KeyError:412 self.assert_(version is None) # didn't expect a stored cookie413 else:414 self.assertEqual(cookie.version, version)415 # 2965 cookies are unaffected416 interact_2965(c, "http://www.example.com/",417 "foo=bar; Version=1")418 if rfc2965:419 cookie2965 = c._cookies["www.example.com"]["/"]["foo"]420 self.assertEqual(cookie2965.version, 1)421422 def test_ns_parser(self):423 from cookielib import CookieJar, DEFAULT_HTTP_PORT424425 c = CookieJar()426 interact_netscape(c, "http://www.acme.com/",427 'spam=eggs; DoMain=.acme.com; port; blArgh="feep"')428 interact_netscape(c, "http://www.acme.com/", 'ni=ni; port=80,8080')429 interact_netscape(c, "http://www.acme.com:80/", 'nini=ni')430 interact_netscape(c, "http://www.acme.com:80/", 'foo=bar; expires=')431 interact_netscape(c, "http://www.acme.com:80/", 'spam=eggs; '432 'expires="Foo Bar 25 33:22:11 3022"')433434 cookie = c._cookies[".acme.com"]["/"]["spam"]435 self.assertEquals(cookie.domain, ".acme.com")436 self.assert_(cookie.domain_specified)437 self.assertEquals(cookie.port, DEFAULT_HTTP_PORT)438 self.assert_(not cookie.port_specified)439 # case is preserved440 self.assert_(cookie.has_nonstandard_attr("blArgh") and441 not cookie.has_nonstandard_attr("blargh"))442443 cookie = c._cookies["www.acme.com"]["/"]["ni"]444 self.assertEquals(cookie.domain, "www.acme.com")445 self.assert_(not cookie.domain_specified)446 self.assertEquals(cookie.port, "80,8080")447 self.assert_(cookie.port_specified)448449 cookie = c._cookies["www.acme.com"]["/"]["nini"]450 self.assert_(cookie.port is None)451 self.assert_(not cookie.port_specified)452453 # invalid expires should not cause cookie to be dropped454 foo = c._cookies["www.acme.com"]["/"]["foo"]455 spam = c._cookies["www.acme.com"]["/"]["foo"]456 self.assert_(foo.expires is None)457 self.assert_(spam.expires is None)458459 def test_ns_parser_special_names(self):460 # names such as 'expires' are not special in first name=value pair461 # of Set-Cookie: header462 from cookielib import CookieJar463464 c = CookieJar()465 interact_netscape(c, "http://www.acme.com/", 'expires=eggs')466 interact_netscape(c, "http://www.acme.com/", 'version=eggs; spam=eggs')467468 cookies = c._cookies["www.acme.com"]["/"]469 self.assert_('expires' in cookies)470 self.assert_('version' in cookies)471472 def test_expires(self):473 from cookielib import time2netscape, CookieJar474475 # if expires is in future, keep cookie...476 c = CookieJar()477 future = time2netscape(time.time()+3600)478 interact_netscape(c, "http://www.acme.com/", 'spam="bar"; expires=%s' %479 future)480 self.assertEquals(len(c), 1)481 now = time2netscape(time.time()-1)482 # ... and if in past or present, discard it483 interact_netscape(c, "http://www.acme.com/", 'foo="eggs"; expires=%s' %484 now)485 h = interact_netscape(c, "http://www.acme.com/")486 self.assertEquals(len(c), 1)487 self.assert_('spam="bar"' in h and "foo" not in h)488489 # max-age takes precedence over expires, and zero max-age is request to490 # delete both new cookie and any old matching cookie491 interact_netscape(c, "http://www.acme.com/", 'eggs="bar"; expires=%s' %492 future)493 interact_netscape(c, "http://www.acme.com/", 'bar="bar"; expires=%s' %494 future)495 self.assertEquals(len(c), 3)496 interact_netscape(c, "http://www.acme.com/", 'eggs="bar"; '497 'expires=%s; max-age=0' % future)498 interact_netscape(c, "http://www.acme.com/", 'bar="bar"; '499 'max-age=0; expires=%s' % future)500 h = interact_netscape(c, "http://www.acme.com/")501 self.assertEquals(len(c), 1)502503 # test expiry at end of session for cookies with no expires attribute504 interact_netscape(c, "http://www.rhubarb.net/", 'whum="fizz"')505 self.assertEquals(len(c), 2)506 c.clear_session_cookies()507 self.assertEquals(len(c), 1)508 self.assert_('spam="bar"' in h)509510 # XXX RFC 2965 expiry rules (some apply to V0 too)511512 def test_default_path(self):513 from cookielib import CookieJar, DefaultCookiePolicy514515 # RFC 2965516 pol = DefaultCookiePolicy(rfc2965=True)517518 c = CookieJar(pol)519 interact_2965(c, "http://www.acme.com/", 'spam="bar"; Version="1"')520 self.assert_("/" in c._cookies["www.acme.com"])521522 c = CookieJar(pol)523 interact_2965(c, "http://www.acme.com/blah", 'eggs="bar"; Version="1"')524 self.assert_("/" in c._cookies["www.acme.com"])525526 c = CookieJar(pol)527 interact_2965(c, "http://www.acme.com/blah/rhubarb",528 'eggs="bar"; Version="1"')529 self.assert_("/blah/" in c._cookies["www.acme.com"])530531 c = CookieJar(pol)532 interact_2965(c, "http://www.acme.com/blah/rhubarb/",533 'eggs="bar"; Version="1"')534 self.assert_("/blah/rhubarb/" in c._cookies["www.acme.com"])535536 # Netscape537538 c = CookieJar()539 interact_netscape(c, "http://www.acme.com/", 'spam="bar"')540 self.assert_("/" in c._cookies["www.acme.com"])541542 c = CookieJar()543 interact_netscape(c, "http://www.acme.com/blah", 'eggs="bar"')544 self.assert_("/" in c._cookies["www.acme.com"])545546 c = CookieJar()547 interact_netscape(c, "http://www.acme.com/blah/rhubarb", 'eggs="bar"')548 self.assert_("/blah" in c._cookies["www.acme.com"])549550 c = CookieJar()551 interact_netscape(c, "http://www.acme.com/blah/rhubarb/", 'eggs="bar"')552 self.assert_("/blah/rhubarb" in c._cookies["www.acme.com"])553554 def test_escape_path(self):555 from cookielib import escape_path556 cases = [557 # quoted safe558 ("/foo%2f/bar", "/foo%2F/bar"),559 ("/foo%2F/bar", "/foo%2F/bar"),560 # quoted %561 ("/foo%%/bar", "/foo%%/bar"),562 # quoted unsafe563 ("/fo%19o/bar", "/fo%19o/bar"),564 ("/fo%7do/bar", "/fo%7Do/bar"),565 # unquoted safe566 ("/foo/bar&", "/foo/bar&"),567 ("/foo//bar", "/foo//bar"),568 ("\176/foo/bar", "\176/foo/bar"),569 # unquoted unsafe570 ("/foo\031/bar", "/foo%19/bar"),571 ("/\175foo/bar", "/%7Dfoo/bar"),572 # unicode573 (u"/foo/bar\uabcd", "/foo/bar%EA%AF%8D"), # UTF-8 encoded574 ]575 for arg, result in cases:576 self.assertEquals(escape_path(arg), result)577578 def test_request_path(self):579 from urllib2 import Request580 from cookielib import request_path581 # with parameters582 req = Request("http://www.example.com/rheum/rhaponicum;"583 "foo=bar;sing=song?apples=pears&spam=eggs#ni")584 self.assertEquals(request_path(req), "/rheum/rhaponicum;"585 "foo=bar;sing=song?apples=pears&spam=eggs#ni")586 # without parameters587 req = Request("http://www.example.com/rheum/rhaponicum?"588 "apples=pears&spam=eggs#ni")589 self.assertEquals(request_path(req), "/rheum/rhaponicum?"590 "apples=pears&spam=eggs#ni")591 # missing final slash592 req = Request("http://www.example.com")593 self.assertEquals(request_path(req), "/")594595 def test_request_port(self):596 from urllib2 import Request597 from cookielib import request_port, DEFAULT_HTTP_PORT598 req = Request("http://www.acme.com:1234/",599 headers={"Host": "www.acme.com:4321"})600 self.assertEquals(request_port(req), "1234")601 req = Request("http://www.acme.com/",602 headers={"Host": "www.acme.com:4321"})603 self.assertEquals(request_port(req), DEFAULT_HTTP_PORT)604605 def test_request_host(self):606 from urllib2 import Request607 from cookielib import request_host608 # this request is illegal (RFC2616, 14.2.3)609 req = Request("http://1.1.1.1/",610 headers={"Host": "www.acme.com:80"})611 # libwww-perl wants this response, but that seems wrong (RFC 2616,612 # section 5.2, point 1., and RFC 2965 section 1, paragraph 3)613 #self.assertEquals(request_host(req), "www.acme.com")614 self.assertEquals(request_host(req), "1.1.1.1")615 req = Request("http://www.acme.com/",616 headers={"Host": "irrelevant.com"})617 self.assertEquals(request_host(req), "www.acme.com")618 # not actually sure this one is valid Request object, so maybe should619 # remove test for no host in url in request_host function?620 req = Request("/resource.html",621 headers={"Host": "www.acme.com"})622 self.assertEquals(request_host(req), "www.acme.com")623 # port shouldn't be in request-host624 req = Request("http://www.acme.com:2345/resource.html",625 headers={"Host": "www.acme.com:5432"})626 self.assertEquals(request_host(req), "www.acme.com")627628 def test_is_HDN(self):629 from cookielib import is_HDN630 self.assert_(is_HDN("foo.bar.com"))631 self.assert_(is_HDN("1foo2.3bar4.5com"))632 self.assert_(not is_HDN("192.168.1.1"))633 self.assert_(not is_HDN(""))634 self.assert_(not is_HDN("."))635 self.assert_(not is_HDN(".foo.bar.com"))636 self.assert_(not is_HDN("..foo"))637 self.assert_(not is_HDN("foo."))638639 def test_reach(self):640 from cookielib import reach641 self.assertEquals(reach("www.acme.com"), ".acme.com")642 self.assertEquals(reach("acme.com"), "acme.com")643 self.assertEquals(reach("acme.local"), ".local")644 self.assertEquals(reach(".local"), ".local")645 self.assertEquals(reach(".com"), ".com")646 self.assertEquals(reach("."), ".")647 self.assertEquals(reach(""), "")648 self.assertEquals(reach("192.168.0.1"), "192.168.0.1")649650 def test_domain_match(self):651 from cookielib import domain_match, user_domain_match652 self.assert_(domain_match("192.168.1.1", "192.168.1.1"))653 self.assert_(not domain_match("192.168.1.1", ".168.1.1"))654 self.assert_(domain_match("x.y.com", "x.Y.com"))655 self.assert_(domain_match("x.y.com", ".Y.com"))656 self.assert_(not domain_match("x.y.com", "Y.com"))657 self.assert_(domain_match("a.b.c.com", ".c.com"))658 self.assert_(not domain_match(".c.com", "a.b.c.com"))659 self.assert_(domain_match("example.local", ".local"))660 self.assert_(not domain_match("blah.blah", ""))661 self.assert_(not domain_match("", ".rhubarb.rhubarb"))662 self.assert_(domain_match("", ""))663664 self.assert_(user_domain_match("acme.com", "acme.com"))665 self.assert_(not user_domain_match("acme.com", ".acme.com"))666 self.assert_(user_domain_match("rhubarb.acme.com", ".acme.com"))667 self.assert_(user_domain_match("www.rhubarb.acme.com", ".acme.com"))668 self.assert_(user_domain_match("x.y.com", "x.Y.com"))669 self.assert_(user_domain_match("x.y.com", ".Y.com"))670 self.assert_(not user_domain_match("x.y.com", "Y.com"))671 self.assert_(user_domain_match("y.com", "Y.com"))672 self.assert_(not user_domain_match(".y.com", "Y.com"))673 self.assert_(user_domain_match(".y.com", ".Y.com"))674 self.assert_(user_domain_match("x.y.com", ".com"))675 self.assert_(not user_domain_match("x.y.com", "com"))676 self.assert_(not user_domain_match("x.y.com", "m"))677 self.assert_(not user_domain_match("x.y.com", ".m"))678 self.assert_(not user_domain_match("x.y.com", ""))679 self.assert_(not user_domain_match("x.y.com", "."))680 self.assert_(user_domain_match("192.168.1.1", "192.168.1.1"))681 # not both HDNs, so must string-compare equal to match682 self.assert_(not user_domain_match("192.168.1.1", ".168.1.1"))683 self.assert_(not user_domain_match("192.168.1.1", "."))684 # empty string is a special case685 self.assert_(not user_domain_match("192.168.1.1", ""))686687 def test_wrong_domain(self):688 # Cookies whose effective request-host name does not domain-match the689 # domain are rejected.690691 # XXX far from complete692 from cookielib import CookieJar693 c = CookieJar()694 interact_2965(c, "http://www.nasty.com/",695 'foo=bar; domain=friendly.org; Version="1"')696 self.assertEquals(len(c), 0)697698 def test_strict_domain(self):699 # Cookies whose domain is a country-code tld like .co.uk should700 # not be set if CookiePolicy.strict_domain is true.701 from cookielib import CookieJar, DefaultCookiePolicy702703 cp = DefaultCookiePolicy(strict_domain=True)704 cj = CookieJar(policy=cp)705 interact_netscape(cj, "http://example.co.uk/", 'no=problemo')706 interact_netscape(cj, "http://example.co.uk/",707 'okey=dokey; Domain=.example.co.uk')708 self.assertEquals(len(cj), 2)709 for pseudo_tld in [".co.uk", ".org.za", ".tx.us", ".name.us"]:710 interact_netscape(cj, "http://example.%s/" % pseudo_tld,711 'spam=eggs; Domain=.co.uk')712 self.assertEquals(len(cj), 2)713714 def test_two_component_domain_ns(self):715 # Netscape: .www.bar.com, www.bar.com, .bar.com, bar.com, no domain716 # should all get accepted, as should .acme.com, acme.com and no domain717 # for 2-component domains like acme.com.718 from cookielib import CookieJar, DefaultCookiePolicy719720 c = CookieJar()721722 # two-component V0 domain is OK723 interact_netscape(c, "http://foo.net/", 'ns=bar')724 self.assertEquals(len(c), 1)725 self.assertEquals(c._cookies["foo.net"]["/"]["ns"].value, "bar")726 self.assertEquals(interact_netscape(c, "http://foo.net/"), "ns=bar")727 # *will* be returned to any other domain (unlike RFC 2965)...728 self.assertEquals(interact_netscape(c, "http://www.foo.net/"),729 "ns=bar")730 # ...unless requested otherwise731 pol = DefaultCookiePolicy(732 strict_ns_domain=DefaultCookiePolicy.DomainStrictNonDomain)733 c.set_policy(pol)734 self.assertEquals(interact_netscape(c, "http://www.foo.net/"), "")735736 # unlike RFC 2965, even explicit two-component domain is OK,737 # because .foo.net matches foo.net738 interact_netscape(c, "http://foo.net/foo/",739 'spam1=eggs; domain=foo.net')740 # even if starts with a dot -- in NS rules, .foo.net matches foo.net!741 interact_netscape(c, "http://foo.net/foo/bar/",742 'spam2=eggs; domain=.foo.net')743 self.assertEquals(len(c), 3)744 self.assertEquals(c._cookies[".foo.net"]["/foo"]["spam1"].value,745 "eggs")746 self.assertEquals(c._cookies[".foo.net"]["/foo/bar"]["spam2"].value,747 "eggs")748 self.assertEquals(interact_netscape(c, "http://foo.net/foo/bar/"),749 "spam2=eggs; spam1=eggs; ns=bar")750751 # top-level domain is too general752 interact_netscape(c, "http://foo.net/", 'nini="ni"; domain=.net')753 self.assertEquals(len(c), 3)754755## # Netscape protocol doesn't allow non-special top level domains (such756## # as co.uk) in the domain attribute unless there are at least three757## # dots in it.758 # Oh yes it does! Real implementations don't check this, and real759 # cookies (of course) rely on that behaviour.760 interact_netscape(c, "http://foo.co.uk", 'nasty=trick; domain=.co.uk')761## self.assertEquals(len(c), 2)762 self.assertEquals(len(c), 4)763764 def test_two_component_domain_rfc2965(self):765 from cookielib import CookieJar, DefaultCookiePolicy766767 pol = DefaultCookiePolicy(rfc2965=True)768 c = CookieJar(pol)769770 # two-component V1 domain is OK771 interact_2965(c, "http://foo.net/", 'foo=bar; Version="1"')772 self.assertEquals(len(c), 1)773 self.assertEquals(c._cookies["foo.net"]["/"]["foo"].value, "bar")774 self.assertEquals(interact_2965(c, "http://foo.net/"),775 "$Version=1; foo=bar")776 # won't be returned to any other domain (because domain was implied)777 self.assertEquals(interact_2965(c, "http://www.foo.net/"), "")778779 # unless domain is given explicitly, because then it must be780 # rewritten to start with a dot: foo.net --> .foo.net, which does781 # not domain-match foo.net782 interact_2965(c, "http://foo.net/foo",783 'spam=eggs; domain=foo.net; path=/foo; Version="1"')784 self.assertEquals(len(c), 1)785 self.assertEquals(interact_2965(c, "http://foo.net/foo"),786 "$Version=1; foo=bar")787788 # explicit foo.net from three-component domain www.foo.net *does* get789 # set, because .foo.net domain-matches .foo.net790 interact_2965(c, "http://www.foo.net/foo/",791 'spam=eggs; domain=foo.net; Version="1"')792 self.assertEquals(c._cookies[".foo.net"]["/foo/"]["spam"].value,793 "eggs")794 self.assertEquals(len(c), 2)795 self.assertEquals(interact_2965(c, "http://foo.net/foo/"),796 "$Version=1; foo=bar")797 self.assertEquals(interact_2965(c, "http://www.foo.net/foo/"),798 '$Version=1; spam=eggs; $Domain="foo.net"')799800 # top-level domain is too general801 interact_2965(c, "http://foo.net/",802 'ni="ni"; domain=".net"; Version="1"')803 self.assertEquals(len(c), 2)804805 # RFC 2965 doesn't require blocking this806 interact_2965(c, "http://foo.co.uk/",807 'nasty=trick; domain=.co.uk; Version="1"')808 self.assertEquals(len(c), 3)809810 def test_domain_allow(self):811 from cookielib import CookieJar, DefaultCookiePolicy812 from urllib2 import Request813814 c = CookieJar(policy=DefaultCookiePolicy(815 blocked_domains=["acme.com"],816 allowed_domains=["www.acme.com"]))817818 req = Request("http://acme.com/")819 headers = ["Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/"]820 res = FakeResponse(headers, "http://acme.com/")821 c.extract_cookies(res, req)822 self.assertEquals(len(c), 0)823824 req = Request("http://www.acme.com/")825 res = FakeResponse(headers, "http://www.acme.com/")826 c.extract_cookies(res, req)827 self.assertEquals(len(c), 1)828829 req = Request("http://www.coyote.com/")830 res = FakeResponse(headers, "http://www.coyote.com/")831 c.extract_cookies(res, req)832 self.assertEquals(len(c), 1)833834 # set a cookie with non-allowed domain...835 req = Request("http://www.coyote.com/")836 res = FakeResponse(headers, "http://www.coyote.com/")837 cookies = c.make_cookies(res, req)838 c.set_cookie(cookies[0])839 self.assertEquals(len(c), 2)840 # ... and check is doesn't get returned841 c.add_cookie_header(req)842 self.assert_(not req.has_header("Cookie"))843844 def test_domain_block(self):845 from cookielib import CookieJar, DefaultCookiePolicy846 from urllib2 import Request847848 pol = DefaultCookiePolicy(849 rfc2965=True, blocked_domains=[".acme.com"])850 c = CookieJar(policy=pol)851 headers = ["Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/"]852853 req = Request("http://www.acme.com/")854 res = FakeResponse(headers, "http://www.acme.com/")855 c.extract_cookies(res, req)856 self.assertEquals(len(c), 0)857858 p = pol.set_blocked_domains(["acme.com"])859 c.extract_cookies(res, req)860 self.assertEquals(len(c), 1)861862 c.clear()863 req = Request("http://www.roadrunner.net/")864 res = FakeResponse(headers, "http://www.roadrunner.net/")865 c.extract_cookies(res, req)866 self.assertEquals(len(c), 1)867 req = Request("http://www.roadrunner.net/")868 c.add_cookie_header(req)869 self.assert_((req.has_header("Cookie") and870 req.has_header("Cookie2")))871872 c.clear()873 pol.set_blocked_domains([".acme.com"])874 c.extract_cookies(res, req)875 self.assertEquals(len(c), 1)876877 # set a cookie with blocked domain...878 req = Request("http://www.acme.com/")879 res = FakeResponse(headers, "http://www.acme.com/")880 cookies = c.make_cookies(res, req)881 c.set_cookie(cookies[0])882 self.assertEquals(len(c), 2)883 # ... and check is doesn't get returned884 c.add_cookie_header(req)885 self.assert_(not req.has_header("Cookie"))886887 def test_secure(self):888 from cookielib import CookieJar, DefaultCookiePolicy889890 for ns in True, False:891 for whitespace in " ", "":892 c = CookieJar()893 if ns:894 pol = DefaultCookiePolicy(rfc2965=False)895 int = interact_netscape
...
cookielib.py
Source:cookielib.py
...1359 self._cookies_lock.acquire()1360 try:1361 self._policy._now = self._now = int(time.time())1362 if self._policy.set_ok(cookie, request):1363 self.set_cookie(cookie)1364 finally:1365 self._cookies_lock.release()1366 def set_cookie(self, cookie):1367 """Set a cookie, without checking whether or not it should be set."""1368 c = self._cookies1369 self._cookies_lock.acquire()1370 try:1371 if cookie.domain not in c: c[cookie.domain] = {}1372 c2 = c[cookie.domain]1373 if cookie.path not in c2: c2[cookie.path] = {}1374 c3 = c2[cookie.path]1375 c3[cookie.name] = cookie1376 finally:1377 self._cookies_lock.release()1378 def extract_cookies(self, response, request):1379 """Extract cookies from response, where allowable given the request."""1380 _debug("extract_cookies: %s", response.info())1381 self._cookies_lock.acquire()1382 try:1383 self._policy._now = self._now = int(time.time())1384 for cookie in self.make_cookies(response, request):1385 if self._policy.set_ok(cookie, request):1386 _debug(" setting cookie: %s", cookie)1387 self.set_cookie(cookie)1388 finally:1389 self._cookies_lock.release()1390 def clear(self, domain=None, path=None, name=None):1391 """Clear some cookies.1392 Invoking this method without arguments will clear all cookies. If1393 given a single argument, only cookies belonging to that domain will be1394 removed. If given two arguments, cookies belonging to the specified1395 path within that domain are removed. If given three arguments, then1396 the cookie with the specified name, path and domain is removed.1397 Raises KeyError if no matching cookie exists.1398 """1399 if name is not None:1400 if (domain is None) or (path is None):1401 raise ValueError(...
cookie-coverage.js
Source:cookie-coverage.js
1/*2YUI 3.7.3 (build 5687)3Copyright 2012 Yahoo! Inc. All rights reserved.4Licensed under the BSD License.5http://yuilibrary.com/license/6*/7if (typeof _yuitest_coverage == "undefined"){8 _yuitest_coverage = {};9 _yuitest_coverline = function(src, line){10 var coverage = _yuitest_coverage[src];11 if (!coverage.lines[line]){12 coverage.calledLines++;13 }14 coverage.lines[line]++;15 };16 _yuitest_coverfunc = function(src, name, line){17 var coverage = _yuitest_coverage[src],18 funcId = name + ":" + line;19 if (!coverage.functions[funcId]){20 coverage.calledFunctions++;21 }22 coverage.functions[funcId]++;23 };24}25_yuitest_coverage["build/cookie/cookie.js"] = {26 lines: {},27 functions: {},28 coveredLines: 0,29 calledLines: 0,30 coveredFunctions: 0,31 calledFunctions: 0,32 path: "build/cookie/cookie.js",33 code: []34};35_yuitest_coverage["build/cookie/cookie.js"].code=["YUI.add('cookie', function (Y, NAME) {","","/**"," * Utilities for cookie management"," * @module cookie"," */",""," //shortcuts"," var L = Y.Lang,"," O = Y.Object,"," NULL = null,"," "," //shortcuts to functions"," isString = L.isString,"," isObject = L.isObject,"," isUndefined = L.isUndefined,"," isFunction = L.isFunction,"," encode = encodeURIComponent,"," decode = decodeURIComponent,"," "," //shortcut to document"," doc = Y.config.doc;"," "," /*"," * Throws an error message."," */"," function error(message){"," throw new TypeError(message);"," } "," "," /*"," * Checks the validity of a cookie name."," */"," function validateCookieName(name){"," if (!isString(name) || name === \"\"){"," error(\"Cookie name must be a non-empty string.\");"," } "," }"," "," /*"," * Checks the validity of a subcookie name."," */ "," function validateSubcookieName(subName){"," if (!isString(subName) || subName === \"\"){"," error(\"Subcookie name must be a non-empty string.\");"," } "," }"," "," /**"," * Cookie utility."," * @class Cookie"," * @static"," */"," Y.Cookie = {"," "," //-------------------------------------------------------------------------"," // Private Methods"," //-------------------------------------------------------------------------"," "," /**"," * Creates a cookie string that can be assigned into document.cookie."," * @param {String} name The name of the cookie."," * @param {String} value The value of the cookie."," * @param {Boolean} encodeValue True to encode the value, false to leave as-is."," * @param {Object} options (Optional) Options for the cookie."," * @return {String} The formatted cookie string."," * @method _createCookieString"," * @private"," * @static"," */"," _createCookieString : function (name /*:String*/, value /*:Variant*/, encodeValue /*:Boolean*/, options /*:Object*/) /*:String*/ {"," "," options = options || {};"," "," var text /*:String*/ = encode(name) + \"=\" + (encodeValue ? encode(value) : value),"," expires = options.expires,"," path = options.path,"," domain = options.domain;"," "," "," if (isObject(options)){"," //expiration date"," if (expires instanceof Date){"," text += \"; expires=\" + expires.toUTCString();"," }"," "," //path"," if (isString(path) && path !== \"\"){"," text += \"; path=\" + path;"," }"," "," //domain"," if (isString(domain) && domain !== \"\"){"," text += \"; domain=\" + domain;"," }"," "," //secure"," if (options.secure === true){"," text += \"; secure\";"," }"," }"," "," return text;"," },"," "," /**"," * Formats a cookie value for an object containing multiple values."," * @param {Object} hash An object of key-value pairs to create a string for."," * @return {String} A string suitable for use as a cookie value."," * @method _createCookieHashString"," * @private"," * @static"," */"," _createCookieHashString : function (hash /*:Object*/) /*:String*/ {"," if (!isObject(hash)){"," error(\"Cookie._createCookieHashString(): Argument must be an object.\");"," }"," "," var text /*:Array*/ = [];",""," O.each(hash, function(value, key){"," if (!isFunction(value) && !isUndefined(value)){"," text.push(encode(key) + \"=\" + encode(String(value)));"," } "," });"," "," return text.join(\"&\");"," },"," "," /**"," * Parses a cookie hash string into an object."," * @param {String} text The cookie hash string to parse (format: n1=v1&n2=v2)."," * @return {Object} An object containing entries for each cookie value."," * @method _parseCookieHash"," * @private"," * @static"," */"," _parseCookieHash : function (text) {"," "," var hashParts = text.split(\"&\"),"," hashPart = NULL,"," hash = {};"," "," if (text.length){"," for (var i=0, len=hashParts.length; i < len; i++){"," hashPart = hashParts[i].split(\"=\");"," hash[decode(hashPart[0])] = decode(hashPart[1]);"," }"," }"," "," return hash; "," },"," "," /**"," * Parses a cookie string into an object representing all accessible cookies."," * @param {String} text The cookie string to parse."," * @param {Boolean} shouldDecode (Optional) Indicates if the cookie values should be decoded or not. Default is true."," * @return {Object} An object containing entries for each accessible cookie."," * @method _parseCookieString"," * @private"," * @static"," */"," _parseCookieString : function (text /*:String*/, shouldDecode /*:Boolean*/) /*:Object*/ {"," "," var cookies /*:Object*/ = {}; "," "," if (isString(text) && text.length > 0) {"," "," var decodeValue = (shouldDecode === false ? function(s){return s;} : decode), "," cookieParts = text.split(/;\\s/g),"," cookieName = NULL,"," cookieValue = NULL,"," cookieNameValue = NULL;"," "," for (var i=0, len=cookieParts.length; i < len; i++){"," "," //check for normally-formatted cookie (name-value)"," cookieNameValue = cookieParts[i].match(/([^=]+)=/i);"," if (cookieNameValue instanceof Array){"," try {"," cookieName = decode(cookieNameValue[1]);"," cookieValue = decodeValue(cookieParts[i].substring(cookieNameValue[1].length+1));"," } catch (ex){"," //intentionally ignore the cookie - the encoding is wrong"," }"," } else {"," //means the cookie does not have an \"=\", so treat it as a boolean flag"," cookieName = decode(cookieParts[i]);"," cookieValue = \"\";"," }"," cookies[cookieName] = cookieValue;"," }",""," }"," "," return cookies;"," }, "," "," /**"," * Sets the document object that the cookie utility uses for setting"," * cookies. This method is necessary to ensure that the cookie utility"," * unit tests can pass even when run on a domain instead of locally."," * This method should not be used otherwise; you should use "," * <code>Y.config.doc</code> to change the document that the cookie"," * utility uses for everyday purposes."," * @param {Object} newDoc The object to use as the document."," * @return {void}"," * @method _setDoc"," * @private"," */ "," _setDoc: function(newDoc){"," doc = newDoc;"," },"," "," //-------------------------------------------------------------------------"," // Public Methods"," //-------------------------------------------------------------------------"," "," /**"," * Determines if the cookie with the given name exists. This is useful for"," * Boolean cookies (those that do not follow the name=value convention)."," * @param {String} name The name of the cookie to check."," * @return {Boolean} True if the cookie exists, false if not."," * @method exists"," * @static"," */"," exists: function(name) {"," "," validateCookieName(name); //throws error"," "," var cookies = this._parseCookieString(doc.cookie, true);"," "," return cookies.hasOwnProperty(name);"," }, "," "," /**"," * Returns the cookie value for the given name."," * @param {String} name The name of the cookie to retrieve."," * @param {Function|Object} options (Optional) An object containing one or more"," * cookie options: raw (true/false) and converter (a function)."," * The converter function is run on the value before returning it. The"," * function is not used if the cookie doesn't exist. The function can be"," * passed instead of the options object for backwards compatibility. When"," * raw is set to true, the cookie value is not URI decoded."," * @return {Variant} If no converter is specified, returns a string or null if"," * the cookie doesn't exist. If the converter is specified, returns the value"," * returned from the converter or null if the cookie doesn't exist."," * @method get"," * @static"," */"," get : function (name, options) {"," "," validateCookieName(name); //throws error "," "," var cookies,"," cookie,"," converter;"," "," //if options is a function, then it's the converter"," if (isFunction(options)) {"," converter = options;"," options = {};"," } else if (isObject(options)) {"," converter = options.converter;"," } else {"," options = {};"," }"," "," cookies = this._parseCookieString(doc.cookie, !options.raw);"," cookie = cookies[name];"," "," //should return null, not undefined if the cookie doesn't exist"," if (isUndefined(cookie)) {"," return NULL;"," }"," "," if (!isFunction(converter)){"," return cookie;"," } else {"," return converter(cookie);"," }"," },"," "," /**"," * Returns the value of a subcookie."," * @param {String} name The name of the cookie to retrieve."," * @param {String} subName The name of the subcookie to retrieve."," * @param {Function} converter (Optional) A function to run on the value before returning"," * it. The function is not used if the cookie doesn't exist."," * @return {Variant} If the cookie doesn't exist, null is returned. If the subcookie"," * doesn't exist, null if also returned. If no converter is specified and the"," * subcookie exists, a string is returned. If a converter is specified and the"," * subcookie exists, the value returned from the converter is returned."," * @method getSub"," * @static"," */"," getSub : function (name /*:String*/, subName /*:String*/, converter /*:Function*/) /*:Variant*/ {"," "," var hash /*:Variant*/ = this.getSubs(name); "," "," if (hash !== NULL) {"," "," validateSubcookieName(subName); //throws error"," "," if (isUndefined(hash[subName])){"," return NULL;"," } "," "," if (!isFunction(converter)){"," return hash[subName];"," } else {"," return converter(hash[subName]);"," }"," } else {"," return NULL;"," }"," "," },"," "," /**"," * Returns an object containing name-value pairs stored in the cookie with the given name."," * @param {String} name The name of the cookie to retrieve."," * @return {Object} An object of name-value pairs if the cookie with the given name"," * exists, null if it does not."," * @method getSubs"," * @static"," */"," getSubs : function (name) {"," "," validateCookieName(name); //throws error"," "," var cookies = this._parseCookieString(doc.cookie, false);"," if (isString(cookies[name])){"," return this._parseCookieHash(cookies[name]);"," }"," return NULL;"," },"," "," /**"," * Removes a cookie from the machine by setting its expiration date to"," * sometime in the past."," * @param {String} name The name of the cookie to remove."," * @param {Object} options (Optional) An object containing one or more"," * cookie options: path (a string), domain (a string), "," * and secure (true/false). The expires option will be overwritten"," * by the method."," * @return {String} The created cookie string."," * @method remove"," * @static"," */"," remove : function (name, options) {"," "," validateCookieName(name); //throws error"," "," //set options"," options = Y.merge(options || {}, {"," expires: new Date(0)"," });"," "," //set cookie"," return this.set(name, \"\", options);"," },"," "," /**"," * Removes a sub cookie with a given name."," * @param {String} name The name of the cookie in which the subcookie exists."," * @param {String} subName The name of the subcookie to remove."," * @param {Object} options (Optional) An object containing one or more"," * cookie options: path (a string), domain (a string), expires (a Date object),"," * removeIfEmpty (true/false), and secure (true/false). This must be the same"," * settings as the original subcookie."," * @return {String} The created cookie string."," * @method removeSub"," * @static"," */"," removeSub : function(name, subName, options) {"," "," validateCookieName(name); //throws error"," "," validateSubcookieName(subName); //throws error"," "," options = options || {};"," "," //get all subcookies for this cookie"," var subs = this.getSubs(name);"," "," //delete the indicated subcookie"," if (isObject(subs) && subs.hasOwnProperty(subName)){"," delete subs[subName];"," "," if (!options.removeIfEmpty) {"," //reset the cookie"," "," return this.setSubs(name, subs, options);"," } else {"," //reset the cookie if there are subcookies left, else remove"," for (var key in subs){"," if (subs.hasOwnProperty(key) && !isFunction(subs[key]) && !isUndefined(subs[key])){"," return this.setSubs(name, subs, options);"," }"," }"," "," return this.remove(name, options);"," } "," } else {"," return \"\";"," }"," "," },"," "," /**"," * Sets a cookie with a given name and value."," * @param {String} name The name of the cookie to set."," * @param {Variant} value The value to set for the cookie."," * @param {Object} options (Optional) An object containing one or more"," * cookie options: path (a string), domain (a string), expires (a Date object),"," * secure (true/false), and raw (true/false). Setting raw to true indicates"," * that the cookie should not be URI encoded before being set."," * @return {String} The created cookie string."," * @method set"," * @static"," */"," set : function (name, value, options) {"," "," validateCookieName(name); //throws error"," "," if (isUndefined(value)){"," error(\"Cookie.set(): Value cannot be undefined.\");"," }"," "," options = options || {};"," "," var text = this._createCookieString(name, value, !options.raw, options);"," doc.cookie = text;"," return text;"," },"," "," /**"," * Sets a sub cookie with a given name to a particular value."," * @param {String} name The name of the cookie to set."," * @param {String} subName The name of the subcookie to set."," * @param {Variant} value The value to set."," * @param {Object} options (Optional) An object containing one or more"," * cookie options: path (a string), domain (a string), expires (a Date object),"," * and secure (true/false)."," * @return {String} The created cookie string."," * @method setSub"," * @static"," */"," setSub : function (name, subName, value, options) {",""," validateCookieName(name); //throws error"," "," validateSubcookieName(subName); //throws error"," "," if (isUndefined(value)){"," error(\"Cookie.setSub(): Subcookie value cannot be undefined.\");"," }"," "," var hash = this.getSubs(name);"," "," if (!isObject(hash)){"," hash = {};"," }"," "," hash[subName] = value; "," "," return this.setSubs(name, hash, options);"," "," },"," "," /**"," * Sets a cookie with a given name to contain a hash of name-value pairs."," * @param {String} name The name of the cookie to set."," * @param {Object} value An object containing name-value pairs."," * @param {Object} options (Optional) An object containing one or more"," * cookie options: path (a string), domain (a string), expires (a Date object),"," * and secure (true/false)."," * @return {String} The created cookie string."," * @method setSubs"," * @static"," */"," setSubs : function (name, value, options) {"," "," validateCookieName(name); //throws error"," "," if (!isObject(value)){"," error(\"Cookie.setSubs(): Cookie value must be an object.\");"," }"," "," var text /*:String*/ = this._createCookieString(name, this._createCookieHashString(value), false, options);"," doc.cookie = text;"," return text; "," } "," "," };","","","}, '3.7.3', {\"requires\": [\"yui-base\"]});"];36_yuitest_coverage["build/cookie/cookie.js"].lines = {"1":0,"9":0,"27":0,"28":0,"34":0,"35":0,"36":0,"43":0,"44":0,"45":0,"54":0,"73":0,"75":0,"81":0,"83":0,"84":0,"88":0,"89":0,"93":0,"94":0,"98":0,"99":0,"103":0,"115":0,"116":0,"119":0,"121":0,"122":0,"123":0,"127":0,"140":0,"144":0,"145":0,"146":0,"147":0,"151":0,"165":0,"167":0,"169":0,"175":0,"178":0,"179":0,"180":0,"181":0,"182":0,"188":0,"189":0,"191":0,"196":0,"212":0,"229":0,"231":0,"233":0,"253":0,"255":0,"260":0,"261":0,"262":0,"263":0,"264":0,"266":0,"269":0,"270":0,"273":0,"274":0,"277":0,"278":0,"280":0,"299":0,"301":0,"303":0,"305":0,"306":0,"309":0,"310":0,"312":0,"315":0,"330":0,"332":0,"333":0,"334":0,"336":0,"353":0,"356":0,"361":0,"378":0,"380":0,"382":0,"385":0,"388":0,"389":0,"391":0,"394":0,"397":0,"398":0,"399":0,"403":0,"406":0,"425":0,"427":0,"428":0,"431":0,"433":0,"434":0,"435":0,"452":0,"454":0,"456":0,"457":0,"460":0,"462":0,"463":0,"466":0,"468":0,"485":0,"487":0,"488":0,"491":0,"492":0,"493":0};37_yuitest_coverage["build/cookie/cookie.js"].functions = {"error:27":0,"validateCookieName:34":0,"validateSubcookieName:43":0,"_createCookieString:71":0,"(anonymous 2):121":0,"_createCookieHashString:114":0,"_parseCookieHash:138":0,"(anonymous 3):169":0,"_parseCookieString:163":0,"_setDoc:211":0,"exists:227":0,"get:251":0,"getSub:297":0,"getSubs:328":0,"remove:351":0,"removeSub:376":0,"set:423":0,"setSub:450":0,"setSubs:483":0,"(anonymous 1):1":0};38_yuitest_coverage["build/cookie/cookie.js"].coveredLines = 120;39_yuitest_coverage["build/cookie/cookie.js"].coveredFunctions = 20;40_yuitest_coverline("build/cookie/cookie.js", 1);41YUI.add('cookie', function (Y, NAME) {42/**43 * Utilities for cookie management44 * @module cookie45 */46 //shortcuts47 _yuitest_coverfunc("build/cookie/cookie.js", "(anonymous 1)", 1);48_yuitest_coverline("build/cookie/cookie.js", 9);49var L = Y.Lang,50 O = Y.Object,51 NULL = null,52 53 //shortcuts to functions54 isString = L.isString,55 isObject = L.isObject,56 isUndefined = L.isUndefined,57 isFunction = L.isFunction,58 encode = encodeURIComponent,59 decode = decodeURIComponent,60 61 //shortcut to document62 doc = Y.config.doc;63 64 /*65 * Throws an error message.66 */67 _yuitest_coverline("build/cookie/cookie.js", 27);68function error(message){69 _yuitest_coverfunc("build/cookie/cookie.js", "error", 27);70_yuitest_coverline("build/cookie/cookie.js", 28);71throw new TypeError(message);72 } 73 74 /*75 * Checks the validity of a cookie name.76 */77 _yuitest_coverline("build/cookie/cookie.js", 34);78function validateCookieName(name){79 _yuitest_coverfunc("build/cookie/cookie.js", "validateCookieName", 34);80_yuitest_coverline("build/cookie/cookie.js", 35);81if (!isString(name) || name === ""){82 _yuitest_coverline("build/cookie/cookie.js", 36);83error("Cookie name must be a non-empty string.");84 } 85 }86 87 /*88 * Checks the validity of a subcookie name.89 */ 90 _yuitest_coverline("build/cookie/cookie.js", 43);91function validateSubcookieName(subName){92 _yuitest_coverfunc("build/cookie/cookie.js", "validateSubcookieName", 43);93_yuitest_coverline("build/cookie/cookie.js", 44);94if (!isString(subName) || subName === ""){95 _yuitest_coverline("build/cookie/cookie.js", 45);96error("Subcookie name must be a non-empty string.");97 } 98 }99 100 /**101 * Cookie utility.102 * @class Cookie103 * @static104 */105 _yuitest_coverline("build/cookie/cookie.js", 54);106Y.Cookie = {107 108 //-------------------------------------------------------------------------109 // Private Methods110 //-------------------------------------------------------------------------111 112 /**113 * Creates a cookie string that can be assigned into document.cookie.114 * @param {String} name The name of the cookie.115 * @param {String} value The value of the cookie.116 * @param {Boolean} encodeValue True to encode the value, false to leave as-is.117 * @param {Object} options (Optional) Options for the cookie.118 * @return {String} The formatted cookie string.119 * @method _createCookieString120 * @private121 * @static122 */123 _createCookieString : function (name /*:String*/, value /*:Variant*/, encodeValue /*:Boolean*/, options /*:Object*/) /*:String*/ {124 125 _yuitest_coverfunc("build/cookie/cookie.js", "_createCookieString", 71);126_yuitest_coverline("build/cookie/cookie.js", 73);127options = options || {};128 129 _yuitest_coverline("build/cookie/cookie.js", 75);130var text /*:String*/ = encode(name) + "=" + (encodeValue ? encode(value) : value),131 expires = options.expires,132 path = options.path,133 domain = options.domain;134 135 136 _yuitest_coverline("build/cookie/cookie.js", 81);137if (isObject(options)){138 //expiration date139 _yuitest_coverline("build/cookie/cookie.js", 83);140if (expires instanceof Date){141 _yuitest_coverline("build/cookie/cookie.js", 84);142text += "; expires=" + expires.toUTCString();143 }144 145 //path146 _yuitest_coverline("build/cookie/cookie.js", 88);147if (isString(path) && path !== ""){148 _yuitest_coverline("build/cookie/cookie.js", 89);149text += "; path=" + path;150 }151 152 //domain153 _yuitest_coverline("build/cookie/cookie.js", 93);154if (isString(domain) && domain !== ""){155 _yuitest_coverline("build/cookie/cookie.js", 94);156text += "; domain=" + domain;157 }158 159 //secure160 _yuitest_coverline("build/cookie/cookie.js", 98);161if (options.secure === true){162 _yuitest_coverline("build/cookie/cookie.js", 99);163text += "; secure";164 }165 }166 167 _yuitest_coverline("build/cookie/cookie.js", 103);168return text;169 },170 171 /**172 * Formats a cookie value for an object containing multiple values.173 * @param {Object} hash An object of key-value pairs to create a string for.174 * @return {String} A string suitable for use as a cookie value.175 * @method _createCookieHashString176 * @private177 * @static178 */179 _createCookieHashString : function (hash /*:Object*/) /*:String*/ {180 _yuitest_coverfunc("build/cookie/cookie.js", "_createCookieHashString", 114);181_yuitest_coverline("build/cookie/cookie.js", 115);182if (!isObject(hash)){183 _yuitest_coverline("build/cookie/cookie.js", 116);184error("Cookie._createCookieHashString(): Argument must be an object.");185 }186 187 _yuitest_coverline("build/cookie/cookie.js", 119);188var text /*:Array*/ = [];189 _yuitest_coverline("build/cookie/cookie.js", 121);190O.each(hash, function(value, key){191 _yuitest_coverfunc("build/cookie/cookie.js", "(anonymous 2)", 121);192_yuitest_coverline("build/cookie/cookie.js", 122);193if (!isFunction(value) && !isUndefined(value)){194 _yuitest_coverline("build/cookie/cookie.js", 123);195text.push(encode(key) + "=" + encode(String(value)));196 } 197 });198 199 _yuitest_coverline("build/cookie/cookie.js", 127);200return text.join("&");201 },202 203 /**204 * Parses a cookie hash string into an object.205 * @param {String} text The cookie hash string to parse (format: n1=v1&n2=v2).206 * @return {Object} An object containing entries for each cookie value.207 * @method _parseCookieHash208 * @private209 * @static210 */211 _parseCookieHash : function (text) {212 213 _yuitest_coverfunc("build/cookie/cookie.js", "_parseCookieHash", 138);214_yuitest_coverline("build/cookie/cookie.js", 140);215var hashParts = text.split("&"),216 hashPart = NULL,217 hash = {};218 219 _yuitest_coverline("build/cookie/cookie.js", 144);220if (text.length){221 _yuitest_coverline("build/cookie/cookie.js", 145);222for (var i=0, len=hashParts.length; i < len; i++){223 _yuitest_coverline("build/cookie/cookie.js", 146);224hashPart = hashParts[i].split("=");225 _yuitest_coverline("build/cookie/cookie.js", 147);226hash[decode(hashPart[0])] = decode(hashPart[1]);227 }228 }229 230 _yuitest_coverline("build/cookie/cookie.js", 151);231return hash; 232 },233 234 /**235 * Parses a cookie string into an object representing all accessible cookies.236 * @param {String} text The cookie string to parse.237 * @param {Boolean} shouldDecode (Optional) Indicates if the cookie values should be decoded or not. Default is true.238 * @return {Object} An object containing entries for each accessible cookie.239 * @method _parseCookieString240 * @private241 * @static242 */243 _parseCookieString : function (text /*:String*/, shouldDecode /*:Boolean*/) /*:Object*/ {244 245 _yuitest_coverfunc("build/cookie/cookie.js", "_parseCookieString", 163);246_yuitest_coverline("build/cookie/cookie.js", 165);247var cookies /*:Object*/ = {}; 248 249 _yuitest_coverline("build/cookie/cookie.js", 167);250if (isString(text) && text.length > 0) {251 252 _yuitest_coverline("build/cookie/cookie.js", 169);253var decodeValue = (shouldDecode === false ? function(s){_yuitest_coverfunc("build/cookie/cookie.js", "(anonymous 3)", 169);254return s;} : decode), 255 cookieParts = text.split(/;\s/g),256 cookieName = NULL,257 cookieValue = NULL,258 cookieNameValue = NULL;259 260 _yuitest_coverline("build/cookie/cookie.js", 175);261for (var i=0, len=cookieParts.length; i < len; i++){262 263 //check for normally-formatted cookie (name-value)264 _yuitest_coverline("build/cookie/cookie.js", 178);265cookieNameValue = cookieParts[i].match(/([^=]+)=/i);266 _yuitest_coverline("build/cookie/cookie.js", 179);267if (cookieNameValue instanceof Array){268 _yuitest_coverline("build/cookie/cookie.js", 180);269try {270 _yuitest_coverline("build/cookie/cookie.js", 181);271cookieName = decode(cookieNameValue[1]);272 _yuitest_coverline("build/cookie/cookie.js", 182);273cookieValue = decodeValue(cookieParts[i].substring(cookieNameValue[1].length+1));274 } catch (ex){275 //intentionally ignore the cookie - the encoding is wrong276 }277 } else {278 //means the cookie does not have an "=", so treat it as a boolean flag279 _yuitest_coverline("build/cookie/cookie.js", 188);280cookieName = decode(cookieParts[i]);281 _yuitest_coverline("build/cookie/cookie.js", 189);282cookieValue = "";283 }284 _yuitest_coverline("build/cookie/cookie.js", 191);285cookies[cookieName] = cookieValue;286 }287 }288 289 _yuitest_coverline("build/cookie/cookie.js", 196);290return cookies;291 }, 292 293 /**294 * Sets the document object that the cookie utility uses for setting295 * cookies. This method is necessary to ensure that the cookie utility296 * unit tests can pass even when run on a domain instead of locally.297 * This method should not be used otherwise; you should use 298 * <code>Y.config.doc</code> to change the document that the cookie299 * utility uses for everyday purposes.300 * @param {Object} newDoc The object to use as the document.301 * @return {void}302 * @method _setDoc303 * @private304 */ 305 _setDoc: function(newDoc){306 _yuitest_coverfunc("build/cookie/cookie.js", "_setDoc", 211);307_yuitest_coverline("build/cookie/cookie.js", 212);308doc = newDoc;309 },310 311 //-------------------------------------------------------------------------312 // Public Methods313 //-------------------------------------------------------------------------314 315 /**316 * Determines if the cookie with the given name exists. This is useful for317 * Boolean cookies (those that do not follow the name=value convention).318 * @param {String} name The name of the cookie to check.319 * @return {Boolean} True if the cookie exists, false if not.320 * @method exists321 * @static322 */323 exists: function(name) {324 325 _yuitest_coverfunc("build/cookie/cookie.js", "exists", 227);326_yuitest_coverline("build/cookie/cookie.js", 229);327validateCookieName(name); //throws error328 329 _yuitest_coverline("build/cookie/cookie.js", 231);330var cookies = this._parseCookieString(doc.cookie, true);331 332 _yuitest_coverline("build/cookie/cookie.js", 233);333return cookies.hasOwnProperty(name);334 }, 335 336 /**337 * Returns the cookie value for the given name.338 * @param {String} name The name of the cookie to retrieve.339 * @param {Function|Object} options (Optional) An object containing one or more340 * cookie options: raw (true/false) and converter (a function).341 * The converter function is run on the value before returning it. The342 * function is not used if the cookie doesn't exist. The function can be343 * passed instead of the options object for backwards compatibility. When344 * raw is set to true, the cookie value is not URI decoded.345 * @return {Variant} If no converter is specified, returns a string or null if346 * the cookie doesn't exist. If the converter is specified, returns the value347 * returned from the converter or null if the cookie doesn't exist.348 * @method get349 * @static350 */351 get : function (name, options) {352 353 _yuitest_coverfunc("build/cookie/cookie.js", "get", 251);354_yuitest_coverline("build/cookie/cookie.js", 253);355validateCookieName(name); //throws error 356 357 _yuitest_coverline("build/cookie/cookie.js", 255);358var cookies,359 cookie,360 converter;361 362 //if options is a function, then it's the converter363 _yuitest_coverline("build/cookie/cookie.js", 260);364if (isFunction(options)) {365 _yuitest_coverline("build/cookie/cookie.js", 261);366converter = options;367 _yuitest_coverline("build/cookie/cookie.js", 262);368options = {};369 } else {_yuitest_coverline("build/cookie/cookie.js", 263);370if (isObject(options)) {371 _yuitest_coverline("build/cookie/cookie.js", 264);372converter = options.converter;373 } else {374 _yuitest_coverline("build/cookie/cookie.js", 266);375options = {};376 }}377 378 _yuitest_coverline("build/cookie/cookie.js", 269);379cookies = this._parseCookieString(doc.cookie, !options.raw);380 _yuitest_coverline("build/cookie/cookie.js", 270);381cookie = cookies[name];382 383 //should return null, not undefined if the cookie doesn't exist384 _yuitest_coverline("build/cookie/cookie.js", 273);385if (isUndefined(cookie)) {386 _yuitest_coverline("build/cookie/cookie.js", 274);387return NULL;388 }389 390 _yuitest_coverline("build/cookie/cookie.js", 277);391if (!isFunction(converter)){392 _yuitest_coverline("build/cookie/cookie.js", 278);393return cookie;394 } else {395 _yuitest_coverline("build/cookie/cookie.js", 280);396return converter(cookie);397 }398 },399 400 /**401 * Returns the value of a subcookie.402 * @param {String} name The name of the cookie to retrieve.403 * @param {String} subName The name of the subcookie to retrieve.404 * @param {Function} converter (Optional) A function to run on the value before returning405 * it. The function is not used if the cookie doesn't exist.406 * @return {Variant} If the cookie doesn't exist, null is returned. If the subcookie407 * doesn't exist, null if also returned. If no converter is specified and the408 * subcookie exists, a string is returned. If a converter is specified and the409 * subcookie exists, the value returned from the converter is returned.410 * @method getSub411 * @static412 */413 getSub : function (name /*:String*/, subName /*:String*/, converter /*:Function*/) /*:Variant*/ {414 415 _yuitest_coverfunc("build/cookie/cookie.js", "getSub", 297);416_yuitest_coverline("build/cookie/cookie.js", 299);417var hash /*:Variant*/ = this.getSubs(name); 418 419 _yuitest_coverline("build/cookie/cookie.js", 301);420if (hash !== NULL) {421 422 _yuitest_coverline("build/cookie/cookie.js", 303);423validateSubcookieName(subName); //throws error424 425 _yuitest_coverline("build/cookie/cookie.js", 305);426if (isUndefined(hash[subName])){427 _yuitest_coverline("build/cookie/cookie.js", 306);428return NULL;429 } 430 431 _yuitest_coverline("build/cookie/cookie.js", 309);432if (!isFunction(converter)){433 _yuitest_coverline("build/cookie/cookie.js", 310);434return hash[subName];435 } else {436 _yuitest_coverline("build/cookie/cookie.js", 312);437return converter(hash[subName]);438 }439 } else {440 _yuitest_coverline("build/cookie/cookie.js", 315);441return NULL;442 }443 444 },445 446 /**447 * Returns an object containing name-value pairs stored in the cookie with the given name.448 * @param {String} name The name of the cookie to retrieve.449 * @return {Object} An object of name-value pairs if the cookie with the given name450 * exists, null if it does not.451 * @method getSubs452 * @static453 */454 getSubs : function (name) {455 456 _yuitest_coverfunc("build/cookie/cookie.js", "getSubs", 328);457_yuitest_coverline("build/cookie/cookie.js", 330);458validateCookieName(name); //throws error459 460 _yuitest_coverline("build/cookie/cookie.js", 332);461var cookies = this._parseCookieString(doc.cookie, false);462 _yuitest_coverline("build/cookie/cookie.js", 333);463if (isString(cookies[name])){464 _yuitest_coverline("build/cookie/cookie.js", 334);465return this._parseCookieHash(cookies[name]);466 }467 _yuitest_coverline("build/cookie/cookie.js", 336);468return NULL;469 },470 471 /**472 * Removes a cookie from the machine by setting its expiration date to473 * sometime in the past.474 * @param {String} name The name of the cookie to remove.475 * @param {Object} options (Optional) An object containing one or more476 * cookie options: path (a string), domain (a string), 477 * and secure (true/false). The expires option will be overwritten478 * by the method.479 * @return {String} The created cookie string.480 * @method remove481 * @static482 */483 remove : function (name, options) {484 485 _yuitest_coverfunc("build/cookie/cookie.js", "remove", 351);486_yuitest_coverline("build/cookie/cookie.js", 353);487validateCookieName(name); //throws error488 489 //set options490 _yuitest_coverline("build/cookie/cookie.js", 356);491options = Y.merge(options || {}, {492 expires: new Date(0)493 });494 495 //set cookie496 _yuitest_coverline("build/cookie/cookie.js", 361);497return this.set(name, "", options);498 },499 500 /**501 * Removes a sub cookie with a given name.502 * @param {String} name The name of the cookie in which the subcookie exists.503 * @param {String} subName The name of the subcookie to remove.504 * @param {Object} options (Optional) An object containing one or more505 * cookie options: path (a string), domain (a string), expires (a Date object),506 * removeIfEmpty (true/false), and secure (true/false). This must be the same507 * settings as the original subcookie.508 * @return {String} The created cookie string.509 * @method removeSub510 * @static511 */512 removeSub : function(name, subName, options) {513 514 _yuitest_coverfunc("build/cookie/cookie.js", "removeSub", 376);515_yuitest_coverline("build/cookie/cookie.js", 378);516validateCookieName(name); //throws error517 518 _yuitest_coverline("build/cookie/cookie.js", 380);519validateSubcookieName(subName); //throws error520 521 _yuitest_coverline("build/cookie/cookie.js", 382);522options = options || {};523 524 //get all subcookies for this cookie525 _yuitest_coverline("build/cookie/cookie.js", 385);526var subs = this.getSubs(name);527 528 //delete the indicated subcookie529 _yuitest_coverline("build/cookie/cookie.js", 388);530if (isObject(subs) && subs.hasOwnProperty(subName)){531 _yuitest_coverline("build/cookie/cookie.js", 389);532delete subs[subName];533 534 _yuitest_coverline("build/cookie/cookie.js", 391);535if (!options.removeIfEmpty) {536 //reset the cookie537 538 _yuitest_coverline("build/cookie/cookie.js", 394);539return this.setSubs(name, subs, options);540 } else {541 //reset the cookie if there are subcookies left, else remove542 _yuitest_coverline("build/cookie/cookie.js", 397);543for (var key in subs){544 _yuitest_coverline("build/cookie/cookie.js", 398);545if (subs.hasOwnProperty(key) && !isFunction(subs[key]) && !isUndefined(subs[key])){546 _yuitest_coverline("build/cookie/cookie.js", 399);547return this.setSubs(name, subs, options);548 }549 }550 551 _yuitest_coverline("build/cookie/cookie.js", 403);552return this.remove(name, options);553 } 554 } else {555 _yuitest_coverline("build/cookie/cookie.js", 406);556return "";557 }558 559 },560 561 /**562 * Sets a cookie with a given name and value.563 * @param {String} name The name of the cookie to set.564 * @param {Variant} value The value to set for the cookie.565 * @param {Object} options (Optional) An object containing one or more566 * cookie options: path (a string), domain (a string), expires (a Date object),567 * secure (true/false), and raw (true/false). Setting raw to true indicates568 * that the cookie should not be URI encoded before being set.569 * @return {String} The created cookie string.570 * @method set571 * @static572 */573 set : function (name, value, options) {574 575 _yuitest_coverfunc("build/cookie/cookie.js", "set", 423);576_yuitest_coverline("build/cookie/cookie.js", 425);577validateCookieName(name); //throws error578 579 _yuitest_coverline("build/cookie/cookie.js", 427);580if (isUndefined(value)){581 _yuitest_coverline("build/cookie/cookie.js", 428);582error("Cookie.set(): Value cannot be undefined.");583 }584 585 _yuitest_coverline("build/cookie/cookie.js", 431);586options = options || {};587 588 _yuitest_coverline("build/cookie/cookie.js", 433);589var text = this._createCookieString(name, value, !options.raw, options);590 _yuitest_coverline("build/cookie/cookie.js", 434);591doc.cookie = text;592 _yuitest_coverline("build/cookie/cookie.js", 435);593return text;594 },595 596 /**597 * Sets a sub cookie with a given name to a particular value.598 * @param {String} name The name of the cookie to set.599 * @param {String} subName The name of the subcookie to set.600 * @param {Variant} value The value to set.601 * @param {Object} options (Optional) An object containing one or more602 * cookie options: path (a string), domain (a string), expires (a Date object),603 * and secure (true/false).604 * @return {String} The created cookie string.605 * @method setSub606 * @static607 */608 setSub : function (name, subName, value, options) {609 _yuitest_coverfunc("build/cookie/cookie.js", "setSub", 450);610_yuitest_coverline("build/cookie/cookie.js", 452);611validateCookieName(name); //throws error612 613 _yuitest_coverline("build/cookie/cookie.js", 454);614validateSubcookieName(subName); //throws error615 616 _yuitest_coverline("build/cookie/cookie.js", 456);617if (isUndefined(value)){618 _yuitest_coverline("build/cookie/cookie.js", 457);619error("Cookie.setSub(): Subcookie value cannot be undefined.");620 }621 622 _yuitest_coverline("build/cookie/cookie.js", 460);623var hash = this.getSubs(name);624 625 _yuitest_coverline("build/cookie/cookie.js", 462);626if (!isObject(hash)){627 _yuitest_coverline("build/cookie/cookie.js", 463);628hash = {};629 }630 631 _yuitest_coverline("build/cookie/cookie.js", 466);632hash[subName] = value; 633 634 _yuitest_coverline("build/cookie/cookie.js", 468);635return this.setSubs(name, hash, options);636 637 },638 639 /**640 * Sets a cookie with a given name to contain a hash of name-value pairs.641 * @param {String} name The name of the cookie to set.642 * @param {Object} value An object containing name-value pairs.643 * @param {Object} options (Optional) An object containing one or more644 * cookie options: path (a string), domain (a string), expires (a Date object),645 * and secure (true/false).646 * @return {String} The created cookie string.647 * @method setSubs648 * @static649 */650 setSubs : function (name, value, options) {651 652 _yuitest_coverfunc("build/cookie/cookie.js", "setSubs", 483);653_yuitest_coverline("build/cookie/cookie.js", 485);654validateCookieName(name); //throws error655 656 _yuitest_coverline("build/cookie/cookie.js", 487);657if (!isObject(value)){658 _yuitest_coverline("build/cookie/cookie.js", 488);659error("Cookie.setSubs(): Cookie value must be an object.");660 }661 662 _yuitest_coverline("build/cookie/cookie.js", 491);663var text /*:String*/ = this._createCookieString(name, this._createCookieHashString(value), false, options);664 _yuitest_coverline("build/cookie/cookie.js", 492);665doc.cookie = text;666 _yuitest_coverline("build/cookie/cookie.js", 493);667return text; 668 } 669 670 };...
Cookie.py
Source:Cookie.py
1#!/usr/bin/env python2#3####4# Copyright 2000 by Timothy O'Malley <timo@alum.mit.edu>5#6# All Rights Reserved7#8# Permission to use, copy, modify, and distribute this software9# and its documentation for any purpose and without fee is hereby10# granted, provided that the above copyright notice appear in all11# copies and that both that copyright notice and this permission12# notice appear in supporting documentation, and that the name of13# Timothy O'Malley not be used in advertising or publicity14# pertaining to distribution of the software without specific, written15# prior permission.16#17# Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS18# SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY19# AND FITNESS, IN NO EVENT SHALL Timothy O'Malley BE LIABLE FOR20# ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES21# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,22# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS23# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR24# PERFORMANCE OF THIS SOFTWARE.25#26####27#28# Id: Cookie.py,v 2.29 2000/08/23 05:28:49 timo Exp29# by Timothy O'Malley <timo@alum.mit.edu>30#31# Cookie.py is a Python module for the handling of HTTP32# cookies as a Python dictionary. See RFC 2109 for more33# information on cookies.34#35# The original idea to treat Cookies as a dictionary came from36# Dave Mitchell (davem@magnet.com) in 1995, when he released the37# first version of nscookie.py.38#39####40r"""41Here's a sample session to show how to use this module.42At the moment, this is the only documentation.43The Basics44----------45Importing is easy..46 >>> import Cookie47Most of the time you start by creating a cookie. Cookies come in48three flavors, each with slightly different encoding semantics, but49more on that later.50 >>> C = Cookie.SimpleCookie()51 >>> C = Cookie.SerialCookie()52 >>> C = Cookie.SmartCookie()53[Note: Long-time users of Cookie.py will remember using54Cookie.Cookie() to create an Cookie object. Although deprecated, it55is still supported by the code. See the Backward Compatibility notes56for more information.]57Once you've created your Cookie, you can add values just as if it were58a dictionary.59 >>> C = Cookie.SmartCookie()60 >>> C["fig"] = "newton"61 >>> C["sugar"] = "wafer"62 >>> C.output()63 'Set-Cookie: fig=newton\r\nSet-Cookie: sugar=wafer'64Notice that the printable representation of a Cookie is the65appropriate format for a Set-Cookie: header. This is the66default behavior. You can change the header and printed67attributes by using the .output() function68 >>> C = Cookie.SmartCookie()69 >>> C["rocky"] = "road"70 >>> C["rocky"]["path"] = "/cookie"71 >>> print C.output(header="Cookie:")72 Cookie: rocky=road; Path=/cookie73 >>> print C.output(attrs=[], header="Cookie:")74 Cookie: rocky=road75The load() method of a Cookie extracts cookies from a string. In a76CGI script, you would use this method to extract the cookies from the77HTTP_COOKIE environment variable.78 >>> C = Cookie.SmartCookie()79 >>> C.load("chips=ahoy; vienna=finger")80 >>> C.output()81 'Set-Cookie: chips=ahoy\r\nSet-Cookie: vienna=finger'82The load() method is darn-tootin smart about identifying cookies83within a string. Escaped quotation marks, nested semicolons, and other84such trickeries do not confuse it.85 >>> C = Cookie.SmartCookie()86 >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')87 >>> print C88 Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"89Each element of the Cookie also supports all of the RFC 210990Cookie attributes. Here's an example which sets the Path91attribute.92 >>> C = Cookie.SmartCookie()93 >>> C["oreo"] = "doublestuff"94 >>> C["oreo"]["path"] = "/"95 >>> print C96 Set-Cookie: oreo=doublestuff; Path=/97Each dictionary element has a 'value' attribute, which gives you98back the value associated with the key.99 >>> C = Cookie.SmartCookie()100 >>> C["twix"] = "none for you"101 >>> C["twix"].value102 'none for you'103A Bit More Advanced104-------------------105As mentioned before, there are three different flavors of Cookie106objects, each with different encoding/decoding semantics. This107section briefly discusses the differences.108SimpleCookie109The SimpleCookie expects that all values should be standard strings.110Just to be sure, SimpleCookie invokes the str() builtin to convert111the value to a string, when the values are set dictionary-style.112 >>> C = Cookie.SimpleCookie()113 >>> C["number"] = 7114 >>> C["string"] = "seven"115 >>> C["number"].value116 '7'117 >>> C["string"].value118 'seven'119 >>> C.output()120 'Set-Cookie: number=7\r\nSet-Cookie: string=seven'121SerialCookie122The SerialCookie expects that all values should be serialized using123cPickle (or pickle, if cPickle isn't available). As a result of124serializing, SerialCookie can save almost any Python object to a125value, and recover the exact same object when the cookie has been126returned. (SerialCookie can yield some strange-looking cookie127values, however.)128 >>> C = Cookie.SerialCookie()129 >>> C["number"] = 7130 >>> C["string"] = "seven"131 >>> C["number"].value132 7133 >>> C["string"].value134 'seven'135 >>> C.output()136 'Set-Cookie: number="I7\\012."\r\nSet-Cookie: string="S\'seven\'\\012p1\\012."'137Be warned, however, if SerialCookie cannot de-serialize a value (because138it isn't a valid pickle'd object), IT WILL RAISE AN EXCEPTION.139SmartCookie140The SmartCookie combines aspects of each of the other two flavors.141When setting a value in a dictionary-fashion, the SmartCookie will142serialize (ala cPickle) the value *if and only if* it isn't a143Python string. String objects are *not* serialized. Similarly,144when the load() method parses out values, it attempts to de-serialize145the value. If it fails, then it fallsback to treating the value146as a string.147 >>> C = Cookie.SmartCookie()148 >>> C["number"] = 7149 >>> C["string"] = "seven"150 >>> C["number"].value151 7152 >>> C["string"].value153 'seven'154 >>> C.output()155 'Set-Cookie: number="I7\\012."\r\nSet-Cookie: string=seven'156Backwards Compatibility157-----------------------158In order to keep compatibilty with earlier versions of Cookie.py,159it is still possible to use Cookie.Cookie() to create a Cookie. In160fact, this simply returns a SmartCookie.161 >>> C = Cookie.Cookie()162 >>> print C.__class__.__name__163 SmartCookie164Finis.165""" #"166# ^167# |----helps out font-lock168#169# Import our required modules170#171import string172try:173 from cPickle import dumps, loads174except ImportError:175 from pickle import dumps, loads176import re, warnings177__all__ = ["CookieError","BaseCookie","SimpleCookie","SerialCookie",178 "SmartCookie","Cookie"]179_nulljoin = ''.join180_semispacejoin = '; '.join181_spacejoin = ' '.join182#183# Define an exception visible to External modules184#185class CookieError(Exception):186 pass187# These quoting routines conform to the RFC2109 specification, which in188# turn references the character definitions from RFC2068. They provide189# a two-way quoting algorithm. Any non-text character is translated190# into a 4 character sequence: a forward-slash followed by the191# three-digit octal equivalent of the character. Any '\' or '"' is192# quoted with a preceeding '\' slash.193#194# These are taken from RFC2068 and RFC2109.195# _LegalChars is the list of chars which don't require "'s196# _Translator hash-table for fast quoting197#198_LegalChars = string.ascii_letters + string.digits + "!#$%&'*+-.^_`|~"199_Translator = {200 '\000' : '\\000', '\001' : '\\001', '\002' : '\\002',201 '\003' : '\\003', '\004' : '\\004', '\005' : '\\005',202 '\006' : '\\006', '\007' : '\\007', '\010' : '\\010',203 '\011' : '\\011', '\012' : '\\012', '\013' : '\\013',204 '\014' : '\\014', '\015' : '\\015', '\016' : '\\016',205 '\017' : '\\017', '\020' : '\\020', '\021' : '\\021',206 '\022' : '\\022', '\023' : '\\023', '\024' : '\\024',207 '\025' : '\\025', '\026' : '\\026', '\027' : '\\027',208 '\030' : '\\030', '\031' : '\\031', '\032' : '\\032',209 '\033' : '\\033', '\034' : '\\034', '\035' : '\\035',210 '\036' : '\\036', '\037' : '\\037',211 # Because of the way browsers really handle cookies (as opposed212 # to what the RFC says) we also encode , and ;213 ',' : '\\054', ';' : '\\073',214 '"' : '\\"', '\\' : '\\\\',215 '\177' : '\\177', '\200' : '\\200', '\201' : '\\201',216 '\202' : '\\202', '\203' : '\\203', '\204' : '\\204',217 '\205' : '\\205', '\206' : '\\206', '\207' : '\\207',218 '\210' : '\\210', '\211' : '\\211', '\212' : '\\212',219 '\213' : '\\213', '\214' : '\\214', '\215' : '\\215',220 '\216' : '\\216', '\217' : '\\217', '\220' : '\\220',221 '\221' : '\\221', '\222' : '\\222', '\223' : '\\223',222 '\224' : '\\224', '\225' : '\\225', '\226' : '\\226',223 '\227' : '\\227', '\230' : '\\230', '\231' : '\\231',224 '\232' : '\\232', '\233' : '\\233', '\234' : '\\234',225 '\235' : '\\235', '\236' : '\\236', '\237' : '\\237',226 '\240' : '\\240', '\241' : '\\241', '\242' : '\\242',227 '\243' : '\\243', '\244' : '\\244', '\245' : '\\245',228 '\246' : '\\246', '\247' : '\\247', '\250' : '\\250',229 '\251' : '\\251', '\252' : '\\252', '\253' : '\\253',230 '\254' : '\\254', '\255' : '\\255', '\256' : '\\256',231 '\257' : '\\257', '\260' : '\\260', '\261' : '\\261',232 '\262' : '\\262', '\263' : '\\263', '\264' : '\\264',233 '\265' : '\\265', '\266' : '\\266', '\267' : '\\267',234 '\270' : '\\270', '\271' : '\\271', '\272' : '\\272',235 '\273' : '\\273', '\274' : '\\274', '\275' : '\\275',236 '\276' : '\\276', '\277' : '\\277', '\300' : '\\300',237 '\301' : '\\301', '\302' : '\\302', '\303' : '\\303',238 '\304' : '\\304', '\305' : '\\305', '\306' : '\\306',239 '\307' : '\\307', '\310' : '\\310', '\311' : '\\311',240 '\312' : '\\312', '\313' : '\\313', '\314' : '\\314',241 '\315' : '\\315', '\316' : '\\316', '\317' : '\\317',242 '\320' : '\\320', '\321' : '\\321', '\322' : '\\322',243 '\323' : '\\323', '\324' : '\\324', '\325' : '\\325',244 '\326' : '\\326', '\327' : '\\327', '\330' : '\\330',245 '\331' : '\\331', '\332' : '\\332', '\333' : '\\333',246 '\334' : '\\334', '\335' : '\\335', '\336' : '\\336',247 '\337' : '\\337', '\340' : '\\340', '\341' : '\\341',248 '\342' : '\\342', '\343' : '\\343', '\344' : '\\344',249 '\345' : '\\345', '\346' : '\\346', '\347' : '\\347',250 '\350' : '\\350', '\351' : '\\351', '\352' : '\\352',251 '\353' : '\\353', '\354' : '\\354', '\355' : '\\355',252 '\356' : '\\356', '\357' : '\\357', '\360' : '\\360',253 '\361' : '\\361', '\362' : '\\362', '\363' : '\\363',254 '\364' : '\\364', '\365' : '\\365', '\366' : '\\366',255 '\367' : '\\367', '\370' : '\\370', '\371' : '\\371',256 '\372' : '\\372', '\373' : '\\373', '\374' : '\\374',257 '\375' : '\\375', '\376' : '\\376', '\377' : '\\377'258 }259_idmap = ''.join(chr(x) for x in xrange(256))260def _quote(str, LegalChars=_LegalChars,261 idmap=_idmap, translate=string.translate):262 #263 # If the string does not need to be double-quoted,264 # then just return the string. Otherwise, surround265 # the string in doublequotes and precede quote (with a \)266 # special characters.267 #268 if "" == translate(str, idmap, LegalChars):269 return str270 else:271 return '"' + _nulljoin( map(_Translator.get, str, str) ) + '"'272# end _quote273_OctalPatt = re.compile(r"\\[0-3][0-7][0-7]")274_QuotePatt = re.compile(r"[\\].")275def _unquote(str):276 # If there aren't any doublequotes,277 # then there can't be any special characters. See RFC 2109.278 if len(str) < 2:279 return str280 if str[0] != '"' or str[-1] != '"':281 return str282 # We have to assume that we must decode this string.283 # Down to work.284 # Remove the "s285 str = str[1:-1]286 # Check for special sequences. Examples:287 # \012 --> \n288 # \" --> "289 #290 i = 0291 n = len(str)292 res = []293 while 0 <= i < n:294 Omatch = _OctalPatt.search(str, i)295 Qmatch = _QuotePatt.search(str, i)296 if not Omatch and not Qmatch: # Neither matched297 res.append(str[i:])298 break299 # else:300 j = k = -1301 if Omatch: j = Omatch.start(0)302 if Qmatch: k = Qmatch.start(0)303 if Qmatch and ( not Omatch or k < j ): # QuotePatt matched304 res.append(str[i:k])305 res.append(str[k+1])306 i = k+2307 else: # OctalPatt matched308 res.append(str[i:j])309 res.append( chr( int(str[j+1:j+4], 8) ) )310 i = j+4311 return _nulljoin(res)312# end _unquote313# The _getdate() routine is used to set the expiration time in314# the cookie's HTTP header. By default, _getdate() returns the315# current time in the appropriate "expires" format for a316# Set-Cookie header. The one optional argument is an offset from317# now, in seconds. For example, an offset of -3600 means "one hour ago".318# The offset may be a floating point number.319#320_weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']321_monthname = [None,322 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',323 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']324def _getdate(future=0, weekdayname=_weekdayname, monthname=_monthname):325 from time import gmtime, time326 now = time()327 year, month, day, hh, mm, ss, wd, y, z = gmtime(now + future)328 return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % \329 (weekdayname[wd], day, monthname[month], year, hh, mm, ss)330#331# A class to hold ONE key,value pair.332# In a cookie, each such pair may have several attributes.333# so this class is used to keep the attributes associated334# with the appropriate key,value pair.335# This class also includes a coded_value attribute, which336# is used to hold the network representation of the337# value. This is most useful when Python objects are338# pickled for network transit.339#340class Morsel(dict):341 # RFC 2109 lists these attributes as reserved:342 # path comment domain343 # max-age secure version344 #345 # For historical reasons, these attributes are also reserved:346 # expires347 #348 # This is an extension from Microsoft:349 # httponly350 #351 # This dictionary provides a mapping from the lowercase352 # variant on the left to the appropriate traditional353 # formatting on the right.354 _reserved = { "expires" : "expires",355 "path" : "Path",356 "comment" : "Comment",357 "domain" : "Domain",358 "max-age" : "Max-Age",359 "secure" : "secure",360 "httponly" : "httponly",361 "version" : "Version",362 }363 def __init__(self):364 # Set defaults365 self.key = self.value = self.coded_value = None366 # Set default attributes367 for K in self._reserved:368 dict.__setitem__(self, K, "")369 # end __init__370 def __setitem__(self, K, V):371 K = K.lower()372 if not K in self._reserved:373 raise CookieError("Invalid Attribute %s" % K)374 dict.__setitem__(self, K, V)375 # end __setitem__376 def isReservedKey(self, K):377 return K.lower() in self._reserved378 # end isReservedKey379 def set(self, key, val, coded_val,380 LegalChars=_LegalChars,381 idmap=_idmap, translate=string.translate):382 # First we verify that the key isn't a reserved word383 # Second we make sure it only contains legal characters384 if key.lower() in self._reserved:385 raise CookieError("Attempt to set a reserved key: %s" % key)386 if "" != translate(key, idmap, LegalChars):387 raise CookieError("Illegal key value: %s" % key)388 # It's a good key, so save it.389 self.key = key390 self.value = val391 self.coded_value = coded_val392 # end set393 def output(self, attrs=None, header = "Set-Cookie:"):394 return "%s %s" % ( header, self.OutputString(attrs) )395 __str__ = output396 def __repr__(self):397 return '<%s: %s=%s>' % (self.__class__.__name__,398 self.key, repr(self.value) )399 def js_output(self, attrs=None):400 # Print javascript401 return """402 <script type="text/javascript">403 <!-- begin hiding404 document.cookie = \"%s\";405 // end hiding -->406 </script>407 """ % ( self.OutputString(attrs).replace('"',r'\"'), )408 # end js_output()409 def OutputString(self, attrs=None):410 # Build up our result411 #412 result = []413 RA = result.append414 # First, the key=value pair415 RA("%s=%s" % (self.key, self.coded_value))416 # Now add any defined attributes417 if attrs is None:418 attrs = self._reserved419 items = self.items()420 items.sort()421 for K,V in items:422 if V == "": continue423 if K not in attrs: continue424 if K == "expires" and type(V) == type(1):425 RA("%s=%s" % (self._reserved[K], _getdate(V)))426 elif K == "max-age" and type(V) == type(1):427 RA("%s=%d" % (self._reserved[K], V))428 elif K == "secure":429 RA(str(self._reserved[K]))430 elif K == "httponly":431 RA(str(self._reserved[K]))432 else:433 RA("%s=%s" % (self._reserved[K], V))434 # Return the result435 return _semispacejoin(result)436 # end OutputString437# end Morsel class438#439# Pattern for finding cookie440#441# This used to be strict parsing based on the RFC2109 and RFC2068442# specifications. I have since discovered that MSIE 3.0x doesn't443# follow the character rules outlined in those specs. As a444# result, the parsing rules here are less strict.445#446_LegalCharsPatt = r"[\w\d!#%&'~_`><@,:/\$\*\+\-\.\^\|\)\(\?\}\{\=]"447_CookiePattern = re.compile(448 r"(?x)" # This is a Verbose pattern449 r"(?P<key>" # Start of group 'key'450 ""+ _LegalCharsPatt +"+?" # Any word of at least one letter, nongreedy451 r")" # End of group 'key'452 r"\s*=\s*" # Equal Sign453 r"(?P<val>" # Start of group 'val'454 r'"(?:[^\\"]|\\.)*"' # Any doublequoted string455 r"|" # or456 r"\w{3},\s[\s\w\d-]{9,11}\s[\d:]{8}\sGMT" # Special case for "expires" attr457 r"|" # or458 ""+ _LegalCharsPatt +"*" # Any word or empty string459 r")" # End of group 'val'460 r"\s*;?" # Probably ending in a semi-colon461 )462# At long last, here is the cookie class.463# Using this class is almost just like using a dictionary.464# See this module's docstring for example usage.465#466class BaseCookie(dict):467 # A container class for a set of Morsels468 #469 def value_decode(self, val):470 """real_value, coded_value = value_decode(STRING)471 Called prior to setting a cookie's value from the network472 representation. The VALUE is the value read from HTTP473 header.474 Override this function to modify the behavior of cookies.475 """476 return val, val477 # end value_encode478 def value_encode(self, val):479 """real_value, coded_value = value_encode(VALUE)480 Called prior to setting a cookie's value from the dictionary481 representation. The VALUE is the value being assigned.482 Override this function to modify the behavior of cookies.483 """484 strval = str(val)485 return strval, strval486 # end value_encode487 def __init__(self, input=None):488 if input: self.load(input)489 # end __init__490 def __set(self, key, real_value, coded_value):491 """Private method for setting a cookie's value"""492 M = self.get(key, Morsel())493 M.set(key, real_value, coded_value)494 dict.__setitem__(self, key, M)495 # end __set496 def __setitem__(self, key, value):497 """Dictionary style assignment."""498 rval, cval = self.value_encode(value)499 self.__set(key, rval, cval)500 # end __setitem__501 def output(self, attrs=None, header="Set-Cookie:", sep="\015\012"):502 """Return a string suitable for HTTP."""503 result = []504 items = self.items()505 items.sort()506 for K,V in items:507 result.append( V.output(attrs, header) )508 return sep.join(result)509 # end output510 __str__ = output511 def __repr__(self):512 L = []513 items = self.items()514 items.sort()515 for K,V in items:516 L.append( '%s=%s' % (K,repr(V.value) ) )517 return '<%s: %s>' % (self.__class__.__name__, _spacejoin(L))518 def js_output(self, attrs=None):519 """Return a string suitable for JavaScript."""520 result = []521 items = self.items()522 items.sort()523 for K,V in items:524 result.append( V.js_output(attrs) )525 return _nulljoin(result)526 # end js_output527 def load(self, rawdata):528 """Load cookies from a string (presumably HTTP_COOKIE) or529 from a dictionary. Loading cookies from a dictionary 'd'530 is equivalent to calling:531 map(Cookie.__setitem__, d.keys(), d.values())532 """533 if type(rawdata) == type(""):534 self.__ParseString(rawdata)535 else:536 # self.update() wouldn't call our custom __setitem__537 for k, v in rawdata.items():538 self[k] = v539 return540 # end load()541 def __ParseString(self, str, patt=_CookiePattern):542 i = 0 # Our starting point543 n = len(str) # Length of string544 M = None # current morsel545 while 0 <= i < n:546 # Start looking for a cookie547 match = patt.search(str, i)548 if not match: break # No more cookies549 K,V = match.group("key"), match.group("val")550 i = match.end(0)551 # Parse the key, value in case it's metainfo552 if K[0] == "$":553 # We ignore attributes which pertain to the cookie554 # mechanism as a whole. See RFC 2109.555 # (Does anyone care?)556 if M:557 M[ K[1:] ] = V558 elif K.lower() in Morsel._reserved:559 if M:560 M[ K ] = _unquote(V)561 else:562 rval, cval = self.value_decode(V)563 self.__set(K, rval, cval)564 M = self[K]565 # end __ParseString566# end BaseCookie class567class SimpleCookie(BaseCookie):568 """SimpleCookie569 SimpleCookie supports strings as cookie values. When setting570 the value using the dictionary assignment notation, SimpleCookie571 calls the builtin str() to convert the value to a string. Values572 received from HTTP are kept as strings.573 """574 def value_decode(self, val):575 return _unquote( val ), val576 def value_encode(self, val):577 strval = str(val)578 return strval, _quote( strval )579# end SimpleCookie580class SerialCookie(BaseCookie):581 """SerialCookie582 SerialCookie supports arbitrary objects as cookie values. All583 values are serialized (using cPickle) before being sent to the584 client. All incoming values are assumed to be valid Pickle585 representations. IF AN INCOMING VALUE IS NOT IN A VALID PICKLE586 FORMAT, THEN AN EXCEPTION WILL BE RAISED.587 Note: Large cookie values add overhead because they must be588 retransmitted on every HTTP transaction.589 Note: HTTP has a 2k limit on the size of a cookie. This class590 does not check for this limit, so be careful!!!591 """592 def __init__(self, input=None):593 warnings.warn("SerialCookie class is insecure; do not use it",594 DeprecationWarning)595 BaseCookie.__init__(self, input)596 # end __init__597 def value_decode(self, val):598 # This could raise an exception!599 return loads( _unquote(val) ), val600 def value_encode(self, val):601 return val, _quote( dumps(val) )602# end SerialCookie603class SmartCookie(BaseCookie):604 """SmartCookie605 SmartCookie supports arbitrary objects as cookie values. If the606 object is a string, then it is quoted. If the object is not a607 string, however, then SmartCookie will use cPickle to serialize608 the object into a string representation.609 Note: Large cookie values add overhead because they must be610 retransmitted on every HTTP transaction.611 Note: HTTP has a 2k limit on the size of a cookie. This class612 does not check for this limit, so be careful!!!613 """614 def __init__(self, input=None):615 warnings.warn("Cookie/SmartCookie class is insecure; do not use it",616 DeprecationWarning)617 BaseCookie.__init__(self, input)618 # end __init__619 def value_decode(self, val):620 strval = _unquote(val)621 try:622 return loads(strval), val623 except:624 return strval, val625 def value_encode(self, val):626 if type(val) == type(""):627 return val, _quote(val)628 else:629 return val, _quote( dumps(val) )630# end SmartCookie631###########################################################632# Backwards Compatibility: Don't break any existing code!633# We provide Cookie() as an alias for SmartCookie()634Cookie = SmartCookie635#636###########################################################637def _test():638 import doctest, Cookie639 return doctest.testmod(Cookie)640if __name__ == "__main__":641 _test()642#Local Variables:643#tab-width: 4...
cookies.py
Source:cookies.py
...142 if value is None:143 remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path'))144 return145 if isinstance(value, Morsel):146 c = morsel_to_cookie(value)147 else:148 c = create_cookie(name, value, **kwargs)149 self.set_cookie(c)150 return c151 def iterkeys(self):152 """Dict-like iterkeys() that returns an iterator of names of cookies from the jar.153 See itervalues() and iteritems()."""154 for cookie in iter(self):155 yield cookie.name156 def keys(self):157 """Dict-like keys() that returns a list of names of cookies from the jar.158 See values() and items()."""159 return list(self.iterkeys())160 def itervalues(self):161 """Dict-like itervalues() that returns an iterator of values of cookies from the jar.162 See iterkeys() and iteritems()."""163 for cookie in iter(self):164 yield cookie.value165 def values(self):166 """Dict-like values() that returns a list of values of cookies from the jar.167 See keys() and items()."""168 return list(self.itervalues())169 def iteritems(self):170 """Dict-like iteritems() that returns an iterator of name-value tuples from the jar.171 See iterkeys() and itervalues()."""172 for cookie in iter(self):173 yield cookie.name, cookie.value174 def items(self):175 """Dict-like items() that returns a list of name-value tuples from the jar.176 See keys() and values(). Allows client-code to call "dict(RequestsCookieJar)177 and get a vanilla python dict of key value pairs."""178 return list(self.iteritems())179 def list_domains(self):180 """Utility method to list all the domains in the jar."""181 domains = []182 for cookie in iter(self):183 if cookie.domain not in domains:184 domains.append(cookie.domain)185 return domains186 def list_paths(self):187 """Utility method to list all the paths in the jar."""188 paths = []189 for cookie in iter(self):190 if cookie.path not in paths:191 paths.append(cookie.path)192 return paths193 def multiple_domains(self):194 """Returns True if there are multiple domains in the jar.195 Returns False otherwise."""196 domains = []197 for cookie in iter(self):198 if cookie.domain is not None and cookie.domain in domains:199 return True200 domains.append(cookie.domain)201 return False # there is only one domain in jar202 def get_dict(self, domain=None, path=None):203 """Takes as an argument an optional domain and path and returns a plain old204 Python dict of name-value pairs of cookies that meet the requirements."""205 dictionary = {}206 for cookie in iter(self):207 if (domain is None or cookie.domain == domain) and (path is None208 or cookie.path == path):209 dictionary[cookie.name] = cookie.value210 return dictionary211 def __getitem__(self, name):212 """Dict-like __getitem__() for compatibility with client code. Throws exception213 if there are more than one cookie with name. In that case, use the more214 explicit get() method instead. Caution: operation is O(n), not O(1)."""215 return self._find_no_duplicates(name)216 def __setitem__(self, name, value):217 """Dict-like __setitem__ for compatibility with client code. Throws exception218 if there is already a cookie of that name in the jar. In that case, use the more219 explicit set() method instead."""220 self.set(name, value)221 def __delitem__(self, name):222 """Deletes a cookie given a name. Wraps cookielib.CookieJar's remove_cookie_by_name()."""223 remove_cookie_by_name(self, name)224 def set_cookie(self, cookie, *args, **kwargs):225 if hasattr(cookie.value, 'startswith') and cookie.value.startswith('"') and cookie.value.endswith('"'):226 cookie.value = cookie.value.replace('\\"', '')227 return super(RequestsCookieJar, self).set_cookie(cookie, *args, **kwargs)228 def update(self, other):229 """Updates this jar with cookies from another CookieJar or dict-like"""230 if isinstance(other, cookielib.CookieJar):231 for cookie in other:232 self.set_cookie(cookie)233 else:234 super(RequestsCookieJar, self).update(other)235 def _find(self, name, domain=None, path=None):236 """Requests uses this method internally to get cookie values. Takes as args name237 and optional domain and path. Returns a cookie.value. If there are conflicting cookies,238 _find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown239 if there are conflicting cookies."""240 for cookie in iter(self):241 if cookie.name == name:242 if domain is None or cookie.domain == domain:243 if path is None or cookie.path == path:244 return cookie.value245 raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))246 def _find_no_duplicates(self, name, domain=None, path=None):247 """__get_item__ and get call _find_no_duplicates -- never used in Requests internally.248 Takes as args name and optional domain and path. Returns a cookie.value.249 Throws KeyError if cookie is not found and CookieConflictError if there are250 multiple cookies that match name and optionally domain and path."""251 toReturn = None252 for cookie in iter(self):253 if cookie.name == name:254 if domain is None or cookie.domain == domain:255 if path is None or cookie.path == path:256 if toReturn is not None: # if there are multiple cookies that meet passed in criteria257 raise CookieConflictError('There are multiple cookies with name, %r' % (name))258 toReturn = cookie.value # we will eventually return this as long as no cookie conflict259 if toReturn:260 return toReturn261 raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))262 def __getstate__(self):263 """Unlike a normal CookieJar, this class is pickleable."""264 state = self.__dict__.copy()265 # remove the unpickleable RLock object266 state.pop('_cookies_lock')267 return state268 def __setstate__(self, state):269 """Unlike a normal CookieJar, this class is pickleable."""270 self.__dict__.update(state)271 if '_cookies_lock' not in self.__dict__:272 self._cookies_lock = threading.RLock()273 def copy(self):274 """Return a copy of this RequestsCookieJar."""275 new_cj = RequestsCookieJar()276 new_cj.update(self)277 return new_cj278def create_cookie(name, value, **kwargs):279 """Make a cookie from underspecified parameters.280 By default, the pair of `name` and `value` will be set for the domain ''281 and sent on every request (this is sometimes called a "supercookie").282 """283 result = dict(284 version=0,285 name=name,286 value=value,287 port=None,288 domain='',289 path='/',290 secure=False,291 expires=None,292 discard=True,293 comment=None,294 comment_url=None,295 rest={'HttpOnly': None},296 rfc2109=False,)297 badargs = set(kwargs) - set(result)298 if badargs:299 err = 'create_cookie() got unexpected keyword arguments: %s'300 raise TypeError(err % list(badargs))301 result.update(kwargs)302 result['port_specified'] = bool(result['port'])303 result['domain_specified'] = bool(result['domain'])304 result['domain_initial_dot'] = result['domain'].startswith('.')305 result['path_specified'] = bool(result['path'])306 return cookielib.Cookie(**result)307def morsel_to_cookie(morsel):308 """Convert a Morsel object into a Cookie containing the one k/v pair."""309 expires = None310 if morsel['max-age']:311 expires = time.time() + morsel['max-age']312 elif morsel['expires']:313 time_template = '%a, %d-%b-%Y %H:%M:%S GMT'314 expires = time.mktime(315 time.strptime(morsel['expires'], time_template)) - time.timezone316 return create_cookie(317 comment=morsel['comment'],318 comment_url=bool(morsel['comment']),319 discard=False,320 domain=morsel['domain'],321 expires=expires,322 name=morsel.key,323 path=morsel['path'],324 port=None,325 rest={'HttpOnly': morsel['httponly']},326 rfc2109=False,327 secure=bool(morsel['secure']),328 value=morsel.value,329 version=morsel['version'] or 0,330 )331def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):332 """Returns a CookieJar from a key/value dictionary.333 :param cookie_dict: Dict of key/values to insert into CookieJar.334 :param cookiejar: (optional) A cookiejar to add the cookies to.335 :param overwrite: (optional) If False, will not replace cookies336 already in the jar with new ones.337 """338 if cookiejar is None:339 cookiejar = RequestsCookieJar()340 if cookie_dict is not None:341 names_from_jar = [cookie.name for cookie in cookiejar]342 for name in cookie_dict:343 if overwrite or (name not in names_from_jar):344 cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))345 return cookiejar346def merge_cookies(cookiejar, cookies):347 """Add cookies to cookiejar and returns a merged CookieJar.348 :param cookiejar: CookieJar object to add the cookies to.349 :param cookies: Dictionary or CookieJar object to be added.350 """351 if not isinstance(cookiejar, cookielib.CookieJar):352 raise ValueError('You can only merge into CookieJar')353 354 if isinstance(cookies, dict):355 cookiejar = cookiejar_from_dict(356 cookies, cookiejar=cookiejar, overwrite=False)357 elif isinstance(cookies, cookielib.CookieJar):358 try:359 cookiejar.update(cookies)360 except AttributeError:361 for cookie_in_jar in cookies:362 cookiejar.set_cookie(cookie_in_jar)...
bootstrap-table-cookie.js
Source:bootstrap-table-cookie.js
1/**2 * @author: Dennis Hernández3 * @webSite: http://djhvscf.github.io/Blog4 * @version: v1.2.25 *6 * @update zhixin wen <wenzhixin2010@gmail.com>7 */8(function ($) {9 'use strict';10 var cookieIds = {11 sortOrder: 'bs.table.sortOrder',12 sortName: 'bs.table.sortName',13 pageNumber: 'bs.table.pageNumber',14 pageList: 'bs.table.pageList',15 columns: 'bs.table.columns',16 searchText: 'bs.table.searchText',17 filterControl: 'bs.table.filterControl'18 };19 var getCurrentHeader = function (that) {20 var header = that.$header;21 if (that.options.height) {22 header = that.$tableHeader;23 }24 return header;25 };26 var getCurrentSearchControls = function (that) {27 var searchControls = 'select, input';28 if (that.options.height) {29 searchControls = 'table select, table input';30 }31 return searchControls;32 };33 var cookieEnabled = function () {34 return !!(navigator.cookieEnabled);35 };36 var inArrayCookiesEnabled = function (cookieName, cookiesEnabled) {37 var index = -1;38 for (var i = 0; i < cookiesEnabled.length; i++) {39 if (cookieName.toLowerCase() === cookiesEnabled[i].toLowerCase()) {40 index = i;41 break;42 }43 }44 return index;45 };46 var setCookie = function (that, cookieName, cookieValue) {47 if ((!that.options.cookie) || (!cookieEnabled()) || (that.options.cookieIdTable === '')) {48 return;49 }50 if (inArrayCookiesEnabled(cookieName, that.options.cookiesEnabled) === -1) {51 return;52 }53 cookieName = that.options.cookieIdTable + '.' + cookieName;54 switch(that.options.cookieStorage) {55 case 'cookieStorage':56 document.cookie = [57 cookieName, '=', cookieValue,58 '; expires=' + that.options.cookieExpire,59 that.options.cookiePath ? '; path=' + that.options.cookiePath : '',60 that.options.cookieDomain ? '; domain=' + that.options.cookieDomain : '',61 that.options.cookieSecure ? '; secure' : ''62 ].join('');63 break;64 case 'localStorage':65 localStorage.setItem(cookieName, cookieValue);66 break;67 case 'sessionStorage':68 sessionStorage.setItem(cookieName, cookieValue);69 break;70 default:71 return false;72 }73 return true;74 };75 var getCookie = function (that, tableName, cookieName) {76 if (!cookieName) {77 return null;78 }79 if (inArrayCookiesEnabled(cookieName, that.options.cookiesEnabled) === -1) {80 return null;81 }82 cookieName = tableName + '.' + cookieName;83 switch(that.options.cookieStorage) {84 case 'cookieStorage':85 return decodeURIComponent(document.cookie.replace(new RegExp('(?:(?:^|.*;)\\s*' + encodeURIComponent(cookieName).replace(/[\-\.\+\*]/g, '\\$&') + '\\s*\\=\\s*([^;]*).*$)|^.*$'), '$1')) || null;86 case 'localStorage':87 return localStorage.getItem(cookieName);88 case 'sessionStorage':89 return sessionStorage.getItem(cookieName);90 default:91 return null;92 }93 };94 var deleteCookie = function (that, tableName, cookieName) {95 cookieName = tableName + '.' + cookieName;96 97 switch(that.options.cookieStorage) {98 case 'cookieStorage':99 document.cookie = [100 encodeURIComponent(cookieName), '=',101 '; expires=Thu, 01 Jan 1970 00:00:00 GMT',102 that.options.cookiePath ? '; path=' + that.options.cookiePath : '',103 that.options.cookieDomain ? '; domain=' + that.options.cookieDomain : '',104 ].join('');105 break;106 case 'localStorage':107 localStorage.removeItem(cookieName);108 break;109 case 'sessionStorage':110 sessionStorage.removeItem(cookieName);111 break;112 }113 return true;114 };115 var calculateExpiration = function(cookieExpire) {116 var time = cookieExpire.replace(/[0-9]*/, ''); //s,mi,h,d,m,y117 cookieExpire = cookieExpire.replace(/[A-Za-z]{1,2}}/, ''); //number118 switch (time.toLowerCase()) {119 case 's':120 cookieExpire = +cookieExpire;121 break;122 case 'mi':123 cookieExpire = cookieExpire * 60;124 break;125 case 'h':126 cookieExpire = cookieExpire * 60 * 60;127 break;128 case 'd':129 cookieExpire = cookieExpire * 24 * 60 * 60;130 break;131 case 'm':132 cookieExpire = cookieExpire * 30 * 24 * 60 * 60;133 break;134 case 'y':135 cookieExpire = cookieExpire * 365 * 24 * 60 * 60;136 break;137 default:138 cookieExpire = undefined;139 break;140 }141 return cookieExpire === undefined ? '' : '; max-age=' + cookieExpire;142 };143 var initCookieFilters = function (bootstrapTable) {144 setTimeout(function () {145 var parsedCookieFilters = JSON.parse(getCookie(bootstrapTable, bootstrapTable.options.cookieIdTable, cookieIds.filterControl));146 if (!bootstrapTable.options.filterControlValuesLoaded && parsedCookieFilters) {147 bootstrapTable.options.filterControlValuesLoaded = true;148 var cachedFilters = {},149 header = getCurrentHeader(bootstrapTable),150 searchControls = getCurrentSearchControls(bootstrapTable),151 applyCookieFilters = function (element, filteredCookies) {152 $(filteredCookies).each(function (i, cookie) {153 $(element).val(cookie.text);154 cachedFilters[cookie.field] = cookie.text;155 });156 };157 header.find(searchControls).each(function () {158 var field = $(this).closest('[data-field]').data('field'),159 filteredCookies = $.grep(parsedCookieFilters, function (cookie) {160 return cookie.field === field;161 });162 applyCookieFilters(this, filteredCookies);163 });164 bootstrapTable.initColumnSearch(cachedFilters);165 }166 }, 250);167 };168 $.extend($.fn.bootstrapTable.defaults, {169 cookie: false,170 cookieExpire: '2h',171 cookiePath: null,172 cookieDomain: null,173 cookieSecure: null,174 cookieIdTable: '',175 cookiesEnabled: [176 'bs.table.sortOrder', 'bs.table.sortName',177 'bs.table.pageNumber', 'bs.table.pageList',178 'bs.table.columns', 'bs.table.searchText',179 'bs.table.filterControl'180 ],181 cookieStorage: 'cookieStorage', //localStorage, sessionStorage182 //internal variable183 filterControls: [],184 filterControlValuesLoaded: false185 });186 $.fn.bootstrapTable.methods.push('getCookies');187 $.fn.bootstrapTable.methods.push('deleteCookie');188 $.extend($.fn.bootstrapTable.utils, {189 setCookie: setCookie,190 getCookie: getCookie191 });192 var BootstrapTable = $.fn.bootstrapTable.Constructor,193 _init = BootstrapTable.prototype.init,194 _initTable = BootstrapTable.prototype.initTable,195 _initServer = BootstrapTable.prototype.initServer,196 _onSort = BootstrapTable.prototype.onSort,197 _onPageNumber = BootstrapTable.prototype.onPageNumber,198 _onPageListChange = BootstrapTable.prototype.onPageListChange,199 _onPageFirst = BootstrapTable.prototype.onPageFirst,200 _onPagePre = BootstrapTable.prototype.onPagePre,201 _onPageNext = BootstrapTable.prototype.onPageNext,202 _onPageLast = BootstrapTable.prototype.onPageLast,203 _toggleColumn = BootstrapTable.prototype.toggleColumn,204 _selectPage = BootstrapTable.prototype.selectPage,205 _onSearch = BootstrapTable.prototype.onSearch;206 BootstrapTable.prototype.init = function () {207 var timeoutId = 0;208 this.options.filterControls = [];209 this.options.filterControlValuesLoaded = false;210 this.options.cookiesEnabled = typeof this.options.cookiesEnabled === 'string' ?211 this.options.cookiesEnabled.replace('[', '').replace(']', '')212 .replace(/ /g, '').toLowerCase().split(',') :213 this.options.cookiesEnabled;214 if (this.options.filterControl) {215 var that = this;216 this.$el.on('column-search.bs.table', function (e, field, text) {217 var isNewField = true;218 for (var i = 0; i < that.options.filterControls.length; i++) {219 if (that.options.filterControls[i].field === field) {220 that.options.filterControls[i].text = text;221 isNewField = false;222 break;223 }224 }225 if (isNewField) {226 that.options.filterControls.push({227 field: field,228 text: text229 });230 }231 setCookie(that, cookieIds.filterControl, JSON.stringify(that.options.filterControls));232 }).on('post-body.bs.table', initCookieFilters(that));233 }234 _init.apply(this, Array.prototype.slice.apply(arguments));235 };236 BootstrapTable.prototype.initServer = function () {237 var bootstrapTable = this,238 selectsWithoutDefaults = [],239 columnHasSelectControl = function (column) {240 return column.filterControl && column.filterControl === 'select';241 },242 columnHasDefaultSelectValues = function (column) {243 return column.filterData && column.filterData !== 'column';244 },245 cookiesPresent = function() {246 var cookie = JSON.parse(getCookie(bootstrapTable, bootstrapTable.options.cookieIdTable, cookieIds.filterControl));247 return bootstrapTable.options.cookie && cookie;248 };249 selectsWithoutDefaults = $.grep(bootstrapTable.columns, function(column) {250 return columnHasSelectControl(column) && !columnHasDefaultSelectValues(column);251 });252 // reset variable to original initServer function, so that future calls to initServer253 // use the original function from this point on.254 BootstrapTable.prototype.initServer = _initServer;255 // early return if we don't need to populate any select values with cookie values256 if (this.options.filterControl && cookiesPresent() && selectsWithoutDefaults.length === 0) {257 return;258 }259 // call BootstrapTable.prototype.initServer260 _initServer.apply(this, Array.prototype.slice.apply(arguments));261 };262 BootstrapTable.prototype.initTable = function () {263 _initTable.apply(this, Array.prototype.slice.apply(arguments));264 this.initCookie();265 };266 BootstrapTable.prototype.initCookie = function () {267 if (!this.options.cookie) {268 return;269 }270 if ((this.options.cookieIdTable === '') || (this.options.cookieExpire === '') || (!cookieEnabled())) {271 throw new Error("Configuration error. Please review the cookieIdTable, cookieExpire properties, if those properties are ok, then this browser does not support the cookies");272 }273 var sortOrderCookie = getCookie(this, this.options.cookieIdTable, cookieIds.sortOrder),274 sortOrderNameCookie = getCookie(this, this.options.cookieIdTable, cookieIds.sortName),275 pageNumberCookie = getCookie(this, this.options.cookieIdTable, cookieIds.pageNumber),276 pageListCookie = getCookie(this, this.options.cookieIdTable, cookieIds.pageList),277 columnsCookie = JSON.parse(getCookie(this, this.options.cookieIdTable, cookieIds.columns)),278 searchTextCookie = getCookie(this, this.options.cookieIdTable, cookieIds.searchText);279 //sortOrder280 this.options.sortOrder = sortOrderCookie ? sortOrderCookie : this.options.sortOrder;281 //sortName282 this.options.sortName = sortOrderNameCookie ? sortOrderNameCookie : this.options.sortName;283 //pageNumber284 this.options.pageNumber = pageNumberCookie ? +pageNumberCookie : this.options.pageNumber;285 //pageSize286 this.options.pageSize = pageListCookie ? pageListCookie === this.options.formatAllRows() ? pageListCookie : +pageListCookie : this.options.pageSize;287 //searchText288 this.options.searchText = searchTextCookie ? searchTextCookie : '';289 if (columnsCookie) {290 $.each(this.columns, function (i, column) {291 column.visible = $.inArray(column.field, columnsCookie) !== -1;292 });293 }294 };295 BootstrapTable.prototype.onSort = function () {296 _onSort.apply(this, Array.prototype.slice.apply(arguments));297 setCookie(this, cookieIds.sortOrder, this.options.sortOrder);298 setCookie(this, cookieIds.sortName, this.options.sortName);299 };300 BootstrapTable.prototype.onPageNumber = function () {301 _onPageNumber.apply(this, Array.prototype.slice.apply(arguments));302 setCookie(this, cookieIds.pageNumber, this.options.pageNumber);303 };304 BootstrapTable.prototype.onPageListChange = function () {305 _onPageListChange.apply(this, Array.prototype.slice.apply(arguments));306 setCookie(this, cookieIds.pageList, this.options.pageSize);307 };308 BootstrapTable.prototype.onPageFirst = function () {309 _onPageFirst.apply(this, Array.prototype.slice.apply(arguments));310 setCookie(this, cookieIds.pageNumber, this.options.pageNumber);311 };312 BootstrapTable.prototype.onPagePre = function () {313 _onPagePre.apply(this, Array.prototype.slice.apply(arguments));314 setCookie(this, cookieIds.pageNumber, this.options.pageNumber);315 };316 BootstrapTable.prototype.onPageNext = function () {317 _onPageNext.apply(this, Array.prototype.slice.apply(arguments));318 setCookie(this, cookieIds.pageNumber, this.options.pageNumber);319 };320 BootstrapTable.prototype.onPageLast = function () {321 _onPageLast.apply(this, Array.prototype.slice.apply(arguments));322 setCookie(this, cookieIds.pageNumber, this.options.pageNumber);323 };324 BootstrapTable.prototype.toggleColumn = function () {325 _toggleColumn.apply(this, Array.prototype.slice.apply(arguments));326 var visibleColumns = [];327 $.each(this.columns, function (i, column) {328 if (column.visible) {329 visibleColumns.push(column.field);330 }331 });332 setCookie(this, cookieIds.columns, JSON.stringify(visibleColumns));333 };334 BootstrapTable.prototype.selectPage = function (page) {335 _selectPage.apply(this, Array.prototype.slice.apply(arguments));336 setCookie(this, cookieIds.pageNumber, page);337 };338 BootstrapTable.prototype.onSearch = function () {339 var target = Array.prototype.slice.apply(arguments);340 _onSearch.apply(this, target);341 if ($(target[0].currentTarget).parent().hasClass('search')) {342 setCookie(this, cookieIds.searchText, this.searchText);343 }344 };345 BootstrapTable.prototype.getCookies = function () {346 var bootstrapTable = this;347 var cookies = {};348 $.each(cookieIds, function(key, value) {349 cookies[key] = getCookie(bootstrapTable, bootstrapTable.options.cookieIdTable, value);350 if (key === 'columns') {351 cookies[key] = JSON.parse(cookies[key]);352 }353 });354 return cookies;355 };356 BootstrapTable.prototype.deleteCookie = function (cookieName) {357 if ((cookieName === '') || (!cookieEnabled())) {358 return;359 }360 deleteCookie(this, this.options.cookieIdTable, cookieIds[cookieName]);361 };...
test_cookies.py
Source:test_cookies.py
...17 "secure": False}18 def tearDown(self):19 self.marionette.delete_all_cookies()20 MarionetteTestCase.tearDown(self)21 def test_add_cookie(self):22 self.marionette.add_cookie(self.COOKIE_A)23 cookie_returned = str(self.marionette.execute_script("return document.cookie"))24 self.assertTrue(self.COOKIE_A["name"] in cookie_returned)25 def test_adding_a_cookie_that_expired_in_the_past(self):26 cookie = self.COOKIE_A.copy()27 cookie["expiry"] = calendar.timegm(time.gmtime()) - 128 self.marionette.add_cookie(cookie)29 cookies = self.marionette.get_cookies()30 self.assertEquals(0, len(cookies))31 def test_chrome_error(self):32 with self.marionette.using_context("chrome"):33 self.assertRaises(UnsupportedOperationException,34 self.marionette.add_cookie, self.COOKIE_A)35 self.assertRaises(UnsupportedOperationException,36 self.marionette.delete_cookie, self.COOKIE_A)37 self.assertRaises(UnsupportedOperationException,38 self.marionette.delete_all_cookies)39 self.assertRaises(UnsupportedOperationException,40 self.marionette.get_cookies)41 def test_delete_all_cookie(self):42 self.marionette.add_cookie(self.COOKIE_A)43 cookie_returned = str(self.marionette.execute_script("return document.cookie"))44 print cookie_returned45 self.assertTrue(self.COOKIE_A["name"] in cookie_returned)46 self.marionette.delete_all_cookies()47 self.assertFalse(self.marionette.get_cookies())48 def test_delete_cookie(self):49 self.marionette.add_cookie(self.COOKIE_A)50 cookie_returned = str(self.marionette.execute_script("return document.cookie"))51 self.assertTrue(self.COOKIE_A["name"] in cookie_returned)52 self.marionette.delete_cookie("foo")53 cookie_returned = str(self.marionette.execute_script("return document.cookie"))54 self.assertFalse(self.COOKIE_A["name"] in cookie_returned)55 def test_should_get_cookie_by_name(self):56 key = "key_{}".format(int(random.random()*10000000))57 self.marionette.execute_script("document.cookie = arguments[0] + '=set';", [key])58 cookie = self.marionette.get_cookie(key)59 self.assertEquals("set", cookie["value"])60 def test_get_all_cookies(self):61 key1 = "key_{}".format(int(random.random()*10000000))62 key2 = "key_{}".format(int(random.random()*10000000))63 cookies = self.marionette.get_cookies()64 count = len(cookies)65 one = {"name" :key1,66 "value": "value"}67 two = {"name":key2,68 "value": "value"}69 self.marionette.add_cookie(one)70 self.marionette.add_cookie(two)71 test_url = self.marionette.absolute_url('test.html')72 self.marionette.navigate(test_url)73 cookies = self.marionette.get_cookies()74 self.assertEquals(count + 2, len(cookies))75 def test_should_not_delete_cookies_with_a_similar_name(self):76 cookieOneName = "fish"77 cookie1 = {"name" :cookieOneName,78 "value":"cod"}79 cookie2 = {"name" :cookieOneName + "x",80 "value": "earth"}81 self.marionette.add_cookie(cookie1)82 self.marionette.add_cookie(cookie2)83 self.marionette.delete_cookie(cookieOneName)84 cookies = self.marionette.get_cookies()85 self.assertFalse(cookie1["name"] == cookies[0]["name"], msg=str(cookies))86 self.assertEquals(cookie2["name"] , cookies[0]["name"], msg=str(cookies))87 def test_we_get_required_elements_when_available(self):88 self.marionette.add_cookie(self.COOKIE_A)89 cookies = self.marionette.get_cookies()90 self.assertIn("name", cookies[0], 'name not available')91 self.assertIn("value", cookies[0], 'value not available')...
Using AI Code Generation
1var navalia = require('navalia');2var browser = new navalia();3 .type('input[name="q"]', 'navalia')4 .click('input[name="btnK"]')5 .wait('div#resultStats')6 .screenshot('google-navalia.png')7 .evaluate(function () {8 return document.title;9 })10 .then(function (title) {11 console.log('Title is: ' + title);12 })13 .catch(function (err) {14 console.log(err);15 });16var navalia = require('navalia');17var browser = new navalia();18 .type('input[name="q"]', 'navalia')19 .click('input[name="btnK"]')20 .wait('div#resultStats')21 .screenshot('google-navalia.png')22 .evaluate(function () {23 return document.title;24 })25 .then(function (title) {26 console.log('Title is: ' + title);27 })28 .catch(function (err) {29 console.log(err);30 });31var navalia = require('navalia');32var browser = new navalia();33 .type('input[name="q"]', 'navalia')34 .click('input[name="btnK"]')35 .wait('div#resultStats')36 .screenshot('google-navalia.png')37 .evaluate(function () {38 return document.title;39 })40 .then(function (title) {41 console.log('Title is: ' + title);42 })43 .catch(function (err) {44 console.log(err);45 });46var navalia = require('navalia');47var browser = new navalia();48 .type('input[name="q"]', 'navalia')49 .click('input[name="btnK"]')50 .wait('div#resultStats')51 .screenshot('google-navalia.png')52 .evaluate(function () {53 return document.title;
Using AI Code Generation
1var navalia = require('navalia');2var browser = navalia();3 .evaluate(function () {4 return document.cookie;5 })6 .then(function (cookie) {7 console.log(cookie);8 })9 .then(function () {10 return browser.close();11 });12var navalia = require('navalia');13var browser = navalia();14 .evaluate(function () {15 return localStorage.getItem('key');16 })17 .then(function (key) {18 console.log(key);19 })20 .then(function () {21 return browser.close();22 });
Using AI Code Generation
1const navalia = require('navalia');2const { Cookie } = require('navalia/cookie');3(async () => {4 const browser = await navalia();5 const page = await browser.newPage();6 await page.setCookie(new Cookie('foo', 'bar'));7 const cookie = await page.getCookie('foo');8 await page.deleteCookie('foo');9})();10const navalia = require('navalia');11const { LocalStorage } = require('navalia/local-storage');12(async () => {13 const browser = await navalia();14 const page = await browser.newPage();15 await page.setLocalStorage(new LocalStorage('foo', 'bar'));16 const localStorage = await page.getLocalStorage('foo');17 await page.deleteLocalStorage('foo');18})();19const navalia = require('navalia');20const { SessionStorage } = require('navalia/session-storage');21(async () => {22 const browser = await navalia();23 const page = await browser.newPage();24 await page.setSessionStorage(new SessionStorage('foo', 'bar'));25 const sessionStorage = await page.getSessionStorage('foo');26 await page.deleteSessionStorage('foo');27})();28const navalia = require('navalia');29const { SessionStorage } = require('navalia/session-storage');30(async () => {31 const browser = await navalia();32 const page = await browser.newPage();33 await page.setSessionStorage(new SessionStorage('foo', 'bar'));34 const sessionStorage = await page.getSessionStorage('foo');
Using AI Code Generation
1const navalia = require('navalia');2const assert = require('assert');3(async () => {4 const browser = await navalia.use(require('navalia-chrome')).launch();5 await browser.setCookie('name', 'value');6 const cookie = await browser.getCookie('name');7 assert.equal(cookie.value, 'value');8 await browser.close();9})();10const navalia = require('navalia');11const assert = require('assert');12(async () => {13 const browser = await navalia.use(require('navalia-chrome')).launch();14 await browser.setLocalStorage('name', 'value');15 const localStorage = await browser.getLocalStorage('name');16 assert.equal(localStorage, 'value');17 await browser.close();18})();19const navalia = require('navalia');20const assert = require('assert');21(async () => {22 const browser = await navalia.use(require('navalia-chrome')).launch();23 await browser.setLocalStorage('name', 'value');24 const localStorage = await browser.getLocalStorage('name');25 assert.equal(localStorage, 'value');26 await browser.close();27})();28const navalia = require('navalia');29const assert = require('assert');30(async () => {31 const browser = await navalia.use(require('navalia-chrome')).launch();32 await browser.setLocalStorage('name', 'value');33 const localStorage = await browser.getLocalStorage('name');34 assert.equal(localStorage, 'value');35 await browser.close();36})();37const navalia = require('navalia');38const assert = require('assert');39(async () => {40 const browser = await navalia.use(require('navalia-chrome')).launch();41 await browser.setLocalStorage('name', 'value');42 const localStorage = await browser.getLocalStorage('name');43 assert.equal(localStorage, 'value');44 await browser.close();45})();46const navalia = require('navalia');47const assert = require('assert');48(async () => {49 const browser = await navalia.use(require('navalia-chrome')).launch();50 await browser.navigate('
Using AI Code Generation
1var navalia = require("navalia");2var browser = navalia.firefox();3 .setCookie("foo", "bar")4 .evaluate(function() {5 return document.cookie;6 })7 .then(function(cookie) {8 console.log(cookie);9 })10 .then(function() {11 return browser.close();12 });13var navalia = require("navalia");14var browser = navalia.firefox();15 .evaluate(function() {16 localStorage.setItem("foo", "bar");17 return localStorage.getItem("foo");18 })19 .then(function(cookie) {20 console.log(cookie);21 })22 .then(function() {23 return browser.close();24 });25var navalia = require("navalia");26var browser = navalia.firefox();27 .evaluate(function() {28 localStorage.setItem("foo", "bar");29 return localStorage.getItem("foo");30 })31 .then(function(cookie) {32 console.log(cookie);33 })34 .then(function() {35 return browser.close();36 });37var navalia = require("navalia");38var browser = navalia.firefox();39 .evaluate(function() {40 localStorage.setItem("foo", "bar");41 return localStorage.getItem("foo");42 })43 .then(function(cookie) {44 console.log(cookie);45 })46 .then(function() {47 return browser.close();48 });49var navalia = require("navalia");50var browser = navalia.firefox();51 .evaluate(function() {52 localStorage.setItem("foo", "bar");53 return localStorage.getItem("foo");54 })55 .then(function(cookie) {56 console.log(cookie);57 })58 .then(function() {59 return browser.close();60 });61var navalia = require("navalia");62var browser = navalia.firefox();
Using AI Code Generation
1const navalia = require('navalia');2const browser = new navalia.Browser();3 .then(() => browser.setCookie({4 }))5 .then(() => browser.setCookie({6 }))7 .then(() => browser.getCookie())8 .then((cookies) => {9 console.log(cookies);10 })11 .then(() => browser.close());
Using AI Code Generation
1var navalia = require('navalia');2var browser = new navalia();3 .evaluate(function() {4 return document.cookie;5 })6 .then(function(cookie) {7 console.log(cookie);8 })9 .catch(function(err) {10 console.error(err);11 });12var navalia = require('navalia');13var browser = new navalia();14 .setLocalStorage('myLocalStorage', 'myValue')15 .evaluate(function() {16 return localStorage.getItem('myLocalStorage');17 })18 .then(function(localStorage) {19 console.log(localStorage);20 })21 .catch(function(err) {22 console.error(err);23 });24var navalia = require('navalia');25var browser = new navalia();26 .setSessionStorage('mySessionStorage', 'myValue')27 .evaluate(function() {28 return sessionStorage.getItem('mySessionStorage');29 })30 .then(function(sessionStorage) {31 console.log(sessionStorage);32 })33 .catch(function(err) {34 console.error(err);35 });
Using AI Code Generation
1var navalia = require('navalia');2var browser = new navalia({driver: 'phantomjs'});3 .setCookie('name', 'value')4 .getCookies()5 .then(function(cookies) {6 })7 .catch(function(error) {8 console.error(error);9 })10 .close();11var navalia = require('navalia');12var browser = new navalia({driver: 'phantomjs'});13 .setLocalStorage('name', 'value')14 .getLocalStorage()15 .then(function(cookies) {16 })17 .catch(function(error) {18 console.error(error);19 })20 .close();21var navalia = require('navalia');22var browser = new navalia({driver: 'phantomjs'});23 .setSessionStorage('name', 'value')24 .getSessionStorage()25 .then(function(cookies) {26 })27 .catch(function(error) {28 console.error(error);29 })30 .close();31var navalia = require('navalia');32var browser = new navalia({driver: 'phantomjs'});33 .setLocalStorage('name', 'value')34 .getLocalStorage()35 .then(function(cookies) {36 })37 .catch(function(error) {38 console.error(error);39 })40 .close();41var navalia = require('navalia');42var browser = new navalia({driver: 'phantomjs'});43 .setLocalStorage('name', 'value')44 .getLocalStorage()45 .then(function(cookies) {46 console.log(cookies);
Using AI Code Generation
1const navalia = require('navalia')2const { Browser } = navalia3const browser = new Browser()4 .then(() => browser.setCookie('cookieName', 'cookieValue'))5 .then(() => browser.getCookie('cookieName'))6 .then(cookie => console.log(cookie))7 .then(() => browser.close())8 .catch(console.error)9const navalia = require('navalia')10const { Browser } = navalia11const browser = new Browser()12 .then(() => browser.setLocalStorage('localStorageName', 'localStorageValue'))13 .then(() => browser.getLocalStorage('localStorageName'))14 .then(localStorage => console.log(localStorage))15 .then(() => browser.close())16 .catch(console.error)17const navalia = require('navalia')18const { Browser } = navalia19#### Browser.goto(url)20const navalia = require('navalia')21const { Browser } = navalia22const browser = new Browser()23#### Browser.setCookie(name, value)24const navalia = require('navalia')25const { Browser } = navalia26const browser = new Browser()27 .then(() => browser.setCookie('cookieName', 'cookieValue'))28 .then(() => browser.close())29#### Browser.getCookie(name)30const navalia = require('navalia')31const { Browser } = navalia32const browser = new Browser()33 .then(() => browser.setCookie('cookieName', 'cookieValue'))34 .then(() => browser.getCookie('cookieName'))35 .then(cookie => console.log(cookie))36 .then(() => browser.close())37#### Browser.setLocalStorage(name, value)38const navalia = require('navalia')39const { Browser } = navalia40const browser = new Browser()41 .then(() => browser.setLocalStorage('localStorageName', 'localStorageValue'))
Using AI Code Generation
1var navalia = require('navalia');2var chai = require('chai');3var assert = chai.assert;4var expect = chai.expect;5describe('cookie test', function() {6 this.timeout(60000);7 it('cookies', function(done) {8 .launch({ show: true })9 .then(function(browser) {10 .then(function() {11 .setCookies([12 {13 }14 .then(function() {15 .getCookies()16 .then(function(cookies) {17 console.log(cookies);18 done();19 })20 .catch(function(err) {21 console.log(err);22 done();23 });24 })25 .catch(function(err) {26 console.log(err);27 done();28 });29 })30 .catch(function(err) {31 console.log(err);32 done();33 });34 })35 .catch(function(err) {36 console.log(err);37 done();38 });39 });40});41var navalia = require('navalia');42var chai = require('chai');43var assert = chai.assert;44var expect = chai.expect;45describe('cookie test', function() {46 this.timeout(60000);47 it('cookies', function(done) {48 .launch({ show: true })49 .then(function(browser) {50 .then(function() {51 .setCookies([52 {53 }54 .then(function() {55 .getCookies()56 .then(function(cookies) {57 console.log(cookies);58 done();59 })60 .catch(function(err) {61 console.log(err);62 done();63 });64 })65 .catch(function(err) {66 console.log(err);67 done();68 });69 })
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!