/Lib/test/test_urllib2.py

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