blob: b4f940ccf9696731cdb398f9da892dfffccd3221 [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 Kumaran52380922013-04-25 05:45:48 -0700907 def test_full_url_setter(self):
908 # Checks to ensure that components are set correctly after setting the
909 # full_url of a Request object
910
911 urls = [
912 'http://example.com?foo=bar#baz',
913 'http://example.com?foo=bar&spam=eggs#bash',
914 'http://example.com',
915 ]
916
917 # testing a reusable request instance, but the url parameter is
918 # required, so just use a dummy one to instantiate
919 r = Request('http://example.com')
920 for url in urls:
921 r.full_url = url
922 self.assertEqual(r.get_full_url(), url)
923
924 def test_full_url_deleter(self):
925 r = Request('http://www.example.com')
926 del r.full_url
927 self.assertIsNone(r.full_url)
928 self.assertIsNone(r.fragment)
929 self.assertEqual(r.selector, '')
930
Senthil Kumaranc2958622010-11-22 04:48:26 +0000931 def test_fixpath_in_weirdurls(self):
932 # Issue4493: urllib2 to supply '/' when to urls where path does not
933 # start with'/'
934
935 h = urllib.request.AbstractHTTPHandler()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700936 h.parent = MockOpener()
Senthil Kumaranc2958622010-11-22 04:48:26 +0000937
938 weird_url = 'http://www.python.org?getspam'
939 req = Request(weird_url)
940 newreq = h.do_request_(req)
941 self.assertEqual(newreq.host,'www.python.org')
942 self.assertEqual(newreq.selector,'/?getspam')
943
944 url_without_path = 'http://www.python.org'
945 req = Request(url_without_path)
946 newreq = h.do_request_(req)
947 self.assertEqual(newreq.host,'www.python.org')
948 self.assertEqual(newreq.selector,'')
949
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000950
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000951 def test_errors(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000952 h = urllib.request.HTTPErrorProcessor()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000953 o = h.parent = MockOpener()
954
955 url = "http://example.com/"
956 req = Request(url)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000957 # all 2xx are passed through
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000958 r = MockResponse(200, "OK", {}, "", url)
959 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +0000960 self.assertIs(r, newr)
961 self.assertFalse(hasattr(o, "proto")) # o.error not called
Guido van Rossumd8faa362007-04-27 19:54:29 +0000962 r = MockResponse(202, "Accepted", {}, "", url)
963 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +0000964 self.assertIs(r, newr)
965 self.assertFalse(hasattr(o, "proto")) # o.error not called
Guido van Rossumd8faa362007-04-27 19:54:29 +0000966 r = MockResponse(206, "Partial content", {}, "", url)
967 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +0000968 self.assertIs(r, newr)
969 self.assertFalse(hasattr(o, "proto")) # o.error not called
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000970 # anything else calls o.error (and MockOpener returns None, here)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000971 r = MockResponse(502, "Bad gateway", {}, "", url)
Florent Xicluna419e3842010-08-08 16:16:07 +0000972 self.assertIsNone(h.http_response(req, r))
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000973 self.assertEqual(o.proto, "http") # o.error called
Guido van Rossumd8faa362007-04-27 19:54:29 +0000974 self.assertEqual(o.args, (req, r, 502, "Bad gateway", {}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000975
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000976 def test_cookies(self):
977 cj = MockCookieJar()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000978 h = urllib.request.HTTPCookieProcessor(cj)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700979 h.parent = MockOpener()
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000980
981 req = Request("http://example.com/")
982 r = MockResponse(200, "OK", {}, "")
983 newreq = h.http_request(req)
Florent Xicluna419e3842010-08-08 16:16:07 +0000984 self.assertIs(cj.ach_req, req)
985 self.assertIs(cj.ach_req, newreq)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -0700986 self.assertEqual(req.origin_req_host, "example.com")
987 self.assertFalse(req.unverifiable)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000988 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +0000989 self.assertIs(cj.ec_req, req)
990 self.assertIs(cj.ec_r, r)
991 self.assertIs(r, newr)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000992
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000993 def test_redirect(self):
994 from_url = "http://example.com/a.html"
995 to_url = "http://example.com/b.html"
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000996 h = urllib.request.HTTPRedirectHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000997 o = h.parent = MockOpener()
998
999 # ordinary redirect behaviour
1000 for code in 301, 302, 303, 307:
1001 for data in None, "blah\nblah\n":
1002 method = getattr(h, "http_error_%s" % code)
1003 req = Request(from_url, data)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001004 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001005 req.add_header("Nonsense", "viking=withhold")
Christian Heimes77c02eb2008-02-09 02:18:51 +00001006 if data is not None:
1007 req.add_header("Content-Length", str(len(data)))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001008 req.add_unredirected_header("Spam", "spam")
1009 try:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001010 method(req, MockFile(), code, "Blah",
1011 MockHeaders({"location": to_url}))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001012 except urllib.error.HTTPError:
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001013 # 307 in response to POST requires user OK
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001014 self.assertTrue(code == 307 and data is not None)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001015 self.assertEqual(o.req.get_full_url(), to_url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001016 try:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001017 self.assertEqual(o.req.get_method(), "GET")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001018 except AttributeError:
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001019 self.assertFalse(o.req.data)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001020
1021 # now it's a GET, there should not be headers regarding content
1022 # (possibly dragged from before being a POST)
1023 headers = [x.lower() for x in o.req.headers]
Benjamin Peterson577473f2010-01-19 00:09:57 +00001024 self.assertNotIn("content-length", headers)
1025 self.assertNotIn("content-type", headers)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001026
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001027 self.assertEqual(o.req.headers["Nonsense"],
1028 "viking=withhold")
Benjamin Peterson577473f2010-01-19 00:09:57 +00001029 self.assertNotIn("Spam", o.req.headers)
1030 self.assertNotIn("Spam", o.req.unredirected_hdrs)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001031
1032 # loop detection
1033 req = Request(from_url)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001034 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001035 def redirect(h, req, url=to_url):
1036 h.http_error_302(req, MockFile(), 302, "Blah",
1037 MockHeaders({"location": url}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001038 # Note that the *original* request shares the same record of
1039 # redirections with the sub-requests caused by the redirections.
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001040
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001041 # detect infinite loop redirect of a URL to itself
1042 req = Request(from_url, origin_req_host="example.com")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001043 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001044 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001045 try:
1046 while 1:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001047 redirect(h, req, "http://example.com/")
1048 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001049 except urllib.error.HTTPError:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001050 # don't stop until max_repeats, because cookies may introduce state
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001051 self.assertEqual(count, urllib.request.HTTPRedirectHandler.max_repeats)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001052
1053 # detect endless non-repeating chain of redirects
1054 req = Request(from_url, origin_req_host="example.com")
1055 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001056 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001057 try:
1058 while 1:
1059 redirect(h, req, "http://example.com/%d" % count)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001060 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001061 except urllib.error.HTTPError:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001062 self.assertEqual(count,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001063 urllib.request.HTTPRedirectHandler.max_redirections)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001064
guido@google.coma119df92011-03-29 11:41:02 -07001065
1066 def test_invalid_redirect(self):
1067 from_url = "http://example.com/a.html"
1068 valid_schemes = ['http','https','ftp']
1069 invalid_schemes = ['file','imap','ldap']
1070 schemeless_url = "example.com/b.html"
1071 h = urllib.request.HTTPRedirectHandler()
1072 o = h.parent = MockOpener()
1073 req = Request(from_url)
1074 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1075
1076 for scheme in invalid_schemes:
1077 invalid_url = scheme + '://' + schemeless_url
1078 self.assertRaises(urllib.error.HTTPError, h.http_error_302,
1079 req, MockFile(), 302, "Security Loophole",
1080 MockHeaders({"location": invalid_url}))
1081
1082 for scheme in valid_schemes:
1083 valid_url = scheme + '://' + schemeless_url
1084 h.http_error_302(req, MockFile(), 302, "That's fine",
1085 MockHeaders({"location": valid_url}))
1086 self.assertEqual(o.req.get_full_url(), valid_url)
1087
Senthil Kumaran6497aa32012-01-04 13:46:59 +08001088 def test_relative_redirect(self):
1089 from_url = "http://example.com/a.html"
1090 relative_url = "/b.html"
1091 h = urllib.request.HTTPRedirectHandler()
1092 o = h.parent = MockOpener()
1093 req = Request(from_url)
1094 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1095
1096 valid_url = urllib.parse.urljoin(from_url,relative_url)
1097 h.http_error_302(req, MockFile(), 302, "That's fine",
1098 MockHeaders({"location": valid_url}))
1099 self.assertEqual(o.req.get_full_url(), valid_url)
1100
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001101 def test_cookie_redirect(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001102 # cookies shouldn't leak into redirected requests
Georg Brandl24420152008-05-26 16:32:26 +00001103 from http.cookiejar import CookieJar
1104 from test.test_http_cookiejar import interact_netscape
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001105
1106 cj = CookieJar()
1107 interact_netscape(cj, "http://www.example.com/", "spam=eggs")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001108 hh = MockHTTPHandler(302, "Location: http://www.cracker.com/\r\n\r\n")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001109 hdeh = urllib.request.HTTPDefaultErrorHandler()
1110 hrh = urllib.request.HTTPRedirectHandler()
1111 cp = urllib.request.HTTPCookieProcessor(cj)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001112 o = build_test_opener(hh, hdeh, hrh, cp)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001113 o.open("http://www.example.com/")
Florent Xicluna419e3842010-08-08 16:16:07 +00001114 self.assertFalse(hh.req.has_header("Cookie"))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001115
Senthil Kumaran26430412011-04-13 07:01:19 +08001116 def test_redirect_fragment(self):
1117 redirected_url = 'http://www.example.com/index.html#OK\r\n\r\n'
1118 hh = MockHTTPHandler(302, 'Location: ' + redirected_url)
1119 hdeh = urllib.request.HTTPDefaultErrorHandler()
1120 hrh = urllib.request.HTTPRedirectHandler()
1121 o = build_test_opener(hh, hdeh, hrh)
1122 fp = o.open('http://www.example.com')
1123 self.assertEqual(fp.geturl(), redirected_url.strip())
1124
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001125 def test_proxy(self):
1126 o = OpenerDirector()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001127 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001128 o.add_handler(ph)
1129 meth_spec = [
1130 [("http_open", "return response")]
1131 ]
1132 handlers = add_ordered_mock_handlers(o, meth_spec)
1133
1134 req = Request("http://acme.example.com/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001135 self.assertEqual(req.host, "acme.example.com")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001136 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001137 self.assertEqual(req.host, "proxy.example.com:3128")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001138
1139 self.assertEqual([(handlers[0], "http_open")],
1140 [tup[0:2] for tup in o.calls])
1141
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001142 def test_proxy_no_proxy(self):
1143 os.environ['no_proxy'] = 'python.org'
1144 o = OpenerDirector()
1145 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1146 o.add_handler(ph)
1147 req = Request("http://www.perl.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001148 self.assertEqual(req.host, "www.perl.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001149 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001150 self.assertEqual(req.host, "proxy.example.com")
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001151 req = Request("http://www.python.org")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001152 self.assertEqual(req.host, "www.python.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001153 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001154 self.assertEqual(req.host, "www.python.org")
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001155 del os.environ['no_proxy']
1156
Ronald Oussorene72e1612011-03-14 18:15:25 -04001157 def test_proxy_no_proxy_all(self):
1158 os.environ['no_proxy'] = '*'
1159 o = OpenerDirector()
1160 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1161 o.add_handler(ph)
1162 req = Request("http://www.python.org")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001163 self.assertEqual(req.host, "www.python.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001164 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001165 self.assertEqual(req.host, "www.python.org")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001166 del os.environ['no_proxy']
1167
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001168
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001169 def test_proxy_https(self):
1170 o = OpenerDirector()
1171 ph = urllib.request.ProxyHandler(dict(https="proxy.example.com:3128"))
1172 o.add_handler(ph)
1173 meth_spec = [
1174 [("https_open", "return response")]
1175 ]
1176 handlers = add_ordered_mock_handlers(o, meth_spec)
1177
1178 req = Request("https://www.example.com/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001179 self.assertEqual(req.host, "www.example.com")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001180 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001181 self.assertEqual(req.host, "proxy.example.com:3128")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001182 self.assertEqual([(handlers[0], "https_open")],
1183 [tup[0:2] for tup in o.calls])
1184
Senthil Kumaran47fff872009-12-20 07:10:31 +00001185 def test_proxy_https_proxy_authorization(self):
1186 o = OpenerDirector()
1187 ph = urllib.request.ProxyHandler(dict(https='proxy.example.com:3128'))
1188 o.add_handler(ph)
1189 https_handler = MockHTTPSHandler()
1190 o.add_handler(https_handler)
1191 req = Request("https://www.example.com/")
1192 req.add_header("Proxy-Authorization","FooBar")
1193 req.add_header("User-Agent","Grail")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001194 self.assertEqual(req.host, "www.example.com")
Senthil Kumaran47fff872009-12-20 07:10:31 +00001195 self.assertIsNone(req._tunnel_host)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001196 o.open(req)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001197 # Verify Proxy-Authorization gets tunneled to request.
1198 # httpsconn req_headers do not have the Proxy-Authorization header but
1199 # the req will have.
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001200 self.assertNotIn(("Proxy-Authorization","FooBar"),
Senthil Kumaran47fff872009-12-20 07:10:31 +00001201 https_handler.httpconn.req_headers)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001202 self.assertIn(("User-Agent","Grail"),
1203 https_handler.httpconn.req_headers)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001204 self.assertIsNotNone(req._tunnel_host)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001205 self.assertEqual(req.host, "proxy.example.com:3128")
Senthil Kumaran47fff872009-12-20 07:10:31 +00001206 self.assertEqual(req.get_header("Proxy-authorization"),"FooBar")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001207
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001208 # TODO: This should be only for OSX
1209 @unittest.skipUnless(sys.platform == 'darwin', "only relevant for OSX")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001210 def test_osx_proxy_bypass(self):
1211 bypass = {
1212 'exclude_simple': False,
1213 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.10',
1214 '10.0/16']
1215 }
1216 # Check hosts that should trigger the proxy bypass
1217 for host in ('foo.bar', 'www.bar.com', '127.0.0.1', '10.10.0.1',
1218 '10.0.0.1'):
1219 self.assertTrue(_proxy_bypass_macosx_sysconf(host, bypass),
1220 'expected bypass of %s to be True' % host)
1221 # Check hosts that should not trigger the proxy bypass
1222 for host in ('abc.foo.bar', 'bar.com', '127.0.0.2', '10.11.0.1', 'test'):
1223 self.assertFalse(_proxy_bypass_macosx_sysconf(host, bypass),
1224 'expected bypass of %s to be False' % host)
1225
1226 # Check the exclude_simple flag
1227 bypass = {'exclude_simple': True, 'exceptions': []}
1228 self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass))
1229
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001230 def test_basic_auth(self, quote_char='"'):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001231 opener = OpenerDirector()
1232 password_manager = MockPasswordManager()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001233 auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001234 realm = "ACME Widget Store"
1235 http_handler = MockHTTPHandler(
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001236 401, 'WWW-Authenticate: Basic realm=%s%s%s\r\n\r\n' %
1237 (quote_char, realm, quote_char) )
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001238 opener.add_handler(auth_handler)
1239 opener.add_handler(http_handler)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001240 self._test_basic_auth(opener, auth_handler, "Authorization",
1241 realm, http_handler, password_manager,
1242 "http://acme.example.com/protected",
1243 "http://acme.example.com/protected",
1244 )
1245
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001246 def test_basic_auth_with_single_quoted_realm(self):
1247 self.test_basic_auth(quote_char="'")
1248
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +08001249 def test_basic_auth_with_unquoted_realm(self):
1250 opener = OpenerDirector()
1251 password_manager = MockPasswordManager()
1252 auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
1253 realm = "ACME Widget Store"
1254 http_handler = MockHTTPHandler(
1255 401, 'WWW-Authenticate: Basic realm=%s\r\n\r\n' % realm)
1256 opener.add_handler(auth_handler)
1257 opener.add_handler(http_handler)
Senthil Kumaran0ea91cb2012-05-15 23:59:42 +08001258 with self.assertWarns(UserWarning):
1259 self._test_basic_auth(opener, auth_handler, "Authorization",
1260 realm, http_handler, password_manager,
1261 "http://acme.example.com/protected",
1262 "http://acme.example.com/protected",
1263 )
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +08001264
Thomas Wouters477c8d52006-05-27 19:21:47 +00001265 def test_proxy_basic_auth(self):
1266 opener = OpenerDirector()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001267 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001268 opener.add_handler(ph)
1269 password_manager = MockPasswordManager()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001270 auth_handler = urllib.request.ProxyBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001271 realm = "ACME Networks"
1272 http_handler = MockHTTPHandler(
1273 407, 'Proxy-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001274 opener.add_handler(auth_handler)
1275 opener.add_handler(http_handler)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001276 self._test_basic_auth(opener, auth_handler, "Proxy-authorization",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001277 realm, http_handler, password_manager,
1278 "http://acme.example.com:3128/protected",
1279 "proxy.example.com:3128",
1280 )
1281
1282 def test_basic_and_digest_auth_handlers(self):
Andrew Svetlov7bd61cb2012-12-19 22:49:25 +02001283 # HTTPDigestAuthHandler raised an exception if it couldn't handle a 40*
Thomas Wouters477c8d52006-05-27 19:21:47 +00001284 # response (http://python.org/sf/1479302), where it should instead
1285 # return None to allow another handler (especially
1286 # HTTPBasicAuthHandler) to handle the response.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001287
1288 # Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must
1289 # try digest first (since it's the strongest auth scheme), so we record
1290 # order of calls here to check digest comes first:
1291 class RecordingOpenerDirector(OpenerDirector):
1292 def __init__(self):
1293 OpenerDirector.__init__(self)
1294 self.recorded = []
1295 def record(self, info):
1296 self.recorded.append(info)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001297 class TestDigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001298 def http_error_401(self, *args, **kwds):
1299 self.parent.record("digest")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001300 urllib.request.HTTPDigestAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001301 *args, **kwds)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001302 class TestBasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001303 def http_error_401(self, *args, **kwds):
1304 self.parent.record("basic")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001305 urllib.request.HTTPBasicAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001306 *args, **kwds)
1307
1308 opener = RecordingOpenerDirector()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001309 password_manager = MockPasswordManager()
1310 digest_handler = TestDigestAuthHandler(password_manager)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001311 basic_handler = TestBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001312 realm = "ACME Networks"
1313 http_handler = MockHTTPHandler(
1314 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001315 opener.add_handler(basic_handler)
1316 opener.add_handler(digest_handler)
1317 opener.add_handler(http_handler)
1318
1319 # check basic auth isn't blocked by digest handler failing
Thomas Wouters477c8d52006-05-27 19:21:47 +00001320 self._test_basic_auth(opener, basic_handler, "Authorization",
1321 realm, http_handler, password_manager,
1322 "http://acme.example.com/protected",
1323 "http://acme.example.com/protected",
1324 )
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001325 # check digest was tried before basic (twice, because
1326 # _test_basic_auth called .open() twice)
1327 self.assertEqual(opener.recorded, ["digest", "basic"]*2)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001328
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001329 def test_unsupported_auth_digest_handler(self):
1330 opener = OpenerDirector()
1331 # While using DigestAuthHandler
1332 digest_auth_handler = urllib.request.HTTPDigestAuthHandler(None)
1333 http_handler = MockHTTPHandler(
1334 401, 'WWW-Authenticate: Kerberos\r\n\r\n')
1335 opener.add_handler(digest_auth_handler)
1336 opener.add_handler(http_handler)
1337 self.assertRaises(ValueError,opener.open,"http://www.example.com")
1338
1339 def test_unsupported_auth_basic_handler(self):
1340 # While using BasicAuthHandler
1341 opener = OpenerDirector()
1342 basic_auth_handler = urllib.request.HTTPBasicAuthHandler(None)
1343 http_handler = MockHTTPHandler(
1344 401, 'WWW-Authenticate: NTLM\r\n\r\n')
1345 opener.add_handler(basic_auth_handler)
1346 opener.add_handler(http_handler)
1347 self.assertRaises(ValueError,opener.open,"http://www.example.com")
1348
Thomas Wouters477c8d52006-05-27 19:21:47 +00001349 def _test_basic_auth(self, opener, auth_handler, auth_header,
1350 realm, http_handler, password_manager,
1351 request_url, protected_url):
Christian Heimes05e8be12008-02-23 18:30:17 +00001352 import base64
Thomas Wouters477c8d52006-05-27 19:21:47 +00001353 user, password = "wile", "coyote"
Thomas Wouters477c8d52006-05-27 19:21:47 +00001354
1355 # .add_password() fed through to password manager
1356 auth_handler.add_password(realm, request_url, user, password)
1357 self.assertEqual(realm, password_manager.realm)
1358 self.assertEqual(request_url, password_manager.url)
1359 self.assertEqual(user, password_manager.user)
1360 self.assertEqual(password, password_manager.password)
1361
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001362 opener.open(request_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001363
1364 # should have asked the password manager for the username/password
1365 self.assertEqual(password_manager.target_realm, realm)
1366 self.assertEqual(password_manager.target_url, protected_url)
1367
1368 # expect one request without authorization, then one with
1369 self.assertEqual(len(http_handler.requests), 2)
1370 self.assertFalse(http_handler.requests[0].has_header(auth_header))
Guido van Rossum98b349f2007-08-27 21:47:52 +00001371 userpass = bytes('%s:%s' % (user, password), "ascii")
Guido van Rossum98297ee2007-11-06 21:34:58 +00001372 auth_hdr_value = ('Basic ' +
Georg Brandl706824f2009-06-04 09:42:55 +00001373 base64.encodebytes(userpass).strip().decode())
Thomas Wouters477c8d52006-05-27 19:21:47 +00001374 self.assertEqual(http_handler.requests[1].get_header(auth_header),
1375 auth_hdr_value)
Senthil Kumaranca2fc9e2010-02-24 16:53:16 +00001376 self.assertEqual(http_handler.requests[1].unredirected_hdrs[auth_header],
1377 auth_hdr_value)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001378 # if the password manager can't find a password, the handler won't
1379 # handle the HTTP auth error
1380 password_manager.user = password_manager.password = None
1381 http_handler.reset()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001382 opener.open(request_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001383 self.assertEqual(len(http_handler.requests), 1)
1384 self.assertFalse(http_handler.requests[0].has_header(auth_header))
1385
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001386
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001387class MiscTests(unittest.TestCase):
1388
Senthil Kumarane9853da2013-03-19 12:07:43 -07001389 def opener_has_handler(self, opener, handler_class):
1390 self.assertTrue(any(h.__class__ == handler_class
1391 for h in opener.handlers))
1392
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001393 def test_build_opener(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001394 class MyHTTPHandler(urllib.request.HTTPHandler): pass
1395 class FooHandler(urllib.request.BaseHandler):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001396 def foo_open(self): pass
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001397 class BarHandler(urllib.request.BaseHandler):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001398 def bar_open(self): pass
1399
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001400 build_opener = urllib.request.build_opener
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001401
1402 o = build_opener(FooHandler, BarHandler)
1403 self.opener_has_handler(o, FooHandler)
1404 self.opener_has_handler(o, BarHandler)
1405
1406 # can take a mix of classes and instances
1407 o = build_opener(FooHandler, BarHandler())
1408 self.opener_has_handler(o, FooHandler)
1409 self.opener_has_handler(o, BarHandler)
1410
1411 # subclasses of default handlers override default handlers
1412 o = build_opener(MyHTTPHandler)
1413 self.opener_has_handler(o, MyHTTPHandler)
1414
1415 # a particular case of overriding: default handlers can be passed
1416 # in explicitly
1417 o = build_opener()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001418 self.opener_has_handler(o, urllib.request.HTTPHandler)
1419 o = build_opener(urllib.request.HTTPHandler)
1420 self.opener_has_handler(o, urllib.request.HTTPHandler)
1421 o = build_opener(urllib.request.HTTPHandler())
1422 self.opener_has_handler(o, urllib.request.HTTPHandler)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001423
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001424 # Issue2670: multiple handlers sharing the same base class
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001425 class MyOtherHTTPHandler(urllib.request.HTTPHandler): pass
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001426 o = build_opener(MyHTTPHandler, MyOtherHTTPHandler)
1427 self.opener_has_handler(o, MyHTTPHandler)
1428 self.opener_has_handler(o, MyOtherHTTPHandler)
1429
Brett Cannon80512de2013-01-25 22:27:21 -05001430 @unittest.skipUnless(support.is_resource_enabled('network'),
1431 'test requires network access')
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001432 def test_issue16464(self):
1433 opener = urllib.request.build_opener()
1434 request = urllib.request.Request("http://www.python.org/~jeremy/")
1435 self.assertEqual(None, request.data)
1436
1437 opener.open(request, "1".encode("us-ascii"))
1438 self.assertEqual(b"1", request.data)
1439 self.assertEqual("1", request.get_header("Content-length"))
1440
1441 opener.open(request, "1234567890".encode("us-ascii"))
1442 self.assertEqual(b"1234567890", request.data)
1443 self.assertEqual("10", request.get_header("Content-length"))
1444
Senthil Kumarane9853da2013-03-19 12:07:43 -07001445 def test_HTTPError_interface(self):
1446 """
1447 Issue 13211 reveals that HTTPError didn't implement the URLError
1448 interface even though HTTPError is a subclass of URLError.
Senthil Kumarane9853da2013-03-19 12:07:43 -07001449 """
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001450 msg = 'something bad happened'
1451 url = code = fp = None
1452 hdrs = 'Content-Length: 42'
1453 err = urllib.error.HTTPError(url, code, msg, hdrs, fp)
1454 self.assertTrue(hasattr(err, 'reason'))
1455 self.assertEqual(err.reason, 'something bad happened')
1456 self.assertTrue(hasattr(err, 'headers'))
1457 self.assertEqual(err.headers, 'Content-Length: 42')
1458 expected_errmsg = 'HTTP Error %s: %s' % (err.code, err.msg)
1459 self.assertEqual(str(err), expected_errmsg)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001460
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001461class RequestTests(unittest.TestCase):
1462
1463 def setUp(self):
1464 self.get = Request("http://www.python.org/~jeremy/")
1465 self.post = Request("http://www.python.org/~jeremy/",
1466 "data",
1467 headers={"X-Test": "test"})
1468
1469 def test_method(self):
1470 self.assertEqual("POST", self.post.get_method())
1471 self.assertEqual("GET", self.get.get_method())
1472
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001473 def test_data(self):
1474 self.assertFalse(self.get.data)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001475 self.assertEqual("GET", self.get.get_method())
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001476 self.get.data = "spam"
1477 self.assertTrue(self.get.data)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001478 self.assertEqual("POST", self.get.get_method())
1479
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001480 # issue 16464
1481 # if we change data we need to remove content-length header
1482 # (cause it's most probably calculated for previous value)
1483 def test_setting_data_should_remove_content_length(self):
R David Murray9cc7d452013-03-20 00:10:51 -04001484 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001485 self.get.add_unredirected_header("Content-length", 42)
1486 self.assertEqual(42, self.get.unredirected_hdrs["Content-length"])
1487 self.get.data = "spam"
R David Murray9cc7d452013-03-20 00:10:51 -04001488 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
1489
1490 # issue 17485 same for deleting data.
1491 def test_deleting_data_should_remove_content_length(self):
1492 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
1493 self.get.data = 'foo'
1494 self.get.add_unredirected_header("Content-length", 3)
1495 self.assertEqual(3, self.get.unredirected_hdrs["Content-length"])
1496 del self.get.data
1497 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001498
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001499 def test_get_full_url(self):
1500 self.assertEqual("http://www.python.org/~jeremy/",
1501 self.get.get_full_url())
1502
1503 def test_selector(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001504 self.assertEqual("/~jeremy/", self.get.selector)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001505 req = Request("http://www.python.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001506 self.assertEqual("/", req.selector)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001507
1508 def test_get_type(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001509 self.assertEqual("http", self.get.type)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001510
1511 def test_get_host(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001512 self.assertEqual("www.python.org", self.get.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001513
1514 def test_get_host_unquote(self):
1515 req = Request("http://www.%70ython.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001516 self.assertEqual("www.python.org", req.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001517
1518 def test_proxy(self):
Florent Xicluna419e3842010-08-08 16:16:07 +00001519 self.assertFalse(self.get.has_proxy())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001520 self.get.set_proxy("www.perl.org", "http")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001521 self.assertTrue(self.get.has_proxy())
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001522 self.assertEqual("www.python.org", self.get.origin_req_host)
1523 self.assertEqual("www.perl.org", self.get.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001524
Senthil Kumarand95cc752010-08-08 11:27:53 +00001525 def test_wrapped_url(self):
1526 req = Request("<URL:http://www.python.org>")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001527 self.assertEqual("www.python.org", req.host)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001528
Senthil Kumaran26430412011-04-13 07:01:19 +08001529 def test_url_fragment(self):
Senthil Kumarand95cc752010-08-08 11:27:53 +00001530 req = Request("http://www.python.org/?qs=query#fragment=true")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001531 self.assertEqual("/?qs=query", req.selector)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001532 req = Request("http://www.python.org/#fun=true")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001533 self.assertEqual("/", req.selector)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001534
Senthil Kumaran26430412011-04-13 07:01:19 +08001535 # Issue 11703: geturl() omits fragment in the original URL.
1536 url = 'http://docs.python.org/library/urllib2.html#OK'
1537 req = Request(url)
1538 self.assertEqual(req.get_full_url(), url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001539
1540def test_main(verbose=None):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001541 from test import test_urllib2
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001542 support.run_doctest(test_urllib2, verbose)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001543 support.run_doctest(urllib.request, verbose)
Andrew M. Kuchlingbd3200f2004-06-29 13:15:46 +00001544 tests = (TrivialTests,
1545 OpenerDirectorTests,
1546 HandlerTests,
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001547 MiscTests,
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001548 RequestTests,
1549 RequestHdrsTests)
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001550 support.run_unittest(*tests)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001551
1552if __name__ == "__main__":
1553 test_main(verbose=True)