blob: 6b73723a6e321a02b60965b6a6c521d7a2fcea6f [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):
Benjamin Petersona0c0a4a2008-06-12 22:15:50 +0000681 import email.utils, socket
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",
728 "file://%s:80%s/%s" % (socket.gethostbyname('localhost'),
729 os.getcwd(), TESTFN),
730 "file://somerandomhost.ontheinternet.com%s/%s" %
731 (os.getcwd(), TESTFN),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000732 ]:
733 try:
Tim Peters58eb11c2004-01-18 20:29:55 +0000734 f = open(TESTFN, "wb")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000735 try:
736 f.write(towrite)
737 finally:
738 f.close()
739
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000740 self.assertRaises(urllib.error.URLError,
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000741 h.file_open, Request(url))
742 finally:
743 os.remove(TESTFN)
744
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000745 h = urllib.request.FileHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000746 o = h.parent = MockOpener()
747 # XXXX why does // mean ftp (and /// mean not ftp!), and where
748 # is file: scheme specified? I think this is really a bug, and
749 # what was intended was to distinguish between URLs like:
750 # file:/blah.txt (a file)
751 # file://localhost/blah.txt (a file)
752 # file:///blah.txt (a file)
753 # file://ftp.example.com/blah.txt (an ftp URL)
754 for url, ftp in [
Senthil Kumaran383c32d2010-10-14 11:57:35 +0000755 ("file://ftp.example.com//foo.txt", False),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000756 ("file://ftp.example.com///foo.txt", False),
757# XXXX bug: fails with OSError, should be URLError
758 ("file://ftp.example.com/foo.txt", False),
Senthil Kumaran383c32d2010-10-14 11:57:35 +0000759 ("file://somehost//foo/something.txt", False),
Senthil Kumaran2ef16322010-07-11 03:12:43 +0000760 ("file://localhost//foo/something.txt", False),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000761 ]:
762 req = Request(url)
763 try:
764 h.file_open(req)
765 # XXXX remove OSError when bug fixed
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000766 except (urllib.error.URLError, OSError):
Florent Xicluna419e3842010-08-08 16:16:07 +0000767 self.assertFalse(ftp)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000768 else:
Florent Xicluna419e3842010-08-08 16:16:07 +0000769 self.assertIs(o.req, req)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000770 self.assertEqual(req.type, "ftp")
Łukasz Langad7e81cc2011-01-09 18:18:53 +0000771 self.assertEqual(req.type == "ftp", ftp)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000772
773 def test_http(self):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000774
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000775 h = urllib.request.AbstractHTTPHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000776 o = h.parent = MockOpener()
777
778 url = "http://example.com/"
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000779 for method, data in [("GET", None), ("POST", b"blah")]:
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000780 req = Request(url, data, {"Foo": "bar"})
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000781 req.timeout = None
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000782 req.add_unredirected_header("Spam", "eggs")
783 http = MockHTTPClass()
784 r = h.do_open(http, req)
785
786 # result attributes
787 r.read; r.readline # wrapped MockFile methods
788 r.info; r.geturl # addinfourl methods
789 r.code, r.msg == 200, "OK" # added from MockHTTPClass.getreply()
790 hdrs = r.info()
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000791 hdrs.get; hdrs.__contains__ # r.info() gives dict from .getreply()
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000792 self.assertEqual(r.geturl(), url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000793
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000794 self.assertEqual(http.host, "example.com")
795 self.assertEqual(http.level, 0)
796 self.assertEqual(http.method, method)
797 self.assertEqual(http.selector, "/")
798 self.assertEqual(http.req_headers,
Jeremy Hyltonb3ee6f92004-02-24 19:40:35 +0000799 [("Connection", "close"),
800 ("Foo", "bar"), ("Spam", "eggs")])
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000801 self.assertEqual(http.data, data)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000802
Andrew Svetlov0832af62012-12-18 23:10:48 +0200803 # check OSError converted to URLError
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000804 http.raise_on_endheaders = True
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000805 self.assertRaises(urllib.error.URLError, h.do_open, http, req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000806
Senthil Kumaran29333122011-02-11 11:25:47 +0000807 # Check for TypeError on POST data which is str.
808 req = Request("http://example.com/","badpost")
809 self.assertRaises(TypeError, h.do_request_, req)
810
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000811 # check adding of standard headers
812 o.addheaders = [("Spam", "eggs")]
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000813 for data in b"", None: # POST, GET
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000814 req = Request("http://example.com/", data)
815 r = MockResponse(200, "OK", {}, "")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000816 newreq = h.do_request_(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000817 if data is None: # GET
Benjamin Peterson577473f2010-01-19 00:09:57 +0000818 self.assertNotIn("Content-length", req.unredirected_hdrs)
819 self.assertNotIn("Content-type", req.unredirected_hdrs)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000820 else: # POST
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000821 self.assertEqual(req.unredirected_hdrs["Content-length"], "0")
822 self.assertEqual(req.unredirected_hdrs["Content-type"],
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000823 "application/x-www-form-urlencoded")
824 # XXX the details of Host could be better tested
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000825 self.assertEqual(req.unredirected_hdrs["Host"], "example.com")
826 self.assertEqual(req.unredirected_hdrs["Spam"], "eggs")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000827
828 # don't clobber existing headers
829 req.add_unredirected_header("Content-length", "foo")
830 req.add_unredirected_header("Content-type", "bar")
831 req.add_unredirected_header("Host", "baz")
832 req.add_unredirected_header("Spam", "foo")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000833 newreq = h.do_request_(req)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000834 self.assertEqual(req.unredirected_hdrs["Content-length"], "foo")
835 self.assertEqual(req.unredirected_hdrs["Content-type"], "bar")
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000836 self.assertEqual(req.unredirected_hdrs["Host"], "baz")
837 self.assertEqual(req.unredirected_hdrs["Spam"], "foo")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000838
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000839 # Check iterable body support
840 def iterable_body():
841 yield b"one"
842 yield b"two"
843 yield b"three"
844
845 for headers in {}, {"Content-Length": 11}:
846 req = Request("http://example.com/", iterable_body(), headers)
847 if not headers:
848 # Having an iterable body without a Content-Length should
849 # raise an exception
850 self.assertRaises(ValueError, h.do_request_, req)
851 else:
852 newreq = h.do_request_(req)
853
Senthil Kumaran29333122011-02-11 11:25:47 +0000854 # A file object.
855 # Test only Content-Length attribute of request.
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000856
Senthil Kumaran29333122011-02-11 11:25:47 +0000857 file_obj = io.BytesIO()
858 file_obj.write(b"Something\nSomething\nSomething\n")
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000859
860 for headers in {}, {"Content-Length": 30}:
861 req = Request("http://example.com/", file_obj, headers)
862 if not headers:
863 # Having an iterable body without a Content-Length should
864 # raise an exception
865 self.assertRaises(ValueError, h.do_request_, req)
866 else:
867 newreq = h.do_request_(req)
868 self.assertEqual(int(newreq.get_header('Content-length')),30)
869
870 file_obj.close()
871
872 # array.array Iterable - Content Length is calculated
873
874 iterable_array = array.array("I",[1,2,3,4])
875
876 for headers in {}, {"Content-Length": 16}:
877 req = Request("http://example.com/", iterable_array, headers)
878 newreq = h.do_request_(req)
879 self.assertEqual(int(newreq.get_header('Content-length')),16)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000880
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000881 def test_http_doubleslash(self):
882 # Checks the presence of any unnecessary double slash in url does not
883 # break anything. Previously, a double slash directly after the host
Ezio Melottie130a522011-10-19 10:58:56 +0300884 # could cause incorrect parsing.
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000885 h = urllib.request.AbstractHTTPHandler()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700886 h.parent = MockOpener()
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000887
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000888 data = b""
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000889 ds_urls = [
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 "http://example.com/foo/bar//baz.html"
894 ]
895
896 for ds_url in ds_urls:
897 ds_req = Request(ds_url, data)
898
899 # Check whether host is determined correctly if there is no proxy
900 np_ds_req = h.do_request_(ds_req)
901 self.assertEqual(np_ds_req.unredirected_hdrs["Host"],"example.com")
902
903 # Check whether host is determined correctly if there is a proxy
904 ds_req.set_proxy("someproxy:3128",None)
905 p_ds_req = h.do_request_(ds_req)
906 self.assertEqual(p_ds_req.unredirected_hdrs["Host"],"example.com")
907
Senthil Kumaran52380922013-04-25 05:45:48 -0700908 def test_full_url_setter(self):
909 # Checks to ensure that components are set correctly after setting the
910 # full_url of a Request object
911
912 urls = [
913 'http://example.com?foo=bar#baz',
914 'http://example.com?foo=bar&spam=eggs#bash',
915 'http://example.com',
916 ]
917
918 # testing a reusable request instance, but the url parameter is
919 # required, so just use a dummy one to instantiate
920 r = Request('http://example.com')
921 for url in urls:
922 r.full_url = url
Senthil Kumaran83070752013-05-24 09:14:12 -0700923 parsed = urlparse(url)
924
Senthil Kumaran52380922013-04-25 05:45:48 -0700925 self.assertEqual(r.get_full_url(), url)
Senthil Kumaran83070752013-05-24 09:14:12 -0700926 # full_url setter uses splittag to split into components.
927 # splittag sets the fragment as None while urlparse sets it to ''
928 self.assertEqual(r.fragment or '', parsed.fragment)
929 self.assertEqual(urlparse(r.get_full_url()).query, parsed.query)
Senthil Kumaran52380922013-04-25 05:45:48 -0700930
931 def test_full_url_deleter(self):
932 r = Request('http://www.example.com')
933 del r.full_url
934 self.assertIsNone(r.full_url)
935 self.assertIsNone(r.fragment)
936 self.assertEqual(r.selector, '')
937
Senthil Kumaranc2958622010-11-22 04:48:26 +0000938 def test_fixpath_in_weirdurls(self):
939 # Issue4493: urllib2 to supply '/' when to urls where path does not
940 # start with'/'
941
942 h = urllib.request.AbstractHTTPHandler()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700943 h.parent = MockOpener()
Senthil Kumaranc2958622010-11-22 04:48:26 +0000944
945 weird_url = 'http://www.python.org?getspam'
946 req = Request(weird_url)
947 newreq = h.do_request_(req)
948 self.assertEqual(newreq.host,'www.python.org')
949 self.assertEqual(newreq.selector,'/?getspam')
950
951 url_without_path = 'http://www.python.org'
952 req = Request(url_without_path)
953 newreq = h.do_request_(req)
954 self.assertEqual(newreq.host,'www.python.org')
955 self.assertEqual(newreq.selector,'')
956
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000957
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000958 def test_errors(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000959 h = urllib.request.HTTPErrorProcessor()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000960 o = h.parent = MockOpener()
961
962 url = "http://example.com/"
963 req = Request(url)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000964 # all 2xx are passed through
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000965 r = MockResponse(200, "OK", {}, "", url)
966 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +0000967 self.assertIs(r, newr)
968 self.assertFalse(hasattr(o, "proto")) # o.error not called
Guido van Rossumd8faa362007-04-27 19:54:29 +0000969 r = MockResponse(202, "Accepted", {}, "", url)
970 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +0000971 self.assertIs(r, newr)
972 self.assertFalse(hasattr(o, "proto")) # o.error not called
Guido van Rossumd8faa362007-04-27 19:54:29 +0000973 r = MockResponse(206, "Partial content", {}, "", url)
974 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +0000975 self.assertIs(r, newr)
976 self.assertFalse(hasattr(o, "proto")) # o.error not called
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000977 # anything else calls o.error (and MockOpener returns None, here)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000978 r = MockResponse(502, "Bad gateway", {}, "", url)
Florent Xicluna419e3842010-08-08 16:16:07 +0000979 self.assertIsNone(h.http_response(req, r))
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000980 self.assertEqual(o.proto, "http") # o.error called
Guido van Rossumd8faa362007-04-27 19:54:29 +0000981 self.assertEqual(o.args, (req, r, 502, "Bad gateway", {}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000982
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000983 def test_cookies(self):
984 cj = MockCookieJar()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000985 h = urllib.request.HTTPCookieProcessor(cj)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700986 h.parent = MockOpener()
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000987
988 req = Request("http://example.com/")
989 r = MockResponse(200, "OK", {}, "")
990 newreq = h.http_request(req)
Florent Xicluna419e3842010-08-08 16:16:07 +0000991 self.assertIs(cj.ach_req, req)
992 self.assertIs(cj.ach_req, newreq)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -0700993 self.assertEqual(req.origin_req_host, "example.com")
994 self.assertFalse(req.unverifiable)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000995 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +0000996 self.assertIs(cj.ec_req, req)
997 self.assertIs(cj.ec_r, r)
998 self.assertIs(r, newr)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000999
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001000 def test_redirect(self):
1001 from_url = "http://example.com/a.html"
1002 to_url = "http://example.com/b.html"
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001003 h = urllib.request.HTTPRedirectHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001004 o = h.parent = MockOpener()
1005
1006 # ordinary redirect behaviour
1007 for code in 301, 302, 303, 307:
1008 for data in None, "blah\nblah\n":
1009 method = getattr(h, "http_error_%s" % code)
1010 req = Request(from_url, data)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001011 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001012 req.add_header("Nonsense", "viking=withhold")
Christian Heimes77c02eb2008-02-09 02:18:51 +00001013 if data is not None:
1014 req.add_header("Content-Length", str(len(data)))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001015 req.add_unredirected_header("Spam", "spam")
1016 try:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001017 method(req, MockFile(), code, "Blah",
1018 MockHeaders({"location": to_url}))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001019 except urllib.error.HTTPError:
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001020 # 307 in response to POST requires user OK
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001021 self.assertEqual(code, 307)
1022 self.assertIsNotNone(data)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001023 self.assertEqual(o.req.get_full_url(), to_url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001024 try:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001025 self.assertEqual(o.req.get_method(), "GET")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001026 except AttributeError:
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001027 self.assertFalse(o.req.data)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001028
1029 # now it's a GET, there should not be headers regarding content
1030 # (possibly dragged from before being a POST)
1031 headers = [x.lower() for x in o.req.headers]
Benjamin Peterson577473f2010-01-19 00:09:57 +00001032 self.assertNotIn("content-length", headers)
1033 self.assertNotIn("content-type", headers)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001034
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001035 self.assertEqual(o.req.headers["Nonsense"],
1036 "viking=withhold")
Benjamin Peterson577473f2010-01-19 00:09:57 +00001037 self.assertNotIn("Spam", o.req.headers)
1038 self.assertNotIn("Spam", o.req.unredirected_hdrs)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001039
1040 # loop detection
1041 req = Request(from_url)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001042 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001043 def redirect(h, req, url=to_url):
1044 h.http_error_302(req, MockFile(), 302, "Blah",
1045 MockHeaders({"location": url}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001046 # Note that the *original* request shares the same record of
1047 # redirections with the sub-requests caused by the redirections.
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001048
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001049 # detect infinite loop redirect of a URL to itself
1050 req = Request(from_url, origin_req_host="example.com")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001051 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001052 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001053 try:
1054 while 1:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001055 redirect(h, req, "http://example.com/")
1056 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001057 except urllib.error.HTTPError:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001058 # don't stop until max_repeats, because cookies may introduce state
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001059 self.assertEqual(count, urllib.request.HTTPRedirectHandler.max_repeats)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001060
1061 # detect endless non-repeating chain of redirects
1062 req = Request(from_url, origin_req_host="example.com")
1063 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001064 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001065 try:
1066 while 1:
1067 redirect(h, req, "http://example.com/%d" % count)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001068 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001069 except urllib.error.HTTPError:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001070 self.assertEqual(count,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001071 urllib.request.HTTPRedirectHandler.max_redirections)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001072
guido@google.coma119df92011-03-29 11:41:02 -07001073
1074 def test_invalid_redirect(self):
1075 from_url = "http://example.com/a.html"
1076 valid_schemes = ['http','https','ftp']
1077 invalid_schemes = ['file','imap','ldap']
1078 schemeless_url = "example.com/b.html"
1079 h = urllib.request.HTTPRedirectHandler()
1080 o = h.parent = MockOpener()
1081 req = Request(from_url)
1082 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1083
1084 for scheme in invalid_schemes:
1085 invalid_url = scheme + '://' + schemeless_url
1086 self.assertRaises(urllib.error.HTTPError, h.http_error_302,
1087 req, MockFile(), 302, "Security Loophole",
1088 MockHeaders({"location": invalid_url}))
1089
1090 for scheme in valid_schemes:
1091 valid_url = scheme + '://' + schemeless_url
1092 h.http_error_302(req, MockFile(), 302, "That's fine",
1093 MockHeaders({"location": valid_url}))
1094 self.assertEqual(o.req.get_full_url(), valid_url)
1095
Senthil Kumaran6497aa32012-01-04 13:46:59 +08001096 def test_relative_redirect(self):
1097 from_url = "http://example.com/a.html"
1098 relative_url = "/b.html"
1099 h = urllib.request.HTTPRedirectHandler()
1100 o = h.parent = MockOpener()
1101 req = Request(from_url)
1102 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1103
1104 valid_url = urllib.parse.urljoin(from_url,relative_url)
1105 h.http_error_302(req, MockFile(), 302, "That's fine",
1106 MockHeaders({"location": valid_url}))
1107 self.assertEqual(o.req.get_full_url(), valid_url)
1108
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001109 def test_cookie_redirect(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001110 # cookies shouldn't leak into redirected requests
Georg Brandl24420152008-05-26 16:32:26 +00001111 from http.cookiejar import CookieJar
1112 from test.test_http_cookiejar import interact_netscape
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001113
1114 cj = CookieJar()
1115 interact_netscape(cj, "http://www.example.com/", "spam=eggs")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001116 hh = MockHTTPHandler(302, "Location: http://www.cracker.com/\r\n\r\n")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001117 hdeh = urllib.request.HTTPDefaultErrorHandler()
1118 hrh = urllib.request.HTTPRedirectHandler()
1119 cp = urllib.request.HTTPCookieProcessor(cj)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001120 o = build_test_opener(hh, hdeh, hrh, cp)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001121 o.open("http://www.example.com/")
Florent Xicluna419e3842010-08-08 16:16:07 +00001122 self.assertFalse(hh.req.has_header("Cookie"))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001123
Senthil Kumaran26430412011-04-13 07:01:19 +08001124 def test_redirect_fragment(self):
1125 redirected_url = 'http://www.example.com/index.html#OK\r\n\r\n'
1126 hh = MockHTTPHandler(302, 'Location: ' + redirected_url)
1127 hdeh = urllib.request.HTTPDefaultErrorHandler()
1128 hrh = urllib.request.HTTPRedirectHandler()
1129 o = build_test_opener(hh, hdeh, hrh)
1130 fp = o.open('http://www.example.com')
1131 self.assertEqual(fp.geturl(), redirected_url.strip())
1132
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001133 def test_proxy(self):
1134 o = OpenerDirector()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001135 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001136 o.add_handler(ph)
1137 meth_spec = [
1138 [("http_open", "return response")]
1139 ]
1140 handlers = add_ordered_mock_handlers(o, meth_spec)
1141
1142 req = Request("http://acme.example.com/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001143 self.assertEqual(req.host, "acme.example.com")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001144 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001145 self.assertEqual(req.host, "proxy.example.com:3128")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001146
1147 self.assertEqual([(handlers[0], "http_open")],
1148 [tup[0:2] for tup in o.calls])
1149
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001150 def test_proxy_no_proxy(self):
1151 os.environ['no_proxy'] = 'python.org'
1152 o = OpenerDirector()
1153 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1154 o.add_handler(ph)
1155 req = Request("http://www.perl.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001156 self.assertEqual(req.host, "www.perl.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001157 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001158 self.assertEqual(req.host, "proxy.example.com")
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001159 req = Request("http://www.python.org")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001160 self.assertEqual(req.host, "www.python.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001161 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001162 self.assertEqual(req.host, "www.python.org")
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001163 del os.environ['no_proxy']
1164
Ronald Oussorene72e1612011-03-14 18:15:25 -04001165 def test_proxy_no_proxy_all(self):
1166 os.environ['no_proxy'] = '*'
1167 o = OpenerDirector()
1168 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1169 o.add_handler(ph)
1170 req = Request("http://www.python.org")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001171 self.assertEqual(req.host, "www.python.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001172 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001173 self.assertEqual(req.host, "www.python.org")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001174 del os.environ['no_proxy']
1175
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001176
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001177 def test_proxy_https(self):
1178 o = OpenerDirector()
1179 ph = urllib.request.ProxyHandler(dict(https="proxy.example.com:3128"))
1180 o.add_handler(ph)
1181 meth_spec = [
1182 [("https_open", "return response")]
1183 ]
1184 handlers = add_ordered_mock_handlers(o, meth_spec)
1185
1186 req = Request("https://www.example.com/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001187 self.assertEqual(req.host, "www.example.com")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001188 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001189 self.assertEqual(req.host, "proxy.example.com:3128")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001190 self.assertEqual([(handlers[0], "https_open")],
1191 [tup[0:2] for tup in o.calls])
1192
Senthil Kumaran47fff872009-12-20 07:10:31 +00001193 def test_proxy_https_proxy_authorization(self):
1194 o = OpenerDirector()
1195 ph = urllib.request.ProxyHandler(dict(https='proxy.example.com:3128'))
1196 o.add_handler(ph)
1197 https_handler = MockHTTPSHandler()
1198 o.add_handler(https_handler)
1199 req = Request("https://www.example.com/")
1200 req.add_header("Proxy-Authorization","FooBar")
1201 req.add_header("User-Agent","Grail")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001202 self.assertEqual(req.host, "www.example.com")
Senthil Kumaran47fff872009-12-20 07:10:31 +00001203 self.assertIsNone(req._tunnel_host)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001204 o.open(req)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001205 # Verify Proxy-Authorization gets tunneled to request.
1206 # httpsconn req_headers do not have the Proxy-Authorization header but
1207 # the req will have.
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001208 self.assertNotIn(("Proxy-Authorization","FooBar"),
Senthil Kumaran47fff872009-12-20 07:10:31 +00001209 https_handler.httpconn.req_headers)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001210 self.assertIn(("User-Agent","Grail"),
1211 https_handler.httpconn.req_headers)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001212 self.assertIsNotNone(req._tunnel_host)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001213 self.assertEqual(req.host, "proxy.example.com:3128")
Senthil Kumaran47fff872009-12-20 07:10:31 +00001214 self.assertEqual(req.get_header("Proxy-authorization"),"FooBar")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001215
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001216 # TODO: This should be only for OSX
1217 @unittest.skipUnless(sys.platform == 'darwin', "only relevant for OSX")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001218 def test_osx_proxy_bypass(self):
1219 bypass = {
1220 'exclude_simple': False,
1221 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.10',
1222 '10.0/16']
1223 }
1224 # Check hosts that should trigger the proxy bypass
1225 for host in ('foo.bar', 'www.bar.com', '127.0.0.1', '10.10.0.1',
1226 '10.0.0.1'):
1227 self.assertTrue(_proxy_bypass_macosx_sysconf(host, bypass),
1228 'expected bypass of %s to be True' % host)
1229 # Check hosts that should not trigger the proxy bypass
R David Murrayfdbe9182014-03-15 12:00:14 -04001230 for host in ('abc.foo.bar', 'bar.com', '127.0.0.2', '10.11.0.1',
1231 'notinbypass'):
Ronald Oussorene72e1612011-03-14 18:15:25 -04001232 self.assertFalse(_proxy_bypass_macosx_sysconf(host, bypass),
1233 'expected bypass of %s to be False' % host)
1234
1235 # Check the exclude_simple flag
1236 bypass = {'exclude_simple': True, 'exceptions': []}
1237 self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass))
1238
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001239 def test_basic_auth(self, quote_char='"'):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001240 opener = OpenerDirector()
1241 password_manager = MockPasswordManager()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001242 auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001243 realm = "ACME Widget Store"
1244 http_handler = MockHTTPHandler(
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001245 401, 'WWW-Authenticate: Basic realm=%s%s%s\r\n\r\n' %
1246 (quote_char, realm, quote_char) )
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001247 opener.add_handler(auth_handler)
1248 opener.add_handler(http_handler)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001249 self._test_basic_auth(opener, auth_handler, "Authorization",
1250 realm, http_handler, password_manager,
1251 "http://acme.example.com/protected",
1252 "http://acme.example.com/protected",
1253 )
1254
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001255 def test_basic_auth_with_single_quoted_realm(self):
1256 self.test_basic_auth(quote_char="'")
1257
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +08001258 def test_basic_auth_with_unquoted_realm(self):
1259 opener = OpenerDirector()
1260 password_manager = MockPasswordManager()
1261 auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
1262 realm = "ACME Widget Store"
1263 http_handler = MockHTTPHandler(
1264 401, 'WWW-Authenticate: Basic realm=%s\r\n\r\n' % realm)
1265 opener.add_handler(auth_handler)
1266 opener.add_handler(http_handler)
Senthil Kumaran0ea91cb2012-05-15 23:59:42 +08001267 with self.assertWarns(UserWarning):
1268 self._test_basic_auth(opener, auth_handler, "Authorization",
1269 realm, http_handler, password_manager,
1270 "http://acme.example.com/protected",
1271 "http://acme.example.com/protected",
1272 )
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +08001273
Thomas Wouters477c8d52006-05-27 19:21:47 +00001274 def test_proxy_basic_auth(self):
1275 opener = OpenerDirector()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001276 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001277 opener.add_handler(ph)
1278 password_manager = MockPasswordManager()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001279 auth_handler = urllib.request.ProxyBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001280 realm = "ACME Networks"
1281 http_handler = MockHTTPHandler(
1282 407, 'Proxy-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001283 opener.add_handler(auth_handler)
1284 opener.add_handler(http_handler)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001285 self._test_basic_auth(opener, auth_handler, "Proxy-authorization",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001286 realm, http_handler, password_manager,
1287 "http://acme.example.com:3128/protected",
1288 "proxy.example.com:3128",
1289 )
1290
1291 def test_basic_and_digest_auth_handlers(self):
Andrew Svetlov7bd61cb2012-12-19 22:49:25 +02001292 # HTTPDigestAuthHandler raised an exception if it couldn't handle a 40*
Thomas Wouters477c8d52006-05-27 19:21:47 +00001293 # response (http://python.org/sf/1479302), where it should instead
1294 # return None to allow another handler (especially
1295 # HTTPBasicAuthHandler) to handle the response.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001296
1297 # Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must
1298 # try digest first (since it's the strongest auth scheme), so we record
1299 # order of calls here to check digest comes first:
1300 class RecordingOpenerDirector(OpenerDirector):
1301 def __init__(self):
1302 OpenerDirector.__init__(self)
1303 self.recorded = []
1304 def record(self, info):
1305 self.recorded.append(info)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001306 class TestDigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001307 def http_error_401(self, *args, **kwds):
1308 self.parent.record("digest")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001309 urllib.request.HTTPDigestAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001310 *args, **kwds)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001311 class TestBasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001312 def http_error_401(self, *args, **kwds):
1313 self.parent.record("basic")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001314 urllib.request.HTTPBasicAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001315 *args, **kwds)
1316
1317 opener = RecordingOpenerDirector()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001318 password_manager = MockPasswordManager()
1319 digest_handler = TestDigestAuthHandler(password_manager)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001320 basic_handler = TestBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001321 realm = "ACME Networks"
1322 http_handler = MockHTTPHandler(
1323 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001324 opener.add_handler(basic_handler)
1325 opener.add_handler(digest_handler)
1326 opener.add_handler(http_handler)
1327
1328 # check basic auth isn't blocked by digest handler failing
Thomas Wouters477c8d52006-05-27 19:21:47 +00001329 self._test_basic_auth(opener, basic_handler, "Authorization",
1330 realm, http_handler, password_manager,
1331 "http://acme.example.com/protected",
1332 "http://acme.example.com/protected",
1333 )
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001334 # check digest was tried before basic (twice, because
1335 # _test_basic_auth called .open() twice)
1336 self.assertEqual(opener.recorded, ["digest", "basic"]*2)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001337
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001338 def test_unsupported_auth_digest_handler(self):
1339 opener = OpenerDirector()
1340 # While using DigestAuthHandler
1341 digest_auth_handler = urllib.request.HTTPDigestAuthHandler(None)
1342 http_handler = MockHTTPHandler(
1343 401, 'WWW-Authenticate: Kerberos\r\n\r\n')
1344 opener.add_handler(digest_auth_handler)
1345 opener.add_handler(http_handler)
1346 self.assertRaises(ValueError,opener.open,"http://www.example.com")
1347
1348 def test_unsupported_auth_basic_handler(self):
1349 # While using BasicAuthHandler
1350 opener = OpenerDirector()
1351 basic_auth_handler = urllib.request.HTTPBasicAuthHandler(None)
1352 http_handler = MockHTTPHandler(
1353 401, 'WWW-Authenticate: NTLM\r\n\r\n')
1354 opener.add_handler(basic_auth_handler)
1355 opener.add_handler(http_handler)
1356 self.assertRaises(ValueError,opener.open,"http://www.example.com")
1357
Thomas Wouters477c8d52006-05-27 19:21:47 +00001358 def _test_basic_auth(self, opener, auth_handler, auth_header,
1359 realm, http_handler, password_manager,
1360 request_url, protected_url):
Christian Heimes05e8be12008-02-23 18:30:17 +00001361 import base64
Thomas Wouters477c8d52006-05-27 19:21:47 +00001362 user, password = "wile", "coyote"
Thomas Wouters477c8d52006-05-27 19:21:47 +00001363
1364 # .add_password() fed through to password manager
1365 auth_handler.add_password(realm, request_url, user, password)
1366 self.assertEqual(realm, password_manager.realm)
1367 self.assertEqual(request_url, password_manager.url)
1368 self.assertEqual(user, password_manager.user)
1369 self.assertEqual(password, password_manager.password)
1370
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001371 opener.open(request_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001372
1373 # should have asked the password manager for the username/password
1374 self.assertEqual(password_manager.target_realm, realm)
1375 self.assertEqual(password_manager.target_url, protected_url)
1376
1377 # expect one request without authorization, then one with
1378 self.assertEqual(len(http_handler.requests), 2)
1379 self.assertFalse(http_handler.requests[0].has_header(auth_header))
Guido van Rossum98b349f2007-08-27 21:47:52 +00001380 userpass = bytes('%s:%s' % (user, password), "ascii")
Guido van Rossum98297ee2007-11-06 21:34:58 +00001381 auth_hdr_value = ('Basic ' +
Georg Brandl706824f2009-06-04 09:42:55 +00001382 base64.encodebytes(userpass).strip().decode())
Thomas Wouters477c8d52006-05-27 19:21:47 +00001383 self.assertEqual(http_handler.requests[1].get_header(auth_header),
1384 auth_hdr_value)
Senthil Kumaranca2fc9e2010-02-24 16:53:16 +00001385 self.assertEqual(http_handler.requests[1].unredirected_hdrs[auth_header],
1386 auth_hdr_value)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001387 # if the password manager can't find a password, the handler won't
1388 # handle the HTTP auth error
1389 password_manager.user = password_manager.password = None
1390 http_handler.reset()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001391 opener.open(request_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001392 self.assertEqual(len(http_handler.requests), 1)
1393 self.assertFalse(http_handler.requests[0].has_header(auth_header))
1394
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001395
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001396class MiscTests(unittest.TestCase):
1397
Senthil Kumarane9853da2013-03-19 12:07:43 -07001398 def opener_has_handler(self, opener, handler_class):
1399 self.assertTrue(any(h.__class__ == handler_class
1400 for h in opener.handlers))
1401
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001402 def test_build_opener(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001403 class MyHTTPHandler(urllib.request.HTTPHandler): pass
1404 class FooHandler(urllib.request.BaseHandler):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001405 def foo_open(self): pass
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001406 class BarHandler(urllib.request.BaseHandler):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001407 def bar_open(self): pass
1408
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001409 build_opener = urllib.request.build_opener
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001410
1411 o = build_opener(FooHandler, BarHandler)
1412 self.opener_has_handler(o, FooHandler)
1413 self.opener_has_handler(o, BarHandler)
1414
1415 # can take a mix of classes and instances
1416 o = build_opener(FooHandler, BarHandler())
1417 self.opener_has_handler(o, FooHandler)
1418 self.opener_has_handler(o, BarHandler)
1419
1420 # subclasses of default handlers override default handlers
1421 o = build_opener(MyHTTPHandler)
1422 self.opener_has_handler(o, MyHTTPHandler)
1423
1424 # a particular case of overriding: default handlers can be passed
1425 # in explicitly
1426 o = build_opener()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001427 self.opener_has_handler(o, urllib.request.HTTPHandler)
1428 o = build_opener(urllib.request.HTTPHandler)
1429 self.opener_has_handler(o, urllib.request.HTTPHandler)
1430 o = build_opener(urllib.request.HTTPHandler())
1431 self.opener_has_handler(o, urllib.request.HTTPHandler)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001432
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001433 # Issue2670: multiple handlers sharing the same base class
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001434 class MyOtherHTTPHandler(urllib.request.HTTPHandler): pass
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001435 o = build_opener(MyHTTPHandler, MyOtherHTTPHandler)
1436 self.opener_has_handler(o, MyHTTPHandler)
1437 self.opener_has_handler(o, MyOtherHTTPHandler)
1438
Brett Cannon80512de2013-01-25 22:27:21 -05001439 @unittest.skipUnless(support.is_resource_enabled('network'),
1440 'test requires network access')
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001441 def test_issue16464(self):
1442 opener = urllib.request.build_opener()
Ned Deily5a507f02014-03-26 23:31:39 -07001443 request = urllib.request.Request("http://www.example.com/")
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001444 self.assertEqual(None, request.data)
1445
1446 opener.open(request, "1".encode("us-ascii"))
1447 self.assertEqual(b"1", request.data)
1448 self.assertEqual("1", request.get_header("Content-length"))
1449
1450 opener.open(request, "1234567890".encode("us-ascii"))
1451 self.assertEqual(b"1234567890", request.data)
1452 self.assertEqual("10", request.get_header("Content-length"))
1453
Senthil Kumarane9853da2013-03-19 12:07:43 -07001454 def test_HTTPError_interface(self):
1455 """
1456 Issue 13211 reveals that HTTPError didn't implement the URLError
1457 interface even though HTTPError is a subclass of URLError.
Senthil Kumarane9853da2013-03-19 12:07:43 -07001458 """
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001459 msg = 'something bad happened'
1460 url = code = fp = None
1461 hdrs = 'Content-Length: 42'
1462 err = urllib.error.HTTPError(url, code, msg, hdrs, fp)
1463 self.assertTrue(hasattr(err, 'reason'))
1464 self.assertEqual(err.reason, 'something bad happened')
1465 self.assertTrue(hasattr(err, 'headers'))
1466 self.assertEqual(err.headers, 'Content-Length: 42')
1467 expected_errmsg = 'HTTP Error %s: %s' % (err.code, err.msg)
1468 self.assertEqual(str(err), expected_errmsg)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001469
Senthil Kumarand8e24f12014-04-14 16:32:20 -04001470 def test_parse_proxy(self):
1471 parse_proxy_test_cases = [
1472 ('proxy.example.com',
1473 (None, None, None, 'proxy.example.com')),
1474 ('proxy.example.com:3128',
1475 (None, None, None, 'proxy.example.com:3128')),
1476 ('proxy.example.com', (None, None, None, 'proxy.example.com')),
1477 ('proxy.example.com:3128',
1478 (None, None, None, 'proxy.example.com:3128')),
1479 # The authority component may optionally include userinfo
1480 # (assumed to be # username:password):
1481 ('joe:password@proxy.example.com',
1482 (None, 'joe', 'password', 'proxy.example.com')),
1483 ('joe:password@proxy.example.com:3128',
1484 (None, 'joe', 'password', 'proxy.example.com:3128')),
1485 #Examples with URLS
1486 ('http://proxy.example.com/',
1487 ('http', None, None, 'proxy.example.com')),
1488 ('http://proxy.example.com:3128/',
1489 ('http', None, None, 'proxy.example.com:3128')),
1490 ('http://joe:password@proxy.example.com/',
1491 ('http', 'joe', 'password', 'proxy.example.com')),
1492 ('http://joe:password@proxy.example.com:3128',
1493 ('http', 'joe', 'password', 'proxy.example.com:3128')),
1494 # Everything after the authority is ignored
1495 ('ftp://joe:password@proxy.example.com/rubbish:3128',
1496 ('ftp', 'joe', 'password', 'proxy.example.com')),
1497 # Test for no trailing '/' case
1498 ('http://joe:password@proxy.example.com',
1499 ('http', 'joe', 'password', 'proxy.example.com'))
1500 ]
1501
1502 for tc, expected in parse_proxy_test_cases:
1503 self.assertEqual(_parse_proxy(tc), expected)
1504
1505 self.assertRaises(ValueError, _parse_proxy, 'file:/ftp.example.com'),
1506
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001507class RequestTests(unittest.TestCase):
Jason R. Coombs4a652422013-09-08 13:03:40 -04001508 class PutRequest(Request):
1509 method='PUT'
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001510
1511 def setUp(self):
1512 self.get = Request("http://www.python.org/~jeremy/")
1513 self.post = Request("http://www.python.org/~jeremy/",
1514 "data",
1515 headers={"X-Test": "test"})
Jason R. Coombs4a652422013-09-08 13:03:40 -04001516 self.head = Request("http://www.python.org/~jeremy/", method='HEAD')
1517 self.put = self.PutRequest("http://www.python.org/~jeremy/")
1518 self.force_post = self.PutRequest("http://www.python.org/~jeremy/",
1519 method="POST")
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001520
1521 def test_method(self):
1522 self.assertEqual("POST", self.post.get_method())
1523 self.assertEqual("GET", self.get.get_method())
Senthil Kumaran0b5463f2013-09-09 23:13:06 -07001524 self.assertEqual("HEAD", self.head.get_method())
Jason R. Coombs4a652422013-09-08 13:03:40 -04001525 self.assertEqual("PUT", self.put.get_method())
1526 self.assertEqual("POST", self.force_post.get_method())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001527
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001528 def test_data(self):
1529 self.assertFalse(self.get.data)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001530 self.assertEqual("GET", self.get.get_method())
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001531 self.get.data = "spam"
1532 self.assertTrue(self.get.data)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001533 self.assertEqual("POST", self.get.get_method())
1534
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001535 # issue 16464
1536 # if we change data we need to remove content-length header
1537 # (cause it's most probably calculated for previous value)
1538 def test_setting_data_should_remove_content_length(self):
R David Murray9cc7d452013-03-20 00:10:51 -04001539 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001540 self.get.add_unredirected_header("Content-length", 42)
1541 self.assertEqual(42, self.get.unredirected_hdrs["Content-length"])
1542 self.get.data = "spam"
R David Murray9cc7d452013-03-20 00:10:51 -04001543 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
1544
1545 # issue 17485 same for deleting data.
1546 def test_deleting_data_should_remove_content_length(self):
1547 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
1548 self.get.data = 'foo'
1549 self.get.add_unredirected_header("Content-length", 3)
1550 self.assertEqual(3, self.get.unredirected_hdrs["Content-length"])
1551 del self.get.data
1552 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001553
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001554 def test_get_full_url(self):
1555 self.assertEqual("http://www.python.org/~jeremy/",
1556 self.get.get_full_url())
1557
1558 def test_selector(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001559 self.assertEqual("/~jeremy/", self.get.selector)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001560 req = Request("http://www.python.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001561 self.assertEqual("/", req.selector)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001562
1563 def test_get_type(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001564 self.assertEqual("http", self.get.type)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001565
1566 def test_get_host(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001567 self.assertEqual("www.python.org", self.get.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001568
1569 def test_get_host_unquote(self):
1570 req = Request("http://www.%70ython.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001571 self.assertEqual("www.python.org", req.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001572
1573 def test_proxy(self):
Florent Xicluna419e3842010-08-08 16:16:07 +00001574 self.assertFalse(self.get.has_proxy())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001575 self.get.set_proxy("www.perl.org", "http")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001576 self.assertTrue(self.get.has_proxy())
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001577 self.assertEqual("www.python.org", self.get.origin_req_host)
1578 self.assertEqual("www.perl.org", self.get.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001579
Senthil Kumarand95cc752010-08-08 11:27:53 +00001580 def test_wrapped_url(self):
1581 req = Request("<URL:http://www.python.org>")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001582 self.assertEqual("www.python.org", req.host)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001583
Senthil Kumaran26430412011-04-13 07:01:19 +08001584 def test_url_fragment(self):
Senthil Kumarand95cc752010-08-08 11:27:53 +00001585 req = Request("http://www.python.org/?qs=query#fragment=true")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001586 self.assertEqual("/?qs=query", req.selector)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001587 req = Request("http://www.python.org/#fun=true")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001588 self.assertEqual("/", req.selector)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001589
Senthil Kumaran26430412011-04-13 07:01:19 +08001590 # Issue 11703: geturl() omits fragment in the original URL.
1591 url = 'http://docs.python.org/library/urllib2.html#OK'
1592 req = Request(url)
1593 self.assertEqual(req.get_full_url(), url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001594
Senthil Kumaran83070752013-05-24 09:14:12 -07001595 def test_url_fullurl_get_full_url(self):
1596 urls = ['http://docs.python.org',
1597 'http://docs.python.org/library/urllib2.html#OK',
1598 'http://www.python.org/?qs=query#fragment=true' ]
1599 for url in urls:
1600 req = Request(url)
1601 self.assertEqual(req.get_full_url(), req.full_url)
1602
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001603def test_main(verbose=None):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001604 from test import test_urllib2
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001605 support.run_doctest(test_urllib2, verbose)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001606 support.run_doctest(urllib.request, verbose)
Andrew M. Kuchlingbd3200f2004-06-29 13:15:46 +00001607 tests = (TrivialTests,
1608 OpenerDirectorTests,
1609 HandlerTests,
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001610 MiscTests,
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001611 RequestTests,
1612 RequestHdrsTests)
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001613 support.run_unittest(*tests)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001614
1615if __name__ == "__main__":
1616 test_main(verbose=True)