PageRenderTime 63ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://bitbucket.org/dac_io/pypy
Python | 1330 lines | 1248 code | 52 blank | 30 comment | 6 complexity | 4c4cf2e1267bceede306539eef93cd99 MD5 | raw 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. def close(self):
  258. pass
  259. class MockHandler:
  260. # useful for testing handler machinery
  261. # see add_ordered_mock_handlers() docstring
  262. handler_order = 500
  263. def __init__(self, methods):
  264. self._define_methods(methods)
  265. def _define_methods(self, methods):
  266. for spec in methods:
  267. if len(spec) == 2: name, action = spec
  268. else: name, action = spec, None
  269. meth = FakeMethod(name, action, self.handle)
  270. setattr(self.__class__, name, meth)
  271. def handle(self, fn_name, action, *args, **kwds):
  272. self.parent.calls.append((self, fn_name, args, kwds))
  273. if action is None:
  274. return None
  275. elif action == "return self":
  276. return self
  277. elif action == "return response":
  278. res = MockResponse(200, "OK", {}, "")
  279. return res
  280. elif action == "return request":
  281. return Request("http://blah/")
  282. elif action.startswith("error"):
  283. code = action[action.rfind(" ")+1:]
  284. try:
  285. code = int(code)
  286. except ValueError:
  287. pass
  288. res = MockResponse(200, "OK", {}, "")
  289. return self.parent.error("http", args[0], res, code, "", {})
  290. elif action == "raise":
  291. raise urllib2.URLError("blah")
  292. assert False
  293. def close(self): pass
  294. def add_parent(self, parent):
  295. self.parent = parent
  296. self.parent.calls = []
  297. def __lt__(self, other):
  298. if not hasattr(other, "handler_order"):
  299. # No handler_order, leave in original order. Yuck.
  300. return True
  301. return self.handler_order < other.handler_order
  302. def add_ordered_mock_handlers(opener, meth_spec):
  303. """Create MockHandlers and add them to an OpenerDirector.
  304. meth_spec: list of lists of tuples and strings defining methods to define
  305. on handlers. eg:
  306. [["http_error", "ftp_open"], ["http_open"]]
  307. defines methods .http_error() and .ftp_open() on one handler, and
  308. .http_open() on another. These methods just record their arguments and
  309. return None. Using a tuple instead of a string causes the method to
  310. perform some action (see MockHandler.handle()), eg:
  311. [["http_error"], [("http_open", "return request")]]
  312. defines .http_error() on one handler (which simply returns None), and
  313. .http_open() on another handler, which returns a Request object.
  314. """
  315. handlers = []
  316. count = 0
  317. for meths in meth_spec:
  318. class MockHandlerSubclass(MockHandler): pass
  319. h = MockHandlerSubclass(meths)
  320. h.handler_order += count
  321. h.add_parent(opener)
  322. count = count + 1
  323. handlers.append(h)
  324. opener.add_handler(h)
  325. return handlers
  326. def build_test_opener(*handler_instances):
  327. opener = OpenerDirector()
  328. for h in handler_instances:
  329. opener.add_handler(h)
  330. return opener
  331. class MockHTTPHandler(urllib2.BaseHandler):
  332. # useful for testing redirections and auth
  333. # sends supplied headers and code as first response
  334. # sends 200 OK as second response
  335. def __init__(self, code, headers):
  336. self.code = code
  337. self.headers = headers
  338. self.reset()
  339. def reset(self):
  340. self._count = 0
  341. self.requests = []
  342. def http_open(self, req):
  343. import mimetools, httplib, copy
  344. from StringIO import StringIO
  345. self.requests.append(copy.deepcopy(req))
  346. if self._count == 0:
  347. self._count = self._count + 1
  348. name = httplib.responses[self.code]
  349. msg = mimetools.Message(StringIO(self.headers))
  350. return self.parent.error(
  351. "http", req, MockFile(), self.code, name, msg)
  352. else:
  353. self.req = req
  354. msg = mimetools.Message(StringIO("\r\n\r\n"))
  355. return MockResponse(200, "OK", msg, "", req.get_full_url())
  356. class MockHTTPSHandler(urllib2.AbstractHTTPHandler):
  357. # Useful for testing the Proxy-Authorization request by verifying the
  358. # properties of httpcon
  359. def __init__(self):
  360. urllib2.AbstractHTTPHandler.__init__(self)
  361. self.httpconn = MockHTTPClass()
  362. def https_open(self, req):
  363. return self.do_open(self.httpconn, req)
  364. class MockPasswordManager:
  365. def add_password(self, realm, uri, user, password):
  366. self.realm = realm
  367. self.url = uri
  368. self.user = user
  369. self.password = password
  370. def find_user_password(self, realm, authuri):
  371. self.target_realm = realm
  372. self.target_url = authuri
  373. return self.user, self.password
  374. class OpenerDirectorTests(unittest.TestCase):
  375. def test_add_non_handler(self):
  376. class NonHandler(object):
  377. pass
  378. self.assertRaises(TypeError,
  379. OpenerDirector().add_handler, NonHandler())
  380. def test_badly_named_methods(self):
  381. # test work-around for three methods that accidentally follow the
  382. # naming conventions for handler methods
  383. # (*_open() / *_request() / *_response())
  384. # These used to call the accidentally-named methods, causing a
  385. # TypeError in real code; here, returning self from these mock
  386. # methods would either cause no exception, or AttributeError.
  387. from urllib2 import URLError
  388. o = OpenerDirector()
  389. meth_spec = [
  390. [("do_open", "return self"), ("proxy_open", "return self")],
  391. [("redirect_request", "return self")],
  392. ]
  393. handlers = add_ordered_mock_handlers(o, meth_spec)
  394. o.add_handler(urllib2.UnknownHandler())
  395. for scheme in "do", "proxy", "redirect":
  396. self.assertRaises(URLError, o.open, scheme+"://example.com/")
  397. def test_handled(self):
  398. # handler returning non-None means no more handlers will be called
  399. o = OpenerDirector()
  400. meth_spec = [
  401. ["http_open", "ftp_open", "http_error_302"],
  402. ["ftp_open"],
  403. [("http_open", "return self")],
  404. [("http_open", "return self")],
  405. ]
  406. handlers = add_ordered_mock_handlers(o, meth_spec)
  407. req = Request("http://example.com/")
  408. r = o.open(req)
  409. # Second .http_open() gets called, third doesn't, since second returned
  410. # non-None. Handlers without .http_open() never get any methods called
  411. # on them.
  412. # In fact, second mock handler defining .http_open() returns self
  413. # (instead of response), which becomes the OpenerDirector's return
  414. # value.
  415. self.assertEqual(r, handlers[2])
  416. calls = [(handlers[0], "http_open"), (handlers[2], "http_open")]
  417. for expected, got in zip(calls, o.calls):
  418. handler, name, args, kwds = got
  419. self.assertEqual((handler, name), expected)
  420. self.assertEqual(args, (req,))
  421. def test_handler_order(self):
  422. o = OpenerDirector()
  423. handlers = []
  424. for meths, handler_order in [
  425. ([("http_open", "return self")], 500),
  426. (["http_open"], 0),
  427. ]:
  428. class MockHandlerSubclass(MockHandler): pass
  429. h = MockHandlerSubclass(meths)
  430. h.handler_order = handler_order
  431. handlers.append(h)
  432. o.add_handler(h)
  433. r = o.open("http://example.com/")
  434. # handlers called in reverse order, thanks to their sort order
  435. self.assertEqual(o.calls[0][0], handlers[1])
  436. self.assertEqual(o.calls[1][0], handlers[0])
  437. def test_raise(self):
  438. # raising URLError stops processing of request
  439. o = OpenerDirector()
  440. meth_spec = [
  441. [("http_open", "raise")],
  442. [("http_open", "return self")],
  443. ]
  444. handlers = add_ordered_mock_handlers(o, meth_spec)
  445. req = Request("http://example.com/")
  446. self.assertRaises(urllib2.URLError, o.open, req)
  447. self.assertEqual(o.calls, [(handlers[0], "http_open", (req,), {})])
  448. ## def test_error(self):
  449. ## # XXX this doesn't actually seem to be used in standard library,
  450. ## # but should really be tested anyway...
  451. def test_http_error(self):
  452. # XXX http_error_default
  453. # http errors are a special case
  454. o = OpenerDirector()
  455. meth_spec = [
  456. [("http_open", "error 302")],
  457. [("http_error_400", "raise"), "http_open"],
  458. [("http_error_302", "return response"), "http_error_303",
  459. "http_error"],
  460. [("http_error_302")],
  461. ]
  462. handlers = add_ordered_mock_handlers(o, meth_spec)
  463. class Unknown:
  464. def __eq__(self, other): return True
  465. req = Request("http://example.com/")
  466. r = o.open(req)
  467. assert len(o.calls) == 2
  468. calls = [(handlers[0], "http_open", (req,)),
  469. (handlers[2], "http_error_302",
  470. (req, Unknown(), 302, "", {}))]
  471. for expected, got in zip(calls, o.calls):
  472. handler, method_name, args = expected
  473. self.assertEqual((handler, method_name), got[:2])
  474. self.assertEqual(args, got[2])
  475. def test_processors(self):
  476. # *_request / *_response methods get called appropriately
  477. o = OpenerDirector()
  478. meth_spec = [
  479. [("http_request", "return request"),
  480. ("http_response", "return response")],
  481. [("http_request", "return request"),
  482. ("http_response", "return response")],
  483. ]
  484. handlers = add_ordered_mock_handlers(o, meth_spec)
  485. req = Request("http://example.com/")
  486. r = o.open(req)
  487. # processor methods are called on *all* handlers that define them,
  488. # not just the first handler that handles the request
  489. calls = [
  490. (handlers[0], "http_request"), (handlers[1], "http_request"),
  491. (handlers[0], "http_response"), (handlers[1], "http_response")]
  492. for i, (handler, name, args, kwds) in enumerate(o.calls):
  493. if i < 2:
  494. # *_request
  495. self.assertEqual((handler, name), calls[i])
  496. self.assertEqual(len(args), 1)
  497. self.assertIsInstance(args[0], Request)
  498. else:
  499. # *_response
  500. self.assertEqual((handler, name), calls[i])
  501. self.assertEqual(len(args), 2)
  502. self.assertIsInstance(args[0], Request)
  503. # response from opener.open is None, because there's no
  504. # handler that defines http_open to handle it
  505. self.assertTrue(args[1] is None or
  506. isinstance(args[1], MockResponse))
  507. def sanepathname2url(path):
  508. import urllib
  509. urlpath = urllib.pathname2url(path)
  510. if os.name == "nt" and urlpath.startswith("///"):
  511. urlpath = urlpath[2:]
  512. # XXX don't ask me about the mac...
  513. return urlpath
  514. class HandlerTests(unittest.TestCase):
  515. def test_ftp(self):
  516. class MockFTPWrapper:
  517. def __init__(self, data): self.data = data
  518. def retrfile(self, filename, filetype):
  519. self.filename, self.filetype = filename, filetype
  520. return StringIO.StringIO(self.data), len(self.data)
  521. class NullFTPHandler(urllib2.FTPHandler):
  522. def __init__(self, data): self.data = data
  523. def connect_ftp(self, user, passwd, host, port, dirs,
  524. timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
  525. self.user, self.passwd = user, passwd
  526. self.host, self.port = host, port
  527. self.dirs = dirs
  528. self.ftpwrapper = MockFTPWrapper(self.data)
  529. return self.ftpwrapper
  530. import ftplib
  531. data = "rheum rhaponicum"
  532. h = NullFTPHandler(data)
  533. o = h.parent = MockOpener()
  534. for url, host, port, user, passwd, type_, dirs, filename, mimetype in [
  535. ("ftp://localhost/foo/bar/baz.html",
  536. "localhost", ftplib.FTP_PORT, "", "", "I",
  537. ["foo", "bar"], "baz.html", "text/html"),
  538. ("ftp://parrot@localhost/foo/bar/baz.html",
  539. "localhost", ftplib.FTP_PORT, "parrot", "", "I",
  540. ["foo", "bar"], "baz.html", "text/html"),
  541. ("ftp://%25parrot@localhost/foo/bar/baz.html",
  542. "localhost", ftplib.FTP_PORT, "%parrot", "", "I",
  543. ["foo", "bar"], "baz.html", "text/html"),
  544. ("ftp://%2542parrot@localhost/foo/bar/baz.html",
  545. "localhost", ftplib.FTP_PORT, "%42parrot", "", "I",
  546. ["foo", "bar"], "baz.html", "text/html"),
  547. ("ftp://localhost:80/foo/bar/",
  548. "localhost", 80, "", "", "D",
  549. ["foo", "bar"], "", None),
  550. ("ftp://localhost/baz.gif;type=a",
  551. "localhost", ftplib.FTP_PORT, "", "", "A",
  552. [], "baz.gif", None), # XXX really this should guess image/gif
  553. ]:
  554. req = Request(url)
  555. req.timeout = None
  556. r = h.ftp_open(req)
  557. # ftp authentication not yet implemented by FTPHandler
  558. self.assertEqual(h.user, user)
  559. self.assertEqual(h.passwd, passwd)
  560. self.assertEqual(h.host, socket.gethostbyname(host))
  561. self.assertEqual(h.port, port)
  562. self.assertEqual(h.dirs, dirs)
  563. self.assertEqual(h.ftpwrapper.filename, filename)
  564. self.assertEqual(h.ftpwrapper.filetype, type_)
  565. headers = r.info()
  566. self.assertEqual(headers.get("Content-type"), mimetype)
  567. self.assertEqual(int(headers["Content-length"]), len(data))
  568. def test_file(self):
  569. import rfc822, socket
  570. h = urllib2.FileHandler()
  571. o = h.parent = MockOpener()
  572. TESTFN = test_support.TESTFN
  573. urlpath = sanepathname2url(os.path.abspath(TESTFN))
  574. towrite = "hello, world\n"
  575. urls = [
  576. "file://localhost%s" % urlpath,
  577. "file://%s" % urlpath,
  578. "file://%s%s" % (socket.gethostbyname('localhost'), urlpath),
  579. ]
  580. try:
  581. localaddr = socket.gethostbyname(socket.gethostname())
  582. except socket.gaierror:
  583. localaddr = ''
  584. if localaddr:
  585. urls.append("file://%s%s" % (localaddr, urlpath))
  586. for url in urls:
  587. f = open(TESTFN, "wb")
  588. try:
  589. try:
  590. f.write(towrite)
  591. finally:
  592. f.close()
  593. r = h.file_open(Request(url))
  594. try:
  595. data = r.read()
  596. headers = r.info()
  597. respurl = r.geturl()
  598. finally:
  599. r.close()
  600. stats = os.stat(TESTFN)
  601. modified = rfc822.formatdate(stats.st_mtime)
  602. finally:
  603. os.remove(TESTFN)
  604. self.assertEqual(data, towrite)
  605. self.assertEqual(headers["Content-type"], "text/plain")
  606. self.assertEqual(headers["Content-length"], "13")
  607. self.assertEqual(headers["Last-modified"], modified)
  608. self.assertEqual(respurl, url)
  609. for url in [
  610. "file://localhost:80%s" % urlpath,
  611. "file:///file_does_not_exist.txt",
  612. "file://%s:80%s/%s" % (socket.gethostbyname('localhost'),
  613. os.getcwd(), TESTFN),
  614. "file://somerandomhost.ontheinternet.com%s/%s" %
  615. (os.getcwd(), TESTFN),
  616. ]:
  617. try:
  618. f = open(TESTFN, "wb")
  619. try:
  620. f.write(towrite)
  621. finally:
  622. f.close()
  623. self.assertRaises(urllib2.URLError,
  624. h.file_open, Request(url))
  625. finally:
  626. os.remove(TESTFN)
  627. h = urllib2.FileHandler()
  628. o = h.parent = MockOpener()
  629. # XXXX why does // mean ftp (and /// mean not ftp!), and where
  630. # is file: scheme specified? I think this is really a bug, and
  631. # what was intended was to distinguish between URLs like:
  632. # file:/blah.txt (a file)
  633. # file://localhost/blah.txt (a file)
  634. # file:///blah.txt (a file)
  635. # file://ftp.example.com/blah.txt (an ftp URL)
  636. for url, ftp in [
  637. ("file://ftp.example.com//foo.txt", True),
  638. ("file://ftp.example.com///foo.txt", False),
  639. # XXXX bug: fails with OSError, should be URLError
  640. ("file://ftp.example.com/foo.txt", False),
  641. ("file://somehost//foo/something.txt", True),
  642. ("file://localhost//foo/something.txt", False),
  643. ]:
  644. req = Request(url)
  645. try:
  646. h.file_open(req)
  647. # XXXX remove OSError when bug fixed
  648. except (urllib2.URLError, OSError):
  649. self.assertTrue(not ftp)
  650. else:
  651. self.assertTrue(o.req is req)
  652. self.assertEqual(req.type, "ftp")
  653. self.assertEqual(req.type == "ftp", ftp)
  654. def test_http(self):
  655. h = urllib2.AbstractHTTPHandler()
  656. o = h.parent = MockOpener()
  657. url = "http://example.com/"
  658. for method, data in [("GET", None), ("POST", "blah")]:
  659. req = Request(url, data, {"Foo": "bar"})
  660. req.timeout = None
  661. req.add_unredirected_header("Spam", "eggs")
  662. http = MockHTTPClass()
  663. r = h.do_open(http, req)
  664. # result attributes
  665. r.read; r.readline # wrapped MockFile methods
  666. r.info; r.geturl # addinfourl methods
  667. r.code, r.msg == 200, "OK" # added from MockHTTPClass.getreply()
  668. hdrs = r.info()
  669. hdrs.get; hdrs.has_key # r.info() gives dict from .getreply()
  670. self.assertEqual(r.geturl(), url)
  671. self.assertEqual(http.host, "example.com")
  672. self.assertEqual(http.level, 0)
  673. self.assertEqual(http.method, method)
  674. self.assertEqual(http.selector, "/")
  675. self.assertEqual(http.req_headers,
  676. [("Connection", "close"),
  677. ("Foo", "bar"), ("Spam", "eggs")])
  678. self.assertEqual(http.data, data)
  679. # check socket.error converted to URLError
  680. http.raise_on_endheaders = True
  681. self.assertRaises(urllib2.URLError, h.do_open, http, req)
  682. # check adding of standard headers
  683. o.addheaders = [("Spam", "eggs")]
  684. for data in "", None: # POST, GET
  685. req = Request("http://example.com/", data)
  686. r = MockResponse(200, "OK", {}, "")
  687. newreq = h.do_request_(req)
  688. if data is None: # GET
  689. self.assertNotIn("Content-length", req.unredirected_hdrs)
  690. self.assertNotIn("Content-type", req.unredirected_hdrs)
  691. else: # POST
  692. self.assertEqual(req.unredirected_hdrs["Content-length"], "0")
  693. self.assertEqual(req.unredirected_hdrs["Content-type"],
  694. "application/x-www-form-urlencoded")
  695. # XXX the details of Host could be better tested
  696. self.assertEqual(req.unredirected_hdrs["Host"], "example.com")
  697. self.assertEqual(req.unredirected_hdrs["Spam"], "eggs")
  698. # don't clobber existing headers
  699. req.add_unredirected_header("Content-length", "foo")
  700. req.add_unredirected_header("Content-type", "bar")
  701. req.add_unredirected_header("Host", "baz")
  702. req.add_unredirected_header("Spam", "foo")
  703. newreq = h.do_request_(req)
  704. self.assertEqual(req.unredirected_hdrs["Content-length"], "foo")
  705. self.assertEqual(req.unredirected_hdrs["Content-type"], "bar")
  706. self.assertEqual(req.unredirected_hdrs["Host"], "baz")
  707. self.assertEqual(req.unredirected_hdrs["Spam"], "foo")
  708. def test_http_doubleslash(self):
  709. # Checks that the presence of an unnecessary double slash in a url doesn't break anything
  710. # Previously, a double slash directly after the host could cause incorrect parsing of the url
  711. h = urllib2.AbstractHTTPHandler()
  712. o = h.parent = MockOpener()
  713. data = ""
  714. ds_urls = [
  715. "http://example.com/foo/bar/baz.html",
  716. "http://example.com//foo/bar/baz.html",
  717. "http://example.com/foo//bar/baz.html",
  718. "http://example.com/foo/bar//baz.html",
  719. ]
  720. for ds_url in ds_urls:
  721. ds_req = Request(ds_url, data)
  722. # Check whether host is determined correctly if there is no proxy
  723. np_ds_req = h.do_request_(ds_req)
  724. self.assertEqual(np_ds_req.unredirected_hdrs["Host"],"example.com")
  725. # Check whether host is determined correctly if there is a proxy
  726. ds_req.set_proxy("someproxy:3128",None)
  727. p_ds_req = h.do_request_(ds_req)
  728. self.assertEqual(p_ds_req.unredirected_hdrs["Host"],"example.com")
  729. def test_fixpath_in_weirdurls(self):
  730. # Issue4493: urllib2 to supply '/' when to urls where path does not
  731. # start with'/'
  732. h = urllib2.AbstractHTTPHandler()
  733. o = h.parent = MockOpener()
  734. weird_url = 'http://www.python.org?getspam'
  735. req = Request(weird_url)
  736. newreq = h.do_request_(req)
  737. self.assertEqual(newreq.get_host(),'www.python.org')
  738. self.assertEqual(newreq.get_selector(),'/?getspam')
  739. url_without_path = 'http://www.python.org'
  740. req = Request(url_without_path)
  741. newreq = h.do_request_(req)
  742. self.assertEqual(newreq.get_host(),'www.python.org')
  743. self.assertEqual(newreq.get_selector(),'')
  744. def test_errors(self):
  745. h = urllib2.HTTPErrorProcessor()
  746. o = h.parent = MockOpener()
  747. url = "http://example.com/"
  748. req = Request(url)
  749. # all 2xx are passed through
  750. r = MockResponse(200, "OK", {}, "", url)
  751. newr = h.http_response(req, r)
  752. self.assertTrue(r is newr)
  753. self.assertTrue(not hasattr(o, "proto")) # o.error not called
  754. r = MockResponse(202, "Accepted", {}, "", url)
  755. newr = h.http_response(req, r)
  756. self.assertTrue(r is newr)
  757. self.assertTrue(not hasattr(o, "proto")) # o.error not called
  758. r = MockResponse(206, "Partial content", {}, "", url)
  759. newr = h.http_response(req, r)
  760. self.assertTrue(r is newr)
  761. self.assertTrue(not hasattr(o, "proto")) # o.error not called
  762. # anything else calls o.error (and MockOpener returns None, here)
  763. r = MockResponse(502, "Bad gateway", {}, "", url)
  764. self.assertTrue(h.http_response(req, r) is None)
  765. self.assertEqual(o.proto, "http") # o.error called
  766. self.assertEqual(o.args, (req, r, 502, "Bad gateway", {}))
  767. def test_cookies(self):
  768. cj = MockCookieJar()
  769. h = urllib2.HTTPCookieProcessor(cj)
  770. o = h.parent = MockOpener()
  771. req = Request("http://example.com/")
  772. r = MockResponse(200, "OK", {}, "")
  773. newreq = h.http_request(req)
  774. self.assertTrue(cj.ach_req is req is newreq)
  775. self.assertEqual(req.get_origin_req_host(), "example.com")
  776. self.assertTrue(not req.is_unverifiable())
  777. newr = h.http_response(req, r)
  778. self.assertTrue(cj.ec_req is req)
  779. self.assertTrue(cj.ec_r is r is newr)
  780. def test_redirect(self):
  781. from_url = "http://example.com/a.html"
  782. to_url = "http://example.com/b.html"
  783. h = urllib2.HTTPRedirectHandler()
  784. o = h.parent = MockOpener()
  785. # ordinary redirect behaviour
  786. for code in 301, 302, 303, 307:
  787. for data in None, "blah\nblah\n":
  788. method = getattr(h, "http_error_%s" % code)
  789. req = Request(from_url, data)
  790. req.add_header("Nonsense", "viking=withhold")
  791. req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
  792. if data is not None:
  793. req.add_header("Content-Length", str(len(data)))
  794. req.add_unredirected_header("Spam", "spam")
  795. try:
  796. method(req, MockFile(), code, "Blah",
  797. MockHeaders({"location": to_url}))
  798. except urllib2.HTTPError:
  799. # 307 in response to POST requires user OK
  800. self.assertTrue(code == 307 and data is not None)
  801. self.assertEqual(o.req.get_full_url(), to_url)
  802. try:
  803. self.assertEqual(o.req.get_method(), "GET")
  804. except AttributeError:
  805. self.assertTrue(not o.req.has_data())
  806. # now it's a GET, there should not be headers regarding content
  807. # (possibly dragged from before being a POST)
  808. headers = [x.lower() for x in o.req.headers]
  809. self.assertNotIn("content-length", headers)
  810. self.assertNotIn("content-type", headers)
  811. self.assertEqual(o.req.headers["Nonsense"],
  812. "viking=withhold")
  813. self.assertNotIn("Spam", o.req.headers)
  814. self.assertNotIn("Spam", o.req.unredirected_hdrs)
  815. # loop detection
  816. req = Request(from_url)
  817. req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
  818. def redirect(h, req, url=to_url):
  819. h.http_error_302(req, MockFile(), 302, "Blah",
  820. MockHeaders({"location": url}))
  821. # Note that the *original* request shares the same record of
  822. # redirections with the sub-requests caused by the redirections.
  823. # detect infinite loop redirect of a URL to itself
  824. req = Request(from_url, origin_req_host="example.com")
  825. count = 0
  826. req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
  827. try:
  828. while 1:
  829. redirect(h, req, "http://example.com/")
  830. count = count + 1
  831. except urllib2.HTTPError:
  832. # don't stop until max_repeats, because cookies may introduce state
  833. self.assertEqual(count, urllib2.HTTPRedirectHandler.max_repeats)
  834. # detect endless non-repeating chain of redirects
  835. req = Request(from_url, origin_req_host="example.com")
  836. count = 0
  837. req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
  838. try:
  839. while 1:
  840. redirect(h, req, "http://example.com/%d" % count)
  841. count = count + 1
  842. except urllib2.HTTPError:
  843. self.assertEqual(count,
  844. urllib2.HTTPRedirectHandler.max_redirections)
  845. def test_invalid_redirect(self):
  846. from_url = "http://example.com/a.html"
  847. valid_schemes = ['http', 'https', 'ftp']
  848. invalid_schemes = ['file', 'imap', 'ldap']
  849. schemeless_url = "example.com/b.html"
  850. h = urllib2.HTTPRedirectHandler()
  851. o = h.parent = MockOpener()
  852. req = Request(from_url)
  853. req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
  854. for scheme in invalid_schemes:
  855. invalid_url = scheme + '://' + schemeless_url
  856. self.assertRaises(urllib2.HTTPError, h.http_error_302,
  857. req, MockFile(), 302, "Security Loophole",
  858. MockHeaders({"location": invalid_url}))
  859. for scheme in valid_schemes:
  860. valid_url = scheme + '://' + schemeless_url
  861. h.http_error_302(req, MockFile(), 302, "That's fine",
  862. MockHeaders({"location": valid_url}))
  863. self.assertEqual(o.req.get_full_url(), valid_url)
  864. def test_cookie_redirect(self):
  865. # cookies shouldn't leak into redirected requests
  866. from cookielib import CookieJar
  867. from test.test_cookielib import interact_netscape
  868. cj = CookieJar()
  869. interact_netscape(cj, "http://www.example.com/", "spam=eggs")
  870. hh = MockHTTPHandler(302, "Location: http://www.cracker.com/\r\n\r\n")
  871. hdeh = urllib2.HTTPDefaultErrorHandler()
  872. hrh = urllib2.HTTPRedirectHandler()
  873. cp = urllib2.HTTPCookieProcessor(cj)
  874. o = build_test_opener(hh, hdeh, hrh, cp)
  875. o.open("http://www.example.com/")
  876. self.assertTrue(not hh.req.has_header("Cookie"))
  877. def test_redirect_fragment(self):
  878. redirected_url = 'http://www.example.com/index.html#OK\r\n\r\n'
  879. hh = MockHTTPHandler(302, 'Location: ' + redirected_url)
  880. hdeh = urllib2.HTTPDefaultErrorHandler()
  881. hrh = urllib2.HTTPRedirectHandler()
  882. o = build_test_opener(hh, hdeh, hrh)
  883. fp = o.open('http://www.example.com')
  884. self.assertEqual(fp.geturl(), redirected_url.strip())
  885. def test_proxy(self):
  886. o = OpenerDirector()
  887. ph = urllib2.ProxyHandler(dict(http="proxy.example.com:3128"))
  888. o.add_handler(ph)
  889. meth_spec = [
  890. [("http_open", "return response")]
  891. ]
  892. handlers = add_ordered_mock_handlers(o, meth_spec)
  893. req = Request("http://acme.example.com/")
  894. self.assertEqual(req.get_host(), "acme.example.com")
  895. r = o.open(req)
  896. self.assertEqual(req.get_host(), "proxy.example.com:3128")
  897. self.assertEqual([(handlers[0], "http_open")],
  898. [tup[0:2] for tup in o.calls])
  899. def test_proxy_no_proxy(self):
  900. os.environ['no_proxy'] = 'python.org'
  901. o = OpenerDirector()
  902. ph = urllib2.ProxyHandler(dict(http="proxy.example.com"))
  903. o.add_handler(ph)
  904. req = Request("http://www.perl.org/")
  905. self.assertEqual(req.get_host(), "www.perl.org")
  906. r = o.open(req)
  907. self.assertEqual(req.get_host(), "proxy.example.com")
  908. req = Request("http://www.python.org")
  909. self.assertEqual(req.get_host(), "www.python.org")
  910. r = o.open(req)
  911. self.assertEqual(req.get_host(), "www.python.org")
  912. del os.environ['no_proxy']
  913. def test_proxy_https(self):
  914. o = OpenerDirector()
  915. ph = urllib2.ProxyHandler(dict(https='proxy.example.com:3128'))
  916. o.add_handler(ph)
  917. meth_spec = [
  918. [("https_open","return response")]
  919. ]
  920. handlers = add_ordered_mock_handlers(o, meth_spec)
  921. req = Request("https://www.example.com/")
  922. self.assertEqual(req.get_host(), "www.example.com")
  923. r = o.open(req)
  924. self.assertEqual(req.get_host(), "proxy.example.com:3128")
  925. self.assertEqual([(handlers[0], "https_open")],
  926. [tup[0:2] for tup in o.calls])
  927. def test_proxy_https_proxy_authorization(self):
  928. o = OpenerDirector()
  929. ph = urllib2.ProxyHandler(dict(https='proxy.example.com:3128'))
  930. o.add_handler(ph)
  931. https_handler = MockHTTPSHandler()
  932. o.add_handler(https_handler)
  933. req = Request("https://www.example.com/")
  934. req.add_header("Proxy-Authorization","FooBar")
  935. req.add_header("User-Agent","Grail")
  936. self.assertEqual(req.get_host(), "www.example.com")
  937. self.assertIsNone(req._tunnel_host)
  938. r = o.open(req)
  939. # Verify Proxy-Authorization gets tunneled to request.
  940. # httpsconn req_headers do not have the Proxy-Authorization header but
  941. # the req will have.
  942. self.assertNotIn(("Proxy-Authorization","FooBar"),
  943. https_handler.httpconn.req_headers)
  944. self.assertIn(("User-Agent","Grail"),
  945. https_handler.httpconn.req_headers)
  946. self.assertIsNotNone(req._tunnel_host)
  947. self.assertEqual(req.get_host(), "proxy.example.com:3128")
  948. self.assertEqual(req.get_header("Proxy-authorization"),"FooBar")
  949. def test_basic_auth(self, quote_char='"'):
  950. opener = OpenerDirector()
  951. password_manager = MockPasswordManager()
  952. auth_handler = urllib2.HTTPBasicAuthHandler(password_manager)
  953. realm = "ACME Widget Store"
  954. http_handler = MockHTTPHandler(
  955. 401, 'WWW-Authenticate: Basic realm=%s%s%s\r\n\r\n' %
  956. (quote_char, realm, quote_char) )
  957. opener.add_handler(auth_handler)
  958. opener.add_handler(http_handler)
  959. self._test_basic_auth(opener, auth_handler, "Authorization",
  960. realm, http_handler, password_manager,
  961. "http://acme.example.com/protected",
  962. "http://acme.example.com/protected",
  963. )
  964. def test_basic_auth_with_single_quoted_realm(self):
  965. self.test_basic_auth(quote_char="'")
  966. def test_proxy_basic_auth(self):
  967. opener = OpenerDirector()
  968. ph = urllib2.ProxyHandler(dict(http="proxy.example.com:3128"))
  969. opener.add_handler(ph)
  970. password_manager = MockPasswordManager()
  971. auth_handler = urllib2.ProxyBasicAuthHandler(password_manager)
  972. realm = "ACME Networks"
  973. http_handler = MockHTTPHandler(
  974. 407, 'Proxy-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
  975. opener.add_handler(auth_handler)
  976. opener.add_handler(http_handler)
  977. self._test_basic_auth(opener, auth_handler, "Proxy-authorization",
  978. realm, http_handler, password_manager,
  979. "http://acme.example.com:3128/protected",
  980. "proxy.example.com:3128",
  981. )
  982. def test_basic_and_digest_auth_handlers(self):
  983. # HTTPDigestAuthHandler threw an exception if it couldn't handle a 40*
  984. # response (http://python.org/sf/1479302), where it should instead
  985. # return None to allow another handler (especially
  986. # HTTPBasicAuthHandler) to handle the response.
  987. # Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must
  988. # try digest first (since it's the strongest auth scheme), so we record
  989. # order of calls here to check digest comes first:
  990. class RecordingOpenerDirector(OpenerDirector):
  991. def __init__(self):
  992. OpenerDirector.__init__(self)
  993. self.recorded = []
  994. def record(self, info):
  995. self.recorded.append(info)
  996. class TestDigestAuthHandler(urllib2.HTTPDigestAuthHandler):
  997. def http_error_401(self, *args, **kwds):
  998. self.parent.record("digest")
  999. urllib2.HTTPDigestAuthHandler.http_error_401(self,
  1000. *args, **kwds)
  1001. class TestBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
  1002. def http_error_401(self, *args, **kwds):
  1003. self.parent.record("basic")
  1004. urllib2.HTTPBasicAuthHandler.http_error_401(self,
  1005. *args, **kwds)
  1006. opener = RecordingOpenerDirector()
  1007. password_manager = MockPasswordManager()
  1008. digest_handler = TestDigestAuthHandler(password_manager)
  1009. basic_handler = TestBasicAuthHandler(password_manager)
  1010. realm = "ACME Networks"
  1011. http_handler = MockHTTPHandler(
  1012. 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
  1013. opener.add_handler(basic_handler)
  1014. opener.add_handler(digest_handler)
  1015. opener.add_handler(http_handler)
  1016. # check basic auth isn't blocked by digest handler failing
  1017. self._test_basic_auth(opener, basic_handler, "Authorization",
  1018. realm, http_handler, password_manager,
  1019. "http://acme.example.com/protected",
  1020. "http://acme.example.com/protected",
  1021. )
  1022. # check digest was tried before basic (twice, because
  1023. # _test_basic_auth called .open() twice)
  1024. self.assertEqual(opener.recorded, ["digest", "basic"]*2)
  1025. def _test_basic_auth(self, opener, auth_handler, auth_header,
  1026. realm, http_handler, password_manager,
  1027. request_url, protected_url):
  1028. import base64
  1029. user, password = "wile", "coyote"
  1030. # .add_password() fed through to password manager
  1031. auth_handler.add_password(realm, request_url, user, password)
  1032. self.assertEqual(realm, password_manager.realm)
  1033. self.assertEqual(request_url, password_manager.url)
  1034. self.assertEqual(user, password_manager.user)
  1035. self.assertEqual(password, password_manager.password)
  1036. r = opener.open(request_url)
  1037. # should have asked the password manager for the username/password
  1038. self.assertEqual(password_manager.target_realm, realm)
  1039. self.assertEqual(password_manager.target_url, protected_url)
  1040. # expect one request without authorization, then one with
  1041. self.assertEqual(len(http_handler.requests), 2)
  1042. self.assertFalse(http_handler.requests[0].has_header(auth_header))
  1043. userpass = '%s:%s' % (user, password)
  1044. auth_hdr_value = 'Basic '+base64.encodestring(userpass).strip()
  1045. self.assertEqual(http_handler.requests[1].get_header(auth_header),
  1046. auth_hdr_value)
  1047. self.assertEqual(http_handler.requests[1].unredirected_hdrs[auth_header],
  1048. auth_hdr_value)
  1049. # if the password manager can't find a password, the handler won't
  1050. # handle the HTTP auth error
  1051. password_manager.user = password_manager.password = None
  1052. http_handler.reset()
  1053. r = opener.open(request_url)
  1054. self.assertEqual(len(http_handler.requests), 1)
  1055. self.assertFalse(http_handler.requests[0].has_header(auth_header))
  1056. class MiscTests(unittest.TestCase):
  1057. def test_build_opener(self):
  1058. class MyHTTPHandler(urllib2.HTTPHandler): pass
  1059. class FooHandler(urllib2.BaseHandler):
  1060. def foo_open(self): pass
  1061. class BarHandler(urllib2.BaseHandler):
  1062. def bar_open(self): pass
  1063. build_opener = urllib2.build_opener
  1064. o = build_opener(FooHandler, BarHandler)
  1065. self.opener_has_handler(o, FooHandler)
  1066. self.opener_has_handler(o, BarHandler)
  1067. # can take a mix of classes and instances
  1068. o = build_opener(FooHandler, BarHandler())
  1069. self.opener_has_handler(o, FooHandler)
  1070. self.opener_has_handler(o, BarHandler)
  1071. # subclasses of default handlers override default handlers
  1072. o = build_opener(MyHTTPHandler)
  1073. self.opener_has_handler(o, MyHTTPHandler)
  1074. # a particular case of overriding: default handlers can be passed
  1075. # in explicitly
  1076. o = build_opener()
  1077. self.opener_has_handler(o, urllib2.HTTPHandler)
  1078. o = build_opener(urllib2.HTTPHandler)
  1079. self.opener_has_handler(o, urllib2.HTTPHandler)
  1080. o = build_opener(urllib2.HTTPHandler())
  1081. self.opener_has_handler(o, urllib2.HTTPHandler)
  1082. # Issue2670: multiple handlers sharing the same base class
  1083. class MyOtherHTTPHandler(urllib2.HTTPHandler): pass
  1084. o = build_opener(MyHTTPHandler, MyOtherHTTPHandler)
  1085. self.opener_has_handler(o, MyHTTPHandler)
  1086. self.opener_has_handler(o, MyOtherHTTPHandler)
  1087. def opener_has_handler(self, opener, handler_class):
  1088. for h in opener.handlers:
  1089. if h.__class__ == handler_class:
  1090. break
  1091. else:
  1092. self.assertTrue(False)
  1093. class RequestTests(unittest.TestCase):
  1094. def setUp(self):
  1095. self.get = urllib2.Request("http://www.python.org/~jeremy/")
  1096. self.post = urllib2.Request("http://www.python.org/~jeremy/",
  1097. "data",
  1098. headers={"X-Test": "test"})
  1099. def test_method(self):
  1100. self.assertEqual("POST", self.post.get_method())
  1101. self.assertEqual("GET", self.get.get_method())
  1102. def test_add_data(self):
  1103. self.assertTrue(not self.get.has_data())
  1104. self.assertEqual("GET", self.get.get_method())
  1105. self.get.add_data("spam")
  1106. self.assertTrue(self.get.has_data())
  1107. self.assertEqual("POST", self.get.get_method())
  1108. def test_get_full_url(self):
  1109. self.assertEqual("http://www.python.org/~jeremy/",
  1110. self.get.get_full_url())
  1111. def test_selector(self):
  1112. self.assertEqual("/~jeremy/", self.get.get_selector())
  1113. req = urllib2.Request("http://www.python.org/")
  1114. self.assertEqual("/", req.get_selector())
  1115. def test_get_type(self):
  1116. self.assertEqual("http", self.get.get_type())
  1117. def test_get_host(self):
  1118. self.assertEqual("www.python.org", self.get.get_host())
  1119. def test_get_host_unquote(self):
  1120. req = urllib2.Request("http://www.%70ython.org/")
  1121. self.assertEqual("www.python.org", req.get_host())
  1122. def test_proxy(self):
  1123. self.assertTrue(not self.get.has_proxy())
  1124. self.get.set_proxy("www.perl.org", "http")
  1125. self.assertTrue(self.get.has_proxy())
  1126. self.assertEqual("www.python.org", self.get.get_origin_req_host())
  1127. self.assertEqual("www.perl.org", self.get.get_host())
  1128. def test_wrapped_url(self):
  1129. req = Request("<URL:http://www.python.org>")
  1130. self.assertEqual("www.python.org", req.get_host())
  1131. def test_url_fragment(self):
  1132. req = Request("http://www.python.org/?qs=query#fragment=true")
  1133. self.assertEqual("/?qs=query", req.get_selector())
  1134. req = Request("http://www.python.org/#fun=true")
  1135. self.assertEqual("/", req.get_selector())
  1136. # Issue 11703: geturl() omits fragment in the original URL.
  1137. url = 'http://docs.python.org/library/urllib2.html#OK'
  1138. req = Request(url)
  1139. self.assertEqual(req.get_full_url(), url)
  1140. def test_main(verbose=None):
  1141. from test import test_urllib2
  1142. test_support.run_doctest(test_urllib2, verbose)
  1143. test_support.run_doctest(urllib2, verbose)
  1144. tests = (TrivialTests,
  1145. OpenerDirectorTests,
  1146. HandlerTests,
  1147. MiscTests,
  1148. RequestTests)
  1149. test_support.run_unittest(*tests)
  1150. if __name__ == "__main__":
  1151. test_main(verbose=True)