blob: cbfa9ba60c2c8f9374a6c49979a2226586f23da8 [file] [log] [blame]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002from test import support
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03003from test.support import socket_helper
Serhiy Storchakaf54c3502014-09-06 21:41:39 +03004from test import test_urllib
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00005
Christian Heimes05e8be12008-02-23 18:30:17 +00006import os
Guido van Rossum34d19282007-08-09 01:03:29 +00007import io
Georg Brandlf78e02b2008-06-10 17:40:04 +00008import socket
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00009import array
Senthil Kumaran4de00a22011-05-11 21:17:57 +080010import sys
Martin Panter3c0d0ba2016-08-24 06:33:33 +000011import tempfile
12import subprocess
Jeremy Hyltone3e61042001-05-09 15:50:25 +000013
Jeremy Hylton1afc1692008-06-18 20:49:58 +000014import urllib.request
Ronald Oussorene72e1612011-03-14 18:15:25 -040015# The proxy bypass method imported below has logic specific to the OSX
16# proxy config data structure but is testable on all platforms.
R David Murray4c7f9952015-04-16 16:36:18 -040017from urllib.request import (Request, OpenerDirector, HTTPBasicAuthHandler,
18 HTTPPasswordMgrWithPriorAuth, _parse_proxy,
Berker Peksage88dd1c2016-03-06 16:16:40 +020019 _proxy_bypass_macosx_sysconf,
20 AbstractDigestAuthHandler)
Senthil Kumaran83070752013-05-24 09:14:12 -070021from urllib.parse import urlparse
guido@google.coma119df92011-03-29 11:41:02 -070022import urllib.error
Serhiy Storchakaf54c3502014-09-06 21:41:39 +030023import http.client
Jeremy Hyltone3e61042001-05-09 15:50:25 +000024
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000025# XXX
26# Request
27# CacheFTPHandler (hard to write)
Thomas Wouters477c8d52006-05-27 19:21:47 +000028# parse_keqv_list, parse_http_list, HTTPDigestAuthHandler
Jeremy Hyltone3e61042001-05-09 15:50:25 +000029
Facundo Batista244afcf2015-04-22 18:35:54 -030030
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000031class TrivialTests(unittest.TestCase):
Senthil Kumaran6c5bd402011-11-01 23:20:31 +080032
33 def test___all__(self):
34 # Verify which names are exposed
35 for module in 'request', 'response', 'parse', 'error', 'robotparser':
36 context = {}
37 exec('from urllib.%s import *' % module, context)
38 del context['__builtins__']
Florent Xicluna3dbb1f12011-11-04 22:15:37 +010039 if module == 'request' and os.name == 'nt':
40 u, p = context.pop('url2pathname'), context.pop('pathname2url')
41 self.assertEqual(u.__module__, 'nturl2path')
42 self.assertEqual(p.__module__, 'nturl2path')
Senthil Kumaran6c5bd402011-11-01 23:20:31 +080043 for k, v in context.items():
44 self.assertEqual(v.__module__, 'urllib.%s' % module,
45 "%r is exposed in 'urllib.%s' but defined in %r" %
46 (k, module, v.__module__))
47
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000048 def test_trivial(self):
49 # A couple trivial tests
Guido van Rossume2ae77b2001-10-24 20:42:55 +000050
Victor Stinner7cb92042019-07-02 14:50:19 +020051 # clear _opener global variable
52 self.addCleanup(urllib.request.urlcleanup)
53
Jeremy Hylton1afc1692008-06-18 20:49:58 +000054 self.assertRaises(ValueError, urllib.request.urlopen, 'bogus url')
Tim Peters861adac2001-07-16 20:49:49 +000055
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000056 # XXX Name hacking to get this to work on Windows.
Serhiy Storchaka5106d042015-01-26 10:26:14 +020057 fname = os.path.abspath(urllib.request.__file__).replace(os.sep, '/')
Senthil Kumarand587e302010-01-10 17:45:52 +000058
Senthil Kumarand587e302010-01-10 17:45:52 +000059 if os.name == 'nt':
60 file_url = "file:///%s" % fname
61 else:
62 file_url = "file://%s" % fname
63
Serhiy Storchaka5b10b982019-03-05 10:06:26 +020064 with urllib.request.urlopen(file_url) as f:
65 f.read()
Tim Petersf5f32b42005-07-17 23:16:17 +000066
Georg Brandle1b13d22005-08-24 22:20:32 +000067 def test_parse_http_list(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +000068 tests = [
69 ('a,b,c', ['a', 'b', 'c']),
70 ('path"o,l"og"i"cal, example', ['path"o,l"og"i"cal', 'example']),
71 ('a, b, "c", "d", "e,f", g, h',
72 ['a', 'b', '"c"', '"d"', '"e,f"', 'g', 'h']),
73 ('a="b\\"c", d="e\\,f", g="h\\\\i"',
74 ['a="b"c"', 'd="e,f"', 'g="h\\i"'])]
Georg Brandle1b13d22005-08-24 22:20:32 +000075 for string, list in tests:
Florent Xicluna419e3842010-08-08 16:16:07 +000076 self.assertEqual(urllib.request.parse_http_list(string), list)
Georg Brandle1b13d22005-08-24 22:20:32 +000077
Senthil Kumaran843fae92013-03-19 13:43:42 -070078 def test_URLError_reasonstr(self):
79 err = urllib.error.URLError('reason')
80 self.assertIn(err.reason, str(err))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000081
Facundo Batista244afcf2015-04-22 18:35:54 -030082
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -070083class RequestHdrsTests(unittest.TestCase):
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000084
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -070085 def test_request_headers_dict(self):
86 """
87 The Request.headers dictionary is not a documented interface. It
88 should stay that way, because the complete set of headers are only
89 accessible through the .get_header(), .has_header(), .header_items()
90 interface. However, .headers pre-dates those methods, and so real code
91 will be using the dictionary.
92
93 The introduction in 2.4 of those methods was a mistake for the same
94 reason: code that previously saw all (urllib2 user)-provided headers in
95 .headers now sees only a subset.
96
97 """
98 url = "http://example.com"
99 self.assertEqual(Request(url,
100 headers={"Spam-eggs": "blah"}
101 ).headers["Spam-eggs"], "blah")
102 self.assertEqual(Request(url,
103 headers={"spam-EggS": "blah"}
104 ).headers["Spam-eggs"], "blah")
105
106 def test_request_headers_methods(self):
107 """
108 Note the case normalization of header names here, to
109 .capitalize()-case. This should be preserved for
110 backwards-compatibility. (In the HTTP case, normalization to
111 .title()-case is done by urllib2 before sending headers to
112 http.client).
113
114 Note that e.g. r.has_header("spam-EggS") is currently False, and
115 r.get_header("spam-EggS") returns None, but that could be changed in
116 future.
117
118 Method r.remove_header should remove items both from r.headers and
119 r.unredirected_hdrs dictionaries
120 """
121 url = "http://example.com"
122 req = Request(url, headers={"Spam-eggs": "blah"})
123 self.assertTrue(req.has_header("Spam-eggs"))
124 self.assertEqual(req.header_items(), [('Spam-eggs', 'blah')])
125
126 req.add_header("Foo-Bar", "baz")
127 self.assertEqual(sorted(req.header_items()),
128 [('Foo-bar', 'baz'), ('Spam-eggs', 'blah')])
129 self.assertFalse(req.has_header("Not-there"))
130 self.assertIsNone(req.get_header("Not-there"))
131 self.assertEqual(req.get_header("Not-there", "default"), "default")
132
133 req.remove_header("Spam-eggs")
134 self.assertFalse(req.has_header("Spam-eggs"))
135
136 req.add_unredirected_header("Unredirected-spam", "Eggs")
137 self.assertTrue(req.has_header("Unredirected-spam"))
138
139 req.remove_header("Unredirected-spam")
140 self.assertFalse(req.has_header("Unredirected-spam"))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000141
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700142 def test_password_manager(self):
143 mgr = urllib.request.HTTPPasswordMgr()
144 add = mgr.add_password
145 find_user_pass = mgr.find_user_password
Senthil Kumaran1f5425f2017-03-31 22:27:27 -0700146
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700147 add("Some Realm", "http://example.com/", "joe", "password")
148 add("Some Realm", "http://example.com/ni", "ni", "ni")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700149 add("Some Realm", "http://c.example.com:3128", "3", "c")
150 add("Some Realm", "d.example.com", "4", "d")
151 add("Some Realm", "e.example.com:3128", "5", "e")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000152
Senthil Kumaran1f5425f2017-03-31 22:27:27 -0700153 # For the same realm, password set the highest path is the winner.
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700154 self.assertEqual(find_user_pass("Some Realm", "example.com"),
155 ('joe', 'password'))
Senthil Kumaran1f5425f2017-03-31 22:27:27 -0700156 self.assertEqual(find_user_pass("Some Realm", "http://example.com/ni"),
157 ('joe', 'password'))
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700158 self.assertEqual(find_user_pass("Some Realm", "http://example.com"),
159 ('joe', 'password'))
160 self.assertEqual(find_user_pass("Some Realm", "http://example.com/"),
161 ('joe', 'password'))
Senthil Kumaran1f5425f2017-03-31 22:27:27 -0700162 self.assertEqual(find_user_pass("Some Realm",
163 "http://example.com/spam"),
164 ('joe', 'password'))
165
166 self.assertEqual(find_user_pass("Some Realm",
167 "http://example.com/spam/spam"),
168 ('joe', 'password'))
169
170 # You can have different passwords for different paths.
171
172 add("c", "http://example.com/foo", "foo", "ni")
173 add("c", "http://example.com/bar", "bar", "nini")
174
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700175 self.assertEqual(find_user_pass("c", "http://example.com/foo"),
176 ('foo', 'ni'))
Senthil Kumaran1f5425f2017-03-31 22:27:27 -0700177
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700178 self.assertEqual(find_user_pass("c", "http://example.com/bar"),
179 ('bar', 'nini'))
Senthil Kumaran1f5425f2017-03-31 22:27:27 -0700180
181 # For the same path, newer password should be considered.
182
183 add("b", "http://example.com/", "first", "blah")
184 add("b", "http://example.com/", "second", "spam")
185
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700186 self.assertEqual(find_user_pass("b", "http://example.com/"),
187 ('second', 'spam'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000188
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700189 # No special relationship between a.example.com and example.com:
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000190
Senthil Kumaran1f5425f2017-03-31 22:27:27 -0700191 add("a", "http://example.com", "1", "a")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700192 self.assertEqual(find_user_pass("a", "http://example.com/"),
193 ('1', 'a'))
Senthil Kumaran1f5425f2017-03-31 22:27:27 -0700194
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700195 self.assertEqual(find_user_pass("a", "http://a.example.com/"),
196 (None, None))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000197
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700198 # Ports:
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000199
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700200 self.assertEqual(find_user_pass("Some Realm", "c.example.com"),
201 (None, None))
202 self.assertEqual(find_user_pass("Some Realm", "c.example.com:3128"),
203 ('3', 'c'))
204 self.assertEqual(
205 find_user_pass("Some Realm", "http://c.example.com:3128"),
206 ('3', 'c'))
207 self.assertEqual(find_user_pass("Some Realm", "d.example.com"),
208 ('4', 'd'))
209 self.assertEqual(find_user_pass("Some Realm", "e.example.com:3128"),
210 ('5', 'e'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000211
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700212 def test_password_manager_default_port(self):
213 """
214 The point to note here is that we can't guess the default port if
215 there's no scheme. This applies to both add_password and
216 find_user_password.
217 """
218 mgr = urllib.request.HTTPPasswordMgr()
219 add = mgr.add_password
220 find_user_pass = mgr.find_user_password
221 add("f", "http://g.example.com:80", "10", "j")
222 add("g", "http://h.example.com", "11", "k")
223 add("h", "i.example.com:80", "12", "l")
224 add("i", "j.example.com", "13", "m")
225 self.assertEqual(find_user_pass("f", "g.example.com:100"),
226 (None, None))
227 self.assertEqual(find_user_pass("f", "g.example.com:80"),
228 ('10', 'j'))
229 self.assertEqual(find_user_pass("f", "g.example.com"),
230 (None, None))
231 self.assertEqual(find_user_pass("f", "http://g.example.com:100"),
232 (None, None))
233 self.assertEqual(find_user_pass("f", "http://g.example.com:80"),
234 ('10', 'j'))
235 self.assertEqual(find_user_pass("f", "http://g.example.com"),
236 ('10', 'j'))
237 self.assertEqual(find_user_pass("g", "h.example.com"), ('11', 'k'))
238 self.assertEqual(find_user_pass("g", "h.example.com:80"), ('11', 'k'))
239 self.assertEqual(find_user_pass("g", "http://h.example.com:80"),
240 ('11', 'k'))
241 self.assertEqual(find_user_pass("h", "i.example.com"), (None, None))
242 self.assertEqual(find_user_pass("h", "i.example.com:80"), ('12', 'l'))
243 self.assertEqual(find_user_pass("h", "http://i.example.com:80"),
244 ('12', 'l'))
245 self.assertEqual(find_user_pass("i", "j.example.com"), ('13', 'm'))
246 self.assertEqual(find_user_pass("i", "j.example.com:80"),
247 (None, None))
248 self.assertEqual(find_user_pass("i", "http://j.example.com"),
249 ('13', 'm'))
250 self.assertEqual(find_user_pass("i", "http://j.example.com:80"),
251 (None, None))
Andrew Svetlovbff98fe2012-11-27 23:06:19 +0200252
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000253
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000254class MockOpener:
255 addheaders = []
Facundo Batista244afcf2015-04-22 18:35:54 -0300256
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000257 def open(self, req, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
258 self.req, self.data, self.timeout = req, data, timeout
Facundo Batista244afcf2015-04-22 18:35:54 -0300259
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000260 def error(self, proto, *args):
261 self.proto, self.args = proto, args
262
Facundo Batista244afcf2015-04-22 18:35:54 -0300263
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000264class MockFile:
Facundo Batista244afcf2015-04-22 18:35:54 -0300265 def read(self, count=None):
266 pass
267
268 def readline(self, count=None):
269 pass
270
271 def close(self):
272 pass
273
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000274
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000275class MockHeaders(dict):
276 def getheaders(self, name):
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000277 return list(self.values())
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000278
Facundo Batista244afcf2015-04-22 18:35:54 -0300279
Guido van Rossum34d19282007-08-09 01:03:29 +0000280class MockResponse(io.StringIO):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000281 def __init__(self, code, msg, headers, data, url=None):
Guido van Rossum34d19282007-08-09 01:03:29 +0000282 io.StringIO.__init__(self, data)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000283 self.code, self.msg, self.headers, self.url = code, msg, headers, url
Facundo Batista244afcf2015-04-22 18:35:54 -0300284
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000285 def info(self):
286 return self.headers
Facundo Batista244afcf2015-04-22 18:35:54 -0300287
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000288 def geturl(self):
289 return self.url
290
Facundo Batista244afcf2015-04-22 18:35:54 -0300291
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000292class MockCookieJar:
293 def add_cookie_header(self, request):
294 self.ach_req = request
Facundo Batista244afcf2015-04-22 18:35:54 -0300295
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000296 def extract_cookies(self, response, request):
297 self.ec_req, self.ec_r = request, response
298
Facundo Batista244afcf2015-04-22 18:35:54 -0300299
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000300class FakeMethod:
301 def __init__(self, meth_name, action, handle):
302 self.meth_name = meth_name
303 self.handle = handle
304 self.action = action
Facundo Batista244afcf2015-04-22 18:35:54 -0300305
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000306 def __call__(self, *args):
307 return self.handle(self.meth_name, self.action, *args)
308
Facundo Batista244afcf2015-04-22 18:35:54 -0300309
Senthil Kumaran47fff872009-12-20 07:10:31 +0000310class MockHTTPResponse(io.IOBase):
311 def __init__(self, fp, msg, status, reason):
312 self.fp = fp
313 self.msg = msg
314 self.status = status
315 self.reason = reason
316 self.code = 200
317
318 def read(self):
319 return ''
320
321 def info(self):
322 return {}
323
324 def geturl(self):
325 return self.url
326
327
328class MockHTTPClass:
329 def __init__(self):
330 self.level = 0
331 self.req_headers = []
332 self.data = None
333 self.raise_on_endheaders = False
Nadeem Vawdabd26b542012-10-21 17:37:43 +0200334 self.sock = None
Senthil Kumaran47fff872009-12-20 07:10:31 +0000335 self._tunnel_headers = {}
336
337 def __call__(self, host, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
338 self.host = host
339 self.timeout = timeout
340 return self
341
342 def set_debuglevel(self, level):
343 self.level = level
344
345 def set_tunnel(self, host, port=None, headers=None):
346 self._tunnel_host = host
347 self._tunnel_port = port
348 if headers:
349 self._tunnel_headers = headers
350 else:
351 self._tunnel_headers.clear()
352
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000353 def request(self, method, url, body=None, headers=None, *,
354 encode_chunked=False):
Senthil Kumaran47fff872009-12-20 07:10:31 +0000355 self.method = method
356 self.selector = url
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000357 if headers is not None:
358 self.req_headers += headers.items()
Senthil Kumaran47fff872009-12-20 07:10:31 +0000359 self.req_headers.sort()
360 if body:
361 self.data = body
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000362 self.encode_chunked = encode_chunked
Senthil Kumaran47fff872009-12-20 07:10:31 +0000363 if self.raise_on_endheaders:
Andrew Svetlov0832af62012-12-18 23:10:48 +0200364 raise OSError()
Facundo Batista244afcf2015-04-22 18:35:54 -0300365
Senthil Kumaran47fff872009-12-20 07:10:31 +0000366 def getresponse(self):
367 return MockHTTPResponse(MockFile(), {}, 200, "OK")
368
Victor Stinnera4c45d72011-06-17 14:01:18 +0200369 def close(self):
370 pass
371
Facundo Batista244afcf2015-04-22 18:35:54 -0300372
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000373class MockHandler:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000374 # useful for testing handler machinery
375 # see add_ordered_mock_handlers() docstring
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000376 handler_order = 500
Facundo Batista244afcf2015-04-22 18:35:54 -0300377
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000378 def __init__(self, methods):
379 self._define_methods(methods)
Facundo Batista244afcf2015-04-22 18:35:54 -0300380
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000381 def _define_methods(self, methods):
382 for spec in methods:
Facundo Batista244afcf2015-04-22 18:35:54 -0300383 if len(spec) == 2:
384 name, action = spec
385 else:
386 name, action = spec, None
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000387 meth = FakeMethod(name, action, self.handle)
388 setattr(self.__class__, name, meth)
Facundo Batista244afcf2015-04-22 18:35:54 -0300389
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000390 def handle(self, fn_name, action, *args, **kwds):
391 self.parent.calls.append((self, fn_name, args, kwds))
392 if action is None:
393 return None
394 elif action == "return self":
395 return self
396 elif action == "return response":
397 res = MockResponse(200, "OK", {}, "")
398 return res
399 elif action == "return request":
400 return Request("http://blah/")
401 elif action.startswith("error"):
402 code = action[action.rfind(" ")+1:]
403 try:
404 code = int(code)
405 except ValueError:
406 pass
407 res = MockResponse(200, "OK", {}, "")
408 return self.parent.error("http", args[0], res, code, "", {})
409 elif action == "raise":
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000410 raise urllib.error.URLError("blah")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000411 assert False
Facundo Batista244afcf2015-04-22 18:35:54 -0300412
413 def close(self):
414 pass
415
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000416 def add_parent(self, parent):
417 self.parent = parent
418 self.parent.calls = []
Facundo Batista244afcf2015-04-22 18:35:54 -0300419
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000420 def __lt__(self, other):
421 if not hasattr(other, "handler_order"):
422 # No handler_order, leave in original order. Yuck.
423 return True
424 return self.handler_order < other.handler_order
425
Facundo Batista244afcf2015-04-22 18:35:54 -0300426
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000427def add_ordered_mock_handlers(opener, meth_spec):
428 """Create MockHandlers and add them to an OpenerDirector.
429
430 meth_spec: list of lists of tuples and strings defining methods to define
431 on handlers. eg:
432
433 [["http_error", "ftp_open"], ["http_open"]]
434
435 defines methods .http_error() and .ftp_open() on one handler, and
436 .http_open() on another. These methods just record their arguments and
437 return None. Using a tuple instead of a string causes the method to
438 perform some action (see MockHandler.handle()), eg:
439
440 [["http_error"], [("http_open", "return request")]]
441
442 defines .http_error() on one handler (which simply returns None), and
443 .http_open() on another handler, which returns a Request object.
444
445 """
446 handlers = []
447 count = 0
448 for meths in meth_spec:
Facundo Batista244afcf2015-04-22 18:35:54 -0300449 class MockHandlerSubclass(MockHandler):
450 pass
451
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000452 h = MockHandlerSubclass(meths)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000453 h.handler_order += count
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000454 h.add_parent(opener)
455 count = count + 1
456 handlers.append(h)
457 opener.add_handler(h)
458 return handlers
459
Facundo Batista244afcf2015-04-22 18:35:54 -0300460
Thomas Wouters477c8d52006-05-27 19:21:47 +0000461def build_test_opener(*handler_instances):
462 opener = OpenerDirector()
463 for h in handler_instances:
464 opener.add_handler(h)
465 return opener
466
Facundo Batista244afcf2015-04-22 18:35:54 -0300467
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000468class MockHTTPHandler(urllib.request.BaseHandler):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000469 # useful for testing redirections and auth
470 # sends supplied headers and code as first response
471 # sends 200 OK as second response
472 def __init__(self, code, headers):
473 self.code = code
474 self.headers = headers
475 self.reset()
Facundo Batista244afcf2015-04-22 18:35:54 -0300476
Thomas Wouters477c8d52006-05-27 19:21:47 +0000477 def reset(self):
478 self._count = 0
479 self.requests = []
Facundo Batista244afcf2015-04-22 18:35:54 -0300480
Thomas Wouters477c8d52006-05-27 19:21:47 +0000481 def http_open(self, req):
Martin Panterce6e0682016-05-16 01:07:13 +0000482 import email, copy
Thomas Wouters477c8d52006-05-27 19:21:47 +0000483 self.requests.append(copy.deepcopy(req))
484 if self._count == 0:
485 self._count = self._count + 1
Georg Brandl24420152008-05-26 16:32:26 +0000486 name = http.client.responses[self.code]
Barry Warsaw820c1202008-06-12 04:06:45 +0000487 msg = email.message_from_string(self.headers)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000488 return self.parent.error(
489 "http", req, MockFile(), self.code, name, msg)
490 else:
491 self.req = req
Barry Warsaw820c1202008-06-12 04:06:45 +0000492 msg = email.message_from_string("\r\n\r\n")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000493 return MockResponse(200, "OK", msg, "", req.get_full_url())
494
Facundo Batista244afcf2015-04-22 18:35:54 -0300495
Senthil Kumaran47fff872009-12-20 07:10:31 +0000496class MockHTTPSHandler(urllib.request.AbstractHTTPHandler):
497 # Useful for testing the Proxy-Authorization request by verifying the
498 # properties of httpcon
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000499
Senthil Kumaran9642eed2016-05-13 01:32:42 -0700500 def __init__(self, debuglevel=0):
501 urllib.request.AbstractHTTPHandler.__init__(self, debuglevel=debuglevel)
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000502 self.httpconn = MockHTTPClass()
503
Senthil Kumaran47fff872009-12-20 07:10:31 +0000504 def https_open(self, req):
505 return self.do_open(self.httpconn, req)
506
R David Murray4c7f9952015-04-16 16:36:18 -0400507
508class MockHTTPHandlerCheckAuth(urllib.request.BaseHandler):
509 # useful for testing auth
510 # sends supplied code response
511 # checks if auth header is specified in request
512 def __init__(self, code):
513 self.code = code
514 self.has_auth_header = False
515
516 def reset(self):
517 self.has_auth_header = False
518
519 def http_open(self, req):
520 if req.has_header('Authorization'):
521 self.has_auth_header = True
522 name = http.client.responses[self.code]
523 return MockResponse(self.code, name, MockFile(), "", req.get_full_url())
524
525
Facundo Batista244afcf2015-04-22 18:35:54 -0300526
Thomas Wouters477c8d52006-05-27 19:21:47 +0000527class MockPasswordManager:
528 def add_password(self, realm, uri, user, password):
529 self.realm = realm
530 self.url = uri
531 self.user = user
532 self.password = password
Facundo Batista244afcf2015-04-22 18:35:54 -0300533
Thomas Wouters477c8d52006-05-27 19:21:47 +0000534 def find_user_password(self, realm, authuri):
535 self.target_realm = realm
536 self.target_url = authuri
537 return self.user, self.password
538
539
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000540class OpenerDirectorTests(unittest.TestCase):
541
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000542 def test_add_non_handler(self):
543 class NonHandler(object):
544 pass
545 self.assertRaises(TypeError,
546 OpenerDirector().add_handler, NonHandler())
547
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000548 def test_badly_named_methods(self):
549 # test work-around for three methods that accidentally follow the
550 # naming conventions for handler methods
551 # (*_open() / *_request() / *_response())
552
553 # These used to call the accidentally-named methods, causing a
554 # TypeError in real code; here, returning self from these mock
555 # methods would either cause no exception, or AttributeError.
556
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000557 from urllib.error import URLError
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000558
559 o = OpenerDirector()
560 meth_spec = [
561 [("do_open", "return self"), ("proxy_open", "return self")],
562 [("redirect_request", "return self")],
563 ]
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700564 add_ordered_mock_handlers(o, meth_spec)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000565 o.add_handler(urllib.request.UnknownHandler())
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000566 for scheme in "do", "proxy", "redirect":
567 self.assertRaises(URLError, o.open, scheme+"://example.com/")
568
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000569 def test_handled(self):
570 # handler returning non-None means no more handlers will be called
571 o = OpenerDirector()
572 meth_spec = [
573 ["http_open", "ftp_open", "http_error_302"],
574 ["ftp_open"],
575 [("http_open", "return self")],
576 [("http_open", "return self")],
577 ]
578 handlers = add_ordered_mock_handlers(o, meth_spec)
579
580 req = Request("http://example.com/")
581 r = o.open(req)
582 # Second .http_open() gets called, third doesn't, since second returned
583 # non-None. Handlers without .http_open() never get any methods called
584 # on them.
585 # In fact, second mock handler defining .http_open() returns self
586 # (instead of response), which becomes the OpenerDirector's return
587 # value.
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000588 self.assertEqual(r, handlers[2])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000589 calls = [(handlers[0], "http_open"), (handlers[2], "http_open")]
590 for expected, got in zip(calls, o.calls):
591 handler, name, args, kwds = got
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000592 self.assertEqual((handler, name), expected)
593 self.assertEqual(args, (req,))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000594
595 def test_handler_order(self):
596 o = OpenerDirector()
597 handlers = []
Facundo Batista244afcf2015-04-22 18:35:54 -0300598 for meths, handler_order in [([("http_open", "return self")], 500),
599 (["http_open"], 0)]:
600 class MockHandlerSubclass(MockHandler):
601 pass
602
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000603 h = MockHandlerSubclass(meths)
604 h.handler_order = handler_order
605 handlers.append(h)
606 o.add_handler(h)
607
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700608 o.open("http://example.com/")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000609 # handlers called in reverse order, thanks to their sort order
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000610 self.assertEqual(o.calls[0][0], handlers[1])
611 self.assertEqual(o.calls[1][0], handlers[0])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000612
613 def test_raise(self):
614 # raising URLError stops processing of request
615 o = OpenerDirector()
616 meth_spec = [
617 [("http_open", "raise")],
618 [("http_open", "return self")],
619 ]
620 handlers = add_ordered_mock_handlers(o, meth_spec)
621
622 req = Request("http://example.com/")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000623 self.assertRaises(urllib.error.URLError, o.open, req)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000624 self.assertEqual(o.calls, [(handlers[0], "http_open", (req,), {})])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000625
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000626 def test_http_error(self):
627 # XXX http_error_default
628 # http errors are a special case
629 o = OpenerDirector()
630 meth_spec = [
631 [("http_open", "error 302")],
632 [("http_error_400", "raise"), "http_open"],
633 [("http_error_302", "return response"), "http_error_303",
634 "http_error"],
635 [("http_error_302")],
636 ]
637 handlers = add_ordered_mock_handlers(o, meth_spec)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000638 req = Request("http://example.com/")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700639 o.open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000640 assert len(o.calls) == 2
641 calls = [(handlers[0], "http_open", (req,)),
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000642 (handlers[2], "http_error_302",
Serhiy Storchaka7d44e7a2019-08-08 08:43:18 +0300643 (req, support.ALWAYS_EQ, 302, "", {}))]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000644 for expected, got in zip(calls, o.calls):
645 handler, method_name, args = expected
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000646 self.assertEqual((handler, method_name), got[:2])
647 self.assertEqual(args, got[2])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000648
649 def test_processors(self):
650 # *_request / *_response methods get called appropriately
651 o = OpenerDirector()
652 meth_spec = [
653 [("http_request", "return request"),
654 ("http_response", "return response")],
655 [("http_request", "return request"),
656 ("http_response", "return response")],
657 ]
658 handlers = add_ordered_mock_handlers(o, meth_spec)
659
660 req = Request("http://example.com/")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700661 o.open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000662 # processor methods are called on *all* handlers that define them,
663 # not just the first handler that handles the request
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000664 calls = [
665 (handlers[0], "http_request"), (handlers[1], "http_request"),
666 (handlers[0], "http_response"), (handlers[1], "http_response")]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000667
668 for i, (handler, name, args, kwds) in enumerate(o.calls):
669 if i < 2:
670 # *_request
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000671 self.assertEqual((handler, name), calls[i])
672 self.assertEqual(len(args), 1)
Ezio Melottie9615932010-01-24 19:26:24 +0000673 self.assertIsInstance(args[0], Request)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000674 else:
675 # *_response
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000676 self.assertEqual((handler, name), calls[i])
677 self.assertEqual(len(args), 2)
Ezio Melottie9615932010-01-24 19:26:24 +0000678 self.assertIsInstance(args[0], Request)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000679 # response from opener.open is None, because there's no
680 # handler that defines http_open to handle it
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200681 if args[1] is not None:
682 self.assertIsInstance(args[1], MockResponse)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000683
Facundo Batista244afcf2015-04-22 18:35:54 -0300684
Tim Peters58eb11c2004-01-18 20:29:55 +0000685def sanepathname2url(path):
Victor Stinner6c6f8512010-08-07 10:09:35 +0000686 try:
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000687 path.encode("utf-8")
Victor Stinner6c6f8512010-08-07 10:09:35 +0000688 except UnicodeEncodeError:
689 raise unittest.SkipTest("path is not encodable to utf8")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000690 urlpath = urllib.request.pathname2url(path)
Tim Peters58eb11c2004-01-18 20:29:55 +0000691 if os.name == "nt" and urlpath.startswith("///"):
692 urlpath = urlpath[2:]
693 # XXX don't ask me about the mac...
694 return urlpath
695
Facundo Batista244afcf2015-04-22 18:35:54 -0300696
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000697class HandlerTests(unittest.TestCase):
698
699 def test_ftp(self):
700 class MockFTPWrapper:
Facundo Batista244afcf2015-04-22 18:35:54 -0300701 def __init__(self, data):
702 self.data = data
703
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000704 def retrfile(self, filename, filetype):
705 self.filename, self.filetype = filename, filetype
Guido van Rossum34d19282007-08-09 01:03:29 +0000706 return io.StringIO(self.data), len(self.data)
Facundo Batista244afcf2015-04-22 18:35:54 -0300707
708 def close(self):
709 pass
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000710
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000711 class NullFTPHandler(urllib.request.FTPHandler):
Facundo Batista244afcf2015-04-22 18:35:54 -0300712 def __init__(self, data):
713 self.data = data
714
Georg Brandlf78e02b2008-06-10 17:40:04 +0000715 def connect_ftp(self, user, passwd, host, port, dirs,
716 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000717 self.user, self.passwd = user, passwd
718 self.host, self.port = host, port
719 self.dirs = dirs
720 self.ftpwrapper = MockFTPWrapper(self.data)
721 return self.ftpwrapper
722
Georg Brandlf78e02b2008-06-10 17:40:04 +0000723 import ftplib
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000724 data = "rheum rhaponicum"
725 h = NullFTPHandler(data)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700726 h.parent = MockOpener()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000727
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000728 for url, host, port, user, passwd, type_, dirs, filename, mimetype in [
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000729 ("ftp://localhost/foo/bar/baz.html",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000730 "localhost", ftplib.FTP_PORT, "", "", "I",
731 ["foo", "bar"], "baz.html", "text/html"),
732 ("ftp://parrot@localhost/foo/bar/baz.html",
733 "localhost", ftplib.FTP_PORT, "parrot", "", "I",
734 ["foo", "bar"], "baz.html", "text/html"),
735 ("ftp://%25parrot@localhost/foo/bar/baz.html",
736 "localhost", ftplib.FTP_PORT, "%parrot", "", "I",
737 ["foo", "bar"], "baz.html", "text/html"),
738 ("ftp://%2542parrot@localhost/foo/bar/baz.html",
739 "localhost", ftplib.FTP_PORT, "%42parrot", "", "I",
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000740 ["foo", "bar"], "baz.html", "text/html"),
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000741 ("ftp://localhost:80/foo/bar/",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000742 "localhost", 80, "", "", "D",
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000743 ["foo", "bar"], "", None),
744 ("ftp://localhost/baz.gif;type=a",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000745 "localhost", ftplib.FTP_PORT, "", "", "A",
Abhilash Raj19a3d872019-10-11 22:41:35 -0700746 [], "baz.gif", None), # XXX really this should guess image/gif
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000747 ]:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000748 req = Request(url)
749 req.timeout = None
750 r = h.ftp_open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000751 # ftp authentication not yet implemented by FTPHandler
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000752 self.assertEqual(h.user, user)
753 self.assertEqual(h.passwd, passwd)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000754 self.assertEqual(h.host, socket.gethostbyname(host))
755 self.assertEqual(h.port, port)
756 self.assertEqual(h.dirs, dirs)
757 self.assertEqual(h.ftpwrapper.filename, filename)
758 self.assertEqual(h.ftpwrapper.filetype, type_)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000759 headers = r.info()
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000760 self.assertEqual(headers.get("Content-type"), mimetype)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000761 self.assertEqual(int(headers["Content-length"]), len(data))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000762
763 def test_file(self):
Senthil Kumaranbc07ac52014-07-22 00:15:20 -0700764 import email.utils
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000765 h = urllib.request.FileHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000766 o = h.parent = MockOpener()
767
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000768 TESTFN = support.TESTFN
Tim Peters58eb11c2004-01-18 20:29:55 +0000769 urlpath = sanepathname2url(os.path.abspath(TESTFN))
Guido van Rossum6a2ccd02007-07-16 20:51:57 +0000770 towrite = b"hello, world\n"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000771 urls = [
Tim Peters58eb11c2004-01-18 20:29:55 +0000772 "file://localhost%s" % urlpath,
773 "file://%s" % urlpath,
774 "file://%s%s" % (socket.gethostbyname('localhost'), urlpath),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000775 ]
776 try:
777 localaddr = socket.gethostbyname(socket.gethostname())
778 except socket.gaierror:
779 localaddr = ''
780 if localaddr:
781 urls.append("file://%s%s" % (localaddr, urlpath))
782
783 for url in urls:
Tim Peters58eb11c2004-01-18 20:29:55 +0000784 f = open(TESTFN, "wb")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000785 try:
786 try:
787 f.write(towrite)
788 finally:
789 f.close()
790
791 r = h.file_open(Request(url))
792 try:
793 data = r.read()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000794 headers = r.info()
Senthil Kumaran4fbed102010-05-08 03:29:09 +0000795 respurl = r.geturl()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000796 finally:
797 r.close()
Tim Peters58eb11c2004-01-18 20:29:55 +0000798 stats = os.stat(TESTFN)
Benjamin Petersona0c0a4a2008-06-12 22:15:50 +0000799 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000800 finally:
801 os.remove(TESTFN)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000802 self.assertEqual(data, towrite)
803 self.assertEqual(headers["Content-type"], "text/plain")
804 self.assertEqual(headers["Content-length"], "13")
Tim Peters58eb11c2004-01-18 20:29:55 +0000805 self.assertEqual(headers["Last-modified"], modified)
Senthil Kumaran4fbed102010-05-08 03:29:09 +0000806 self.assertEqual(respurl, url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000807
808 for url in [
Tim Peters58eb11c2004-01-18 20:29:55 +0000809 "file://localhost:80%s" % urlpath,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000810 "file:///file_does_not_exist.txt",
Senthil Kumaranbc07ac52014-07-22 00:15:20 -0700811 "file://not-a-local-host.com//dir/file.txt",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000812 "file://%s:80%s/%s" % (socket.gethostbyname('localhost'),
813 os.getcwd(), TESTFN),
814 "file://somerandomhost.ontheinternet.com%s/%s" %
815 (os.getcwd(), TESTFN),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000816 ]:
817 try:
Tim Peters58eb11c2004-01-18 20:29:55 +0000818 f = open(TESTFN, "wb")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000819 try:
820 f.write(towrite)
821 finally:
822 f.close()
823
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000824 self.assertRaises(urllib.error.URLError,
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000825 h.file_open, Request(url))
826 finally:
827 os.remove(TESTFN)
828
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000829 h = urllib.request.FileHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000830 o = h.parent = MockOpener()
831 # XXXX why does // mean ftp (and /// mean not ftp!), and where
832 # is file: scheme specified? I think this is really a bug, and
833 # what was intended was to distinguish between URLs like:
834 # file:/blah.txt (a file)
835 # file://localhost/blah.txt (a file)
836 # file:///blah.txt (a file)
837 # file://ftp.example.com/blah.txt (an ftp URL)
838 for url, ftp in [
Senthil Kumaran383c32d2010-10-14 11:57:35 +0000839 ("file://ftp.example.com//foo.txt", False),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000840 ("file://ftp.example.com///foo.txt", False),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000841 ("file://ftp.example.com/foo.txt", False),
Senthil Kumaran383c32d2010-10-14 11:57:35 +0000842 ("file://somehost//foo/something.txt", False),
Senthil Kumaran2ef16322010-07-11 03:12:43 +0000843 ("file://localhost//foo/something.txt", False),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000844 ]:
845 req = Request(url)
846 try:
847 h.file_open(req)
Senthil Kumaraned3dd1c2017-03-30 22:43:05 -0700848 except urllib.error.URLError:
Florent Xicluna419e3842010-08-08 16:16:07 +0000849 self.assertFalse(ftp)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000850 else:
Florent Xicluna419e3842010-08-08 16:16:07 +0000851 self.assertIs(o.req, req)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000852 self.assertEqual(req.type, "ftp")
Łukasz Langad7e81cc2011-01-09 18:18:53 +0000853 self.assertEqual(req.type == "ftp", ftp)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000854
855 def test_http(self):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000856
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000857 h = urllib.request.AbstractHTTPHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000858 o = h.parent = MockOpener()
859
860 url = "http://example.com/"
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000861 for method, data in [("GET", None), ("POST", b"blah")]:
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000862 req = Request(url, data, {"Foo": "bar"})
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000863 req.timeout = None
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000864 req.add_unredirected_header("Spam", "eggs")
865 http = MockHTTPClass()
866 r = h.do_open(http, req)
867
868 # result attributes
869 r.read; r.readline # wrapped MockFile methods
870 r.info; r.geturl # addinfourl methods
871 r.code, r.msg == 200, "OK" # added from MockHTTPClass.getreply()
872 hdrs = r.info()
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000873 hdrs.get; hdrs.__contains__ # r.info() gives dict from .getreply()
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000874 self.assertEqual(r.geturl(), url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000875
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000876 self.assertEqual(http.host, "example.com")
877 self.assertEqual(http.level, 0)
878 self.assertEqual(http.method, method)
879 self.assertEqual(http.selector, "/")
880 self.assertEqual(http.req_headers,
Jeremy Hyltonb3ee6f92004-02-24 19:40:35 +0000881 [("Connection", "close"),
882 ("Foo", "bar"), ("Spam", "eggs")])
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000883 self.assertEqual(http.data, data)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000884
Andrew Svetlov0832af62012-12-18 23:10:48 +0200885 # check OSError converted to URLError
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000886 http.raise_on_endheaders = True
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000887 self.assertRaises(urllib.error.URLError, h.do_open, http, req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000888
Senthil Kumaran29333122011-02-11 11:25:47 +0000889 # Check for TypeError on POST data which is str.
890 req = Request("http://example.com/","badpost")
891 self.assertRaises(TypeError, h.do_request_, req)
892
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000893 # check adding of standard headers
894 o.addheaders = [("Spam", "eggs")]
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000895 for data in b"", None: # POST, GET
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000896 req = Request("http://example.com/", data)
897 r = MockResponse(200, "OK", {}, "")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000898 newreq = h.do_request_(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000899 if data is None: # GET
Benjamin Peterson577473f2010-01-19 00:09:57 +0000900 self.assertNotIn("Content-length", req.unredirected_hdrs)
901 self.assertNotIn("Content-type", req.unredirected_hdrs)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000902 else: # POST
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000903 self.assertEqual(req.unredirected_hdrs["Content-length"], "0")
904 self.assertEqual(req.unredirected_hdrs["Content-type"],
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000905 "application/x-www-form-urlencoded")
906 # XXX the details of Host could be better tested
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000907 self.assertEqual(req.unredirected_hdrs["Host"], "example.com")
908 self.assertEqual(req.unredirected_hdrs["Spam"], "eggs")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000909
910 # don't clobber existing headers
911 req.add_unredirected_header("Content-length", "foo")
912 req.add_unredirected_header("Content-type", "bar")
913 req.add_unredirected_header("Host", "baz")
914 req.add_unredirected_header("Spam", "foo")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000915 newreq = h.do_request_(req)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000916 self.assertEqual(req.unredirected_hdrs["Content-length"], "foo")
917 self.assertEqual(req.unredirected_hdrs["Content-type"], "bar")
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000918 self.assertEqual(req.unredirected_hdrs["Host"], "baz")
919 self.assertEqual(req.unredirected_hdrs["Spam"], "foo")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000920
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000921 def test_http_body_file(self):
Martin Panteref91bb22016-08-27 01:39:26 +0000922 # A regular file - chunked encoding is used unless Content Length is
923 # already set.
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000924
925 h = urllib.request.AbstractHTTPHandler()
926 o = h.parent = MockOpener()
927
928 file_obj = tempfile.NamedTemporaryFile(mode='w+b', delete=False)
929 file_path = file_obj.name
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000930 file_obj.close()
Martin Panteref91bb22016-08-27 01:39:26 +0000931 self.addCleanup(os.unlink, file_path)
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, {})
935 newreq = h.do_request_(req)
936 te = newreq.get_header('Transfer-encoding')
937 self.assertEqual(te, "chunked")
938 self.assertFalse(newreq.has_header('Content-length'))
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000939
Martin Panteref91bb22016-08-27 01:39:26 +0000940 with open(file_path, "rb") as f:
941 req = Request("http://example.com/", f, {"Content-Length": 30})
942 newreq = h.do_request_(req)
943 self.assertEqual(int(newreq.get_header('Content-length')), 30)
944 self.assertFalse(newreq.has_header("Transfer-encoding"))
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000945
946 def test_http_body_fileobj(self):
Martin Panteref91bb22016-08-27 01:39:26 +0000947 # A file object - chunked encoding is used
948 # unless Content Length is already set.
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000949 # (Note that there are some subtle differences to a regular
950 # file, that is why we are testing both cases.)
951
952 h = urllib.request.AbstractHTTPHandler()
953 o = h.parent = MockOpener()
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000954 file_obj = io.BytesIO()
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000955
Martin Panteref91bb22016-08-27 01:39:26 +0000956 req = Request("http://example.com/", file_obj, {})
957 newreq = h.do_request_(req)
958 self.assertEqual(newreq.get_header('Transfer-encoding'), 'chunked')
959 self.assertFalse(newreq.has_header('Content-length'))
960
961 headers = {"Content-Length": 30}
962 req = Request("http://example.com/", file_obj, headers)
963 newreq = h.do_request_(req)
964 self.assertEqual(int(newreq.get_header('Content-length')), 30)
965 self.assertFalse(newreq.has_header("Transfer-encoding"))
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000966
967 file_obj.close()
968
969 def test_http_body_pipe(self):
970 # A file reading from a pipe.
971 # A pipe cannot be seek'ed. There is no way to determine the
972 # content length up front. Thus, do_request_() should fall
973 # back to Transfer-encoding chunked.
974
975 h = urllib.request.AbstractHTTPHandler()
976 o = h.parent = MockOpener()
977
Martin Panteref91bb22016-08-27 01:39:26 +0000978 cmd = [sys.executable, "-c", r"pass"]
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000979 for headers in {}, {"Content-Length": 30}:
980 with subprocess.Popen(cmd, stdout=subprocess.PIPE) as proc:
981 req = Request("http://example.com/", proc.stdout, headers)
982 newreq = h.do_request_(req)
983 if not headers:
984 self.assertEqual(newreq.get_header('Content-length'), None)
985 self.assertEqual(newreq.get_header('Transfer-encoding'),
986 'chunked')
987 else:
988 self.assertEqual(int(newreq.get_header('Content-length')),
989 30)
990
991 def test_http_body_iterable(self):
992 # Generic iterable. There is no way to determine the content
993 # length up front. Fall back to Transfer-encoding chunked.
994
995 h = urllib.request.AbstractHTTPHandler()
996 o = h.parent = MockOpener()
997
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000998 def iterable_body():
999 yield b"one"
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001000
1001 for headers in {}, {"Content-Length": 11}:
1002 req = Request("http://example.com/", iterable_body(), headers)
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001003 newreq = h.do_request_(req)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001004 if not headers:
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001005 self.assertEqual(newreq.get_header('Content-length'), None)
1006 self.assertEqual(newreq.get_header('Transfer-encoding'),
1007 'chunked')
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001008 else:
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001009 self.assertEqual(int(newreq.get_header('Content-length')), 11)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001010
Martin Panteref91bb22016-08-27 01:39:26 +00001011 def test_http_body_empty_seq(self):
1012 # Zero-length iterable body should be treated like any other iterable
1013 h = urllib.request.AbstractHTTPHandler()
1014 h.parent = MockOpener()
1015 req = h.do_request_(Request("http://example.com/", ()))
1016 self.assertEqual(req.get_header("Transfer-encoding"), "chunked")
1017 self.assertFalse(req.has_header("Content-length"))
1018
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001019 def test_http_body_array(self):
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001020 # array.array Iterable - Content Length is calculated
1021
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001022 h = urllib.request.AbstractHTTPHandler()
1023 o = h.parent = MockOpener()
1024
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001025 iterable_array = array.array("I",[1,2,3,4])
1026
1027 for headers in {}, {"Content-Length": 16}:
1028 req = Request("http://example.com/", iterable_array, headers)
1029 newreq = h.do_request_(req)
1030 self.assertEqual(int(newreq.get_header('Content-length')),16)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001031
Senthil Kumaran9642eed2016-05-13 01:32:42 -07001032 def test_http_handler_debuglevel(self):
1033 o = OpenerDirector()
1034 h = MockHTTPSHandler(debuglevel=1)
1035 o.add_handler(h)
1036 o.open("https://www.example.com")
1037 self.assertEqual(h._debuglevel, 1)
1038
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001039 def test_http_doubleslash(self):
1040 # Checks the presence of any unnecessary double slash in url does not
1041 # break anything. Previously, a double slash directly after the host
Ezio Melottie130a522011-10-19 10:58:56 +03001042 # could cause incorrect parsing.
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001043 h = urllib.request.AbstractHTTPHandler()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001044 h.parent = MockOpener()
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001045
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001046 data = b""
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001047 ds_urls = [
1048 "http://example.com/foo/bar/baz.html",
1049 "http://example.com//foo/bar/baz.html",
1050 "http://example.com/foo//bar/baz.html",
1051 "http://example.com/foo/bar//baz.html"
1052 ]
1053
1054 for ds_url in ds_urls:
1055 ds_req = Request(ds_url, data)
1056
1057 # Check whether host is determined correctly if there is no proxy
1058 np_ds_req = h.do_request_(ds_req)
Facundo Batista244afcf2015-04-22 18:35:54 -03001059 self.assertEqual(np_ds_req.unredirected_hdrs["Host"], "example.com")
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001060
1061 # Check whether host is determined correctly if there is a proxy
Facundo Batista244afcf2015-04-22 18:35:54 -03001062 ds_req.set_proxy("someproxy:3128", None)
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001063 p_ds_req = h.do_request_(ds_req)
Facundo Batista244afcf2015-04-22 18:35:54 -03001064 self.assertEqual(p_ds_req.unredirected_hdrs["Host"], "example.com")
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001065
Senthil Kumaran52380922013-04-25 05:45:48 -07001066 def test_full_url_setter(self):
1067 # Checks to ensure that components are set correctly after setting the
1068 # full_url of a Request object
1069
1070 urls = [
1071 'http://example.com?foo=bar#baz',
1072 'http://example.com?foo=bar&spam=eggs#bash',
1073 'http://example.com',
1074 ]
1075
1076 # testing a reusable request instance, but the url parameter is
1077 # required, so just use a dummy one to instantiate
1078 r = Request('http://example.com')
1079 for url in urls:
1080 r.full_url = url
Senthil Kumaran83070752013-05-24 09:14:12 -07001081 parsed = urlparse(url)
1082
Senthil Kumaran52380922013-04-25 05:45:48 -07001083 self.assertEqual(r.get_full_url(), url)
Senthil Kumaran83070752013-05-24 09:14:12 -07001084 # full_url setter uses splittag to split into components.
1085 # splittag sets the fragment as None while urlparse sets it to ''
1086 self.assertEqual(r.fragment or '', parsed.fragment)
1087 self.assertEqual(urlparse(r.get_full_url()).query, parsed.query)
Senthil Kumaran52380922013-04-25 05:45:48 -07001088
1089 def test_full_url_deleter(self):
1090 r = Request('http://www.example.com')
1091 del r.full_url
1092 self.assertIsNone(r.full_url)
1093 self.assertIsNone(r.fragment)
1094 self.assertEqual(r.selector, '')
1095
Senthil Kumaranc2958622010-11-22 04:48:26 +00001096 def test_fixpath_in_weirdurls(self):
1097 # Issue4493: urllib2 to supply '/' when to urls where path does not
1098 # start with'/'
1099
1100 h = urllib.request.AbstractHTTPHandler()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001101 h.parent = MockOpener()
Senthil Kumaranc2958622010-11-22 04:48:26 +00001102
1103 weird_url = 'http://www.python.org?getspam'
1104 req = Request(weird_url)
1105 newreq = h.do_request_(req)
Facundo Batista244afcf2015-04-22 18:35:54 -03001106 self.assertEqual(newreq.host, 'www.python.org')
1107 self.assertEqual(newreq.selector, '/?getspam')
Senthil Kumaranc2958622010-11-22 04:48:26 +00001108
1109 url_without_path = 'http://www.python.org'
1110 req = Request(url_without_path)
1111 newreq = h.do_request_(req)
Facundo Batista244afcf2015-04-22 18:35:54 -03001112 self.assertEqual(newreq.host, 'www.python.org')
1113 self.assertEqual(newreq.selector, '')
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001114
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001115 def test_errors(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001116 h = urllib.request.HTTPErrorProcessor()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001117 o = h.parent = MockOpener()
1118
1119 url = "http://example.com/"
1120 req = Request(url)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001121 # all 2xx are passed through
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001122 r = MockResponse(200, "OK", {}, "", url)
1123 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +00001124 self.assertIs(r, newr)
1125 self.assertFalse(hasattr(o, "proto")) # o.error not called
Guido van Rossumd8faa362007-04-27 19:54:29 +00001126 r = MockResponse(202, "Accepted", {}, "", url)
1127 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +00001128 self.assertIs(r, newr)
1129 self.assertFalse(hasattr(o, "proto")) # o.error not called
Guido van Rossumd8faa362007-04-27 19:54:29 +00001130 r = MockResponse(206, "Partial content", {}, "", url)
1131 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +00001132 self.assertIs(r, newr)
1133 self.assertFalse(hasattr(o, "proto")) # o.error not called
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001134 # anything else calls o.error (and MockOpener returns None, here)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001135 r = MockResponse(502, "Bad gateway", {}, "", url)
Florent Xicluna419e3842010-08-08 16:16:07 +00001136 self.assertIsNone(h.http_response(req, r))
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001137 self.assertEqual(o.proto, "http") # o.error called
Guido van Rossumd8faa362007-04-27 19:54:29 +00001138 self.assertEqual(o.args, (req, r, 502, "Bad gateway", {}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001139
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001140 def test_cookies(self):
1141 cj = MockCookieJar()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001142 h = urllib.request.HTTPCookieProcessor(cj)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001143 h.parent = MockOpener()
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001144
1145 req = Request("http://example.com/")
1146 r = MockResponse(200, "OK", {}, "")
1147 newreq = h.http_request(req)
Florent Xicluna419e3842010-08-08 16:16:07 +00001148 self.assertIs(cj.ach_req, req)
1149 self.assertIs(cj.ach_req, newreq)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001150 self.assertEqual(req.origin_req_host, "example.com")
1151 self.assertFalse(req.unverifiable)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001152 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +00001153 self.assertIs(cj.ec_req, req)
1154 self.assertIs(cj.ec_r, r)
1155 self.assertIs(r, newr)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001156
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001157 def test_redirect(self):
1158 from_url = "http://example.com/a.html"
1159 to_url = "http://example.com/b.html"
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001160 h = urllib.request.HTTPRedirectHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001161 o = h.parent = MockOpener()
1162
1163 # ordinary redirect behaviour
1164 for code in 301, 302, 303, 307:
1165 for data in None, "blah\nblah\n":
1166 method = getattr(h, "http_error_%s" % code)
1167 req = Request(from_url, data)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001168 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001169 req.add_header("Nonsense", "viking=withhold")
Christian Heimes77c02eb2008-02-09 02:18:51 +00001170 if data is not None:
1171 req.add_header("Content-Length", str(len(data)))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001172 req.add_unredirected_header("Spam", "spam")
1173 try:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001174 method(req, MockFile(), code, "Blah",
1175 MockHeaders({"location": to_url}))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001176 except urllib.error.HTTPError:
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001177 # 307 in response to POST requires user OK
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001178 self.assertEqual(code, 307)
1179 self.assertIsNotNone(data)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001180 self.assertEqual(o.req.get_full_url(), to_url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001181 try:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001182 self.assertEqual(o.req.get_method(), "GET")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001183 except AttributeError:
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001184 self.assertFalse(o.req.data)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001185
1186 # now it's a GET, there should not be headers regarding content
1187 # (possibly dragged from before being a POST)
1188 headers = [x.lower() for x in o.req.headers]
Benjamin Peterson577473f2010-01-19 00:09:57 +00001189 self.assertNotIn("content-length", headers)
1190 self.assertNotIn("content-type", headers)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001191
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001192 self.assertEqual(o.req.headers["Nonsense"],
1193 "viking=withhold")
Benjamin Peterson577473f2010-01-19 00:09:57 +00001194 self.assertNotIn("Spam", o.req.headers)
1195 self.assertNotIn("Spam", o.req.unredirected_hdrs)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001196
1197 # loop detection
1198 req = Request(from_url)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001199 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Facundo Batista244afcf2015-04-22 18:35:54 -03001200
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001201 def redirect(h, req, url=to_url):
1202 h.http_error_302(req, MockFile(), 302, "Blah",
1203 MockHeaders({"location": url}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001204 # Note that the *original* request shares the same record of
1205 # redirections with the sub-requests caused by the redirections.
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001206
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001207 # detect infinite loop redirect of a URL to itself
1208 req = Request(from_url, origin_req_host="example.com")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001209 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001210 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001211 try:
1212 while 1:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001213 redirect(h, req, "http://example.com/")
1214 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001215 except urllib.error.HTTPError:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001216 # don't stop until max_repeats, because cookies may introduce state
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001217 self.assertEqual(count, urllib.request.HTTPRedirectHandler.max_repeats)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001218
1219 # detect endless non-repeating chain of redirects
1220 req = Request(from_url, origin_req_host="example.com")
1221 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001222 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001223 try:
1224 while 1:
1225 redirect(h, req, "http://example.com/%d" % count)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001226 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001227 except urllib.error.HTTPError:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001228 self.assertEqual(count,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001229 urllib.request.HTTPRedirectHandler.max_redirections)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001230
guido@google.coma119df92011-03-29 11:41:02 -07001231 def test_invalid_redirect(self):
1232 from_url = "http://example.com/a.html"
1233 valid_schemes = ['http','https','ftp']
1234 invalid_schemes = ['file','imap','ldap']
1235 schemeless_url = "example.com/b.html"
1236 h = urllib.request.HTTPRedirectHandler()
1237 o = h.parent = MockOpener()
1238 req = Request(from_url)
1239 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1240
1241 for scheme in invalid_schemes:
1242 invalid_url = scheme + '://' + schemeless_url
1243 self.assertRaises(urllib.error.HTTPError, h.http_error_302,
1244 req, MockFile(), 302, "Security Loophole",
1245 MockHeaders({"location": invalid_url}))
1246
1247 for scheme in valid_schemes:
1248 valid_url = scheme + '://' + schemeless_url
1249 h.http_error_302(req, MockFile(), 302, "That's fine",
1250 MockHeaders({"location": valid_url}))
1251 self.assertEqual(o.req.get_full_url(), valid_url)
1252
Senthil Kumaran6497aa32012-01-04 13:46:59 +08001253 def test_relative_redirect(self):
1254 from_url = "http://example.com/a.html"
1255 relative_url = "/b.html"
1256 h = urllib.request.HTTPRedirectHandler()
1257 o = h.parent = MockOpener()
1258 req = Request(from_url)
1259 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1260
1261 valid_url = urllib.parse.urljoin(from_url,relative_url)
1262 h.http_error_302(req, MockFile(), 302, "That's fine",
1263 MockHeaders({"location": valid_url}))
1264 self.assertEqual(o.req.get_full_url(), valid_url)
1265
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001266 def test_cookie_redirect(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001267 # cookies shouldn't leak into redirected requests
Georg Brandl24420152008-05-26 16:32:26 +00001268 from http.cookiejar import CookieJar
1269 from test.test_http_cookiejar import interact_netscape
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001270
1271 cj = CookieJar()
1272 interact_netscape(cj, "http://www.example.com/", "spam=eggs")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001273 hh = MockHTTPHandler(302, "Location: http://www.cracker.com/\r\n\r\n")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001274 hdeh = urllib.request.HTTPDefaultErrorHandler()
1275 hrh = urllib.request.HTTPRedirectHandler()
1276 cp = urllib.request.HTTPCookieProcessor(cj)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001277 o = build_test_opener(hh, hdeh, hrh, cp)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001278 o.open("http://www.example.com/")
Florent Xicluna419e3842010-08-08 16:16:07 +00001279 self.assertFalse(hh.req.has_header("Cookie"))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001280
Senthil Kumaran26430412011-04-13 07:01:19 +08001281 def test_redirect_fragment(self):
1282 redirected_url = 'http://www.example.com/index.html#OK\r\n\r\n'
1283 hh = MockHTTPHandler(302, 'Location: ' + redirected_url)
1284 hdeh = urllib.request.HTTPDefaultErrorHandler()
1285 hrh = urllib.request.HTTPRedirectHandler()
1286 o = build_test_opener(hh, hdeh, hrh)
1287 fp = o.open('http://www.example.com')
1288 self.assertEqual(fp.geturl(), redirected_url.strip())
1289
Martin Panterce6e0682016-05-16 01:07:13 +00001290 def test_redirect_no_path(self):
1291 # Issue 14132: Relative redirect strips original path
Victor Stinner7cb92042019-07-02 14:50:19 +02001292
1293 # clear _opener global variable
1294 self.addCleanup(urllib.request.urlcleanup)
1295
Martin Panterce6e0682016-05-16 01:07:13 +00001296 real_class = http.client.HTTPConnection
1297 response1 = b"HTTP/1.1 302 Found\r\nLocation: ?query\r\n\r\n"
1298 http.client.HTTPConnection = test_urllib.fakehttp(response1)
1299 self.addCleanup(setattr, http.client, "HTTPConnection", real_class)
1300 urls = iter(("/path", "/path?query"))
1301 def request(conn, method, url, *pos, **kw):
1302 self.assertEqual(url, next(urls))
1303 real_class.request(conn, method, url, *pos, **kw)
1304 # Change response for subsequent connection
1305 conn.__class__.fakedata = b"HTTP/1.1 200 OK\r\n\r\nHello!"
1306 http.client.HTTPConnection.request = request
1307 fp = urllib.request.urlopen("http://python.org/path")
1308 self.assertEqual(fp.geturl(), "http://python.org/path?query")
1309
Martin Pantere6f06092016-05-16 01:14:20 +00001310 def test_redirect_encoding(self):
1311 # Some characters in the redirect target may need special handling,
1312 # but most ASCII characters should be treated as already encoded
1313 class Handler(urllib.request.HTTPHandler):
1314 def http_open(self, req):
1315 result = self.do_open(self.connection, req)
1316 self.last_buf = self.connection.buf
1317 # Set up a normal response for the next request
1318 self.connection = test_urllib.fakehttp(
1319 b'HTTP/1.1 200 OK\r\n'
1320 b'Content-Length: 3\r\n'
1321 b'\r\n'
1322 b'123'
1323 )
1324 return result
1325 handler = Handler()
1326 opener = urllib.request.build_opener(handler)
1327 tests = (
1328 (b'/p\xC3\xA5-dansk/', b'/p%C3%A5-dansk/'),
1329 (b'/spaced%20path/', b'/spaced%20path/'),
1330 (b'/spaced path/', b'/spaced%20path/'),
1331 (b'/?p\xC3\xA5-dansk', b'/?p%C3%A5-dansk'),
1332 )
1333 for [location, result] in tests:
1334 with self.subTest(repr(location)):
1335 handler.connection = test_urllib.fakehttp(
1336 b'HTTP/1.1 302 Redirect\r\n'
1337 b'Location: ' + location + b'\r\n'
1338 b'\r\n'
1339 )
1340 response = opener.open('http://example.com/')
1341 expected = b'GET ' + result + b' '
1342 request = handler.last_buf
1343 self.assertTrue(request.startswith(expected), repr(request))
1344
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001345 def test_proxy(self):
Zackery Spytzb761e3a2019-09-13 08:07:07 -06001346 u = "proxy.example.com:3128"
1347 for d in dict(http=u), dict(HTTP=u):
1348 o = OpenerDirector()
1349 ph = urllib.request.ProxyHandler(d)
1350 o.add_handler(ph)
1351 meth_spec = [
1352 [("http_open", "return response")]
1353 ]
1354 handlers = add_ordered_mock_handlers(o, meth_spec)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001355
Zackery Spytzb761e3a2019-09-13 08:07:07 -06001356 req = Request("http://acme.example.com/")
1357 self.assertEqual(req.host, "acme.example.com")
1358 o.open(req)
1359 self.assertEqual(req.host, u)
1360 self.assertEqual([(handlers[0], "http_open")],
1361 [tup[0:2] for tup in o.calls])
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001362
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001363 def test_proxy_no_proxy(self):
1364 os.environ['no_proxy'] = 'python.org'
1365 o = OpenerDirector()
1366 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1367 o.add_handler(ph)
1368 req = Request("http://www.perl.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001369 self.assertEqual(req.host, "www.perl.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001370 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001371 self.assertEqual(req.host, "proxy.example.com")
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001372 req = Request("http://www.python.org")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001373 self.assertEqual(req.host, "www.python.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001374 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001375 self.assertEqual(req.host, "www.python.org")
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001376 del os.environ['no_proxy']
1377
Ronald Oussorene72e1612011-03-14 18:15:25 -04001378 def test_proxy_no_proxy_all(self):
1379 os.environ['no_proxy'] = '*'
1380 o = OpenerDirector()
1381 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1382 o.add_handler(ph)
1383 req = Request("http://www.python.org")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001384 self.assertEqual(req.host, "www.python.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001385 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001386 self.assertEqual(req.host, "www.python.org")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001387 del os.environ['no_proxy']
1388
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001389 def test_proxy_https(self):
1390 o = OpenerDirector()
1391 ph = urllib.request.ProxyHandler(dict(https="proxy.example.com:3128"))
1392 o.add_handler(ph)
1393 meth_spec = [
1394 [("https_open", "return response")]
1395 ]
1396 handlers = add_ordered_mock_handlers(o, meth_spec)
1397
1398 req = Request("https://www.example.com/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001399 self.assertEqual(req.host, "www.example.com")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001400 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001401 self.assertEqual(req.host, "proxy.example.com:3128")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001402 self.assertEqual([(handlers[0], "https_open")],
1403 [tup[0:2] for tup in o.calls])
1404
Senthil Kumaran47fff872009-12-20 07:10:31 +00001405 def test_proxy_https_proxy_authorization(self):
1406 o = OpenerDirector()
1407 ph = urllib.request.ProxyHandler(dict(https='proxy.example.com:3128'))
1408 o.add_handler(ph)
1409 https_handler = MockHTTPSHandler()
1410 o.add_handler(https_handler)
1411 req = Request("https://www.example.com/")
Facundo Batista244afcf2015-04-22 18:35:54 -03001412 req.add_header("Proxy-Authorization", "FooBar")
1413 req.add_header("User-Agent", "Grail")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001414 self.assertEqual(req.host, "www.example.com")
Senthil Kumaran47fff872009-12-20 07:10:31 +00001415 self.assertIsNone(req._tunnel_host)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001416 o.open(req)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001417 # Verify Proxy-Authorization gets tunneled to request.
1418 # httpsconn req_headers do not have the Proxy-Authorization header but
1419 # the req will have.
Facundo Batista244afcf2015-04-22 18:35:54 -03001420 self.assertNotIn(("Proxy-Authorization", "FooBar"),
Senthil Kumaran47fff872009-12-20 07:10:31 +00001421 https_handler.httpconn.req_headers)
Facundo Batista244afcf2015-04-22 18:35:54 -03001422 self.assertIn(("User-Agent", "Grail"),
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001423 https_handler.httpconn.req_headers)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001424 self.assertIsNotNone(req._tunnel_host)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001425 self.assertEqual(req.host, "proxy.example.com:3128")
Facundo Batista244afcf2015-04-22 18:35:54 -03001426 self.assertEqual(req.get_header("Proxy-authorization"), "FooBar")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001427
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001428 @unittest.skipUnless(sys.platform == 'darwin', "only relevant for OSX")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001429 def test_osx_proxy_bypass(self):
1430 bypass = {
1431 'exclude_simple': False,
1432 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.10',
1433 '10.0/16']
1434 }
1435 # Check hosts that should trigger the proxy bypass
1436 for host in ('foo.bar', 'www.bar.com', '127.0.0.1', '10.10.0.1',
1437 '10.0.0.1'):
1438 self.assertTrue(_proxy_bypass_macosx_sysconf(host, bypass),
1439 'expected bypass of %s to be True' % host)
1440 # Check hosts that should not trigger the proxy bypass
R David Murrayfdbe9182014-03-15 12:00:14 -04001441 for host in ('abc.foo.bar', 'bar.com', '127.0.0.2', '10.11.0.1',
1442 'notinbypass'):
Ronald Oussorene72e1612011-03-14 18:15:25 -04001443 self.assertFalse(_proxy_bypass_macosx_sysconf(host, bypass),
1444 'expected bypass of %s to be False' % host)
1445
1446 # Check the exclude_simple flag
1447 bypass = {'exclude_simple': True, 'exceptions': []}
1448 self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass))
1449
Victor Stinner0b297d42020-04-02 02:52:20 +02001450 def check_basic_auth(self, headers, realm):
1451 with self.subTest(realm=realm, headers=headers):
1452 opener = OpenerDirector()
1453 password_manager = MockPasswordManager()
1454 auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
1455 body = '\r\n'.join(headers) + '\r\n\r\n'
1456 http_handler = MockHTTPHandler(401, body)
1457 opener.add_handler(auth_handler)
1458 opener.add_handler(http_handler)
Senthil Kumaran0ea91cb2012-05-15 23:59:42 +08001459 self._test_basic_auth(opener, auth_handler, "Authorization",
Victor Stinner0b297d42020-04-02 02:52:20 +02001460 realm, http_handler, password_manager,
1461 "http://acme.example.com/protected",
1462 "http://acme.example.com/protected")
1463
1464 def test_basic_auth(self):
1465 realm = "realm2@example.com"
1466 realm2 = "realm2@example.com"
1467 basic = f'Basic realm="{realm}"'
1468 basic2 = f'Basic realm="{realm2}"'
1469 other_no_realm = 'Otherscheme xxx'
1470 digest = (f'Digest realm="{realm2}", '
1471 f'qop="auth, auth-int", '
1472 f'nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", '
1473 f'opaque="5ccc069c403ebaf9f0171e9517f40e41"')
1474 for realm_str in (
1475 # test "quote" and 'quote'
1476 f'Basic realm="{realm}"',
1477 f"Basic realm='{realm}'",
1478
1479 # charset is ignored
1480 f'Basic realm="{realm}", charset="UTF-8"',
1481
1482 # Multiple challenges per header
1483 f'{basic}, {basic2}',
1484 f'{basic}, {other_no_realm}',
1485 f'{other_no_realm}, {basic}',
1486 f'{basic}, {digest}',
1487 f'{digest}, {basic}',
1488 ):
1489 headers = [f'WWW-Authenticate: {realm_str}']
1490 self.check_basic_auth(headers, realm)
1491
1492 # no quote: expect a warning
1493 with support.check_warnings(("Basic Auth Realm was unquoted",
1494 UserWarning)):
1495 headers = [f'WWW-Authenticate: Basic realm={realm}']
1496 self.check_basic_auth(headers, realm)
1497
1498 # Multiple headers: one challenge per header.
1499 # Use the first Basic realm.
1500 for challenges in (
1501 [basic, basic2],
1502 [basic, digest],
1503 [digest, basic],
1504 ):
1505 headers = [f'WWW-Authenticate: {challenge}'
1506 for challenge in challenges]
1507 self.check_basic_auth(headers, realm)
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +08001508
Thomas Wouters477c8d52006-05-27 19:21:47 +00001509 def test_proxy_basic_auth(self):
1510 opener = OpenerDirector()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001511 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001512 opener.add_handler(ph)
1513 password_manager = MockPasswordManager()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001514 auth_handler = urllib.request.ProxyBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001515 realm = "ACME Networks"
1516 http_handler = MockHTTPHandler(
1517 407, 'Proxy-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001518 opener.add_handler(auth_handler)
1519 opener.add_handler(http_handler)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001520 self._test_basic_auth(opener, auth_handler, "Proxy-authorization",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001521 realm, http_handler, password_manager,
1522 "http://acme.example.com:3128/protected",
1523 "proxy.example.com:3128",
1524 )
1525
1526 def test_basic_and_digest_auth_handlers(self):
Andrew Svetlov7bd61cb2012-12-19 22:49:25 +02001527 # HTTPDigestAuthHandler raised an exception if it couldn't handle a 40*
Thomas Wouters477c8d52006-05-27 19:21:47 +00001528 # response (http://python.org/sf/1479302), where it should instead
1529 # return None to allow another handler (especially
1530 # HTTPBasicAuthHandler) to handle the response.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001531
1532 # Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must
1533 # try digest first (since it's the strongest auth scheme), so we record
1534 # order of calls here to check digest comes first:
1535 class RecordingOpenerDirector(OpenerDirector):
1536 def __init__(self):
1537 OpenerDirector.__init__(self)
1538 self.recorded = []
Facundo Batista244afcf2015-04-22 18:35:54 -03001539
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001540 def record(self, info):
1541 self.recorded.append(info)
Facundo Batista244afcf2015-04-22 18:35:54 -03001542
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001543 class TestDigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001544 def http_error_401(self, *args, **kwds):
1545 self.parent.record("digest")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001546 urllib.request.HTTPDigestAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001547 *args, **kwds)
Facundo Batista244afcf2015-04-22 18:35:54 -03001548
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001549 class TestBasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001550 def http_error_401(self, *args, **kwds):
1551 self.parent.record("basic")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001552 urllib.request.HTTPBasicAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001553 *args, **kwds)
1554
1555 opener = RecordingOpenerDirector()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001556 password_manager = MockPasswordManager()
1557 digest_handler = TestDigestAuthHandler(password_manager)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001558 basic_handler = TestBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001559 realm = "ACME Networks"
1560 http_handler = MockHTTPHandler(
1561 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001562 opener.add_handler(basic_handler)
1563 opener.add_handler(digest_handler)
1564 opener.add_handler(http_handler)
1565
1566 # check basic auth isn't blocked by digest handler failing
Thomas Wouters477c8d52006-05-27 19:21:47 +00001567 self._test_basic_auth(opener, basic_handler, "Authorization",
1568 realm, http_handler, password_manager,
1569 "http://acme.example.com/protected",
1570 "http://acme.example.com/protected",
1571 )
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001572 # check digest was tried before basic (twice, because
1573 # _test_basic_auth called .open() twice)
1574 self.assertEqual(opener.recorded, ["digest", "basic"]*2)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001575
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001576 def test_unsupported_auth_digest_handler(self):
1577 opener = OpenerDirector()
1578 # While using DigestAuthHandler
1579 digest_auth_handler = urllib.request.HTTPDigestAuthHandler(None)
1580 http_handler = MockHTTPHandler(
1581 401, 'WWW-Authenticate: Kerberos\r\n\r\n')
1582 opener.add_handler(digest_auth_handler)
1583 opener.add_handler(http_handler)
Facundo Batista244afcf2015-04-22 18:35:54 -03001584 self.assertRaises(ValueError, opener.open, "http://www.example.com")
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001585
1586 def test_unsupported_auth_basic_handler(self):
1587 # While using BasicAuthHandler
1588 opener = OpenerDirector()
1589 basic_auth_handler = urllib.request.HTTPBasicAuthHandler(None)
1590 http_handler = MockHTTPHandler(
1591 401, 'WWW-Authenticate: NTLM\r\n\r\n')
1592 opener.add_handler(basic_auth_handler)
1593 opener.add_handler(http_handler)
Facundo Batista244afcf2015-04-22 18:35:54 -03001594 self.assertRaises(ValueError, opener.open, "http://www.example.com")
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001595
Thomas Wouters477c8d52006-05-27 19:21:47 +00001596 def _test_basic_auth(self, opener, auth_handler, auth_header,
1597 realm, http_handler, password_manager,
1598 request_url, protected_url):
Christian Heimes05e8be12008-02-23 18:30:17 +00001599 import base64
Thomas Wouters477c8d52006-05-27 19:21:47 +00001600 user, password = "wile", "coyote"
Thomas Wouters477c8d52006-05-27 19:21:47 +00001601
1602 # .add_password() fed through to password manager
1603 auth_handler.add_password(realm, request_url, user, password)
1604 self.assertEqual(realm, password_manager.realm)
1605 self.assertEqual(request_url, password_manager.url)
1606 self.assertEqual(user, password_manager.user)
1607 self.assertEqual(password, password_manager.password)
1608
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001609 opener.open(request_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001610
1611 # should have asked the password manager for the username/password
1612 self.assertEqual(password_manager.target_realm, realm)
1613 self.assertEqual(password_manager.target_url, protected_url)
1614
1615 # expect one request without authorization, then one with
1616 self.assertEqual(len(http_handler.requests), 2)
1617 self.assertFalse(http_handler.requests[0].has_header(auth_header))
Guido van Rossum98b349f2007-08-27 21:47:52 +00001618 userpass = bytes('%s:%s' % (user, password), "ascii")
Guido van Rossum98297ee2007-11-06 21:34:58 +00001619 auth_hdr_value = ('Basic ' +
Georg Brandl706824f2009-06-04 09:42:55 +00001620 base64.encodebytes(userpass).strip().decode())
Thomas Wouters477c8d52006-05-27 19:21:47 +00001621 self.assertEqual(http_handler.requests[1].get_header(auth_header),
1622 auth_hdr_value)
Senthil Kumaranca2fc9e2010-02-24 16:53:16 +00001623 self.assertEqual(http_handler.requests[1].unredirected_hdrs[auth_header],
1624 auth_hdr_value)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001625 # if the password manager can't find a password, the handler won't
1626 # handle the HTTP auth error
1627 password_manager.user = password_manager.password = None
1628 http_handler.reset()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001629 opener.open(request_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001630 self.assertEqual(len(http_handler.requests), 1)
1631 self.assertFalse(http_handler.requests[0].has_header(auth_header))
1632
R David Murray4c7f9952015-04-16 16:36:18 -04001633 def test_basic_prior_auth_auto_send(self):
1634 # Assume already authenticated if is_authenticated=True
1635 # for APIs like Github that don't return 401
1636
1637 user, password = "wile", "coyote"
1638 request_url = "http://acme.example.com/protected"
1639
1640 http_handler = MockHTTPHandlerCheckAuth(200)
1641
1642 pwd_manager = HTTPPasswordMgrWithPriorAuth()
1643 auth_prior_handler = HTTPBasicAuthHandler(pwd_manager)
1644 auth_prior_handler.add_password(
1645 None, request_url, user, password, is_authenticated=True)
1646
1647 is_auth = pwd_manager.is_authenticated(request_url)
1648 self.assertTrue(is_auth)
1649
1650 opener = OpenerDirector()
1651 opener.add_handler(auth_prior_handler)
1652 opener.add_handler(http_handler)
1653
1654 opener.open(request_url)
1655
1656 # expect request to be sent with auth header
1657 self.assertTrue(http_handler.has_auth_header)
1658
1659 def test_basic_prior_auth_send_after_first_success(self):
1660 # Auto send auth header after authentication is successful once
1661
1662 user, password = 'wile', 'coyote'
1663 request_url = 'http://acme.example.com/protected'
1664 realm = 'ACME'
1665
1666 pwd_manager = HTTPPasswordMgrWithPriorAuth()
1667 auth_prior_handler = HTTPBasicAuthHandler(pwd_manager)
1668 auth_prior_handler.add_password(realm, request_url, user, password)
1669
1670 is_auth = pwd_manager.is_authenticated(request_url)
1671 self.assertFalse(is_auth)
1672
1673 opener = OpenerDirector()
1674 opener.add_handler(auth_prior_handler)
1675
1676 http_handler = MockHTTPHandler(
1677 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % None)
1678 opener.add_handler(http_handler)
1679
1680 opener.open(request_url)
1681
1682 is_auth = pwd_manager.is_authenticated(request_url)
1683 self.assertTrue(is_auth)
1684
1685 http_handler = MockHTTPHandlerCheckAuth(200)
1686 self.assertFalse(http_handler.has_auth_header)
1687
1688 opener = OpenerDirector()
1689 opener.add_handler(auth_prior_handler)
1690 opener.add_handler(http_handler)
1691
1692 # After getting 200 from MockHTTPHandler
1693 # Next request sends header in the first request
1694 opener.open(request_url)
1695
1696 # expect request to be sent with auth header
1697 self.assertTrue(http_handler.has_auth_header)
1698
Serhiy Storchakaf54c3502014-09-06 21:41:39 +03001699 def test_http_closed(self):
1700 """Test the connection is cleaned up when the response is closed"""
1701 for (transfer, data) in (
1702 ("Connection: close", b"data"),
1703 ("Transfer-Encoding: chunked", b"4\r\ndata\r\n0\r\n\r\n"),
1704 ("Content-Length: 4", b"data"),
1705 ):
1706 header = "HTTP/1.1 200 OK\r\n{}\r\n\r\n".format(transfer)
1707 conn = test_urllib.fakehttp(header.encode() + data)
1708 handler = urllib.request.AbstractHTTPHandler()
1709 req = Request("http://dummy/")
1710 req.timeout = None
1711 with handler.do_open(conn, req) as resp:
1712 resp.read()
1713 self.assertTrue(conn.fakesock.closed,
1714 "Connection not closed with {!r}".format(transfer))
1715
1716 def test_invalid_closed(self):
1717 """Test the connection is cleaned up after an invalid response"""
1718 conn = test_urllib.fakehttp(b"")
1719 handler = urllib.request.AbstractHTTPHandler()
1720 req = Request("http://dummy/")
1721 req.timeout = None
1722 with self.assertRaises(http.client.BadStatusLine):
1723 handler.do_open(conn, req)
1724 self.assertTrue(conn.fakesock.closed, "Connection not closed")
1725
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001726
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001727class MiscTests(unittest.TestCase):
1728
Senthil Kumarane9853da2013-03-19 12:07:43 -07001729 def opener_has_handler(self, opener, handler_class):
1730 self.assertTrue(any(h.__class__ == handler_class
1731 for h in opener.handlers))
1732
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001733 def test_build_opener(self):
Facundo Batista244afcf2015-04-22 18:35:54 -03001734 class MyHTTPHandler(urllib.request.HTTPHandler):
1735 pass
1736
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001737 class FooHandler(urllib.request.BaseHandler):
Facundo Batista244afcf2015-04-22 18:35:54 -03001738 def foo_open(self):
1739 pass
1740
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001741 class BarHandler(urllib.request.BaseHandler):
Facundo Batista244afcf2015-04-22 18:35:54 -03001742 def bar_open(self):
1743 pass
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001744
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001745 build_opener = urllib.request.build_opener
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001746
1747 o = build_opener(FooHandler, BarHandler)
1748 self.opener_has_handler(o, FooHandler)
1749 self.opener_has_handler(o, BarHandler)
1750
1751 # can take a mix of classes and instances
1752 o = build_opener(FooHandler, BarHandler())
1753 self.opener_has_handler(o, FooHandler)
1754 self.opener_has_handler(o, BarHandler)
1755
1756 # subclasses of default handlers override default handlers
1757 o = build_opener(MyHTTPHandler)
1758 self.opener_has_handler(o, MyHTTPHandler)
1759
1760 # a particular case of overriding: default handlers can be passed
1761 # in explicitly
1762 o = build_opener()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001763 self.opener_has_handler(o, urllib.request.HTTPHandler)
1764 o = build_opener(urllib.request.HTTPHandler)
1765 self.opener_has_handler(o, urllib.request.HTTPHandler)
1766 o = build_opener(urllib.request.HTTPHandler())
1767 self.opener_has_handler(o, urllib.request.HTTPHandler)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001768
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001769 # Issue2670: multiple handlers sharing the same base class
Facundo Batista244afcf2015-04-22 18:35:54 -03001770 class MyOtherHTTPHandler(urllib.request.HTTPHandler):
1771 pass
1772
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001773 o = build_opener(MyHTTPHandler, MyOtherHTTPHandler)
1774 self.opener_has_handler(o, MyHTTPHandler)
1775 self.opener_has_handler(o, MyOtherHTTPHandler)
1776
Brett Cannon80512de2013-01-25 22:27:21 -05001777 @unittest.skipUnless(support.is_resource_enabled('network'),
1778 'test requires network access')
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001779 def test_issue16464(self):
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001780 with socket_helper.transient_internet("http://www.example.com/"):
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001781 opener = urllib.request.build_opener()
1782 request = urllib.request.Request("http://www.example.com/")
1783 self.assertEqual(None, request.data)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001784
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001785 opener.open(request, "1".encode("us-ascii"))
1786 self.assertEqual(b"1", request.data)
1787 self.assertEqual("1", request.get_header("Content-length"))
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001788
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001789 opener.open(request, "1234567890".encode("us-ascii"))
1790 self.assertEqual(b"1234567890", request.data)
1791 self.assertEqual("10", request.get_header("Content-length"))
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001792
Senthil Kumarane9853da2013-03-19 12:07:43 -07001793 def test_HTTPError_interface(self):
1794 """
1795 Issue 13211 reveals that HTTPError didn't implement the URLError
1796 interface even though HTTPError is a subclass of URLError.
Senthil Kumarane9853da2013-03-19 12:07:43 -07001797 """
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001798 msg = 'something bad happened'
1799 url = code = fp = None
1800 hdrs = 'Content-Length: 42'
1801 err = urllib.error.HTTPError(url, code, msg, hdrs, fp)
1802 self.assertTrue(hasattr(err, 'reason'))
1803 self.assertEqual(err.reason, 'something bad happened')
1804 self.assertTrue(hasattr(err, 'headers'))
1805 self.assertEqual(err.headers, 'Content-Length: 42')
1806 expected_errmsg = 'HTTP Error %s: %s' % (err.code, err.msg)
1807 self.assertEqual(str(err), expected_errmsg)
Facundo Batista244afcf2015-04-22 18:35:54 -03001808 expected_errmsg = '<HTTPError %s: %r>' % (err.code, err.msg)
1809 self.assertEqual(repr(err), expected_errmsg)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001810
Senthil Kumarand8e24f12014-04-14 16:32:20 -04001811 def test_parse_proxy(self):
1812 parse_proxy_test_cases = [
1813 ('proxy.example.com',
1814 (None, None, None, 'proxy.example.com')),
1815 ('proxy.example.com:3128',
1816 (None, None, None, 'proxy.example.com:3128')),
1817 ('proxy.example.com', (None, None, None, 'proxy.example.com')),
1818 ('proxy.example.com:3128',
1819 (None, None, None, 'proxy.example.com:3128')),
1820 # The authority component may optionally include userinfo
1821 # (assumed to be # username:password):
1822 ('joe:password@proxy.example.com',
1823 (None, 'joe', 'password', 'proxy.example.com')),
1824 ('joe:password@proxy.example.com:3128',
1825 (None, 'joe', 'password', 'proxy.example.com:3128')),
1826 #Examples with URLS
1827 ('http://proxy.example.com/',
1828 ('http', None, None, 'proxy.example.com')),
1829 ('http://proxy.example.com:3128/',
1830 ('http', None, None, 'proxy.example.com:3128')),
1831 ('http://joe:password@proxy.example.com/',
1832 ('http', 'joe', 'password', 'proxy.example.com')),
1833 ('http://joe:password@proxy.example.com:3128',
1834 ('http', 'joe', 'password', 'proxy.example.com:3128')),
1835 # Everything after the authority is ignored
1836 ('ftp://joe:password@proxy.example.com/rubbish:3128',
1837 ('ftp', 'joe', 'password', 'proxy.example.com')),
1838 # Test for no trailing '/' case
1839 ('http://joe:password@proxy.example.com',
1840 ('http', 'joe', 'password', 'proxy.example.com'))
1841 ]
1842
1843 for tc, expected in parse_proxy_test_cases:
1844 self.assertEqual(_parse_proxy(tc), expected)
1845
1846 self.assertRaises(ValueError, _parse_proxy, 'file:/ftp.example.com'),
1847
Berker Peksage88dd1c2016-03-06 16:16:40 +02001848 def test_unsupported_algorithm(self):
1849 handler = AbstractDigestAuthHandler()
1850 with self.assertRaises(ValueError) as exc:
1851 handler.get_algorithm_impls('invalid')
1852 self.assertEqual(
1853 str(exc.exception),
1854 "Unsupported digest authentication algorithm 'invalid'"
1855 )
1856
Facundo Batista244afcf2015-04-22 18:35:54 -03001857
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001858class RequestTests(unittest.TestCase):
Jason R. Coombs4a652422013-09-08 13:03:40 -04001859 class PutRequest(Request):
Facundo Batista244afcf2015-04-22 18:35:54 -03001860 method = 'PUT'
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001861
1862 def setUp(self):
1863 self.get = Request("http://www.python.org/~jeremy/")
1864 self.post = Request("http://www.python.org/~jeremy/",
1865 "data",
1866 headers={"X-Test": "test"})
Jason R. Coombs4a652422013-09-08 13:03:40 -04001867 self.head = Request("http://www.python.org/~jeremy/", method='HEAD')
1868 self.put = self.PutRequest("http://www.python.org/~jeremy/")
1869 self.force_post = self.PutRequest("http://www.python.org/~jeremy/",
1870 method="POST")
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001871
1872 def test_method(self):
1873 self.assertEqual("POST", self.post.get_method())
1874 self.assertEqual("GET", self.get.get_method())
Senthil Kumaran0b5463f2013-09-09 23:13:06 -07001875 self.assertEqual("HEAD", self.head.get_method())
Jason R. Coombs4a652422013-09-08 13:03:40 -04001876 self.assertEqual("PUT", self.put.get_method())
1877 self.assertEqual("POST", self.force_post.get_method())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001878
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001879 def test_data(self):
1880 self.assertFalse(self.get.data)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001881 self.assertEqual("GET", self.get.get_method())
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001882 self.get.data = "spam"
1883 self.assertTrue(self.get.data)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001884 self.assertEqual("POST", self.get.get_method())
1885
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001886 # issue 16464
1887 # if we change data we need to remove content-length header
1888 # (cause it's most probably calculated for previous value)
1889 def test_setting_data_should_remove_content_length(self):
R David Murray9cc7d452013-03-20 00:10:51 -04001890 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001891 self.get.add_unredirected_header("Content-length", 42)
1892 self.assertEqual(42, self.get.unredirected_hdrs["Content-length"])
1893 self.get.data = "spam"
R David Murray9cc7d452013-03-20 00:10:51 -04001894 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
1895
1896 # issue 17485 same for deleting data.
1897 def test_deleting_data_should_remove_content_length(self):
1898 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
1899 self.get.data = 'foo'
1900 self.get.add_unredirected_header("Content-length", 3)
1901 self.assertEqual(3, self.get.unredirected_hdrs["Content-length"])
1902 del self.get.data
1903 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001904
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001905 def test_get_full_url(self):
1906 self.assertEqual("http://www.python.org/~jeremy/",
1907 self.get.get_full_url())
1908
1909 def test_selector(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001910 self.assertEqual("/~jeremy/", self.get.selector)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001911 req = Request("http://www.python.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001912 self.assertEqual("/", req.selector)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001913
1914 def test_get_type(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001915 self.assertEqual("http", self.get.type)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001916
1917 def test_get_host(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001918 self.assertEqual("www.python.org", self.get.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001919
1920 def test_get_host_unquote(self):
1921 req = Request("http://www.%70ython.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001922 self.assertEqual("www.python.org", req.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001923
1924 def test_proxy(self):
Florent Xicluna419e3842010-08-08 16:16:07 +00001925 self.assertFalse(self.get.has_proxy())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001926 self.get.set_proxy("www.perl.org", "http")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001927 self.assertTrue(self.get.has_proxy())
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001928 self.assertEqual("www.python.org", self.get.origin_req_host)
1929 self.assertEqual("www.perl.org", self.get.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001930
Senthil Kumarand95cc752010-08-08 11:27:53 +00001931 def test_wrapped_url(self):
1932 req = Request("<URL:http://www.python.org>")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001933 self.assertEqual("www.python.org", req.host)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001934
Senthil Kumaran26430412011-04-13 07:01:19 +08001935 def test_url_fragment(self):
Senthil Kumarand95cc752010-08-08 11:27:53 +00001936 req = Request("http://www.python.org/?qs=query#fragment=true")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001937 self.assertEqual("/?qs=query", req.selector)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001938 req = Request("http://www.python.org/#fun=true")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001939 self.assertEqual("/", req.selector)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001940
Senthil Kumaran26430412011-04-13 07:01:19 +08001941 # Issue 11703: geturl() omits fragment in the original URL.
1942 url = 'http://docs.python.org/library/urllib2.html#OK'
1943 req = Request(url)
1944 self.assertEqual(req.get_full_url(), url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001945
Senthil Kumaran83070752013-05-24 09:14:12 -07001946 def test_url_fullurl_get_full_url(self):
1947 urls = ['http://docs.python.org',
1948 'http://docs.python.org/library/urllib2.html#OK',
Facundo Batista244afcf2015-04-22 18:35:54 -03001949 'http://www.python.org/?qs=query#fragment=true']
Senthil Kumaran83070752013-05-24 09:14:12 -07001950 for url in urls:
1951 req = Request(url)
1952 self.assertEqual(req.get_full_url(), req.full_url)
1953
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001954
1955if __name__ == "__main__":
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001956 unittest.main()