blob: 9d9260ab3dbff97242bc9d27184f1039b82dcc88 [file] [log] [blame]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002from test import support
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00003
Christian Heimes05e8be12008-02-23 18:30:17 +00004import os
Guido van Rossum34d19282007-08-09 01:03:29 +00005import io
Georg Brandlf78e02b2008-06-10 17:40:04 +00006import socket
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00007import array
Senthil Kumaran4de00a22011-05-11 21:17:57 +08008import sys
Jeremy Hyltone3e61042001-05-09 15:50:25 +00009
Jeremy Hylton1afc1692008-06-18 20:49:58 +000010import urllib.request
Ronald Oussorene72e1612011-03-14 18:15:25 -040011# The proxy bypass method imported below has logic specific to the OSX
12# proxy config data structure but is testable on all platforms.
13from urllib.request import Request, OpenerDirector, _proxy_bypass_macosx_sysconf
guido@google.coma119df92011-03-29 11:41:02 -070014import urllib.error
Jeremy Hyltone3e61042001-05-09 15:50:25 +000015
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000016# XXX
17# Request
18# CacheFTPHandler (hard to write)
Thomas Wouters477c8d52006-05-27 19:21:47 +000019# parse_keqv_list, parse_http_list, HTTPDigestAuthHandler
Jeremy Hyltone3e61042001-05-09 15:50:25 +000020
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000021class TrivialTests(unittest.TestCase):
Senthil Kumaran6c5bd402011-11-01 23:20:31 +080022
23 def test___all__(self):
24 # Verify which names are exposed
25 for module in 'request', 'response', 'parse', 'error', 'robotparser':
26 context = {}
27 exec('from urllib.%s import *' % module, context)
28 del context['__builtins__']
Florent Xicluna3dbb1f12011-11-04 22:15:37 +010029 if module == 'request' and os.name == 'nt':
30 u, p = context.pop('url2pathname'), context.pop('pathname2url')
31 self.assertEqual(u.__module__, 'nturl2path')
32 self.assertEqual(p.__module__, 'nturl2path')
Senthil Kumaran6c5bd402011-11-01 23:20:31 +080033 for k, v in context.items():
34 self.assertEqual(v.__module__, 'urllib.%s' % module,
35 "%r is exposed in 'urllib.%s' but defined in %r" %
36 (k, module, v.__module__))
37
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000038 def test_trivial(self):
39 # A couple trivial tests
Guido van Rossume2ae77b2001-10-24 20:42:55 +000040
Jeremy Hylton1afc1692008-06-18 20:49:58 +000041 self.assertRaises(ValueError, urllib.request.urlopen, 'bogus url')
Tim Peters861adac2001-07-16 20:49:49 +000042
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000043 # XXX Name hacking to get this to work on Windows.
Jeremy Hylton1afc1692008-06-18 20:49:58 +000044 fname = os.path.abspath(urllib.request.__file__).replace('\\', '/')
Senthil Kumarand587e302010-01-10 17:45:52 +000045
Senthil Kumarand587e302010-01-10 17:45:52 +000046 if os.name == 'nt':
47 file_url = "file:///%s" % fname
48 else:
49 file_url = "file://%s" % fname
50
Jeremy Hylton1afc1692008-06-18 20:49:58 +000051 f = urllib.request.urlopen(file_url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000052
53 buf = f.read()
54 f.close()
Tim Petersf5f32b42005-07-17 23:16:17 +000055
Georg Brandle1b13d22005-08-24 22:20:32 +000056 def test_parse_http_list(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +000057 tests = [
58 ('a,b,c', ['a', 'b', 'c']),
59 ('path"o,l"og"i"cal, example', ['path"o,l"og"i"cal', 'example']),
60 ('a, b, "c", "d", "e,f", g, h',
61 ['a', 'b', '"c"', '"d"', '"e,f"', 'g', 'h']),
62 ('a="b\\"c", d="e\\,f", g="h\\\\i"',
63 ['a="b"c"', 'd="e,f"', 'g="h\\i"'])]
Georg Brandle1b13d22005-08-24 22:20:32 +000064 for string, list in tests:
Florent Xicluna419e3842010-08-08 16:16:07 +000065 self.assertEqual(urllib.request.parse_http_list(string), list)
Georg Brandle1b13d22005-08-24 22:20:32 +000066
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000067
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000068def test_request_headers_dict():
69 """
70 The Request.headers dictionary is not a documented interface. It should
71 stay that way, because the complete set of headers are only accessible
72 through the .get_header(), .has_header(), .header_items() interface.
73 However, .headers pre-dates those methods, and so real code will be using
74 the dictionary.
75
76 The introduction in 2.4 of those methods was a mistake for the same reason:
77 code that previously saw all (urllib2 user)-provided headers in .headers
78 now sees only a subset (and the function interface is ugly and incomplete).
79 A better change would have been to replace .headers dict with a dict
80 subclass (or UserDict.DictMixin instance?) that preserved the .headers
81 interface and also provided access to the "unredirected" headers. It's
82 probably too late to fix that, though.
83
84
85 Check .capitalize() case normalization:
86
87 >>> url = "http://example.com"
88 >>> Request(url, headers={"Spam-eggs": "blah"}).headers["Spam-eggs"]
89 'blah'
90 >>> Request(url, headers={"spam-EggS": "blah"}).headers["Spam-eggs"]
91 'blah'
92
93 Currently, Request(url, "Spam-eggs").headers["Spam-Eggs"] raises KeyError,
94 but that could be changed in future.
95
96 """
97
98def test_request_headers_methods():
99 """
100 Note the case normalization of header names here, to .capitalize()-case.
101 This should be preserved for backwards-compatibility. (In the HTTP case,
102 normalization to .title()-case is done by urllib2 before sending headers to
Georg Brandl24420152008-05-26 16:32:26 +0000103 http.client).
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000104
105 >>> url = "http://example.com"
106 >>> r = Request(url, headers={"Spam-eggs": "blah"})
107 >>> r.has_header("Spam-eggs")
108 True
109 >>> r.header_items()
110 [('Spam-eggs', 'blah')]
111 >>> r.add_header("Foo-Bar", "baz")
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000112 >>> items = sorted(r.header_items())
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000113 >>> items
114 [('Foo-bar', 'baz'), ('Spam-eggs', 'blah')]
115
116 Note that e.g. r.has_header("spam-EggS") is currently False, and
117 r.get_header("spam-EggS") returns None, but that could be changed in
118 future.
119
120 >>> r.has_header("Not-there")
121 False
Guido van Rossum7131f842007-02-09 20:13:25 +0000122 >>> print(r.get_header("Not-there"))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000123 None
124 >>> r.get_header("Not-there", "default")
125 'default'
126
127 """
128
129
Thomas Wouters477c8d52006-05-27 19:21:47 +0000130def test_password_manager(self):
131 """
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000132 >>> mgr = urllib.request.HTTPPasswordMgr()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000133 >>> add = mgr.add_password
134 >>> add("Some Realm", "http://example.com/", "joe", "password")
135 >>> add("Some Realm", "http://example.com/ni", "ni", "ni")
136 >>> add("c", "http://example.com/foo", "foo", "ni")
137 >>> add("c", "http://example.com/bar", "bar", "nini")
138 >>> add("b", "http://example.com/", "first", "blah")
139 >>> add("b", "http://example.com/", "second", "spam")
140 >>> add("a", "http://example.com", "1", "a")
141 >>> add("Some Realm", "http://c.example.com:3128", "3", "c")
142 >>> add("Some Realm", "d.example.com", "4", "d")
143 >>> add("Some Realm", "e.example.com:3128", "5", "e")
144
145 >>> mgr.find_user_password("Some Realm", "example.com")
146 ('joe', 'password')
147 >>> mgr.find_user_password("Some Realm", "http://example.com")
148 ('joe', 'password')
149 >>> mgr.find_user_password("Some Realm", "http://example.com/")
150 ('joe', 'password')
151 >>> mgr.find_user_password("Some Realm", "http://example.com/spam")
152 ('joe', 'password')
153 >>> mgr.find_user_password("Some Realm", "http://example.com/spam/spam")
154 ('joe', 'password')
155 >>> mgr.find_user_password("c", "http://example.com/foo")
156 ('foo', 'ni')
157 >>> mgr.find_user_password("c", "http://example.com/bar")
158 ('bar', 'nini')
159
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000160 Actually, this is really undefined ATM
161## Currently, we use the highest-level path where more than one match:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000162
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000163## >>> mgr.find_user_password("Some Realm", "http://example.com/ni")
164## ('joe', 'password')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000165
166 Use latest add_password() in case of conflict:
167
168 >>> mgr.find_user_password("b", "http://example.com/")
169 ('second', 'spam')
170
171 No special relationship between a.example.com and example.com:
172
173 >>> mgr.find_user_password("a", "http://example.com/")
174 ('1', 'a')
175 >>> mgr.find_user_password("a", "http://a.example.com/")
176 (None, None)
177
178 Ports:
179
180 >>> mgr.find_user_password("Some Realm", "c.example.com")
181 (None, None)
182 >>> mgr.find_user_password("Some Realm", "c.example.com:3128")
183 ('3', 'c')
184 >>> mgr.find_user_password("Some Realm", "http://c.example.com:3128")
185 ('3', 'c')
186 >>> mgr.find_user_password("Some Realm", "d.example.com")
187 ('4', 'd')
188 >>> mgr.find_user_password("Some Realm", "e.example.com:3128")
189 ('5', 'e')
190
191 """
192 pass
193
194
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000195def test_password_manager_default_port(self):
196 """
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000197 >>> mgr = urllib.request.HTTPPasswordMgr()
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000198 >>> add = mgr.add_password
199
200 The point to note here is that we can't guess the default port if there's
201 no scheme. This applies to both add_password and find_user_password.
202
203 >>> add("f", "http://g.example.com:80", "10", "j")
204 >>> add("g", "http://h.example.com", "11", "k")
205 >>> add("h", "i.example.com:80", "12", "l")
206 >>> add("i", "j.example.com", "13", "m")
207 >>> mgr.find_user_password("f", "g.example.com:100")
208 (None, None)
209 >>> mgr.find_user_password("f", "g.example.com:80")
210 ('10', 'j')
211 >>> mgr.find_user_password("f", "g.example.com")
212 (None, None)
213 >>> mgr.find_user_password("f", "http://g.example.com:100")
214 (None, None)
215 >>> mgr.find_user_password("f", "http://g.example.com:80")
216 ('10', 'j')
217 >>> mgr.find_user_password("f", "http://g.example.com")
218 ('10', 'j')
219 >>> mgr.find_user_password("g", "h.example.com")
220 ('11', 'k')
221 >>> mgr.find_user_password("g", "h.example.com:80")
222 ('11', 'k')
223 >>> mgr.find_user_password("g", "http://h.example.com:80")
224 ('11', 'k')
225 >>> mgr.find_user_password("h", "i.example.com")
226 (None, None)
227 >>> mgr.find_user_password("h", "i.example.com:80")
228 ('12', 'l')
229 >>> mgr.find_user_password("h", "http://i.example.com:80")
230 ('12', 'l')
231 >>> mgr.find_user_password("i", "j.example.com")
232 ('13', 'm')
233 >>> mgr.find_user_password("i", "j.example.com:80")
234 (None, None)
235 >>> mgr.find_user_password("i", "http://j.example.com")
236 ('13', 'm')
237 >>> mgr.find_user_password("i", "http://j.example.com:80")
238 (None, None)
239
240 """
241
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000242class MockOpener:
243 addheaders = []
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000244 def open(self, req, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
245 self.req, self.data, self.timeout = req, data, timeout
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000246 def error(self, proto, *args):
247 self.proto, self.args = proto, args
248
249class MockFile:
250 def read(self, count=None): pass
251 def readline(self, count=None): pass
252 def close(self): pass
253
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000254class MockHeaders(dict):
255 def getheaders(self, name):
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000256 return list(self.values())
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000257
Guido van Rossum34d19282007-08-09 01:03:29 +0000258class MockResponse(io.StringIO):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000259 def __init__(self, code, msg, headers, data, url=None):
Guido van Rossum34d19282007-08-09 01:03:29 +0000260 io.StringIO.__init__(self, data)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000261 self.code, self.msg, self.headers, self.url = code, msg, headers, url
262 def info(self):
263 return self.headers
264 def geturl(self):
265 return self.url
266
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000267class MockCookieJar:
268 def add_cookie_header(self, request):
269 self.ach_req = request
270 def extract_cookies(self, response, request):
271 self.ec_req, self.ec_r = request, response
272
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000273class FakeMethod:
274 def __init__(self, meth_name, action, handle):
275 self.meth_name = meth_name
276 self.handle = handle
277 self.action = action
278 def __call__(self, *args):
279 return self.handle(self.meth_name, self.action, *args)
280
Senthil Kumaran47fff872009-12-20 07:10:31 +0000281class MockHTTPResponse(io.IOBase):
282 def __init__(self, fp, msg, status, reason):
283 self.fp = fp
284 self.msg = msg
285 self.status = status
286 self.reason = reason
287 self.code = 200
288
289 def read(self):
290 return ''
291
292 def info(self):
293 return {}
294
295 def geturl(self):
296 return self.url
297
298
299class MockHTTPClass:
300 def __init__(self):
301 self.level = 0
302 self.req_headers = []
303 self.data = None
304 self.raise_on_endheaders = False
305 self._tunnel_headers = {}
306
307 def __call__(self, host, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
308 self.host = host
309 self.timeout = timeout
310 return self
311
312 def set_debuglevel(self, level):
313 self.level = level
314
315 def set_tunnel(self, host, port=None, headers=None):
316 self._tunnel_host = host
317 self._tunnel_port = port
318 if headers:
319 self._tunnel_headers = headers
320 else:
321 self._tunnel_headers.clear()
322
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000323 def request(self, method, url, body=None, headers=None):
Senthil Kumaran47fff872009-12-20 07:10:31 +0000324 self.method = method
325 self.selector = url
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000326 if headers is not None:
327 self.req_headers += headers.items()
Senthil Kumaran47fff872009-12-20 07:10:31 +0000328 self.req_headers.sort()
329 if body:
330 self.data = body
331 if self.raise_on_endheaders:
332 import socket
333 raise socket.error()
334 def getresponse(self):
335 return MockHTTPResponse(MockFile(), {}, 200, "OK")
336
Victor Stinnera4c45d72011-06-17 14:01:18 +0200337 def close(self):
338 pass
339
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000340class MockHandler:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000341 # useful for testing handler machinery
342 # see add_ordered_mock_handlers() docstring
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000343 handler_order = 500
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000344 def __init__(self, methods):
345 self._define_methods(methods)
346 def _define_methods(self, methods):
347 for spec in methods:
348 if len(spec) == 2: name, action = spec
349 else: name, action = spec, None
350 meth = FakeMethod(name, action, self.handle)
351 setattr(self.__class__, name, meth)
352 def handle(self, fn_name, action, *args, **kwds):
353 self.parent.calls.append((self, fn_name, args, kwds))
354 if action is None:
355 return None
356 elif action == "return self":
357 return self
358 elif action == "return response":
359 res = MockResponse(200, "OK", {}, "")
360 return res
361 elif action == "return request":
362 return Request("http://blah/")
363 elif action.startswith("error"):
364 code = action[action.rfind(" ")+1:]
365 try:
366 code = int(code)
367 except ValueError:
368 pass
369 res = MockResponse(200, "OK", {}, "")
370 return self.parent.error("http", args[0], res, code, "", {})
371 elif action == "raise":
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000372 raise urllib.error.URLError("blah")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000373 assert False
374 def close(self): pass
375 def add_parent(self, parent):
376 self.parent = parent
377 self.parent.calls = []
378 def __lt__(self, other):
379 if not hasattr(other, "handler_order"):
380 # No handler_order, leave in original order. Yuck.
381 return True
382 return self.handler_order < other.handler_order
383
384def add_ordered_mock_handlers(opener, meth_spec):
385 """Create MockHandlers and add them to an OpenerDirector.
386
387 meth_spec: list of lists of tuples and strings defining methods to define
388 on handlers. eg:
389
390 [["http_error", "ftp_open"], ["http_open"]]
391
392 defines methods .http_error() and .ftp_open() on one handler, and
393 .http_open() on another. These methods just record their arguments and
394 return None. Using a tuple instead of a string causes the method to
395 perform some action (see MockHandler.handle()), eg:
396
397 [["http_error"], [("http_open", "return request")]]
398
399 defines .http_error() on one handler (which simply returns None), and
400 .http_open() on another handler, which returns a Request object.
401
402 """
403 handlers = []
404 count = 0
405 for meths in meth_spec:
406 class MockHandlerSubclass(MockHandler): pass
407 h = MockHandlerSubclass(meths)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000408 h.handler_order += count
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000409 h.add_parent(opener)
410 count = count + 1
411 handlers.append(h)
412 opener.add_handler(h)
413 return handlers
414
Thomas Wouters477c8d52006-05-27 19:21:47 +0000415def build_test_opener(*handler_instances):
416 opener = OpenerDirector()
417 for h in handler_instances:
418 opener.add_handler(h)
419 return opener
420
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000421class MockHTTPHandler(urllib.request.BaseHandler):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000422 # useful for testing redirections and auth
423 # sends supplied headers and code as first response
424 # sends 200 OK as second response
425 def __init__(self, code, headers):
426 self.code = code
427 self.headers = headers
428 self.reset()
429 def reset(self):
430 self._count = 0
431 self.requests = []
432 def http_open(self, req):
Barry Warsaw820c1202008-06-12 04:06:45 +0000433 import email, http.client, copy
Guido van Rossum34d19282007-08-09 01:03:29 +0000434 from io import StringIO
Thomas Wouters477c8d52006-05-27 19:21:47 +0000435 self.requests.append(copy.deepcopy(req))
436 if self._count == 0:
437 self._count = self._count + 1
Georg Brandl24420152008-05-26 16:32:26 +0000438 name = http.client.responses[self.code]
Barry Warsaw820c1202008-06-12 04:06:45 +0000439 msg = email.message_from_string(self.headers)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000440 return self.parent.error(
441 "http", req, MockFile(), self.code, name, msg)
442 else:
443 self.req = req
Barry Warsaw820c1202008-06-12 04:06:45 +0000444 msg = email.message_from_string("\r\n\r\n")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000445 return MockResponse(200, "OK", msg, "", req.get_full_url())
446
Senthil Kumaran47fff872009-12-20 07:10:31 +0000447class MockHTTPSHandler(urllib.request.AbstractHTTPHandler):
448 # Useful for testing the Proxy-Authorization request by verifying the
449 # properties of httpcon
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000450
451 def __init__(self):
452 urllib.request.AbstractHTTPHandler.__init__(self)
453 self.httpconn = MockHTTPClass()
454
Senthil Kumaran47fff872009-12-20 07:10:31 +0000455 def https_open(self, req):
456 return self.do_open(self.httpconn, req)
457
Thomas Wouters477c8d52006-05-27 19:21:47 +0000458class MockPasswordManager:
459 def add_password(self, realm, uri, user, password):
460 self.realm = realm
461 self.url = uri
462 self.user = user
463 self.password = password
464 def find_user_password(self, realm, authuri):
465 self.target_realm = realm
466 self.target_url = authuri
467 return self.user, self.password
468
469
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000470class OpenerDirectorTests(unittest.TestCase):
471
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000472 def test_add_non_handler(self):
473 class NonHandler(object):
474 pass
475 self.assertRaises(TypeError,
476 OpenerDirector().add_handler, NonHandler())
477
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000478 def test_badly_named_methods(self):
479 # test work-around for three methods that accidentally follow the
480 # naming conventions for handler methods
481 # (*_open() / *_request() / *_response())
482
483 # These used to call the accidentally-named methods, causing a
484 # TypeError in real code; here, returning self from these mock
485 # methods would either cause no exception, or AttributeError.
486
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000487 from urllib.error import URLError
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000488
489 o = OpenerDirector()
490 meth_spec = [
491 [("do_open", "return self"), ("proxy_open", "return self")],
492 [("redirect_request", "return self")],
493 ]
494 handlers = add_ordered_mock_handlers(o, meth_spec)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000495 o.add_handler(urllib.request.UnknownHandler())
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000496 for scheme in "do", "proxy", "redirect":
497 self.assertRaises(URLError, o.open, scheme+"://example.com/")
498
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000499 def test_handled(self):
500 # handler returning non-None means no more handlers will be called
501 o = OpenerDirector()
502 meth_spec = [
503 ["http_open", "ftp_open", "http_error_302"],
504 ["ftp_open"],
505 [("http_open", "return self")],
506 [("http_open", "return self")],
507 ]
508 handlers = add_ordered_mock_handlers(o, meth_spec)
509
510 req = Request("http://example.com/")
511 r = o.open(req)
512 # Second .http_open() gets called, third doesn't, since second returned
513 # non-None. Handlers without .http_open() never get any methods called
514 # on them.
515 # In fact, second mock handler defining .http_open() returns self
516 # (instead of response), which becomes the OpenerDirector's return
517 # value.
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000518 self.assertEqual(r, handlers[2])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000519 calls = [(handlers[0], "http_open"), (handlers[2], "http_open")]
520 for expected, got in zip(calls, o.calls):
521 handler, name, args, kwds = got
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000522 self.assertEqual((handler, name), expected)
523 self.assertEqual(args, (req,))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000524
525 def test_handler_order(self):
526 o = OpenerDirector()
527 handlers = []
528 for meths, handler_order in [
529 ([("http_open", "return self")], 500),
530 (["http_open"], 0),
531 ]:
532 class MockHandlerSubclass(MockHandler): pass
533 h = MockHandlerSubclass(meths)
534 h.handler_order = handler_order
535 handlers.append(h)
536 o.add_handler(h)
537
538 r = o.open("http://example.com/")
539 # handlers called in reverse order, thanks to their sort order
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000540 self.assertEqual(o.calls[0][0], handlers[1])
541 self.assertEqual(o.calls[1][0], handlers[0])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000542
543 def test_raise(self):
544 # raising URLError stops processing of request
545 o = OpenerDirector()
546 meth_spec = [
547 [("http_open", "raise")],
548 [("http_open", "return self")],
549 ]
550 handlers = add_ordered_mock_handlers(o, meth_spec)
551
552 req = Request("http://example.com/")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000553 self.assertRaises(urllib.error.URLError, o.open, req)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000554 self.assertEqual(o.calls, [(handlers[0], "http_open", (req,), {})])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000555
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000556 def test_http_error(self):
557 # XXX http_error_default
558 # http errors are a special case
559 o = OpenerDirector()
560 meth_spec = [
561 [("http_open", "error 302")],
562 [("http_error_400", "raise"), "http_open"],
563 [("http_error_302", "return response"), "http_error_303",
564 "http_error"],
565 [("http_error_302")],
566 ]
567 handlers = add_ordered_mock_handlers(o, meth_spec)
568
569 class Unknown:
570 def __eq__(self, other): return True
571
572 req = Request("http://example.com/")
573 r = o.open(req)
574 assert len(o.calls) == 2
575 calls = [(handlers[0], "http_open", (req,)),
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000576 (handlers[2], "http_error_302",
577 (req, Unknown(), 302, "", {}))]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000578 for expected, got in zip(calls, o.calls):
579 handler, method_name, args = expected
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000580 self.assertEqual((handler, method_name), got[:2])
581 self.assertEqual(args, got[2])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000582
Senthil Kumaran38b968b2012-03-14 13:43:53 -0700583
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000584 def test_processors(self):
585 # *_request / *_response methods get called appropriately
586 o = OpenerDirector()
587 meth_spec = [
588 [("http_request", "return request"),
589 ("http_response", "return response")],
590 [("http_request", "return request"),
591 ("http_response", "return response")],
592 ]
593 handlers = add_ordered_mock_handlers(o, meth_spec)
594
595 req = Request("http://example.com/")
596 r = o.open(req)
597 # processor methods are called on *all* handlers that define them,
598 # not just the first handler that handles the request
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000599 calls = [
600 (handlers[0], "http_request"), (handlers[1], "http_request"),
601 (handlers[0], "http_response"), (handlers[1], "http_response")]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000602
603 for i, (handler, name, args, kwds) in enumerate(o.calls):
604 if i < 2:
605 # *_request
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000606 self.assertEqual((handler, name), calls[i])
607 self.assertEqual(len(args), 1)
Ezio Melottie9615932010-01-24 19:26:24 +0000608 self.assertIsInstance(args[0], Request)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000609 else:
610 # *_response
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000611 self.assertEqual((handler, name), calls[i])
612 self.assertEqual(len(args), 2)
Ezio Melottie9615932010-01-24 19:26:24 +0000613 self.assertIsInstance(args[0], Request)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000614 # response from opener.open is None, because there's no
615 # handler that defines http_open to handle it
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000616 self.assertTrue(args[1] is None or
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000617 isinstance(args[1], MockResponse))
618
Senthil Kumaran38b968b2012-03-14 13:43:53 -0700619 def test_method_deprecations(self):
620 req = Request("http://www.example.com")
Senthil Kumaran08bd4aa2012-04-11 23:05:49 +0800621
622 with self.assertWarns(DeprecationWarning) as cm:
Senthil Kumaran38b968b2012-03-14 13:43:53 -0700623 req.add_data("data")
Senthil Kumaran08bd4aa2012-04-11 23:05:49 +0800624 with self.assertWarns(DeprecationWarning) as cm:
Senthil Kumaran38b968b2012-03-14 13:43:53 -0700625 req.has_data()
Senthil Kumaran08bd4aa2012-04-11 23:05:49 +0800626 with self.assertWarns(DeprecationWarning) as cm:
Senthil Kumaran38b968b2012-03-14 13:43:53 -0700627 req.get_data()
Senthil Kumaran08bd4aa2012-04-11 23:05:49 +0800628 with self.assertWarns(DeprecationWarning) as cm:
Senthil Kumaran38b968b2012-03-14 13:43:53 -0700629 req.get_host()
Senthil Kumaran08bd4aa2012-04-11 23:05:49 +0800630 with self.assertWarns(DeprecationWarning) as cm:
Senthil Kumaran38b968b2012-03-14 13:43:53 -0700631 req.get_selector()
Senthil Kumaran08bd4aa2012-04-11 23:05:49 +0800632 with self.assertWarns(DeprecationWarning) as cm:
Senthil Kumaran38b968b2012-03-14 13:43:53 -0700633 req.is_unverifiable()
Senthil Kumaran08bd4aa2012-04-11 23:05:49 +0800634 with self.assertWarns(DeprecationWarning) as cm:
Senthil Kumaran38b968b2012-03-14 13:43:53 -0700635 req.get_origin_req_host()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000636
Senthil Kumaran08bd4aa2012-04-11 23:05:49 +0800637
Tim Peters58eb11c2004-01-18 20:29:55 +0000638def sanepathname2url(path):
Victor Stinner6c6f8512010-08-07 10:09:35 +0000639 try:
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000640 path.encode("utf-8")
Victor Stinner6c6f8512010-08-07 10:09:35 +0000641 except UnicodeEncodeError:
642 raise unittest.SkipTest("path is not encodable to utf8")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000643 urlpath = urllib.request.pathname2url(path)
Tim Peters58eb11c2004-01-18 20:29:55 +0000644 if os.name == "nt" and urlpath.startswith("///"):
645 urlpath = urlpath[2:]
646 # XXX don't ask me about the mac...
647 return urlpath
648
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000649class HandlerTests(unittest.TestCase):
650
651 def test_ftp(self):
652 class MockFTPWrapper:
653 def __init__(self, data): self.data = data
654 def retrfile(self, filename, filetype):
655 self.filename, self.filetype = filename, filetype
Guido van Rossum34d19282007-08-09 01:03:29 +0000656 return io.StringIO(self.data), len(self.data)
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +0200657 def close(self): pass
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000658
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000659 class NullFTPHandler(urllib.request.FTPHandler):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000660 def __init__(self, data): self.data = data
Georg Brandlf78e02b2008-06-10 17:40:04 +0000661 def connect_ftp(self, user, passwd, host, port, dirs,
662 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000663 self.user, self.passwd = user, passwd
664 self.host, self.port = host, port
665 self.dirs = dirs
666 self.ftpwrapper = MockFTPWrapper(self.data)
667 return self.ftpwrapper
668
Georg Brandlf78e02b2008-06-10 17:40:04 +0000669 import ftplib
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000670 data = "rheum rhaponicum"
671 h = NullFTPHandler(data)
672 o = h.parent = MockOpener()
673
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000674 for url, host, port, user, passwd, type_, dirs, filename, mimetype in [
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000675 ("ftp://localhost/foo/bar/baz.html",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000676 "localhost", ftplib.FTP_PORT, "", "", "I",
677 ["foo", "bar"], "baz.html", "text/html"),
678 ("ftp://parrot@localhost/foo/bar/baz.html",
679 "localhost", ftplib.FTP_PORT, "parrot", "", "I",
680 ["foo", "bar"], "baz.html", "text/html"),
681 ("ftp://%25parrot@localhost/foo/bar/baz.html",
682 "localhost", ftplib.FTP_PORT, "%parrot", "", "I",
683 ["foo", "bar"], "baz.html", "text/html"),
684 ("ftp://%2542parrot@localhost/foo/bar/baz.html",
685 "localhost", ftplib.FTP_PORT, "%42parrot", "", "I",
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000686 ["foo", "bar"], "baz.html", "text/html"),
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000687 ("ftp://localhost:80/foo/bar/",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000688 "localhost", 80, "", "", "D",
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000689 ["foo", "bar"], "", None),
690 ("ftp://localhost/baz.gif;type=a",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000691 "localhost", ftplib.FTP_PORT, "", "", "A",
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000692 [], "baz.gif", None), # XXX really this should guess image/gif
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000693 ]:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000694 req = Request(url)
695 req.timeout = None
696 r = h.ftp_open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000697 # ftp authentication not yet implemented by FTPHandler
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000698 self.assertEqual(h.user, user)
699 self.assertEqual(h.passwd, passwd)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000700 self.assertEqual(h.host, socket.gethostbyname(host))
701 self.assertEqual(h.port, port)
702 self.assertEqual(h.dirs, dirs)
703 self.assertEqual(h.ftpwrapper.filename, filename)
704 self.assertEqual(h.ftpwrapper.filetype, type_)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000705 headers = r.info()
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000706 self.assertEqual(headers.get("Content-type"), mimetype)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000707 self.assertEqual(int(headers["Content-length"]), len(data))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000708
709 def test_file(self):
Benjamin Petersona0c0a4a2008-06-12 22:15:50 +0000710 import email.utils, socket
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000711 h = urllib.request.FileHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000712 o = h.parent = MockOpener()
713
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000714 TESTFN = support.TESTFN
Tim Peters58eb11c2004-01-18 20:29:55 +0000715 urlpath = sanepathname2url(os.path.abspath(TESTFN))
Guido van Rossum6a2ccd02007-07-16 20:51:57 +0000716 towrite = b"hello, world\n"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000717 urls = [
Tim Peters58eb11c2004-01-18 20:29:55 +0000718 "file://localhost%s" % urlpath,
719 "file://%s" % urlpath,
720 "file://%s%s" % (socket.gethostbyname('localhost'), urlpath),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000721 ]
722 try:
723 localaddr = socket.gethostbyname(socket.gethostname())
724 except socket.gaierror:
725 localaddr = ''
726 if localaddr:
727 urls.append("file://%s%s" % (localaddr, urlpath))
728
729 for url in urls:
Tim Peters58eb11c2004-01-18 20:29:55 +0000730 f = open(TESTFN, "wb")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000731 try:
732 try:
733 f.write(towrite)
734 finally:
735 f.close()
736
737 r = h.file_open(Request(url))
738 try:
739 data = r.read()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000740 headers = r.info()
Senthil Kumaran4fbed102010-05-08 03:29:09 +0000741 respurl = r.geturl()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000742 finally:
743 r.close()
Tim Peters58eb11c2004-01-18 20:29:55 +0000744 stats = os.stat(TESTFN)
Benjamin Petersona0c0a4a2008-06-12 22:15:50 +0000745 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000746 finally:
747 os.remove(TESTFN)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000748 self.assertEqual(data, towrite)
749 self.assertEqual(headers["Content-type"], "text/plain")
750 self.assertEqual(headers["Content-length"], "13")
Tim Peters58eb11c2004-01-18 20:29:55 +0000751 self.assertEqual(headers["Last-modified"], modified)
Senthil Kumaran4fbed102010-05-08 03:29:09 +0000752 self.assertEqual(respurl, url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000753
754 for url in [
Tim Peters58eb11c2004-01-18 20:29:55 +0000755 "file://localhost:80%s" % urlpath,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000756 "file:///file_does_not_exist.txt",
757 "file://%s:80%s/%s" % (socket.gethostbyname('localhost'),
758 os.getcwd(), TESTFN),
759 "file://somerandomhost.ontheinternet.com%s/%s" %
760 (os.getcwd(), TESTFN),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000761 ]:
762 try:
Tim Peters58eb11c2004-01-18 20:29:55 +0000763 f = open(TESTFN, "wb")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000764 try:
765 f.write(towrite)
766 finally:
767 f.close()
768
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000769 self.assertRaises(urllib.error.URLError,
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000770 h.file_open, Request(url))
771 finally:
772 os.remove(TESTFN)
773
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000774 h = urllib.request.FileHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000775 o = h.parent = MockOpener()
776 # XXXX why does // mean ftp (and /// mean not ftp!), and where
777 # is file: scheme specified? I think this is really a bug, and
778 # what was intended was to distinguish between URLs like:
779 # file:/blah.txt (a file)
780 # file://localhost/blah.txt (a file)
781 # file:///blah.txt (a file)
782 # file://ftp.example.com/blah.txt (an ftp URL)
783 for url, ftp in [
Senthil Kumaran383c32d2010-10-14 11:57:35 +0000784 ("file://ftp.example.com//foo.txt", False),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000785 ("file://ftp.example.com///foo.txt", False),
786# XXXX bug: fails with OSError, should be URLError
787 ("file://ftp.example.com/foo.txt", False),
Senthil Kumaran383c32d2010-10-14 11:57:35 +0000788 ("file://somehost//foo/something.txt", False),
Senthil Kumaran2ef16322010-07-11 03:12:43 +0000789 ("file://localhost//foo/something.txt", False),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000790 ]:
791 req = Request(url)
792 try:
793 h.file_open(req)
794 # XXXX remove OSError when bug fixed
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000795 except (urllib.error.URLError, OSError):
Florent Xicluna419e3842010-08-08 16:16:07 +0000796 self.assertFalse(ftp)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000797 else:
Florent Xicluna419e3842010-08-08 16:16:07 +0000798 self.assertIs(o.req, req)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000799 self.assertEqual(req.type, "ftp")
Łukasz Langad7e81cc2011-01-09 18:18:53 +0000800 self.assertEqual(req.type == "ftp", ftp)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000801
802 def test_http(self):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000803
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000804 h = urllib.request.AbstractHTTPHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000805 o = h.parent = MockOpener()
806
807 url = "http://example.com/"
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000808 for method, data in [("GET", None), ("POST", b"blah")]:
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000809 req = Request(url, data, {"Foo": "bar"})
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000810 req.timeout = None
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000811 req.add_unredirected_header("Spam", "eggs")
812 http = MockHTTPClass()
813 r = h.do_open(http, req)
814
815 # result attributes
816 r.read; r.readline # wrapped MockFile methods
817 r.info; r.geturl # addinfourl methods
818 r.code, r.msg == 200, "OK" # added from MockHTTPClass.getreply()
819 hdrs = r.info()
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000820 hdrs.get; hdrs.__contains__ # r.info() gives dict from .getreply()
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000821 self.assertEqual(r.geturl(), url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000822
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000823 self.assertEqual(http.host, "example.com")
824 self.assertEqual(http.level, 0)
825 self.assertEqual(http.method, method)
826 self.assertEqual(http.selector, "/")
827 self.assertEqual(http.req_headers,
Jeremy Hyltonb3ee6f92004-02-24 19:40:35 +0000828 [("Connection", "close"),
829 ("Foo", "bar"), ("Spam", "eggs")])
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000830 self.assertEqual(http.data, data)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000831
832 # check socket.error converted to URLError
833 http.raise_on_endheaders = True
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000834 self.assertRaises(urllib.error.URLError, h.do_open, http, req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000835
Senthil Kumaran29333122011-02-11 11:25:47 +0000836 # Check for TypeError on POST data which is str.
837 req = Request("http://example.com/","badpost")
838 self.assertRaises(TypeError, h.do_request_, req)
839
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000840 # check adding of standard headers
841 o.addheaders = [("Spam", "eggs")]
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000842 for data in b"", None: # POST, GET
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000843 req = Request("http://example.com/", data)
844 r = MockResponse(200, "OK", {}, "")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000845 newreq = h.do_request_(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000846 if data is None: # GET
Benjamin Peterson577473f2010-01-19 00:09:57 +0000847 self.assertNotIn("Content-length", req.unredirected_hdrs)
848 self.assertNotIn("Content-type", req.unredirected_hdrs)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000849 else: # POST
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000850 self.assertEqual(req.unredirected_hdrs["Content-length"], "0")
851 self.assertEqual(req.unredirected_hdrs["Content-type"],
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000852 "application/x-www-form-urlencoded")
853 # XXX the details of Host could be better tested
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000854 self.assertEqual(req.unredirected_hdrs["Host"], "example.com")
855 self.assertEqual(req.unredirected_hdrs["Spam"], "eggs")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000856
857 # don't clobber existing headers
858 req.add_unredirected_header("Content-length", "foo")
859 req.add_unredirected_header("Content-type", "bar")
860 req.add_unredirected_header("Host", "baz")
861 req.add_unredirected_header("Spam", "foo")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000862 newreq = h.do_request_(req)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000863 self.assertEqual(req.unredirected_hdrs["Content-length"], "foo")
864 self.assertEqual(req.unredirected_hdrs["Content-type"], "bar")
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000865 self.assertEqual(req.unredirected_hdrs["Host"], "baz")
866 self.assertEqual(req.unredirected_hdrs["Spam"], "foo")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000867
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000868 # Check iterable body support
869 def iterable_body():
870 yield b"one"
871 yield b"two"
872 yield b"three"
873
874 for headers in {}, {"Content-Length": 11}:
875 req = Request("http://example.com/", iterable_body(), headers)
876 if not headers:
877 # Having an iterable body without a Content-Length should
878 # raise an exception
879 self.assertRaises(ValueError, h.do_request_, req)
880 else:
881 newreq = h.do_request_(req)
882
Senthil Kumaran29333122011-02-11 11:25:47 +0000883 # A file object.
884 # Test only Content-Length attribute of request.
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000885
Senthil Kumaran29333122011-02-11 11:25:47 +0000886 file_obj = io.BytesIO()
887 file_obj.write(b"Something\nSomething\nSomething\n")
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000888
889 for headers in {}, {"Content-Length": 30}:
890 req = Request("http://example.com/", file_obj, headers)
891 if not headers:
892 # Having an iterable body without a Content-Length should
893 # raise an exception
894 self.assertRaises(ValueError, h.do_request_, req)
895 else:
896 newreq = h.do_request_(req)
897 self.assertEqual(int(newreq.get_header('Content-length')),30)
898
899 file_obj.close()
900
901 # array.array Iterable - Content Length is calculated
902
903 iterable_array = array.array("I",[1,2,3,4])
904
905 for headers in {}, {"Content-Length": 16}:
906 req = Request("http://example.com/", iterable_array, headers)
907 newreq = h.do_request_(req)
908 self.assertEqual(int(newreq.get_header('Content-length')),16)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000909
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000910 def test_http_doubleslash(self):
911 # Checks the presence of any unnecessary double slash in url does not
912 # break anything. Previously, a double slash directly after the host
Ezio Melottie130a522011-10-19 10:58:56 +0300913 # could cause incorrect parsing.
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000914 h = urllib.request.AbstractHTTPHandler()
915 o = h.parent = MockOpener()
916
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000917 data = b""
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000918 ds_urls = [
919 "http://example.com/foo/bar/baz.html",
920 "http://example.com//foo/bar/baz.html",
921 "http://example.com/foo//bar/baz.html",
922 "http://example.com/foo/bar//baz.html"
923 ]
924
925 for ds_url in ds_urls:
926 ds_req = Request(ds_url, data)
927
928 # Check whether host is determined correctly if there is no proxy
929 np_ds_req = h.do_request_(ds_req)
930 self.assertEqual(np_ds_req.unredirected_hdrs["Host"],"example.com")
931
932 # Check whether host is determined correctly if there is a proxy
933 ds_req.set_proxy("someproxy:3128",None)
934 p_ds_req = h.do_request_(ds_req)
935 self.assertEqual(p_ds_req.unredirected_hdrs["Host"],"example.com")
936
Senthil Kumaranc2958622010-11-22 04:48:26 +0000937 def test_fixpath_in_weirdurls(self):
938 # Issue4493: urllib2 to supply '/' when to urls where path does not
939 # start with'/'
940
941 h = urllib.request.AbstractHTTPHandler()
942 o = h.parent = MockOpener()
943
944 weird_url = 'http://www.python.org?getspam'
945 req = Request(weird_url)
946 newreq = h.do_request_(req)
947 self.assertEqual(newreq.host,'www.python.org')
948 self.assertEqual(newreq.selector,'/?getspam')
949
950 url_without_path = 'http://www.python.org'
951 req = Request(url_without_path)
952 newreq = h.do_request_(req)
953 self.assertEqual(newreq.host,'www.python.org')
954 self.assertEqual(newreq.selector,'')
955
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000956
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000957 def test_errors(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000958 h = urllib.request.HTTPErrorProcessor()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000959 o = h.parent = MockOpener()
960
961 url = "http://example.com/"
962 req = Request(url)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000963 # all 2xx are passed through
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000964 r = MockResponse(200, "OK", {}, "", url)
965 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +0000966 self.assertIs(r, newr)
967 self.assertFalse(hasattr(o, "proto")) # o.error not called
Guido van Rossumd8faa362007-04-27 19:54:29 +0000968 r = MockResponse(202, "Accepted", {}, "", url)
969 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +0000970 self.assertIs(r, newr)
971 self.assertFalse(hasattr(o, "proto")) # o.error not called
Guido van Rossumd8faa362007-04-27 19:54:29 +0000972 r = MockResponse(206, "Partial content", {}, "", url)
973 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +0000974 self.assertIs(r, newr)
975 self.assertFalse(hasattr(o, "proto")) # o.error not called
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000976 # anything else calls o.error (and MockOpener returns None, here)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000977 r = MockResponse(502, "Bad gateway", {}, "", url)
Florent Xicluna419e3842010-08-08 16:16:07 +0000978 self.assertIsNone(h.http_response(req, r))
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000979 self.assertEqual(o.proto, "http") # o.error called
Guido van Rossumd8faa362007-04-27 19:54:29 +0000980 self.assertEqual(o.args, (req, r, 502, "Bad gateway", {}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000981
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000982 def test_cookies(self):
983 cj = MockCookieJar()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000984 h = urllib.request.HTTPCookieProcessor(cj)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000985 o = h.parent = MockOpener()
986
987 req = Request("http://example.com/")
988 r = MockResponse(200, "OK", {}, "")
989 newreq = h.http_request(req)
Florent Xicluna419e3842010-08-08 16:16:07 +0000990 self.assertIs(cj.ach_req, req)
991 self.assertIs(cj.ach_req, newreq)
992 self.assertEqual(req.get_origin_req_host(), "example.com")
993 self.assertFalse(req.is_unverifiable())
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000994 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +0000995 self.assertIs(cj.ec_req, req)
996 self.assertIs(cj.ec_r, r)
997 self.assertIs(r, newr)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000998
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000999 def test_redirect(self):
1000 from_url = "http://example.com/a.html"
1001 to_url = "http://example.com/b.html"
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001002 h = urllib.request.HTTPRedirectHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001003 o = h.parent = MockOpener()
1004
1005 # ordinary redirect behaviour
1006 for code in 301, 302, 303, 307:
1007 for data in None, "blah\nblah\n":
1008 method = getattr(h, "http_error_%s" % code)
1009 req = Request(from_url, data)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001010 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001011 req.add_header("Nonsense", "viking=withhold")
Christian Heimes77c02eb2008-02-09 02:18:51 +00001012 if data is not None:
1013 req.add_header("Content-Length", str(len(data)))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001014 req.add_unredirected_header("Spam", "spam")
1015 try:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001016 method(req, MockFile(), code, "Blah",
1017 MockHeaders({"location": to_url}))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001018 except urllib.error.HTTPError:
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001019 # 307 in response to POST requires user OK
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001020 self.assertTrue(code == 307 and data is not None)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001021 self.assertEqual(o.req.get_full_url(), to_url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001022 try:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001023 self.assertEqual(o.req.get_method(), "GET")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001024 except AttributeError:
Florent Xicluna419e3842010-08-08 16:16:07 +00001025 self.assertFalse(o.req.has_data())
Christian Heimes77c02eb2008-02-09 02:18:51 +00001026
1027 # now it's a GET, there should not be headers regarding content
1028 # (possibly dragged from before being a POST)
1029 headers = [x.lower() for x in o.req.headers]
Benjamin Peterson577473f2010-01-19 00:09:57 +00001030 self.assertNotIn("content-length", headers)
1031 self.assertNotIn("content-type", headers)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001032
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001033 self.assertEqual(o.req.headers["Nonsense"],
1034 "viking=withhold")
Benjamin Peterson577473f2010-01-19 00:09:57 +00001035 self.assertNotIn("Spam", o.req.headers)
1036 self.assertNotIn("Spam", o.req.unredirected_hdrs)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001037
1038 # loop detection
1039 req = Request(from_url)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001040 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001041 def redirect(h, req, url=to_url):
1042 h.http_error_302(req, MockFile(), 302, "Blah",
1043 MockHeaders({"location": url}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001044 # Note that the *original* request shares the same record of
1045 # redirections with the sub-requests caused by the redirections.
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001046
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001047 # detect infinite loop redirect of a URL to itself
1048 req = Request(from_url, origin_req_host="example.com")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001049 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001050 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001051 try:
1052 while 1:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001053 redirect(h, req, "http://example.com/")
1054 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001055 except urllib.error.HTTPError:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001056 # don't stop until max_repeats, because cookies may introduce state
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001057 self.assertEqual(count, urllib.request.HTTPRedirectHandler.max_repeats)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001058
1059 # detect endless non-repeating chain of redirects
1060 req = Request(from_url, origin_req_host="example.com")
1061 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001062 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001063 try:
1064 while 1:
1065 redirect(h, req, "http://example.com/%d" % count)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001066 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001067 except urllib.error.HTTPError:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001068 self.assertEqual(count,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001069 urllib.request.HTTPRedirectHandler.max_redirections)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001070
guido@google.coma119df92011-03-29 11:41:02 -07001071
1072 def test_invalid_redirect(self):
1073 from_url = "http://example.com/a.html"
1074 valid_schemes = ['http','https','ftp']
1075 invalid_schemes = ['file','imap','ldap']
1076 schemeless_url = "example.com/b.html"
1077 h = urllib.request.HTTPRedirectHandler()
1078 o = h.parent = MockOpener()
1079 req = Request(from_url)
1080 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1081
1082 for scheme in invalid_schemes:
1083 invalid_url = scheme + '://' + schemeless_url
1084 self.assertRaises(urllib.error.HTTPError, h.http_error_302,
1085 req, MockFile(), 302, "Security Loophole",
1086 MockHeaders({"location": invalid_url}))
1087
1088 for scheme in valid_schemes:
1089 valid_url = scheme + '://' + schemeless_url
1090 h.http_error_302(req, MockFile(), 302, "That's fine",
1091 MockHeaders({"location": valid_url}))
1092 self.assertEqual(o.req.get_full_url(), valid_url)
1093
Senthil Kumaran6497aa32012-01-04 13:46:59 +08001094 def test_relative_redirect(self):
1095 from_url = "http://example.com/a.html"
1096 relative_url = "/b.html"
1097 h = urllib.request.HTTPRedirectHandler()
1098 o = h.parent = MockOpener()
1099 req = Request(from_url)
1100 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1101
1102 valid_url = urllib.parse.urljoin(from_url,relative_url)
1103 h.http_error_302(req, MockFile(), 302, "That's fine",
1104 MockHeaders({"location": valid_url}))
1105 self.assertEqual(o.req.get_full_url(), valid_url)
1106
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001107 def test_cookie_redirect(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001108 # cookies shouldn't leak into redirected requests
Georg Brandl24420152008-05-26 16:32:26 +00001109 from http.cookiejar import CookieJar
1110 from test.test_http_cookiejar import interact_netscape
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001111
1112 cj = CookieJar()
1113 interact_netscape(cj, "http://www.example.com/", "spam=eggs")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001114 hh = MockHTTPHandler(302, "Location: http://www.cracker.com/\r\n\r\n")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001115 hdeh = urllib.request.HTTPDefaultErrorHandler()
1116 hrh = urllib.request.HTTPRedirectHandler()
1117 cp = urllib.request.HTTPCookieProcessor(cj)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001118 o = build_test_opener(hh, hdeh, hrh, cp)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001119 o.open("http://www.example.com/")
Florent Xicluna419e3842010-08-08 16:16:07 +00001120 self.assertFalse(hh.req.has_header("Cookie"))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001121
Senthil Kumaran26430412011-04-13 07:01:19 +08001122 def test_redirect_fragment(self):
1123 redirected_url = 'http://www.example.com/index.html#OK\r\n\r\n'
1124 hh = MockHTTPHandler(302, 'Location: ' + redirected_url)
1125 hdeh = urllib.request.HTTPDefaultErrorHandler()
1126 hrh = urllib.request.HTTPRedirectHandler()
1127 o = build_test_opener(hh, hdeh, hrh)
1128 fp = o.open('http://www.example.com')
1129 self.assertEqual(fp.geturl(), redirected_url.strip())
1130
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001131 def test_proxy(self):
1132 o = OpenerDirector()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001133 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001134 o.add_handler(ph)
1135 meth_spec = [
1136 [("http_open", "return response")]
1137 ]
1138 handlers = add_ordered_mock_handlers(o, meth_spec)
1139
1140 req = Request("http://acme.example.com/")
1141 self.assertEqual(req.get_host(), "acme.example.com")
1142 r = o.open(req)
1143 self.assertEqual(req.get_host(), "proxy.example.com:3128")
1144
1145 self.assertEqual([(handlers[0], "http_open")],
1146 [tup[0:2] for tup in o.calls])
1147
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001148 def test_proxy_no_proxy(self):
1149 os.environ['no_proxy'] = 'python.org'
1150 o = OpenerDirector()
1151 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1152 o.add_handler(ph)
1153 req = Request("http://www.perl.org/")
1154 self.assertEqual(req.get_host(), "www.perl.org")
1155 r = o.open(req)
1156 self.assertEqual(req.get_host(), "proxy.example.com")
1157 req = Request("http://www.python.org")
1158 self.assertEqual(req.get_host(), "www.python.org")
1159 r = o.open(req)
1160 self.assertEqual(req.get_host(), "www.python.org")
1161 del os.environ['no_proxy']
1162
Ronald Oussorene72e1612011-03-14 18:15:25 -04001163 def test_proxy_no_proxy_all(self):
1164 os.environ['no_proxy'] = '*'
1165 o = OpenerDirector()
1166 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1167 o.add_handler(ph)
1168 req = Request("http://www.python.org")
1169 self.assertEqual(req.get_host(), "www.python.org")
1170 r = o.open(req)
1171 self.assertEqual(req.get_host(), "www.python.org")
1172 del os.environ['no_proxy']
1173
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001174
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001175 def test_proxy_https(self):
1176 o = OpenerDirector()
1177 ph = urllib.request.ProxyHandler(dict(https="proxy.example.com:3128"))
1178 o.add_handler(ph)
1179 meth_spec = [
1180 [("https_open", "return response")]
1181 ]
1182 handlers = add_ordered_mock_handlers(o, meth_spec)
1183
1184 req = Request("https://www.example.com/")
1185 self.assertEqual(req.get_host(), "www.example.com")
1186 r = o.open(req)
1187 self.assertEqual(req.get_host(), "proxy.example.com:3128")
1188 self.assertEqual([(handlers[0], "https_open")],
1189 [tup[0:2] for tup in o.calls])
1190
Senthil Kumaran47fff872009-12-20 07:10:31 +00001191 def test_proxy_https_proxy_authorization(self):
1192 o = OpenerDirector()
1193 ph = urllib.request.ProxyHandler(dict(https='proxy.example.com:3128'))
1194 o.add_handler(ph)
1195 https_handler = MockHTTPSHandler()
1196 o.add_handler(https_handler)
1197 req = Request("https://www.example.com/")
1198 req.add_header("Proxy-Authorization","FooBar")
1199 req.add_header("User-Agent","Grail")
1200 self.assertEqual(req.get_host(), "www.example.com")
1201 self.assertIsNone(req._tunnel_host)
1202 r = o.open(req)
1203 # Verify Proxy-Authorization gets tunneled to request.
1204 # httpsconn req_headers do not have the Proxy-Authorization header but
1205 # the req will have.
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001206 self.assertNotIn(("Proxy-Authorization","FooBar"),
Senthil Kumaran47fff872009-12-20 07:10:31 +00001207 https_handler.httpconn.req_headers)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001208 self.assertIn(("User-Agent","Grail"),
1209 https_handler.httpconn.req_headers)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001210 self.assertIsNotNone(req._tunnel_host)
1211 self.assertEqual(req.get_host(), "proxy.example.com:3128")
1212 self.assertEqual(req.get_header("Proxy-authorization"),"FooBar")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001213
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001214 # TODO: This should be only for OSX
1215 @unittest.skipUnless(sys.platform == 'darwin', "only relevant for OSX")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001216 def test_osx_proxy_bypass(self):
1217 bypass = {
1218 'exclude_simple': False,
1219 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.10',
1220 '10.0/16']
1221 }
1222 # Check hosts that should trigger the proxy bypass
1223 for host in ('foo.bar', 'www.bar.com', '127.0.0.1', '10.10.0.1',
1224 '10.0.0.1'):
1225 self.assertTrue(_proxy_bypass_macosx_sysconf(host, bypass),
1226 'expected bypass of %s to be True' % host)
1227 # Check hosts that should not trigger the proxy bypass
1228 for host in ('abc.foo.bar', 'bar.com', '127.0.0.2', '10.11.0.1', 'test'):
1229 self.assertFalse(_proxy_bypass_macosx_sysconf(host, bypass),
1230 'expected bypass of %s to be False' % host)
1231
1232 # Check the exclude_simple flag
1233 bypass = {'exclude_simple': True, 'exceptions': []}
1234 self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass))
1235
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001236 def test_basic_auth(self, quote_char='"'):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001237 opener = OpenerDirector()
1238 password_manager = MockPasswordManager()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001239 auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001240 realm = "ACME Widget Store"
1241 http_handler = MockHTTPHandler(
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001242 401, 'WWW-Authenticate: Basic realm=%s%s%s\r\n\r\n' %
1243 (quote_char, realm, quote_char) )
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001244 opener.add_handler(auth_handler)
1245 opener.add_handler(http_handler)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001246 self._test_basic_auth(opener, auth_handler, "Authorization",
1247 realm, http_handler, password_manager,
1248 "http://acme.example.com/protected",
1249 "http://acme.example.com/protected",
1250 )
1251
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001252 def test_basic_auth_with_single_quoted_realm(self):
1253 self.test_basic_auth(quote_char="'")
1254
Thomas Wouters477c8d52006-05-27 19:21:47 +00001255 def test_proxy_basic_auth(self):
1256 opener = OpenerDirector()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001257 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001258 opener.add_handler(ph)
1259 password_manager = MockPasswordManager()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001260 auth_handler = urllib.request.ProxyBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001261 realm = "ACME Networks"
1262 http_handler = MockHTTPHandler(
1263 407, 'Proxy-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001264 opener.add_handler(auth_handler)
1265 opener.add_handler(http_handler)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001266 self._test_basic_auth(opener, auth_handler, "Proxy-authorization",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001267 realm, http_handler, password_manager,
1268 "http://acme.example.com:3128/protected",
1269 "proxy.example.com:3128",
1270 )
1271
1272 def test_basic_and_digest_auth_handlers(self):
1273 # HTTPDigestAuthHandler threw an exception if it couldn't handle a 40*
1274 # response (http://python.org/sf/1479302), where it should instead
1275 # return None to allow another handler (especially
1276 # HTTPBasicAuthHandler) to handle the response.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001277
1278 # Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must
1279 # try digest first (since it's the strongest auth scheme), so we record
1280 # order of calls here to check digest comes first:
1281 class RecordingOpenerDirector(OpenerDirector):
1282 def __init__(self):
1283 OpenerDirector.__init__(self)
1284 self.recorded = []
1285 def record(self, info):
1286 self.recorded.append(info)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001287 class TestDigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001288 def http_error_401(self, *args, **kwds):
1289 self.parent.record("digest")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001290 urllib.request.HTTPDigestAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001291 *args, **kwds)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001292 class TestBasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001293 def http_error_401(self, *args, **kwds):
1294 self.parent.record("basic")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001295 urllib.request.HTTPBasicAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001296 *args, **kwds)
1297
1298 opener = RecordingOpenerDirector()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001299 password_manager = MockPasswordManager()
1300 digest_handler = TestDigestAuthHandler(password_manager)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001301 basic_handler = TestBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001302 realm = "ACME Networks"
1303 http_handler = MockHTTPHandler(
1304 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001305 opener.add_handler(basic_handler)
1306 opener.add_handler(digest_handler)
1307 opener.add_handler(http_handler)
1308
1309 # check basic auth isn't blocked by digest handler failing
Thomas Wouters477c8d52006-05-27 19:21:47 +00001310 self._test_basic_auth(opener, basic_handler, "Authorization",
1311 realm, http_handler, password_manager,
1312 "http://acme.example.com/protected",
1313 "http://acme.example.com/protected",
1314 )
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001315 # check digest was tried before basic (twice, because
1316 # _test_basic_auth called .open() twice)
1317 self.assertEqual(opener.recorded, ["digest", "basic"]*2)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001318
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001319 def test_unsupported_auth_digest_handler(self):
1320 opener = OpenerDirector()
1321 # While using DigestAuthHandler
1322 digest_auth_handler = urllib.request.HTTPDigestAuthHandler(None)
1323 http_handler = MockHTTPHandler(
1324 401, 'WWW-Authenticate: Kerberos\r\n\r\n')
1325 opener.add_handler(digest_auth_handler)
1326 opener.add_handler(http_handler)
1327 self.assertRaises(ValueError,opener.open,"http://www.example.com")
1328
1329 def test_unsupported_auth_basic_handler(self):
1330 # While using BasicAuthHandler
1331 opener = OpenerDirector()
1332 basic_auth_handler = urllib.request.HTTPBasicAuthHandler(None)
1333 http_handler = MockHTTPHandler(
1334 401, 'WWW-Authenticate: NTLM\r\n\r\n')
1335 opener.add_handler(basic_auth_handler)
1336 opener.add_handler(http_handler)
1337 self.assertRaises(ValueError,opener.open,"http://www.example.com")
1338
Thomas Wouters477c8d52006-05-27 19:21:47 +00001339 def _test_basic_auth(self, opener, auth_handler, auth_header,
1340 realm, http_handler, password_manager,
1341 request_url, protected_url):
Christian Heimes05e8be12008-02-23 18:30:17 +00001342 import base64
Thomas Wouters477c8d52006-05-27 19:21:47 +00001343 user, password = "wile", "coyote"
Thomas Wouters477c8d52006-05-27 19:21:47 +00001344
1345 # .add_password() fed through to password manager
1346 auth_handler.add_password(realm, request_url, user, password)
1347 self.assertEqual(realm, password_manager.realm)
1348 self.assertEqual(request_url, password_manager.url)
1349 self.assertEqual(user, password_manager.user)
1350 self.assertEqual(password, password_manager.password)
1351
1352 r = opener.open(request_url)
1353
1354 # should have asked the password manager for the username/password
1355 self.assertEqual(password_manager.target_realm, realm)
1356 self.assertEqual(password_manager.target_url, protected_url)
1357
1358 # expect one request without authorization, then one with
1359 self.assertEqual(len(http_handler.requests), 2)
1360 self.assertFalse(http_handler.requests[0].has_header(auth_header))
Guido van Rossum98b349f2007-08-27 21:47:52 +00001361 userpass = bytes('%s:%s' % (user, password), "ascii")
Guido van Rossum98297ee2007-11-06 21:34:58 +00001362 auth_hdr_value = ('Basic ' +
Georg Brandl706824f2009-06-04 09:42:55 +00001363 base64.encodebytes(userpass).strip().decode())
Thomas Wouters477c8d52006-05-27 19:21:47 +00001364 self.assertEqual(http_handler.requests[1].get_header(auth_header),
1365 auth_hdr_value)
Senthil Kumaranca2fc9e2010-02-24 16:53:16 +00001366 self.assertEqual(http_handler.requests[1].unredirected_hdrs[auth_header],
1367 auth_hdr_value)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001368 # if the password manager can't find a password, the handler won't
1369 # handle the HTTP auth error
1370 password_manager.user = password_manager.password = None
1371 http_handler.reset()
1372 r = opener.open(request_url)
1373 self.assertEqual(len(http_handler.requests), 1)
1374 self.assertFalse(http_handler.requests[0].has_header(auth_header))
1375
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001376
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001377class MiscTests(unittest.TestCase):
1378
1379 def test_build_opener(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001380 class MyHTTPHandler(urllib.request.HTTPHandler): pass
1381 class FooHandler(urllib.request.BaseHandler):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001382 def foo_open(self): pass
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001383 class BarHandler(urllib.request.BaseHandler):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001384 def bar_open(self): pass
1385
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001386 build_opener = urllib.request.build_opener
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001387
1388 o = build_opener(FooHandler, BarHandler)
1389 self.opener_has_handler(o, FooHandler)
1390 self.opener_has_handler(o, BarHandler)
1391
1392 # can take a mix of classes and instances
1393 o = build_opener(FooHandler, BarHandler())
1394 self.opener_has_handler(o, FooHandler)
1395 self.opener_has_handler(o, BarHandler)
1396
1397 # subclasses of default handlers override default handlers
1398 o = build_opener(MyHTTPHandler)
1399 self.opener_has_handler(o, MyHTTPHandler)
1400
1401 # a particular case of overriding: default handlers can be passed
1402 # in explicitly
1403 o = build_opener()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001404 self.opener_has_handler(o, urllib.request.HTTPHandler)
1405 o = build_opener(urllib.request.HTTPHandler)
1406 self.opener_has_handler(o, urllib.request.HTTPHandler)
1407 o = build_opener(urllib.request.HTTPHandler())
1408 self.opener_has_handler(o, urllib.request.HTTPHandler)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001409
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001410 # Issue2670: multiple handlers sharing the same base class
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001411 class MyOtherHTTPHandler(urllib.request.HTTPHandler): pass
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001412 o = build_opener(MyHTTPHandler, MyOtherHTTPHandler)
1413 self.opener_has_handler(o, MyHTTPHandler)
1414 self.opener_has_handler(o, MyOtherHTTPHandler)
1415
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001416 def opener_has_handler(self, opener, handler_class):
Florent Xicluna419e3842010-08-08 16:16:07 +00001417 self.assertTrue(any(h.__class__ == handler_class
1418 for h in opener.handlers))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001419
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001420class RequestTests(unittest.TestCase):
1421
1422 def setUp(self):
1423 self.get = Request("http://www.python.org/~jeremy/")
1424 self.post = Request("http://www.python.org/~jeremy/",
1425 "data",
1426 headers={"X-Test": "test"})
1427
1428 def test_method(self):
1429 self.assertEqual("POST", self.post.get_method())
1430 self.assertEqual("GET", self.get.get_method())
1431
1432 def test_add_data(self):
Florent Xicluna419e3842010-08-08 16:16:07 +00001433 self.assertFalse(self.get.has_data())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001434 self.assertEqual("GET", self.get.get_method())
1435 self.get.add_data("spam")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001436 self.assertTrue(self.get.has_data())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001437 self.assertEqual("POST", self.get.get_method())
1438
1439 def test_get_full_url(self):
1440 self.assertEqual("http://www.python.org/~jeremy/",
1441 self.get.get_full_url())
1442
1443 def test_selector(self):
1444 self.assertEqual("/~jeremy/", self.get.get_selector())
1445 req = Request("http://www.python.org/")
1446 self.assertEqual("/", req.get_selector())
1447
1448 def test_get_type(self):
1449 self.assertEqual("http", self.get.get_type())
1450
1451 def test_get_host(self):
1452 self.assertEqual("www.python.org", self.get.get_host())
1453
1454 def test_get_host_unquote(self):
1455 req = Request("http://www.%70ython.org/")
1456 self.assertEqual("www.python.org", req.get_host())
1457
1458 def test_proxy(self):
Florent Xicluna419e3842010-08-08 16:16:07 +00001459 self.assertFalse(self.get.has_proxy())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001460 self.get.set_proxy("www.perl.org", "http")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001461 self.assertTrue(self.get.has_proxy())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001462 self.assertEqual("www.python.org", self.get.get_origin_req_host())
1463 self.assertEqual("www.perl.org", self.get.get_host())
1464
Senthil Kumarand95cc752010-08-08 11:27:53 +00001465 def test_wrapped_url(self):
1466 req = Request("<URL:http://www.python.org>")
1467 self.assertEqual("www.python.org", req.get_host())
1468
Senthil Kumaran26430412011-04-13 07:01:19 +08001469 def test_url_fragment(self):
Senthil Kumarand95cc752010-08-08 11:27:53 +00001470 req = Request("http://www.python.org/?qs=query#fragment=true")
1471 self.assertEqual("/?qs=query", req.get_selector())
1472 req = Request("http://www.python.org/#fun=true")
1473 self.assertEqual("/", req.get_selector())
1474
Senthil Kumaran26430412011-04-13 07:01:19 +08001475 # Issue 11703: geturl() omits fragment in the original URL.
1476 url = 'http://docs.python.org/library/urllib2.html#OK'
1477 req = Request(url)
1478 self.assertEqual(req.get_full_url(), url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001479
Jason R. Coombsaa204db2011-11-07 10:50:32 -05001480def test_HTTPError_interface():
1481 """
1482 Issue 13211 reveals that HTTPError didn't implement the URLError
1483 interface even though HTTPError is a subclass of URLError.
1484
Jason R. Coombs7ff21d72011-12-03 23:18:11 -05001485 >>> msg = 'something bad happened'
1486 >>> url = code = hdrs = fp = None
Jason R. Coombs9c3895f2011-12-04 08:14:18 -05001487 >>> err = urllib.error.HTTPError(url, code, msg, hdrs, fp)
Jason R. Coombsaa204db2011-11-07 10:50:32 -05001488 >>> assert hasattr(err, 'reason')
1489 >>> err.reason
1490 'something bad happened'
1491 """
1492
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001493def test_main(verbose=None):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001494 from test import test_urllib2
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001495 support.run_doctest(test_urllib2, verbose)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001496 support.run_doctest(urllib.request, verbose)
Andrew M. Kuchlingbd3200f2004-06-29 13:15:46 +00001497 tests = (TrivialTests,
1498 OpenerDirectorTests,
1499 HandlerTests,
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001500 MiscTests,
1501 RequestTests)
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001502 support.run_unittest(*tests)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001503
1504if __name__ == "__main__":
1505 test_main(verbose=True)