blob: b537fca3c31adf4bcf838a339a6fd6732551138e [file] [log] [blame]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002from test import support
Serhiy Storchakaf54c3502014-09-06 21:41:39 +03003from test import test_urllib
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00004
Christian Heimes05e8be12008-02-23 18:30:17 +00005import os
Guido van Rossum34d19282007-08-09 01:03:29 +00006import io
Georg Brandlf78e02b2008-06-10 17:40:04 +00007import socket
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00008import array
Senthil Kumaran4de00a22011-05-11 21:17:57 +08009import sys
Martin Panter3c0d0ba2016-08-24 06:33:33 +000010import tempfile
11import subprocess
Jeremy Hyltone3e61042001-05-09 15:50:25 +000012
Jeremy Hylton1afc1692008-06-18 20:49:58 +000013import urllib.request
Ronald Oussorene72e1612011-03-14 18:15:25 -040014# The proxy bypass method imported below has logic specific to the OSX
15# proxy config data structure but is testable on all platforms.
R David Murray4c7f9952015-04-16 16:36:18 -040016from urllib.request import (Request, OpenerDirector, HTTPBasicAuthHandler,
17 HTTPPasswordMgrWithPriorAuth, _parse_proxy,
Berker Peksage88dd1c2016-03-06 16:16:40 +020018 _proxy_bypass_macosx_sysconf,
19 AbstractDigestAuthHandler)
Senthil Kumaran83070752013-05-24 09:14:12 -070020from urllib.parse import urlparse
guido@google.coma119df92011-03-29 11:41:02 -070021import urllib.error
Serhiy Storchakaf54c3502014-09-06 21:41:39 +030022import http.client
Jeremy Hyltone3e61042001-05-09 15:50:25 +000023
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000024# XXX
25# Request
26# CacheFTPHandler (hard to write)
Thomas Wouters477c8d52006-05-27 19:21:47 +000027# parse_keqv_list, parse_http_list, HTTPDigestAuthHandler
Jeremy Hyltone3e61042001-05-09 15:50:25 +000028
Facundo Batista244afcf2015-04-22 18:35:54 -030029
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000030class TrivialTests(unittest.TestCase):
Senthil Kumaran6c5bd402011-11-01 23:20:31 +080031
32 def test___all__(self):
33 # Verify which names are exposed
34 for module in 'request', 'response', 'parse', 'error', 'robotparser':
35 context = {}
36 exec('from urllib.%s import *' % module, context)
37 del context['__builtins__']
Florent Xicluna3dbb1f12011-11-04 22:15:37 +010038 if module == 'request' and os.name == 'nt':
39 u, p = context.pop('url2pathname'), context.pop('pathname2url')
40 self.assertEqual(u.__module__, 'nturl2path')
41 self.assertEqual(p.__module__, 'nturl2path')
Senthil Kumaran6c5bd402011-11-01 23:20:31 +080042 for k, v in context.items():
43 self.assertEqual(v.__module__, 'urllib.%s' % module,
44 "%r is exposed in 'urllib.%s' but defined in %r" %
45 (k, module, v.__module__))
46
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000047 def test_trivial(self):
48 # A couple trivial tests
Guido van Rossume2ae77b2001-10-24 20:42:55 +000049
Jeremy Hylton1afc1692008-06-18 20:49:58 +000050 self.assertRaises(ValueError, urllib.request.urlopen, 'bogus url')
Tim Peters861adac2001-07-16 20:49:49 +000051
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000052 # XXX Name hacking to get this to work on Windows.
Serhiy Storchaka5106d042015-01-26 10:26:14 +020053 fname = os.path.abspath(urllib.request.__file__).replace(os.sep, '/')
Senthil Kumarand587e302010-01-10 17:45:52 +000054
Senthil Kumarand587e302010-01-10 17:45:52 +000055 if os.name == 'nt':
56 file_url = "file:///%s" % fname
57 else:
58 file_url = "file://%s" % fname
59
Jeremy Hylton1afc1692008-06-18 20:49:58 +000060 f = urllib.request.urlopen(file_url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000061
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -070062 f.read()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000063 f.close()
Tim Petersf5f32b42005-07-17 23:16:17 +000064
Georg Brandle1b13d22005-08-24 22:20:32 +000065 def test_parse_http_list(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +000066 tests = [
67 ('a,b,c', ['a', 'b', 'c']),
68 ('path"o,l"og"i"cal, example', ['path"o,l"og"i"cal', 'example']),
69 ('a, b, "c", "d", "e,f", g, h',
70 ['a', 'b', '"c"', '"d"', '"e,f"', 'g', 'h']),
71 ('a="b\\"c", d="e\\,f", g="h\\\\i"',
72 ['a="b"c"', 'd="e,f"', 'g="h\\i"'])]
Georg Brandle1b13d22005-08-24 22:20:32 +000073 for string, list in tests:
Florent Xicluna419e3842010-08-08 16:16:07 +000074 self.assertEqual(urllib.request.parse_http_list(string), list)
Georg Brandle1b13d22005-08-24 22:20:32 +000075
Senthil Kumaran843fae92013-03-19 13:43:42 -070076 def test_URLError_reasonstr(self):
77 err = urllib.error.URLError('reason')
78 self.assertIn(err.reason, str(err))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000079
Facundo Batista244afcf2015-04-22 18:35:54 -030080
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -070081class RequestHdrsTests(unittest.TestCase):
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000082
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -070083 def test_request_headers_dict(self):
84 """
85 The Request.headers dictionary is not a documented interface. It
86 should stay that way, because the complete set of headers are only
87 accessible through the .get_header(), .has_header(), .header_items()
88 interface. However, .headers pre-dates those methods, and so real code
89 will be using the dictionary.
90
91 The introduction in 2.4 of those methods was a mistake for the same
92 reason: code that previously saw all (urllib2 user)-provided headers in
93 .headers now sees only a subset.
94
95 """
96 url = "http://example.com"
97 self.assertEqual(Request(url,
98 headers={"Spam-eggs": "blah"}
99 ).headers["Spam-eggs"], "blah")
100 self.assertEqual(Request(url,
101 headers={"spam-EggS": "blah"}
102 ).headers["Spam-eggs"], "blah")
103
104 def test_request_headers_methods(self):
105 """
106 Note the case normalization of header names here, to
107 .capitalize()-case. This should be preserved for
108 backwards-compatibility. (In the HTTP case, normalization to
109 .title()-case is done by urllib2 before sending headers to
110 http.client).
111
112 Note that e.g. r.has_header("spam-EggS") is currently False, and
113 r.get_header("spam-EggS") returns None, but that could be changed in
114 future.
115
116 Method r.remove_header should remove items both from r.headers and
117 r.unredirected_hdrs dictionaries
118 """
119 url = "http://example.com"
120 req = Request(url, headers={"Spam-eggs": "blah"})
121 self.assertTrue(req.has_header("Spam-eggs"))
122 self.assertEqual(req.header_items(), [('Spam-eggs', 'blah')])
123
124 req.add_header("Foo-Bar", "baz")
125 self.assertEqual(sorted(req.header_items()),
126 [('Foo-bar', 'baz'), ('Spam-eggs', 'blah')])
127 self.assertFalse(req.has_header("Not-there"))
128 self.assertIsNone(req.get_header("Not-there"))
129 self.assertEqual(req.get_header("Not-there", "default"), "default")
130
131 req.remove_header("Spam-eggs")
132 self.assertFalse(req.has_header("Spam-eggs"))
133
134 req.add_unredirected_header("Unredirected-spam", "Eggs")
135 self.assertTrue(req.has_header("Unredirected-spam"))
136
137 req.remove_header("Unredirected-spam")
138 self.assertFalse(req.has_header("Unredirected-spam"))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000139
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700140 def test_password_manager(self):
141 mgr = urllib.request.HTTPPasswordMgr()
142 add = mgr.add_password
143 find_user_pass = mgr.find_user_password
144 add("Some Realm", "http://example.com/", "joe", "password")
145 add("Some Realm", "http://example.com/ni", "ni", "ni")
146 add("c", "http://example.com/foo", "foo", "ni")
147 add("c", "http://example.com/bar", "bar", "nini")
148 add("b", "http://example.com/", "first", "blah")
149 add("b", "http://example.com/", "second", "spam")
150 add("a", "http://example.com", "1", "a")
151 add("Some Realm", "http://c.example.com:3128", "3", "c")
152 add("Some Realm", "d.example.com", "4", "d")
153 add("Some Realm", "e.example.com:3128", "5", "e")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000154
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700155 self.assertEqual(find_user_pass("Some Realm", "example.com"),
156 ('joe', 'password'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000157
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700158 #self.assertEqual(find_user_pass("Some Realm", "http://example.com/ni"),
159 # ('ni', 'ni'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000160
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700161 self.assertEqual(find_user_pass("Some Realm", "http://example.com"),
162 ('joe', 'password'))
163 self.assertEqual(find_user_pass("Some Realm", "http://example.com/"),
164 ('joe', 'password'))
165 self.assertEqual(
166 find_user_pass("Some Realm", "http://example.com/spam"),
167 ('joe', 'password'))
168 self.assertEqual(
169 find_user_pass("Some Realm", "http://example.com/spam/spam"),
170 ('joe', 'password'))
171 self.assertEqual(find_user_pass("c", "http://example.com/foo"),
172 ('foo', 'ni'))
173 self.assertEqual(find_user_pass("c", "http://example.com/bar"),
174 ('bar', 'nini'))
175 self.assertEqual(find_user_pass("b", "http://example.com/"),
176 ('second', 'spam'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000177
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700178 # No special relationship between a.example.com and example.com:
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000179
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700180 self.assertEqual(find_user_pass("a", "http://example.com/"),
181 ('1', 'a'))
182 self.assertEqual(find_user_pass("a", "http://a.example.com/"),
183 (None, None))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000184
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700185 # Ports:
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000186
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700187 self.assertEqual(find_user_pass("Some Realm", "c.example.com"),
188 (None, None))
189 self.assertEqual(find_user_pass("Some Realm", "c.example.com:3128"),
190 ('3', 'c'))
191 self.assertEqual(
192 find_user_pass("Some Realm", "http://c.example.com:3128"),
193 ('3', 'c'))
194 self.assertEqual(find_user_pass("Some Realm", "d.example.com"),
195 ('4', 'd'))
196 self.assertEqual(find_user_pass("Some Realm", "e.example.com:3128"),
197 ('5', 'e'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000198
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700199 def test_password_manager_default_port(self):
200 """
201 The point to note here is that we can't guess the default port if
202 there's no scheme. This applies to both add_password and
203 find_user_password.
204 """
205 mgr = urllib.request.HTTPPasswordMgr()
206 add = mgr.add_password
207 find_user_pass = mgr.find_user_password
208 add("f", "http://g.example.com:80", "10", "j")
209 add("g", "http://h.example.com", "11", "k")
210 add("h", "i.example.com:80", "12", "l")
211 add("i", "j.example.com", "13", "m")
212 self.assertEqual(find_user_pass("f", "g.example.com:100"),
213 (None, None))
214 self.assertEqual(find_user_pass("f", "g.example.com:80"),
215 ('10', 'j'))
216 self.assertEqual(find_user_pass("f", "g.example.com"),
217 (None, None))
218 self.assertEqual(find_user_pass("f", "http://g.example.com:100"),
219 (None, None))
220 self.assertEqual(find_user_pass("f", "http://g.example.com:80"),
221 ('10', 'j'))
222 self.assertEqual(find_user_pass("f", "http://g.example.com"),
223 ('10', 'j'))
224 self.assertEqual(find_user_pass("g", "h.example.com"), ('11', 'k'))
225 self.assertEqual(find_user_pass("g", "h.example.com:80"), ('11', 'k'))
226 self.assertEqual(find_user_pass("g", "http://h.example.com:80"),
227 ('11', 'k'))
228 self.assertEqual(find_user_pass("h", "i.example.com"), (None, None))
229 self.assertEqual(find_user_pass("h", "i.example.com:80"), ('12', 'l'))
230 self.assertEqual(find_user_pass("h", "http://i.example.com:80"),
231 ('12', 'l'))
232 self.assertEqual(find_user_pass("i", "j.example.com"), ('13', 'm'))
233 self.assertEqual(find_user_pass("i", "j.example.com:80"),
234 (None, None))
235 self.assertEqual(find_user_pass("i", "http://j.example.com"),
236 ('13', 'm'))
237 self.assertEqual(find_user_pass("i", "http://j.example.com:80"),
238 (None, None))
Andrew Svetlovbff98fe2012-11-27 23:06:19 +0200239
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000240
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000241class MockOpener:
242 addheaders = []
Facundo Batista244afcf2015-04-22 18:35:54 -0300243
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000244 def open(self, req, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
245 self.req, self.data, self.timeout = req, data, timeout
Facundo Batista244afcf2015-04-22 18:35:54 -0300246
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000247 def error(self, proto, *args):
248 self.proto, self.args = proto, args
249
Facundo Batista244afcf2015-04-22 18:35:54 -0300250
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000251class MockFile:
Facundo Batista244afcf2015-04-22 18:35:54 -0300252 def read(self, count=None):
253 pass
254
255 def readline(self, count=None):
256 pass
257
258 def close(self):
259 pass
260
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000261
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000262class MockHeaders(dict):
263 def getheaders(self, name):
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000264 return list(self.values())
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000265
Facundo Batista244afcf2015-04-22 18:35:54 -0300266
Guido van Rossum34d19282007-08-09 01:03:29 +0000267class MockResponse(io.StringIO):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000268 def __init__(self, code, msg, headers, data, url=None):
Guido van Rossum34d19282007-08-09 01:03:29 +0000269 io.StringIO.__init__(self, data)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000270 self.code, self.msg, self.headers, self.url = code, msg, headers, url
Facundo Batista244afcf2015-04-22 18:35:54 -0300271
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000272 def info(self):
273 return self.headers
Facundo Batista244afcf2015-04-22 18:35:54 -0300274
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000275 def geturl(self):
276 return self.url
277
Facundo Batista244afcf2015-04-22 18:35:54 -0300278
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000279class MockCookieJar:
280 def add_cookie_header(self, request):
281 self.ach_req = request
Facundo Batista244afcf2015-04-22 18:35:54 -0300282
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000283 def extract_cookies(self, response, request):
284 self.ec_req, self.ec_r = request, response
285
Facundo Batista244afcf2015-04-22 18:35:54 -0300286
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000287class FakeMethod:
288 def __init__(self, meth_name, action, handle):
289 self.meth_name = meth_name
290 self.handle = handle
291 self.action = action
Facundo Batista244afcf2015-04-22 18:35:54 -0300292
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000293 def __call__(self, *args):
294 return self.handle(self.meth_name, self.action, *args)
295
Facundo Batista244afcf2015-04-22 18:35:54 -0300296
Senthil Kumaran47fff872009-12-20 07:10:31 +0000297class MockHTTPResponse(io.IOBase):
298 def __init__(self, fp, msg, status, reason):
299 self.fp = fp
300 self.msg = msg
301 self.status = status
302 self.reason = reason
303 self.code = 200
304
305 def read(self):
306 return ''
307
308 def info(self):
309 return {}
310
311 def geturl(self):
312 return self.url
313
314
315class MockHTTPClass:
316 def __init__(self):
317 self.level = 0
318 self.req_headers = []
319 self.data = None
320 self.raise_on_endheaders = False
Nadeem Vawdabd26b542012-10-21 17:37:43 +0200321 self.sock = None
Senthil Kumaran47fff872009-12-20 07:10:31 +0000322 self._tunnel_headers = {}
323
324 def __call__(self, host, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
325 self.host = host
326 self.timeout = timeout
327 return self
328
329 def set_debuglevel(self, level):
330 self.level = level
331
332 def set_tunnel(self, host, port=None, headers=None):
333 self._tunnel_host = host
334 self._tunnel_port = port
335 if headers:
336 self._tunnel_headers = headers
337 else:
338 self._tunnel_headers.clear()
339
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000340 def request(self, method, url, body=None, headers=None, *,
341 encode_chunked=False):
Senthil Kumaran47fff872009-12-20 07:10:31 +0000342 self.method = method
343 self.selector = url
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000344 if headers is not None:
345 self.req_headers += headers.items()
Senthil Kumaran47fff872009-12-20 07:10:31 +0000346 self.req_headers.sort()
347 if body:
348 self.data = body
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000349 self.encode_chunked = encode_chunked
Senthil Kumaran47fff872009-12-20 07:10:31 +0000350 if self.raise_on_endheaders:
Andrew Svetlov0832af62012-12-18 23:10:48 +0200351 raise OSError()
Facundo Batista244afcf2015-04-22 18:35:54 -0300352
Senthil Kumaran47fff872009-12-20 07:10:31 +0000353 def getresponse(self):
354 return MockHTTPResponse(MockFile(), {}, 200, "OK")
355
Victor Stinnera4c45d72011-06-17 14:01:18 +0200356 def close(self):
357 pass
358
Facundo Batista244afcf2015-04-22 18:35:54 -0300359
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000360class MockHandler:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000361 # useful for testing handler machinery
362 # see add_ordered_mock_handlers() docstring
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000363 handler_order = 500
Facundo Batista244afcf2015-04-22 18:35:54 -0300364
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000365 def __init__(self, methods):
366 self._define_methods(methods)
Facundo Batista244afcf2015-04-22 18:35:54 -0300367
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000368 def _define_methods(self, methods):
369 for spec in methods:
Facundo Batista244afcf2015-04-22 18:35:54 -0300370 if len(spec) == 2:
371 name, action = spec
372 else:
373 name, action = spec, None
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000374 meth = FakeMethod(name, action, self.handle)
375 setattr(self.__class__, name, meth)
Facundo Batista244afcf2015-04-22 18:35:54 -0300376
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000377 def handle(self, fn_name, action, *args, **kwds):
378 self.parent.calls.append((self, fn_name, args, kwds))
379 if action is None:
380 return None
381 elif action == "return self":
382 return self
383 elif action == "return response":
384 res = MockResponse(200, "OK", {}, "")
385 return res
386 elif action == "return request":
387 return Request("http://blah/")
388 elif action.startswith("error"):
389 code = action[action.rfind(" ")+1:]
390 try:
391 code = int(code)
392 except ValueError:
393 pass
394 res = MockResponse(200, "OK", {}, "")
395 return self.parent.error("http", args[0], res, code, "", {})
396 elif action == "raise":
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000397 raise urllib.error.URLError("blah")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000398 assert False
Facundo Batista244afcf2015-04-22 18:35:54 -0300399
400 def close(self):
401 pass
402
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000403 def add_parent(self, parent):
404 self.parent = parent
405 self.parent.calls = []
Facundo Batista244afcf2015-04-22 18:35:54 -0300406
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000407 def __lt__(self, other):
408 if not hasattr(other, "handler_order"):
409 # No handler_order, leave in original order. Yuck.
410 return True
411 return self.handler_order < other.handler_order
412
Facundo Batista244afcf2015-04-22 18:35:54 -0300413
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000414def add_ordered_mock_handlers(opener, meth_spec):
415 """Create MockHandlers and add them to an OpenerDirector.
416
417 meth_spec: list of lists of tuples and strings defining methods to define
418 on handlers. eg:
419
420 [["http_error", "ftp_open"], ["http_open"]]
421
422 defines methods .http_error() and .ftp_open() on one handler, and
423 .http_open() on another. These methods just record their arguments and
424 return None. Using a tuple instead of a string causes the method to
425 perform some action (see MockHandler.handle()), eg:
426
427 [["http_error"], [("http_open", "return request")]]
428
429 defines .http_error() on one handler (which simply returns None), and
430 .http_open() on another handler, which returns a Request object.
431
432 """
433 handlers = []
434 count = 0
435 for meths in meth_spec:
Facundo Batista244afcf2015-04-22 18:35:54 -0300436 class MockHandlerSubclass(MockHandler):
437 pass
438
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000439 h = MockHandlerSubclass(meths)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000440 h.handler_order += count
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000441 h.add_parent(opener)
442 count = count + 1
443 handlers.append(h)
444 opener.add_handler(h)
445 return handlers
446
Facundo Batista244afcf2015-04-22 18:35:54 -0300447
Thomas Wouters477c8d52006-05-27 19:21:47 +0000448def build_test_opener(*handler_instances):
449 opener = OpenerDirector()
450 for h in handler_instances:
451 opener.add_handler(h)
452 return opener
453
Facundo Batista244afcf2015-04-22 18:35:54 -0300454
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000455class MockHTTPHandler(urllib.request.BaseHandler):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000456 # useful for testing redirections and auth
457 # sends supplied headers and code as first response
458 # sends 200 OK as second response
459 def __init__(self, code, headers):
460 self.code = code
461 self.headers = headers
462 self.reset()
Facundo Batista244afcf2015-04-22 18:35:54 -0300463
Thomas Wouters477c8d52006-05-27 19:21:47 +0000464 def reset(self):
465 self._count = 0
466 self.requests = []
Facundo Batista244afcf2015-04-22 18:35:54 -0300467
Thomas Wouters477c8d52006-05-27 19:21:47 +0000468 def http_open(self, req):
Martin Panterce6e0682016-05-16 01:07:13 +0000469 import email, copy
Thomas Wouters477c8d52006-05-27 19:21:47 +0000470 self.requests.append(copy.deepcopy(req))
471 if self._count == 0:
472 self._count = self._count + 1
Georg Brandl24420152008-05-26 16:32:26 +0000473 name = http.client.responses[self.code]
Barry Warsaw820c1202008-06-12 04:06:45 +0000474 msg = email.message_from_string(self.headers)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000475 return self.parent.error(
476 "http", req, MockFile(), self.code, name, msg)
477 else:
478 self.req = req
Barry Warsaw820c1202008-06-12 04:06:45 +0000479 msg = email.message_from_string("\r\n\r\n")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000480 return MockResponse(200, "OK", msg, "", req.get_full_url())
481
Facundo Batista244afcf2015-04-22 18:35:54 -0300482
Senthil Kumaran47fff872009-12-20 07:10:31 +0000483class MockHTTPSHandler(urllib.request.AbstractHTTPHandler):
484 # Useful for testing the Proxy-Authorization request by verifying the
485 # properties of httpcon
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000486
Senthil Kumaran9642eed2016-05-13 01:32:42 -0700487 def __init__(self, debuglevel=0):
488 urllib.request.AbstractHTTPHandler.__init__(self, debuglevel=debuglevel)
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000489 self.httpconn = MockHTTPClass()
490
Senthil Kumaran47fff872009-12-20 07:10:31 +0000491 def https_open(self, req):
492 return self.do_open(self.httpconn, req)
493
R David Murray4c7f9952015-04-16 16:36:18 -0400494
495class MockHTTPHandlerCheckAuth(urllib.request.BaseHandler):
496 # useful for testing auth
497 # sends supplied code response
498 # checks if auth header is specified in request
499 def __init__(self, code):
500 self.code = code
501 self.has_auth_header = False
502
503 def reset(self):
504 self.has_auth_header = False
505
506 def http_open(self, req):
507 if req.has_header('Authorization'):
508 self.has_auth_header = True
509 name = http.client.responses[self.code]
510 return MockResponse(self.code, name, MockFile(), "", req.get_full_url())
511
512
Facundo Batista244afcf2015-04-22 18:35:54 -0300513
Thomas Wouters477c8d52006-05-27 19:21:47 +0000514class MockPasswordManager:
515 def add_password(self, realm, uri, user, password):
516 self.realm = realm
517 self.url = uri
518 self.user = user
519 self.password = password
Facundo Batista244afcf2015-04-22 18:35:54 -0300520
Thomas Wouters477c8d52006-05-27 19:21:47 +0000521 def find_user_password(self, realm, authuri):
522 self.target_realm = realm
523 self.target_url = authuri
524 return self.user, self.password
525
526
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000527class OpenerDirectorTests(unittest.TestCase):
528
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000529 def test_add_non_handler(self):
530 class NonHandler(object):
531 pass
532 self.assertRaises(TypeError,
533 OpenerDirector().add_handler, NonHandler())
534
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000535 def test_badly_named_methods(self):
536 # test work-around for three methods that accidentally follow the
537 # naming conventions for handler methods
538 # (*_open() / *_request() / *_response())
539
540 # These used to call the accidentally-named methods, causing a
541 # TypeError in real code; here, returning self from these mock
542 # methods would either cause no exception, or AttributeError.
543
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000544 from urllib.error import URLError
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000545
546 o = OpenerDirector()
547 meth_spec = [
548 [("do_open", "return self"), ("proxy_open", "return self")],
549 [("redirect_request", "return self")],
550 ]
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700551 add_ordered_mock_handlers(o, meth_spec)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000552 o.add_handler(urllib.request.UnknownHandler())
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000553 for scheme in "do", "proxy", "redirect":
554 self.assertRaises(URLError, o.open, scheme+"://example.com/")
555
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000556 def test_handled(self):
557 # handler returning non-None means no more handlers will be called
558 o = OpenerDirector()
559 meth_spec = [
560 ["http_open", "ftp_open", "http_error_302"],
561 ["ftp_open"],
562 [("http_open", "return self")],
563 [("http_open", "return self")],
564 ]
565 handlers = add_ordered_mock_handlers(o, meth_spec)
566
567 req = Request("http://example.com/")
568 r = o.open(req)
569 # Second .http_open() gets called, third doesn't, since second returned
570 # non-None. Handlers without .http_open() never get any methods called
571 # on them.
572 # In fact, second mock handler defining .http_open() returns self
573 # (instead of response), which becomes the OpenerDirector's return
574 # value.
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000575 self.assertEqual(r, handlers[2])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000576 calls = [(handlers[0], "http_open"), (handlers[2], "http_open")]
577 for expected, got in zip(calls, o.calls):
578 handler, name, args, kwds = got
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000579 self.assertEqual((handler, name), expected)
580 self.assertEqual(args, (req,))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000581
582 def test_handler_order(self):
583 o = OpenerDirector()
584 handlers = []
Facundo Batista244afcf2015-04-22 18:35:54 -0300585 for meths, handler_order in [([("http_open", "return self")], 500),
586 (["http_open"], 0)]:
587 class MockHandlerSubclass(MockHandler):
588 pass
589
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000590 h = MockHandlerSubclass(meths)
591 h.handler_order = handler_order
592 handlers.append(h)
593 o.add_handler(h)
594
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700595 o.open("http://example.com/")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000596 # handlers called in reverse order, thanks to their sort order
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000597 self.assertEqual(o.calls[0][0], handlers[1])
598 self.assertEqual(o.calls[1][0], handlers[0])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000599
600 def test_raise(self):
601 # raising URLError stops processing of request
602 o = OpenerDirector()
603 meth_spec = [
604 [("http_open", "raise")],
605 [("http_open", "return self")],
606 ]
607 handlers = add_ordered_mock_handlers(o, meth_spec)
608
609 req = Request("http://example.com/")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000610 self.assertRaises(urllib.error.URLError, o.open, req)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000611 self.assertEqual(o.calls, [(handlers[0], "http_open", (req,), {})])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000612
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000613 def test_http_error(self):
614 # XXX http_error_default
615 # http errors are a special case
616 o = OpenerDirector()
617 meth_spec = [
618 [("http_open", "error 302")],
619 [("http_error_400", "raise"), "http_open"],
620 [("http_error_302", "return response"), "http_error_303",
621 "http_error"],
622 [("http_error_302")],
623 ]
624 handlers = add_ordered_mock_handlers(o, meth_spec)
625
626 class Unknown:
Facundo Batista244afcf2015-04-22 18:35:54 -0300627 def __eq__(self, other):
628 return True
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000629
630 req = Request("http://example.com/")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700631 o.open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000632 assert len(o.calls) == 2
633 calls = [(handlers[0], "http_open", (req,)),
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000634 (handlers[2], "http_error_302",
635 (req, Unknown(), 302, "", {}))]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000636 for expected, got in zip(calls, o.calls):
637 handler, method_name, args = expected
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000638 self.assertEqual((handler, method_name), got[:2])
639 self.assertEqual(args, got[2])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000640
641 def test_processors(self):
642 # *_request / *_response methods get called appropriately
643 o = OpenerDirector()
644 meth_spec = [
645 [("http_request", "return request"),
646 ("http_response", "return response")],
647 [("http_request", "return request"),
648 ("http_response", "return response")],
649 ]
650 handlers = add_ordered_mock_handlers(o, meth_spec)
651
652 req = Request("http://example.com/")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700653 o.open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000654 # processor methods are called on *all* handlers that define them,
655 # not just the first handler that handles the request
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000656 calls = [
657 (handlers[0], "http_request"), (handlers[1], "http_request"),
658 (handlers[0], "http_response"), (handlers[1], "http_response")]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000659
660 for i, (handler, name, args, kwds) in enumerate(o.calls):
661 if i < 2:
662 # *_request
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000663 self.assertEqual((handler, name), calls[i])
664 self.assertEqual(len(args), 1)
Ezio Melottie9615932010-01-24 19:26:24 +0000665 self.assertIsInstance(args[0], Request)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000666 else:
667 # *_response
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000668 self.assertEqual((handler, name), calls[i])
669 self.assertEqual(len(args), 2)
Ezio Melottie9615932010-01-24 19:26:24 +0000670 self.assertIsInstance(args[0], Request)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000671 # response from opener.open is None, because there's no
672 # handler that defines http_open to handle it
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200673 if args[1] is not None:
674 self.assertIsInstance(args[1], MockResponse)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000675
Facundo Batista244afcf2015-04-22 18:35:54 -0300676
Tim Peters58eb11c2004-01-18 20:29:55 +0000677def sanepathname2url(path):
Victor Stinner6c6f8512010-08-07 10:09:35 +0000678 try:
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000679 path.encode("utf-8")
Victor Stinner6c6f8512010-08-07 10:09:35 +0000680 except UnicodeEncodeError:
681 raise unittest.SkipTest("path is not encodable to utf8")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000682 urlpath = urllib.request.pathname2url(path)
Tim Peters58eb11c2004-01-18 20:29:55 +0000683 if os.name == "nt" and urlpath.startswith("///"):
684 urlpath = urlpath[2:]
685 # XXX don't ask me about the mac...
686 return urlpath
687
Facundo Batista244afcf2015-04-22 18:35:54 -0300688
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000689class HandlerTests(unittest.TestCase):
690
691 def test_ftp(self):
692 class MockFTPWrapper:
Facundo Batista244afcf2015-04-22 18:35:54 -0300693 def __init__(self, data):
694 self.data = data
695
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000696 def retrfile(self, filename, filetype):
697 self.filename, self.filetype = filename, filetype
Guido van Rossum34d19282007-08-09 01:03:29 +0000698 return io.StringIO(self.data), len(self.data)
Facundo Batista244afcf2015-04-22 18:35:54 -0300699
700 def close(self):
701 pass
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000702
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000703 class NullFTPHandler(urllib.request.FTPHandler):
Facundo Batista244afcf2015-04-22 18:35:54 -0300704 def __init__(self, data):
705 self.data = data
706
Georg Brandlf78e02b2008-06-10 17:40:04 +0000707 def connect_ftp(self, user, passwd, host, port, dirs,
708 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000709 self.user, self.passwd = user, passwd
710 self.host, self.port = host, port
711 self.dirs = dirs
712 self.ftpwrapper = MockFTPWrapper(self.data)
713 return self.ftpwrapper
714
Georg Brandlf78e02b2008-06-10 17:40:04 +0000715 import ftplib
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000716 data = "rheum rhaponicum"
717 h = NullFTPHandler(data)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700718 h.parent = MockOpener()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000719
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000720 for url, host, port, user, passwd, type_, dirs, filename, mimetype in [
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000721 ("ftp://localhost/foo/bar/baz.html",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000722 "localhost", ftplib.FTP_PORT, "", "", "I",
723 ["foo", "bar"], "baz.html", "text/html"),
724 ("ftp://parrot@localhost/foo/bar/baz.html",
725 "localhost", ftplib.FTP_PORT, "parrot", "", "I",
726 ["foo", "bar"], "baz.html", "text/html"),
727 ("ftp://%25parrot@localhost/foo/bar/baz.html",
728 "localhost", ftplib.FTP_PORT, "%parrot", "", "I",
729 ["foo", "bar"], "baz.html", "text/html"),
730 ("ftp://%2542parrot@localhost/foo/bar/baz.html",
731 "localhost", ftplib.FTP_PORT, "%42parrot", "", "I",
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000732 ["foo", "bar"], "baz.html", "text/html"),
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000733 ("ftp://localhost:80/foo/bar/",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000734 "localhost", 80, "", "", "D",
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000735 ["foo", "bar"], "", None),
736 ("ftp://localhost/baz.gif;type=a",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000737 "localhost", ftplib.FTP_PORT, "", "", "A",
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000738 [], "baz.gif", None), # XXX really this should guess image/gif
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000739 ]:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000740 req = Request(url)
741 req.timeout = None
742 r = h.ftp_open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000743 # ftp authentication not yet implemented by FTPHandler
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000744 self.assertEqual(h.user, user)
745 self.assertEqual(h.passwd, passwd)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000746 self.assertEqual(h.host, socket.gethostbyname(host))
747 self.assertEqual(h.port, port)
748 self.assertEqual(h.dirs, dirs)
749 self.assertEqual(h.ftpwrapper.filename, filename)
750 self.assertEqual(h.ftpwrapper.filetype, type_)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000751 headers = r.info()
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000752 self.assertEqual(headers.get("Content-type"), mimetype)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000753 self.assertEqual(int(headers["Content-length"]), len(data))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000754
755 def test_file(self):
Senthil Kumaranbc07ac52014-07-22 00:15:20 -0700756 import email.utils
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000757 h = urllib.request.FileHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000758 o = h.parent = MockOpener()
759
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000760 TESTFN = support.TESTFN
Tim Peters58eb11c2004-01-18 20:29:55 +0000761 urlpath = sanepathname2url(os.path.abspath(TESTFN))
Guido van Rossum6a2ccd02007-07-16 20:51:57 +0000762 towrite = b"hello, world\n"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000763 urls = [
Tim Peters58eb11c2004-01-18 20:29:55 +0000764 "file://localhost%s" % urlpath,
765 "file://%s" % urlpath,
766 "file://%s%s" % (socket.gethostbyname('localhost'), urlpath),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000767 ]
768 try:
769 localaddr = socket.gethostbyname(socket.gethostname())
770 except socket.gaierror:
771 localaddr = ''
772 if localaddr:
773 urls.append("file://%s%s" % (localaddr, urlpath))
774
775 for url in urls:
Tim Peters58eb11c2004-01-18 20:29:55 +0000776 f = open(TESTFN, "wb")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000777 try:
778 try:
779 f.write(towrite)
780 finally:
781 f.close()
782
783 r = h.file_open(Request(url))
784 try:
785 data = r.read()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000786 headers = r.info()
Senthil Kumaran4fbed102010-05-08 03:29:09 +0000787 respurl = r.geturl()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000788 finally:
789 r.close()
Tim Peters58eb11c2004-01-18 20:29:55 +0000790 stats = os.stat(TESTFN)
Benjamin Petersona0c0a4a2008-06-12 22:15:50 +0000791 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000792 finally:
793 os.remove(TESTFN)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000794 self.assertEqual(data, towrite)
795 self.assertEqual(headers["Content-type"], "text/plain")
796 self.assertEqual(headers["Content-length"], "13")
Tim Peters58eb11c2004-01-18 20:29:55 +0000797 self.assertEqual(headers["Last-modified"], modified)
Senthil Kumaran4fbed102010-05-08 03:29:09 +0000798 self.assertEqual(respurl, url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000799
800 for url in [
Tim Peters58eb11c2004-01-18 20:29:55 +0000801 "file://localhost:80%s" % urlpath,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000802 "file:///file_does_not_exist.txt",
Senthil Kumaranbc07ac52014-07-22 00:15:20 -0700803 "file://not-a-local-host.com//dir/file.txt",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000804 "file://%s:80%s/%s" % (socket.gethostbyname('localhost'),
805 os.getcwd(), TESTFN),
806 "file://somerandomhost.ontheinternet.com%s/%s" %
807 (os.getcwd(), TESTFN),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000808 ]:
809 try:
Tim Peters58eb11c2004-01-18 20:29:55 +0000810 f = open(TESTFN, "wb")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000811 try:
812 f.write(towrite)
813 finally:
814 f.close()
815
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000816 self.assertRaises(urllib.error.URLError,
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000817 h.file_open, Request(url))
818 finally:
819 os.remove(TESTFN)
820
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000821 h = urllib.request.FileHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000822 o = h.parent = MockOpener()
823 # XXXX why does // mean ftp (and /// mean not ftp!), and where
824 # is file: scheme specified? I think this is really a bug, and
825 # what was intended was to distinguish between URLs like:
826 # file:/blah.txt (a file)
827 # file://localhost/blah.txt (a file)
828 # file:///blah.txt (a file)
829 # file://ftp.example.com/blah.txt (an ftp URL)
830 for url, ftp in [
Senthil Kumaran383c32d2010-10-14 11:57:35 +0000831 ("file://ftp.example.com//foo.txt", False),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000832 ("file://ftp.example.com///foo.txt", False),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000833 ("file://ftp.example.com/foo.txt", False),
Senthil Kumaran383c32d2010-10-14 11:57:35 +0000834 ("file://somehost//foo/something.txt", False),
Senthil Kumaran2ef16322010-07-11 03:12:43 +0000835 ("file://localhost//foo/something.txt", False),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000836 ]:
837 req = Request(url)
838 try:
839 h.file_open(req)
840 # XXXX remove OSError when bug fixed
Senthil Kumaran8d1f9352017-03-30 23:15:51 -0700841 except urllib.error.URLError:
Florent Xicluna419e3842010-08-08 16:16:07 +0000842 self.assertFalse(ftp)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000843 else:
Florent Xicluna419e3842010-08-08 16:16:07 +0000844 self.assertIs(o.req, req)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000845 self.assertEqual(req.type, "ftp")
Łukasz Langad7e81cc2011-01-09 18:18:53 +0000846 self.assertEqual(req.type == "ftp", ftp)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000847
848 def test_http(self):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000849
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000850 h = urllib.request.AbstractHTTPHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000851 o = h.parent = MockOpener()
852
853 url = "http://example.com/"
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000854 for method, data in [("GET", None), ("POST", b"blah")]:
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000855 req = Request(url, data, {"Foo": "bar"})
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000856 req.timeout = None
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000857 req.add_unredirected_header("Spam", "eggs")
858 http = MockHTTPClass()
859 r = h.do_open(http, req)
860
861 # result attributes
862 r.read; r.readline # wrapped MockFile methods
863 r.info; r.geturl # addinfourl methods
864 r.code, r.msg == 200, "OK" # added from MockHTTPClass.getreply()
865 hdrs = r.info()
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000866 hdrs.get; hdrs.__contains__ # r.info() gives dict from .getreply()
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000867 self.assertEqual(r.geturl(), url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000868
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000869 self.assertEqual(http.host, "example.com")
870 self.assertEqual(http.level, 0)
871 self.assertEqual(http.method, method)
872 self.assertEqual(http.selector, "/")
873 self.assertEqual(http.req_headers,
Jeremy Hyltonb3ee6f92004-02-24 19:40:35 +0000874 [("Connection", "close"),
875 ("Foo", "bar"), ("Spam", "eggs")])
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000876 self.assertEqual(http.data, data)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000877
Andrew Svetlov0832af62012-12-18 23:10:48 +0200878 # check OSError converted to URLError
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000879 http.raise_on_endheaders = True
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000880 self.assertRaises(urllib.error.URLError, h.do_open, http, req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000881
Senthil Kumaran29333122011-02-11 11:25:47 +0000882 # Check for TypeError on POST data which is str.
883 req = Request("http://example.com/","badpost")
884 self.assertRaises(TypeError, h.do_request_, req)
885
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000886 # check adding of standard headers
887 o.addheaders = [("Spam", "eggs")]
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000888 for data in b"", None: # POST, GET
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000889 req = Request("http://example.com/", data)
890 r = MockResponse(200, "OK", {}, "")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000891 newreq = h.do_request_(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000892 if data is None: # GET
Benjamin Peterson577473f2010-01-19 00:09:57 +0000893 self.assertNotIn("Content-length", req.unredirected_hdrs)
894 self.assertNotIn("Content-type", req.unredirected_hdrs)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000895 else: # POST
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000896 self.assertEqual(req.unredirected_hdrs["Content-length"], "0")
897 self.assertEqual(req.unredirected_hdrs["Content-type"],
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000898 "application/x-www-form-urlencoded")
899 # XXX the details of Host could be better tested
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000900 self.assertEqual(req.unredirected_hdrs["Host"], "example.com")
901 self.assertEqual(req.unredirected_hdrs["Spam"], "eggs")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000902
903 # don't clobber existing headers
904 req.add_unredirected_header("Content-length", "foo")
905 req.add_unredirected_header("Content-type", "bar")
906 req.add_unredirected_header("Host", "baz")
907 req.add_unredirected_header("Spam", "foo")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000908 newreq = h.do_request_(req)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000909 self.assertEqual(req.unredirected_hdrs["Content-length"], "foo")
910 self.assertEqual(req.unredirected_hdrs["Content-type"], "bar")
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000911 self.assertEqual(req.unredirected_hdrs["Host"], "baz")
912 self.assertEqual(req.unredirected_hdrs["Spam"], "foo")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000913
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000914 def test_http_body_file(self):
Martin Panteref91bb22016-08-27 01:39:26 +0000915 # A regular file - chunked encoding is used unless Content Length is
916 # already set.
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000917
918 h = urllib.request.AbstractHTTPHandler()
919 o = h.parent = MockOpener()
920
921 file_obj = tempfile.NamedTemporaryFile(mode='w+b', delete=False)
922 file_path = file_obj.name
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000923 file_obj.close()
Martin Panteref91bb22016-08-27 01:39:26 +0000924 self.addCleanup(os.unlink, file_path)
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000925
Martin Panteref91bb22016-08-27 01:39:26 +0000926 with open(file_path, "rb") as f:
927 req = Request("http://example.com/", f, {})
928 newreq = h.do_request_(req)
929 te = newreq.get_header('Transfer-encoding')
930 self.assertEqual(te, "chunked")
931 self.assertFalse(newreq.has_header('Content-length'))
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000932
Martin Panteref91bb22016-08-27 01:39:26 +0000933 with open(file_path, "rb") as f:
934 req = Request("http://example.com/", f, {"Content-Length": 30})
935 newreq = h.do_request_(req)
936 self.assertEqual(int(newreq.get_header('Content-length')), 30)
937 self.assertFalse(newreq.has_header("Transfer-encoding"))
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000938
939 def test_http_body_fileobj(self):
Martin Panteref91bb22016-08-27 01:39:26 +0000940 # A file object - chunked encoding is used
941 # unless Content Length is already set.
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000942 # (Note that there are some subtle differences to a regular
943 # file, that is why we are testing both cases.)
944
945 h = urllib.request.AbstractHTTPHandler()
946 o = h.parent = MockOpener()
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000947 file_obj = io.BytesIO()
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000948
Martin Panteref91bb22016-08-27 01:39:26 +0000949 req = Request("http://example.com/", file_obj, {})
950 newreq = h.do_request_(req)
951 self.assertEqual(newreq.get_header('Transfer-encoding'), 'chunked')
952 self.assertFalse(newreq.has_header('Content-length'))
953
954 headers = {"Content-Length": 30}
955 req = Request("http://example.com/", file_obj, headers)
956 newreq = h.do_request_(req)
957 self.assertEqual(int(newreq.get_header('Content-length')), 30)
958 self.assertFalse(newreq.has_header("Transfer-encoding"))
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000959
960 file_obj.close()
961
962 def test_http_body_pipe(self):
963 # A file reading from a pipe.
964 # A pipe cannot be seek'ed. There is no way to determine the
965 # content length up front. Thus, do_request_() should fall
966 # back to Transfer-encoding chunked.
967
968 h = urllib.request.AbstractHTTPHandler()
969 o = h.parent = MockOpener()
970
Martin Panteref91bb22016-08-27 01:39:26 +0000971 cmd = [sys.executable, "-c", r"pass"]
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000972 for headers in {}, {"Content-Length": 30}:
973 with subprocess.Popen(cmd, stdout=subprocess.PIPE) as proc:
974 req = Request("http://example.com/", proc.stdout, headers)
975 newreq = h.do_request_(req)
976 if not headers:
977 self.assertEqual(newreq.get_header('Content-length'), None)
978 self.assertEqual(newreq.get_header('Transfer-encoding'),
979 'chunked')
980 else:
981 self.assertEqual(int(newreq.get_header('Content-length')),
982 30)
983
984 def test_http_body_iterable(self):
985 # Generic iterable. There is no way to determine the content
986 # length up front. Fall back to Transfer-encoding chunked.
987
988 h = urllib.request.AbstractHTTPHandler()
989 o = h.parent = MockOpener()
990
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000991 def iterable_body():
992 yield b"one"
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000993
994 for headers in {}, {"Content-Length": 11}:
995 req = Request("http://example.com/", iterable_body(), headers)
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000996 newreq = h.do_request_(req)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000997 if not headers:
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000998 self.assertEqual(newreq.get_header('Content-length'), None)
999 self.assertEqual(newreq.get_header('Transfer-encoding'),
1000 'chunked')
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001001 else:
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001002 self.assertEqual(int(newreq.get_header('Content-length')), 11)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001003
Martin Panteref91bb22016-08-27 01:39:26 +00001004 def test_http_body_empty_seq(self):
1005 # Zero-length iterable body should be treated like any other iterable
1006 h = urllib.request.AbstractHTTPHandler()
1007 h.parent = MockOpener()
1008 req = h.do_request_(Request("http://example.com/", ()))
1009 self.assertEqual(req.get_header("Transfer-encoding"), "chunked")
1010 self.assertFalse(req.has_header("Content-length"))
1011
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001012 def test_http_body_array(self):
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001013 # array.array Iterable - Content Length is calculated
1014
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001015 h = urllib.request.AbstractHTTPHandler()
1016 o = h.parent = MockOpener()
1017
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001018 iterable_array = array.array("I",[1,2,3,4])
1019
1020 for headers in {}, {"Content-Length": 16}:
1021 req = Request("http://example.com/", iterable_array, headers)
1022 newreq = h.do_request_(req)
1023 self.assertEqual(int(newreq.get_header('Content-length')),16)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001024
Senthil Kumaran9642eed2016-05-13 01:32:42 -07001025 def test_http_handler_debuglevel(self):
1026 o = OpenerDirector()
1027 h = MockHTTPSHandler(debuglevel=1)
1028 o.add_handler(h)
1029 o.open("https://www.example.com")
1030 self.assertEqual(h._debuglevel, 1)
1031
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001032 def test_http_doubleslash(self):
1033 # Checks the presence of any unnecessary double slash in url does not
1034 # break anything. Previously, a double slash directly after the host
Ezio Melottie130a522011-10-19 10:58:56 +03001035 # could cause incorrect parsing.
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001036 h = urllib.request.AbstractHTTPHandler()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001037 h.parent = MockOpener()
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001038
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001039 data = b""
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001040 ds_urls = [
1041 "http://example.com/foo/bar/baz.html",
1042 "http://example.com//foo/bar/baz.html",
1043 "http://example.com/foo//bar/baz.html",
1044 "http://example.com/foo/bar//baz.html"
1045 ]
1046
1047 for ds_url in ds_urls:
1048 ds_req = Request(ds_url, data)
1049
1050 # Check whether host is determined correctly if there is no proxy
1051 np_ds_req = h.do_request_(ds_req)
Facundo Batista244afcf2015-04-22 18:35:54 -03001052 self.assertEqual(np_ds_req.unredirected_hdrs["Host"], "example.com")
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001053
1054 # Check whether host is determined correctly if there is a proxy
Facundo Batista244afcf2015-04-22 18:35:54 -03001055 ds_req.set_proxy("someproxy:3128", None)
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001056 p_ds_req = h.do_request_(ds_req)
Facundo Batista244afcf2015-04-22 18:35:54 -03001057 self.assertEqual(p_ds_req.unredirected_hdrs["Host"], "example.com")
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001058
Senthil Kumaran52380922013-04-25 05:45:48 -07001059 def test_full_url_setter(self):
1060 # Checks to ensure that components are set correctly after setting the
1061 # full_url of a Request object
1062
1063 urls = [
1064 'http://example.com?foo=bar#baz',
1065 'http://example.com?foo=bar&spam=eggs#bash',
1066 'http://example.com',
1067 ]
1068
1069 # testing a reusable request instance, but the url parameter is
1070 # required, so just use a dummy one to instantiate
1071 r = Request('http://example.com')
1072 for url in urls:
1073 r.full_url = url
Senthil Kumaran83070752013-05-24 09:14:12 -07001074 parsed = urlparse(url)
1075
Senthil Kumaran52380922013-04-25 05:45:48 -07001076 self.assertEqual(r.get_full_url(), url)
Senthil Kumaran83070752013-05-24 09:14:12 -07001077 # full_url setter uses splittag to split into components.
1078 # splittag sets the fragment as None while urlparse sets it to ''
1079 self.assertEqual(r.fragment or '', parsed.fragment)
1080 self.assertEqual(urlparse(r.get_full_url()).query, parsed.query)
Senthil Kumaran52380922013-04-25 05:45:48 -07001081
1082 def test_full_url_deleter(self):
1083 r = Request('http://www.example.com')
1084 del r.full_url
1085 self.assertIsNone(r.full_url)
1086 self.assertIsNone(r.fragment)
1087 self.assertEqual(r.selector, '')
1088
Senthil Kumaranc2958622010-11-22 04:48:26 +00001089 def test_fixpath_in_weirdurls(self):
1090 # Issue4493: urllib2 to supply '/' when to urls where path does not
1091 # start with'/'
1092
1093 h = urllib.request.AbstractHTTPHandler()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001094 h.parent = MockOpener()
Senthil Kumaranc2958622010-11-22 04:48:26 +00001095
1096 weird_url = 'http://www.python.org?getspam'
1097 req = Request(weird_url)
1098 newreq = h.do_request_(req)
Facundo Batista244afcf2015-04-22 18:35:54 -03001099 self.assertEqual(newreq.host, 'www.python.org')
1100 self.assertEqual(newreq.selector, '/?getspam')
Senthil Kumaranc2958622010-11-22 04:48:26 +00001101
1102 url_without_path = 'http://www.python.org'
1103 req = Request(url_without_path)
1104 newreq = h.do_request_(req)
Facundo Batista244afcf2015-04-22 18:35:54 -03001105 self.assertEqual(newreq.host, 'www.python.org')
1106 self.assertEqual(newreq.selector, '')
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001107
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001108 def test_errors(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001109 h = urllib.request.HTTPErrorProcessor()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001110 o = h.parent = MockOpener()
1111
1112 url = "http://example.com/"
1113 req = Request(url)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001114 # all 2xx are passed through
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001115 r = MockResponse(200, "OK", {}, "", url)
1116 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +00001117 self.assertIs(r, newr)
1118 self.assertFalse(hasattr(o, "proto")) # o.error not called
Guido van Rossumd8faa362007-04-27 19:54:29 +00001119 r = MockResponse(202, "Accepted", {}, "", url)
1120 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +00001121 self.assertIs(r, newr)
1122 self.assertFalse(hasattr(o, "proto")) # o.error not called
Guido van Rossumd8faa362007-04-27 19:54:29 +00001123 r = MockResponse(206, "Partial content", {}, "", url)
1124 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +00001125 self.assertIs(r, newr)
1126 self.assertFalse(hasattr(o, "proto")) # o.error not called
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001127 # anything else calls o.error (and MockOpener returns None, here)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001128 r = MockResponse(502, "Bad gateway", {}, "", url)
Florent Xicluna419e3842010-08-08 16:16:07 +00001129 self.assertIsNone(h.http_response(req, r))
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001130 self.assertEqual(o.proto, "http") # o.error called
Guido van Rossumd8faa362007-04-27 19:54:29 +00001131 self.assertEqual(o.args, (req, r, 502, "Bad gateway", {}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001132
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001133 def test_cookies(self):
1134 cj = MockCookieJar()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001135 h = urllib.request.HTTPCookieProcessor(cj)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001136 h.parent = MockOpener()
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001137
1138 req = Request("http://example.com/")
1139 r = MockResponse(200, "OK", {}, "")
1140 newreq = h.http_request(req)
Florent Xicluna419e3842010-08-08 16:16:07 +00001141 self.assertIs(cj.ach_req, req)
1142 self.assertIs(cj.ach_req, newreq)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001143 self.assertEqual(req.origin_req_host, "example.com")
1144 self.assertFalse(req.unverifiable)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001145 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +00001146 self.assertIs(cj.ec_req, req)
1147 self.assertIs(cj.ec_r, r)
1148 self.assertIs(r, newr)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001149
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001150 def test_redirect(self):
1151 from_url = "http://example.com/a.html"
1152 to_url = "http://example.com/b.html"
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001153 h = urllib.request.HTTPRedirectHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001154 o = h.parent = MockOpener()
1155
1156 # ordinary redirect behaviour
1157 for code in 301, 302, 303, 307:
1158 for data in None, "blah\nblah\n":
1159 method = getattr(h, "http_error_%s" % code)
1160 req = Request(from_url, data)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001161 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001162 req.add_header("Nonsense", "viking=withhold")
Christian Heimes77c02eb2008-02-09 02:18:51 +00001163 if data is not None:
1164 req.add_header("Content-Length", str(len(data)))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001165 req.add_unredirected_header("Spam", "spam")
1166 try:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001167 method(req, MockFile(), code, "Blah",
1168 MockHeaders({"location": to_url}))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001169 except urllib.error.HTTPError:
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001170 # 307 in response to POST requires user OK
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001171 self.assertEqual(code, 307)
1172 self.assertIsNotNone(data)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001173 self.assertEqual(o.req.get_full_url(), to_url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001174 try:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001175 self.assertEqual(o.req.get_method(), "GET")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001176 except AttributeError:
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001177 self.assertFalse(o.req.data)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001178
1179 # now it's a GET, there should not be headers regarding content
1180 # (possibly dragged from before being a POST)
1181 headers = [x.lower() for x in o.req.headers]
Benjamin Peterson577473f2010-01-19 00:09:57 +00001182 self.assertNotIn("content-length", headers)
1183 self.assertNotIn("content-type", headers)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001184
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001185 self.assertEqual(o.req.headers["Nonsense"],
1186 "viking=withhold")
Benjamin Peterson577473f2010-01-19 00:09:57 +00001187 self.assertNotIn("Spam", o.req.headers)
1188 self.assertNotIn("Spam", o.req.unredirected_hdrs)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001189
1190 # loop detection
1191 req = Request(from_url)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001192 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Facundo Batista244afcf2015-04-22 18:35:54 -03001193
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001194 def redirect(h, req, url=to_url):
1195 h.http_error_302(req, MockFile(), 302, "Blah",
1196 MockHeaders({"location": url}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001197 # Note that the *original* request shares the same record of
1198 # redirections with the sub-requests caused by the redirections.
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001199
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001200 # detect infinite loop redirect of a URL to itself
1201 req = Request(from_url, origin_req_host="example.com")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001202 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001203 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001204 try:
1205 while 1:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001206 redirect(h, req, "http://example.com/")
1207 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001208 except urllib.error.HTTPError:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001209 # don't stop until max_repeats, because cookies may introduce state
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001210 self.assertEqual(count, urllib.request.HTTPRedirectHandler.max_repeats)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001211
1212 # detect endless non-repeating chain of redirects
1213 req = Request(from_url, origin_req_host="example.com")
1214 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001215 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001216 try:
1217 while 1:
1218 redirect(h, req, "http://example.com/%d" % count)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001219 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001220 except urllib.error.HTTPError:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001221 self.assertEqual(count,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001222 urllib.request.HTTPRedirectHandler.max_redirections)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001223
guido@google.coma119df92011-03-29 11:41:02 -07001224 def test_invalid_redirect(self):
1225 from_url = "http://example.com/a.html"
1226 valid_schemes = ['http','https','ftp']
1227 invalid_schemes = ['file','imap','ldap']
1228 schemeless_url = "example.com/b.html"
1229 h = urllib.request.HTTPRedirectHandler()
1230 o = h.parent = MockOpener()
1231 req = Request(from_url)
1232 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1233
1234 for scheme in invalid_schemes:
1235 invalid_url = scheme + '://' + schemeless_url
1236 self.assertRaises(urllib.error.HTTPError, h.http_error_302,
1237 req, MockFile(), 302, "Security Loophole",
1238 MockHeaders({"location": invalid_url}))
1239
1240 for scheme in valid_schemes:
1241 valid_url = scheme + '://' + schemeless_url
1242 h.http_error_302(req, MockFile(), 302, "That's fine",
1243 MockHeaders({"location": valid_url}))
1244 self.assertEqual(o.req.get_full_url(), valid_url)
1245
Senthil Kumaran6497aa32012-01-04 13:46:59 +08001246 def test_relative_redirect(self):
1247 from_url = "http://example.com/a.html"
1248 relative_url = "/b.html"
1249 h = urllib.request.HTTPRedirectHandler()
1250 o = h.parent = MockOpener()
1251 req = Request(from_url)
1252 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1253
1254 valid_url = urllib.parse.urljoin(from_url,relative_url)
1255 h.http_error_302(req, MockFile(), 302, "That's fine",
1256 MockHeaders({"location": valid_url}))
1257 self.assertEqual(o.req.get_full_url(), valid_url)
1258
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001259 def test_cookie_redirect(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001260 # cookies shouldn't leak into redirected requests
Georg Brandl24420152008-05-26 16:32:26 +00001261 from http.cookiejar import CookieJar
1262 from test.test_http_cookiejar import interact_netscape
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001263
1264 cj = CookieJar()
1265 interact_netscape(cj, "http://www.example.com/", "spam=eggs")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001266 hh = MockHTTPHandler(302, "Location: http://www.cracker.com/\r\n\r\n")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001267 hdeh = urllib.request.HTTPDefaultErrorHandler()
1268 hrh = urllib.request.HTTPRedirectHandler()
1269 cp = urllib.request.HTTPCookieProcessor(cj)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001270 o = build_test_opener(hh, hdeh, hrh, cp)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001271 o.open("http://www.example.com/")
Florent Xicluna419e3842010-08-08 16:16:07 +00001272 self.assertFalse(hh.req.has_header("Cookie"))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001273
Senthil Kumaran26430412011-04-13 07:01:19 +08001274 def test_redirect_fragment(self):
1275 redirected_url = 'http://www.example.com/index.html#OK\r\n\r\n'
1276 hh = MockHTTPHandler(302, 'Location: ' + redirected_url)
1277 hdeh = urllib.request.HTTPDefaultErrorHandler()
1278 hrh = urllib.request.HTTPRedirectHandler()
1279 o = build_test_opener(hh, hdeh, hrh)
1280 fp = o.open('http://www.example.com')
1281 self.assertEqual(fp.geturl(), redirected_url.strip())
1282
Martin Panterce6e0682016-05-16 01:07:13 +00001283 def test_redirect_no_path(self):
1284 # Issue 14132: Relative redirect strips original path
1285 real_class = http.client.HTTPConnection
1286 response1 = b"HTTP/1.1 302 Found\r\nLocation: ?query\r\n\r\n"
1287 http.client.HTTPConnection = test_urllib.fakehttp(response1)
1288 self.addCleanup(setattr, http.client, "HTTPConnection", real_class)
1289 urls = iter(("/path", "/path?query"))
1290 def request(conn, method, url, *pos, **kw):
1291 self.assertEqual(url, next(urls))
1292 real_class.request(conn, method, url, *pos, **kw)
1293 # Change response for subsequent connection
1294 conn.__class__.fakedata = b"HTTP/1.1 200 OK\r\n\r\nHello!"
1295 http.client.HTTPConnection.request = request
1296 fp = urllib.request.urlopen("http://python.org/path")
1297 self.assertEqual(fp.geturl(), "http://python.org/path?query")
1298
Martin Pantere6f06092016-05-16 01:14:20 +00001299 def test_redirect_encoding(self):
1300 # Some characters in the redirect target may need special handling,
1301 # but most ASCII characters should be treated as already encoded
1302 class Handler(urllib.request.HTTPHandler):
1303 def http_open(self, req):
1304 result = self.do_open(self.connection, req)
1305 self.last_buf = self.connection.buf
1306 # Set up a normal response for the next request
1307 self.connection = test_urllib.fakehttp(
1308 b'HTTP/1.1 200 OK\r\n'
1309 b'Content-Length: 3\r\n'
1310 b'\r\n'
1311 b'123'
1312 )
1313 return result
1314 handler = Handler()
1315 opener = urllib.request.build_opener(handler)
1316 tests = (
1317 (b'/p\xC3\xA5-dansk/', b'/p%C3%A5-dansk/'),
1318 (b'/spaced%20path/', b'/spaced%20path/'),
1319 (b'/spaced path/', b'/spaced%20path/'),
1320 (b'/?p\xC3\xA5-dansk', b'/?p%C3%A5-dansk'),
1321 )
1322 for [location, result] in tests:
1323 with self.subTest(repr(location)):
1324 handler.connection = test_urllib.fakehttp(
1325 b'HTTP/1.1 302 Redirect\r\n'
1326 b'Location: ' + location + b'\r\n'
1327 b'\r\n'
1328 )
1329 response = opener.open('http://example.com/')
1330 expected = b'GET ' + result + b' '
1331 request = handler.last_buf
1332 self.assertTrue(request.startswith(expected), repr(request))
1333
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001334 def test_proxy(self):
1335 o = OpenerDirector()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001336 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001337 o.add_handler(ph)
1338 meth_spec = [
1339 [("http_open", "return response")]
1340 ]
1341 handlers = add_ordered_mock_handlers(o, meth_spec)
1342
1343 req = Request("http://acme.example.com/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001344 self.assertEqual(req.host, "acme.example.com")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001345 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001346 self.assertEqual(req.host, "proxy.example.com:3128")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001347
1348 self.assertEqual([(handlers[0], "http_open")],
1349 [tup[0:2] for tup in o.calls])
1350
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001351 def test_proxy_no_proxy(self):
1352 os.environ['no_proxy'] = 'python.org'
1353 o = OpenerDirector()
1354 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1355 o.add_handler(ph)
1356 req = Request("http://www.perl.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001357 self.assertEqual(req.host, "www.perl.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001358 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001359 self.assertEqual(req.host, "proxy.example.com")
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001360 req = Request("http://www.python.org")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001361 self.assertEqual(req.host, "www.python.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001362 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001363 self.assertEqual(req.host, "www.python.org")
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001364 del os.environ['no_proxy']
1365
Ronald Oussorene72e1612011-03-14 18:15:25 -04001366 def test_proxy_no_proxy_all(self):
1367 os.environ['no_proxy'] = '*'
1368 o = OpenerDirector()
1369 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1370 o.add_handler(ph)
1371 req = Request("http://www.python.org")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001372 self.assertEqual(req.host, "www.python.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001373 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001374 self.assertEqual(req.host, "www.python.org")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001375 del os.environ['no_proxy']
1376
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001377 def test_proxy_https(self):
1378 o = OpenerDirector()
1379 ph = urllib.request.ProxyHandler(dict(https="proxy.example.com:3128"))
1380 o.add_handler(ph)
1381 meth_spec = [
1382 [("https_open", "return response")]
1383 ]
1384 handlers = add_ordered_mock_handlers(o, meth_spec)
1385
1386 req = Request("https://www.example.com/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001387 self.assertEqual(req.host, "www.example.com")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001388 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001389 self.assertEqual(req.host, "proxy.example.com:3128")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001390 self.assertEqual([(handlers[0], "https_open")],
1391 [tup[0:2] for tup in o.calls])
1392
Senthil Kumaran47fff872009-12-20 07:10:31 +00001393 def test_proxy_https_proxy_authorization(self):
1394 o = OpenerDirector()
1395 ph = urllib.request.ProxyHandler(dict(https='proxy.example.com:3128'))
1396 o.add_handler(ph)
1397 https_handler = MockHTTPSHandler()
1398 o.add_handler(https_handler)
1399 req = Request("https://www.example.com/")
Facundo Batista244afcf2015-04-22 18:35:54 -03001400 req.add_header("Proxy-Authorization", "FooBar")
1401 req.add_header("User-Agent", "Grail")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001402 self.assertEqual(req.host, "www.example.com")
Senthil Kumaran47fff872009-12-20 07:10:31 +00001403 self.assertIsNone(req._tunnel_host)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001404 o.open(req)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001405 # Verify Proxy-Authorization gets tunneled to request.
1406 # httpsconn req_headers do not have the Proxy-Authorization header but
1407 # the req will have.
Facundo Batista244afcf2015-04-22 18:35:54 -03001408 self.assertNotIn(("Proxy-Authorization", "FooBar"),
Senthil Kumaran47fff872009-12-20 07:10:31 +00001409 https_handler.httpconn.req_headers)
Facundo Batista244afcf2015-04-22 18:35:54 -03001410 self.assertIn(("User-Agent", "Grail"),
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001411 https_handler.httpconn.req_headers)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001412 self.assertIsNotNone(req._tunnel_host)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001413 self.assertEqual(req.host, "proxy.example.com:3128")
Facundo Batista244afcf2015-04-22 18:35:54 -03001414 self.assertEqual(req.get_header("Proxy-authorization"), "FooBar")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001415
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001416 @unittest.skipUnless(sys.platform == 'darwin', "only relevant for OSX")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001417 def test_osx_proxy_bypass(self):
1418 bypass = {
1419 'exclude_simple': False,
1420 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.10',
1421 '10.0/16']
1422 }
1423 # Check hosts that should trigger the proxy bypass
1424 for host in ('foo.bar', 'www.bar.com', '127.0.0.1', '10.10.0.1',
1425 '10.0.0.1'):
1426 self.assertTrue(_proxy_bypass_macosx_sysconf(host, bypass),
1427 'expected bypass of %s to be True' % host)
1428 # Check hosts that should not trigger the proxy bypass
R David Murrayfdbe9182014-03-15 12:00:14 -04001429 for host in ('abc.foo.bar', 'bar.com', '127.0.0.2', '10.11.0.1',
1430 'notinbypass'):
Ronald Oussorene72e1612011-03-14 18:15:25 -04001431 self.assertFalse(_proxy_bypass_macosx_sysconf(host, bypass),
1432 'expected bypass of %s to be False' % host)
1433
1434 # Check the exclude_simple flag
1435 bypass = {'exclude_simple': True, 'exceptions': []}
1436 self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass))
1437
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001438 def test_basic_auth(self, quote_char='"'):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001439 opener = OpenerDirector()
1440 password_manager = MockPasswordManager()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001441 auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001442 realm = "ACME Widget Store"
1443 http_handler = MockHTTPHandler(
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001444 401, 'WWW-Authenticate: Basic realm=%s%s%s\r\n\r\n' %
Facundo Batista244afcf2015-04-22 18:35:54 -03001445 (quote_char, realm, quote_char))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001446 opener.add_handler(auth_handler)
1447 opener.add_handler(http_handler)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001448 self._test_basic_auth(opener, auth_handler, "Authorization",
1449 realm, http_handler, password_manager,
1450 "http://acme.example.com/protected",
1451 "http://acme.example.com/protected",
1452 )
1453
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001454 def test_basic_auth_with_single_quoted_realm(self):
1455 self.test_basic_auth(quote_char="'")
1456
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +08001457 def test_basic_auth_with_unquoted_realm(self):
1458 opener = OpenerDirector()
1459 password_manager = MockPasswordManager()
1460 auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
1461 realm = "ACME Widget Store"
1462 http_handler = MockHTTPHandler(
1463 401, 'WWW-Authenticate: Basic realm=%s\r\n\r\n' % realm)
1464 opener.add_handler(auth_handler)
1465 opener.add_handler(http_handler)
Senthil Kumaran0ea91cb2012-05-15 23:59:42 +08001466 with self.assertWarns(UserWarning):
1467 self._test_basic_auth(opener, auth_handler, "Authorization",
1468 realm, http_handler, password_manager,
1469 "http://acme.example.com/protected",
1470 "http://acme.example.com/protected",
1471 )
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +08001472
Thomas Wouters477c8d52006-05-27 19:21:47 +00001473 def test_proxy_basic_auth(self):
1474 opener = OpenerDirector()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001475 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001476 opener.add_handler(ph)
1477 password_manager = MockPasswordManager()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001478 auth_handler = urllib.request.ProxyBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001479 realm = "ACME Networks"
1480 http_handler = MockHTTPHandler(
1481 407, 'Proxy-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001482 opener.add_handler(auth_handler)
1483 opener.add_handler(http_handler)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001484 self._test_basic_auth(opener, auth_handler, "Proxy-authorization",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001485 realm, http_handler, password_manager,
1486 "http://acme.example.com:3128/protected",
1487 "proxy.example.com:3128",
1488 )
1489
1490 def test_basic_and_digest_auth_handlers(self):
Andrew Svetlov7bd61cb2012-12-19 22:49:25 +02001491 # HTTPDigestAuthHandler raised an exception if it couldn't handle a 40*
Thomas Wouters477c8d52006-05-27 19:21:47 +00001492 # response (http://python.org/sf/1479302), where it should instead
1493 # return None to allow another handler (especially
1494 # HTTPBasicAuthHandler) to handle the response.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001495
1496 # Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must
1497 # try digest first (since it's the strongest auth scheme), so we record
1498 # order of calls here to check digest comes first:
1499 class RecordingOpenerDirector(OpenerDirector):
1500 def __init__(self):
1501 OpenerDirector.__init__(self)
1502 self.recorded = []
Facundo Batista244afcf2015-04-22 18:35:54 -03001503
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001504 def record(self, info):
1505 self.recorded.append(info)
Facundo Batista244afcf2015-04-22 18:35:54 -03001506
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001507 class TestDigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001508 def http_error_401(self, *args, **kwds):
1509 self.parent.record("digest")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001510 urllib.request.HTTPDigestAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001511 *args, **kwds)
Facundo Batista244afcf2015-04-22 18:35:54 -03001512
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001513 class TestBasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001514 def http_error_401(self, *args, **kwds):
1515 self.parent.record("basic")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001516 urllib.request.HTTPBasicAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001517 *args, **kwds)
1518
1519 opener = RecordingOpenerDirector()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001520 password_manager = MockPasswordManager()
1521 digest_handler = TestDigestAuthHandler(password_manager)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001522 basic_handler = TestBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001523 realm = "ACME Networks"
1524 http_handler = MockHTTPHandler(
1525 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001526 opener.add_handler(basic_handler)
1527 opener.add_handler(digest_handler)
1528 opener.add_handler(http_handler)
1529
1530 # check basic auth isn't blocked by digest handler failing
Thomas Wouters477c8d52006-05-27 19:21:47 +00001531 self._test_basic_auth(opener, basic_handler, "Authorization",
1532 realm, http_handler, password_manager,
1533 "http://acme.example.com/protected",
1534 "http://acme.example.com/protected",
1535 )
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001536 # check digest was tried before basic (twice, because
1537 # _test_basic_auth called .open() twice)
1538 self.assertEqual(opener.recorded, ["digest", "basic"]*2)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001539
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001540 def test_unsupported_auth_digest_handler(self):
1541 opener = OpenerDirector()
1542 # While using DigestAuthHandler
1543 digest_auth_handler = urllib.request.HTTPDigestAuthHandler(None)
1544 http_handler = MockHTTPHandler(
1545 401, 'WWW-Authenticate: Kerberos\r\n\r\n')
1546 opener.add_handler(digest_auth_handler)
1547 opener.add_handler(http_handler)
Facundo Batista244afcf2015-04-22 18:35:54 -03001548 self.assertRaises(ValueError, opener.open, "http://www.example.com")
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001549
1550 def test_unsupported_auth_basic_handler(self):
1551 # While using BasicAuthHandler
1552 opener = OpenerDirector()
1553 basic_auth_handler = urllib.request.HTTPBasicAuthHandler(None)
1554 http_handler = MockHTTPHandler(
1555 401, 'WWW-Authenticate: NTLM\r\n\r\n')
1556 opener.add_handler(basic_auth_handler)
1557 opener.add_handler(http_handler)
Facundo Batista244afcf2015-04-22 18:35:54 -03001558 self.assertRaises(ValueError, opener.open, "http://www.example.com")
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001559
Thomas Wouters477c8d52006-05-27 19:21:47 +00001560 def _test_basic_auth(self, opener, auth_handler, auth_header,
1561 realm, http_handler, password_manager,
1562 request_url, protected_url):
Christian Heimes05e8be12008-02-23 18:30:17 +00001563 import base64
Thomas Wouters477c8d52006-05-27 19:21:47 +00001564 user, password = "wile", "coyote"
Thomas Wouters477c8d52006-05-27 19:21:47 +00001565
1566 # .add_password() fed through to password manager
1567 auth_handler.add_password(realm, request_url, user, password)
1568 self.assertEqual(realm, password_manager.realm)
1569 self.assertEqual(request_url, password_manager.url)
1570 self.assertEqual(user, password_manager.user)
1571 self.assertEqual(password, password_manager.password)
1572
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001573 opener.open(request_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001574
1575 # should have asked the password manager for the username/password
1576 self.assertEqual(password_manager.target_realm, realm)
1577 self.assertEqual(password_manager.target_url, protected_url)
1578
1579 # expect one request without authorization, then one with
1580 self.assertEqual(len(http_handler.requests), 2)
1581 self.assertFalse(http_handler.requests[0].has_header(auth_header))
Guido van Rossum98b349f2007-08-27 21:47:52 +00001582 userpass = bytes('%s:%s' % (user, password), "ascii")
Guido van Rossum98297ee2007-11-06 21:34:58 +00001583 auth_hdr_value = ('Basic ' +
Georg Brandl706824f2009-06-04 09:42:55 +00001584 base64.encodebytes(userpass).strip().decode())
Thomas Wouters477c8d52006-05-27 19:21:47 +00001585 self.assertEqual(http_handler.requests[1].get_header(auth_header),
1586 auth_hdr_value)
Senthil Kumaranca2fc9e2010-02-24 16:53:16 +00001587 self.assertEqual(http_handler.requests[1].unredirected_hdrs[auth_header],
1588 auth_hdr_value)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001589 # if the password manager can't find a password, the handler won't
1590 # handle the HTTP auth error
1591 password_manager.user = password_manager.password = None
1592 http_handler.reset()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001593 opener.open(request_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001594 self.assertEqual(len(http_handler.requests), 1)
1595 self.assertFalse(http_handler.requests[0].has_header(auth_header))
1596
R David Murray4c7f9952015-04-16 16:36:18 -04001597 def test_basic_prior_auth_auto_send(self):
1598 # Assume already authenticated if is_authenticated=True
1599 # for APIs like Github that don't return 401
1600
1601 user, password = "wile", "coyote"
1602 request_url = "http://acme.example.com/protected"
1603
1604 http_handler = MockHTTPHandlerCheckAuth(200)
1605
1606 pwd_manager = HTTPPasswordMgrWithPriorAuth()
1607 auth_prior_handler = HTTPBasicAuthHandler(pwd_manager)
1608 auth_prior_handler.add_password(
1609 None, request_url, user, password, is_authenticated=True)
1610
1611 is_auth = pwd_manager.is_authenticated(request_url)
1612 self.assertTrue(is_auth)
1613
1614 opener = OpenerDirector()
1615 opener.add_handler(auth_prior_handler)
1616 opener.add_handler(http_handler)
1617
1618 opener.open(request_url)
1619
1620 # expect request to be sent with auth header
1621 self.assertTrue(http_handler.has_auth_header)
1622
1623 def test_basic_prior_auth_send_after_first_success(self):
1624 # Auto send auth header after authentication is successful once
1625
1626 user, password = 'wile', 'coyote'
1627 request_url = 'http://acme.example.com/protected'
1628 realm = 'ACME'
1629
1630 pwd_manager = HTTPPasswordMgrWithPriorAuth()
1631 auth_prior_handler = HTTPBasicAuthHandler(pwd_manager)
1632 auth_prior_handler.add_password(realm, request_url, user, password)
1633
1634 is_auth = pwd_manager.is_authenticated(request_url)
1635 self.assertFalse(is_auth)
1636
1637 opener = OpenerDirector()
1638 opener.add_handler(auth_prior_handler)
1639
1640 http_handler = MockHTTPHandler(
1641 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % None)
1642 opener.add_handler(http_handler)
1643
1644 opener.open(request_url)
1645
1646 is_auth = pwd_manager.is_authenticated(request_url)
1647 self.assertTrue(is_auth)
1648
1649 http_handler = MockHTTPHandlerCheckAuth(200)
1650 self.assertFalse(http_handler.has_auth_header)
1651
1652 opener = OpenerDirector()
1653 opener.add_handler(auth_prior_handler)
1654 opener.add_handler(http_handler)
1655
1656 # After getting 200 from MockHTTPHandler
1657 # Next request sends header in the first request
1658 opener.open(request_url)
1659
1660 # expect request to be sent with auth header
1661 self.assertTrue(http_handler.has_auth_header)
1662
Serhiy Storchakaf54c3502014-09-06 21:41:39 +03001663 def test_http_closed(self):
1664 """Test the connection is cleaned up when the response is closed"""
1665 for (transfer, data) in (
1666 ("Connection: close", b"data"),
1667 ("Transfer-Encoding: chunked", b"4\r\ndata\r\n0\r\n\r\n"),
1668 ("Content-Length: 4", b"data"),
1669 ):
1670 header = "HTTP/1.1 200 OK\r\n{}\r\n\r\n".format(transfer)
1671 conn = test_urllib.fakehttp(header.encode() + data)
1672 handler = urllib.request.AbstractHTTPHandler()
1673 req = Request("http://dummy/")
1674 req.timeout = None
1675 with handler.do_open(conn, req) as resp:
1676 resp.read()
1677 self.assertTrue(conn.fakesock.closed,
1678 "Connection not closed with {!r}".format(transfer))
1679
1680 def test_invalid_closed(self):
1681 """Test the connection is cleaned up after an invalid response"""
1682 conn = test_urllib.fakehttp(b"")
1683 handler = urllib.request.AbstractHTTPHandler()
1684 req = Request("http://dummy/")
1685 req.timeout = None
1686 with self.assertRaises(http.client.BadStatusLine):
1687 handler.do_open(conn, req)
1688 self.assertTrue(conn.fakesock.closed, "Connection not closed")
1689
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001690
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001691class MiscTests(unittest.TestCase):
1692
Senthil Kumarane9853da2013-03-19 12:07:43 -07001693 def opener_has_handler(self, opener, handler_class):
1694 self.assertTrue(any(h.__class__ == handler_class
1695 for h in opener.handlers))
1696
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001697 def test_build_opener(self):
Facundo Batista244afcf2015-04-22 18:35:54 -03001698 class MyHTTPHandler(urllib.request.HTTPHandler):
1699 pass
1700
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001701 class FooHandler(urllib.request.BaseHandler):
Facundo Batista244afcf2015-04-22 18:35:54 -03001702 def foo_open(self):
1703 pass
1704
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001705 class BarHandler(urllib.request.BaseHandler):
Facundo Batista244afcf2015-04-22 18:35:54 -03001706 def bar_open(self):
1707 pass
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001708
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001709 build_opener = urllib.request.build_opener
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001710
1711 o = build_opener(FooHandler, BarHandler)
1712 self.opener_has_handler(o, FooHandler)
1713 self.opener_has_handler(o, BarHandler)
1714
1715 # can take a mix of classes and instances
1716 o = build_opener(FooHandler, BarHandler())
1717 self.opener_has_handler(o, FooHandler)
1718 self.opener_has_handler(o, BarHandler)
1719
1720 # subclasses of default handlers override default handlers
1721 o = build_opener(MyHTTPHandler)
1722 self.opener_has_handler(o, MyHTTPHandler)
1723
1724 # a particular case of overriding: default handlers can be passed
1725 # in explicitly
1726 o = build_opener()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001727 self.opener_has_handler(o, urllib.request.HTTPHandler)
1728 o = build_opener(urllib.request.HTTPHandler)
1729 self.opener_has_handler(o, urllib.request.HTTPHandler)
1730 o = build_opener(urllib.request.HTTPHandler())
1731 self.opener_has_handler(o, urllib.request.HTTPHandler)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001732
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001733 # Issue2670: multiple handlers sharing the same base class
Facundo Batista244afcf2015-04-22 18:35:54 -03001734 class MyOtherHTTPHandler(urllib.request.HTTPHandler):
1735 pass
1736
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001737 o = build_opener(MyHTTPHandler, MyOtherHTTPHandler)
1738 self.opener_has_handler(o, MyHTTPHandler)
1739 self.opener_has_handler(o, MyOtherHTTPHandler)
1740
Brett Cannon80512de2013-01-25 22:27:21 -05001741 @unittest.skipUnless(support.is_resource_enabled('network'),
1742 'test requires network access')
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001743 def test_issue16464(self):
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001744 with support.transient_internet("http://www.example.com/"):
1745 opener = urllib.request.build_opener()
1746 request = urllib.request.Request("http://www.example.com/")
1747 self.assertEqual(None, request.data)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001748
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001749 opener.open(request, "1".encode("us-ascii"))
1750 self.assertEqual(b"1", request.data)
1751 self.assertEqual("1", request.get_header("Content-length"))
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001752
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001753 opener.open(request, "1234567890".encode("us-ascii"))
1754 self.assertEqual(b"1234567890", request.data)
1755 self.assertEqual("10", request.get_header("Content-length"))
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001756
Senthil Kumarane9853da2013-03-19 12:07:43 -07001757 def test_HTTPError_interface(self):
1758 """
1759 Issue 13211 reveals that HTTPError didn't implement the URLError
1760 interface even though HTTPError is a subclass of URLError.
Senthil Kumarane9853da2013-03-19 12:07:43 -07001761 """
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001762 msg = 'something bad happened'
1763 url = code = fp = None
1764 hdrs = 'Content-Length: 42'
1765 err = urllib.error.HTTPError(url, code, msg, hdrs, fp)
1766 self.assertTrue(hasattr(err, 'reason'))
1767 self.assertEqual(err.reason, 'something bad happened')
1768 self.assertTrue(hasattr(err, 'headers'))
1769 self.assertEqual(err.headers, 'Content-Length: 42')
1770 expected_errmsg = 'HTTP Error %s: %s' % (err.code, err.msg)
1771 self.assertEqual(str(err), expected_errmsg)
Facundo Batista244afcf2015-04-22 18:35:54 -03001772 expected_errmsg = '<HTTPError %s: %r>' % (err.code, err.msg)
1773 self.assertEqual(repr(err), expected_errmsg)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001774
Senthil Kumarand8e24f12014-04-14 16:32:20 -04001775 def test_parse_proxy(self):
1776 parse_proxy_test_cases = [
1777 ('proxy.example.com',
1778 (None, None, None, 'proxy.example.com')),
1779 ('proxy.example.com:3128',
1780 (None, None, None, 'proxy.example.com:3128')),
1781 ('proxy.example.com', (None, None, None, 'proxy.example.com')),
1782 ('proxy.example.com:3128',
1783 (None, None, None, 'proxy.example.com:3128')),
1784 # The authority component may optionally include userinfo
1785 # (assumed to be # username:password):
1786 ('joe:password@proxy.example.com',
1787 (None, 'joe', 'password', 'proxy.example.com')),
1788 ('joe:password@proxy.example.com:3128',
1789 (None, 'joe', 'password', 'proxy.example.com:3128')),
1790 #Examples with URLS
1791 ('http://proxy.example.com/',
1792 ('http', None, None, 'proxy.example.com')),
1793 ('http://proxy.example.com:3128/',
1794 ('http', None, None, 'proxy.example.com:3128')),
1795 ('http://joe:password@proxy.example.com/',
1796 ('http', 'joe', 'password', 'proxy.example.com')),
1797 ('http://joe:password@proxy.example.com:3128',
1798 ('http', 'joe', 'password', 'proxy.example.com:3128')),
1799 # Everything after the authority is ignored
1800 ('ftp://joe:password@proxy.example.com/rubbish:3128',
1801 ('ftp', 'joe', 'password', 'proxy.example.com')),
1802 # Test for no trailing '/' case
1803 ('http://joe:password@proxy.example.com',
1804 ('http', 'joe', 'password', 'proxy.example.com'))
1805 ]
1806
1807 for tc, expected in parse_proxy_test_cases:
1808 self.assertEqual(_parse_proxy(tc), expected)
1809
1810 self.assertRaises(ValueError, _parse_proxy, 'file:/ftp.example.com'),
1811
Berker Peksage88dd1c2016-03-06 16:16:40 +02001812 def test_unsupported_algorithm(self):
1813 handler = AbstractDigestAuthHandler()
1814 with self.assertRaises(ValueError) as exc:
1815 handler.get_algorithm_impls('invalid')
1816 self.assertEqual(
1817 str(exc.exception),
1818 "Unsupported digest authentication algorithm 'invalid'"
1819 )
1820
Facundo Batista244afcf2015-04-22 18:35:54 -03001821
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001822class RequestTests(unittest.TestCase):
Jason R. Coombs4a652422013-09-08 13:03:40 -04001823 class PutRequest(Request):
Facundo Batista244afcf2015-04-22 18:35:54 -03001824 method = 'PUT'
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001825
1826 def setUp(self):
1827 self.get = Request("http://www.python.org/~jeremy/")
1828 self.post = Request("http://www.python.org/~jeremy/",
1829 "data",
1830 headers={"X-Test": "test"})
Jason R. Coombs4a652422013-09-08 13:03:40 -04001831 self.head = Request("http://www.python.org/~jeremy/", method='HEAD')
1832 self.put = self.PutRequest("http://www.python.org/~jeremy/")
1833 self.force_post = self.PutRequest("http://www.python.org/~jeremy/",
1834 method="POST")
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001835
1836 def test_method(self):
1837 self.assertEqual("POST", self.post.get_method())
1838 self.assertEqual("GET", self.get.get_method())
Senthil Kumaran0b5463f2013-09-09 23:13:06 -07001839 self.assertEqual("HEAD", self.head.get_method())
Jason R. Coombs4a652422013-09-08 13:03:40 -04001840 self.assertEqual("PUT", self.put.get_method())
1841 self.assertEqual("POST", self.force_post.get_method())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001842
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001843 def test_data(self):
1844 self.assertFalse(self.get.data)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001845 self.assertEqual("GET", self.get.get_method())
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001846 self.get.data = "spam"
1847 self.assertTrue(self.get.data)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001848 self.assertEqual("POST", self.get.get_method())
1849
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001850 # issue 16464
1851 # if we change data we need to remove content-length header
1852 # (cause it's most probably calculated for previous value)
1853 def test_setting_data_should_remove_content_length(self):
R David Murray9cc7d452013-03-20 00:10:51 -04001854 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001855 self.get.add_unredirected_header("Content-length", 42)
1856 self.assertEqual(42, self.get.unredirected_hdrs["Content-length"])
1857 self.get.data = "spam"
R David Murray9cc7d452013-03-20 00:10:51 -04001858 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
1859
1860 # issue 17485 same for deleting data.
1861 def test_deleting_data_should_remove_content_length(self):
1862 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
1863 self.get.data = 'foo'
1864 self.get.add_unredirected_header("Content-length", 3)
1865 self.assertEqual(3, self.get.unredirected_hdrs["Content-length"])
1866 del self.get.data
1867 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001868
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001869 def test_get_full_url(self):
1870 self.assertEqual("http://www.python.org/~jeremy/",
1871 self.get.get_full_url())
1872
1873 def test_selector(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001874 self.assertEqual("/~jeremy/", self.get.selector)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001875 req = Request("http://www.python.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001876 self.assertEqual("/", req.selector)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001877
1878 def test_get_type(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001879 self.assertEqual("http", self.get.type)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001880
1881 def test_get_host(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001882 self.assertEqual("www.python.org", self.get.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001883
1884 def test_get_host_unquote(self):
1885 req = Request("http://www.%70ython.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001886 self.assertEqual("www.python.org", req.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001887
1888 def test_proxy(self):
Florent Xicluna419e3842010-08-08 16:16:07 +00001889 self.assertFalse(self.get.has_proxy())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001890 self.get.set_proxy("www.perl.org", "http")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001891 self.assertTrue(self.get.has_proxy())
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001892 self.assertEqual("www.python.org", self.get.origin_req_host)
1893 self.assertEqual("www.perl.org", self.get.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001894
Senthil Kumarand95cc752010-08-08 11:27:53 +00001895 def test_wrapped_url(self):
1896 req = Request("<URL:http://www.python.org>")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001897 self.assertEqual("www.python.org", req.host)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001898
Senthil Kumaran26430412011-04-13 07:01:19 +08001899 def test_url_fragment(self):
Senthil Kumarand95cc752010-08-08 11:27:53 +00001900 req = Request("http://www.python.org/?qs=query#fragment=true")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001901 self.assertEqual("/?qs=query", req.selector)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001902 req = Request("http://www.python.org/#fun=true")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001903 self.assertEqual("/", req.selector)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001904
Senthil Kumaran26430412011-04-13 07:01:19 +08001905 # Issue 11703: geturl() omits fragment in the original URL.
1906 url = 'http://docs.python.org/library/urllib2.html#OK'
1907 req = Request(url)
1908 self.assertEqual(req.get_full_url(), url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001909
Senthil Kumaran83070752013-05-24 09:14:12 -07001910 def test_url_fullurl_get_full_url(self):
1911 urls = ['http://docs.python.org',
1912 'http://docs.python.org/library/urllib2.html#OK',
Facundo Batista244afcf2015-04-22 18:35:54 -03001913 'http://www.python.org/?qs=query#fragment=true']
Senthil Kumaran83070752013-05-24 09:14:12 -07001914 for url in urls:
1915 req = Request(url)
1916 self.assertEqual(req.get_full_url(), req.full_url)
1917
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001918
1919if __name__ == "__main__":
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001920 unittest.main()