[Python-checkins] python/dist/src/Lib/test test_cookielib.py, NONE, 1.1 test_urllib2.py, 1.12, 1.13

loewis at users.sourceforge.net loewis at users.sourceforge.net
Mon May 31 14:22:42 EDT 2004


Update of /cvsroot/python/python/dist/src/Lib/test
In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv27715/Lib/test

Modified Files:
	test_urllib2.py 
Added Files:
	test_cookielib.py 
Log Message:
Patch #963318: Add support for client-side cookie management.


--- NEW FILE: test_cookielib.py ---
# -*- coding: utf-8 -*-
"""Tests for cookielib.py."""

import re, os, time
from unittest import TestCase

from test import test_support

class DateTimeTests(TestCase):

    def test_time2isoz(self):
        from cookielib import time2isoz

        base = 1019227000
        day = 24*3600
        self.assertEquals(time2isoz(base), "2002-04-19 14:36:40Z")
        self.assertEquals(time2isoz(base+day), "2002-04-20 14:36:40Z")
        self.assertEquals(time2isoz(base+2*day), "2002-04-21 14:36:40Z")
        self.assertEquals(time2isoz(base+3*day), "2002-04-22 14:36:40Z")
[...1581 lines suppressed...]
        self.assert_(not (
            # a permanent cookie got lost accidently
            counter["perm_after"] != counter["perm_before"] or
            # a session cookie hasn't been cleared
            counter["session_after"] != 0 or
            # we didn't have session cookies in the first place
            counter["session_before"] == 0))


def test_main(verbose=None):
    from test import test_sets
    test_support.run_unittest(
        DateTimeTests,
        HeaderTests,
        CookieTests,
        LWPCookieTests,
        )

if __name__ == "__main__":
    test_main(verbose=True)

Index: test_urllib2.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_urllib2.py,v
retrieving revision 1.12
retrieving revision 1.13
diff -C2 -d -r1.12 -r1.13
*** test_urllib2.py	24 Feb 2004 19:40:35 -0000	1.12
--- test_urllib2.py	31 May 2004 18:22:40 -0000	1.13
***************
*** 55,58 ****
--- 55,62 ----
      def close(self): pass
  
+ class MockHeaders(dict):
+     def getheaders(self, name):
+         return self.values()
+ 
  class MockResponse(StringIO.StringIO):
      def __init__(self, code, msg, headers, data, url=None):
***************
*** 64,67 ****
--- 68,77 ----
          return self.url
  
+ class MockCookieJar:
+     def add_cookie_header(self, request):
+         self.ach_req = request
+     def extract_cookies(self, response, request):
+         self.ec_req, self.ec_r = request, response
+ 
  class FakeMethod:
      def __init__(self, meth_name, action, handle):
***************
*** 475,479 ****
              req = Request("http://example.com/", data)
              r = MockResponse(200, "OK", {}, "")
!             newreq = h.do_request(req)
              if data is None:  # GET
                  self.assert_("Content-length" not in req.unredirected_hdrs)
--- 485,489 ----
              req = Request("http://example.com/", data)
              r = MockResponse(200, "OK", {}, "")
!             newreq = h.do_request_(req)
              if data is None:  # GET
                  self.assert_("Content-length" not in req.unredirected_hdrs)
***************
*** 492,496 ****
              req.add_unredirected_header("Host", "baz")
              req.add_unredirected_header("Spam", "foo")
!             newreq = h.do_request(req)
              self.assertEqual(req.unredirected_hdrs["Content-length"], "foo")
              self.assertEqual(req.unredirected_hdrs["Content-type"], "bar")
--- 502,506 ----
              req.add_unredirected_header("Host", "baz")
              req.add_unredirected_header("Spam", "foo")
!             newreq = h.do_request_(req)
              self.assertEqual(req.unredirected_hdrs["Content-length"], "foo")
              self.assertEqual(req.unredirected_hdrs["Content-type"], "bar")
***************
*** 515,518 ****
--- 525,543 ----
          self.assertEqual(o.args, (req, r, 201, "Created", {}))
  
+     def test_cookies(self):
+         cj = MockCookieJar()
+         h = urllib2.HTTPCookieProcessor(cj)
+         o = h.parent = MockOpener()
+ 
+         req = Request("http://example.com/")
+         r = MockResponse(200, "OK", {}, "")
+         newreq = h.http_request(req)
+         self.assert_(cj.ach_req is req is newreq)
+         self.assertEquals(req.get_origin_req_host(), "example.com")
+         self.assert_(not req.is_unverifiable())
+         newr = h.http_response(req, r)
+         self.assert_(cj.ec_req is req)
+         self.assert_(cj.ec_r is r is newr)
+ 
      def test_redirect(self):
          from_url = "http://example.com/a.html"
***************
*** 529,533 ****
                  req.add_unredirected_header("Spam", "spam")
                  try:
!                     method(req, MockFile(), code, "Blah", {"location": to_url})
                  except urllib2.HTTPError:
                      # 307 in response to POST requires user OK
--- 554,559 ----
                  req.add_unredirected_header("Spam", "spam")
                  try:
!                     method(req, MockFile(), code, "Blah",
!                            MockHeaders({"location": to_url}))
                  except urllib2.HTTPError:
                      # 307 in response to POST requires user OK
***************
*** 545,575 ****
          # loop detection
          req = Request(from_url)
!         req.origin_req_host = "example.com"
!         def redirect(h, req, code, url=to_url):
!             method = getattr(h, "http_error_%s" % code)
!             method(req, MockFile(), code, "Blah", {"location": url})
          # Note that the *original* request shares the same record of
          # redirections with the sub-requests caused by the redirections.
!         # once
!         redirect(h, req, 302)
!         # twice: loop detected
!         self.assertRaises(urllib2.HTTPError, redirect, h, req, 302)
!         # and again
!         self.assertRaises(urllib2.HTTPError, redirect, h, req, 302)
!         # but this is a different redirect code, so OK...
!         redirect(h, req, 301)
!         self.assertRaises(urllib2.HTTPError, redirect, h, req, 301)
!         # order doesn't matter
!         redirect(h, req, 303)
!         redirect(h, req, 307)
!         self.assertRaises(urllib2.HTTPError, redirect, h, req, 303)
  
          # detect endless non-repeating chain of redirects
!         req = Request(from_url)
!         req.origin_req_host = "example.com"
          count = 0
          try:
              while 1:
!                 redirect(h, req, 302, "http://example.com/%d" % count)
                  count = count + 1
          except urllib2.HTTPError:
--- 571,597 ----
          # loop detection
          req = Request(from_url)
!         def redirect(h, req, url=to_url):
!             h.http_error_302(req, MockFile(), 302, "Blah",
!                              MockHeaders({"location": url}))
          # Note that the *original* request shares the same record of
          # redirections with the sub-requests caused by the redirections.
! 
!         # detect infinite loop redirect of a URL to itself
!         req = Request(from_url, origin_req_host="example.com")
!         count = 0
!         try:
!             while 1:
!                 redirect(h, req, "http://example.com/")
!                 count = count + 1
!         except urllib2.HTTPError:
!             # don't stop until max_repeats, because cookies may introduce state
!             self.assertEqual(count, urllib2.HTTPRedirectHandler.max_repeats)
  
          # detect endless non-repeating chain of redirects
!         req = Request(from_url, origin_req_host="example.com")
          count = 0
          try:
              while 1:
!                 redirect(h, req, "http://example.com/%d" % count)
                  count = count + 1
          except urllib2.HTTPError:
***************
*** 577,580 ****
--- 599,633 ----
                               urllib2.HTTPRedirectHandler.max_redirections)
  
+     def test_cookie_redirect(self):
+         class MockHTTPHandler(urllib2.HTTPHandler):
+             def __init__(self): self._count = 0
+             def http_open(self, req):
+                 import mimetools
+                 from StringIO import StringIO
+                 if self._count == 0:
+                     self._count = self._count + 1
+                     msg = mimetools.Message(
+                         StringIO("Location: http://www.cracker.com/\r\n\r\n"))
+                     return self.parent.error(
+                         "http", req, MockFile(), 302, "Found", msg)
+                 else:
+                     self.req = req
+                     msg = mimetools.Message(StringIO("\r\n\r\n"))
+                     return MockResponse(200, "OK", msg, "", req.get_full_url())
+         # cookies shouldn't leak into redirected requests
+         from cookielib import CookieJar
+         from urllib2 import build_opener, HTTPHandler, HTTPError, \
+              HTTPCookieProcessor
+ 
+         from test_cookielib import interact_netscape
+ 
+         cj = CookieJar()
+         interact_netscape(cj, "http://www.example.com/", "spam=eggs")
+         hh = MockHTTPHandler()
+         cp = HTTPCookieProcessor(cj)
+         o = build_opener(hh, cp)
+         o.open("http://www.example.com/")
+         self.assert_(not hh.req.has_header("Cookie"))
+ 
  
  class MiscTests(unittest.TestCase):




More information about the Python-checkins mailing list