blob: 089e04c795a7391c1335c7237c2fda3b62277879 [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 Kumaranfa1b02a2013-04-08 22:24:17 -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 Kumaranfa1b02a2013-04-08 22:24:17 -070071class RequestHdrsTests(unittest.TestCase):
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000072
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -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")
120
121 req.remove_header("Spam-eggs")
122 self.assertFalse(req.has_header("Spam-eggs"))
123
124 req.add_unredirected_header("Unredirected-spam", "Eggs")
125 self.assertTrue(req.has_header("Unredirected-spam"))
126
127 req.remove_header("Unredirected-spam")
128 self.assertFalse(req.has_header("Unredirected-spam"))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000129
130
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700131 def test_password_manager(self):
132 mgr = urllib.request.HTTPPasswordMgr()
133 add = mgr.add_password
134 find_user_pass = mgr.find_user_password
135 add("Some Realm", "http://example.com/", "joe", "password")
136 add("Some Realm", "http://example.com/ni", "ni", "ni")
137 add("c", "http://example.com/foo", "foo", "ni")
138 add("c", "http://example.com/bar", "bar", "nini")
139 add("b", "http://example.com/", "first", "blah")
140 add("b", "http://example.com/", "second", "spam")
141 add("a", "http://example.com", "1", "a")
142 add("Some Realm", "http://c.example.com:3128", "3", "c")
143 add("Some Realm", "d.example.com", "4", "d")
144 add("Some Realm", "e.example.com:3128", "5", "e")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000145
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700146 self.assertEqual(find_user_pass("Some Realm", "example.com"),
147 ('joe', 'password'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000148
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700149 #self.assertEqual(find_user_pass("Some Realm", "http://example.com/ni"),
150 # ('ni', 'ni'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000151
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700152 self.assertEqual(find_user_pass("Some Realm", "http://example.com"),
153 ('joe', 'password'))
154 self.assertEqual(find_user_pass("Some Realm", "http://example.com/"),
155 ('joe', 'password'))
156 self.assertEqual(
157 find_user_pass("Some Realm", "http://example.com/spam"),
158 ('joe', 'password'))
159 self.assertEqual(
160 find_user_pass("Some Realm", "http://example.com/spam/spam"),
161 ('joe', 'password'))
162 self.assertEqual(find_user_pass("c", "http://example.com/foo"),
163 ('foo', 'ni'))
164 self.assertEqual(find_user_pass("c", "http://example.com/bar"),
165 ('bar', 'nini'))
166 self.assertEqual(find_user_pass("b", "http://example.com/"),
167 ('second', 'spam'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000168
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700169 # No special relationship between a.example.com and example.com:
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000170
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700171 self.assertEqual(find_user_pass("a", "http://example.com/"),
172 ('1', 'a'))
173 self.assertEqual(find_user_pass("a", "http://a.example.com/"),
174 (None, None))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000175
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700176 # Ports:
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000177
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700178 self.assertEqual(find_user_pass("Some Realm", "c.example.com"),
179 (None, None))
180 self.assertEqual(find_user_pass("Some Realm", "c.example.com:3128"),
181 ('3', 'c'))
182 self.assertEqual(
183 find_user_pass("Some Realm", "http://c.example.com:3128"),
184 ('3', 'c'))
185 self.assertEqual(find_user_pass("Some Realm", "d.example.com"),
186 ('4', 'd'))
187 self.assertEqual(find_user_pass("Some Realm", "e.example.com:3128"),
188 ('5', 'e'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000189
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700190 def test_password_manager_default_port(self):
191 """
192 The point to note here is that we can't guess the default port if
193 there's no scheme. This applies to both add_password and
194 find_user_password.
195 """
196 mgr = urllib.request.HTTPPasswordMgr()
197 add = mgr.add_password
198 find_user_pass = mgr.find_user_password
199 add("f", "http://g.example.com:80", "10", "j")
200 add("g", "http://h.example.com", "11", "k")
201 add("h", "i.example.com:80", "12", "l")
202 add("i", "j.example.com", "13", "m")
203 self.assertEqual(find_user_pass("f", "g.example.com:100"),
204 (None, None))
205 self.assertEqual(find_user_pass("f", "g.example.com:80"),
206 ('10', 'j'))
207 self.assertEqual(find_user_pass("f", "g.example.com"),
208 (None, None))
209 self.assertEqual(find_user_pass("f", "http://g.example.com:100"),
210 (None, None))
211 self.assertEqual(find_user_pass("f", "http://g.example.com:80"),
212 ('10', 'j'))
213 self.assertEqual(find_user_pass("f", "http://g.example.com"),
214 ('10', 'j'))
215 self.assertEqual(find_user_pass("g", "h.example.com"), ('11', 'k'))
216 self.assertEqual(find_user_pass("g", "h.example.com:80"), ('11', 'k'))
217 self.assertEqual(find_user_pass("g", "http://h.example.com:80"),
218 ('11', 'k'))
219 self.assertEqual(find_user_pass("h", "i.example.com"), (None, None))
220 self.assertEqual(find_user_pass("h", "i.example.com:80"), ('12', 'l'))
221 self.assertEqual(find_user_pass("h", "http://i.example.com:80"),
222 ('12', 'l'))
223 self.assertEqual(find_user_pass("i", "j.example.com"), ('13', 'm'))
224 self.assertEqual(find_user_pass("i", "j.example.com:80"),
225 (None, None))
226 self.assertEqual(find_user_pass("i", "http://j.example.com"),
227 ('13', 'm'))
228 self.assertEqual(find_user_pass("i", "http://j.example.com:80"),
229 (None, None))
Andrew Svetlovbff98fe2012-11-27 23:06:19 +0200230
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000231
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000232class MockOpener:
233 addheaders = []
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000234 def open(self, req, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
235 self.req, self.data, self.timeout = req, data, timeout
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000236 def error(self, proto, *args):
237 self.proto, self.args = proto, args
238
239class MockFile:
240 def read(self, count=None): pass
241 def readline(self, count=None): pass
242 def close(self): pass
243
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000244class MockHeaders(dict):
245 def getheaders(self, name):
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000246 return list(self.values())
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000247
Guido van Rossum34d19282007-08-09 01:03:29 +0000248class MockResponse(io.StringIO):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000249 def __init__(self, code, msg, headers, data, url=None):
Guido van Rossum34d19282007-08-09 01:03:29 +0000250 io.StringIO.__init__(self, data)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000251 self.code, self.msg, self.headers, self.url = code, msg, headers, url
252 def info(self):
253 return self.headers
254 def geturl(self):
255 return self.url
256
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000257class MockCookieJar:
258 def add_cookie_header(self, request):
259 self.ach_req = request
260 def extract_cookies(self, response, request):
261 self.ec_req, self.ec_r = request, response
262
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000263class FakeMethod:
264 def __init__(self, meth_name, action, handle):
265 self.meth_name = meth_name
266 self.handle = handle
267 self.action = action
268 def __call__(self, *args):
269 return self.handle(self.meth_name, self.action, *args)
270
Senthil Kumaran47fff872009-12-20 07:10:31 +0000271class MockHTTPResponse(io.IOBase):
272 def __init__(self, fp, msg, status, reason):
273 self.fp = fp
274 self.msg = msg
275 self.status = status
276 self.reason = reason
277 self.code = 200
278
279 def read(self):
280 return ''
281
282 def info(self):
283 return {}
284
285 def geturl(self):
286 return self.url
287
288
289class MockHTTPClass:
290 def __init__(self):
291 self.level = 0
292 self.req_headers = []
293 self.data = None
294 self.raise_on_endheaders = False
Nadeem Vawdabd26b542012-10-21 17:37:43 +0200295 self.sock = None
Senthil Kumaran47fff872009-12-20 07:10:31 +0000296 self._tunnel_headers = {}
297
298 def __call__(self, host, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
299 self.host = host
300 self.timeout = timeout
301 return self
302
303 def set_debuglevel(self, level):
304 self.level = level
305
306 def set_tunnel(self, host, port=None, headers=None):
307 self._tunnel_host = host
308 self._tunnel_port = port
309 if headers:
310 self._tunnel_headers = headers
311 else:
312 self._tunnel_headers.clear()
313
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000314 def request(self, method, url, body=None, headers=None):
Senthil Kumaran47fff872009-12-20 07:10:31 +0000315 self.method = method
316 self.selector = url
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000317 if headers is not None:
318 self.req_headers += headers.items()
Senthil Kumaran47fff872009-12-20 07:10:31 +0000319 self.req_headers.sort()
320 if body:
321 self.data = body
322 if self.raise_on_endheaders:
Andrew Svetlov0832af62012-12-18 23:10:48 +0200323 raise OSError()
Senthil Kumaran47fff872009-12-20 07:10:31 +0000324 def getresponse(self):
325 return MockHTTPResponse(MockFile(), {}, 200, "OK")
326
Victor Stinnera4c45d72011-06-17 14:01:18 +0200327 def close(self):
328 pass
329
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000330class MockHandler:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000331 # useful for testing handler machinery
332 # see add_ordered_mock_handlers() docstring
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000333 handler_order = 500
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000334 def __init__(self, methods):
335 self._define_methods(methods)
336 def _define_methods(self, methods):
337 for spec in methods:
338 if len(spec) == 2: name, action = spec
339 else: name, action = spec, None
340 meth = FakeMethod(name, action, self.handle)
341 setattr(self.__class__, name, meth)
342 def handle(self, fn_name, action, *args, **kwds):
343 self.parent.calls.append((self, fn_name, args, kwds))
344 if action is None:
345 return None
346 elif action == "return self":
347 return self
348 elif action == "return response":
349 res = MockResponse(200, "OK", {}, "")
350 return res
351 elif action == "return request":
352 return Request("http://blah/")
353 elif action.startswith("error"):
354 code = action[action.rfind(" ")+1:]
355 try:
356 code = int(code)
357 except ValueError:
358 pass
359 res = MockResponse(200, "OK", {}, "")
360 return self.parent.error("http", args[0], res, code, "", {})
361 elif action == "raise":
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000362 raise urllib.error.URLError("blah")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000363 assert False
364 def close(self): pass
365 def add_parent(self, parent):
366 self.parent = parent
367 self.parent.calls = []
368 def __lt__(self, other):
369 if not hasattr(other, "handler_order"):
370 # No handler_order, leave in original order. Yuck.
371 return True
372 return self.handler_order < other.handler_order
373
374def add_ordered_mock_handlers(opener, meth_spec):
375 """Create MockHandlers and add them to an OpenerDirector.
376
377 meth_spec: list of lists of tuples and strings defining methods to define
378 on handlers. eg:
379
380 [["http_error", "ftp_open"], ["http_open"]]
381
382 defines methods .http_error() and .ftp_open() on one handler, and
383 .http_open() on another. These methods just record their arguments and
384 return None. Using a tuple instead of a string causes the method to
385 perform some action (see MockHandler.handle()), eg:
386
387 [["http_error"], [("http_open", "return request")]]
388
389 defines .http_error() on one handler (which simply returns None), and
390 .http_open() on another handler, which returns a Request object.
391
392 """
393 handlers = []
394 count = 0
395 for meths in meth_spec:
396 class MockHandlerSubclass(MockHandler): pass
397 h = MockHandlerSubclass(meths)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000398 h.handler_order += count
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000399 h.add_parent(opener)
400 count = count + 1
401 handlers.append(h)
402 opener.add_handler(h)
403 return handlers
404
Thomas Wouters477c8d52006-05-27 19:21:47 +0000405def build_test_opener(*handler_instances):
406 opener = OpenerDirector()
407 for h in handler_instances:
408 opener.add_handler(h)
409 return opener
410
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000411class MockHTTPHandler(urllib.request.BaseHandler):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000412 # useful for testing redirections and auth
413 # sends supplied headers and code as first response
414 # sends 200 OK as second response
415 def __init__(self, code, headers):
416 self.code = code
417 self.headers = headers
418 self.reset()
419 def reset(self):
420 self._count = 0
421 self.requests = []
422 def http_open(self, req):
Barry Warsaw820c1202008-06-12 04:06:45 +0000423 import email, http.client, copy
Thomas Wouters477c8d52006-05-27 19:21:47 +0000424 self.requests.append(copy.deepcopy(req))
425 if self._count == 0:
426 self._count = self._count + 1
Georg Brandl24420152008-05-26 16:32:26 +0000427 name = http.client.responses[self.code]
Barry Warsaw820c1202008-06-12 04:06:45 +0000428 msg = email.message_from_string(self.headers)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000429 return self.parent.error(
430 "http", req, MockFile(), self.code, name, msg)
431 else:
432 self.req = req
Barry Warsaw820c1202008-06-12 04:06:45 +0000433 msg = email.message_from_string("\r\n\r\n")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000434 return MockResponse(200, "OK", msg, "", req.get_full_url())
435
Senthil Kumaran47fff872009-12-20 07:10:31 +0000436class MockHTTPSHandler(urllib.request.AbstractHTTPHandler):
437 # Useful for testing the Proxy-Authorization request by verifying the
438 # properties of httpcon
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000439
440 def __init__(self):
441 urllib.request.AbstractHTTPHandler.__init__(self)
442 self.httpconn = MockHTTPClass()
443
Senthil Kumaran47fff872009-12-20 07:10:31 +0000444 def https_open(self, req):
445 return self.do_open(self.httpconn, req)
446
Thomas Wouters477c8d52006-05-27 19:21:47 +0000447class MockPasswordManager:
448 def add_password(self, realm, uri, user, password):
449 self.realm = realm
450 self.url = uri
451 self.user = user
452 self.password = password
453 def find_user_password(self, realm, authuri):
454 self.target_realm = realm
455 self.target_url = authuri
456 return self.user, self.password
457
458
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000459class OpenerDirectorTests(unittest.TestCase):
460
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000461 def test_add_non_handler(self):
462 class NonHandler(object):
463 pass
464 self.assertRaises(TypeError,
465 OpenerDirector().add_handler, NonHandler())
466
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000467 def test_badly_named_methods(self):
468 # test work-around for three methods that accidentally follow the
469 # naming conventions for handler methods
470 # (*_open() / *_request() / *_response())
471
472 # These used to call the accidentally-named methods, causing a
473 # TypeError in real code; here, returning self from these mock
474 # methods would either cause no exception, or AttributeError.
475
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000476 from urllib.error import URLError
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000477
478 o = OpenerDirector()
479 meth_spec = [
480 [("do_open", "return self"), ("proxy_open", "return self")],
481 [("redirect_request", "return self")],
482 ]
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700483 add_ordered_mock_handlers(o, meth_spec)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000484 o.add_handler(urllib.request.UnknownHandler())
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000485 for scheme in "do", "proxy", "redirect":
486 self.assertRaises(URLError, o.open, scheme+"://example.com/")
487
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000488 def test_handled(self):
489 # handler returning non-None means no more handlers will be called
490 o = OpenerDirector()
491 meth_spec = [
492 ["http_open", "ftp_open", "http_error_302"],
493 ["ftp_open"],
494 [("http_open", "return self")],
495 [("http_open", "return self")],
496 ]
497 handlers = add_ordered_mock_handlers(o, meth_spec)
498
499 req = Request("http://example.com/")
500 r = o.open(req)
501 # Second .http_open() gets called, third doesn't, since second returned
502 # non-None. Handlers without .http_open() never get any methods called
503 # on them.
504 # In fact, second mock handler defining .http_open() returns self
505 # (instead of response), which becomes the OpenerDirector's return
506 # value.
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000507 self.assertEqual(r, handlers[2])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000508 calls = [(handlers[0], "http_open"), (handlers[2], "http_open")]
509 for expected, got in zip(calls, o.calls):
510 handler, name, args, kwds = got
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000511 self.assertEqual((handler, name), expected)
512 self.assertEqual(args, (req,))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000513
514 def test_handler_order(self):
515 o = OpenerDirector()
516 handlers = []
517 for meths, handler_order in [
518 ([("http_open", "return self")], 500),
519 (["http_open"], 0),
520 ]:
521 class MockHandlerSubclass(MockHandler): pass
522 h = MockHandlerSubclass(meths)
523 h.handler_order = handler_order
524 handlers.append(h)
525 o.add_handler(h)
526
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700527 o.open("http://example.com/")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000528 # handlers called in reverse order, thanks to their sort order
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000529 self.assertEqual(o.calls[0][0], handlers[1])
530 self.assertEqual(o.calls[1][0], handlers[0])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000531
532 def test_raise(self):
533 # raising URLError stops processing of request
534 o = OpenerDirector()
535 meth_spec = [
536 [("http_open", "raise")],
537 [("http_open", "return self")],
538 ]
539 handlers = add_ordered_mock_handlers(o, meth_spec)
540
541 req = Request("http://example.com/")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000542 self.assertRaises(urllib.error.URLError, o.open, req)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000543 self.assertEqual(o.calls, [(handlers[0], "http_open", (req,), {})])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000544
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000545 def test_http_error(self):
546 # XXX http_error_default
547 # http errors are a special case
548 o = OpenerDirector()
549 meth_spec = [
550 [("http_open", "error 302")],
551 [("http_error_400", "raise"), "http_open"],
552 [("http_error_302", "return response"), "http_error_303",
553 "http_error"],
554 [("http_error_302")],
555 ]
556 handlers = add_ordered_mock_handlers(o, meth_spec)
557
558 class Unknown:
559 def __eq__(self, other): return True
560
561 req = Request("http://example.com/")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700562 o.open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000563 assert len(o.calls) == 2
564 calls = [(handlers[0], "http_open", (req,)),
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000565 (handlers[2], "http_error_302",
566 (req, Unknown(), 302, "", {}))]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000567 for expected, got in zip(calls, o.calls):
568 handler, method_name, args = expected
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000569 self.assertEqual((handler, method_name), got[:2])
570 self.assertEqual(args, got[2])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000571
Senthil Kumaran38b968b92012-03-14 13:43:53 -0700572
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000573 def test_processors(self):
574 # *_request / *_response methods get called appropriately
575 o = OpenerDirector()
576 meth_spec = [
577 [("http_request", "return request"),
578 ("http_response", "return response")],
579 [("http_request", "return request"),
580 ("http_response", "return response")],
581 ]
582 handlers = add_ordered_mock_handlers(o, meth_spec)
583
584 req = Request("http://example.com/")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700585 o.open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000586 # processor methods are called on *all* handlers that define them,
587 # not just the first handler that handles the request
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000588 calls = [
589 (handlers[0], "http_request"), (handlers[1], "http_request"),
590 (handlers[0], "http_response"), (handlers[1], "http_response")]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000591
592 for i, (handler, name, args, kwds) in enumerate(o.calls):
593 if i < 2:
594 # *_request
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000595 self.assertEqual((handler, name), calls[i])
596 self.assertEqual(len(args), 1)
Ezio Melottie9615932010-01-24 19:26:24 +0000597 self.assertIsInstance(args[0], Request)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000598 else:
599 # *_response
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000600 self.assertEqual((handler, name), calls[i])
601 self.assertEqual(len(args), 2)
Ezio Melottie9615932010-01-24 19:26:24 +0000602 self.assertIsInstance(args[0], Request)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000603 # response from opener.open is None, because there's no
604 # handler that defines http_open to handle it
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000605 self.assertTrue(args[1] is None or
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000606 isinstance(args[1], MockResponse))
607
Tim Peters58eb11c2004-01-18 20:29:55 +0000608def sanepathname2url(path):
Victor Stinner6c6f8512010-08-07 10:09:35 +0000609 try:
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000610 path.encode("utf-8")
Victor Stinner6c6f8512010-08-07 10:09:35 +0000611 except UnicodeEncodeError:
612 raise unittest.SkipTest("path is not encodable to utf8")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000613 urlpath = urllib.request.pathname2url(path)
Tim Peters58eb11c2004-01-18 20:29:55 +0000614 if os.name == "nt" and urlpath.startswith("///"):
615 urlpath = urlpath[2:]
616 # XXX don't ask me about the mac...
617 return urlpath
618
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000619class HandlerTests(unittest.TestCase):
620
621 def test_ftp(self):
622 class MockFTPWrapper:
623 def __init__(self, data): self.data = data
624 def retrfile(self, filename, filetype):
625 self.filename, self.filetype = filename, filetype
Guido van Rossum34d19282007-08-09 01:03:29 +0000626 return io.StringIO(self.data), len(self.data)
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +0200627 def close(self): pass
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000628
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000629 class NullFTPHandler(urllib.request.FTPHandler):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000630 def __init__(self, data): self.data = data
Georg Brandlf78e02b2008-06-10 17:40:04 +0000631 def connect_ftp(self, user, passwd, host, port, dirs,
632 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000633 self.user, self.passwd = user, passwd
634 self.host, self.port = host, port
635 self.dirs = dirs
636 self.ftpwrapper = MockFTPWrapper(self.data)
637 return self.ftpwrapper
638
Georg Brandlf78e02b2008-06-10 17:40:04 +0000639 import ftplib
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000640 data = "rheum rhaponicum"
641 h = NullFTPHandler(data)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700642 h.parent = MockOpener()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000643
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000644 for url, host, port, user, passwd, type_, dirs, filename, mimetype in [
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000645 ("ftp://localhost/foo/bar/baz.html",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000646 "localhost", ftplib.FTP_PORT, "", "", "I",
647 ["foo", "bar"], "baz.html", "text/html"),
648 ("ftp://parrot@localhost/foo/bar/baz.html",
649 "localhost", ftplib.FTP_PORT, "parrot", "", "I",
650 ["foo", "bar"], "baz.html", "text/html"),
651 ("ftp://%25parrot@localhost/foo/bar/baz.html",
652 "localhost", ftplib.FTP_PORT, "%parrot", "", "I",
653 ["foo", "bar"], "baz.html", "text/html"),
654 ("ftp://%2542parrot@localhost/foo/bar/baz.html",
655 "localhost", ftplib.FTP_PORT, "%42parrot", "", "I",
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000656 ["foo", "bar"], "baz.html", "text/html"),
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000657 ("ftp://localhost:80/foo/bar/",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000658 "localhost", 80, "", "", "D",
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000659 ["foo", "bar"], "", None),
660 ("ftp://localhost/baz.gif;type=a",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000661 "localhost", ftplib.FTP_PORT, "", "", "A",
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000662 [], "baz.gif", None), # XXX really this should guess image/gif
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000663 ]:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000664 req = Request(url)
665 req.timeout = None
666 r = h.ftp_open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000667 # ftp authentication not yet implemented by FTPHandler
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000668 self.assertEqual(h.user, user)
669 self.assertEqual(h.passwd, passwd)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000670 self.assertEqual(h.host, socket.gethostbyname(host))
671 self.assertEqual(h.port, port)
672 self.assertEqual(h.dirs, dirs)
673 self.assertEqual(h.ftpwrapper.filename, filename)
674 self.assertEqual(h.ftpwrapper.filetype, type_)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000675 headers = r.info()
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000676 self.assertEqual(headers.get("Content-type"), mimetype)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000677 self.assertEqual(int(headers["Content-length"]), len(data))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000678
679 def test_file(self):
Benjamin Petersona0c0a4a2008-06-12 22:15:50 +0000680 import email.utils, socket
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000681 h = urllib.request.FileHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000682 o = h.parent = MockOpener()
683
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000684 TESTFN = support.TESTFN
Tim Peters58eb11c2004-01-18 20:29:55 +0000685 urlpath = sanepathname2url(os.path.abspath(TESTFN))
Guido van Rossum6a2ccd02007-07-16 20:51:57 +0000686 towrite = b"hello, world\n"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000687 urls = [
Tim Peters58eb11c2004-01-18 20:29:55 +0000688 "file://localhost%s" % urlpath,
689 "file://%s" % urlpath,
690 "file://%s%s" % (socket.gethostbyname('localhost'), urlpath),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000691 ]
692 try:
693 localaddr = socket.gethostbyname(socket.gethostname())
694 except socket.gaierror:
695 localaddr = ''
696 if localaddr:
697 urls.append("file://%s%s" % (localaddr, urlpath))
698
699 for url in urls:
Tim Peters58eb11c2004-01-18 20:29:55 +0000700 f = open(TESTFN, "wb")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000701 try:
702 try:
703 f.write(towrite)
704 finally:
705 f.close()
706
707 r = h.file_open(Request(url))
708 try:
709 data = r.read()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000710 headers = r.info()
Senthil Kumaran4fbed102010-05-08 03:29:09 +0000711 respurl = r.geturl()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000712 finally:
713 r.close()
Tim Peters58eb11c2004-01-18 20:29:55 +0000714 stats = os.stat(TESTFN)
Benjamin Petersona0c0a4a2008-06-12 22:15:50 +0000715 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000716 finally:
717 os.remove(TESTFN)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000718 self.assertEqual(data, towrite)
719 self.assertEqual(headers["Content-type"], "text/plain")
720 self.assertEqual(headers["Content-length"], "13")
Tim Peters58eb11c2004-01-18 20:29:55 +0000721 self.assertEqual(headers["Last-modified"], modified)
Senthil Kumaran4fbed102010-05-08 03:29:09 +0000722 self.assertEqual(respurl, url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000723
724 for url in [
Tim Peters58eb11c2004-01-18 20:29:55 +0000725 "file://localhost:80%s" % urlpath,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000726 "file:///file_does_not_exist.txt",
727 "file://%s:80%s/%s" % (socket.gethostbyname('localhost'),
728 os.getcwd(), TESTFN),
729 "file://somerandomhost.ontheinternet.com%s/%s" %
730 (os.getcwd(), TESTFN),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000731 ]:
732 try:
Tim Peters58eb11c2004-01-18 20:29:55 +0000733 f = open(TESTFN, "wb")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000734 try:
735 f.write(towrite)
736 finally:
737 f.close()
738
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000739 self.assertRaises(urllib.error.URLError,
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000740 h.file_open, Request(url))
741 finally:
742 os.remove(TESTFN)
743
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000744 h = urllib.request.FileHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000745 o = h.parent = MockOpener()
746 # XXXX why does // mean ftp (and /// mean not ftp!), and where
747 # is file: scheme specified? I think this is really a bug, and
748 # what was intended was to distinguish between URLs like:
749 # file:/blah.txt (a file)
750 # file://localhost/blah.txt (a file)
751 # file:///blah.txt (a file)
752 # file://ftp.example.com/blah.txt (an ftp URL)
753 for url, ftp in [
Senthil Kumaran383c32d2010-10-14 11:57:35 +0000754 ("file://ftp.example.com//foo.txt", False),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000755 ("file://ftp.example.com///foo.txt", False),
756# XXXX bug: fails with OSError, should be URLError
757 ("file://ftp.example.com/foo.txt", False),
Senthil Kumaran383c32d2010-10-14 11:57:35 +0000758 ("file://somehost//foo/something.txt", False),
Senthil Kumaran2ef16322010-07-11 03:12:43 +0000759 ("file://localhost//foo/something.txt", False),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000760 ]:
761 req = Request(url)
762 try:
763 h.file_open(req)
764 # XXXX remove OSError when bug fixed
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000765 except (urllib.error.URLError, OSError):
Florent Xicluna419e3842010-08-08 16:16:07 +0000766 self.assertFalse(ftp)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000767 else:
Florent Xicluna419e3842010-08-08 16:16:07 +0000768 self.assertIs(o.req, req)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000769 self.assertEqual(req.type, "ftp")
Łukasz Langad7e81cc2011-01-09 18:18:53 +0000770 self.assertEqual(req.type == "ftp", ftp)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000771
772 def test_http(self):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000773
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000774 h = urllib.request.AbstractHTTPHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000775 o = h.parent = MockOpener()
776
777 url = "http://example.com/"
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000778 for method, data in [("GET", None), ("POST", b"blah")]:
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000779 req = Request(url, data, {"Foo": "bar"})
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000780 req.timeout = None
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000781 req.add_unredirected_header("Spam", "eggs")
782 http = MockHTTPClass()
783 r = h.do_open(http, req)
784
785 # result attributes
786 r.read; r.readline # wrapped MockFile methods
787 r.info; r.geturl # addinfourl methods
788 r.code, r.msg == 200, "OK" # added from MockHTTPClass.getreply()
789 hdrs = r.info()
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000790 hdrs.get; hdrs.__contains__ # r.info() gives dict from .getreply()
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000791 self.assertEqual(r.geturl(), url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000792
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000793 self.assertEqual(http.host, "example.com")
794 self.assertEqual(http.level, 0)
795 self.assertEqual(http.method, method)
796 self.assertEqual(http.selector, "/")
797 self.assertEqual(http.req_headers,
Jeremy Hyltonb3ee6f92004-02-24 19:40:35 +0000798 [("Connection", "close"),
799 ("Foo", "bar"), ("Spam", "eggs")])
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000800 self.assertEqual(http.data, data)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000801
Andrew Svetlov0832af62012-12-18 23:10:48 +0200802 # check OSError converted to URLError
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000803 http.raise_on_endheaders = True
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000804 self.assertRaises(urllib.error.URLError, h.do_open, http, req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000805
Senthil Kumaran29333122011-02-11 11:25:47 +0000806 # Check for TypeError on POST data which is str.
807 req = Request("http://example.com/","badpost")
808 self.assertRaises(TypeError, h.do_request_, req)
809
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000810 # check adding of standard headers
811 o.addheaders = [("Spam", "eggs")]
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000812 for data in b"", None: # POST, GET
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000813 req = Request("http://example.com/", data)
814 r = MockResponse(200, "OK", {}, "")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000815 newreq = h.do_request_(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000816 if data is None: # GET
Benjamin Peterson577473f2010-01-19 00:09:57 +0000817 self.assertNotIn("Content-length", req.unredirected_hdrs)
818 self.assertNotIn("Content-type", req.unredirected_hdrs)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000819 else: # POST
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000820 self.assertEqual(req.unredirected_hdrs["Content-length"], "0")
821 self.assertEqual(req.unredirected_hdrs["Content-type"],
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000822 "application/x-www-form-urlencoded")
823 # XXX the details of Host could be better tested
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000824 self.assertEqual(req.unredirected_hdrs["Host"], "example.com")
825 self.assertEqual(req.unredirected_hdrs["Spam"], "eggs")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000826
827 # don't clobber existing headers
828 req.add_unredirected_header("Content-length", "foo")
829 req.add_unredirected_header("Content-type", "bar")
830 req.add_unredirected_header("Host", "baz")
831 req.add_unredirected_header("Spam", "foo")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000832 newreq = h.do_request_(req)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000833 self.assertEqual(req.unredirected_hdrs["Content-length"], "foo")
834 self.assertEqual(req.unredirected_hdrs["Content-type"], "bar")
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000835 self.assertEqual(req.unredirected_hdrs["Host"], "baz")
836 self.assertEqual(req.unredirected_hdrs["Spam"], "foo")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000837
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000838 # Check iterable body support
839 def iterable_body():
840 yield b"one"
841 yield b"two"
842 yield b"three"
843
844 for headers in {}, {"Content-Length": 11}:
845 req = Request("http://example.com/", iterable_body(), headers)
846 if not headers:
847 # Having an iterable body without a Content-Length should
848 # raise an exception
849 self.assertRaises(ValueError, h.do_request_, req)
850 else:
851 newreq = h.do_request_(req)
852
Senthil Kumaran29333122011-02-11 11:25:47 +0000853 # A file object.
854 # Test only Content-Length attribute of request.
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000855
Senthil Kumaran29333122011-02-11 11:25:47 +0000856 file_obj = io.BytesIO()
857 file_obj.write(b"Something\nSomething\nSomething\n")
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000858
859 for headers in {}, {"Content-Length": 30}:
860 req = Request("http://example.com/", file_obj, headers)
861 if not headers:
862 # Having an iterable body without a Content-Length should
863 # raise an exception
864 self.assertRaises(ValueError, h.do_request_, req)
865 else:
866 newreq = h.do_request_(req)
867 self.assertEqual(int(newreq.get_header('Content-length')),30)
868
869 file_obj.close()
870
871 # array.array Iterable - Content Length is calculated
872
873 iterable_array = array.array("I",[1,2,3,4])
874
875 for headers in {}, {"Content-Length": 16}:
876 req = Request("http://example.com/", iterable_array, headers)
877 newreq = h.do_request_(req)
878 self.assertEqual(int(newreq.get_header('Content-length')),16)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000879
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000880 def test_http_doubleslash(self):
881 # Checks the presence of any unnecessary double slash in url does not
882 # break anything. Previously, a double slash directly after the host
Ezio Melottie130a522011-10-19 10:58:56 +0300883 # could cause incorrect parsing.
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000884 h = urllib.request.AbstractHTTPHandler()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700885 h.parent = MockOpener()
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000886
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000887 data = b""
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000888 ds_urls = [
889 "http://example.com/foo/bar/baz.html",
890 "http://example.com//foo/bar/baz.html",
891 "http://example.com/foo//bar/baz.html",
892 "http://example.com/foo/bar//baz.html"
893 ]
894
895 for ds_url in ds_urls:
896 ds_req = Request(ds_url, data)
897
898 # Check whether host is determined correctly if there is no proxy
899 np_ds_req = h.do_request_(ds_req)
900 self.assertEqual(np_ds_req.unredirected_hdrs["Host"],"example.com")
901
902 # Check whether host is determined correctly if there is a proxy
903 ds_req.set_proxy("someproxy:3128",None)
904 p_ds_req = h.do_request_(ds_req)
905 self.assertEqual(p_ds_req.unredirected_hdrs["Host"],"example.com")
906
Senthil Kumaranc2958622010-11-22 04:48:26 +0000907 def test_fixpath_in_weirdurls(self):
908 # Issue4493: urllib2 to supply '/' when to urls where path does not
909 # start with'/'
910
911 h = urllib.request.AbstractHTTPHandler()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700912 h.parent = MockOpener()
Senthil Kumaranc2958622010-11-22 04:48:26 +0000913
914 weird_url = 'http://www.python.org?getspam'
915 req = Request(weird_url)
916 newreq = h.do_request_(req)
917 self.assertEqual(newreq.host,'www.python.org')
918 self.assertEqual(newreq.selector,'/?getspam')
919
920 url_without_path = 'http://www.python.org'
921 req = Request(url_without_path)
922 newreq = h.do_request_(req)
923 self.assertEqual(newreq.host,'www.python.org')
924 self.assertEqual(newreq.selector,'')
925
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000926
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000927 def test_errors(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000928 h = urllib.request.HTTPErrorProcessor()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000929 o = h.parent = MockOpener()
930
931 url = "http://example.com/"
932 req = Request(url)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000933 # all 2xx are passed through
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000934 r = MockResponse(200, "OK", {}, "", url)
935 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +0000936 self.assertIs(r, newr)
937 self.assertFalse(hasattr(o, "proto")) # o.error not called
Guido van Rossumd8faa362007-04-27 19:54:29 +0000938 r = MockResponse(202, "Accepted", {}, "", url)
939 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +0000940 self.assertIs(r, newr)
941 self.assertFalse(hasattr(o, "proto")) # o.error not called
Guido van Rossumd8faa362007-04-27 19:54:29 +0000942 r = MockResponse(206, "Partial content", {}, "", url)
943 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +0000944 self.assertIs(r, newr)
945 self.assertFalse(hasattr(o, "proto")) # o.error not called
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000946 # anything else calls o.error (and MockOpener returns None, here)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000947 r = MockResponse(502, "Bad gateway", {}, "", url)
Florent Xicluna419e3842010-08-08 16:16:07 +0000948 self.assertIsNone(h.http_response(req, r))
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000949 self.assertEqual(o.proto, "http") # o.error called
Guido van Rossumd8faa362007-04-27 19:54:29 +0000950 self.assertEqual(o.args, (req, r, 502, "Bad gateway", {}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000951
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000952 def test_cookies(self):
953 cj = MockCookieJar()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000954 h = urllib.request.HTTPCookieProcessor(cj)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700955 h.parent = MockOpener()
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000956
957 req = Request("http://example.com/")
958 r = MockResponse(200, "OK", {}, "")
959 newreq = h.http_request(req)
Florent Xicluna419e3842010-08-08 16:16:07 +0000960 self.assertIs(cj.ach_req, req)
961 self.assertIs(cj.ach_req, newreq)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -0700962 self.assertEqual(req.origin_req_host, "example.com")
963 self.assertFalse(req.unverifiable)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000964 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +0000965 self.assertIs(cj.ec_req, req)
966 self.assertIs(cj.ec_r, r)
967 self.assertIs(r, newr)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000968
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000969 def test_redirect(self):
970 from_url = "http://example.com/a.html"
971 to_url = "http://example.com/b.html"
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000972 h = urllib.request.HTTPRedirectHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000973 o = h.parent = MockOpener()
974
975 # ordinary redirect behaviour
976 for code in 301, 302, 303, 307:
977 for data in None, "blah\nblah\n":
978 method = getattr(h, "http_error_%s" % code)
979 req = Request(from_url, data)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000980 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000981 req.add_header("Nonsense", "viking=withhold")
Christian Heimes77c02eb2008-02-09 02:18:51 +0000982 if data is not None:
983 req.add_header("Content-Length", str(len(data)))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000984 req.add_unredirected_header("Spam", "spam")
985 try:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000986 method(req, MockFile(), code, "Blah",
987 MockHeaders({"location": to_url}))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000988 except urllib.error.HTTPError:
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000989 # 307 in response to POST requires user OK
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000990 self.assertTrue(code == 307 and data is not None)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000991 self.assertEqual(o.req.get_full_url(), to_url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000992 try:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000993 self.assertEqual(o.req.get_method(), "GET")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000994 except AttributeError:
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -0700995 self.assertFalse(o.req.data)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000996
997 # now it's a GET, there should not be headers regarding content
998 # (possibly dragged from before being a POST)
999 headers = [x.lower() for x in o.req.headers]
Benjamin Peterson577473f2010-01-19 00:09:57 +00001000 self.assertNotIn("content-length", headers)
1001 self.assertNotIn("content-type", headers)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001002
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001003 self.assertEqual(o.req.headers["Nonsense"],
1004 "viking=withhold")
Benjamin Peterson577473f2010-01-19 00:09:57 +00001005 self.assertNotIn("Spam", o.req.headers)
1006 self.assertNotIn("Spam", o.req.unredirected_hdrs)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001007
1008 # loop detection
1009 req = Request(from_url)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001010 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001011 def redirect(h, req, url=to_url):
1012 h.http_error_302(req, MockFile(), 302, "Blah",
1013 MockHeaders({"location": url}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001014 # Note that the *original* request shares the same record of
1015 # redirections with the sub-requests caused by the redirections.
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001016
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001017 # detect infinite loop redirect of a URL to itself
1018 req = Request(from_url, origin_req_host="example.com")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001019 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001020 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001021 try:
1022 while 1:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001023 redirect(h, req, "http://example.com/")
1024 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001025 except urllib.error.HTTPError:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001026 # don't stop until max_repeats, because cookies may introduce state
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001027 self.assertEqual(count, urllib.request.HTTPRedirectHandler.max_repeats)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001028
1029 # detect endless non-repeating chain of redirects
1030 req = Request(from_url, origin_req_host="example.com")
1031 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001032 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001033 try:
1034 while 1:
1035 redirect(h, req, "http://example.com/%d" % count)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001036 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001037 except urllib.error.HTTPError:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001038 self.assertEqual(count,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001039 urllib.request.HTTPRedirectHandler.max_redirections)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001040
guido@google.coma119df92011-03-29 11:41:02 -07001041
1042 def test_invalid_redirect(self):
1043 from_url = "http://example.com/a.html"
1044 valid_schemes = ['http','https','ftp']
1045 invalid_schemes = ['file','imap','ldap']
1046 schemeless_url = "example.com/b.html"
1047 h = urllib.request.HTTPRedirectHandler()
1048 o = h.parent = MockOpener()
1049 req = Request(from_url)
1050 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1051
1052 for scheme in invalid_schemes:
1053 invalid_url = scheme + '://' + schemeless_url
1054 self.assertRaises(urllib.error.HTTPError, h.http_error_302,
1055 req, MockFile(), 302, "Security Loophole",
1056 MockHeaders({"location": invalid_url}))
1057
1058 for scheme in valid_schemes:
1059 valid_url = scheme + '://' + schemeless_url
1060 h.http_error_302(req, MockFile(), 302, "That's fine",
1061 MockHeaders({"location": valid_url}))
1062 self.assertEqual(o.req.get_full_url(), valid_url)
1063
Senthil Kumaran6497aa32012-01-04 13:46:59 +08001064 def test_relative_redirect(self):
1065 from_url = "http://example.com/a.html"
1066 relative_url = "/b.html"
1067 h = urllib.request.HTTPRedirectHandler()
1068 o = h.parent = MockOpener()
1069 req = Request(from_url)
1070 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1071
1072 valid_url = urllib.parse.urljoin(from_url,relative_url)
1073 h.http_error_302(req, MockFile(), 302, "That's fine",
1074 MockHeaders({"location": valid_url}))
1075 self.assertEqual(o.req.get_full_url(), valid_url)
1076
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001077 def test_cookie_redirect(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001078 # cookies shouldn't leak into redirected requests
Georg Brandl24420152008-05-26 16:32:26 +00001079 from http.cookiejar import CookieJar
1080 from test.test_http_cookiejar import interact_netscape
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001081
1082 cj = CookieJar()
1083 interact_netscape(cj, "http://www.example.com/", "spam=eggs")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001084 hh = MockHTTPHandler(302, "Location: http://www.cracker.com/\r\n\r\n")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001085 hdeh = urllib.request.HTTPDefaultErrorHandler()
1086 hrh = urllib.request.HTTPRedirectHandler()
1087 cp = urllib.request.HTTPCookieProcessor(cj)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001088 o = build_test_opener(hh, hdeh, hrh, cp)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001089 o.open("http://www.example.com/")
Florent Xicluna419e3842010-08-08 16:16:07 +00001090 self.assertFalse(hh.req.has_header("Cookie"))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001091
Senthil Kumaran26430412011-04-13 07:01:19 +08001092 def test_redirect_fragment(self):
1093 redirected_url = 'http://www.example.com/index.html#OK\r\n\r\n'
1094 hh = MockHTTPHandler(302, 'Location: ' + redirected_url)
1095 hdeh = urllib.request.HTTPDefaultErrorHandler()
1096 hrh = urllib.request.HTTPRedirectHandler()
1097 o = build_test_opener(hh, hdeh, hrh)
1098 fp = o.open('http://www.example.com')
1099 self.assertEqual(fp.geturl(), redirected_url.strip())
1100
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001101 def test_proxy(self):
1102 o = OpenerDirector()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001103 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001104 o.add_handler(ph)
1105 meth_spec = [
1106 [("http_open", "return response")]
1107 ]
1108 handlers = add_ordered_mock_handlers(o, meth_spec)
1109
1110 req = Request("http://acme.example.com/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001111 self.assertEqual(req.host, "acme.example.com")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001112 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001113 self.assertEqual(req.host, "proxy.example.com:3128")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001114
1115 self.assertEqual([(handlers[0], "http_open")],
1116 [tup[0:2] for tup in o.calls])
1117
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001118 def test_proxy_no_proxy(self):
1119 os.environ['no_proxy'] = 'python.org'
1120 o = OpenerDirector()
1121 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1122 o.add_handler(ph)
1123 req = Request("http://www.perl.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001124 self.assertEqual(req.host, "www.perl.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001125 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001126 self.assertEqual(req.host, "proxy.example.com")
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001127 req = Request("http://www.python.org")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001128 self.assertEqual(req.host, "www.python.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001129 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001130 self.assertEqual(req.host, "www.python.org")
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001131 del os.environ['no_proxy']
1132
Ronald Oussorene72e1612011-03-14 18:15:25 -04001133 def test_proxy_no_proxy_all(self):
1134 os.environ['no_proxy'] = '*'
1135 o = OpenerDirector()
1136 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1137 o.add_handler(ph)
1138 req = Request("http://www.python.org")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001139 self.assertEqual(req.host, "www.python.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001140 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001141 self.assertEqual(req.host, "www.python.org")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001142 del os.environ['no_proxy']
1143
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001144
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001145 def test_proxy_https(self):
1146 o = OpenerDirector()
1147 ph = urllib.request.ProxyHandler(dict(https="proxy.example.com:3128"))
1148 o.add_handler(ph)
1149 meth_spec = [
1150 [("https_open", "return response")]
1151 ]
1152 handlers = add_ordered_mock_handlers(o, meth_spec)
1153
1154 req = Request("https://www.example.com/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001155 self.assertEqual(req.host, "www.example.com")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001156 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001157 self.assertEqual(req.host, "proxy.example.com:3128")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001158 self.assertEqual([(handlers[0], "https_open")],
1159 [tup[0:2] for tup in o.calls])
1160
Senthil Kumaran47fff872009-12-20 07:10:31 +00001161 def test_proxy_https_proxy_authorization(self):
1162 o = OpenerDirector()
1163 ph = urllib.request.ProxyHandler(dict(https='proxy.example.com:3128'))
1164 o.add_handler(ph)
1165 https_handler = MockHTTPSHandler()
1166 o.add_handler(https_handler)
1167 req = Request("https://www.example.com/")
1168 req.add_header("Proxy-Authorization","FooBar")
1169 req.add_header("User-Agent","Grail")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001170 self.assertEqual(req.host, "www.example.com")
Senthil Kumaran47fff872009-12-20 07:10:31 +00001171 self.assertIsNone(req._tunnel_host)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001172 o.open(req)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001173 # Verify Proxy-Authorization gets tunneled to request.
1174 # httpsconn req_headers do not have the Proxy-Authorization header but
1175 # the req will have.
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001176 self.assertNotIn(("Proxy-Authorization","FooBar"),
Senthil Kumaran47fff872009-12-20 07:10:31 +00001177 https_handler.httpconn.req_headers)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001178 self.assertIn(("User-Agent","Grail"),
1179 https_handler.httpconn.req_headers)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001180 self.assertIsNotNone(req._tunnel_host)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001181 self.assertEqual(req.host, "proxy.example.com:3128")
Senthil Kumaran47fff872009-12-20 07:10:31 +00001182 self.assertEqual(req.get_header("Proxy-authorization"),"FooBar")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001183
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001184 # TODO: This should be only for OSX
1185 @unittest.skipUnless(sys.platform == 'darwin', "only relevant for OSX")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001186 def test_osx_proxy_bypass(self):
1187 bypass = {
1188 'exclude_simple': False,
1189 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.10',
1190 '10.0/16']
1191 }
1192 # Check hosts that should trigger the proxy bypass
1193 for host in ('foo.bar', 'www.bar.com', '127.0.0.1', '10.10.0.1',
1194 '10.0.0.1'):
1195 self.assertTrue(_proxy_bypass_macosx_sysconf(host, bypass),
1196 'expected bypass of %s to be True' % host)
1197 # Check hosts that should not trigger the proxy bypass
1198 for host in ('abc.foo.bar', 'bar.com', '127.0.0.2', '10.11.0.1', 'test'):
1199 self.assertFalse(_proxy_bypass_macosx_sysconf(host, bypass),
1200 'expected bypass of %s to be False' % host)
1201
1202 # Check the exclude_simple flag
1203 bypass = {'exclude_simple': True, 'exceptions': []}
1204 self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass))
1205
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001206 def test_basic_auth(self, quote_char='"'):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001207 opener = OpenerDirector()
1208 password_manager = MockPasswordManager()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001209 auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001210 realm = "ACME Widget Store"
1211 http_handler = MockHTTPHandler(
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001212 401, 'WWW-Authenticate: Basic realm=%s%s%s\r\n\r\n' %
1213 (quote_char, realm, quote_char) )
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001214 opener.add_handler(auth_handler)
1215 opener.add_handler(http_handler)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001216 self._test_basic_auth(opener, auth_handler, "Authorization",
1217 realm, http_handler, password_manager,
1218 "http://acme.example.com/protected",
1219 "http://acme.example.com/protected",
1220 )
1221
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001222 def test_basic_auth_with_single_quoted_realm(self):
1223 self.test_basic_auth(quote_char="'")
1224
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +08001225 def test_basic_auth_with_unquoted_realm(self):
1226 opener = OpenerDirector()
1227 password_manager = MockPasswordManager()
1228 auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
1229 realm = "ACME Widget Store"
1230 http_handler = MockHTTPHandler(
1231 401, 'WWW-Authenticate: Basic realm=%s\r\n\r\n' % realm)
1232 opener.add_handler(auth_handler)
1233 opener.add_handler(http_handler)
Senthil Kumaran0ea91cb2012-05-15 23:59:42 +08001234 with self.assertWarns(UserWarning):
1235 self._test_basic_auth(opener, auth_handler, "Authorization",
1236 realm, http_handler, password_manager,
1237 "http://acme.example.com/protected",
1238 "http://acme.example.com/protected",
1239 )
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +08001240
Thomas Wouters477c8d52006-05-27 19:21:47 +00001241 def test_proxy_basic_auth(self):
1242 opener = OpenerDirector()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001243 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001244 opener.add_handler(ph)
1245 password_manager = MockPasswordManager()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001246 auth_handler = urllib.request.ProxyBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001247 realm = "ACME Networks"
1248 http_handler = MockHTTPHandler(
1249 407, 'Proxy-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001250 opener.add_handler(auth_handler)
1251 opener.add_handler(http_handler)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001252 self._test_basic_auth(opener, auth_handler, "Proxy-authorization",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001253 realm, http_handler, password_manager,
1254 "http://acme.example.com:3128/protected",
1255 "proxy.example.com:3128",
1256 )
1257
1258 def test_basic_and_digest_auth_handlers(self):
Andrew Svetlov7bd61cb2012-12-19 22:49:25 +02001259 # HTTPDigestAuthHandler raised an exception if it couldn't handle a 40*
Thomas Wouters477c8d52006-05-27 19:21:47 +00001260 # response (http://python.org/sf/1479302), where it should instead
1261 # return None to allow another handler (especially
1262 # HTTPBasicAuthHandler) to handle the response.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001263
1264 # Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must
1265 # try digest first (since it's the strongest auth scheme), so we record
1266 # order of calls here to check digest comes first:
1267 class RecordingOpenerDirector(OpenerDirector):
1268 def __init__(self):
1269 OpenerDirector.__init__(self)
1270 self.recorded = []
1271 def record(self, info):
1272 self.recorded.append(info)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001273 class TestDigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001274 def http_error_401(self, *args, **kwds):
1275 self.parent.record("digest")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001276 urllib.request.HTTPDigestAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001277 *args, **kwds)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001278 class TestBasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001279 def http_error_401(self, *args, **kwds):
1280 self.parent.record("basic")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001281 urllib.request.HTTPBasicAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001282 *args, **kwds)
1283
1284 opener = RecordingOpenerDirector()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001285 password_manager = MockPasswordManager()
1286 digest_handler = TestDigestAuthHandler(password_manager)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001287 basic_handler = TestBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001288 realm = "ACME Networks"
1289 http_handler = MockHTTPHandler(
1290 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001291 opener.add_handler(basic_handler)
1292 opener.add_handler(digest_handler)
1293 opener.add_handler(http_handler)
1294
1295 # check basic auth isn't blocked by digest handler failing
Thomas Wouters477c8d52006-05-27 19:21:47 +00001296 self._test_basic_auth(opener, basic_handler, "Authorization",
1297 realm, http_handler, password_manager,
1298 "http://acme.example.com/protected",
1299 "http://acme.example.com/protected",
1300 )
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001301 # check digest was tried before basic (twice, because
1302 # _test_basic_auth called .open() twice)
1303 self.assertEqual(opener.recorded, ["digest", "basic"]*2)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001304
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001305 def test_unsupported_auth_digest_handler(self):
1306 opener = OpenerDirector()
1307 # While using DigestAuthHandler
1308 digest_auth_handler = urllib.request.HTTPDigestAuthHandler(None)
1309 http_handler = MockHTTPHandler(
1310 401, 'WWW-Authenticate: Kerberos\r\n\r\n')
1311 opener.add_handler(digest_auth_handler)
1312 opener.add_handler(http_handler)
1313 self.assertRaises(ValueError,opener.open,"http://www.example.com")
1314
1315 def test_unsupported_auth_basic_handler(self):
1316 # While using BasicAuthHandler
1317 opener = OpenerDirector()
1318 basic_auth_handler = urllib.request.HTTPBasicAuthHandler(None)
1319 http_handler = MockHTTPHandler(
1320 401, 'WWW-Authenticate: NTLM\r\n\r\n')
1321 opener.add_handler(basic_auth_handler)
1322 opener.add_handler(http_handler)
1323 self.assertRaises(ValueError,opener.open,"http://www.example.com")
1324
Thomas Wouters477c8d52006-05-27 19:21:47 +00001325 def _test_basic_auth(self, opener, auth_handler, auth_header,
1326 realm, http_handler, password_manager,
1327 request_url, protected_url):
Christian Heimes05e8be12008-02-23 18:30:17 +00001328 import base64
Thomas Wouters477c8d52006-05-27 19:21:47 +00001329 user, password = "wile", "coyote"
Thomas Wouters477c8d52006-05-27 19:21:47 +00001330
1331 # .add_password() fed through to password manager
1332 auth_handler.add_password(realm, request_url, user, password)
1333 self.assertEqual(realm, password_manager.realm)
1334 self.assertEqual(request_url, password_manager.url)
1335 self.assertEqual(user, password_manager.user)
1336 self.assertEqual(password, password_manager.password)
1337
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001338 opener.open(request_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001339
1340 # should have asked the password manager for the username/password
1341 self.assertEqual(password_manager.target_realm, realm)
1342 self.assertEqual(password_manager.target_url, protected_url)
1343
1344 # expect one request without authorization, then one with
1345 self.assertEqual(len(http_handler.requests), 2)
1346 self.assertFalse(http_handler.requests[0].has_header(auth_header))
Guido van Rossum98b349f2007-08-27 21:47:52 +00001347 userpass = bytes('%s:%s' % (user, password), "ascii")
Guido van Rossum98297ee2007-11-06 21:34:58 +00001348 auth_hdr_value = ('Basic ' +
Georg Brandl706824f2009-06-04 09:42:55 +00001349 base64.encodebytes(userpass).strip().decode())
Thomas Wouters477c8d52006-05-27 19:21:47 +00001350 self.assertEqual(http_handler.requests[1].get_header(auth_header),
1351 auth_hdr_value)
Senthil Kumaranca2fc9e2010-02-24 16:53:16 +00001352 self.assertEqual(http_handler.requests[1].unredirected_hdrs[auth_header],
1353 auth_hdr_value)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001354 # if the password manager can't find a password, the handler won't
1355 # handle the HTTP auth error
1356 password_manager.user = password_manager.password = None
1357 http_handler.reset()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001358 opener.open(request_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001359 self.assertEqual(len(http_handler.requests), 1)
1360 self.assertFalse(http_handler.requests[0].has_header(auth_header))
1361
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001362
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001363class MiscTests(unittest.TestCase):
1364
Senthil Kumarane9853da2013-03-19 12:07:43 -07001365 def opener_has_handler(self, opener, handler_class):
1366 self.assertTrue(any(h.__class__ == handler_class
1367 for h in opener.handlers))
1368
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001369 def test_build_opener(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001370 class MyHTTPHandler(urllib.request.HTTPHandler): pass
1371 class FooHandler(urllib.request.BaseHandler):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001372 def foo_open(self): pass
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001373 class BarHandler(urllib.request.BaseHandler):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001374 def bar_open(self): pass
1375
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001376 build_opener = urllib.request.build_opener
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001377
1378 o = build_opener(FooHandler, BarHandler)
1379 self.opener_has_handler(o, FooHandler)
1380 self.opener_has_handler(o, BarHandler)
1381
1382 # can take a mix of classes and instances
1383 o = build_opener(FooHandler, BarHandler())
1384 self.opener_has_handler(o, FooHandler)
1385 self.opener_has_handler(o, BarHandler)
1386
1387 # subclasses of default handlers override default handlers
1388 o = build_opener(MyHTTPHandler)
1389 self.opener_has_handler(o, MyHTTPHandler)
1390
1391 # a particular case of overriding: default handlers can be passed
1392 # in explicitly
1393 o = build_opener()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001394 self.opener_has_handler(o, urllib.request.HTTPHandler)
1395 o = build_opener(urllib.request.HTTPHandler)
1396 self.opener_has_handler(o, urllib.request.HTTPHandler)
1397 o = build_opener(urllib.request.HTTPHandler())
1398 self.opener_has_handler(o, urllib.request.HTTPHandler)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001399
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001400 # Issue2670: multiple handlers sharing the same base class
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001401 class MyOtherHTTPHandler(urllib.request.HTTPHandler): pass
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001402 o = build_opener(MyHTTPHandler, MyOtherHTTPHandler)
1403 self.opener_has_handler(o, MyHTTPHandler)
1404 self.opener_has_handler(o, MyOtherHTTPHandler)
1405
Brett Cannon80512de2013-01-25 22:27:21 -05001406 @unittest.skipUnless(support.is_resource_enabled('network'),
1407 'test requires network access')
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001408 def test_issue16464(self):
1409 opener = urllib.request.build_opener()
1410 request = urllib.request.Request("http://www.python.org/~jeremy/")
1411 self.assertEqual(None, request.data)
1412
1413 opener.open(request, "1".encode("us-ascii"))
1414 self.assertEqual(b"1", request.data)
1415 self.assertEqual("1", request.get_header("Content-length"))
1416
1417 opener.open(request, "1234567890".encode("us-ascii"))
1418 self.assertEqual(b"1234567890", request.data)
1419 self.assertEqual("10", request.get_header("Content-length"))
1420
Senthil Kumarane9853da2013-03-19 12:07:43 -07001421 def test_HTTPError_interface(self):
1422 """
1423 Issue 13211 reveals that HTTPError didn't implement the URLError
1424 interface even though HTTPError is a subclass of URLError.
Senthil Kumarane9853da2013-03-19 12:07:43 -07001425 """
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001426 msg = 'something bad happened'
1427 url = code = fp = None
1428 hdrs = 'Content-Length: 42'
1429 err = urllib.error.HTTPError(url, code, msg, hdrs, fp)
1430 self.assertTrue(hasattr(err, 'reason'))
1431 self.assertEqual(err.reason, 'something bad happened')
1432 self.assertTrue(hasattr(err, 'headers'))
1433 self.assertEqual(err.headers, 'Content-Length: 42')
1434 expected_errmsg = 'HTTP Error %s: %s' % (err.code, err.msg)
1435 self.assertEqual(str(err), expected_errmsg)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001436
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001437class RequestTests(unittest.TestCase):
1438
1439 def setUp(self):
1440 self.get = Request("http://www.python.org/~jeremy/")
1441 self.post = Request("http://www.python.org/~jeremy/",
1442 "data",
1443 headers={"X-Test": "test"})
1444
1445 def test_method(self):
1446 self.assertEqual("POST", self.post.get_method())
1447 self.assertEqual("GET", self.get.get_method())
1448
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001449 def test_data(self):
1450 self.assertFalse(self.get.data)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001451 self.assertEqual("GET", self.get.get_method())
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001452 self.get.data = "spam"
1453 self.assertTrue(self.get.data)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001454 self.assertEqual("POST", self.get.get_method())
1455
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001456 # issue 16464
1457 # if we change data we need to remove content-length header
1458 # (cause it's most probably calculated for previous value)
1459 def test_setting_data_should_remove_content_length(self):
R David Murray9cc7d452013-03-20 00:10:51 -04001460 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001461 self.get.add_unredirected_header("Content-length", 42)
1462 self.assertEqual(42, self.get.unredirected_hdrs["Content-length"])
1463 self.get.data = "spam"
R David Murray9cc7d452013-03-20 00:10:51 -04001464 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
1465
1466 # issue 17485 same for deleting data.
1467 def test_deleting_data_should_remove_content_length(self):
1468 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
1469 self.get.data = 'foo'
1470 self.get.add_unredirected_header("Content-length", 3)
1471 self.assertEqual(3, self.get.unredirected_hdrs["Content-length"])
1472 del self.get.data
1473 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001474
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001475 def test_get_full_url(self):
1476 self.assertEqual("http://www.python.org/~jeremy/",
1477 self.get.get_full_url())
1478
1479 def test_selector(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001480 self.assertEqual("/~jeremy/", self.get.selector)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001481 req = Request("http://www.python.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001482 self.assertEqual("/", req.selector)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001483
1484 def test_get_type(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001485 self.assertEqual("http", self.get.type)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001486
1487 def test_get_host(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001488 self.assertEqual("www.python.org", self.get.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001489
1490 def test_get_host_unquote(self):
1491 req = Request("http://www.%70ython.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001492 self.assertEqual("www.python.org", req.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001493
1494 def test_proxy(self):
Florent Xicluna419e3842010-08-08 16:16:07 +00001495 self.assertFalse(self.get.has_proxy())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001496 self.get.set_proxy("www.perl.org", "http")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001497 self.assertTrue(self.get.has_proxy())
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001498 self.assertEqual("www.python.org", self.get.origin_req_host)
1499 self.assertEqual("www.perl.org", self.get.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001500
Senthil Kumarand95cc752010-08-08 11:27:53 +00001501 def test_wrapped_url(self):
1502 req = Request("<URL:http://www.python.org>")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001503 self.assertEqual("www.python.org", req.host)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001504
Senthil Kumaran26430412011-04-13 07:01:19 +08001505 def test_url_fragment(self):
Senthil Kumarand95cc752010-08-08 11:27:53 +00001506 req = Request("http://www.python.org/?qs=query#fragment=true")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001507 self.assertEqual("/?qs=query", req.selector)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001508 req = Request("http://www.python.org/#fun=true")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001509 self.assertEqual("/", req.selector)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001510
Senthil Kumaran26430412011-04-13 07:01:19 +08001511 # Issue 11703: geturl() omits fragment in the original URL.
1512 url = 'http://docs.python.org/library/urllib2.html#OK'
1513 req = Request(url)
1514 self.assertEqual(req.get_full_url(), url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001515
1516def test_main(verbose=None):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001517 from test import test_urllib2
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001518 support.run_doctest(test_urllib2, verbose)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001519 support.run_doctest(urllib.request, verbose)
Andrew M. Kuchlingbd3200f2004-06-29 13:15:46 +00001520 tests = (TrivialTests,
1521 OpenerDirectorTests,
1522 HandlerTests,
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001523 MiscTests,
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001524 RequestTests,
1525 RequestHdrsTests)
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001526 support.run_unittest(*tests)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001527
1528if __name__ == "__main__":
1529 test_main(verbose=True)