blob: 76208768a5bf06ad38dd53b6461bff3143feed39 [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.
Senthil Kumarand8e24f12014-04-14 16:32:20 -040013from urllib.request import Request, OpenerDirector, _parse_proxy, _proxy_bypass_macosx_sysconf
Senthil Kumaran83070752013-05-24 09:14:12 -070014from urllib.parse import urlparse
guido@google.coma119df92011-03-29 11:41:02 -070015import urllib.error
Jeremy Hyltone3e61042001-05-09 15:50:25 +000016
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000017# XXX
18# Request
19# CacheFTPHandler (hard to write)
Thomas Wouters477c8d52006-05-27 19:21:47 +000020# parse_keqv_list, parse_http_list, HTTPDigestAuthHandler
Jeremy Hyltone3e61042001-05-09 15:50:25 +000021
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000022class TrivialTests(unittest.TestCase):
Senthil Kumaran6c5bd402011-11-01 23:20:31 +080023
24 def test___all__(self):
25 # Verify which names are exposed
26 for module in 'request', 'response', 'parse', 'error', 'robotparser':
27 context = {}
28 exec('from urllib.%s import *' % module, context)
29 del context['__builtins__']
Florent Xicluna3dbb1f12011-11-04 22:15:37 +010030 if module == 'request' and os.name == 'nt':
31 u, p = context.pop('url2pathname'), context.pop('pathname2url')
32 self.assertEqual(u.__module__, 'nturl2path')
33 self.assertEqual(p.__module__, 'nturl2path')
Senthil Kumaran6c5bd402011-11-01 23:20:31 +080034 for k, v in context.items():
35 self.assertEqual(v.__module__, 'urllib.%s' % module,
36 "%r is exposed in 'urllib.%s' but defined in %r" %
37 (k, module, v.__module__))
38
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000039 def test_trivial(self):
40 # A couple trivial tests
Guido van Rossume2ae77b2001-10-24 20:42:55 +000041
Jeremy Hylton1afc1692008-06-18 20:49:58 +000042 self.assertRaises(ValueError, urllib.request.urlopen, 'bogus url')
Tim Peters861adac2001-07-16 20:49:49 +000043
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000044 # XXX Name hacking to get this to work on Windows.
Jeremy Hylton1afc1692008-06-18 20:49:58 +000045 fname = os.path.abspath(urllib.request.__file__).replace('\\', '/')
Senthil Kumarand587e302010-01-10 17:45:52 +000046
Senthil Kumarand587e302010-01-10 17:45:52 +000047 if os.name == 'nt':
48 file_url = "file:///%s" % fname
49 else:
50 file_url = "file://%s" % fname
51
Jeremy Hylton1afc1692008-06-18 20:49:58 +000052 f = urllib.request.urlopen(file_url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000053
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -070054 f.read()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000055 f.close()
Tim Petersf5f32b42005-07-17 23:16:17 +000056
Georg Brandle1b13d22005-08-24 22:20:32 +000057 def test_parse_http_list(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +000058 tests = [
59 ('a,b,c', ['a', 'b', 'c']),
60 ('path"o,l"og"i"cal, example', ['path"o,l"og"i"cal', 'example']),
61 ('a, b, "c", "d", "e,f", g, h',
62 ['a', 'b', '"c"', '"d"', '"e,f"', 'g', 'h']),
63 ('a="b\\"c", d="e\\,f", g="h\\\\i"',
64 ['a="b"c"', 'd="e,f"', 'g="h\\i"'])]
Georg Brandle1b13d22005-08-24 22:20:32 +000065 for string, list in tests:
Florent Xicluna419e3842010-08-08 16:16:07 +000066 self.assertEqual(urllib.request.parse_http_list(string), list)
Georg Brandle1b13d22005-08-24 22:20:32 +000067
Senthil Kumaran843fae92013-03-19 13:43:42 -070068 def test_URLError_reasonstr(self):
69 err = urllib.error.URLError('reason')
70 self.assertIn(err.reason, str(err))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000071
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -070072class RequestHdrsTests(unittest.TestCase):
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000073
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -070074 def test_request_headers_dict(self):
75 """
76 The Request.headers dictionary is not a documented interface. It
77 should stay that way, because the complete set of headers are only
78 accessible through the .get_header(), .has_header(), .header_items()
79 interface. However, .headers pre-dates those methods, and so real code
80 will be using the dictionary.
81
82 The introduction in 2.4 of those methods was a mistake for the same
83 reason: code that previously saw all (urllib2 user)-provided headers in
84 .headers now sees only a subset.
85
86 """
87 url = "http://example.com"
88 self.assertEqual(Request(url,
89 headers={"Spam-eggs": "blah"}
90 ).headers["Spam-eggs"], "blah")
91 self.assertEqual(Request(url,
92 headers={"spam-EggS": "blah"}
93 ).headers["Spam-eggs"], "blah")
94
95 def test_request_headers_methods(self):
96 """
97 Note the case normalization of header names here, to
98 .capitalize()-case. This should be preserved for
99 backwards-compatibility. (In the HTTP case, normalization to
100 .title()-case is done by urllib2 before sending headers to
101 http.client).
102
103 Note that e.g. r.has_header("spam-EggS") is currently False, and
104 r.get_header("spam-EggS") returns None, but that could be changed in
105 future.
106
107 Method r.remove_header should remove items both from r.headers and
108 r.unredirected_hdrs dictionaries
109 """
110 url = "http://example.com"
111 req = Request(url, headers={"Spam-eggs": "blah"})
112 self.assertTrue(req.has_header("Spam-eggs"))
113 self.assertEqual(req.header_items(), [('Spam-eggs', 'blah')])
114
115 req.add_header("Foo-Bar", "baz")
116 self.assertEqual(sorted(req.header_items()),
117 [('Foo-bar', 'baz'), ('Spam-eggs', 'blah')])
118 self.assertFalse(req.has_header("Not-there"))
119 self.assertIsNone(req.get_header("Not-there"))
120 self.assertEqual(req.get_header("Not-there", "default"), "default")
121
122 req.remove_header("Spam-eggs")
123 self.assertFalse(req.has_header("Spam-eggs"))
124
125 req.add_unredirected_header("Unredirected-spam", "Eggs")
126 self.assertTrue(req.has_header("Unredirected-spam"))
127
128 req.remove_header("Unredirected-spam")
129 self.assertFalse(req.has_header("Unredirected-spam"))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000130
131
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700132 def test_password_manager(self):
133 mgr = urllib.request.HTTPPasswordMgr()
134 add = mgr.add_password
135 find_user_pass = mgr.find_user_password
136 add("Some Realm", "http://example.com/", "joe", "password")
137 add("Some Realm", "http://example.com/ni", "ni", "ni")
138 add("c", "http://example.com/foo", "foo", "ni")
139 add("c", "http://example.com/bar", "bar", "nini")
140 add("b", "http://example.com/", "first", "blah")
141 add("b", "http://example.com/", "second", "spam")
142 add("a", "http://example.com", "1", "a")
143 add("Some Realm", "http://c.example.com:3128", "3", "c")
144 add("Some Realm", "d.example.com", "4", "d")
145 add("Some Realm", "e.example.com:3128", "5", "e")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000146
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700147 self.assertEqual(find_user_pass("Some Realm", "example.com"),
148 ('joe', 'password'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000149
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700150 #self.assertEqual(find_user_pass("Some Realm", "http://example.com/ni"),
151 # ('ni', 'ni'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000152
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700153 self.assertEqual(find_user_pass("Some Realm", "http://example.com"),
154 ('joe', 'password'))
155 self.assertEqual(find_user_pass("Some Realm", "http://example.com/"),
156 ('joe', 'password'))
157 self.assertEqual(
158 find_user_pass("Some Realm", "http://example.com/spam"),
159 ('joe', 'password'))
160 self.assertEqual(
161 find_user_pass("Some Realm", "http://example.com/spam/spam"),
162 ('joe', 'password'))
163 self.assertEqual(find_user_pass("c", "http://example.com/foo"),
164 ('foo', 'ni'))
165 self.assertEqual(find_user_pass("c", "http://example.com/bar"),
166 ('bar', 'nini'))
167 self.assertEqual(find_user_pass("b", "http://example.com/"),
168 ('second', 'spam'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000169
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700170 # No special relationship between a.example.com and example.com:
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000171
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700172 self.assertEqual(find_user_pass("a", "http://example.com/"),
173 ('1', 'a'))
174 self.assertEqual(find_user_pass("a", "http://a.example.com/"),
175 (None, None))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000176
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700177 # Ports:
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000178
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700179 self.assertEqual(find_user_pass("Some Realm", "c.example.com"),
180 (None, None))
181 self.assertEqual(find_user_pass("Some Realm", "c.example.com:3128"),
182 ('3', 'c'))
183 self.assertEqual(
184 find_user_pass("Some Realm", "http://c.example.com:3128"),
185 ('3', 'c'))
186 self.assertEqual(find_user_pass("Some Realm", "d.example.com"),
187 ('4', 'd'))
188 self.assertEqual(find_user_pass("Some Realm", "e.example.com:3128"),
189 ('5', 'e'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000190
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700191 def test_password_manager_default_port(self):
192 """
193 The point to note here is that we can't guess the default port if
194 there's no scheme. This applies to both add_password and
195 find_user_password.
196 """
197 mgr = urllib.request.HTTPPasswordMgr()
198 add = mgr.add_password
199 find_user_pass = mgr.find_user_password
200 add("f", "http://g.example.com:80", "10", "j")
201 add("g", "http://h.example.com", "11", "k")
202 add("h", "i.example.com:80", "12", "l")
203 add("i", "j.example.com", "13", "m")
204 self.assertEqual(find_user_pass("f", "g.example.com:100"),
205 (None, None))
206 self.assertEqual(find_user_pass("f", "g.example.com:80"),
207 ('10', 'j'))
208 self.assertEqual(find_user_pass("f", "g.example.com"),
209 (None, None))
210 self.assertEqual(find_user_pass("f", "http://g.example.com:100"),
211 (None, None))
212 self.assertEqual(find_user_pass("f", "http://g.example.com:80"),
213 ('10', 'j'))
214 self.assertEqual(find_user_pass("f", "http://g.example.com"),
215 ('10', 'j'))
216 self.assertEqual(find_user_pass("g", "h.example.com"), ('11', 'k'))
217 self.assertEqual(find_user_pass("g", "h.example.com:80"), ('11', 'k'))
218 self.assertEqual(find_user_pass("g", "http://h.example.com:80"),
219 ('11', 'k'))
220 self.assertEqual(find_user_pass("h", "i.example.com"), (None, None))
221 self.assertEqual(find_user_pass("h", "i.example.com:80"), ('12', 'l'))
222 self.assertEqual(find_user_pass("h", "http://i.example.com:80"),
223 ('12', 'l'))
224 self.assertEqual(find_user_pass("i", "j.example.com"), ('13', 'm'))
225 self.assertEqual(find_user_pass("i", "j.example.com:80"),
226 (None, None))
227 self.assertEqual(find_user_pass("i", "http://j.example.com"),
228 ('13', 'm'))
229 self.assertEqual(find_user_pass("i", "http://j.example.com:80"),
230 (None, None))
Andrew Svetlovbff98fe2012-11-27 23:06:19 +0200231
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000232
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000233class MockOpener:
234 addheaders = []
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000235 def open(self, req, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
236 self.req, self.data, self.timeout = req, data, timeout
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000237 def error(self, proto, *args):
238 self.proto, self.args = proto, args
239
240class MockFile:
241 def read(self, count=None): pass
242 def readline(self, count=None): pass
243 def close(self): pass
244
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000245class MockHeaders(dict):
246 def getheaders(self, name):
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000247 return list(self.values())
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000248
Guido van Rossum34d19282007-08-09 01:03:29 +0000249class MockResponse(io.StringIO):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000250 def __init__(self, code, msg, headers, data, url=None):
Guido van Rossum34d19282007-08-09 01:03:29 +0000251 io.StringIO.__init__(self, data)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000252 self.code, self.msg, self.headers, self.url = code, msg, headers, url
253 def info(self):
254 return self.headers
255 def geturl(self):
256 return self.url
257
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000258class MockCookieJar:
259 def add_cookie_header(self, request):
260 self.ach_req = request
261 def extract_cookies(self, response, request):
262 self.ec_req, self.ec_r = request, response
263
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000264class FakeMethod:
265 def __init__(self, meth_name, action, handle):
266 self.meth_name = meth_name
267 self.handle = handle
268 self.action = action
269 def __call__(self, *args):
270 return self.handle(self.meth_name, self.action, *args)
271
Senthil Kumaran47fff872009-12-20 07:10:31 +0000272class MockHTTPResponse(io.IOBase):
273 def __init__(self, fp, msg, status, reason):
274 self.fp = fp
275 self.msg = msg
276 self.status = status
277 self.reason = reason
278 self.code = 200
279
280 def read(self):
281 return ''
282
283 def info(self):
284 return {}
285
286 def geturl(self):
287 return self.url
288
289
290class MockHTTPClass:
291 def __init__(self):
292 self.level = 0
293 self.req_headers = []
294 self.data = None
295 self.raise_on_endheaders = False
Nadeem Vawdabd26b542012-10-21 17:37:43 +0200296 self.sock = None
Senthil Kumaran47fff872009-12-20 07:10:31 +0000297 self._tunnel_headers = {}
298
299 def __call__(self, host, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
300 self.host = host
301 self.timeout = timeout
302 return self
303
304 def set_debuglevel(self, level):
305 self.level = level
306
307 def set_tunnel(self, host, port=None, headers=None):
308 self._tunnel_host = host
309 self._tunnel_port = port
310 if headers:
311 self._tunnel_headers = headers
312 else:
313 self._tunnel_headers.clear()
314
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000315 def request(self, method, url, body=None, headers=None):
Senthil Kumaran47fff872009-12-20 07:10:31 +0000316 self.method = method
317 self.selector = url
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000318 if headers is not None:
319 self.req_headers += headers.items()
Senthil Kumaran47fff872009-12-20 07:10:31 +0000320 self.req_headers.sort()
321 if body:
322 self.data = body
323 if self.raise_on_endheaders:
Andrew Svetlov0832af62012-12-18 23:10:48 +0200324 raise OSError()
Senthil Kumaran47fff872009-12-20 07:10:31 +0000325 def getresponse(self):
326 return MockHTTPResponse(MockFile(), {}, 200, "OK")
327
Victor Stinnera4c45d72011-06-17 14:01:18 +0200328 def close(self):
329 pass
330
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000331class MockHandler:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000332 # useful for testing handler machinery
333 # see add_ordered_mock_handlers() docstring
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000334 handler_order = 500
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000335 def __init__(self, methods):
336 self._define_methods(methods)
337 def _define_methods(self, methods):
338 for spec in methods:
339 if len(spec) == 2: name, action = spec
340 else: name, action = spec, None
341 meth = FakeMethod(name, action, self.handle)
342 setattr(self.__class__, name, meth)
343 def handle(self, fn_name, action, *args, **kwds):
344 self.parent.calls.append((self, fn_name, args, kwds))
345 if action is None:
346 return None
347 elif action == "return self":
348 return self
349 elif action == "return response":
350 res = MockResponse(200, "OK", {}, "")
351 return res
352 elif action == "return request":
353 return Request("http://blah/")
354 elif action.startswith("error"):
355 code = action[action.rfind(" ")+1:]
356 try:
357 code = int(code)
358 except ValueError:
359 pass
360 res = MockResponse(200, "OK", {}, "")
361 return self.parent.error("http", args[0], res, code, "", {})
362 elif action == "raise":
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000363 raise urllib.error.URLError("blah")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000364 assert False
365 def close(self): pass
366 def add_parent(self, parent):
367 self.parent = parent
368 self.parent.calls = []
369 def __lt__(self, other):
370 if not hasattr(other, "handler_order"):
371 # No handler_order, leave in original order. Yuck.
372 return True
373 return self.handler_order < other.handler_order
374
375def add_ordered_mock_handlers(opener, meth_spec):
376 """Create MockHandlers and add them to an OpenerDirector.
377
378 meth_spec: list of lists of tuples and strings defining methods to define
379 on handlers. eg:
380
381 [["http_error", "ftp_open"], ["http_open"]]
382
383 defines methods .http_error() and .ftp_open() on one handler, and
384 .http_open() on another. These methods just record their arguments and
385 return None. Using a tuple instead of a string causes the method to
386 perform some action (see MockHandler.handle()), eg:
387
388 [["http_error"], [("http_open", "return request")]]
389
390 defines .http_error() on one handler (which simply returns None), and
391 .http_open() on another handler, which returns a Request object.
392
393 """
394 handlers = []
395 count = 0
396 for meths in meth_spec:
397 class MockHandlerSubclass(MockHandler): pass
398 h = MockHandlerSubclass(meths)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000399 h.handler_order += count
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000400 h.add_parent(opener)
401 count = count + 1
402 handlers.append(h)
403 opener.add_handler(h)
404 return handlers
405
Thomas Wouters477c8d52006-05-27 19:21:47 +0000406def build_test_opener(*handler_instances):
407 opener = OpenerDirector()
408 for h in handler_instances:
409 opener.add_handler(h)
410 return opener
411
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000412class MockHTTPHandler(urllib.request.BaseHandler):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000413 # useful for testing redirections and auth
414 # sends supplied headers and code as first response
415 # sends 200 OK as second response
416 def __init__(self, code, headers):
417 self.code = code
418 self.headers = headers
419 self.reset()
420 def reset(self):
421 self._count = 0
422 self.requests = []
423 def http_open(self, req):
Barry Warsaw820c1202008-06-12 04:06:45 +0000424 import email, http.client, copy
Thomas Wouters477c8d52006-05-27 19:21:47 +0000425 self.requests.append(copy.deepcopy(req))
426 if self._count == 0:
427 self._count = self._count + 1
Georg Brandl24420152008-05-26 16:32:26 +0000428 name = http.client.responses[self.code]
Barry Warsaw820c1202008-06-12 04:06:45 +0000429 msg = email.message_from_string(self.headers)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000430 return self.parent.error(
431 "http", req, MockFile(), self.code, name, msg)
432 else:
433 self.req = req
Barry Warsaw820c1202008-06-12 04:06:45 +0000434 msg = email.message_from_string("\r\n\r\n")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000435 return MockResponse(200, "OK", msg, "", req.get_full_url())
436
Senthil Kumaran47fff872009-12-20 07:10:31 +0000437class MockHTTPSHandler(urllib.request.AbstractHTTPHandler):
438 # Useful for testing the Proxy-Authorization request by verifying the
439 # properties of httpcon
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000440
441 def __init__(self):
442 urllib.request.AbstractHTTPHandler.__init__(self)
443 self.httpconn = MockHTTPClass()
444
Senthil Kumaran47fff872009-12-20 07:10:31 +0000445 def https_open(self, req):
446 return self.do_open(self.httpconn, req)
447
Thomas Wouters477c8d52006-05-27 19:21:47 +0000448class MockPasswordManager:
449 def add_password(self, realm, uri, user, password):
450 self.realm = realm
451 self.url = uri
452 self.user = user
453 self.password = password
454 def find_user_password(self, realm, authuri):
455 self.target_realm = realm
456 self.target_url = authuri
457 return self.user, self.password
458
459
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000460class OpenerDirectorTests(unittest.TestCase):
461
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000462 def test_add_non_handler(self):
463 class NonHandler(object):
464 pass
465 self.assertRaises(TypeError,
466 OpenerDirector().add_handler, NonHandler())
467
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000468 def test_badly_named_methods(self):
469 # test work-around for three methods that accidentally follow the
470 # naming conventions for handler methods
471 # (*_open() / *_request() / *_response())
472
473 # These used to call the accidentally-named methods, causing a
474 # TypeError in real code; here, returning self from these mock
475 # methods would either cause no exception, or AttributeError.
476
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000477 from urllib.error import URLError
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000478
479 o = OpenerDirector()
480 meth_spec = [
481 [("do_open", "return self"), ("proxy_open", "return self")],
482 [("redirect_request", "return self")],
483 ]
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700484 add_ordered_mock_handlers(o, meth_spec)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000485 o.add_handler(urllib.request.UnknownHandler())
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000486 for scheme in "do", "proxy", "redirect":
487 self.assertRaises(URLError, o.open, scheme+"://example.com/")
488
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000489 def test_handled(self):
490 # handler returning non-None means no more handlers will be called
491 o = OpenerDirector()
492 meth_spec = [
493 ["http_open", "ftp_open", "http_error_302"],
494 ["ftp_open"],
495 [("http_open", "return self")],
496 [("http_open", "return self")],
497 ]
498 handlers = add_ordered_mock_handlers(o, meth_spec)
499
500 req = Request("http://example.com/")
501 r = o.open(req)
502 # Second .http_open() gets called, third doesn't, since second returned
503 # non-None. Handlers without .http_open() never get any methods called
504 # on them.
505 # In fact, second mock handler defining .http_open() returns self
506 # (instead of response), which becomes the OpenerDirector's return
507 # value.
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000508 self.assertEqual(r, handlers[2])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000509 calls = [(handlers[0], "http_open"), (handlers[2], "http_open")]
510 for expected, got in zip(calls, o.calls):
511 handler, name, args, kwds = got
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000512 self.assertEqual((handler, name), expected)
513 self.assertEqual(args, (req,))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000514
515 def test_handler_order(self):
516 o = OpenerDirector()
517 handlers = []
518 for meths, handler_order in [
519 ([("http_open", "return self")], 500),
520 (["http_open"], 0),
521 ]:
522 class MockHandlerSubclass(MockHandler): pass
523 h = MockHandlerSubclass(meths)
524 h.handler_order = handler_order
525 handlers.append(h)
526 o.add_handler(h)
527
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700528 o.open("http://example.com/")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000529 # handlers called in reverse order, thanks to their sort order
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000530 self.assertEqual(o.calls[0][0], handlers[1])
531 self.assertEqual(o.calls[1][0], handlers[0])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000532
533 def test_raise(self):
534 # raising URLError stops processing of request
535 o = OpenerDirector()
536 meth_spec = [
537 [("http_open", "raise")],
538 [("http_open", "return self")],
539 ]
540 handlers = add_ordered_mock_handlers(o, meth_spec)
541
542 req = Request("http://example.com/")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000543 self.assertRaises(urllib.error.URLError, o.open, req)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000544 self.assertEqual(o.calls, [(handlers[0], "http_open", (req,), {})])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000545
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000546 def test_http_error(self):
547 # XXX http_error_default
548 # http errors are a special case
549 o = OpenerDirector()
550 meth_spec = [
551 [("http_open", "error 302")],
552 [("http_error_400", "raise"), "http_open"],
553 [("http_error_302", "return response"), "http_error_303",
554 "http_error"],
555 [("http_error_302")],
556 ]
557 handlers = add_ordered_mock_handlers(o, meth_spec)
558
559 class Unknown:
560 def __eq__(self, other): return True
561
562 req = Request("http://example.com/")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700563 o.open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000564 assert len(o.calls) == 2
565 calls = [(handlers[0], "http_open", (req,)),
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000566 (handlers[2], "http_error_302",
567 (req, Unknown(), 302, "", {}))]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000568 for expected, got in zip(calls, o.calls):
569 handler, method_name, args = expected
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000570 self.assertEqual((handler, method_name), got[:2])
571 self.assertEqual(args, got[2])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000572
Senthil Kumaran38b968b92012-03-14 13:43:53 -0700573
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000574 def test_processors(self):
575 # *_request / *_response methods get called appropriately
576 o = OpenerDirector()
577 meth_spec = [
578 [("http_request", "return request"),
579 ("http_response", "return response")],
580 [("http_request", "return request"),
581 ("http_response", "return response")],
582 ]
583 handlers = add_ordered_mock_handlers(o, meth_spec)
584
585 req = Request("http://example.com/")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700586 o.open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000587 # processor methods are called on *all* handlers that define them,
588 # not just the first handler that handles the request
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000589 calls = [
590 (handlers[0], "http_request"), (handlers[1], "http_request"),
591 (handlers[0], "http_response"), (handlers[1], "http_response")]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000592
593 for i, (handler, name, args, kwds) in enumerate(o.calls):
594 if i < 2:
595 # *_request
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000596 self.assertEqual((handler, name), calls[i])
597 self.assertEqual(len(args), 1)
Ezio Melottie9615932010-01-24 19:26:24 +0000598 self.assertIsInstance(args[0], Request)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000599 else:
600 # *_response
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000601 self.assertEqual((handler, name), calls[i])
602 self.assertEqual(len(args), 2)
Ezio Melottie9615932010-01-24 19:26:24 +0000603 self.assertIsInstance(args[0], Request)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000604 # response from opener.open is None, because there's no
605 # handler that defines http_open to handle it
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200606 if args[1] is not None:
607 self.assertIsInstance(args[1], MockResponse)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000608
Tim Peters58eb11c2004-01-18 20:29:55 +0000609def sanepathname2url(path):
Victor Stinner6c6f8512010-08-07 10:09:35 +0000610 try:
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000611 path.encode("utf-8")
Victor Stinner6c6f8512010-08-07 10:09:35 +0000612 except UnicodeEncodeError:
613 raise unittest.SkipTest("path is not encodable to utf8")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000614 urlpath = urllib.request.pathname2url(path)
Tim Peters58eb11c2004-01-18 20:29:55 +0000615 if os.name == "nt" and urlpath.startswith("///"):
616 urlpath = urlpath[2:]
617 # XXX don't ask me about the mac...
618 return urlpath
619
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000620class HandlerTests(unittest.TestCase):
621
622 def test_ftp(self):
623 class MockFTPWrapper:
624 def __init__(self, data): self.data = data
625 def retrfile(self, filename, filetype):
626 self.filename, self.filetype = filename, filetype
Guido van Rossum34d19282007-08-09 01:03:29 +0000627 return io.StringIO(self.data), len(self.data)
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +0200628 def close(self): pass
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000629
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000630 class NullFTPHandler(urllib.request.FTPHandler):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000631 def __init__(self, data): self.data = data
Georg Brandlf78e02b2008-06-10 17:40:04 +0000632 def connect_ftp(self, user, passwd, host, port, dirs,
633 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000634 self.user, self.passwd = user, passwd
635 self.host, self.port = host, port
636 self.dirs = dirs
637 self.ftpwrapper = MockFTPWrapper(self.data)
638 return self.ftpwrapper
639
Georg Brandlf78e02b2008-06-10 17:40:04 +0000640 import ftplib
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000641 data = "rheum rhaponicum"
642 h = NullFTPHandler(data)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700643 h.parent = MockOpener()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000644
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000645 for url, host, port, user, passwd, type_, dirs, filename, mimetype in [
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000646 ("ftp://localhost/foo/bar/baz.html",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000647 "localhost", ftplib.FTP_PORT, "", "", "I",
648 ["foo", "bar"], "baz.html", "text/html"),
649 ("ftp://parrot@localhost/foo/bar/baz.html",
650 "localhost", ftplib.FTP_PORT, "parrot", "", "I",
651 ["foo", "bar"], "baz.html", "text/html"),
652 ("ftp://%25parrot@localhost/foo/bar/baz.html",
653 "localhost", ftplib.FTP_PORT, "%parrot", "", "I",
654 ["foo", "bar"], "baz.html", "text/html"),
655 ("ftp://%2542parrot@localhost/foo/bar/baz.html",
656 "localhost", ftplib.FTP_PORT, "%42parrot", "", "I",
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000657 ["foo", "bar"], "baz.html", "text/html"),
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000658 ("ftp://localhost:80/foo/bar/",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000659 "localhost", 80, "", "", "D",
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000660 ["foo", "bar"], "", None),
661 ("ftp://localhost/baz.gif;type=a",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000662 "localhost", ftplib.FTP_PORT, "", "", "A",
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000663 [], "baz.gif", None), # XXX really this should guess image/gif
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000664 ]:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000665 req = Request(url)
666 req.timeout = None
667 r = h.ftp_open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000668 # ftp authentication not yet implemented by FTPHandler
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000669 self.assertEqual(h.user, user)
670 self.assertEqual(h.passwd, passwd)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000671 self.assertEqual(h.host, socket.gethostbyname(host))
672 self.assertEqual(h.port, port)
673 self.assertEqual(h.dirs, dirs)
674 self.assertEqual(h.ftpwrapper.filename, filename)
675 self.assertEqual(h.ftpwrapper.filetype, type_)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000676 headers = r.info()
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000677 self.assertEqual(headers.get("Content-type"), mimetype)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000678 self.assertEqual(int(headers["Content-length"]), len(data))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000679
680 def test_file(self):
Senthil Kumaranbc07ac52014-07-22 00:15:20 -0700681 import email.utils
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000682 h = urllib.request.FileHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000683 o = h.parent = MockOpener()
684
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000685 TESTFN = support.TESTFN
Tim Peters58eb11c2004-01-18 20:29:55 +0000686 urlpath = sanepathname2url(os.path.abspath(TESTFN))
Guido van Rossum6a2ccd02007-07-16 20:51:57 +0000687 towrite = b"hello, world\n"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000688 urls = [
Tim Peters58eb11c2004-01-18 20:29:55 +0000689 "file://localhost%s" % urlpath,
690 "file://%s" % urlpath,
691 "file://%s%s" % (socket.gethostbyname('localhost'), urlpath),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000692 ]
693 try:
694 localaddr = socket.gethostbyname(socket.gethostname())
695 except socket.gaierror:
696 localaddr = ''
697 if localaddr:
698 urls.append("file://%s%s" % (localaddr, urlpath))
699
700 for url in urls:
Tim Peters58eb11c2004-01-18 20:29:55 +0000701 f = open(TESTFN, "wb")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000702 try:
703 try:
704 f.write(towrite)
705 finally:
706 f.close()
707
708 r = h.file_open(Request(url))
709 try:
710 data = r.read()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000711 headers = r.info()
Senthil Kumaran4fbed102010-05-08 03:29:09 +0000712 respurl = r.geturl()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000713 finally:
714 r.close()
Tim Peters58eb11c2004-01-18 20:29:55 +0000715 stats = os.stat(TESTFN)
Benjamin Petersona0c0a4a2008-06-12 22:15:50 +0000716 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000717 finally:
718 os.remove(TESTFN)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000719 self.assertEqual(data, towrite)
720 self.assertEqual(headers["Content-type"], "text/plain")
721 self.assertEqual(headers["Content-length"], "13")
Tim Peters58eb11c2004-01-18 20:29:55 +0000722 self.assertEqual(headers["Last-modified"], modified)
Senthil Kumaran4fbed102010-05-08 03:29:09 +0000723 self.assertEqual(respurl, url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000724
725 for url in [
Tim Peters58eb11c2004-01-18 20:29:55 +0000726 "file://localhost:80%s" % urlpath,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000727 "file:///file_does_not_exist.txt",
Senthil Kumaranbc07ac52014-07-22 00:15:20 -0700728 "file://not-a-local-host.com//dir/file.txt",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000729 "file://%s:80%s/%s" % (socket.gethostbyname('localhost'),
730 os.getcwd(), TESTFN),
731 "file://somerandomhost.ontheinternet.com%s/%s" %
732 (os.getcwd(), TESTFN),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000733 ]:
734 try:
Tim Peters58eb11c2004-01-18 20:29:55 +0000735 f = open(TESTFN, "wb")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000736 try:
737 f.write(towrite)
738 finally:
739 f.close()
740
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000741 self.assertRaises(urllib.error.URLError,
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000742 h.file_open, Request(url))
743 finally:
744 os.remove(TESTFN)
745
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000746 h = urllib.request.FileHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000747 o = h.parent = MockOpener()
748 # XXXX why does // mean ftp (and /// mean not ftp!), and where
749 # is file: scheme specified? I think this is really a bug, and
750 # what was intended was to distinguish between URLs like:
751 # file:/blah.txt (a file)
752 # file://localhost/blah.txt (a file)
753 # file:///blah.txt (a file)
754 # file://ftp.example.com/blah.txt (an ftp URL)
755 for url, ftp in [
Senthil Kumaran383c32d2010-10-14 11:57:35 +0000756 ("file://ftp.example.com//foo.txt", False),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000757 ("file://ftp.example.com///foo.txt", False),
758# XXXX bug: fails with OSError, should be URLError
759 ("file://ftp.example.com/foo.txt", False),
Senthil Kumaran383c32d2010-10-14 11:57:35 +0000760 ("file://somehost//foo/something.txt", False),
Senthil Kumaran2ef16322010-07-11 03:12:43 +0000761 ("file://localhost//foo/something.txt", False),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000762 ]:
763 req = Request(url)
764 try:
765 h.file_open(req)
766 # XXXX remove OSError when bug fixed
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000767 except (urllib.error.URLError, OSError):
Florent Xicluna419e3842010-08-08 16:16:07 +0000768 self.assertFalse(ftp)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000769 else:
Florent Xicluna419e3842010-08-08 16:16:07 +0000770 self.assertIs(o.req, req)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000771 self.assertEqual(req.type, "ftp")
Łukasz Langad7e81cc2011-01-09 18:18:53 +0000772 self.assertEqual(req.type == "ftp", ftp)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000773
774 def test_http(self):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000775
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000776 h = urllib.request.AbstractHTTPHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000777 o = h.parent = MockOpener()
778
779 url = "http://example.com/"
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000780 for method, data in [("GET", None), ("POST", b"blah")]:
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000781 req = Request(url, data, {"Foo": "bar"})
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000782 req.timeout = None
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000783 req.add_unredirected_header("Spam", "eggs")
784 http = MockHTTPClass()
785 r = h.do_open(http, req)
786
787 # result attributes
788 r.read; r.readline # wrapped MockFile methods
789 r.info; r.geturl # addinfourl methods
790 r.code, r.msg == 200, "OK" # added from MockHTTPClass.getreply()
791 hdrs = r.info()
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000792 hdrs.get; hdrs.__contains__ # r.info() gives dict from .getreply()
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000793 self.assertEqual(r.geturl(), url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000794
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000795 self.assertEqual(http.host, "example.com")
796 self.assertEqual(http.level, 0)
797 self.assertEqual(http.method, method)
798 self.assertEqual(http.selector, "/")
799 self.assertEqual(http.req_headers,
Jeremy Hyltonb3ee6f92004-02-24 19:40:35 +0000800 [("Connection", "close"),
801 ("Foo", "bar"), ("Spam", "eggs")])
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000802 self.assertEqual(http.data, data)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000803
Andrew Svetlov0832af62012-12-18 23:10:48 +0200804 # check OSError converted to URLError
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000805 http.raise_on_endheaders = True
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000806 self.assertRaises(urllib.error.URLError, h.do_open, http, req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000807
Senthil Kumaran29333122011-02-11 11:25:47 +0000808 # Check for TypeError on POST data which is str.
809 req = Request("http://example.com/","badpost")
810 self.assertRaises(TypeError, h.do_request_, req)
811
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000812 # check adding of standard headers
813 o.addheaders = [("Spam", "eggs")]
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000814 for data in b"", None: # POST, GET
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000815 req = Request("http://example.com/", data)
816 r = MockResponse(200, "OK", {}, "")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000817 newreq = h.do_request_(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000818 if data is None: # GET
Benjamin Peterson577473f2010-01-19 00:09:57 +0000819 self.assertNotIn("Content-length", req.unredirected_hdrs)
820 self.assertNotIn("Content-type", req.unredirected_hdrs)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000821 else: # POST
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000822 self.assertEqual(req.unredirected_hdrs["Content-length"], "0")
823 self.assertEqual(req.unredirected_hdrs["Content-type"],
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000824 "application/x-www-form-urlencoded")
825 # XXX the details of Host could be better tested
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000826 self.assertEqual(req.unredirected_hdrs["Host"], "example.com")
827 self.assertEqual(req.unredirected_hdrs["Spam"], "eggs")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000828
829 # don't clobber existing headers
830 req.add_unredirected_header("Content-length", "foo")
831 req.add_unredirected_header("Content-type", "bar")
832 req.add_unredirected_header("Host", "baz")
833 req.add_unredirected_header("Spam", "foo")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000834 newreq = h.do_request_(req)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000835 self.assertEqual(req.unredirected_hdrs["Content-length"], "foo")
836 self.assertEqual(req.unredirected_hdrs["Content-type"], "bar")
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000837 self.assertEqual(req.unredirected_hdrs["Host"], "baz")
838 self.assertEqual(req.unredirected_hdrs["Spam"], "foo")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000839
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000840 # Check iterable body support
841 def iterable_body():
842 yield b"one"
843 yield b"two"
844 yield b"three"
845
846 for headers in {}, {"Content-Length": 11}:
847 req = Request("http://example.com/", iterable_body(), headers)
848 if not headers:
849 # Having an iterable body without a Content-Length should
850 # raise an exception
851 self.assertRaises(ValueError, h.do_request_, req)
852 else:
853 newreq = h.do_request_(req)
854
Senthil Kumaran29333122011-02-11 11:25:47 +0000855 # A file object.
856 # Test only Content-Length attribute of request.
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000857
Senthil Kumaran29333122011-02-11 11:25:47 +0000858 file_obj = io.BytesIO()
859 file_obj.write(b"Something\nSomething\nSomething\n")
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000860
861 for headers in {}, {"Content-Length": 30}:
862 req = Request("http://example.com/", file_obj, headers)
863 if not headers:
864 # Having an iterable body without a Content-Length should
865 # raise an exception
866 self.assertRaises(ValueError, h.do_request_, req)
867 else:
868 newreq = h.do_request_(req)
869 self.assertEqual(int(newreq.get_header('Content-length')),30)
870
871 file_obj.close()
872
873 # array.array Iterable - Content Length is calculated
874
875 iterable_array = array.array("I",[1,2,3,4])
876
877 for headers in {}, {"Content-Length": 16}:
878 req = Request("http://example.com/", iterable_array, headers)
879 newreq = h.do_request_(req)
880 self.assertEqual(int(newreq.get_header('Content-length')),16)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000881
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000882 def test_http_doubleslash(self):
883 # Checks the presence of any unnecessary double slash in url does not
884 # break anything. Previously, a double slash directly after the host
Ezio Melottie130a522011-10-19 10:58:56 +0300885 # could cause incorrect parsing.
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000886 h = urllib.request.AbstractHTTPHandler()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700887 h.parent = MockOpener()
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000888
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000889 data = b""
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000890 ds_urls = [
891 "http://example.com/foo/bar/baz.html",
892 "http://example.com//foo/bar/baz.html",
893 "http://example.com/foo//bar/baz.html",
894 "http://example.com/foo/bar//baz.html"
895 ]
896
897 for ds_url in ds_urls:
898 ds_req = Request(ds_url, data)
899
900 # Check whether host is determined correctly if there is no proxy
901 np_ds_req = h.do_request_(ds_req)
902 self.assertEqual(np_ds_req.unredirected_hdrs["Host"],"example.com")
903
904 # Check whether host is determined correctly if there is a proxy
905 ds_req.set_proxy("someproxy:3128",None)
906 p_ds_req = h.do_request_(ds_req)
907 self.assertEqual(p_ds_req.unredirected_hdrs["Host"],"example.com")
908
Senthil Kumaran52380922013-04-25 05:45:48 -0700909 def test_full_url_setter(self):
910 # Checks to ensure that components are set correctly after setting the
911 # full_url of a Request object
912
913 urls = [
914 'http://example.com?foo=bar#baz',
915 'http://example.com?foo=bar&spam=eggs#bash',
916 'http://example.com',
917 ]
918
919 # testing a reusable request instance, but the url parameter is
920 # required, so just use a dummy one to instantiate
921 r = Request('http://example.com')
922 for url in urls:
923 r.full_url = url
Senthil Kumaran83070752013-05-24 09:14:12 -0700924 parsed = urlparse(url)
925
Senthil Kumaran52380922013-04-25 05:45:48 -0700926 self.assertEqual(r.get_full_url(), url)
Senthil Kumaran83070752013-05-24 09:14:12 -0700927 # full_url setter uses splittag to split into components.
928 # splittag sets the fragment as None while urlparse sets it to ''
929 self.assertEqual(r.fragment or '', parsed.fragment)
930 self.assertEqual(urlparse(r.get_full_url()).query, parsed.query)
Senthil Kumaran52380922013-04-25 05:45:48 -0700931
932 def test_full_url_deleter(self):
933 r = Request('http://www.example.com')
934 del r.full_url
935 self.assertIsNone(r.full_url)
936 self.assertIsNone(r.fragment)
937 self.assertEqual(r.selector, '')
938
Senthil Kumaranc2958622010-11-22 04:48:26 +0000939 def test_fixpath_in_weirdurls(self):
940 # Issue4493: urllib2 to supply '/' when to urls where path does not
941 # start with'/'
942
943 h = urllib.request.AbstractHTTPHandler()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700944 h.parent = MockOpener()
Senthil Kumaranc2958622010-11-22 04:48:26 +0000945
946 weird_url = 'http://www.python.org?getspam'
947 req = Request(weird_url)
948 newreq = h.do_request_(req)
949 self.assertEqual(newreq.host,'www.python.org')
950 self.assertEqual(newreq.selector,'/?getspam')
951
952 url_without_path = 'http://www.python.org'
953 req = Request(url_without_path)
954 newreq = h.do_request_(req)
955 self.assertEqual(newreq.host,'www.python.org')
956 self.assertEqual(newreq.selector,'')
957
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000958
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000959 def test_errors(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000960 h = urllib.request.HTTPErrorProcessor()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000961 o = h.parent = MockOpener()
962
963 url = "http://example.com/"
964 req = Request(url)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000965 # all 2xx are passed through
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000966 r = MockResponse(200, "OK", {}, "", 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
Guido van Rossumd8faa362007-04-27 19:54:29 +0000970 r = MockResponse(202, "Accepted", {}, "", url)
971 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +0000972 self.assertIs(r, newr)
973 self.assertFalse(hasattr(o, "proto")) # o.error not called
Guido van Rossumd8faa362007-04-27 19:54:29 +0000974 r = MockResponse(206, "Partial content", {}, "", url)
975 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +0000976 self.assertIs(r, newr)
977 self.assertFalse(hasattr(o, "proto")) # o.error not called
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000978 # anything else calls o.error (and MockOpener returns None, here)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000979 r = MockResponse(502, "Bad gateway", {}, "", url)
Florent Xicluna419e3842010-08-08 16:16:07 +0000980 self.assertIsNone(h.http_response(req, r))
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000981 self.assertEqual(o.proto, "http") # o.error called
Guido van Rossumd8faa362007-04-27 19:54:29 +0000982 self.assertEqual(o.args, (req, r, 502, "Bad gateway", {}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000983
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000984 def test_cookies(self):
985 cj = MockCookieJar()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000986 h = urllib.request.HTTPCookieProcessor(cj)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700987 h.parent = MockOpener()
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000988
989 req = Request("http://example.com/")
990 r = MockResponse(200, "OK", {}, "")
991 newreq = h.http_request(req)
Florent Xicluna419e3842010-08-08 16:16:07 +0000992 self.assertIs(cj.ach_req, req)
993 self.assertIs(cj.ach_req, newreq)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -0700994 self.assertEqual(req.origin_req_host, "example.com")
995 self.assertFalse(req.unverifiable)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000996 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +0000997 self.assertIs(cj.ec_req, req)
998 self.assertIs(cj.ec_r, r)
999 self.assertIs(r, newr)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001000
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001001 def test_redirect(self):
1002 from_url = "http://example.com/a.html"
1003 to_url = "http://example.com/b.html"
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001004 h = urllib.request.HTTPRedirectHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001005 o = h.parent = MockOpener()
1006
1007 # ordinary redirect behaviour
1008 for code in 301, 302, 303, 307:
1009 for data in None, "blah\nblah\n":
1010 method = getattr(h, "http_error_%s" % code)
1011 req = Request(from_url, data)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001012 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001013 req.add_header("Nonsense", "viking=withhold")
Christian Heimes77c02eb2008-02-09 02:18:51 +00001014 if data is not None:
1015 req.add_header("Content-Length", str(len(data)))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001016 req.add_unredirected_header("Spam", "spam")
1017 try:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001018 method(req, MockFile(), code, "Blah",
1019 MockHeaders({"location": to_url}))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001020 except urllib.error.HTTPError:
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001021 # 307 in response to POST requires user OK
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001022 self.assertEqual(code, 307)
1023 self.assertIsNotNone(data)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001024 self.assertEqual(o.req.get_full_url(), to_url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001025 try:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001026 self.assertEqual(o.req.get_method(), "GET")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001027 except AttributeError:
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001028 self.assertFalse(o.req.data)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001029
1030 # now it's a GET, there should not be headers regarding content
1031 # (possibly dragged from before being a POST)
1032 headers = [x.lower() for x in o.req.headers]
Benjamin Peterson577473f2010-01-19 00:09:57 +00001033 self.assertNotIn("content-length", headers)
1034 self.assertNotIn("content-type", headers)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001035
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001036 self.assertEqual(o.req.headers["Nonsense"],
1037 "viking=withhold")
Benjamin Peterson577473f2010-01-19 00:09:57 +00001038 self.assertNotIn("Spam", o.req.headers)
1039 self.assertNotIn("Spam", o.req.unredirected_hdrs)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001040
1041 # loop detection
1042 req = Request(from_url)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001043 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001044 def redirect(h, req, url=to_url):
1045 h.http_error_302(req, MockFile(), 302, "Blah",
1046 MockHeaders({"location": url}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001047 # Note that the *original* request shares the same record of
1048 # redirections with the sub-requests caused by the redirections.
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001049
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001050 # detect infinite loop redirect of a URL to itself
1051 req = Request(from_url, origin_req_host="example.com")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001052 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001053 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001054 try:
1055 while 1:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001056 redirect(h, req, "http://example.com/")
1057 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001058 except urllib.error.HTTPError:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001059 # don't stop until max_repeats, because cookies may introduce state
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001060 self.assertEqual(count, urllib.request.HTTPRedirectHandler.max_repeats)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001061
1062 # detect endless non-repeating chain of redirects
1063 req = Request(from_url, origin_req_host="example.com")
1064 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001065 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001066 try:
1067 while 1:
1068 redirect(h, req, "http://example.com/%d" % count)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001069 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001070 except urllib.error.HTTPError:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001071 self.assertEqual(count,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001072 urllib.request.HTTPRedirectHandler.max_redirections)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001073
guido@google.coma119df92011-03-29 11:41:02 -07001074
1075 def test_invalid_redirect(self):
1076 from_url = "http://example.com/a.html"
1077 valid_schemes = ['http','https','ftp']
1078 invalid_schemes = ['file','imap','ldap']
1079 schemeless_url = "example.com/b.html"
1080 h = urllib.request.HTTPRedirectHandler()
1081 o = h.parent = MockOpener()
1082 req = Request(from_url)
1083 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1084
1085 for scheme in invalid_schemes:
1086 invalid_url = scheme + '://' + schemeless_url
1087 self.assertRaises(urllib.error.HTTPError, h.http_error_302,
1088 req, MockFile(), 302, "Security Loophole",
1089 MockHeaders({"location": invalid_url}))
1090
1091 for scheme in valid_schemes:
1092 valid_url = scheme + '://' + schemeless_url
1093 h.http_error_302(req, MockFile(), 302, "That's fine",
1094 MockHeaders({"location": valid_url}))
1095 self.assertEqual(o.req.get_full_url(), valid_url)
1096
Senthil Kumaran6497aa32012-01-04 13:46:59 +08001097 def test_relative_redirect(self):
1098 from_url = "http://example.com/a.html"
1099 relative_url = "/b.html"
1100 h = urllib.request.HTTPRedirectHandler()
1101 o = h.parent = MockOpener()
1102 req = Request(from_url)
1103 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1104
1105 valid_url = urllib.parse.urljoin(from_url,relative_url)
1106 h.http_error_302(req, MockFile(), 302, "That's fine",
1107 MockHeaders({"location": valid_url}))
1108 self.assertEqual(o.req.get_full_url(), valid_url)
1109
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001110 def test_cookie_redirect(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001111 # cookies shouldn't leak into redirected requests
Georg Brandl24420152008-05-26 16:32:26 +00001112 from http.cookiejar import CookieJar
1113 from test.test_http_cookiejar import interact_netscape
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001114
1115 cj = CookieJar()
1116 interact_netscape(cj, "http://www.example.com/", "spam=eggs")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001117 hh = MockHTTPHandler(302, "Location: http://www.cracker.com/\r\n\r\n")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001118 hdeh = urllib.request.HTTPDefaultErrorHandler()
1119 hrh = urllib.request.HTTPRedirectHandler()
1120 cp = urllib.request.HTTPCookieProcessor(cj)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001121 o = build_test_opener(hh, hdeh, hrh, cp)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001122 o.open("http://www.example.com/")
Florent Xicluna419e3842010-08-08 16:16:07 +00001123 self.assertFalse(hh.req.has_header("Cookie"))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001124
Senthil Kumaran26430412011-04-13 07:01:19 +08001125 def test_redirect_fragment(self):
1126 redirected_url = 'http://www.example.com/index.html#OK\r\n\r\n'
1127 hh = MockHTTPHandler(302, 'Location: ' + redirected_url)
1128 hdeh = urllib.request.HTTPDefaultErrorHandler()
1129 hrh = urllib.request.HTTPRedirectHandler()
1130 o = build_test_opener(hh, hdeh, hrh)
1131 fp = o.open('http://www.example.com')
1132 self.assertEqual(fp.geturl(), redirected_url.strip())
1133
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001134 def test_proxy(self):
1135 o = OpenerDirector()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001136 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001137 o.add_handler(ph)
1138 meth_spec = [
1139 [("http_open", "return response")]
1140 ]
1141 handlers = add_ordered_mock_handlers(o, meth_spec)
1142
1143 req = Request("http://acme.example.com/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001144 self.assertEqual(req.host, "acme.example.com")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001145 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001146 self.assertEqual(req.host, "proxy.example.com:3128")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001147
1148 self.assertEqual([(handlers[0], "http_open")],
1149 [tup[0:2] for tup in o.calls])
1150
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001151 def test_proxy_no_proxy(self):
1152 os.environ['no_proxy'] = 'python.org'
1153 o = OpenerDirector()
1154 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1155 o.add_handler(ph)
1156 req = Request("http://www.perl.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001157 self.assertEqual(req.host, "www.perl.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001158 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001159 self.assertEqual(req.host, "proxy.example.com")
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001160 req = Request("http://www.python.org")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001161 self.assertEqual(req.host, "www.python.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001162 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001163 self.assertEqual(req.host, "www.python.org")
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001164 del os.environ['no_proxy']
1165
Ronald Oussorene72e1612011-03-14 18:15:25 -04001166 def test_proxy_no_proxy_all(self):
1167 os.environ['no_proxy'] = '*'
1168 o = OpenerDirector()
1169 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1170 o.add_handler(ph)
1171 req = Request("http://www.python.org")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001172 self.assertEqual(req.host, "www.python.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001173 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001174 self.assertEqual(req.host, "www.python.org")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001175 del os.environ['no_proxy']
1176
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001177
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001178 def test_proxy_https(self):
1179 o = OpenerDirector()
1180 ph = urllib.request.ProxyHandler(dict(https="proxy.example.com:3128"))
1181 o.add_handler(ph)
1182 meth_spec = [
1183 [("https_open", "return response")]
1184 ]
1185 handlers = add_ordered_mock_handlers(o, meth_spec)
1186
1187 req = Request("https://www.example.com/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001188 self.assertEqual(req.host, "www.example.com")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001189 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001190 self.assertEqual(req.host, "proxy.example.com:3128")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001191 self.assertEqual([(handlers[0], "https_open")],
1192 [tup[0:2] for tup in o.calls])
1193
Senthil Kumaran47fff872009-12-20 07:10:31 +00001194 def test_proxy_https_proxy_authorization(self):
1195 o = OpenerDirector()
1196 ph = urllib.request.ProxyHandler(dict(https='proxy.example.com:3128'))
1197 o.add_handler(ph)
1198 https_handler = MockHTTPSHandler()
1199 o.add_handler(https_handler)
1200 req = Request("https://www.example.com/")
1201 req.add_header("Proxy-Authorization","FooBar")
1202 req.add_header("User-Agent","Grail")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001203 self.assertEqual(req.host, "www.example.com")
Senthil Kumaran47fff872009-12-20 07:10:31 +00001204 self.assertIsNone(req._tunnel_host)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001205 o.open(req)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001206 # Verify Proxy-Authorization gets tunneled to request.
1207 # httpsconn req_headers do not have the Proxy-Authorization header but
1208 # the req will have.
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001209 self.assertNotIn(("Proxy-Authorization","FooBar"),
Senthil Kumaran47fff872009-12-20 07:10:31 +00001210 https_handler.httpconn.req_headers)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001211 self.assertIn(("User-Agent","Grail"),
1212 https_handler.httpconn.req_headers)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001213 self.assertIsNotNone(req._tunnel_host)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001214 self.assertEqual(req.host, "proxy.example.com:3128")
Senthil Kumaran47fff872009-12-20 07:10:31 +00001215 self.assertEqual(req.get_header("Proxy-authorization"),"FooBar")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001216
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001217 # TODO: This should be only for OSX
1218 @unittest.skipUnless(sys.platform == 'darwin', "only relevant for OSX")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001219 def test_osx_proxy_bypass(self):
1220 bypass = {
1221 'exclude_simple': False,
1222 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.10',
1223 '10.0/16']
1224 }
1225 # Check hosts that should trigger the proxy bypass
1226 for host in ('foo.bar', 'www.bar.com', '127.0.0.1', '10.10.0.1',
1227 '10.0.0.1'):
1228 self.assertTrue(_proxy_bypass_macosx_sysconf(host, bypass),
1229 'expected bypass of %s to be True' % host)
1230 # Check hosts that should not trigger the proxy bypass
R David Murrayfdbe9182014-03-15 12:00:14 -04001231 for host in ('abc.foo.bar', 'bar.com', '127.0.0.2', '10.11.0.1',
1232 'notinbypass'):
Ronald Oussorene72e1612011-03-14 18:15:25 -04001233 self.assertFalse(_proxy_bypass_macosx_sysconf(host, bypass),
1234 'expected bypass of %s to be False' % host)
1235
1236 # Check the exclude_simple flag
1237 bypass = {'exclude_simple': True, 'exceptions': []}
1238 self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass))
1239
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001240 def test_basic_auth(self, quote_char='"'):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001241 opener = OpenerDirector()
1242 password_manager = MockPasswordManager()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001243 auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001244 realm = "ACME Widget Store"
1245 http_handler = MockHTTPHandler(
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001246 401, 'WWW-Authenticate: Basic realm=%s%s%s\r\n\r\n' %
1247 (quote_char, realm, quote_char) )
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001248 opener.add_handler(auth_handler)
1249 opener.add_handler(http_handler)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001250 self._test_basic_auth(opener, auth_handler, "Authorization",
1251 realm, http_handler, password_manager,
1252 "http://acme.example.com/protected",
1253 "http://acme.example.com/protected",
1254 )
1255
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001256 def test_basic_auth_with_single_quoted_realm(self):
1257 self.test_basic_auth(quote_char="'")
1258
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +08001259 def test_basic_auth_with_unquoted_realm(self):
1260 opener = OpenerDirector()
1261 password_manager = MockPasswordManager()
1262 auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
1263 realm = "ACME Widget Store"
1264 http_handler = MockHTTPHandler(
1265 401, 'WWW-Authenticate: Basic realm=%s\r\n\r\n' % realm)
1266 opener.add_handler(auth_handler)
1267 opener.add_handler(http_handler)
Senthil Kumaran0ea91cb2012-05-15 23:59:42 +08001268 with self.assertWarns(UserWarning):
1269 self._test_basic_auth(opener, auth_handler, "Authorization",
1270 realm, http_handler, password_manager,
1271 "http://acme.example.com/protected",
1272 "http://acme.example.com/protected",
1273 )
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +08001274
Thomas Wouters477c8d52006-05-27 19:21:47 +00001275 def test_proxy_basic_auth(self):
1276 opener = OpenerDirector()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001277 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001278 opener.add_handler(ph)
1279 password_manager = MockPasswordManager()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001280 auth_handler = urllib.request.ProxyBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001281 realm = "ACME Networks"
1282 http_handler = MockHTTPHandler(
1283 407, 'Proxy-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001284 opener.add_handler(auth_handler)
1285 opener.add_handler(http_handler)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001286 self._test_basic_auth(opener, auth_handler, "Proxy-authorization",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001287 realm, http_handler, password_manager,
1288 "http://acme.example.com:3128/protected",
1289 "proxy.example.com:3128",
1290 )
1291
1292 def test_basic_and_digest_auth_handlers(self):
Andrew Svetlov7bd61cb2012-12-19 22:49:25 +02001293 # HTTPDigestAuthHandler raised an exception if it couldn't handle a 40*
Thomas Wouters477c8d52006-05-27 19:21:47 +00001294 # response (http://python.org/sf/1479302), where it should instead
1295 # return None to allow another handler (especially
1296 # HTTPBasicAuthHandler) to handle the response.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001297
1298 # Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must
1299 # try digest first (since it's the strongest auth scheme), so we record
1300 # order of calls here to check digest comes first:
1301 class RecordingOpenerDirector(OpenerDirector):
1302 def __init__(self):
1303 OpenerDirector.__init__(self)
1304 self.recorded = []
1305 def record(self, info):
1306 self.recorded.append(info)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001307 class TestDigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001308 def http_error_401(self, *args, **kwds):
1309 self.parent.record("digest")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001310 urllib.request.HTTPDigestAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001311 *args, **kwds)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001312 class TestBasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001313 def http_error_401(self, *args, **kwds):
1314 self.parent.record("basic")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001315 urllib.request.HTTPBasicAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001316 *args, **kwds)
1317
1318 opener = RecordingOpenerDirector()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001319 password_manager = MockPasswordManager()
1320 digest_handler = TestDigestAuthHandler(password_manager)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001321 basic_handler = TestBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001322 realm = "ACME Networks"
1323 http_handler = MockHTTPHandler(
1324 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001325 opener.add_handler(basic_handler)
1326 opener.add_handler(digest_handler)
1327 opener.add_handler(http_handler)
1328
1329 # check basic auth isn't blocked by digest handler failing
Thomas Wouters477c8d52006-05-27 19:21:47 +00001330 self._test_basic_auth(opener, basic_handler, "Authorization",
1331 realm, http_handler, password_manager,
1332 "http://acme.example.com/protected",
1333 "http://acme.example.com/protected",
1334 )
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001335 # check digest was tried before basic (twice, because
1336 # _test_basic_auth called .open() twice)
1337 self.assertEqual(opener.recorded, ["digest", "basic"]*2)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001338
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001339 def test_unsupported_auth_digest_handler(self):
1340 opener = OpenerDirector()
1341 # While using DigestAuthHandler
1342 digest_auth_handler = urllib.request.HTTPDigestAuthHandler(None)
1343 http_handler = MockHTTPHandler(
1344 401, 'WWW-Authenticate: Kerberos\r\n\r\n')
1345 opener.add_handler(digest_auth_handler)
1346 opener.add_handler(http_handler)
1347 self.assertRaises(ValueError,opener.open,"http://www.example.com")
1348
1349 def test_unsupported_auth_basic_handler(self):
1350 # While using BasicAuthHandler
1351 opener = OpenerDirector()
1352 basic_auth_handler = urllib.request.HTTPBasicAuthHandler(None)
1353 http_handler = MockHTTPHandler(
1354 401, 'WWW-Authenticate: NTLM\r\n\r\n')
1355 opener.add_handler(basic_auth_handler)
1356 opener.add_handler(http_handler)
1357 self.assertRaises(ValueError,opener.open,"http://www.example.com")
1358
Thomas Wouters477c8d52006-05-27 19:21:47 +00001359 def _test_basic_auth(self, opener, auth_handler, auth_header,
1360 realm, http_handler, password_manager,
1361 request_url, protected_url):
Christian Heimes05e8be12008-02-23 18:30:17 +00001362 import base64
Thomas Wouters477c8d52006-05-27 19:21:47 +00001363 user, password = "wile", "coyote"
Thomas Wouters477c8d52006-05-27 19:21:47 +00001364
1365 # .add_password() fed through to password manager
1366 auth_handler.add_password(realm, request_url, user, password)
1367 self.assertEqual(realm, password_manager.realm)
1368 self.assertEqual(request_url, password_manager.url)
1369 self.assertEqual(user, password_manager.user)
1370 self.assertEqual(password, password_manager.password)
1371
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001372 opener.open(request_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001373
1374 # should have asked the password manager for the username/password
1375 self.assertEqual(password_manager.target_realm, realm)
1376 self.assertEqual(password_manager.target_url, protected_url)
1377
1378 # expect one request without authorization, then one with
1379 self.assertEqual(len(http_handler.requests), 2)
1380 self.assertFalse(http_handler.requests[0].has_header(auth_header))
Guido van Rossum98b349f2007-08-27 21:47:52 +00001381 userpass = bytes('%s:%s' % (user, password), "ascii")
Guido van Rossum98297ee2007-11-06 21:34:58 +00001382 auth_hdr_value = ('Basic ' +
Georg Brandl706824f2009-06-04 09:42:55 +00001383 base64.encodebytes(userpass).strip().decode())
Thomas Wouters477c8d52006-05-27 19:21:47 +00001384 self.assertEqual(http_handler.requests[1].get_header(auth_header),
1385 auth_hdr_value)
Senthil Kumaranca2fc9e2010-02-24 16:53:16 +00001386 self.assertEqual(http_handler.requests[1].unredirected_hdrs[auth_header],
1387 auth_hdr_value)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001388 # if the password manager can't find a password, the handler won't
1389 # handle the HTTP auth error
1390 password_manager.user = password_manager.password = None
1391 http_handler.reset()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001392 opener.open(request_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001393 self.assertEqual(len(http_handler.requests), 1)
1394 self.assertFalse(http_handler.requests[0].has_header(auth_header))
1395
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001396
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001397class MiscTests(unittest.TestCase):
1398
Senthil Kumarane9853da2013-03-19 12:07:43 -07001399 def opener_has_handler(self, opener, handler_class):
1400 self.assertTrue(any(h.__class__ == handler_class
1401 for h in opener.handlers))
1402
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001403 def test_build_opener(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001404 class MyHTTPHandler(urllib.request.HTTPHandler): pass
1405 class FooHandler(urllib.request.BaseHandler):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001406 def foo_open(self): pass
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001407 class BarHandler(urllib.request.BaseHandler):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001408 def bar_open(self): pass
1409
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001410 build_opener = urllib.request.build_opener
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001411
1412 o = build_opener(FooHandler, BarHandler)
1413 self.opener_has_handler(o, FooHandler)
1414 self.opener_has_handler(o, BarHandler)
1415
1416 # can take a mix of classes and instances
1417 o = build_opener(FooHandler, BarHandler())
1418 self.opener_has_handler(o, FooHandler)
1419 self.opener_has_handler(o, BarHandler)
1420
1421 # subclasses of default handlers override default handlers
1422 o = build_opener(MyHTTPHandler)
1423 self.opener_has_handler(o, MyHTTPHandler)
1424
1425 # a particular case of overriding: default handlers can be passed
1426 # in explicitly
1427 o = build_opener()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001428 self.opener_has_handler(o, urllib.request.HTTPHandler)
1429 o = build_opener(urllib.request.HTTPHandler)
1430 self.opener_has_handler(o, urllib.request.HTTPHandler)
1431 o = build_opener(urllib.request.HTTPHandler())
1432 self.opener_has_handler(o, urllib.request.HTTPHandler)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001433
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001434 # Issue2670: multiple handlers sharing the same base class
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001435 class MyOtherHTTPHandler(urllib.request.HTTPHandler): pass
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001436 o = build_opener(MyHTTPHandler, MyOtherHTTPHandler)
1437 self.opener_has_handler(o, MyHTTPHandler)
1438 self.opener_has_handler(o, MyOtherHTTPHandler)
1439
Brett Cannon80512de2013-01-25 22:27:21 -05001440 @unittest.skipUnless(support.is_resource_enabled('network'),
1441 'test requires network access')
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001442 def test_issue16464(self):
1443 opener = urllib.request.build_opener()
Ned Deily5a507f02014-03-26 23:31:39 -07001444 request = urllib.request.Request("http://www.example.com/")
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001445 self.assertEqual(None, request.data)
1446
1447 opener.open(request, "1".encode("us-ascii"))
1448 self.assertEqual(b"1", request.data)
1449 self.assertEqual("1", request.get_header("Content-length"))
1450
1451 opener.open(request, "1234567890".encode("us-ascii"))
1452 self.assertEqual(b"1234567890", request.data)
1453 self.assertEqual("10", request.get_header("Content-length"))
1454
Senthil Kumarane9853da2013-03-19 12:07:43 -07001455 def test_HTTPError_interface(self):
1456 """
1457 Issue 13211 reveals that HTTPError didn't implement the URLError
1458 interface even though HTTPError is a subclass of URLError.
Senthil Kumarane9853da2013-03-19 12:07:43 -07001459 """
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001460 msg = 'something bad happened'
1461 url = code = fp = None
1462 hdrs = 'Content-Length: 42'
1463 err = urllib.error.HTTPError(url, code, msg, hdrs, fp)
1464 self.assertTrue(hasattr(err, 'reason'))
1465 self.assertEqual(err.reason, 'something bad happened')
1466 self.assertTrue(hasattr(err, 'headers'))
1467 self.assertEqual(err.headers, 'Content-Length: 42')
1468 expected_errmsg = 'HTTP Error %s: %s' % (err.code, err.msg)
1469 self.assertEqual(str(err), expected_errmsg)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001470
Senthil Kumarand8e24f12014-04-14 16:32:20 -04001471 def test_parse_proxy(self):
1472 parse_proxy_test_cases = [
1473 ('proxy.example.com',
1474 (None, None, None, 'proxy.example.com')),
1475 ('proxy.example.com:3128',
1476 (None, None, None, 'proxy.example.com:3128')),
1477 ('proxy.example.com', (None, None, None, 'proxy.example.com')),
1478 ('proxy.example.com:3128',
1479 (None, None, None, 'proxy.example.com:3128')),
1480 # The authority component may optionally include userinfo
1481 # (assumed to be # username:password):
1482 ('joe:password@proxy.example.com',
1483 (None, 'joe', 'password', 'proxy.example.com')),
1484 ('joe:password@proxy.example.com:3128',
1485 (None, 'joe', 'password', 'proxy.example.com:3128')),
1486 #Examples with URLS
1487 ('http://proxy.example.com/',
1488 ('http', None, None, 'proxy.example.com')),
1489 ('http://proxy.example.com:3128/',
1490 ('http', None, None, 'proxy.example.com:3128')),
1491 ('http://joe:password@proxy.example.com/',
1492 ('http', 'joe', 'password', 'proxy.example.com')),
1493 ('http://joe:password@proxy.example.com:3128',
1494 ('http', 'joe', 'password', 'proxy.example.com:3128')),
1495 # Everything after the authority is ignored
1496 ('ftp://joe:password@proxy.example.com/rubbish:3128',
1497 ('ftp', 'joe', 'password', 'proxy.example.com')),
1498 # Test for no trailing '/' case
1499 ('http://joe:password@proxy.example.com',
1500 ('http', 'joe', 'password', 'proxy.example.com'))
1501 ]
1502
1503 for tc, expected in parse_proxy_test_cases:
1504 self.assertEqual(_parse_proxy(tc), expected)
1505
1506 self.assertRaises(ValueError, _parse_proxy, 'file:/ftp.example.com'),
1507
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001508class RequestTests(unittest.TestCase):
Jason R. Coombs4a652422013-09-08 13:03:40 -04001509 class PutRequest(Request):
1510 method='PUT'
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001511
1512 def setUp(self):
1513 self.get = Request("http://www.python.org/~jeremy/")
1514 self.post = Request("http://www.python.org/~jeremy/",
1515 "data",
1516 headers={"X-Test": "test"})
Jason R. Coombs4a652422013-09-08 13:03:40 -04001517 self.head = Request("http://www.python.org/~jeremy/", method='HEAD')
1518 self.put = self.PutRequest("http://www.python.org/~jeremy/")
1519 self.force_post = self.PutRequest("http://www.python.org/~jeremy/",
1520 method="POST")
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001521
1522 def test_method(self):
1523 self.assertEqual("POST", self.post.get_method())
1524 self.assertEqual("GET", self.get.get_method())
Senthil Kumaran0b5463f2013-09-09 23:13:06 -07001525 self.assertEqual("HEAD", self.head.get_method())
Jason R. Coombs4a652422013-09-08 13:03:40 -04001526 self.assertEqual("PUT", self.put.get_method())
1527 self.assertEqual("POST", self.force_post.get_method())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001528
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001529 def test_data(self):
1530 self.assertFalse(self.get.data)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001531 self.assertEqual("GET", self.get.get_method())
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001532 self.get.data = "spam"
1533 self.assertTrue(self.get.data)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001534 self.assertEqual("POST", self.get.get_method())
1535
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001536 # issue 16464
1537 # if we change data we need to remove content-length header
1538 # (cause it's most probably calculated for previous value)
1539 def test_setting_data_should_remove_content_length(self):
R David Murray9cc7d452013-03-20 00:10:51 -04001540 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001541 self.get.add_unredirected_header("Content-length", 42)
1542 self.assertEqual(42, self.get.unredirected_hdrs["Content-length"])
1543 self.get.data = "spam"
R David Murray9cc7d452013-03-20 00:10:51 -04001544 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
1545
1546 # issue 17485 same for deleting data.
1547 def test_deleting_data_should_remove_content_length(self):
1548 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
1549 self.get.data = 'foo'
1550 self.get.add_unredirected_header("Content-length", 3)
1551 self.assertEqual(3, self.get.unredirected_hdrs["Content-length"])
1552 del self.get.data
1553 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001554
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001555 def test_get_full_url(self):
1556 self.assertEqual("http://www.python.org/~jeremy/",
1557 self.get.get_full_url())
1558
1559 def test_selector(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001560 self.assertEqual("/~jeremy/", self.get.selector)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001561 req = Request("http://www.python.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001562 self.assertEqual("/", req.selector)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001563
1564 def test_get_type(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001565 self.assertEqual("http", self.get.type)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001566
1567 def test_get_host(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001568 self.assertEqual("www.python.org", self.get.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001569
1570 def test_get_host_unquote(self):
1571 req = Request("http://www.%70ython.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001572 self.assertEqual("www.python.org", req.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001573
1574 def test_proxy(self):
Florent Xicluna419e3842010-08-08 16:16:07 +00001575 self.assertFalse(self.get.has_proxy())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001576 self.get.set_proxy("www.perl.org", "http")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001577 self.assertTrue(self.get.has_proxy())
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001578 self.assertEqual("www.python.org", self.get.origin_req_host)
1579 self.assertEqual("www.perl.org", self.get.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001580
Senthil Kumarand95cc752010-08-08 11:27:53 +00001581 def test_wrapped_url(self):
1582 req = Request("<URL:http://www.python.org>")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001583 self.assertEqual("www.python.org", req.host)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001584
Senthil Kumaran26430412011-04-13 07:01:19 +08001585 def test_url_fragment(self):
Senthil Kumarand95cc752010-08-08 11:27:53 +00001586 req = Request("http://www.python.org/?qs=query#fragment=true")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001587 self.assertEqual("/?qs=query", req.selector)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001588 req = Request("http://www.python.org/#fun=true")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001589 self.assertEqual("/", req.selector)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001590
Senthil Kumaran26430412011-04-13 07:01:19 +08001591 # Issue 11703: geturl() omits fragment in the original URL.
1592 url = 'http://docs.python.org/library/urllib2.html#OK'
1593 req = Request(url)
1594 self.assertEqual(req.get_full_url(), url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001595
Senthil Kumaran83070752013-05-24 09:14:12 -07001596 def test_url_fullurl_get_full_url(self):
1597 urls = ['http://docs.python.org',
1598 'http://docs.python.org/library/urllib2.html#OK',
1599 'http://www.python.org/?qs=query#fragment=true' ]
1600 for url in urls:
1601 req = Request(url)
1602 self.assertEqual(req.get_full_url(), req.full_url)
1603
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001604def test_main(verbose=None):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001605 from test import test_urllib2
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001606 support.run_doctest(test_urllib2, verbose)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001607 support.run_doctest(urllib.request, verbose)
Andrew M. Kuchlingbd3200f2004-06-29 13:15:46 +00001608 tests = (TrivialTests,
1609 OpenerDirectorTests,
1610 HandlerTests,
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001611 MiscTests,
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001612 RequestTests,
1613 RequestHdrsTests)
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001614 support.run_unittest(*tests)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001615
1616if __name__ == "__main__":
1617 test_main(verbose=True)