PageRenderTime 55ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/test/test_urllib2.py

https://bitbucket.org/dac_io/pypy
Python | 1327 lines | 1245 code | 52 blank | 30 comment | 6 complexity | 59e15c3d20432fc98a6b1634087aaba9 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. import unittest
  2. from test import test_support
  3. import os
  4. import socket
  5. import StringIO
  6. import urllib2
  7. from urllib2 import Request, OpenerDirector
  8. # XXX
  9. # Request
  10. # CacheFTPHandler (hard to write)
  11. # parse_keqv_list, parse_http_list, HTTPDigestAuthHandler
  12. class TrivialTests(unittest.TestCase):
  13. def test_trivial(self):
  14. # A couple trivial tests
  15. self.assertRaises(ValueError, urllib2.urlopen, 'bogus url')
  16. # XXX Name hacking to get this to work on Windows.
  17. fname = os.path.abspath(urllib2.__file__).replace('\\', '/')
  18. # And more hacking to get it to work on MacOS. This assumes
  19. # urllib.pathname2url works, unfortunately...
  20. if os.name == 'riscos':
  21. import string
  22. fname = os.expand(fname)
  23. fname = fname.translate(string.maketrans("/.", "./"))
  24. if os.name == 'nt':
  25. file_url = "file:///%s" % fname
  26. else:
  27. file_url = "file://%s" % fname
  28. f = urllib2.urlopen(file_url)
  29. buf = f.read()
  30. f.close()
  31. def test_parse_http_list(self):
  32. tests = [('a,b,c', ['a', 'b', 'c']),
  33. ('path"o,l"og"i"cal, example', ['path"o,l"og"i"cal', 'example']),
  34. ('a, b, "c", "d", "e,f", g, h', ['a', 'b', '"c"', '"d"', '"e,f"', 'g', 'h']),
  35. ('a="b\\"c", d="e\\,f", g="h\\\\i"', ['a="b"c"', 'd="e,f"', 'g="h\\i"'])]
  36. for string, list in tests:
  37. self.assertEqual(urllib2.parse_http_list(string), list)
  38. def test_request_headers_dict():
  39. """
  40. The Request.headers dictionary is not a documented interface. It should
  41. stay that way, because the complete set of headers are only accessible
  42. through the .get_header(), .has_header(), .header_items() interface.
  43. However, .headers pre-dates those methods, and so real code will be using
  44. the dictionary.
  45. The introduction in 2.4 of those methods was a mistake for the same reason:
  46. code that previously saw all (urllib2 user)-provided headers in .headers
  47. now sees only a subset (and the function interface is ugly and incomplete).
  48. A better change would have been to replace .headers dict with a dict
  49. subclass (or UserDict.DictMixin instance?) that preserved the .headers
  50. interface and also provided access to the "unredirected" headers. It's
  51. probably too late to fix that, though.
  52. Check .capitalize() case normalization:
  53. >>> url = "http://example.com"
  54. >>> Request(url, headers={"Spam-eggs": "blah"}).headers["Spam-eggs"]
  55. 'blah'
  56. >>> Request(url, headers={"spam-EggS": "blah"}).headers["Spam-eggs"]
  57. 'blah'
  58. Currently, Request(url, "Spam-eggs").headers["Spam-Eggs"] raises KeyError,
  59. but that could be changed in future.
  60. """
  61. def test_request_headers_methods():
  62. """
  63. Note the case normalization of header names here, to .capitalize()-case.
  64. This should be preserved for backwards-compatibility. (In the HTTP case,
  65. normalization to .title()-case is done by urllib2 before sending headers to
  66. httplib).
  67. >>> url = "http://example.com"
  68. >>> r = Request(url, headers={"Spam-eggs": "blah"})
  69. >>> r.has_header("Spam-eggs")
  70. True
  71. >>> r.header_items()
  72. [('Spam-eggs', 'blah')]
  73. >>> r.add_header("Foo-Bar", "baz")
  74. >>> items = r.header_items()
  75. >>> items.sort()
  76. >>> items
  77. [('Foo-bar', 'baz'), ('Spam-eggs', 'blah')]
  78. Note that e.g. r.has_header("spam-EggS") is currently False, and
  79. r.get_header("spam-EggS") returns None, but that could be changed in
  80. future.
  81. >>> r.has_header("Not-there")
  82. False
  83. >>> print r.get_header("Not-there")
  84. None
  85. >>> r.get_header("Not-there", "default")
  86. 'default'
  87. """
  88. def test_password_manager(self):
  89. """
  90. >>> mgr = urllib2.HTTPPasswordMgr()
  91. >>> add = mgr.add_password
  92. >>> add("Some Realm", "http://example.com/", "joe", "password")
  93. >>> add("Some Realm", "http://example.com/ni", "ni", "ni")
  94. >>> add("c", "http://example.com/foo", "foo", "ni")
  95. >>> add("c", "http://example.com/bar", "bar", "nini")
  96. >>> add("b", "http://example.com/", "first", "blah")
  97. >>> add("b", "http://example.com/", "second", "spam")
  98. >>> add("a", "http://example.com", "1", "a")
  99. >>> add("Some Realm", "http://c.example.com:3128", "3", "c")
  100. >>> add("Some Realm", "d.example.com", "4", "d")
  101. >>> add("Some Realm", "e.example.com:3128", "5", "e")
  102. >>> mgr.find_user_password("Some Realm", "example.com")
  103. ('joe', 'password')
  104. >>> mgr.find_user_password("Some Realm", "http://example.com")
  105. ('joe', 'password')
  106. >>> mgr.find_user_password("Some Realm", "http://example.com/")
  107. ('joe', 'password')
  108. >>> mgr.find_user_password("Some Realm", "http://example.com/spam")
  109. ('joe', 'password')
  110. >>> mgr.find_user_password("Some Realm", "http://example.com/spam/spam")
  111. ('joe', 'password')
  112. >>> mgr.find_user_password("c", "http://example.com/foo")
  113. ('foo', 'ni')
  114. >>> mgr.find_user_password("c", "http://example.com/bar")
  115. ('bar', 'nini')
  116. Actually, this is really undefined ATM
  117. ## Currently, we use the highest-level path where more than one match:
  118. ## >>> mgr.find_user_password("Some Realm", "http://example.com/ni")
  119. ## ('joe', 'password')
  120. Use latest add_password() in case of conflict:
  121. >>> mgr.find_user_password("b", "http://example.com/")
  122. ('second', 'spam')
  123. No special relationship between a.example.com and example.com:
  124. >>> mgr.find_user_password("a", "http://example.com/")
  125. ('1', 'a')
  126. >>> mgr.find_user_password("a", "http://a.example.com/")
  127. (None, None)
  128. Ports:
  129. >>> mgr.find_user_password("Some Realm", "c.example.com")
  130. (None, None)
  131. >>> mgr.find_user_password("Some Realm", "c.example.com:3128")
  132. ('3', 'c')
  133. >>> mgr.find_user_password("Some Realm", "http://c.example.com:3128")
  134. ('3', 'c')
  135. >>> mgr.find_user_password("Some Realm", "d.example.com")
  136. ('4', 'd')
  137. >>> mgr.find_user_password("Some Realm", "e.example.com:3128")
  138. ('5', 'e')
  139. """
  140. pass
  141. def test_password_manager_default_port(self):
  142. """
  143. >>> mgr = urllib2.HTTPPasswordMgr()
  144. >>> add = mgr.add_password
  145. The point to note here is that we can't guess the default port if there's
  146. no scheme. This applies to both add_password and find_user_password.
  147. >>> add("f", "http://g.example.com:80", "10", "j")
  148. >>> add("g", "http://h.example.com", "11", "k")
  149. >>> add("h", "i.example.com:80", "12", "l")
  150. >>> add("i", "j.example.com", "13", "m")
  151. >>> mgr.find_user_password("f", "g.example.com:100")
  152. (None, None)
  153. >>> mgr.find_user_password("f", "g.example.com:80")
  154. ('10', 'j')
  155. >>> mgr.find_user_password("f", "g.example.com")
  156. (None, None)
  157. >>> mgr.find_user_password("f", "http://g.example.com:100")
  158. (None, None)
  159. >>> mgr.find_user_password("f", "http://g.example.com:80")
  160. ('10', 'j')
  161. >>> mgr.find_user_password("f", "http://g.example.com")
  162. ('10', 'j')
  163. >>> mgr.find_user_password("g", "h.example.com")
  164. ('11', 'k')
  165. >>> mgr.find_user_password("g", "h.example.com:80")
  166. ('11', 'k')
  167. >>> mgr.find_user_password("g", "http://h.example.com:80")
  168. ('11', 'k')
  169. >>> mgr.find_user_password("h", "i.example.com")
  170. (None, None)
  171. >>> mgr.find_user_password("h", "i.example.com:80")
  172. ('12', 'l')
  173. >>> mgr.find_user_password("h", "http://i.example.com:80")
  174. ('12', 'l')
  175. >>> mgr.find_user_password("i", "j.example.com")
  176. ('13', 'm')
  177. >>> mgr.find_user_password("i", "j.example.com:80")
  178. (None, None)
  179. >>> mgr.find_user_password("i", "http://j.example.com")
  180. ('13', 'm')
  181. >>> mgr.find_user_password("i", "http://j.example.com:80")
  182. (None, None)
  183. """
  184. class MockOpener:
  185. addheaders = []
  186. def open(self, req, data=None,timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
  187. self.req, self.data, self.timeout = req, data, timeout
  188. def error(self, proto, *args):
  189. self.proto, self.args = proto, args
  190. class MockFile:
  191. def read(self, count=None): pass
  192. def readline(self, count=None): pass
  193. def close(self): pass
  194. class MockHeaders(dict):
  195. def getheaders(self, name):
  196. return self.values()
  197. class MockResponse(StringIO.StringIO):
  198. def __init__(self, code, msg, headers, data, url=None):
  199. StringIO.StringIO.__init__(self, data)
  200. self.code, self.msg, self.headers, self.url = code, msg, headers, url
  201. def info(self):
  202. return self.headers
  203. def geturl(self):
  204. return self.url
  205. class MockCookieJar:
  206. def add_cookie_header(self, request):
  207. self.ach_req = request
  208. def extract_cookies(self, response, request):
  209. self.ec_req, self.ec_r = request, response
  210. class FakeMethod:
  211. def __init__(self, meth_name, action, handle):
  212. self.meth_name = meth_name
  213. self.handle = handle
  214. self.action = action
  215. def __call__(self, *args):
  216. return self.handle(self.meth_name, self.action, *args)
  217. class MockHTTPResponse:
  218. def __init__(self, fp, msg, status, reason):
  219. self.fp = fp
  220. self.msg = msg
  221. self.status = status
  222. self.reason = reason
  223. def read(self):
  224. return ''
  225. class MockHTTPClass:
  226. def __init__(self):
  227. self.req_headers = []
  228. self.data = None
  229. self.raise_on_endheaders = False
  230. self._tunnel_headers = {}
  231. def __call__(self, host, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
  232. self.host = host
  233. self.timeout = timeout
  234. return self
  235. def set_debuglevel(self, level):
  236. self.level = level
  237. def set_tunnel(self, host, port=None, headers=None):
  238. self._tunnel_host = host
  239. self._tunnel_port = port
  240. if headers:
  241. self._tunnel_headers = headers
  242. else:
  243. self._tunnel_headers.clear()
  244. def request(self, method, url, body=None, headers=None):
  245. self.method = method
  246. self.selector = url
  247. if headers is not None:
  248. self.req_headers += headers.items()
  249. self.req_headers.sort()
  250. if body:
  251. self.data = body
  252. if self.raise_on_endheaders:
  253. import socket
  254. raise socket.error()
  255. def getresponse(self):
  256. return MockHTTPResponse(MockFile(), {}, 200, "OK")
  257. class MockHandler:
  258. # useful for testing handler machinery
  259. # see add_ordered_mock_handlers() docstring
  260. handler_order = 500
  261. def __init__(self, methods):
  262. self._define_methods(methods)
  263. def _define_methods(self, methods):
  264. for spec in methods:
  265. if len(spec) == 2: name, action = spec
  266. else: name, action = spec, None
  267. meth = FakeMethod(name, action, self.handle)
  268. setattr(self.__class__, name, meth)
  269. def handle(self, fn_name, action, *args, **kwds):
  270. self.parent.calls.append((self, fn_name, args, kwds))
  271. if action is None:
  272. return None
  273. elif action == "return self":
  274. return self
  275. elif action == "return response":
  276. res = MockResponse(200, "OK", {}, "")
  277. return res
  278. elif action == "return request":
  279. return Request("http://blah/")
  280. elif action.startswith("error"):
  281. code = action[action.rfind(" ")+1:]
  282. try:
  283. code = int(code)
  284. except ValueError:
  285. pass
  286. res = MockResponse(200, "OK", {}, "")
  287. return self.parent.error("http", args[0], res, code, "", {})
  288. elif action == "raise":
  289. raise urllib2.URLError("blah")
  290. assert False
  291. def close(self): pass
  292. def add_parent(self, parent):
  293. self.parent = parent
  294. self.parent.calls = []
  295. def __lt__(self, other):
  296. if not hasattr(other, "handler_order"):
  297. # No handler_order, leave in original order. Yuck.
  298. return True
  299. return self.handler_order < other.handler_order
  300. def add_ordered_mock_handlers(opener, meth_spec):
  301. """Create MockHandlers and add them to an OpenerDirector.
  302. meth_spec: list of lists of tuples and strings defining methods to define
  303. on handlers. eg:
  304. [["http_error", "ftp_open"], ["http_open"]]
  305. defines methods .http_error() and .ftp_open() on one handler, and
  306. .http_open() on another. These methods just record their arguments and
  307. return None. Using a tuple instead of a string causes the method to
  308. perform some action (see MockHandler.handle()), eg:
  309. [["http_error"], [("http_open", "return request")]]
  310. defines .http_error() on one handler (which simply returns None), and
  311. .http_open() on another handler, which returns a Request object.
  312. """
  313. handlers = []
  314. count = 0
  315. for meths in meth_spec:
  316. class MockHandlerSubclass(MockHandler): pass
  317. h = MockHandlerSubclass(meths)
  318. h.handler_order += count
  319. h.add_parent(opener)
  320. count = count + 1
  321. handlers.append(h)
  322. opener.add_handler(h)
  323. return handlers
  324. def build_test_opener(*handler_instances):
  325. opener = OpenerDirector()
  326. for h in handler_instances:
  327. opener.add_handler(h)
  328. return opener
  329. class MockHTTPHandler(urllib2.BaseHandler):
  330. # useful for testing redirections and auth
  331. # sends supplied headers and code as first response
  332. # sends 200 OK as second response
  333. def __init__(self, code, headers):
  334. self.code = code
  335. self.headers = headers
  336. self.reset()
  337. def reset(self):
  338. self._count = 0
  339. self.requests = []
  340. def http_open(self, req):
  341. import mimetools, httplib, copy
  342. from StringIO import StringIO
  343. self.requests.append(copy.deepcopy(req))
  344. if self._count == 0:
  345. self._count = self._count + 1
  346. name = httplib.responses[self.code]
  347. msg = mimetools.Message(StringIO(self.headers))
  348. return self.parent.error(
  349. "http", req, MockFile(), self.code, name, msg)
  350. else:
  351. self.req = req
  352. msg = mimetools.Message(StringIO("\r\n\r\n"))
  353. return MockResponse(200, "OK", msg, "", req.get_full_url())
  354. class MockHTTPSHandler(urllib2.AbstractHTTPHandler):
  355. # Useful for testing the Proxy-Authorization request by verifying the
  356. # properties of httpcon
  357. def __init__(self):
  358. urllib2.AbstractHTTPHandler.__init__(self)
  359. self.httpconn = MockHTTPClass()
  360. def https_open(self, req):
  361. return self.do_open(self.httpconn, req)
  362. class MockPasswordManager:
  363. def add_password(self, realm, uri, user, password):
  364. self.realm = realm
  365. self.url = uri
  366. self.user = user
  367. self.password = password
  368. def find_user_password(self, realm, authuri):
  369. self.target_realm = realm
  370. self.target_url = authuri
  371. return self.user, self.password
  372. class OpenerDirectorTests(unittest.TestCase):
  373. def test_add_non_handler(self):
  374. class NonHandler(object):
  375. pass
  376. self.assertRaises(TypeError,
  377. OpenerDirector().add_handler, NonHandler())
  378. def test_badly_named_methods(self):
  379. # test work-around for three methods that accidentally follow the
  380. # naming conventions for handler methods
  381. # (*_open() / *_request() / *_response())
  382. # These used to call the accidentally-named methods, causing a
  383. # TypeError in real code; here, returning self from these mock
  384. # methods would either cause no exception, or AttributeError.
  385. from urllib2 import URLError
  386. o = OpenerDirector()
  387. meth_spec = [
  388. [("do_open", "return self"), ("proxy_open", "return self")],
  389. [("redirect_request", "return self")],
  390. ]
  391. handlers = add_ordered_mock_handlers(o, meth_spec)
  392. o.add_handler(urllib2.UnknownHandler())
  393. for scheme in "do", "proxy", "redirect":
  394. self.assertRaises(URLError, o.open, scheme+"://example.com/")
  395. def test_handled(self):
  396. # handler returning non-None means no more handlers will be called
  397. o = OpenerDirector()
  398. meth_spec = [
  399. ["http_open", "ftp_open", "http_error_302"],
  400. ["ftp_open"],
  401. [("http_open", "return self")],
  402. [("http_open", "return self")],
  403. ]
  404. handlers = add_ordered_mock_handlers(o, meth_spec)
  405. req = Request("http://example.com/")
  406. r = o.open(req)
  407. # Second .http_open() gets called, third doesn't, since second returned
  408. # non-None. Handlers without .http_open() never get any methods called
  409. # on them.
  410. # In fact, second mock handler defining .http_open() returns self
  411. # (instead of response), which becomes the OpenerDirector's return
  412. # value.
  413. self.assertEqual(r, handlers[2])
  414. calls = [(handlers[0], "http_open"), (handlers[2], "http_open")]
  415. for expected, got in zip(calls, o.calls):
  416. handler, name, args, kwds = got
  417. self.assertEqual((handler, name), expected)
  418. self.assertEqual(args, (req,))
  419. def test_handler_order(self):
  420. o = OpenerDirector()
  421. handlers = []
  422. for meths, handler_order in [
  423. ([("http_open", "return self")], 500),
  424. (["http_open"], 0),
  425. ]:
  426. class MockHandlerSubclass(MockHandler): pass
  427. h = MockHandlerSubclass(meths)
  428. h.handler_order = handler_order
  429. handlers.append(h)
  430. o.add_handler(h)
  431. r = o.open("http://example.com/")
  432. # handlers called in reverse order, thanks to their sort order
  433. self.assertEqual(o.calls[0][0], handlers[1])
  434. self.assertEqual(o.calls[1][0], handlers[0])
  435. def test_raise(self):
  436. # raising URLError stops processing of request
  437. o = OpenerDirector()
  438. meth_spec = [
  439. [("http_open", "raise")],
  440. [("http_open", "return self")],
  441. ]
  442. handlers = add_ordered_mock_handlers(o, meth_spec)
  443. req = Request("http://example.com/")
  444. self.assertRaises(urllib2.URLError, o.open, req)
  445. self.assertEqual(o.calls, [(handlers[0], "http_open", (req,), {})])
  446. ## def test_error(self):
  447. ## # XXX this doesn't actually seem to be used in standard library,
  448. ## # but should really be tested anyway...
  449. def test_http_error(self):
  450. # XXX http_error_default
  451. # http errors are a special case
  452. o = OpenerDirector()
  453. meth_spec = [
  454. [("http_open", "error 302")],
  455. [("http_error_400", "raise"), "http_open"],
  456. [("http_error_302", "return response"), "http_error_303",
  457. "http_error"],
  458. [("http_error_302")],
  459. ]
  460. handlers = add_ordered_mock_handlers(o, meth_spec)
  461. class Unknown:
  462. def __eq__(self, other): return True
  463. req = Request("http://example.com/")
  464. r = o.open(req)
  465. assert len(o.calls) == 2
  466. calls = [(handlers[0], "http_open", (req,)),
  467. (handlers[2], "http_error_302",
  468. (req, Unknown(), 302, "", {}))]
  469. for expected, got in zip(calls, o.calls):
  470. handler, method_name, args = expected
  471. self.assertEqual((handler, method_name), got[:2])
  472. self.assertEqual(args, got[2])
  473. def test_processors(self):
  474. # *_request / *_response methods get called appropriately
  475. o = OpenerDirector()
  476. meth_spec = [
  477. [("http_request", "return request"),
  478. ("http_response", "return response")],
  479. [("http_request", "return request"),
  480. ("http_response", "return response")],
  481. ]
  482. handlers = add_ordered_mock_handlers(o, meth_spec)
  483. req = Request("http://example.com/")
  484. r = o.open(req)
  485. # processor methods are called on *all* handlers that define them,
  486. # not just the first handler that handles the request
  487. calls = [
  488. (handlers[0], "http_request"), (handlers[1], "http_request"),
  489. (handlers[0], "http_response"), (handlers[1], "http_response")]
  490. for i, (handler, name, args, kwds) in enumerate(o.calls):
  491. if i < 2:
  492. # *_request
  493. self.assertEqual((handler, name), calls[i])
  494. self.assertEqual(len(args), 1)
  495. self.assertIsInstance(args[0], Request)
  496. else:
  497. # *_response
  498. self.assertEqual((handler, name), calls[i])
  499. self.assertEqual(len(args), 2)
  500. self.assertIsInstance(args[0], Request)
  501. # response from opener.open is None, because there's no
  502. # handler that defines http_open to handle it
  503. self.assertTrue(args[1] is None or
  504. isinstance(args[1], MockResponse))
  505. def sanepathname2url(path):
  506. import urllib
  507. urlpath = urllib.pathname2url(path)
  508. if os.name == "nt" and urlpath.startswith("///"):
  509. urlpath = urlpath[2:]
  510. # XXX don't ask me about the mac...
  511. return urlpath
  512. class HandlerTests(unittest.TestCase):
  513. def test_ftp(self):
  514. class MockFTPWrapper:
  515. def __init__(self, data): self.data = data
  516. def retrfile(self, filename, filetype):
  517. self.filename, self.filetype = filename, filetype
  518. return StringIO.StringIO(self.data), len(self.data)
  519. class NullFTPHandler(urllib2.FTPHandler):
  520. def __init__(self, data): self.data = data
  521. def connect_ftp(self, user, passwd, host, port, dirs,
  522. timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
  523. self.user, self.passwd = user, passwd
  524. self.host, self.port = host, port
  525. self.dirs = dirs
  526. self.ftpwrapper = MockFTPWrapper(self.data)
  527. return self.ftpwrapper
  528. import ftplib
  529. data = "rheum rhaponicum"
  530. h = NullFTPHandler(data)
  531. o = h.parent = MockOpener()
  532. for url, host, port, user, passwd, type_, dirs, filename, mimetype in [
  533. ("ftp://localhost/foo/bar/baz.html",
  534. "localhost", ftplib.FTP_PORT, "", "", "I",
  535. ["foo", "bar"], "baz.html", "text/html"),
  536. ("ftp://parrot@localhost/foo/bar/baz.html",
  537. "localhost", ftplib.FTP_PORT, "parrot", "", "I",
  538. ["foo", "bar"], "baz.html", "text/html"),
  539. ("ftp://%25parrot@localhost/foo/bar/baz.html",
  540. "localhost", ftplib.FTP_PORT, "%parrot", "", "I",
  541. ["foo", "bar"], "baz.html", "text/html"),
  542. ("ftp://%2542parrot@localhost/foo/bar/baz.html",
  543. "localhost", ftplib.FTP_PORT, "%42parrot", "", "I",
  544. ["foo", "bar"], "baz.html", "text/html"),
  545. ("ftp://localhost:80/foo/bar/",
  546. "localhost", 80, "", "", "D",
  547. ["foo", "bar"], "", None),
  548. ("ftp://localhost/baz.gif;type=a",
  549. "localhost", ftplib.FTP_PORT, "", "", "A",
  550. [], "baz.gif", None), # XXX really this should guess image/gif
  551. ]:
  552. req = Request(url)
  553. req.timeout = None
  554. r = h.ftp_open(req)
  555. # ftp authentication not yet implemented by FTPHandler
  556. self.assertEqual(h.user, user)
  557. self.assertEqual(h.passwd, passwd)
  558. self.assertEqual(h.host, socket.gethostbyname(host))
  559. self.assertEqual(h.port, port)
  560. self.assertEqual(h.dirs, dirs)
  561. self.assertEqual(h.ftpwrapper.filename, filename)
  562. self.assertEqual(h.ftpwrapper.filetype, type_)
  563. headers = r.info()
  564. self.assertEqual(headers.get("Content-type"), mimetype)
  565. self.assertEqual(int(headers["Content-length"]), len(data))
  566. def test_file(self):
  567. import rfc822, socket
  568. h = urllib2.FileHandler()
  569. o = h.parent = MockOpener()
  570. TESTFN = test_support.TESTFN
  571. urlpath = sanepathname2url(os.path.abspath(TESTFN))
  572. towrite = "hello, world\n"
  573. urls = [
  574. "file://localhost%s" % urlpath,
  575. "file://%s" % urlpath,
  576. "file://%s%s" % (socket.gethostbyname('localhost'), urlpath),
  577. ]
  578. try:
  579. localaddr = socket.gethostbyname(socket.gethostname())
  580. except socket.gaierror:
  581. localaddr = ''
  582. if localaddr:
  583. urls.append("file://%s%s" % (localaddr, urlpath))
  584. for url in urls:
  585. f = open(TESTFN, "wb")
  586. try:
  587. try:
  588. f.write(towrite)
  589. finally:
  590. f.close()
  591. r = h.file_open(Request(url))
  592. try:
  593. data = r.read()
  594. headers = r.info()
  595. respurl = r.geturl()
  596. finally:
  597. r.close()
  598. stats = os.stat(TESTFN)
  599. modified = rfc822.formatdate(stats.st_mtime)
  600. finally:
  601. os.remove(TESTFN)
  602. self.assertEqual(data, towrite)
  603. self.assertEqual(headers["Content-type"], "text/plain")
  604. self.assertEqual(headers["Content-length"], "13")
  605. self.assertEqual(headers["Last-modified"], modified)
  606. self.assertEqual(respurl, url)
  607. for url in [
  608. "file://localhost:80%s" % urlpath,
  609. "file:///file_does_not_exist.txt",
  610. "file://%s:80%s/%s" % (socket.gethostbyname('localhost'),
  611. os.getcwd(), TESTFN),
  612. "file://somerandomhost.ontheinternet.com%s/%s" %
  613. (os.getcwd(), TESTFN),
  614. ]:
  615. try:
  616. f = open(TESTFN, "wb")
  617. try:
  618. f.write(towrite)
  619. finally:
  620. f.close()
  621. self.assertRaises(urllib2.URLError,
  622. h.file_open, Request(url))
  623. finally:
  624. os.remove(TESTFN)
  625. h = urllib2.FileHandler()
  626. o = h.parent = MockOpener()
  627. # XXXX why does // mean ftp (and /// mean not ftp!), and where
  628. # is file: scheme specified? I think this is really a bug, and
  629. # what was intended was to distinguish between URLs like:
  630. # file:/blah.txt (a file)
  631. # file://localhost/blah.txt (a file)
  632. # file:///blah.txt (a file)
  633. # file://ftp.example.com/blah.txt (an ftp URL)
  634. for url, ftp in [
  635. ("file://ftp.example.com//foo.txt", True),
  636. ("file://ftp.example.com///foo.txt", False),
  637. # XXXX bug: fails with OSError, should be URLError
  638. ("file://ftp.example.com/foo.txt", False),
  639. ("file://somehost//foo/something.txt", True),
  640. ("file://localhost//foo/something.txt", False),
  641. ]:
  642. req = Request(url)
  643. try:
  644. h.file_open(req)
  645. # XXXX remove OSError when bug fixed
  646. except (urllib2.URLError, OSError):
  647. self.assertTrue(not ftp)
  648. else:
  649. self.assertTrue(o.req is req)
  650. self.assertEqual(req.type, "ftp")
  651. self.assertEqual(req.type == "ftp", ftp)
  652. def test_http(self):
  653. h = urllib2.AbstractHTTPHandler()
  654. o = h.parent = MockOpener()
  655. url = "http://example.com/"
  656. for method, data in [("GET", None), ("POST", "blah")]:
  657. req = Request(url, data, {"Foo": "bar"})
  658. req.timeout = None
  659. req.add_unredirected_header("Spam", "eggs")
  660. http = MockHTTPClass()
  661. r = h.do_open(http, req)
  662. # result attributes
  663. r.read; r.readline # wrapped MockFile methods
  664. r.info; r.geturl # addinfourl methods
  665. r.code, r.msg == 200, "OK" # added from MockHTTPClass.getreply()
  666. hdrs = r.info()
  667. hdrs.get; hdrs.has_key # r.info() gives dict from .getreply()
  668. self.assertEqual(r.geturl(), url)
  669. self.assertEqual(http.host, "example.com")
  670. self.assertEqual(http.level, 0)
  671. self.assertEqual(http.method, method)
  672. self.assertEqual(http.selector, "/")
  673. self.assertEqual(http.req_headers,
  674. [("Connection", "close"),
  675. ("Foo", "bar"), ("Spam", "eggs")])
  676. self.assertEqual(http.data, data)
  677. # check socket.error converted to URLError
  678. http.raise_on_endheaders = True
  679. self.assertRaises(urllib2.URLError, h.do_open, http, req)
  680. # check adding of standard headers
  681. o.addheaders = [("Spam", "eggs")]
  682. for data in "", None: # POST, GET
  683. req = Request("http://example.com/", data)
  684. r = MockResponse(200, "OK", {}, "")
  685. newreq = h.do_request_(req)
  686. if data is None: # GET
  687. self.assertNotIn("Content-length", req.unredirected_hdrs)
  688. self.assertNotIn("Content-type", req.unredirected_hdrs)
  689. else: # POST
  690. self.assertEqual(req.unredirected_hdrs["Content-length"], "0")
  691. self.assertEqual(req.unredirected_hdrs["Content-type"],
  692. "application/x-www-form-urlencoded")
  693. # XXX the details of Host could be better tested
  694. self.assertEqual(req.unredirected_hdrs["Host"], "example.com")
  695. self.assertEqual(req.unredirected_hdrs["Spam"], "eggs")
  696. # don't clobber existing headers
  697. req.add_unredirected_header("Content-length", "foo")
  698. req.add_unredirected_header("Content-type", "bar")
  699. req.add_unredirected_header("Host", "baz")
  700. req.add_unredirected_header("Spam", "foo")
  701. newreq = h.do_request_(req)
  702. self.assertEqual(req.unredirected_hdrs["Content-length"], "foo")
  703. self.assertEqual(req.unredirected_hdrs["Content-type"], "bar")
  704. self.assertEqual(req.unredirected_hdrs["Host"], "baz")
  705. self.assertEqual(req.unredirected_hdrs["Spam"], "foo")
  706. def test_http_doubleslash(self):
  707. # Checks that the presence of an unnecessary double slash in a url doesn't break anything
  708. # Previously, a double slash directly after the host could cause incorrect parsing of the url
  709. h = urllib2.AbstractHTTPHandler()
  710. o = h.parent = MockOpener()
  711. data = ""
  712. ds_urls = [
  713. "http://example.com/foo/bar/baz.html",
  714. "http://example.com//foo/bar/baz.html",
  715. "http://example.com/foo//bar/baz.html",
  716. "http://example.com/foo/bar//baz.html",
  717. ]
  718. for ds_url in ds_urls:
  719. ds_req = Request(ds_url, data)
  720. # Check whether host is determined correctly if there is no proxy
  721. np_ds_req = h.do_request_(ds_req)
  722. self.assertEqual(np_ds_req.unredirected_hdrs["Host"],"example.com")
  723. # Check whether host is determined correctly if there is a proxy
  724. ds_req.set_proxy("someproxy:3128",None)
  725. p_ds_req = h.do_request_(ds_req)
  726. self.assertEqual(p_ds_req.unredirected_hdrs["Host"],"example.com")
  727. def test_fixpath_in_weirdurls(self):
  728. # Issue4493: urllib2 to supply '/' when to urls where path does not
  729. # start with'/'
  730. h = urllib2.AbstractHTTPHandler()
  731. o = h.parent = MockOpener()
  732. weird_url = 'http://www.python.org?getspam'
  733. req = Request(weird_url)
  734. newreq = h.do_request_(req)
  735. self.assertEqual(newreq.get_host(),'www.python.org')
  736. self.assertEqual(newreq.get_selector(),'/?getspam')
  737. url_without_path = 'http://www.python.org'
  738. req = Request(url_without_path)
  739. newreq = h.do_request_(req)
  740. self.assertEqual(newreq.get_host(),'www.python.org')
  741. self.assertEqual(newreq.get_selector(),'')
  742. def test_errors(self):
  743. h = urllib2.HTTPErrorProcessor()
  744. o = h.parent = MockOpener()
  745. url = "http://example.com/"
  746. req = Request(url)
  747. # all 2xx are passed through
  748. r = MockResponse(200, "OK", {}, "", url)
  749. newr = h.http_response(req, r)
  750. self.assertTrue(r is newr)
  751. self.assertTrue(not hasattr(o, "proto")) # o.error not called
  752. r = MockResponse(202, "Accepted", {}, "", url)
  753. newr = h.http_response(req, r)
  754. self.assertTrue(r is newr)
  755. self.assertTrue(not hasattr(o, "proto")) # o.error not called
  756. r = MockResponse(206, "Partial content", {}, "", url)
  757. newr = h.http_response(req, r)
  758. self.assertTrue(r is newr)
  759. self.assertTrue(not hasattr(o, "proto")) # o.error not called
  760. # anything else calls o.error (and MockOpener returns None, here)
  761. r = MockResponse(502, "Bad gateway", {}, "", url)
  762. self.assertTrue(h.http_response(req, r) is None)
  763. self.assertEqual(o.proto, "http") # o.error called
  764. self.assertEqual(o.args, (req, r, 502, "Bad gateway", {}))
  765. def test_cookies(self):
  766. cj = MockCookieJar()
  767. h = urllib2.HTTPCookieProcessor(cj)
  768. o = h.parent = MockOpener()
  769. req = Request("http://example.com/")
  770. r = MockResponse(200, "OK", {}, "")
  771. newreq = h.http_request(req)
  772. self.assertTrue(cj.ach_req is req is newreq)
  773. self.assertEqual(req.get_origin_req_host(), "example.com")
  774. self.assertTrue(not req.is_unverifiable())
  775. newr = h.http_response(req, r)
  776. self.assertTrue(cj.ec_req is req)
  777. self.assertTrue(cj.ec_r is r is newr)
  778. def test_redirect(self):
  779. from_url = "http://example.com/a.html"
  780. to_url = "http://example.com/b.html"
  781. h = urllib2.HTTPRedirectHandler()
  782. o = h.parent = MockOpener()
  783. # ordinary redirect behaviour
  784. for code in 301, 302, 303, 307:
  785. for data in None, "blah\nblah\n":
  786. method = getattr(h, "http_error_%s" % code)
  787. req = Request(from_url, data)
  788. req.add_header("Nonsense", "viking=withhold")
  789. req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
  790. if data is not None:
  791. req.add_header("Content-Length", str(len(data)))
  792. req.add_unredirected_header("Spam", "spam")
  793. try:
  794. method(req, MockFile(), code, "Blah",
  795. MockHeaders({"location": to_url}))
  796. except urllib2.HTTPError:
  797. # 307 in response to POST requires user OK
  798. self.assertTrue(code == 307 and data is not None)
  799. self.assertEqual(o.req.get_full_url(), to_url)
  800. try:
  801. self.assertEqual(o.req.get_method(), "GET")
  802. except AttributeError:
  803. self.assertTrue(not o.req.has_data())
  804. # now it's a GET, there should not be headers regarding content
  805. # (possibly dragged from before being a POST)
  806. headers = [x.lower() for x in o.req.headers]
  807. self.assertNotIn("content-length", headers)
  808. self.assertNotIn("content-type", headers)
  809. self.assertEqual(o.req.headers["Nonsense"],
  810. "viking=withhold")
  811. self.assertNotIn("Spam", o.req.headers)
  812. self.assertNotIn("Spam", o.req.unredirected_hdrs)
  813. # loop detection
  814. req = Request(from_url)
  815. req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
  816. def redirect(h, req, url=to_url):
  817. h.http_error_302(req, MockFile(), 302, "Blah",
  818. MockHeaders({"location": url}))
  819. # Note that the *original* request shares the same record of
  820. # redirections with the sub-requests caused by the redirections.
  821. # detect infinite loop redirect of a URL to itself
  822. req = Request(from_url, origin_req_host="example.com")
  823. count = 0
  824. req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
  825. try:
  826. while 1:
  827. redirect(h, req, "http://example.com/")
  828. count = count + 1
  829. except urllib2.HTTPError:
  830. # don't stop until max_repeats, because cookies may introduce state
  831. self.assertEqual(count, urllib2.HTTPRedirectHandler.max_repeats)
  832. # detect endless non-repeating chain of redirects
  833. req = Request(from_url, origin_req_host="example.com")
  834. count = 0
  835. req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
  836. try:
  837. while 1:
  838. redirect(h, req, "http://example.com/%d" % count)
  839. count = count + 1
  840. except urllib2.HTTPError:
  841. self.assertEqual(count,
  842. urllib2.HTTPRedirectHandler.max_redirections)
  843. def test_invalid_redirect(self):
  844. from_url = "http://example.com/a.html"
  845. valid_schemes = ['http', 'https', 'ftp']
  846. invalid_schemes = ['file', 'imap', 'ldap']
  847. schemeless_url = "example.com/b.html"
  848. h = urllib2.HTTPRedirectHandler()
  849. o = h.parent = MockOpener()
  850. req = Request(from_url)
  851. req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
  852. for scheme in invalid_schemes:
  853. invalid_url = scheme + '://' + schemeless_url
  854. self.assertRaises(urllib2.HTTPError, h.http_error_302,
  855. req, MockFile(), 302, "Security Loophole",
  856. MockHeaders({"location": invalid_url}))
  857. for scheme in valid_schemes:
  858. valid_url = scheme + '://' + schemeless_url
  859. h.http_error_302(req, MockFile(), 302, "That's fine",
  860. MockHeaders({"location": valid_url}))
  861. self.assertEqual(o.req.get_full_url(), valid_url)
  862. def test_cookie_redirect(self):
  863. # cookies shouldn't leak into redirected requests
  864. from cookielib import CookieJar
  865. from test.test_cookielib import interact_netscape
  866. cj = CookieJar()
  867. interact_netscape(cj, "http://www.example.com/", "spam=eggs")
  868. hh = MockHTTPHandler(302, "Location: http://www.cracker.com/\r\n\r\n")
  869. hdeh = urllib2.HTTPDefaultErrorHandler()
  870. hrh = urllib2.HTTPRedirectHandler()
  871. cp = urllib2.HTTPCookieProcessor(cj)
  872. o = build_test_opener(hh, hdeh, hrh, cp)
  873. o.open("http://www.example.com/")
  874. self.assertTrue(not hh.req.has_header("Cookie"))
  875. def test_redirect_fragment(self):
  876. redirected_url = 'http://www.example.com/index.html#OK\r\n\r\n'
  877. hh = MockHTTPHandler(302, 'Location: ' + redirected_url)
  878. hdeh = urllib2.HTTPDefaultErrorHandler()
  879. hrh = urllib2.HTTPRedirectHandler()
  880. o = build_test_opener(hh, hdeh, hrh)
  881. fp = o.open('http://www.example.com')
  882. self.assertEqual(fp.geturl(), redirected_url.strip())
  883. def test_proxy(self):
  884. o = OpenerDirector()
  885. ph = urllib2.ProxyHandler(dict(http="proxy.example.com:3128"))
  886. o.add_handler(ph)
  887. meth_spec = [
  888. [("http_open", "return response")]
  889. ]
  890. handlers = add_ordered_mock_handlers(o, meth_spec)
  891. req = Request("http://acme.example.com/")
  892. self.assertEqual(req.get_host(), "acme.example.com")
  893. r = o.open(req)
  894. self.assertEqual(req.get_host(), "proxy.example.com:3128")
  895. self.assertEqual([(handlers[0], "http_open")],
  896. [tup[0:2] for tup in o.calls])
  897. def test_proxy_no_proxy(self):
  898. os.environ['no_proxy'] = 'python.org'
  899. o = OpenerDirector()
  900. ph = urllib2.ProxyHandler(dict(http="proxy.example.com"))
  901. o.add_handler(ph)
  902. req = Request("http://www.perl.org/")
  903. self.assertEqual(req.get_host(), "www.perl.org")
  904. r = o.open(req)
  905. self.assertEqual(req.get_host(), "proxy.example.com")
  906. req = Request("http://www.python.org")
  907. self.assertEqual(req.get_host(), "www.python.org")
  908. r = o.open(req)
  909. self.assertEqual(req.get_host(), "www.python.org")
  910. del os.environ['no_proxy']
  911. def test_proxy_https(self):
  912. o = OpenerDirector()
  913. ph = urllib2.ProxyHandler(dict(https='proxy.example.com:3128'))
  914. o.add_handler(ph)
  915. meth_spec = [
  916. [("https_open","return response")]
  917. ]
  918. handlers = add_ordered_mock_handlers(o, meth_spec)
  919. req = Request("https://www.example.com/")
  920. self.assertEqual(req.get_host(), "www.example.com")
  921. r = o.open(req)
  922. self.assertEqual(req.get_host(), "proxy.example.com:3128")
  923. self.assertEqual([(handlers[0], "https_open")],
  924. [tup[0:2] for tup in o.calls])
  925. def test_proxy_https_proxy_authorization(self):
  926. o = OpenerDirector()
  927. ph = urllib2.ProxyHandler(dict(https='proxy.example.com:3128'))
  928. o.add_handler(ph)
  929. https_handler = MockHTTPSHandler()
  930. o.add_handler(https_handler)
  931. req = Request("https://www.example.com/")
  932. req.add_header("Proxy-Authorization","FooBar")
  933. req.add_header("User-Agent","Grail")
  934. self.assertEqual(req.get_host(), "www.example.com")
  935. self.assertIsNone(req._tunnel_host)
  936. r = o.open(req)
  937. # Verify Proxy-Authorization gets tunneled to request.
  938. # httpsconn req_headers do not have the Proxy-Authorization header but
  939. # the req will have.
  940. self.assertNotIn(("Proxy-Authorization","FooBar"),
  941. https_handler.httpconn.req_headers)
  942. self.assertIn(("User-Agent","Grail"),
  943. https_handler.httpconn.req_headers)
  944. self.assertIsNotNone(req._tunnel_host)
  945. self.assertEqual(req.get_host(), "proxy.example.com:3128")
  946. self.assertEqual(req.get_header("Proxy-authorization"),"FooBar")
  947. def test_basic_auth(self, quote_char='"'):
  948. opener = OpenerDirector()
  949. password_manager = MockPasswordManager()
  950. auth_handler = urllib2.HTTPBasicAuthHandler(password_manager)
  951. realm = "ACME Widget Store"
  952. http_handler = MockHTTPHandler(
  953. 401, 'WWW-Authenticate: Basic realm=%s%s%s\r\n\r\n' %
  954. (quote_char, realm, quote_char) )
  955. opener.add_handler(auth_handler)
  956. opener.add_handler(http_handler)
  957. self._test_basic_auth(opener, auth_handler, "Authorization",
  958. realm, http_handler, password_manager,
  959. "http://acme.example.com/protected",
  960. "http://acme.example.com/protected",
  961. )
  962. def test_basic_auth_with_single_quoted_realm(self):
  963. self.test_basic_auth(quote_char="'")
  964. def test_proxy_basic_auth(self):
  965. opener = OpenerDirector()
  966. ph = urllib2.ProxyHandler(dict(http="proxy.example.com:3128"))
  967. opener.add_handler(ph)
  968. password_manager = MockPasswordManager()
  969. auth_handler = urllib2.ProxyBasicAuthHandler(password_manager)
  970. realm = "ACME Networks"
  971. http_handler = MockHTTPHandler(
  972. 407, 'Proxy-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
  973. opener.add_handler(auth_handler)
  974. opener.add_handler(http_handler)
  975. self._test_basic_auth(opener, auth_handler, "Proxy-authorization",
  976. realm, http_handler, password_manager,
  977. "http://acme.example.com:3128/protected",
  978. "proxy.example.com:3128",
  979. )
  980. def test_basic_and_digest_auth_handlers(self):
  981. # HTTPDigestAuthHandler threw an exception if it couldn't handle a 40*
  982. # response (http://python.org/sf/1479302), where it should instead
  983. # return None to allow another handler (especially
  984. # HTTPBasicAuthHandler) to handle the response.
  985. # Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must
  986. # try digest first (since it's the strongest auth scheme), so we record
  987. # order of calls here to check digest comes first:
  988. class RecordingOpenerDirector(OpenerDirector):
  989. def __init__(self):
  990. OpenerDirector.__init__(self)
  991. self.recorded = []
  992. def record(self, info):
  993. self.recorded.append(info)
  994. class TestDigestAuthHandler(urllib2.HTTPDigestAuthHandler):
  995. def http_error_401(self, *args, **kwds):
  996. self.parent.record("digest")
  997. urllib2.HTTPDigestAuthHandler.http_error_401(self,
  998. *args, **kwds)
  999. class TestBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
  1000. def http_error_401(self, *args, **kwds):
  1001. self.parent.record("basic")
  1002. urllib2.HTTPBasicAuthHandler.http_error_401(self,
  1003. *args, **kwds)
  1004. opener = RecordingOpenerDirector()
  1005. password_manager = MockPasswordManager()
  1006. digest_handler = TestDigestAuthHandler(password_manager)
  1007. basic_handler = TestBasicAuthHandler(password_manager)
  1008. realm = "ACME Networks"
  1009. http_handler = MockHTTPHandler(
  1010. 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
  1011. opener.add_handler(basic_handler)
  1012. opener.add_handler(digest_handler)
  1013. opener.add_handler(http_handler)
  1014. # check basic auth isn't blocked by digest handler failing
  1015. self._test_basic_auth(opener, basic_handler, "Authorization",
  1016. realm, http_handler, password_manager,
  1017. "http://acme.example.com/protected",
  1018. "http://acme.example.com/protected",
  1019. )
  1020. # check digest was tried before basic (twice, because
  1021. # _test_basic_auth called .open() twice)
  1022. self.assertEqual(opener.recorded, ["digest", "basic"]*2)
  1023. def _test_basic_auth(self, opener, auth_handler, auth_header,
  1024. realm, http_handler, password_manager,
  1025. request_url, protected_url):
  1026. import base64
  1027. user, password = "wile", "coyote"
  1028. # .add_password() fed through to password manager
  1029. auth_handler.add_password(realm, request_url, user, password)
  1030. self.assertEqual(realm, password_manager.realm)
  1031. self.assertEqual(request_url, password_manager.url)
  1032. self.assertEqual(user, password_manager.user)
  1033. self.assertEqual(password, password_manager.password)
  1034. r = opener.open(request_url)
  1035. # should have asked the password manager for the username/password
  1036. self.assertEqual(password_manager.target_realm, realm)
  1037. self.assertEqual(password_manager.target_url, protected_url)
  1038. # expect one request without authorization, then one with
  1039. self.assertEqual(len(http_handler.requests), 2)
  1040. self.assertFalse(http_handler.requests[0].has_header(auth_header))
  1041. userpass = '%s:%s' % (user, password)
  1042. auth_hdr_value = 'Basic '+base64.encodestring(userpass).strip()
  1043. self.assertEqual(http_handler.requests[1].get_header(auth_header),
  1044. auth_hdr_value)
  1045. self.assertEqual(http_handler.requests[1].unredirected_hdrs[auth_header],
  1046. auth_hdr_value)
  1047. # if the password manager can't find a password, the handler won't
  1048. # handle the HTTP auth error
  1049. password_manager.user = password_manager.password = None
  1050. http_handler.reset()
  1051. r = opener.open(request_url)
  1052. self.assertEqual(len(http_handler.requests), 1)
  1053. self.assertFalse(http_handler.requests[0].has_header(auth_header))
  1054. class MiscTests(unittest.TestCase):
  1055. def test_build_opener(self):
  1056. class MyHTTPHandler(urllib2.HTTPHandler): pass
  1057. class FooHandler(urllib2.BaseHandler):
  1058. def foo_open(self): pass
  1059. class BarHandler(urllib2.BaseHandler):
  1060. def bar_open(self): pass
  1061. build_opener = urllib2.build_opener
  1062. o = build_opener(FooHandler, BarHandler)
  1063. self.opener_has_handler(o, FooHandler)
  1064. self.opener_has_handler(o, BarHandler)
  1065. # can take a mix of classes and instances
  1066. o = build_opener(FooHandler, BarHandler())
  1067. self.opener_has_handler(o, FooHandler)
  1068. self.opener_has_handler(o, BarHandler)
  1069. # subclasses of default handlers override default handlers
  1070. o = build_opener(MyHTTPHandler)
  1071. self.opener_has_handler(o, MyHTTPHandler)
  1072. # a particular case of overriding: default handlers can be passed
  1073. # in explicitly
  1074. o = build_opener()
  1075. self.opener_has_handler(o, urllib2.HTTPHandler)
  1076. o = build_opener(urllib2.HTTPHandler)
  1077. self.opener_has_handler(o, urllib2.HTTPHandler)
  1078. o = build_opener(urllib2.HTTPHandler())
  1079. self.opener_has_handler(o, urllib2.HTTPHandler)
  1080. # Issue2670: multiple handlers sharing the same base class
  1081. class MyOtherHTTPHandler(urllib2.HTTPHandler): pass
  1082. o = build_opener(MyHTTPHandler, MyOtherHTTPHandler)
  1083. self.opener_has_handler(o, MyHTTPHandler)
  1084. self.opener_has_handler(o, MyOtherHTTPHandler)
  1085. def opener_has_handler(self, opener, handler_class):
  1086. for h in opener.handlers:
  1087. if h.__class__ == handler_class:
  1088. break
  1089. else:
  1090. self.assertTrue(False)
  1091. class RequestTests(unittest.TestCase):
  1092. def setUp(self):
  1093. self.get = urllib2.Request("http://www.python.org/~jeremy/")
  1094. self.post = urllib2.Request("http://www.python.org/~jeremy/",
  1095. "data",
  1096. headers={"X-Test": "test"})
  1097. def test_method(self):
  1098. self.assertEqual("POST", self.post.get_method())
  1099. self.assertEqual("GET", self.get.get_method())
  1100. def

Large files files are truncated, but you can click here to view the full file