blob: 33f90f48ca6eb8b98e67e5353e4403dbc7fa0c1f [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
Senthil Kumarand281c732013-04-09 06:00:16 -070053 f.read()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000054 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
Senthil Kumaran843fae92013-03-19 13:43:42 -070067 def test_URLError_reasonstr(self):
68 err = urllib.error.URLError('reason')
69 self.assertIn(err.reason, str(err))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000070
Senthil Kumarand281c732013-04-09 06:00:16 -070071class RequestHdrsTests(unittest.TestCase):
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000072
Senthil Kumarand281c732013-04-09 06:00:16 -070073 def test_request_headers_dict(self):
74 """
75 The Request.headers dictionary is not a documented interface. It
76 should stay that way, because the complete set of headers are only
77 accessible through the .get_header(), .has_header(), .header_items()
78 interface. However, .headers pre-dates those methods, and so real code
79 will be using the dictionary.
80
81 The introduction in 2.4 of those methods was a mistake for the same
82 reason: code that previously saw all (urllib2 user)-provided headers in
83 .headers now sees only a subset.
84
85 """
86 url = "http://example.com"
87 self.assertEqual(Request(url,
88 headers={"Spam-eggs": "blah"}
89 ).headers["Spam-eggs"], "blah")
90 self.assertEqual(Request(url,
91 headers={"spam-EggS": "blah"}
92 ).headers["Spam-eggs"], "blah")
93
94 def test_request_headers_methods(self):
95 """
96 Note the case normalization of header names here, to
97 .capitalize()-case. This should be preserved for
98 backwards-compatibility. (In the HTTP case, normalization to
99 .title()-case is done by urllib2 before sending headers to
100 http.client).
101
102 Note that e.g. r.has_header("spam-EggS") is currently False, and
103 r.get_header("spam-EggS") returns None, but that could be changed in
104 future.
105
106 Method r.remove_header should remove items both from r.headers and
107 r.unredirected_hdrs dictionaries
108 """
109 url = "http://example.com"
110 req = Request(url, headers={"Spam-eggs": "blah"})
111 self.assertTrue(req.has_header("Spam-eggs"))
112 self.assertEqual(req.header_items(), [('Spam-eggs', 'blah')])
113
114 req.add_header("Foo-Bar", "baz")
115 self.assertEqual(sorted(req.header_items()),
116 [('Foo-bar', 'baz'), ('Spam-eggs', 'blah')])
117 self.assertFalse(req.has_header("Not-there"))
118 self.assertIsNone(req.get_header("Not-there"))
119 self.assertEqual(req.get_header("Not-there", "default"), "default")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000120
121
Senthil Kumarand281c732013-04-09 06:00:16 -0700122 def test_password_manager(self):
123 mgr = urllib.request.HTTPPasswordMgr()
124 add = mgr.add_password
125 find_user_pass = mgr.find_user_password
126 add("Some Realm", "http://example.com/", "joe", "password")
127 add("Some Realm", "http://example.com/ni", "ni", "ni")
128 add("c", "http://example.com/foo", "foo", "ni")
129 add("c", "http://example.com/bar", "bar", "nini")
130 add("b", "http://example.com/", "first", "blah")
131 add("b", "http://example.com/", "second", "spam")
132 add("a", "http://example.com", "1", "a")
133 add("Some Realm", "http://c.example.com:3128", "3", "c")
134 add("Some Realm", "d.example.com", "4", "d")
135 add("Some Realm", "e.example.com:3128", "5", "e")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000136
Senthil Kumarand281c732013-04-09 06:00:16 -0700137 self.assertEqual(find_user_pass("Some Realm", "example.com"),
138 ('joe', 'password'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000139
Senthil Kumarand281c732013-04-09 06:00:16 -0700140 #self.assertEqual(find_user_pass("Some Realm", "http://example.com/ni"),
141 # ('ni', 'ni'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000142
Senthil Kumarand281c732013-04-09 06:00:16 -0700143 self.assertEqual(find_user_pass("Some Realm", "http://example.com"),
144 ('joe', 'password'))
145 self.assertEqual(find_user_pass("Some Realm", "http://example.com/"),
146 ('joe', 'password'))
147 self.assertEqual(
148 find_user_pass("Some Realm", "http://example.com/spam"),
149 ('joe', 'password'))
150 self.assertEqual(
151 find_user_pass("Some Realm", "http://example.com/spam/spam"),
152 ('joe', 'password'))
153 self.assertEqual(find_user_pass("c", "http://example.com/foo"),
154 ('foo', 'ni'))
155 self.assertEqual(find_user_pass("c", "http://example.com/bar"),
156 ('bar', 'nini'))
157 self.assertEqual(find_user_pass("b", "http://example.com/"),
158 ('second', 'spam'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000159
Senthil Kumarand281c732013-04-09 06:00:16 -0700160 # No special relationship between a.example.com and example.com:
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000161
Senthil Kumarand281c732013-04-09 06:00:16 -0700162 self.assertEqual(find_user_pass("a", "http://example.com/"),
163 ('1', 'a'))
164 self.assertEqual(find_user_pass("a", "http://a.example.com/"),
165 (None, None))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000166
Senthil Kumarand281c732013-04-09 06:00:16 -0700167 # Ports:
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000168
Senthil Kumarand281c732013-04-09 06:00:16 -0700169 self.assertEqual(find_user_pass("Some Realm", "c.example.com"),
170 (None, None))
171 self.assertEqual(find_user_pass("Some Realm", "c.example.com:3128"),
172 ('3', 'c'))
173 self.assertEqual(
174 find_user_pass("Some Realm", "http://c.example.com:3128"),
175 ('3', 'c'))
176 self.assertEqual(find_user_pass("Some Realm", "d.example.com"),
177 ('4', 'd'))
178 self.assertEqual(find_user_pass("Some Realm", "e.example.com:3128"),
179 ('5', 'e'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000180
Senthil Kumarand281c732013-04-09 06:00:16 -0700181 def test_password_manager_default_port(self):
182 """
183 The point to note here is that we can't guess the default port if
184 there's no scheme. This applies to both add_password and
185 find_user_password.
186 """
187 mgr = urllib.request.HTTPPasswordMgr()
188 add = mgr.add_password
189 find_user_pass = mgr.find_user_password
190 add("f", "http://g.example.com:80", "10", "j")
191 add("g", "http://h.example.com", "11", "k")
192 add("h", "i.example.com:80", "12", "l")
193 add("i", "j.example.com", "13", "m")
194 self.assertEqual(find_user_pass("f", "g.example.com:100"),
195 (None, None))
196 self.assertEqual(find_user_pass("f", "g.example.com:80"),
197 ('10', 'j'))
198 self.assertEqual(find_user_pass("f", "g.example.com"),
199 (None, None))
200 self.assertEqual(find_user_pass("f", "http://g.example.com:100"),
201 (None, None))
202 self.assertEqual(find_user_pass("f", "http://g.example.com:80"),
203 ('10', 'j'))
204 self.assertEqual(find_user_pass("f", "http://g.example.com"),
205 ('10', 'j'))
206 self.assertEqual(find_user_pass("g", "h.example.com"), ('11', 'k'))
207 self.assertEqual(find_user_pass("g", "h.example.com:80"), ('11', 'k'))
208 self.assertEqual(find_user_pass("g", "http://h.example.com:80"),
209 ('11', 'k'))
210 self.assertEqual(find_user_pass("h", "i.example.com"), (None, None))
211 self.assertEqual(find_user_pass("h", "i.example.com:80"), ('12', 'l'))
212 self.assertEqual(find_user_pass("h", "http://i.example.com:80"),
213 ('12', 'l'))
214 self.assertEqual(find_user_pass("i", "j.example.com"), ('13', 'm'))
215 self.assertEqual(find_user_pass("i", "j.example.com:80"),
216 (None, None))
217 self.assertEqual(find_user_pass("i", "http://j.example.com"),
218 ('13', 'm'))
219 self.assertEqual(find_user_pass("i", "http://j.example.com:80"),
220 (None, None))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000221
222
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000223class MockOpener:
224 addheaders = []
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000225 def open(self, req, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
226 self.req, self.data, self.timeout = req, data, timeout
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000227 def error(self, proto, *args):
228 self.proto, self.args = proto, args
229
230class MockFile:
231 def read(self, count=None): pass
232 def readline(self, count=None): pass
233 def close(self): pass
234
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000235class MockHeaders(dict):
236 def getheaders(self, name):
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000237 return list(self.values())
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000238
Guido van Rossum34d19282007-08-09 01:03:29 +0000239class MockResponse(io.StringIO):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000240 def __init__(self, code, msg, headers, data, url=None):
Guido van Rossum34d19282007-08-09 01:03:29 +0000241 io.StringIO.__init__(self, data)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000242 self.code, self.msg, self.headers, self.url = code, msg, headers, url
243 def info(self):
244 return self.headers
245 def geturl(self):
246 return self.url
247
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000248class MockCookieJar:
249 def add_cookie_header(self, request):
250 self.ach_req = request
251 def extract_cookies(self, response, request):
252 self.ec_req, self.ec_r = request, response
253
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000254class FakeMethod:
255 def __init__(self, meth_name, action, handle):
256 self.meth_name = meth_name
257 self.handle = handle
258 self.action = action
259 def __call__(self, *args):
260 return self.handle(self.meth_name, self.action, *args)
261
Senthil Kumaran47fff872009-12-20 07:10:31 +0000262class MockHTTPResponse(io.IOBase):
263 def __init__(self, fp, msg, status, reason):
264 self.fp = fp
265 self.msg = msg
266 self.status = status
267 self.reason = reason
268 self.code = 200
269
270 def read(self):
271 return ''
272
273 def info(self):
274 return {}
275
276 def geturl(self):
277 return self.url
278
279
280class MockHTTPClass:
281 def __init__(self):
282 self.level = 0
283 self.req_headers = []
284 self.data = None
285 self.raise_on_endheaders = False
286 self._tunnel_headers = {}
287
288 def __call__(self, host, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
289 self.host = host
290 self.timeout = timeout
291 return self
292
293 def set_debuglevel(self, level):
294 self.level = level
295
296 def set_tunnel(self, host, port=None, headers=None):
297 self._tunnel_host = host
298 self._tunnel_port = port
299 if headers:
300 self._tunnel_headers = headers
301 else:
302 self._tunnel_headers.clear()
303
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000304 def request(self, method, url, body=None, headers=None):
Senthil Kumaran47fff872009-12-20 07:10:31 +0000305 self.method = method
306 self.selector = url
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000307 if headers is not None:
308 self.req_headers += headers.items()
Senthil Kumaran47fff872009-12-20 07:10:31 +0000309 self.req_headers.sort()
310 if body:
311 self.data = body
312 if self.raise_on_endheaders:
313 import socket
314 raise socket.error()
315 def getresponse(self):
316 return MockHTTPResponse(MockFile(), {}, 200, "OK")
317
Victor Stinnera4c45d72011-06-17 14:01:18 +0200318 def close(self):
319 pass
320
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000321class MockHandler:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000322 # useful for testing handler machinery
323 # see add_ordered_mock_handlers() docstring
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000324 handler_order = 500
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000325 def __init__(self, methods):
326 self._define_methods(methods)
327 def _define_methods(self, methods):
328 for spec in methods:
329 if len(spec) == 2: name, action = spec
330 else: name, action = spec, None
331 meth = FakeMethod(name, action, self.handle)
332 setattr(self.__class__, name, meth)
333 def handle(self, fn_name, action, *args, **kwds):
334 self.parent.calls.append((self, fn_name, args, kwds))
335 if action is None:
336 return None
337 elif action == "return self":
338 return self
339 elif action == "return response":
340 res = MockResponse(200, "OK", {}, "")
341 return res
342 elif action == "return request":
343 return Request("http://blah/")
344 elif action.startswith("error"):
345 code = action[action.rfind(" ")+1:]
346 try:
347 code = int(code)
348 except ValueError:
349 pass
350 res = MockResponse(200, "OK", {}, "")
351 return self.parent.error("http", args[0], res, code, "", {})
352 elif action == "raise":
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000353 raise urllib.error.URLError("blah")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000354 assert False
355 def close(self): pass
356 def add_parent(self, parent):
357 self.parent = parent
358 self.parent.calls = []
359 def __lt__(self, other):
360 if not hasattr(other, "handler_order"):
361 # No handler_order, leave in original order. Yuck.
362 return True
363 return self.handler_order < other.handler_order
364
365def add_ordered_mock_handlers(opener, meth_spec):
366 """Create MockHandlers and add them to an OpenerDirector.
367
368 meth_spec: list of lists of tuples and strings defining methods to define
369 on handlers. eg:
370
371 [["http_error", "ftp_open"], ["http_open"]]
372
373 defines methods .http_error() and .ftp_open() on one handler, and
374 .http_open() on another. These methods just record their arguments and
375 return None. Using a tuple instead of a string causes the method to
376 perform some action (see MockHandler.handle()), eg:
377
378 [["http_error"], [("http_open", "return request")]]
379
380 defines .http_error() on one handler (which simply returns None), and
381 .http_open() on another handler, which returns a Request object.
382
383 """
384 handlers = []
385 count = 0
386 for meths in meth_spec:
387 class MockHandlerSubclass(MockHandler): pass
388 h = MockHandlerSubclass(meths)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000389 h.handler_order += count
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000390 h.add_parent(opener)
391 count = count + 1
392 handlers.append(h)
393 opener.add_handler(h)
394 return handlers
395
Thomas Wouters477c8d52006-05-27 19:21:47 +0000396def build_test_opener(*handler_instances):
397 opener = OpenerDirector()
398 for h in handler_instances:
399 opener.add_handler(h)
400 return opener
401
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000402class MockHTTPHandler(urllib.request.BaseHandler):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000403 # useful for testing redirections and auth
404 # sends supplied headers and code as first response
405 # sends 200 OK as second response
406 def __init__(self, code, headers):
407 self.code = code
408 self.headers = headers
409 self.reset()
410 def reset(self):
411 self._count = 0
412 self.requests = []
413 def http_open(self, req):
Barry Warsaw820c1202008-06-12 04:06:45 +0000414 import email, http.client, copy
Thomas Wouters477c8d52006-05-27 19:21:47 +0000415 self.requests.append(copy.deepcopy(req))
416 if self._count == 0:
417 self._count = self._count + 1
Georg Brandl24420152008-05-26 16:32:26 +0000418 name = http.client.responses[self.code]
Barry Warsaw820c1202008-06-12 04:06:45 +0000419 msg = email.message_from_string(self.headers)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000420 return self.parent.error(
421 "http", req, MockFile(), self.code, name, msg)
422 else:
423 self.req = req
Barry Warsaw820c1202008-06-12 04:06:45 +0000424 msg = email.message_from_string("\r\n\r\n")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000425 return MockResponse(200, "OK", msg, "", req.get_full_url())
426
Senthil Kumaran47fff872009-12-20 07:10:31 +0000427class MockHTTPSHandler(urllib.request.AbstractHTTPHandler):
428 # Useful for testing the Proxy-Authorization request by verifying the
429 # properties of httpcon
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000430
431 def __init__(self):
432 urllib.request.AbstractHTTPHandler.__init__(self)
433 self.httpconn = MockHTTPClass()
434
Senthil Kumaran47fff872009-12-20 07:10:31 +0000435 def https_open(self, req):
436 return self.do_open(self.httpconn, req)
437
Thomas Wouters477c8d52006-05-27 19:21:47 +0000438class MockPasswordManager:
439 def add_password(self, realm, uri, user, password):
440 self.realm = realm
441 self.url = uri
442 self.user = user
443 self.password = password
444 def find_user_password(self, realm, authuri):
445 self.target_realm = realm
446 self.target_url = authuri
447 return self.user, self.password
448
449
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000450class OpenerDirectorTests(unittest.TestCase):
451
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000452 def test_add_non_handler(self):
453 class NonHandler(object):
454 pass
455 self.assertRaises(TypeError,
456 OpenerDirector().add_handler, NonHandler())
457
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000458 def test_badly_named_methods(self):
459 # test work-around for three methods that accidentally follow the
460 # naming conventions for handler methods
461 # (*_open() / *_request() / *_response())
462
463 # These used to call the accidentally-named methods, causing a
464 # TypeError in real code; here, returning self from these mock
465 # methods would either cause no exception, or AttributeError.
466
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000467 from urllib.error import URLError
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000468
469 o = OpenerDirector()
470 meth_spec = [
471 [("do_open", "return self"), ("proxy_open", "return self")],
472 [("redirect_request", "return self")],
473 ]
Senthil Kumarand281c732013-04-09 06:00:16 -0700474 add_ordered_mock_handlers(o, meth_spec)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000475 o.add_handler(urllib.request.UnknownHandler())
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000476 for scheme in "do", "proxy", "redirect":
477 self.assertRaises(URLError, o.open, scheme+"://example.com/")
478
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000479 def test_handled(self):
480 # handler returning non-None means no more handlers will be called
481 o = OpenerDirector()
482 meth_spec = [
483 ["http_open", "ftp_open", "http_error_302"],
484 ["ftp_open"],
485 [("http_open", "return self")],
486 [("http_open", "return self")],
487 ]
488 handlers = add_ordered_mock_handlers(o, meth_spec)
489
490 req = Request("http://example.com/")
491 r = o.open(req)
492 # Second .http_open() gets called, third doesn't, since second returned
493 # non-None. Handlers without .http_open() never get any methods called
494 # on them.
495 # In fact, second mock handler defining .http_open() returns self
496 # (instead of response), which becomes the OpenerDirector's return
497 # value.
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000498 self.assertEqual(r, handlers[2])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000499 calls = [(handlers[0], "http_open"), (handlers[2], "http_open")]
500 for expected, got in zip(calls, o.calls):
501 handler, name, args, kwds = got
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000502 self.assertEqual((handler, name), expected)
503 self.assertEqual(args, (req,))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000504
505 def test_handler_order(self):
506 o = OpenerDirector()
507 handlers = []
508 for meths, handler_order in [
509 ([("http_open", "return self")], 500),
510 (["http_open"], 0),
511 ]:
512 class MockHandlerSubclass(MockHandler): pass
513 h = MockHandlerSubclass(meths)
514 h.handler_order = handler_order
515 handlers.append(h)
516 o.add_handler(h)
517
Senthil Kumarand281c732013-04-09 06:00:16 -0700518 o.open("http://example.com/")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000519 # handlers called in reverse order, thanks to their sort order
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000520 self.assertEqual(o.calls[0][0], handlers[1])
521 self.assertEqual(o.calls[1][0], handlers[0])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000522
523 def test_raise(self):
524 # raising URLError stops processing of request
525 o = OpenerDirector()
526 meth_spec = [
527 [("http_open", "raise")],
528 [("http_open", "return self")],
529 ]
530 handlers = add_ordered_mock_handlers(o, meth_spec)
531
532 req = Request("http://example.com/")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000533 self.assertRaises(urllib.error.URLError, o.open, req)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000534 self.assertEqual(o.calls, [(handlers[0], "http_open", (req,), {})])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000535
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000536 def test_http_error(self):
537 # XXX http_error_default
538 # http errors are a special case
539 o = OpenerDirector()
540 meth_spec = [
541 [("http_open", "error 302")],
542 [("http_error_400", "raise"), "http_open"],
543 [("http_error_302", "return response"), "http_error_303",
544 "http_error"],
545 [("http_error_302")],
546 ]
547 handlers = add_ordered_mock_handlers(o, meth_spec)
548
549 class Unknown:
550 def __eq__(self, other): return True
551
552 req = Request("http://example.com/")
Senthil Kumarand281c732013-04-09 06:00:16 -0700553 o.open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000554 assert len(o.calls) == 2
555 calls = [(handlers[0], "http_open", (req,)),
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000556 (handlers[2], "http_error_302",
557 (req, Unknown(), 302, "", {}))]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000558 for expected, got in zip(calls, o.calls):
559 handler, method_name, args = expected
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000560 self.assertEqual((handler, method_name), got[:2])
561 self.assertEqual(args, got[2])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000562
Senthil Kumaran38b968b92012-03-14 13:43:53 -0700563
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000564 def test_processors(self):
565 # *_request / *_response methods get called appropriately
566 o = OpenerDirector()
567 meth_spec = [
568 [("http_request", "return request"),
569 ("http_response", "return response")],
570 [("http_request", "return request"),
571 ("http_response", "return response")],
572 ]
573 handlers = add_ordered_mock_handlers(o, meth_spec)
574
575 req = Request("http://example.com/")
Senthil Kumarand281c732013-04-09 06:00:16 -0700576 o.open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000577 # processor methods are called on *all* handlers that define them,
578 # not just the first handler that handles the request
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000579 calls = [
580 (handlers[0], "http_request"), (handlers[1], "http_request"),
581 (handlers[0], "http_response"), (handlers[1], "http_response")]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000582
583 for i, (handler, name, args, kwds) in enumerate(o.calls):
584 if i < 2:
585 # *_request
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000586 self.assertEqual((handler, name), calls[i])
587 self.assertEqual(len(args), 1)
Ezio Melottie9615932010-01-24 19:26:24 +0000588 self.assertIsInstance(args[0], Request)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000589 else:
590 # *_response
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000591 self.assertEqual((handler, name), calls[i])
592 self.assertEqual(len(args), 2)
Ezio Melottie9615932010-01-24 19:26:24 +0000593 self.assertIsInstance(args[0], Request)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000594 # response from opener.open is None, because there's no
595 # handler that defines http_open to handle it
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000596 self.assertTrue(args[1] is None or
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000597 isinstance(args[1], MockResponse))
598
Senthil Kumaran38b968b92012-03-14 13:43:53 -0700599 def test_method_deprecations(self):
600 req = Request("http://www.example.com")
Senthil Kumaran08bd4aa2012-04-11 23:05:49 +0800601
Senthil Kumaran80a133b2012-04-12 19:28:07 +0800602 with self.assertWarns(DeprecationWarning):
Senthil Kumaran38b968b92012-03-14 13:43:53 -0700603 req.add_data("data")
Senthil Kumaran80a133b2012-04-12 19:28:07 +0800604 with self.assertWarns(DeprecationWarning):
Senthil Kumaran38b968b92012-03-14 13:43:53 -0700605 req.get_data()
Senthil Kumaran80a133b2012-04-12 19:28:07 +0800606 with self.assertWarns(DeprecationWarning):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -0700607 req.has_data()
608 with self.assertWarns(DeprecationWarning):
Senthil Kumaran38b968b92012-03-14 13:43:53 -0700609 req.get_host()
Senthil Kumaran80a133b2012-04-12 19:28:07 +0800610 with self.assertWarns(DeprecationWarning):
Senthil Kumaran38b968b92012-03-14 13:43:53 -0700611 req.get_selector()
Senthil Kumaran80a133b2012-04-12 19:28:07 +0800612 with self.assertWarns(DeprecationWarning):
Senthil Kumaran38b968b92012-03-14 13:43:53 -0700613 req.is_unverifiable()
Senthil Kumaran80a133b2012-04-12 19:28:07 +0800614 with self.assertWarns(DeprecationWarning):
Senthil Kumaran38b968b92012-03-14 13:43:53 -0700615 req.get_origin_req_host()
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -0700616 with self.assertWarns(DeprecationWarning):
617 req.get_type()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000618
Senthil Kumaran08bd4aa2012-04-11 23:05:49 +0800619
Tim Peters58eb11c2004-01-18 20:29:55 +0000620def sanepathname2url(path):
Victor Stinner6c6f8512010-08-07 10:09:35 +0000621 try:
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000622 path.encode("utf-8")
Victor Stinner6c6f8512010-08-07 10:09:35 +0000623 except UnicodeEncodeError:
624 raise unittest.SkipTest("path is not encodable to utf8")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000625 urlpath = urllib.request.pathname2url(path)
Tim Peters58eb11c2004-01-18 20:29:55 +0000626 if os.name == "nt" and urlpath.startswith("///"):
627 urlpath = urlpath[2:]
628 # XXX don't ask me about the mac...
629 return urlpath
630
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000631class HandlerTests(unittest.TestCase):
632
633 def test_ftp(self):
634 class MockFTPWrapper:
635 def __init__(self, data): self.data = data
636 def retrfile(self, filename, filetype):
637 self.filename, self.filetype = filename, filetype
Guido van Rossum34d19282007-08-09 01:03:29 +0000638 return io.StringIO(self.data), len(self.data)
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +0200639 def close(self): pass
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000640
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000641 class NullFTPHandler(urllib.request.FTPHandler):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000642 def __init__(self, data): self.data = data
Georg Brandlf78e02b2008-06-10 17:40:04 +0000643 def connect_ftp(self, user, passwd, host, port, dirs,
644 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000645 self.user, self.passwd = user, passwd
646 self.host, self.port = host, port
647 self.dirs = dirs
648 self.ftpwrapper = MockFTPWrapper(self.data)
649 return self.ftpwrapper
650
Georg Brandlf78e02b2008-06-10 17:40:04 +0000651 import ftplib
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000652 data = "rheum rhaponicum"
653 h = NullFTPHandler(data)
Senthil Kumarand281c732013-04-09 06:00:16 -0700654 h.parent = MockOpener()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000655
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000656 for url, host, port, user, passwd, type_, dirs, filename, mimetype in [
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000657 ("ftp://localhost/foo/bar/baz.html",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000658 "localhost", ftplib.FTP_PORT, "", "", "I",
659 ["foo", "bar"], "baz.html", "text/html"),
660 ("ftp://parrot@localhost/foo/bar/baz.html",
661 "localhost", ftplib.FTP_PORT, "parrot", "", "I",
662 ["foo", "bar"], "baz.html", "text/html"),
663 ("ftp://%25parrot@localhost/foo/bar/baz.html",
664 "localhost", ftplib.FTP_PORT, "%parrot", "", "I",
665 ["foo", "bar"], "baz.html", "text/html"),
666 ("ftp://%2542parrot@localhost/foo/bar/baz.html",
667 "localhost", ftplib.FTP_PORT, "%42parrot", "", "I",
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000668 ["foo", "bar"], "baz.html", "text/html"),
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000669 ("ftp://localhost:80/foo/bar/",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000670 "localhost", 80, "", "", "D",
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000671 ["foo", "bar"], "", None),
672 ("ftp://localhost/baz.gif;type=a",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000673 "localhost", ftplib.FTP_PORT, "", "", "A",
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000674 [], "baz.gif", None), # XXX really this should guess image/gif
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000675 ]:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000676 req = Request(url)
677 req.timeout = None
678 r = h.ftp_open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000679 # ftp authentication not yet implemented by FTPHandler
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000680 self.assertEqual(h.user, user)
681 self.assertEqual(h.passwd, passwd)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000682 self.assertEqual(h.host, socket.gethostbyname(host))
683 self.assertEqual(h.port, port)
684 self.assertEqual(h.dirs, dirs)
685 self.assertEqual(h.ftpwrapper.filename, filename)
686 self.assertEqual(h.ftpwrapper.filetype, type_)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000687 headers = r.info()
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000688 self.assertEqual(headers.get("Content-type"), mimetype)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000689 self.assertEqual(int(headers["Content-length"]), len(data))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000690
691 def test_file(self):
Benjamin Petersona0c0a4a2008-06-12 22:15:50 +0000692 import email.utils, socket
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000693 h = urllib.request.FileHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000694 o = h.parent = MockOpener()
695
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000696 TESTFN = support.TESTFN
Tim Peters58eb11c2004-01-18 20:29:55 +0000697 urlpath = sanepathname2url(os.path.abspath(TESTFN))
Guido van Rossum6a2ccd02007-07-16 20:51:57 +0000698 towrite = b"hello, world\n"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000699 urls = [
Tim Peters58eb11c2004-01-18 20:29:55 +0000700 "file://localhost%s" % urlpath,
701 "file://%s" % urlpath,
702 "file://%s%s" % (socket.gethostbyname('localhost'), urlpath),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000703 ]
704 try:
705 localaddr = socket.gethostbyname(socket.gethostname())
706 except socket.gaierror:
707 localaddr = ''
708 if localaddr:
709 urls.append("file://%s%s" % (localaddr, urlpath))
710
711 for url in urls:
Tim Peters58eb11c2004-01-18 20:29:55 +0000712 f = open(TESTFN, "wb")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000713 try:
714 try:
715 f.write(towrite)
716 finally:
717 f.close()
718
719 r = h.file_open(Request(url))
720 try:
721 data = r.read()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000722 headers = r.info()
Senthil Kumaran4fbed102010-05-08 03:29:09 +0000723 respurl = r.geturl()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000724 finally:
725 r.close()
Tim Peters58eb11c2004-01-18 20:29:55 +0000726 stats = os.stat(TESTFN)
Benjamin Petersona0c0a4a2008-06-12 22:15:50 +0000727 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000728 finally:
729 os.remove(TESTFN)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000730 self.assertEqual(data, towrite)
731 self.assertEqual(headers["Content-type"], "text/plain")
732 self.assertEqual(headers["Content-length"], "13")
Tim Peters58eb11c2004-01-18 20:29:55 +0000733 self.assertEqual(headers["Last-modified"], modified)
Senthil Kumaran4fbed102010-05-08 03:29:09 +0000734 self.assertEqual(respurl, url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000735
736 for url in [
Tim Peters58eb11c2004-01-18 20:29:55 +0000737 "file://localhost:80%s" % urlpath,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000738 "file:///file_does_not_exist.txt",
739 "file://%s:80%s/%s" % (socket.gethostbyname('localhost'),
740 os.getcwd(), TESTFN),
741 "file://somerandomhost.ontheinternet.com%s/%s" %
742 (os.getcwd(), TESTFN),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000743 ]:
744 try:
Tim Peters58eb11c2004-01-18 20:29:55 +0000745 f = open(TESTFN, "wb")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000746 try:
747 f.write(towrite)
748 finally:
749 f.close()
750
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000751 self.assertRaises(urllib.error.URLError,
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000752 h.file_open, Request(url))
753 finally:
754 os.remove(TESTFN)
755
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000756 h = urllib.request.FileHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000757 o = h.parent = MockOpener()
758 # XXXX why does // mean ftp (and /// mean not ftp!), and where
759 # is file: scheme specified? I think this is really a bug, and
760 # what was intended was to distinguish between URLs like:
761 # file:/blah.txt (a file)
762 # file://localhost/blah.txt (a file)
763 # file:///blah.txt (a file)
764 # file://ftp.example.com/blah.txt (an ftp URL)
765 for url, ftp in [
Senthil Kumaran383c32d2010-10-14 11:57:35 +0000766 ("file://ftp.example.com//foo.txt", False),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000767 ("file://ftp.example.com///foo.txt", False),
768# XXXX bug: fails with OSError, should be URLError
769 ("file://ftp.example.com/foo.txt", False),
Senthil Kumaran383c32d2010-10-14 11:57:35 +0000770 ("file://somehost//foo/something.txt", False),
Senthil Kumaran2ef16322010-07-11 03:12:43 +0000771 ("file://localhost//foo/something.txt", False),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000772 ]:
773 req = Request(url)
774 try:
775 h.file_open(req)
776 # XXXX remove OSError when bug fixed
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000777 except (urllib.error.URLError, OSError):
Florent Xicluna419e3842010-08-08 16:16:07 +0000778 self.assertFalse(ftp)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000779 else:
Florent Xicluna419e3842010-08-08 16:16:07 +0000780 self.assertIs(o.req, req)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000781 self.assertEqual(req.type, "ftp")
Łukasz Langad7e81cc2011-01-09 18:18:53 +0000782 self.assertEqual(req.type == "ftp", ftp)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000783
784 def test_http(self):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000785
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000786 h = urllib.request.AbstractHTTPHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000787 o = h.parent = MockOpener()
788
789 url = "http://example.com/"
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000790 for method, data in [("GET", None), ("POST", b"blah")]:
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000791 req = Request(url, data, {"Foo": "bar"})
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000792 req.timeout = None
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000793 req.add_unredirected_header("Spam", "eggs")
794 http = MockHTTPClass()
795 r = h.do_open(http, req)
796
797 # result attributes
798 r.read; r.readline # wrapped MockFile methods
799 r.info; r.geturl # addinfourl methods
800 r.code, r.msg == 200, "OK" # added from MockHTTPClass.getreply()
801 hdrs = r.info()
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000802 hdrs.get; hdrs.__contains__ # r.info() gives dict from .getreply()
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000803 self.assertEqual(r.geturl(), url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000804
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000805 self.assertEqual(http.host, "example.com")
806 self.assertEqual(http.level, 0)
807 self.assertEqual(http.method, method)
808 self.assertEqual(http.selector, "/")
809 self.assertEqual(http.req_headers,
Jeremy Hyltonb3ee6f92004-02-24 19:40:35 +0000810 [("Connection", "close"),
811 ("Foo", "bar"), ("Spam", "eggs")])
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000812 self.assertEqual(http.data, data)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000813
814 # check socket.error converted to URLError
815 http.raise_on_endheaders = True
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000816 self.assertRaises(urllib.error.URLError, h.do_open, http, req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000817
Senthil Kumaran29333122011-02-11 11:25:47 +0000818 # Check for TypeError on POST data which is str.
819 req = Request("http://example.com/","badpost")
820 self.assertRaises(TypeError, h.do_request_, req)
821
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000822 # check adding of standard headers
823 o.addheaders = [("Spam", "eggs")]
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000824 for data in b"", None: # POST, GET
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000825 req = Request("http://example.com/", data)
826 r = MockResponse(200, "OK", {}, "")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000827 newreq = h.do_request_(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000828 if data is None: # GET
Benjamin Peterson577473f2010-01-19 00:09:57 +0000829 self.assertNotIn("Content-length", req.unredirected_hdrs)
830 self.assertNotIn("Content-type", req.unredirected_hdrs)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000831 else: # POST
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000832 self.assertEqual(req.unredirected_hdrs["Content-length"], "0")
833 self.assertEqual(req.unredirected_hdrs["Content-type"],
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000834 "application/x-www-form-urlencoded")
835 # XXX the details of Host could be better tested
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000836 self.assertEqual(req.unredirected_hdrs["Host"], "example.com")
837 self.assertEqual(req.unredirected_hdrs["Spam"], "eggs")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000838
839 # don't clobber existing headers
840 req.add_unredirected_header("Content-length", "foo")
841 req.add_unredirected_header("Content-type", "bar")
842 req.add_unredirected_header("Host", "baz")
843 req.add_unredirected_header("Spam", "foo")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000844 newreq = h.do_request_(req)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000845 self.assertEqual(req.unredirected_hdrs["Content-length"], "foo")
846 self.assertEqual(req.unredirected_hdrs["Content-type"], "bar")
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000847 self.assertEqual(req.unredirected_hdrs["Host"], "baz")
848 self.assertEqual(req.unredirected_hdrs["Spam"], "foo")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000849
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000850 # Check iterable body support
851 def iterable_body():
852 yield b"one"
853 yield b"two"
854 yield b"three"
855
856 for headers in {}, {"Content-Length": 11}:
857 req = Request("http://example.com/", iterable_body(), headers)
858 if not headers:
859 # Having an iterable body without a Content-Length should
860 # raise an exception
861 self.assertRaises(ValueError, h.do_request_, req)
862 else:
863 newreq = h.do_request_(req)
864
Senthil Kumaran29333122011-02-11 11:25:47 +0000865 # A file object.
866 # Test only Content-Length attribute of request.
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000867
Senthil Kumaran29333122011-02-11 11:25:47 +0000868 file_obj = io.BytesIO()
869 file_obj.write(b"Something\nSomething\nSomething\n")
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000870
871 for headers in {}, {"Content-Length": 30}:
872 req = Request("http://example.com/", file_obj, headers)
873 if not headers:
874 # Having an iterable body without a Content-Length should
875 # raise an exception
876 self.assertRaises(ValueError, h.do_request_, req)
877 else:
878 newreq = h.do_request_(req)
879 self.assertEqual(int(newreq.get_header('Content-length')),30)
880
881 file_obj.close()
882
883 # array.array Iterable - Content Length is calculated
884
885 iterable_array = array.array("I",[1,2,3,4])
886
887 for headers in {}, {"Content-Length": 16}:
888 req = Request("http://example.com/", iterable_array, headers)
889 newreq = h.do_request_(req)
890 self.assertEqual(int(newreq.get_header('Content-length')),16)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000891
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000892 def test_http_doubleslash(self):
893 # Checks the presence of any unnecessary double slash in url does not
894 # break anything. Previously, a double slash directly after the host
Ezio Melottie130a522011-10-19 10:58:56 +0300895 # could cause incorrect parsing.
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000896 h = urllib.request.AbstractHTTPHandler()
Senthil Kumarand281c732013-04-09 06:00:16 -0700897 h.parent = MockOpener()
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000898
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000899 data = b""
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000900 ds_urls = [
901 "http://example.com/foo/bar/baz.html",
902 "http://example.com//foo/bar/baz.html",
903 "http://example.com/foo//bar/baz.html",
904 "http://example.com/foo/bar//baz.html"
905 ]
906
907 for ds_url in ds_urls:
908 ds_req = Request(ds_url, data)
909
910 # Check whether host is determined correctly if there is no proxy
911 np_ds_req = h.do_request_(ds_req)
912 self.assertEqual(np_ds_req.unredirected_hdrs["Host"],"example.com")
913
914 # Check whether host is determined correctly if there is a proxy
915 ds_req.set_proxy("someproxy:3128",None)
916 p_ds_req = h.do_request_(ds_req)
917 self.assertEqual(p_ds_req.unredirected_hdrs["Host"],"example.com")
918
Senthil Kumaranc2958622010-11-22 04:48:26 +0000919 def test_fixpath_in_weirdurls(self):
920 # Issue4493: urllib2 to supply '/' when to urls where path does not
921 # start with'/'
922
923 h = urllib.request.AbstractHTTPHandler()
Senthil Kumarand281c732013-04-09 06:00:16 -0700924 h.parent = MockOpener()
Senthil Kumaranc2958622010-11-22 04:48:26 +0000925
926 weird_url = 'http://www.python.org?getspam'
927 req = Request(weird_url)
928 newreq = h.do_request_(req)
929 self.assertEqual(newreq.host,'www.python.org')
930 self.assertEqual(newreq.selector,'/?getspam')
931
932 url_without_path = 'http://www.python.org'
933 req = Request(url_without_path)
934 newreq = h.do_request_(req)
935 self.assertEqual(newreq.host,'www.python.org')
936 self.assertEqual(newreq.selector,'')
937
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000938
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000939 def test_errors(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000940 h = urllib.request.HTTPErrorProcessor()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000941 o = h.parent = MockOpener()
942
943 url = "http://example.com/"
944 req = Request(url)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000945 # all 2xx are passed through
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000946 r = MockResponse(200, "OK", {}, "", url)
947 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +0000948 self.assertIs(r, newr)
949 self.assertFalse(hasattr(o, "proto")) # o.error not called
Guido van Rossumd8faa362007-04-27 19:54:29 +0000950 r = MockResponse(202, "Accepted", {}, "", url)
951 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +0000952 self.assertIs(r, newr)
953 self.assertFalse(hasattr(o, "proto")) # o.error not called
Guido van Rossumd8faa362007-04-27 19:54:29 +0000954 r = MockResponse(206, "Partial content", {}, "", url)
955 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +0000956 self.assertIs(r, newr)
957 self.assertFalse(hasattr(o, "proto")) # o.error not called
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000958 # anything else calls o.error (and MockOpener returns None, here)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000959 r = MockResponse(502, "Bad gateway", {}, "", url)
Florent Xicluna419e3842010-08-08 16:16:07 +0000960 self.assertIsNone(h.http_response(req, r))
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000961 self.assertEqual(o.proto, "http") # o.error called
Guido van Rossumd8faa362007-04-27 19:54:29 +0000962 self.assertEqual(o.args, (req, r, 502, "Bad gateway", {}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000963
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000964 def test_cookies(self):
965 cj = MockCookieJar()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000966 h = urllib.request.HTTPCookieProcessor(cj)
Senthil Kumarand281c732013-04-09 06:00:16 -0700967 h.parent = MockOpener()
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000968
969 req = Request("http://example.com/")
970 r = MockResponse(200, "OK", {}, "")
971 newreq = h.http_request(req)
Florent Xicluna419e3842010-08-08 16:16:07 +0000972 self.assertIs(cj.ach_req, req)
973 self.assertIs(cj.ach_req, newreq)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -0700974 self.assertEqual(req.origin_req_host, "example.com")
975 self.assertFalse(req.unverifiable)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000976 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +0000977 self.assertIs(cj.ec_req, req)
978 self.assertIs(cj.ec_r, r)
979 self.assertIs(r, newr)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000980
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000981 def test_redirect(self):
982 from_url = "http://example.com/a.html"
983 to_url = "http://example.com/b.html"
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000984 h = urllib.request.HTTPRedirectHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000985 o = h.parent = MockOpener()
986
987 # ordinary redirect behaviour
988 for code in 301, 302, 303, 307:
989 for data in None, "blah\nblah\n":
990 method = getattr(h, "http_error_%s" % code)
991 req = Request(from_url, data)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000992 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000993 req.add_header("Nonsense", "viking=withhold")
Christian Heimes77c02eb2008-02-09 02:18:51 +0000994 if data is not None:
995 req.add_header("Content-Length", str(len(data)))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000996 req.add_unredirected_header("Spam", "spam")
997 try:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000998 method(req, MockFile(), code, "Blah",
999 MockHeaders({"location": to_url}))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001000 except urllib.error.HTTPError:
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001001 # 307 in response to POST requires user OK
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001002 self.assertTrue(code == 307 and data is not None)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001003 self.assertEqual(o.req.get_full_url(), to_url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001004 try:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001005 self.assertEqual(o.req.get_method(), "GET")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001006 except AttributeError:
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001007 self.assertFalse(o.req.data)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001008
1009 # now it's a GET, there should not be headers regarding content
1010 # (possibly dragged from before being a POST)
1011 headers = [x.lower() for x in o.req.headers]
Benjamin Peterson577473f2010-01-19 00:09:57 +00001012 self.assertNotIn("content-length", headers)
1013 self.assertNotIn("content-type", headers)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001014
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001015 self.assertEqual(o.req.headers["Nonsense"],
1016 "viking=withhold")
Benjamin Peterson577473f2010-01-19 00:09:57 +00001017 self.assertNotIn("Spam", o.req.headers)
1018 self.assertNotIn("Spam", o.req.unredirected_hdrs)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001019
1020 # loop detection
1021 req = Request(from_url)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001022 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001023 def redirect(h, req, url=to_url):
1024 h.http_error_302(req, MockFile(), 302, "Blah",
1025 MockHeaders({"location": url}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001026 # Note that the *original* request shares the same record of
1027 # redirections with the sub-requests caused by the redirections.
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001028
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001029 # detect infinite loop redirect of a URL to itself
1030 req = Request(from_url, origin_req_host="example.com")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001031 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001032 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001033 try:
1034 while 1:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001035 redirect(h, req, "http://example.com/")
1036 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001037 except urllib.error.HTTPError:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001038 # don't stop until max_repeats, because cookies may introduce state
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001039 self.assertEqual(count, urllib.request.HTTPRedirectHandler.max_repeats)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001040
1041 # detect endless non-repeating chain of redirects
1042 req = Request(from_url, origin_req_host="example.com")
1043 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001044 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001045 try:
1046 while 1:
1047 redirect(h, req, "http://example.com/%d" % count)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001048 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001049 except urllib.error.HTTPError:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001050 self.assertEqual(count,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001051 urllib.request.HTTPRedirectHandler.max_redirections)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001052
guido@google.coma119df92011-03-29 11:41:02 -07001053
1054 def test_invalid_redirect(self):
1055 from_url = "http://example.com/a.html"
1056 valid_schemes = ['http','https','ftp']
1057 invalid_schemes = ['file','imap','ldap']
1058 schemeless_url = "example.com/b.html"
1059 h = urllib.request.HTTPRedirectHandler()
1060 o = h.parent = MockOpener()
1061 req = Request(from_url)
1062 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1063
1064 for scheme in invalid_schemes:
1065 invalid_url = scheme + '://' + schemeless_url
1066 self.assertRaises(urllib.error.HTTPError, h.http_error_302,
1067 req, MockFile(), 302, "Security Loophole",
1068 MockHeaders({"location": invalid_url}))
1069
1070 for scheme in valid_schemes:
1071 valid_url = scheme + '://' + schemeless_url
1072 h.http_error_302(req, MockFile(), 302, "That's fine",
1073 MockHeaders({"location": valid_url}))
1074 self.assertEqual(o.req.get_full_url(), valid_url)
1075
Senthil Kumaran6497aa32012-01-04 13:46:59 +08001076 def test_relative_redirect(self):
1077 from_url = "http://example.com/a.html"
1078 relative_url = "/b.html"
1079 h = urllib.request.HTTPRedirectHandler()
1080 o = h.parent = MockOpener()
1081 req = Request(from_url)
1082 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1083
1084 valid_url = urllib.parse.urljoin(from_url,relative_url)
1085 h.http_error_302(req, MockFile(), 302, "That's fine",
1086 MockHeaders({"location": valid_url}))
1087 self.assertEqual(o.req.get_full_url(), valid_url)
1088
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001089 def test_cookie_redirect(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001090 # cookies shouldn't leak into redirected requests
Georg Brandl24420152008-05-26 16:32:26 +00001091 from http.cookiejar import CookieJar
1092 from test.test_http_cookiejar import interact_netscape
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001093
1094 cj = CookieJar()
1095 interact_netscape(cj, "http://www.example.com/", "spam=eggs")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001096 hh = MockHTTPHandler(302, "Location: http://www.cracker.com/\r\n\r\n")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001097 hdeh = urllib.request.HTTPDefaultErrorHandler()
1098 hrh = urllib.request.HTTPRedirectHandler()
1099 cp = urllib.request.HTTPCookieProcessor(cj)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001100 o = build_test_opener(hh, hdeh, hrh, cp)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001101 o.open("http://www.example.com/")
Florent Xicluna419e3842010-08-08 16:16:07 +00001102 self.assertFalse(hh.req.has_header("Cookie"))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001103
Senthil Kumaran26430412011-04-13 07:01:19 +08001104 def test_redirect_fragment(self):
1105 redirected_url = 'http://www.example.com/index.html#OK\r\n\r\n'
1106 hh = MockHTTPHandler(302, 'Location: ' + redirected_url)
1107 hdeh = urllib.request.HTTPDefaultErrorHandler()
1108 hrh = urllib.request.HTTPRedirectHandler()
1109 o = build_test_opener(hh, hdeh, hrh)
1110 fp = o.open('http://www.example.com')
1111 self.assertEqual(fp.geturl(), redirected_url.strip())
1112
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001113 def test_proxy(self):
1114 o = OpenerDirector()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001115 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001116 o.add_handler(ph)
1117 meth_spec = [
1118 [("http_open", "return response")]
1119 ]
1120 handlers = add_ordered_mock_handlers(o, meth_spec)
1121
1122 req = Request("http://acme.example.com/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001123 self.assertEqual(req.host, "acme.example.com")
Senthil Kumarand281c732013-04-09 06:00:16 -07001124 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001125 self.assertEqual(req.host, "proxy.example.com:3128")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001126
1127 self.assertEqual([(handlers[0], "http_open")],
1128 [tup[0:2] for tup in o.calls])
1129
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001130 def test_proxy_no_proxy(self):
1131 os.environ['no_proxy'] = 'python.org'
1132 o = OpenerDirector()
1133 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1134 o.add_handler(ph)
1135 req = Request("http://www.perl.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001136 self.assertEqual(req.host, "www.perl.org")
Senthil Kumarand281c732013-04-09 06:00:16 -07001137 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001138 self.assertEqual(req.host, "proxy.example.com")
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001139 req = Request("http://www.python.org")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001140 self.assertEqual(req.host, "www.python.org")
Senthil Kumarand281c732013-04-09 06:00:16 -07001141 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001142 self.assertEqual(req.host, "www.python.org")
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001143 del os.environ['no_proxy']
1144
Ronald Oussorene72e1612011-03-14 18:15:25 -04001145 def test_proxy_no_proxy_all(self):
1146 os.environ['no_proxy'] = '*'
1147 o = OpenerDirector()
1148 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1149 o.add_handler(ph)
1150 req = Request("http://www.python.org")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001151 self.assertEqual(req.host, "www.python.org")
Senthil Kumarand281c732013-04-09 06:00:16 -07001152 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001153 self.assertEqual(req.host, "www.python.org")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001154 del os.environ['no_proxy']
1155
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001156
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001157 def test_proxy_https(self):
1158 o = OpenerDirector()
1159 ph = urllib.request.ProxyHandler(dict(https="proxy.example.com:3128"))
1160 o.add_handler(ph)
1161 meth_spec = [
1162 [("https_open", "return response")]
1163 ]
1164 handlers = add_ordered_mock_handlers(o, meth_spec)
1165
1166 req = Request("https://www.example.com/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001167 self.assertEqual(req.host, "www.example.com")
Senthil Kumarand281c732013-04-09 06:00:16 -07001168 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001169 self.assertEqual(req.host, "proxy.example.com:3128")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001170 self.assertEqual([(handlers[0], "https_open")],
1171 [tup[0:2] for tup in o.calls])
1172
Senthil Kumaran47fff872009-12-20 07:10:31 +00001173 def test_proxy_https_proxy_authorization(self):
1174 o = OpenerDirector()
1175 ph = urllib.request.ProxyHandler(dict(https='proxy.example.com:3128'))
1176 o.add_handler(ph)
1177 https_handler = MockHTTPSHandler()
1178 o.add_handler(https_handler)
1179 req = Request("https://www.example.com/")
1180 req.add_header("Proxy-Authorization","FooBar")
1181 req.add_header("User-Agent","Grail")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001182 self.assertEqual(req.host, "www.example.com")
Senthil Kumaran47fff872009-12-20 07:10:31 +00001183 self.assertIsNone(req._tunnel_host)
Senthil Kumarand281c732013-04-09 06:00:16 -07001184 o.open(req)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001185 # Verify Proxy-Authorization gets tunneled to request.
1186 # httpsconn req_headers do not have the Proxy-Authorization header but
1187 # the req will have.
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001188 self.assertNotIn(("Proxy-Authorization","FooBar"),
Senthil Kumaran47fff872009-12-20 07:10:31 +00001189 https_handler.httpconn.req_headers)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001190 self.assertIn(("User-Agent","Grail"),
1191 https_handler.httpconn.req_headers)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001192 self.assertIsNotNone(req._tunnel_host)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001193 self.assertEqual(req.host, "proxy.example.com:3128")
Senthil Kumaran47fff872009-12-20 07:10:31 +00001194 self.assertEqual(req.get_header("Proxy-authorization"),"FooBar")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001195
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001196 # TODO: This should be only for OSX
1197 @unittest.skipUnless(sys.platform == 'darwin', "only relevant for OSX")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001198 def test_osx_proxy_bypass(self):
1199 bypass = {
1200 'exclude_simple': False,
1201 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.10',
1202 '10.0/16']
1203 }
1204 # Check hosts that should trigger the proxy bypass
1205 for host in ('foo.bar', 'www.bar.com', '127.0.0.1', '10.10.0.1',
1206 '10.0.0.1'):
1207 self.assertTrue(_proxy_bypass_macosx_sysconf(host, bypass),
1208 'expected bypass of %s to be True' % host)
1209 # Check hosts that should not trigger the proxy bypass
1210 for host in ('abc.foo.bar', 'bar.com', '127.0.0.2', '10.11.0.1', 'test'):
1211 self.assertFalse(_proxy_bypass_macosx_sysconf(host, bypass),
1212 'expected bypass of %s to be False' % host)
1213
1214 # Check the exclude_simple flag
1215 bypass = {'exclude_simple': True, 'exceptions': []}
1216 self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass))
1217
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001218 def test_basic_auth(self, quote_char='"'):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001219 opener = OpenerDirector()
1220 password_manager = MockPasswordManager()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001221 auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001222 realm = "ACME Widget Store"
1223 http_handler = MockHTTPHandler(
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001224 401, 'WWW-Authenticate: Basic realm=%s%s%s\r\n\r\n' %
1225 (quote_char, realm, quote_char) )
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001226 opener.add_handler(auth_handler)
1227 opener.add_handler(http_handler)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001228 self._test_basic_auth(opener, auth_handler, "Authorization",
1229 realm, http_handler, password_manager,
1230 "http://acme.example.com/protected",
1231 "http://acme.example.com/protected",
1232 )
1233
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001234 def test_basic_auth_with_single_quoted_realm(self):
1235 self.test_basic_auth(quote_char="'")
1236
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +08001237 def test_basic_auth_with_unquoted_realm(self):
1238 opener = OpenerDirector()
1239 password_manager = MockPasswordManager()
1240 auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
1241 realm = "ACME Widget Store"
1242 http_handler = MockHTTPHandler(
1243 401, 'WWW-Authenticate: Basic realm=%s\r\n\r\n' % realm)
1244 opener.add_handler(auth_handler)
1245 opener.add_handler(http_handler)
Senthil Kumaran0ea91cb2012-05-15 23:59:42 +08001246 with self.assertWarns(UserWarning):
1247 self._test_basic_auth(opener, auth_handler, "Authorization",
1248 realm, http_handler, password_manager,
1249 "http://acme.example.com/protected",
1250 "http://acme.example.com/protected",
1251 )
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +08001252
Thomas Wouters477c8d52006-05-27 19:21:47 +00001253 def test_proxy_basic_auth(self):
1254 opener = OpenerDirector()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001255 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001256 opener.add_handler(ph)
1257 password_manager = MockPasswordManager()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001258 auth_handler = urllib.request.ProxyBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001259 realm = "ACME Networks"
1260 http_handler = MockHTTPHandler(
1261 407, 'Proxy-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001262 opener.add_handler(auth_handler)
1263 opener.add_handler(http_handler)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001264 self._test_basic_auth(opener, auth_handler, "Proxy-authorization",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001265 realm, http_handler, password_manager,
1266 "http://acme.example.com:3128/protected",
1267 "proxy.example.com:3128",
1268 )
1269
1270 def test_basic_and_digest_auth_handlers(self):
Andrew Svetlov7bd61cb2012-12-19 22:49:25 +02001271 # HTTPDigestAuthHandler raised an exception if it couldn't handle a 40*
Thomas Wouters477c8d52006-05-27 19:21:47 +00001272 # response (http://python.org/sf/1479302), where it should instead
1273 # return None to allow another handler (especially
1274 # HTTPBasicAuthHandler) to handle the response.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001275
1276 # Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must
1277 # try digest first (since it's the strongest auth scheme), so we record
1278 # order of calls here to check digest comes first:
1279 class RecordingOpenerDirector(OpenerDirector):
1280 def __init__(self):
1281 OpenerDirector.__init__(self)
1282 self.recorded = []
1283 def record(self, info):
1284 self.recorded.append(info)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001285 class TestDigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001286 def http_error_401(self, *args, **kwds):
1287 self.parent.record("digest")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001288 urllib.request.HTTPDigestAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001289 *args, **kwds)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001290 class TestBasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001291 def http_error_401(self, *args, **kwds):
1292 self.parent.record("basic")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001293 urllib.request.HTTPBasicAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001294 *args, **kwds)
1295
1296 opener = RecordingOpenerDirector()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001297 password_manager = MockPasswordManager()
1298 digest_handler = TestDigestAuthHandler(password_manager)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001299 basic_handler = TestBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001300 realm = "ACME Networks"
1301 http_handler = MockHTTPHandler(
1302 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001303 opener.add_handler(basic_handler)
1304 opener.add_handler(digest_handler)
1305 opener.add_handler(http_handler)
1306
1307 # check basic auth isn't blocked by digest handler failing
Thomas Wouters477c8d52006-05-27 19:21:47 +00001308 self._test_basic_auth(opener, basic_handler, "Authorization",
1309 realm, http_handler, password_manager,
1310 "http://acme.example.com/protected",
1311 "http://acme.example.com/protected",
1312 )
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001313 # check digest was tried before basic (twice, because
1314 # _test_basic_auth called .open() twice)
1315 self.assertEqual(opener.recorded, ["digest", "basic"]*2)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001316
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001317 def test_unsupported_auth_digest_handler(self):
1318 opener = OpenerDirector()
1319 # While using DigestAuthHandler
1320 digest_auth_handler = urllib.request.HTTPDigestAuthHandler(None)
1321 http_handler = MockHTTPHandler(
1322 401, 'WWW-Authenticate: Kerberos\r\n\r\n')
1323 opener.add_handler(digest_auth_handler)
1324 opener.add_handler(http_handler)
1325 self.assertRaises(ValueError,opener.open,"http://www.example.com")
1326
1327 def test_unsupported_auth_basic_handler(self):
1328 # While using BasicAuthHandler
1329 opener = OpenerDirector()
1330 basic_auth_handler = urllib.request.HTTPBasicAuthHandler(None)
1331 http_handler = MockHTTPHandler(
1332 401, 'WWW-Authenticate: NTLM\r\n\r\n')
1333 opener.add_handler(basic_auth_handler)
1334 opener.add_handler(http_handler)
1335 self.assertRaises(ValueError,opener.open,"http://www.example.com")
1336
Thomas Wouters477c8d52006-05-27 19:21:47 +00001337 def _test_basic_auth(self, opener, auth_handler, auth_header,
1338 realm, http_handler, password_manager,
1339 request_url, protected_url):
Christian Heimes05e8be12008-02-23 18:30:17 +00001340 import base64
Thomas Wouters477c8d52006-05-27 19:21:47 +00001341 user, password = "wile", "coyote"
Thomas Wouters477c8d52006-05-27 19:21:47 +00001342
1343 # .add_password() fed through to password manager
1344 auth_handler.add_password(realm, request_url, user, password)
1345 self.assertEqual(realm, password_manager.realm)
1346 self.assertEqual(request_url, password_manager.url)
1347 self.assertEqual(user, password_manager.user)
1348 self.assertEqual(password, password_manager.password)
1349
Senthil Kumarand281c732013-04-09 06:00:16 -07001350 opener.open(request_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001351
1352 # should have asked the password manager for the username/password
1353 self.assertEqual(password_manager.target_realm, realm)
1354 self.assertEqual(password_manager.target_url, protected_url)
1355
1356 # expect one request without authorization, then one with
1357 self.assertEqual(len(http_handler.requests), 2)
1358 self.assertFalse(http_handler.requests[0].has_header(auth_header))
Guido van Rossum98b349f2007-08-27 21:47:52 +00001359 userpass = bytes('%s:%s' % (user, password), "ascii")
Guido van Rossum98297ee2007-11-06 21:34:58 +00001360 auth_hdr_value = ('Basic ' +
Georg Brandl706824f2009-06-04 09:42:55 +00001361 base64.encodebytes(userpass).strip().decode())
Thomas Wouters477c8d52006-05-27 19:21:47 +00001362 self.assertEqual(http_handler.requests[1].get_header(auth_header),
1363 auth_hdr_value)
Senthil Kumaranca2fc9e2010-02-24 16:53:16 +00001364 self.assertEqual(http_handler.requests[1].unredirected_hdrs[auth_header],
1365 auth_hdr_value)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001366 # if the password manager can't find a password, the handler won't
1367 # handle the HTTP auth error
1368 password_manager.user = password_manager.password = None
1369 http_handler.reset()
Senthil Kumarand281c732013-04-09 06:00:16 -07001370 opener.open(request_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001371 self.assertEqual(len(http_handler.requests), 1)
1372 self.assertFalse(http_handler.requests[0].has_header(auth_header))
1373
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001374
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001375class MiscTests(unittest.TestCase):
1376
Senthil Kumarand281c732013-04-09 06:00:16 -07001377 def opener_has_handler(self, opener, handler_class):
1378 self.assertTrue(any(h.__class__ == handler_class
1379 for h in opener.handlers))
1380
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001381 def test_build_opener(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001382 class MyHTTPHandler(urllib.request.HTTPHandler): pass
1383 class FooHandler(urllib.request.BaseHandler):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001384 def foo_open(self): pass
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001385 class BarHandler(urllib.request.BaseHandler):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001386 def bar_open(self): pass
1387
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001388 build_opener = urllib.request.build_opener
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001389
1390 o = build_opener(FooHandler, BarHandler)
1391 self.opener_has_handler(o, FooHandler)
1392 self.opener_has_handler(o, BarHandler)
1393
1394 # can take a mix of classes and instances
1395 o = build_opener(FooHandler, BarHandler())
1396 self.opener_has_handler(o, FooHandler)
1397 self.opener_has_handler(o, BarHandler)
1398
1399 # subclasses of default handlers override default handlers
1400 o = build_opener(MyHTTPHandler)
1401 self.opener_has_handler(o, MyHTTPHandler)
1402
1403 # a particular case of overriding: default handlers can be passed
1404 # in explicitly
1405 o = build_opener()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001406 self.opener_has_handler(o, urllib.request.HTTPHandler)
1407 o = build_opener(urllib.request.HTTPHandler)
1408 self.opener_has_handler(o, urllib.request.HTTPHandler)
1409 o = build_opener(urllib.request.HTTPHandler())
1410 self.opener_has_handler(o, urllib.request.HTTPHandler)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001411
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001412 # Issue2670: multiple handlers sharing the same base class
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001413 class MyOtherHTTPHandler(urllib.request.HTTPHandler): pass
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001414 o = build_opener(MyHTTPHandler, MyOtherHTTPHandler)
1415 self.opener_has_handler(o, MyHTTPHandler)
1416 self.opener_has_handler(o, MyOtherHTTPHandler)
1417
Senthil Kumarand281c732013-04-09 06:00:16 -07001418 def test_HTTPError_interface(self):
1419 """
1420 Issue 13211 reveals that HTTPError didn't implement the URLError
1421 interface even though HTTPError is a subclass of URLError.
1422 """
1423 msg = 'something bad happened'
1424 url = code = fp = None
1425 hdrs = 'Content-Length: 42'
1426 err = urllib.error.HTTPError(url, code, msg, hdrs, fp)
1427 self.assertTrue(hasattr(err, 'reason'))
1428 self.assertEqual(err.reason, 'something bad happened')
1429 self.assertTrue(hasattr(err, 'hdrs'))
1430 self.assertEqual(err.hdrs, 'Content-Length: 42')
1431 expected_errmsg = 'HTTP Error %s: %s' % (err.code, err.msg)
1432 self.assertEqual(str(err), expected_errmsg)
1433
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001434
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001435class RequestTests(unittest.TestCase):
1436
1437 def setUp(self):
1438 self.get = Request("http://www.python.org/~jeremy/")
1439 self.post = Request("http://www.python.org/~jeremy/",
1440 "data",
1441 headers={"X-Test": "test"})
1442
1443 def test_method(self):
1444 self.assertEqual("POST", self.post.get_method())
1445 self.assertEqual("GET", self.get.get_method())
1446
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001447 def test_data(self):
1448 self.assertFalse(self.get.data)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001449 self.assertEqual("GET", self.get.get_method())
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001450 self.get.data = "spam"
1451 self.assertTrue(self.get.data)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001452 self.assertEqual("POST", self.get.get_method())
1453
1454 def test_get_full_url(self):
1455 self.assertEqual("http://www.python.org/~jeremy/",
1456 self.get.get_full_url())
1457
1458 def test_selector(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001459 self.assertEqual("/~jeremy/", self.get.selector)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001460 req = Request("http://www.python.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001461 self.assertEqual("/", req.selector)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001462
1463 def test_get_type(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001464 self.assertEqual("http", self.get.type)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001465
1466 def test_get_host(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001467 self.assertEqual("www.python.org", self.get.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001468
1469 def test_get_host_unquote(self):
1470 req = Request("http://www.%70ython.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001471 self.assertEqual("www.python.org", req.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001472
1473 def test_proxy(self):
Florent Xicluna419e3842010-08-08 16:16:07 +00001474 self.assertFalse(self.get.has_proxy())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001475 self.get.set_proxy("www.perl.org", "http")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001476 self.assertTrue(self.get.has_proxy())
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001477 self.assertEqual("www.python.org", self.get.origin_req_host)
1478 self.assertEqual("www.perl.org", self.get.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001479
Senthil Kumarand95cc752010-08-08 11:27:53 +00001480 def test_wrapped_url(self):
1481 req = Request("<URL:http://www.python.org>")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001482 self.assertEqual("www.python.org", req.host)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001483
Senthil Kumaran26430412011-04-13 07:01:19 +08001484 def test_url_fragment(self):
Senthil Kumarand95cc752010-08-08 11:27:53 +00001485 req = Request("http://www.python.org/?qs=query#fragment=true")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001486 self.assertEqual("/?qs=query", req.selector)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001487 req = Request("http://www.python.org/#fun=true")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001488 self.assertEqual("/", req.selector)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001489
Senthil Kumaran26430412011-04-13 07:01:19 +08001490 # Issue 11703: geturl() omits fragment in the original URL.
1491 url = 'http://docs.python.org/library/urllib2.html#OK'
1492 req = Request(url)
1493 self.assertEqual(req.get_full_url(), url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001494
Senthil Kumaran41e66a22012-12-23 09:04:24 -08001495 def test_HTTPError_interface_call(self):
1496 """
1497 Issue 15701 - HTTPError interface has info method available from URLError
1498 """
1499 err = urllib.request.HTTPError(msg="something bad happened", url=None,
1500 code=None, hdrs='Content-Length:42', fp=None)
1501 self.assertTrue(hasattr(err, 'reason'))
1502 assert hasattr(err, 'reason')
1503 assert hasattr(err, 'info')
1504 assert callable(err.info)
1505 try:
1506 err.info()
1507 except AttributeError:
1508 self.fail('err.info call failed.')
1509 self.assertEqual(err.info(), "Content-Length:42")
Jason R. Coombsaa204db2011-11-07 10:50:32 -05001510
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001511def test_main(verbose=None):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001512 from test import test_urllib2
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001513 support.run_doctest(test_urllib2, verbose)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001514 support.run_doctest(urllib.request, verbose)
Andrew M. Kuchlingbd3200f2004-06-29 13:15:46 +00001515 tests = (TrivialTests,
1516 OpenerDirectorTests,
1517 HandlerTests,
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001518 MiscTests,
Senthil Kumarand281c732013-04-09 06:00:16 -07001519 RequestTests,
1520 RequestHdrsTests)
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001521 support.run_unittest(*tests)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001522
1523if __name__ == "__main__":
1524 test_main(verbose=True)