Python cookielib.Cookie() Examples

The following are 30 code examples of cookielib.Cookie(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cookielib , or try the search function .
Example #1
Source File: coursera_offline.py    From coursera-offline with GNU General Public License v3.0 6 votes vote down vote up
def get_cookie(name, value):
    return cookielib.Cookie(version=0,
                name=name,
                value=value,
                domain=_204_DOMAIN,
                domain_specified=False,
                domain_initial_dot=False,
                path=_204_PATH,
                path_specified=False,
                secure=False,
                expires=None,
                comment=None,
                comment_url=None,
                rest={'HttpOnly':None},
                rfc2109=False,
                discard=False,
                port=None,
                port_specified=False
            ) 
Example #2
Source File: jsoncookie.py    From watchdog with Apache License 2.0 6 votes vote down vote up
def addcookies(self, cookies):
        if not isinstance(cookies, requests.cookies.RequestsCookieJar):
            return False
        for domain, pathdict in cookies._cookies.items():
            dotdomain = domain if domain[0] == '.' else '.' + domain
            if dotdomain not in self.cookiedict.keys():
                self.cookiedict[dotdomain] = {}
            for path, keydict in pathdict.items():
                if path not in self.cookiedict[dotdomain].keys():
                    self.cookiedict[dotdomain][path] = {}
                for key, cookieobj in keydict.items():
                    if isinstance(cookieobj, cookielib.Cookie):
                        print cookieobj
                        cookie_attrs = {}
                        cookie_attrs["value"] = cookieobj.value
                        cookie_attrs["expires"] = cookieobj.expires
                        cookie_attrs["secure"] = cookieobj.secure
                        cookie_attrs["port"] = cookieobj.port
                        cookie_attrs["version"] = cookieobj.version
                        self.cookiedict[dotdomain][path][key] = cookie_attrs 
Example #3
Source File: httptools.py    From addon with GNU General Public License v3.0 6 votes vote down vote up
def get_url_headers(url, forced=False):
    from . import scrapertools
    
    domain = urlparse.urlparse(url)[1]
    sub_dom = scrapertools.find_single_match(domain, '\.(.*?\.\w+)')
    if sub_dom and not 'google' in url:
        domain = sub_dom
    domain_cookies = cj._cookies.get("." + domain, {}).get("/", {})

    if "|" in url or not "cf_clearance" in domain_cookies:
        if not forced:
            return url

    headers = dict()
    headers["User-Agent"] = default_headers["User-Agent"]
    headers["Cookie"] = "; ".join(["%s=%s" % (c.name, c.value) for c in list(domain_cookies.values())])

    return url + "|" + "&".join(["%s=%s" % (h, urllib.quote(headers[h])) for h in headers]) 
Example #4
Source File: comcast.py    From plugin.video.nbcsnliveextra-legacy with GNU General Public License v2.0 6 votes vote down vote up
def GET_S_VI_COOKIE(self, referer):
        cj = cookielib.LWPCookieJar(os.path.join(ADDON_PATH_PROFILE, 'cookies.lwp'))
        cj.load(os.path.join(ADDON_PATH_PROFILE, 'cookies.lwp'),ignore_discard=True)

        ck = cookielib.Cookie(version=0, name='s_cc', value='true', port=None, port_specified=False, domain='.comcast.net', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False)
        cj.set_cookie(ck)
        ck = cookielib.Cookie(version=0, name='s_sq', value='%5B%5BB%5D%5D', port=None, port_specified=False, domain='.comcast.net', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False)
        cj.set_cookie(ck)
        
        url = "https://serviceos.comcast.net/b/ss/comcastnet/1/H.27.5/s41303345554477?AQB=1&pccr=true&vidn=2C0299A205011584-60000137E007532F&&ndh=1&t=17%2F9%2F2016%2016%3A23%3A32%201%20240&fid=1F8FC523BD7D4396-2E7FF98D1A765CCC&ce=UTF-8&ns=comcast&pageName=mobile%20app%20sign%20in&g=https%3A%2F%2Flogin.comcast.net%2Flogin%3Fr%3Dcomcast.net%26s%3Doauth%26continue%3Dhttps%253A%252F%252Flogin.comcast.net%252Foauth%252Fauthorize%253Fresponse_type%253Dcode%2526redirect_uri%253Dhttps%253A%252F%252Fsp.auth.adobe.com%252Fadobe-services%252Foauth2%2526state%253DQyqYoV%2526scope%253Dopenid%252520prof&cc=USD&ch=sign%20in&events=event11&c1=%2Flogin%2F%3Amobile%20app%20sign%20in&v1=%2Flogin%2F%3Amobile%20app%20sign%20in&c4=sign%20in&c7=adobepass-nbcsports&v7=adobepass-nbcsports&c23=small&c31=comcast&v31=mobile%20app%20sign%20in&c32=cim&v32=cim&c33=comcast%20net&v33=comcast%20net&c34=comcast%20net%3Asign%20in&c35=authentication&v35=authentication&c36=site%3Ahome&v36=site%3Ahome&v41=small&c44=anonymous%3Amobile%20app%20sign%20in&v47=anonymous&h1=comcast%3Acim%3Acomcast%20net%3Asign%20in%3Amobile%20app%20sign%20in&h2=%2Flogin&s=375x667&c=32&j=1.6&v=N&k=Y&bw=375&bh=667&-g=ile%252520https%253A%252F%252Flogin.comcast.net%252Fpdp%252Ftve%2526client_id%253Dadobepass-nbcsports%2526acr_values%253Durn%253Aoasis%253Anames%253Atc%253ASAML%253A2.0%253Aac%253Aclasses%253AInternetProtocol%2526response%253D1%26reqId%3D51e0dfcb-71e4-4a3f-96ad-8b8366155e6b%26ipAddrAuthn%3D1%26client_id%3Dadobepass-nbcsports&AQE=1"
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))    
        opener.addheaders = [ ("Accept", "*/*"),
                            ("Accept-Encoding", "gzip, deflate"),
                            ("Accept-Language", "en-us"),                                                        
                            ("Connection", "keep-alive"),
                            ("Referer", referer),
                            ("User-Agent", UA_IPHONE)]
        resp = opener.open(url)        
        resp.close()
        SAVE_COOKIE(cj) 
Example #5
Source File: jsoncookie.py    From watchdog with Apache License 2.0 6 votes vote down vote up
def addcookies(self, cookies):
        if not isinstance(cookies, requests.cookies.RequestsCookieJar):
            return False
        for domain, pathdict in cookies._cookies.items():
            dotdomain = domain if domain[0] == '.' else '.' + domain
            if dotdomain not in self.cookiedict.keys():
                self.cookiedict[dotdomain] = {}
            for path, keydict in pathdict.items():
                if path not in self.cookiedict[dotdomain].keys():
                    self.cookiedict[dotdomain][path] = {}
                for key, cookieobj in keydict.items():
                    if isinstance(cookieobj, cookielib.Cookie):
                        print cookieobj
                        cookie_attrs = {}
                        cookie_attrs["value"] = cookieobj.value
                        cookie_attrs["expires"] = cookieobj.expires
                        cookie_attrs["secure"] = cookieobj.secure
                        cookie_attrs["port"] = cookieobj.port
                        cookie_attrs["version"] = cookieobj.version
                        self.cookiedict[dotdomain][path][key] = cookie_attrs 
Example #6
Source File: v2ex_daily.py    From v2ex with MIT License 6 votes vote down vote up
def make_cookie(name, value):
    return cookielib.Cookie(
        version=0,
        name=name,
        value=value,
        port=None,
        port_specified=False,
        domain=V2EX_DOMAIN,
        domain_specified=True,
        domain_initial_dot=False,
        path='/',
        path_specified=True,
        secure=False,
        expires=None,
        discard=False,
        comment=None,
        comment_url=None,
        rest=None
    ) 
Example #7
Source File: HttpClient.py    From QQRobot with GNU General Public License v3.0 5 votes vote down vote up
def setCookie(self, key, val, domain):
        ck = cookielib.Cookie(version=0, name=key, value=val, port=None, port_specified=False, domain=domain, domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False)
        self.__cookie.set_cookie(ck)
#self.__cookie.clear() clean cookie
# vim : tabstop=2 shiftwidth=2 softtabstop=2 expandtab 
Example #8
Source File: test_cookielib.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_Cookie_iterator(self):
        from cookielib import CookieJar, Cookie, DefaultCookiePolicy

        cs = CookieJar(DefaultCookiePolicy(rfc2965=True))
        # add some random cookies
        interact_2965(cs, "http://blah.spam.org/", 'foo=eggs; Version=1; '
                      'Comment="does anybody read these?"; '
                      'CommentURL="http://foo.bar.net/comment.html"')
        interact_netscape(cs, "http://www.acme.com/blah/", "spam=bar; secure")
        interact_2965(cs, "http://www.acme.com/blah/",
                      "foo=bar; secure; Version=1")
        interact_2965(cs, "http://www.acme.com/blah/",
                      "foo=bar; path=/; Version=1")
        interact_2965(cs, "http://www.sol.no",
                      r'bang=wallop; version=1; domain=".sol.no"; '
                      r'port="90,100, 80,8080"; '
                      r'max-age=100; Comment = "Just kidding! (\"|\\\\) "')

        versions = [1, 1, 1, 0, 1]
        names = ["bang", "foo", "foo", "spam", "foo"]
        domains = [".sol.no", "blah.spam.org", "www.acme.com",
                   "www.acme.com", "www.acme.com"]
        paths = ["/", "/", "/", "/blah", "/blah/"]

        for i in range(4):
            i = 0
            for c in cs:
                self.assertIsInstance(c, Cookie)
                self.assertEqual(c.version, versions[i])
                self.assertEqual(c.name, names[i])
                self.assertEqual(c.domain, domains[i])
                self.assertEqual(c.path, paths[i])
                i = i + 1 
Example #9
Source File: test_cookielib.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def test_missing_value(self):
        from cookielib import MozillaCookieJar, lwp_cookie_str

        # missing = sign in Cookie: header is regarded by Mozilla as a missing
        # name, and by cookielib as a missing value
        filename = test_support.TESTFN
        c = MozillaCookieJar(filename)
        interact_netscape(c, "http://www.acme.com/", 'eggs')
        interact_netscape(c, "http://www.acme.com/", '"spam"; path=/foo/')
        cookie = c._cookies["www.acme.com"]["/"]["eggs"]
        self.assert_(cookie.value is None)
        self.assertEquals(cookie.name, "eggs")
        cookie = c._cookies["www.acme.com"]['/foo/']['"spam"']
        self.assert_(cookie.value is None)
        self.assertEquals(cookie.name, '"spam"')
        self.assertEquals(lwp_cookie_str(cookie), (
            r'"spam"; path="/foo/"; domain="www.acme.com"; '
            'path_spec; discard; version=0'))
        old_str = repr(c)
        c.save(ignore_expires=True, ignore_discard=True)
        try:
            c = MozillaCookieJar(filename)
            c.revert(ignore_expires=True, ignore_discard=True)
        finally:
            os.unlink(c.filename)
        # cookies unchanged apart from lost info re. whether path was specified
        self.assertEquals(
            repr(c),
            re.sub("path_specified=%s" % True, "path_specified=%s" % False,
                   old_str)
            )
        self.assertEquals(interact_netscape(c, "http://www.acme.com/foo/"),
                          '"spam"; eggs') 
Example #10
Source File: test_cookielib.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def _interact(cookiejar, url, set_cookie_hdrs, hdr_name):
    """Perform a single request / response cycle, returning Cookie: header."""
    from urllib2 import Request
    req = Request(url)
    cookiejar.add_cookie_header(req)
    cookie_hdr = req.get_header("Cookie", "")
    headers = []
    for hdr in set_cookie_hdrs:
        headers.append("%s: %s" % (hdr_name, hdr))
    res = FakeResponse(headers, url)
    cookiejar.extract_cookies(res, req)
    return cookie_hdr 
Example #11
Source File: test_cookielib.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def interact_netscape(cookiejar, url, *set_cookie_hdrs):
    return _interact(cookiejar, url, set_cookie_hdrs, "Set-Cookie") 
Example #12
Source File: test_cookielib.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def test_parse_ns_headers_special_names(self):
        # names such as 'expires' are not special in first name=value pair
        # of Set-Cookie: header
        from cookielib import parse_ns_headers

        # Cookie with name 'expires'
        hdr = 'expires=01 Jan 2040 22:23:32 GMT'
        expected = [[("expires", "01 Jan 2040 22:23:32 GMT"), ("version", "0")]]
        self.assertEquals(parse_ns_headers([hdr]), expected) 
Example #13
Source File: test_cookielib.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def interact_netscape(cookiejar, url, *set_cookie_hdrs):
    return _interact(cookiejar, url, set_cookie_hdrs, "Set-Cookie") 
Example #14
Source File: test_cookielib.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_empty_path(self):
        from cookielib import CookieJar, DefaultCookiePolicy
        from urllib2 import Request

        # Test for empty path
        # Broken web-server ORION/1.3.38 returns to the client response like
        #
        #       Set-Cookie: JSESSIONID=ABCDERANDOM123; Path=
        #
        # ie. with Path set to nothing.
        # In this case, extract_cookies() must set cookie to / (root)
        c = CookieJar(DefaultCookiePolicy(rfc2965 = True))
        headers = []

        req = Request("http://www.ants.com/")
        headers.append("Set-Cookie: JSESSIONID=ABCDERANDOM123; Path=")
        res = FakeResponse(headers, "http://www.ants.com/")
        c.extract_cookies(res, req)

        req = Request("http://www.ants.com/")
        c.add_cookie_header(req)

        self.assertEqual(req.get_header("Cookie"),
                         "JSESSIONID=ABCDERANDOM123")
        self.assertEqual(req.get_header("Cookie2"), '$Version="1"')

        # missing path in the request URI
        req = Request("http://www.ants.com:8080")
        c.add_cookie_header(req)

        self.assertEqual(req.get_header("Cookie"),
                         "JSESSIONID=ABCDERANDOM123")
        self.assertEqual(req.get_header("Cookie2"), '$Version="1"') 
Example #15
Source File: test_cookielib.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_netscape_misc(self):
        # Some additional Netscape cookies tests.
        from cookielib import CookieJar
        from urllib2 import Request

        c = CookieJar()
        headers = []
        req = Request("http://foo.bar.acme.com/foo")

        # Netscape allows a host part that contains dots
        headers.append("Set-Cookie: Customer=WILE_E_COYOTE; domain=.acme.com")
        res = FakeResponse(headers, "http://www.acme.com/foo")
        c.extract_cookies(res, req)

        # and that the domain is the same as the host without adding a leading
        # dot to the domain.  Should not quote even if strange chars are used
        # in the cookie value.
        headers.append("Set-Cookie: PART_NUMBER=3,4; domain=foo.bar.acme.com")
        res = FakeResponse(headers, "http://www.acme.com/foo")
        c.extract_cookies(res, req)

        req = Request("http://foo.bar.acme.com/foo")
        c.add_cookie_header(req)
        self.assertTrue(
            "PART_NUMBER=3,4" in req.get_header("Cookie") and
            "Customer=WILE_E_COYOTE" in req.get_header("Cookie")) 
Example #16
Source File: test_cookielib.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_bad_cookie_header(self):

        def cookiejar_from_cookie_headers(headers):
            from cookielib import CookieJar
            from urllib2 import Request
            c = CookieJar()
            req = Request("http://www.example.com/")
            r = FakeResponse(headers, "http://www.example.com/")
            c.extract_cookies(r, req)
            return c

        # none of these bad headers should cause an exception to be raised
        for headers in [
            ["Set-Cookie: "],  # actually, nothing wrong with this
            ["Set-Cookie2: "],  # ditto
            # missing domain value
            ["Set-Cookie2: a=foo; path=/; Version=1; domain"],
            # bad max-age
            ["Set-Cookie: b=foo; max-age=oops"],
            # bad version
            ["Set-Cookie: b=foo; version=spam"],
            ]:
            c = cookiejar_from_cookie_headers(headers)
            # these bad cookies shouldn't be set
            self.assertEqual(len(c), 0)

        # cookie with invalid expires is treated as session cookie
        headers = ["Set-Cookie: c=foo; expires=Foo Bar 12 33:22:11 2000"]
        c = cookiejar_from_cookie_headers(headers)
        cookie = c._cookies["www.example.com"]["/"]["c"]
        self.assertIsNone(cookie.expires) 
Example #17
Source File: test_cookielib.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_parse_ns_headers_special_names(self):
        # names such as 'expires' are not special in first name=value pair
        # of Set-Cookie: header
        from cookielib import parse_ns_headers

        # Cookie with name 'expires'
        hdr = 'expires=01 Jan 2040 22:23:32 GMT'
        expected = [[("expires", "01 Jan 2040 22:23:32 GMT"), ("version", "0")]]
        self.assertEqual(parse_ns_headers([hdr]), expected) 
Example #18
Source File: HttpClient.py    From QzoneLiker with GNU General Public License v3.0 5 votes vote down vote up
def setCookie(self, key, val, domain):
        ck = cookielib.Cookie(version=0, name=key, value=val, port=None, port_specified=False, domain=domain, domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False)
        self.__cookie.set_cookie(ck)
#self.__cookie.clear() clean cookie
# vim : tabstop=2 shiftwidth=2 softtabstop=2 expandtab 
Example #19
Source File: coursera_offline.py    From coursera-offline with GNU General Public License v3.0 5 votes vote down vote up
def login(email, password):
    # Logs into coursera and sets the cookie
    # Spoofs the requests to Coursera servers to login
    # Returns the cookie jar
    cookie_jar = cookielib.LWPCookieJar(absolute_path(COOKIE_FILE))
    if has_cookiefile():
        cookie_jar.load(ignore_discard=True)
        if isLoggedIn(cookie_jar):
            return cookie_jar
        elif not email or not password:
            exit_with_message('Provide email and password')
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_jar))

    csrf2_token = 'csrf2_token_' + csrfMake(8)
    csrf2_token_value = csrfMake()
    csrf_token = csrfMake()

    csrf2 = get_cookie(csrf2_token, csrf2_token_value)
    csrf = get_cookie('csrftoken', csrf_token)
    cookie_jar.set_cookie(csrf)
    cookie_jar.set_cookie(csrf2)

    DEFAULT_HEADERS['X-CSRFToken'] = csrf_token
    DEFAULT_HEADERS['X-CSRF2-Token'] = csrf2_token_value
    DEFAULT_HEADERS['X-CSRF2-Cookie'] = csrf2_token
    data = {
        'email' : email,
        'password' : password,
        'webrequest' : 'true'
    }

    try:
        login_res = opener.open(urllib2.Request(AUTH_URL, urllib.urlencode(data), DEFAULT_HEADERS))
    except Exception, e:
        exit_with_message(e) 
Example #20
Source File: addon.py    From plugin.video.xunleicloud with GNU General Public License v2.0 5 votes vote down vote up
def setcookie(self, domain, k, v):
        c = cookielib.Cookie(
            version=0, name=k, value=v, comment_url=None, port_specified=False,
            domain=domain, domain_specified=True, path='/', secure=False,
            domain_initial_dot=True, path_specified=True, expires=None,
            discard=True, comment=None, port=None, rest={}, rfc2109=False)
        self.cookiejar.set_cookie(c)
        self.cookiejar.save(cookiefile, ignore_discard=True) 
Example #21
Source File: HttpClient.py    From QQParking with GNU General Public License v3.0 5 votes vote down vote up
def setCookie(self, key, val, domain):
        ck = cookielib.Cookie(version=0, name=key, value=val, port=None, port_specified=False, domain=domain, domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False)
        self.__cookie.set_cookie(ck)
#self.__cookie.clear() clean cookie
# vim : tabstop=2 shiftwidth=2 softtabstop=2 expandtab 
Example #22
Source File: test_cookielib.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_empty_path(self):
        from cookielib import CookieJar, DefaultCookiePolicy
        from urllib2 import Request

        # Test for empty path
        # Broken web-server ORION/1.3.38 returns to the client response like
        #
        #       Set-Cookie: JSESSIONID=ABCDERANDOM123; Path=
        #
        # ie. with Path set to nothing.
        # In this case, extract_cookies() must set cookie to / (root)
        c = CookieJar(DefaultCookiePolicy(rfc2965 = True))
        headers = []

        req = Request("http://www.ants.com/")
        headers.append("Set-Cookie: JSESSIONID=ABCDERANDOM123; Path=")
        res = FakeResponse(headers, "http://www.ants.com/")
        c.extract_cookies(res, req)

        req = Request("http://www.ants.com/")
        c.add_cookie_header(req)

        self.assertEqual(req.get_header("Cookie"),
                         "JSESSIONID=ABCDERANDOM123")
        self.assertEqual(req.get_header("Cookie2"), '$Version="1"')

        # missing path in the request URI
        req = Request("http://www.ants.com:8080")
        c.add_cookie_header(req)

        self.assertEqual(req.get_header("Cookie"),
                         "JSESSIONID=ABCDERANDOM123")
        self.assertEqual(req.get_header("Cookie2"), '$Version="1"') 
Example #23
Source File: test_cookielib.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_netscape_misc(self):
        # Some additional Netscape cookies tests.
        from cookielib import CookieJar
        from urllib2 import Request

        c = CookieJar()
        headers = []
        req = Request("http://foo.bar.acme.com/foo")

        # Netscape allows a host part that contains dots
        headers.append("Set-Cookie: Customer=WILE_E_COYOTE; domain=.acme.com")
        res = FakeResponse(headers, "http://www.acme.com/foo")
        c.extract_cookies(res, req)

        # and that the domain is the same as the host without adding a leading
        # dot to the domain.  Should not quote even if strange chars are used
        # in the cookie value.
        headers.append("Set-Cookie: PART_NUMBER=3,4; domain=foo.bar.acme.com")
        res = FakeResponse(headers, "http://www.acme.com/foo")
        c.extract_cookies(res, req)

        req = Request("http://foo.bar.acme.com/foo")
        c.add_cookie_header(req)
        self.assertTrue(
            "PART_NUMBER=3,4" in req.get_header("Cookie") and
            "Customer=WILE_E_COYOTE" in req.get_header("Cookie")) 
Example #24
Source File: test_cookielib.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_bad_cookie_header(self):

        def cookiejar_from_cookie_headers(headers):
            from cookielib import CookieJar
            from urllib2 import Request
            c = CookieJar()
            req = Request("http://www.example.com/")
            r = FakeResponse(headers, "http://www.example.com/")
            c.extract_cookies(r, req)
            return c

        # none of these bad headers should cause an exception to be raised
        for headers in [
            ["Set-Cookie: "],  # actually, nothing wrong with this
            ["Set-Cookie2: "],  # ditto
            # missing domain value
            ["Set-Cookie2: a=foo; path=/; Version=1; domain"],
            # bad max-age
            ["Set-Cookie: b=foo; max-age=oops"],
            # bad version
            ["Set-Cookie: b=foo; version=spam"],
            ]:
            c = cookiejar_from_cookie_headers(headers)
            # these bad cookies shouldn't be set
            self.assertEqual(len(c), 0)

        # cookie with invalid expires is treated as session cookie
        headers = ["Set-Cookie: c=foo; expires=Foo Bar 12 33:22:11 2000"]
        c = cookiejar_from_cookie_headers(headers)
        cookie = c._cookies["www.example.com"]["/"]["c"]
        self.assertIsNone(cookie.expires) 
Example #25
Source File: test_cookielib.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_Cookie_iterator(self):
        from cookielib import CookieJar, Cookie, DefaultCookiePolicy

        cs = CookieJar(DefaultCookiePolicy(rfc2965=True))
        # add some random cookies
        interact_2965(cs, "http://blah.spam.org/", 'foo=eggs; Version=1; '
                      'Comment="does anybody read these?"; '
                      'CommentURL="http://foo.bar.net/comment.html"')
        interact_netscape(cs, "http://www.acme.com/blah/", "spam=bar; secure")
        interact_2965(cs, "http://www.acme.com/blah/",
                      "foo=bar; secure; Version=1")
        interact_2965(cs, "http://www.acme.com/blah/",
                      "foo=bar; path=/; Version=1")
        interact_2965(cs, "http://www.sol.no",
                      r'bang=wallop; version=1; domain=".sol.no"; '
                      r'port="90,100, 80,8080"; '
                      r'max-age=100; Comment = "Just kidding! (\"|\\\\) "')

        versions = [1, 1, 1, 0, 1]
        names = ["bang", "foo", "foo", "spam", "foo"]
        domains = [".sol.no", "blah.spam.org", "www.acme.com",
                   "www.acme.com", "www.acme.com"]
        paths = ["/", "/", "/", "/blah", "/blah/"]

        for i in range(4):
            i = 0
            for c in cs:
                self.assertIsInstance(c, Cookie)
                self.assertEqual(c.version, versions[i])
                self.assertEqual(c.name, names[i])
                self.assertEqual(c.domain, domains[i])
                self.assertEqual(c.path, paths[i])
                i = i + 1 
Example #26
Source File: test_cookielib.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_missing_final_slash(self):
        # Missing slash from request URL's abs_path should be assumed present.
        from cookielib import CookieJar, DefaultCookiePolicy
        from urllib2 import Request
        url = "http://www.acme.com"
        c = CookieJar(DefaultCookiePolicy(rfc2965=True))
        interact_2965(c, url, "foo=bar; Version=1")
        req = Request(url)
        self.assertEqual(len(c), 1)
        c.add_cookie_header(req)
        self.assertTrue(req.has_header("Cookie")) 
Example #27
Source File: test_cookielib.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_ns_parser_special_names(self):
        # names such as 'expires' are not special in first name=value pair
        # of Set-Cookie: header
        from cookielib import CookieJar

        c = CookieJar()
        interact_netscape(c, "http://www.acme.com/", 'expires=eggs')
        interact_netscape(c, "http://www.acme.com/", 'version=eggs; spam=eggs')

        cookies = c._cookies["www.acme.com"]["/"]
        self.assertTrue('expires' in cookies)
        self.assertTrue('version' in cookies) 
Example #28
Source File: test_cookielib.py    From oss-ftp with MIT License 5 votes vote down vote up
def _interact(cookiejar, url, set_cookie_hdrs, hdr_name):
    """Perform a single request / response cycle, returning Cookie: header."""
    from urllib2 import Request
    req = Request(url)
    cookiejar.add_cookie_header(req)
    cookie_hdr = req.get_header("Cookie", "")
    headers = []
    for hdr in set_cookie_hdrs:
        headers.append("%s: %s" % (hdr_name, hdr))
    res = FakeResponse(headers, url)
    cookiejar.extract_cookies(res, req)
    return cookie_hdr 
Example #29
Source File: test_cookielib.py    From oss-ftp with MIT License 5 votes vote down vote up
def interact_netscape(cookiejar, url, *set_cookie_hdrs):
    return _interact(cookiejar, url, set_cookie_hdrs, "Set-Cookie") 
Example #30
Source File: test_cookielib.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_parse_ns_headers_special_names(self):
        # names such as 'expires' are not special in first name=value pair
        # of Set-Cookie: header
        from cookielib import parse_ns_headers

        # Cookie with name 'expires'
        hdr = 'expires=01 Jan 2040 22:23:32 GMT'
        expected = [[("expires", "01 Jan 2040 22:23:32 GMT"), ("version", "0")]]
        self.assertEqual(parse_ns_headers([hdr]), expected)