blob: dbd1c60ec24bd6fc1a6014c991d267d233c3bcbf [file] [log] [blame]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002from test import support
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00003
Christian Heimes05e8be12008-02-23 18:30:17 +00004import os
Guido van Rossum34d19282007-08-09 01:03:29 +00005import io
Georg Brandlf78e02b2008-06-10 17:40:04 +00006import socket
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00007import array
Senthil Kumaran4de00a22011-05-11 21:17:57 +08008import sys
Jeremy Hyltone3e61042001-05-09 15:50:25 +00009
Jeremy Hylton1afc1692008-06-18 20:49:58 +000010import urllib.request
Ronald Oussorene72e1612011-03-14 18:15:25 -040011# The proxy bypass method imported below has logic specific to the OSX
12# proxy config data structure but is testable on all platforms.
13from urllib.request import Request, OpenerDirector, _proxy_bypass_macosx_sysconf
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
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000606 self.assertTrue(args[1] is None or
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000607 isinstance(args[1], MockResponse))
608
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
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001021 self.assertTrue(code == 307 and data is not None)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001022 self.assertEqual(o.req.get_full_url(), to_url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001023 try:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001024 self.assertEqual(o.req.get_method(), "GET")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001025 except AttributeError:
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001026 self.assertFalse(o.req.data)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001027
1028 # now it's a GET, there should not be headers regarding content
1029 # (possibly dragged from before being a POST)
1030 headers = [x.lower() for x in o.req.headers]
Benjamin Peterson577473f2010-01-19 00:09:57 +00001031 self.assertNotIn("content-length", headers)
1032 self.assertNotIn("content-type", headers)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001033
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001034 self.assertEqual(o.req.headers["Nonsense"],
1035 "viking=withhold")
Benjamin Peterson577473f2010-01-19 00:09:57 +00001036 self.assertNotIn("Spam", o.req.headers)
1037 self.assertNotIn("Spam", o.req.unredirected_hdrs)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001038
1039 # loop detection
1040 req = Request(from_url)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001041 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001042 def redirect(h, req, url=to_url):
1043 h.http_error_302(req, MockFile(), 302, "Blah",
1044 MockHeaders({"location": url}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001045 # Note that the *original* request shares the same record of
1046 # redirections with the sub-requests caused by the redirections.
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001047
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001048 # detect infinite loop redirect of a URL to itself
1049 req = Request(from_url, origin_req_host="example.com")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001050 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001051 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001052 try:
1053 while 1:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001054 redirect(h, req, "http://example.com/")
1055 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001056 except urllib.error.HTTPError:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001057 # don't stop until max_repeats, because cookies may introduce state
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001058 self.assertEqual(count, urllib.request.HTTPRedirectHandler.max_repeats)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001059
1060 # detect endless non-repeating chain of redirects
1061 req = Request(from_url, origin_req_host="example.com")
1062 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001063 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001064 try:
1065 while 1:
1066 redirect(h, req, "http://example.com/%d" % count)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001067 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001068 except urllib.error.HTTPError:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001069 self.assertEqual(count,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001070 urllib.request.HTTPRedirectHandler.max_redirections)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001071
guido@google.coma119df92011-03-29 11:41:02 -07001072
1073 def test_invalid_redirect(self):
1074 from_url = "http://example.com/a.html"
1075 valid_schemes = ['http','https','ftp']
1076 invalid_schemes = ['file','imap','ldap']
1077 schemeless_url = "example.com/b.html"
1078 h = urllib.request.HTTPRedirectHandler()
1079 o = h.parent = MockOpener()
1080 req = Request(from_url)
1081 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1082
1083 for scheme in invalid_schemes:
1084 invalid_url = scheme + '://' + schemeless_url
1085 self.assertRaises(urllib.error.HTTPError, h.http_error_302,
1086 req, MockFile(), 302, "Security Loophole",
1087 MockHeaders({"location": invalid_url}))
1088
1089 for scheme in valid_schemes:
1090 valid_url = scheme + '://' + schemeless_url
1091 h.http_error_302(req, MockFile(), 302, "That's fine",
1092 MockHeaders({"location": valid_url}))
1093 self.assertEqual(o.req.get_full_url(), valid_url)
1094
Senthil Kumaran6497aa32012-01-04 13:46:59 +08001095 def test_relative_redirect(self):
1096 from_url = "http://example.com/a.html"
1097 relative_url = "/b.html"
1098 h = urllib.request.HTTPRedirectHandler()
1099 o = h.parent = MockOpener()
1100 req = Request(from_url)
1101 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1102
1103 valid_url = urllib.parse.urljoin(from_url,relative_url)
1104 h.http_error_302(req, MockFile(), 302, "That's fine",
1105 MockHeaders({"location": valid_url}))
1106 self.assertEqual(o.req.get_full_url(), valid_url)
1107
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001108 def test_cookie_redirect(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001109 # cookies shouldn't leak into redirected requests
Georg Brandl24420152008-05-26 16:32:26 +00001110 from http.cookiejar import CookieJar
1111 from test.test_http_cookiejar import interact_netscape
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001112
1113 cj = CookieJar()
1114 interact_netscape(cj, "http://www.example.com/", "spam=eggs")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001115 hh = MockHTTPHandler(302, "Location: http://www.cracker.com/\r\n\r\n")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001116 hdeh = urllib.request.HTTPDefaultErrorHandler()
1117 hrh = urllib.request.HTTPRedirectHandler()
1118 cp = urllib.request.HTTPCookieProcessor(cj)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001119 o = build_test_opener(hh, hdeh, hrh, cp)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001120 o.open("http://www.example.com/")
Florent Xicluna419e3842010-08-08 16:16:07 +00001121 self.assertFalse(hh.req.has_header("Cookie"))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001122
Senthil Kumaran26430412011-04-13 07:01:19 +08001123 def test_redirect_fragment(self):
1124 redirected_url = 'http://www.example.com/index.html#OK\r\n\r\n'
1125 hh = MockHTTPHandler(302, 'Location: ' + redirected_url)
1126 hdeh = urllib.request.HTTPDefaultErrorHandler()
1127 hrh = urllib.request.HTTPRedirectHandler()
1128 o = build_test_opener(hh, hdeh, hrh)
1129 fp = o.open('http://www.example.com')
1130 self.assertEqual(fp.geturl(), redirected_url.strip())
1131
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001132 def test_proxy(self):
1133 o = OpenerDirector()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001134 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001135 o.add_handler(ph)
1136 meth_spec = [
1137 [("http_open", "return response")]
1138 ]
1139 handlers = add_ordered_mock_handlers(o, meth_spec)
1140
1141 req = Request("http://acme.example.com/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001142 self.assertEqual(req.host, "acme.example.com")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001143 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001144 self.assertEqual(req.host, "proxy.example.com:3128")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001145
1146 self.assertEqual([(handlers[0], "http_open")],
1147 [tup[0:2] for tup in o.calls])
1148
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001149 def test_proxy_no_proxy(self):
1150 os.environ['no_proxy'] = 'python.org'
1151 o = OpenerDirector()
1152 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1153 o.add_handler(ph)
1154 req = Request("http://www.perl.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001155 self.assertEqual(req.host, "www.perl.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001156 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001157 self.assertEqual(req.host, "proxy.example.com")
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001158 req = Request("http://www.python.org")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001159 self.assertEqual(req.host, "www.python.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001160 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001161 self.assertEqual(req.host, "www.python.org")
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001162 del os.environ['no_proxy']
1163
Ronald Oussorene72e1612011-03-14 18:15:25 -04001164 def test_proxy_no_proxy_all(self):
1165 os.environ['no_proxy'] = '*'
1166 o = OpenerDirector()
1167 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1168 o.add_handler(ph)
1169 req = Request("http://www.python.org")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001170 self.assertEqual(req.host, "www.python.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001171 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001172 self.assertEqual(req.host, "www.python.org")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001173 del os.environ['no_proxy']
1174
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001175
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001176 def test_proxy_https(self):
1177 o = OpenerDirector()
1178 ph = urllib.request.ProxyHandler(dict(https="proxy.example.com:3128"))
1179 o.add_handler(ph)
1180 meth_spec = [
1181 [("https_open", "return response")]
1182 ]
1183 handlers = add_ordered_mock_handlers(o, meth_spec)
1184
1185 req = Request("https://www.example.com/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001186 self.assertEqual(req.host, "www.example.com")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001187 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001188 self.assertEqual(req.host, "proxy.example.com:3128")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001189 self.assertEqual([(handlers[0], "https_open")],
1190 [tup[0:2] for tup in o.calls])
1191
Senthil Kumaran47fff872009-12-20 07:10:31 +00001192 def test_proxy_https_proxy_authorization(self):
1193 o = OpenerDirector()
1194 ph = urllib.request.ProxyHandler(dict(https='proxy.example.com:3128'))
1195 o.add_handler(ph)
1196 https_handler = MockHTTPSHandler()
1197 o.add_handler(https_handler)
1198 req = Request("https://www.example.com/")
1199 req.add_header("Proxy-Authorization","FooBar")
1200 req.add_header("User-Agent","Grail")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001201 self.assertEqual(req.host, "www.example.com")
Senthil Kumaran47fff872009-12-20 07:10:31 +00001202 self.assertIsNone(req._tunnel_host)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001203 o.open(req)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001204 # Verify Proxy-Authorization gets tunneled to request.
1205 # httpsconn req_headers do not have the Proxy-Authorization header but
1206 # the req will have.
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001207 self.assertNotIn(("Proxy-Authorization","FooBar"),
Senthil Kumaran47fff872009-12-20 07:10:31 +00001208 https_handler.httpconn.req_headers)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001209 self.assertIn(("User-Agent","Grail"),
1210 https_handler.httpconn.req_headers)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001211 self.assertIsNotNone(req._tunnel_host)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001212 self.assertEqual(req.host, "proxy.example.com:3128")
Senthil Kumaran47fff872009-12-20 07:10:31 +00001213 self.assertEqual(req.get_header("Proxy-authorization"),"FooBar")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001214
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001215 # TODO: This should be only for OSX
1216 @unittest.skipUnless(sys.platform == 'darwin', "only relevant for OSX")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001217 def test_osx_proxy_bypass(self):
1218 bypass = {
1219 'exclude_simple': False,
1220 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.10',
1221 '10.0/16']
1222 }
1223 # Check hosts that should trigger the proxy bypass
1224 for host in ('foo.bar', 'www.bar.com', '127.0.0.1', '10.10.0.1',
1225 '10.0.0.1'):
1226 self.assertTrue(_proxy_bypass_macosx_sysconf(host, bypass),
1227 'expected bypass of %s to be True' % host)
1228 # Check hosts that should not trigger the proxy bypass
1229 for host in ('abc.foo.bar', 'bar.com', '127.0.0.2', '10.11.0.1', 'test'):
1230 self.assertFalse(_proxy_bypass_macosx_sysconf(host, bypass),
1231 'expected bypass of %s to be False' % host)
1232
1233 # Check the exclude_simple flag
1234 bypass = {'exclude_simple': True, 'exceptions': []}
1235 self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass))
1236
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001237 def test_basic_auth(self, quote_char='"'):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001238 opener = OpenerDirector()
1239 password_manager = MockPasswordManager()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001240 auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001241 realm = "ACME Widget Store"
1242 http_handler = MockHTTPHandler(
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001243 401, 'WWW-Authenticate: Basic realm=%s%s%s\r\n\r\n' %
1244 (quote_char, realm, quote_char) )
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001245 opener.add_handler(auth_handler)
1246 opener.add_handler(http_handler)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001247 self._test_basic_auth(opener, auth_handler, "Authorization",
1248 realm, http_handler, password_manager,
1249 "http://acme.example.com/protected",
1250 "http://acme.example.com/protected",
1251 )
1252
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001253 def test_basic_auth_with_single_quoted_realm(self):
1254 self.test_basic_auth(quote_char="'")
1255
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +08001256 def test_basic_auth_with_unquoted_realm(self):
1257 opener = OpenerDirector()
1258 password_manager = MockPasswordManager()
1259 auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
1260 realm = "ACME Widget Store"
1261 http_handler = MockHTTPHandler(
1262 401, 'WWW-Authenticate: Basic realm=%s\r\n\r\n' % realm)
1263 opener.add_handler(auth_handler)
1264 opener.add_handler(http_handler)
Senthil Kumaran0ea91cb2012-05-15 23:59:42 +08001265 with self.assertWarns(UserWarning):
1266 self._test_basic_auth(opener, auth_handler, "Authorization",
1267 realm, http_handler, password_manager,
1268 "http://acme.example.com/protected",
1269 "http://acme.example.com/protected",
1270 )
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +08001271
Thomas Wouters477c8d52006-05-27 19:21:47 +00001272 def test_proxy_basic_auth(self):
1273 opener = OpenerDirector()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001274 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001275 opener.add_handler(ph)
1276 password_manager = MockPasswordManager()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001277 auth_handler = urllib.request.ProxyBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001278 realm = "ACME Networks"
1279 http_handler = MockHTTPHandler(
1280 407, 'Proxy-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001281 opener.add_handler(auth_handler)
1282 opener.add_handler(http_handler)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001283 self._test_basic_auth(opener, auth_handler, "Proxy-authorization",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001284 realm, http_handler, password_manager,
1285 "http://acme.example.com:3128/protected",
1286 "proxy.example.com:3128",
1287 )
1288
1289 def test_basic_and_digest_auth_handlers(self):
Andrew Svetlov7bd61cb2012-12-19 22:49:25 +02001290 # HTTPDigestAuthHandler raised an exception if it couldn't handle a 40*
Thomas Wouters477c8d52006-05-27 19:21:47 +00001291 # response (http://python.org/sf/1479302), where it should instead
1292 # return None to allow another handler (especially
1293 # HTTPBasicAuthHandler) to handle the response.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001294
1295 # Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must
1296 # try digest first (since it's the strongest auth scheme), so we record
1297 # order of calls here to check digest comes first:
1298 class RecordingOpenerDirector(OpenerDirector):
1299 def __init__(self):
1300 OpenerDirector.__init__(self)
1301 self.recorded = []
1302 def record(self, info):
1303 self.recorded.append(info)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001304 class TestDigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001305 def http_error_401(self, *args, **kwds):
1306 self.parent.record("digest")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001307 urllib.request.HTTPDigestAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001308 *args, **kwds)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001309 class TestBasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001310 def http_error_401(self, *args, **kwds):
1311 self.parent.record("basic")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001312 urllib.request.HTTPBasicAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001313 *args, **kwds)
1314
1315 opener = RecordingOpenerDirector()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001316 password_manager = MockPasswordManager()
1317 digest_handler = TestDigestAuthHandler(password_manager)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001318 basic_handler = TestBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001319 realm = "ACME Networks"
1320 http_handler = MockHTTPHandler(
1321 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001322 opener.add_handler(basic_handler)
1323 opener.add_handler(digest_handler)
1324 opener.add_handler(http_handler)
1325
1326 # check basic auth isn't blocked by digest handler failing
Thomas Wouters477c8d52006-05-27 19:21:47 +00001327 self._test_basic_auth(opener, basic_handler, "Authorization",
1328 realm, http_handler, password_manager,
1329 "http://acme.example.com/protected",
1330 "http://acme.example.com/protected",
1331 )
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001332 # check digest was tried before basic (twice, because
1333 # _test_basic_auth called .open() twice)
1334 self.assertEqual(opener.recorded, ["digest", "basic"]*2)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001335
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001336 def test_unsupported_auth_digest_handler(self):
1337 opener = OpenerDirector()
1338 # While using DigestAuthHandler
1339 digest_auth_handler = urllib.request.HTTPDigestAuthHandler(None)
1340 http_handler = MockHTTPHandler(
1341 401, 'WWW-Authenticate: Kerberos\r\n\r\n')
1342 opener.add_handler(digest_auth_handler)
1343 opener.add_handler(http_handler)
1344 self.assertRaises(ValueError,opener.open,"http://www.example.com")
1345
1346 def test_unsupported_auth_basic_handler(self):
1347 # While using BasicAuthHandler
1348 opener = OpenerDirector()
1349 basic_auth_handler = urllib.request.HTTPBasicAuthHandler(None)
1350 http_handler = MockHTTPHandler(
1351 401, 'WWW-Authenticate: NTLM\r\n\r\n')
1352 opener.add_handler(basic_auth_handler)
1353 opener.add_handler(http_handler)
1354 self.assertRaises(ValueError,opener.open,"http://www.example.com")
1355
Thomas Wouters477c8d52006-05-27 19:21:47 +00001356 def _test_basic_auth(self, opener, auth_handler, auth_header,
1357 realm, http_handler, password_manager,
1358 request_url, protected_url):
Christian Heimes05e8be12008-02-23 18:30:17 +00001359 import base64
Thomas Wouters477c8d52006-05-27 19:21:47 +00001360 user, password = "wile", "coyote"
Thomas Wouters477c8d52006-05-27 19:21:47 +00001361
1362 # .add_password() fed through to password manager
1363 auth_handler.add_password(realm, request_url, user, password)
1364 self.assertEqual(realm, password_manager.realm)
1365 self.assertEqual(request_url, password_manager.url)
1366 self.assertEqual(user, password_manager.user)
1367 self.assertEqual(password, password_manager.password)
1368
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001369 opener.open(request_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001370
1371 # should have asked the password manager for the username/password
1372 self.assertEqual(password_manager.target_realm, realm)
1373 self.assertEqual(password_manager.target_url, protected_url)
1374
1375 # expect one request without authorization, then one with
1376 self.assertEqual(len(http_handler.requests), 2)
1377 self.assertFalse(http_handler.requests[0].has_header(auth_header))
Guido van Rossum98b349f2007-08-27 21:47:52 +00001378 userpass = bytes('%s:%s' % (user, password), "ascii")
Guido van Rossum98297ee2007-11-06 21:34:58 +00001379 auth_hdr_value = ('Basic ' +
Georg Brandl706824f2009-06-04 09:42:55 +00001380 base64.encodebytes(userpass).strip().decode())
Thomas Wouters477c8d52006-05-27 19:21:47 +00001381 self.assertEqual(http_handler.requests[1].get_header(auth_header),
1382 auth_hdr_value)
Senthil Kumaranca2fc9e2010-02-24 16:53:16 +00001383 self.assertEqual(http_handler.requests[1].unredirected_hdrs[auth_header],
1384 auth_hdr_value)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001385 # if the password manager can't find a password, the handler won't
1386 # handle the HTTP auth error
1387 password_manager.user = password_manager.password = None
1388 http_handler.reset()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001389 opener.open(request_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001390 self.assertEqual(len(http_handler.requests), 1)
1391 self.assertFalse(http_handler.requests[0].has_header(auth_header))
1392
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001393
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001394class MiscTests(unittest.TestCase):
1395
Senthil Kumarane9853da2013-03-19 12:07:43 -07001396 def opener_has_handler(self, opener, handler_class):
1397 self.assertTrue(any(h.__class__ == handler_class
1398 for h in opener.handlers))
1399
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001400 def test_build_opener(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001401 class MyHTTPHandler(urllib.request.HTTPHandler): pass
1402 class FooHandler(urllib.request.BaseHandler):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001403 def foo_open(self): pass
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001404 class BarHandler(urllib.request.BaseHandler):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001405 def bar_open(self): pass
1406
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001407 build_opener = urllib.request.build_opener
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001408
1409 o = build_opener(FooHandler, BarHandler)
1410 self.opener_has_handler(o, FooHandler)
1411 self.opener_has_handler(o, BarHandler)
1412
1413 # can take a mix of classes and instances
1414 o = build_opener(FooHandler, BarHandler())
1415 self.opener_has_handler(o, FooHandler)
1416 self.opener_has_handler(o, BarHandler)
1417
1418 # subclasses of default handlers override default handlers
1419 o = build_opener(MyHTTPHandler)
1420 self.opener_has_handler(o, MyHTTPHandler)
1421
1422 # a particular case of overriding: default handlers can be passed
1423 # in explicitly
1424 o = build_opener()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001425 self.opener_has_handler(o, urllib.request.HTTPHandler)
1426 o = build_opener(urllib.request.HTTPHandler)
1427 self.opener_has_handler(o, urllib.request.HTTPHandler)
1428 o = build_opener(urllib.request.HTTPHandler())
1429 self.opener_has_handler(o, urllib.request.HTTPHandler)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001430
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001431 # Issue2670: multiple handlers sharing the same base class
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001432 class MyOtherHTTPHandler(urllib.request.HTTPHandler): pass
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001433 o = build_opener(MyHTTPHandler, MyOtherHTTPHandler)
1434 self.opener_has_handler(o, MyHTTPHandler)
1435 self.opener_has_handler(o, MyOtherHTTPHandler)
1436
Brett Cannon80512de2013-01-25 22:27:21 -05001437 @unittest.skipUnless(support.is_resource_enabled('network'),
1438 'test requires network access')
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001439 def test_issue16464(self):
1440 opener = urllib.request.build_opener()
1441 request = urllib.request.Request("http://www.python.org/~jeremy/")
1442 self.assertEqual(None, request.data)
1443
1444 opener.open(request, "1".encode("us-ascii"))
1445 self.assertEqual(b"1", request.data)
1446 self.assertEqual("1", request.get_header("Content-length"))
1447
1448 opener.open(request, "1234567890".encode("us-ascii"))
1449 self.assertEqual(b"1234567890", request.data)
1450 self.assertEqual("10", request.get_header("Content-length"))
1451
Senthil Kumarane9853da2013-03-19 12:07:43 -07001452 def test_HTTPError_interface(self):
1453 """
1454 Issue 13211 reveals that HTTPError didn't implement the URLError
1455 interface even though HTTPError is a subclass of URLError.
Senthil Kumarane9853da2013-03-19 12:07:43 -07001456 """
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001457 msg = 'something bad happened'
1458 url = code = fp = None
1459 hdrs = 'Content-Length: 42'
1460 err = urllib.error.HTTPError(url, code, msg, hdrs, fp)
1461 self.assertTrue(hasattr(err, 'reason'))
1462 self.assertEqual(err.reason, 'something bad happened')
1463 self.assertTrue(hasattr(err, 'headers'))
1464 self.assertEqual(err.headers, 'Content-Length: 42')
1465 expected_errmsg = 'HTTP Error %s: %s' % (err.code, err.msg)
1466 self.assertEqual(str(err), expected_errmsg)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001467
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001468class RequestTests(unittest.TestCase):
Jason R. Coombs4a652422013-09-08 13:03:40 -04001469 class PutRequest(Request):
1470 method='PUT'
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001471
1472 def setUp(self):
1473 self.get = Request("http://www.python.org/~jeremy/")
1474 self.post = Request("http://www.python.org/~jeremy/",
1475 "data",
1476 headers={"X-Test": "test"})
Jason R. Coombs4a652422013-09-08 13:03:40 -04001477 self.head = Request("http://www.python.org/~jeremy/", method='HEAD')
1478 self.put = self.PutRequest("http://www.python.org/~jeremy/")
1479 self.force_post = self.PutRequest("http://www.python.org/~jeremy/",
1480 method="POST")
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001481
1482 def test_method(self):
1483 self.assertEqual("POST", self.post.get_method())
1484 self.assertEqual("GET", self.get.get_method())
Senthil Kumaran0b5463f2013-09-09 23:13:06 -07001485 self.assertEqual("HEAD", self.head.get_method())
Jason R. Coombs4a652422013-09-08 13:03:40 -04001486 self.assertEqual("PUT", self.put.get_method())
1487 self.assertEqual("POST", self.force_post.get_method())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001488
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001489 def test_data(self):
1490 self.assertFalse(self.get.data)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001491 self.assertEqual("GET", self.get.get_method())
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001492 self.get.data = "spam"
1493 self.assertTrue(self.get.data)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001494 self.assertEqual("POST", self.get.get_method())
1495
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001496 # issue 16464
1497 # if we change data we need to remove content-length header
1498 # (cause it's most probably calculated for previous value)
1499 def test_setting_data_should_remove_content_length(self):
R David Murray9cc7d452013-03-20 00:10:51 -04001500 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001501 self.get.add_unredirected_header("Content-length", 42)
1502 self.assertEqual(42, self.get.unredirected_hdrs["Content-length"])
1503 self.get.data = "spam"
R David Murray9cc7d452013-03-20 00:10:51 -04001504 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
1505
1506 # issue 17485 same for deleting data.
1507 def test_deleting_data_should_remove_content_length(self):
1508 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
1509 self.get.data = 'foo'
1510 self.get.add_unredirected_header("Content-length", 3)
1511 self.assertEqual(3, self.get.unredirected_hdrs["Content-length"])
1512 del self.get.data
1513 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001514
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001515 def test_get_full_url(self):
1516 self.assertEqual("http://www.python.org/~jeremy/",
1517 self.get.get_full_url())
1518
1519 def test_selector(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001520 self.assertEqual("/~jeremy/", self.get.selector)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001521 req = Request("http://www.python.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001522 self.assertEqual("/", req.selector)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001523
1524 def test_get_type(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001525 self.assertEqual("http", self.get.type)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001526
1527 def test_get_host(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001528 self.assertEqual("www.python.org", self.get.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001529
1530 def test_get_host_unquote(self):
1531 req = Request("http://www.%70ython.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001532 self.assertEqual("www.python.org", req.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001533
1534 def test_proxy(self):
Florent Xicluna419e3842010-08-08 16:16:07 +00001535 self.assertFalse(self.get.has_proxy())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001536 self.get.set_proxy("www.perl.org", "http")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001537 self.assertTrue(self.get.has_proxy())
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001538 self.assertEqual("www.python.org", self.get.origin_req_host)
1539 self.assertEqual("www.perl.org", self.get.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001540
Senthil Kumarand95cc752010-08-08 11:27:53 +00001541 def test_wrapped_url(self):
1542 req = Request("<URL:http://www.python.org>")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001543 self.assertEqual("www.python.org", req.host)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001544
Senthil Kumaran26430412011-04-13 07:01:19 +08001545 def test_url_fragment(self):
Senthil Kumarand95cc752010-08-08 11:27:53 +00001546 req = Request("http://www.python.org/?qs=query#fragment=true")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001547 self.assertEqual("/?qs=query", req.selector)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001548 req = Request("http://www.python.org/#fun=true")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001549 self.assertEqual("/", req.selector)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001550
Senthil Kumaran26430412011-04-13 07:01:19 +08001551 # Issue 11703: geturl() omits fragment in the original URL.
1552 url = 'http://docs.python.org/library/urllib2.html#OK'
1553 req = Request(url)
1554 self.assertEqual(req.get_full_url(), url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001555
Senthil Kumaran83070752013-05-24 09:14:12 -07001556 def test_url_fullurl_get_full_url(self):
1557 urls = ['http://docs.python.org',
1558 'http://docs.python.org/library/urllib2.html#OK',
1559 'http://www.python.org/?qs=query#fragment=true' ]
1560 for url in urls:
1561 req = Request(url)
1562 self.assertEqual(req.get_full_url(), req.full_url)
1563
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001564def test_main(verbose=None):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001565 from test import test_urllib2
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001566 support.run_doctest(test_urllib2, verbose)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001567 support.run_doctest(urllib.request, verbose)
Andrew M. Kuchlingbd3200f2004-06-29 13:15:46 +00001568 tests = (TrivialTests,
1569 OpenerDirectorTests,
1570 HandlerTests,
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001571 MiscTests,
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001572 RequestTests,
1573 RequestHdrsTests)
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001574 support.run_unittest(*tests)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001575
1576if __name__ == "__main__":
1577 test_main(verbose=True)