blob: eda7cccc6035a6b5d3742de67a521fb70895f4dc [file] [log] [blame]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002from test import support
Serhiy Storchakaf54c3502014-09-06 21:41:39 +03003from test import test_urllib
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00004
Christian Heimes05e8be12008-02-23 18:30:17 +00005import os
Guido van Rossum34d19282007-08-09 01:03:29 +00006import io
Georg Brandlf78e02b2008-06-10 17:40:04 +00007import socket
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00008import array
Senthil Kumaran4de00a22011-05-11 21:17:57 +08009import sys
Jeremy Hyltone3e61042001-05-09 15:50:25 +000010
Jeremy Hylton1afc1692008-06-18 20:49:58 +000011import urllib.request
Ronald Oussorene72e1612011-03-14 18:15:25 -040012# The proxy bypass method imported below has logic specific to the OSX
13# proxy config data structure but is testable on all platforms.
R David Murray4c7f9952015-04-16 16:36:18 -040014from urllib.request import (Request, OpenerDirector, HTTPBasicAuthHandler,
15 HTTPPasswordMgrWithPriorAuth, _parse_proxy,
Berker Peksage88dd1c2016-03-06 16:16:40 +020016 _proxy_bypass_macosx_sysconf,
17 AbstractDigestAuthHandler)
Senthil Kumaran83070752013-05-24 09:14:12 -070018from urllib.parse import urlparse
guido@google.coma119df92011-03-29 11:41:02 -070019import urllib.error
Serhiy Storchakaf54c3502014-09-06 21:41:39 +030020import http.client
Jeremy Hyltone3e61042001-05-09 15:50:25 +000021
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000022# XXX
23# Request
24# CacheFTPHandler (hard to write)
Thomas Wouters477c8d52006-05-27 19:21:47 +000025# parse_keqv_list, parse_http_list, HTTPDigestAuthHandler
Jeremy Hyltone3e61042001-05-09 15:50:25 +000026
Facundo Batista244afcf2015-04-22 18:35:54 -030027
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000028class TrivialTests(unittest.TestCase):
Senthil Kumaran6c5bd402011-11-01 23:20:31 +080029
30 def test___all__(self):
31 # Verify which names are exposed
32 for module in 'request', 'response', 'parse', 'error', 'robotparser':
33 context = {}
34 exec('from urllib.%s import *' % module, context)
35 del context['__builtins__']
Florent Xicluna3dbb1f12011-11-04 22:15:37 +010036 if module == 'request' and os.name == 'nt':
37 u, p = context.pop('url2pathname'), context.pop('pathname2url')
38 self.assertEqual(u.__module__, 'nturl2path')
39 self.assertEqual(p.__module__, 'nturl2path')
Senthil Kumaran6c5bd402011-11-01 23:20:31 +080040 for k, v in context.items():
41 self.assertEqual(v.__module__, 'urllib.%s' % module,
42 "%r is exposed in 'urllib.%s' but defined in %r" %
43 (k, module, v.__module__))
44
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000045 def test_trivial(self):
46 # A couple trivial tests
Guido van Rossume2ae77b2001-10-24 20:42:55 +000047
Jeremy Hylton1afc1692008-06-18 20:49:58 +000048 self.assertRaises(ValueError, urllib.request.urlopen, 'bogus url')
Tim Peters861adac2001-07-16 20:49:49 +000049
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000050 # XXX Name hacking to get this to work on Windows.
Serhiy Storchaka5106d042015-01-26 10:26:14 +020051 fname = os.path.abspath(urllib.request.__file__).replace(os.sep, '/')
Senthil Kumarand587e302010-01-10 17:45:52 +000052
Senthil Kumarand587e302010-01-10 17:45:52 +000053 if os.name == 'nt':
54 file_url = "file:///%s" % fname
55 else:
56 file_url = "file://%s" % fname
57
Jeremy Hylton1afc1692008-06-18 20:49:58 +000058 f = urllib.request.urlopen(file_url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000059
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -070060 f.read()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000061 f.close()
Tim Petersf5f32b42005-07-17 23:16:17 +000062
Georg Brandle1b13d22005-08-24 22:20:32 +000063 def test_parse_http_list(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +000064 tests = [
65 ('a,b,c', ['a', 'b', 'c']),
66 ('path"o,l"og"i"cal, example', ['path"o,l"og"i"cal', 'example']),
67 ('a, b, "c", "d", "e,f", g, h',
68 ['a', 'b', '"c"', '"d"', '"e,f"', 'g', 'h']),
69 ('a="b\\"c", d="e\\,f", g="h\\\\i"',
70 ['a="b"c"', 'd="e,f"', 'g="h\\i"'])]
Georg Brandle1b13d22005-08-24 22:20:32 +000071 for string, list in tests:
Florent Xicluna419e3842010-08-08 16:16:07 +000072 self.assertEqual(urllib.request.parse_http_list(string), list)
Georg Brandle1b13d22005-08-24 22:20:32 +000073
Senthil Kumaran843fae92013-03-19 13:43:42 -070074 def test_URLError_reasonstr(self):
75 err = urllib.error.URLError('reason')
76 self.assertIn(err.reason, str(err))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000077
Facundo Batista244afcf2015-04-22 18:35:54 -030078
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -070079class RequestHdrsTests(unittest.TestCase):
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000080
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -070081 def test_request_headers_dict(self):
82 """
83 The Request.headers dictionary is not a documented interface. It
84 should stay that way, because the complete set of headers are only
85 accessible through the .get_header(), .has_header(), .header_items()
86 interface. However, .headers pre-dates those methods, and so real code
87 will be using the dictionary.
88
89 The introduction in 2.4 of those methods was a mistake for the same
90 reason: code that previously saw all (urllib2 user)-provided headers in
91 .headers now sees only a subset.
92
93 """
94 url = "http://example.com"
95 self.assertEqual(Request(url,
96 headers={"Spam-eggs": "blah"}
97 ).headers["Spam-eggs"], "blah")
98 self.assertEqual(Request(url,
99 headers={"spam-EggS": "blah"}
100 ).headers["Spam-eggs"], "blah")
101
102 def test_request_headers_methods(self):
103 """
104 Note the case normalization of header names here, to
105 .capitalize()-case. This should be preserved for
106 backwards-compatibility. (In the HTTP case, normalization to
107 .title()-case is done by urllib2 before sending headers to
108 http.client).
109
110 Note that e.g. r.has_header("spam-EggS") is currently False, and
111 r.get_header("spam-EggS") returns None, but that could be changed in
112 future.
113
114 Method r.remove_header should remove items both from r.headers and
115 r.unredirected_hdrs dictionaries
116 """
117 url = "http://example.com"
118 req = Request(url, headers={"Spam-eggs": "blah"})
119 self.assertTrue(req.has_header("Spam-eggs"))
120 self.assertEqual(req.header_items(), [('Spam-eggs', 'blah')])
121
122 req.add_header("Foo-Bar", "baz")
123 self.assertEqual(sorted(req.header_items()),
124 [('Foo-bar', 'baz'), ('Spam-eggs', 'blah')])
125 self.assertFalse(req.has_header("Not-there"))
126 self.assertIsNone(req.get_header("Not-there"))
127 self.assertEqual(req.get_header("Not-there", "default"), "default")
128
129 req.remove_header("Spam-eggs")
130 self.assertFalse(req.has_header("Spam-eggs"))
131
132 req.add_unredirected_header("Unredirected-spam", "Eggs")
133 self.assertTrue(req.has_header("Unredirected-spam"))
134
135 req.remove_header("Unredirected-spam")
136 self.assertFalse(req.has_header("Unredirected-spam"))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000137
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700138 def test_password_manager(self):
139 mgr = urllib.request.HTTPPasswordMgr()
140 add = mgr.add_password
141 find_user_pass = mgr.find_user_password
142 add("Some Realm", "http://example.com/", "joe", "password")
143 add("Some Realm", "http://example.com/ni", "ni", "ni")
144 add("c", "http://example.com/foo", "foo", "ni")
145 add("c", "http://example.com/bar", "bar", "nini")
146 add("b", "http://example.com/", "first", "blah")
147 add("b", "http://example.com/", "second", "spam")
148 add("a", "http://example.com", "1", "a")
149 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 Kumaranfa1b02a2013-04-08 22:24:17 -0700153 self.assertEqual(find_user_pass("Some Realm", "example.com"),
154 ('joe', 'password'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000155
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700156 #self.assertEqual(find_user_pass("Some Realm", "http://example.com/ni"),
157 # ('ni', 'ni'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000158
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700159 self.assertEqual(find_user_pass("Some Realm", "http://example.com"),
160 ('joe', 'password'))
161 self.assertEqual(find_user_pass("Some Realm", "http://example.com/"),
162 ('joe', 'password'))
163 self.assertEqual(
164 find_user_pass("Some Realm", "http://example.com/spam"),
165 ('joe', 'password'))
166 self.assertEqual(
167 find_user_pass("Some Realm", "http://example.com/spam/spam"),
168 ('joe', 'password'))
169 self.assertEqual(find_user_pass("c", "http://example.com/foo"),
170 ('foo', 'ni'))
171 self.assertEqual(find_user_pass("c", "http://example.com/bar"),
172 ('bar', 'nini'))
173 self.assertEqual(find_user_pass("b", "http://example.com/"),
174 ('second', 'spam'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000175
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700176 # No special relationship between a.example.com and example.com:
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000177
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700178 self.assertEqual(find_user_pass("a", "http://example.com/"),
179 ('1', 'a'))
180 self.assertEqual(find_user_pass("a", "http://a.example.com/"),
181 (None, None))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000182
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700183 # Ports:
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000184
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700185 self.assertEqual(find_user_pass("Some Realm", "c.example.com"),
186 (None, None))
187 self.assertEqual(find_user_pass("Some Realm", "c.example.com:3128"),
188 ('3', 'c'))
189 self.assertEqual(
190 find_user_pass("Some Realm", "http://c.example.com:3128"),
191 ('3', 'c'))
192 self.assertEqual(find_user_pass("Some Realm", "d.example.com"),
193 ('4', 'd'))
194 self.assertEqual(find_user_pass("Some Realm", "e.example.com:3128"),
195 ('5', 'e'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000196
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700197 def test_password_manager_default_port(self):
198 """
199 The point to note here is that we can't guess the default port if
200 there's no scheme. This applies to both add_password and
201 find_user_password.
202 """
203 mgr = urllib.request.HTTPPasswordMgr()
204 add = mgr.add_password
205 find_user_pass = mgr.find_user_password
206 add("f", "http://g.example.com:80", "10", "j")
207 add("g", "http://h.example.com", "11", "k")
208 add("h", "i.example.com:80", "12", "l")
209 add("i", "j.example.com", "13", "m")
210 self.assertEqual(find_user_pass("f", "g.example.com:100"),
211 (None, None))
212 self.assertEqual(find_user_pass("f", "g.example.com:80"),
213 ('10', 'j'))
214 self.assertEqual(find_user_pass("f", "g.example.com"),
215 (None, None))
216 self.assertEqual(find_user_pass("f", "http://g.example.com:100"),
217 (None, None))
218 self.assertEqual(find_user_pass("f", "http://g.example.com:80"),
219 ('10', 'j'))
220 self.assertEqual(find_user_pass("f", "http://g.example.com"),
221 ('10', 'j'))
222 self.assertEqual(find_user_pass("g", "h.example.com"), ('11', 'k'))
223 self.assertEqual(find_user_pass("g", "h.example.com:80"), ('11', 'k'))
224 self.assertEqual(find_user_pass("g", "http://h.example.com:80"),
225 ('11', 'k'))
226 self.assertEqual(find_user_pass("h", "i.example.com"), (None, None))
227 self.assertEqual(find_user_pass("h", "i.example.com:80"), ('12', 'l'))
228 self.assertEqual(find_user_pass("h", "http://i.example.com:80"),
229 ('12', 'l'))
230 self.assertEqual(find_user_pass("i", "j.example.com"), ('13', 'm'))
231 self.assertEqual(find_user_pass("i", "j.example.com:80"),
232 (None, None))
233 self.assertEqual(find_user_pass("i", "http://j.example.com"),
234 ('13', 'm'))
235 self.assertEqual(find_user_pass("i", "http://j.example.com:80"),
236 (None, None))
Andrew Svetlovbff98fe2012-11-27 23:06:19 +0200237
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000238
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000239class MockOpener:
240 addheaders = []
Facundo Batista244afcf2015-04-22 18:35:54 -0300241
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000242 def open(self, req, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
243 self.req, self.data, self.timeout = req, data, timeout
Facundo Batista244afcf2015-04-22 18:35:54 -0300244
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000245 def error(self, proto, *args):
246 self.proto, self.args = proto, args
247
Facundo Batista244afcf2015-04-22 18:35:54 -0300248
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000249class MockFile:
Facundo Batista244afcf2015-04-22 18:35:54 -0300250 def read(self, count=None):
251 pass
252
253 def readline(self, count=None):
254 pass
255
256 def close(self):
257 pass
258
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000259
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000260class MockHeaders(dict):
261 def getheaders(self, name):
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000262 return list(self.values())
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000263
Facundo Batista244afcf2015-04-22 18:35:54 -0300264
Guido van Rossum34d19282007-08-09 01:03:29 +0000265class MockResponse(io.StringIO):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000266 def __init__(self, code, msg, headers, data, url=None):
Guido van Rossum34d19282007-08-09 01:03:29 +0000267 io.StringIO.__init__(self, data)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000268 self.code, self.msg, self.headers, self.url = code, msg, headers, url
Facundo Batista244afcf2015-04-22 18:35:54 -0300269
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000270 def info(self):
271 return self.headers
Facundo Batista244afcf2015-04-22 18:35:54 -0300272
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000273 def geturl(self):
274 return self.url
275
Facundo Batista244afcf2015-04-22 18:35:54 -0300276
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000277class MockCookieJar:
278 def add_cookie_header(self, request):
279 self.ach_req = request
Facundo Batista244afcf2015-04-22 18:35:54 -0300280
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000281 def extract_cookies(self, response, request):
282 self.ec_req, self.ec_r = request, response
283
Facundo Batista244afcf2015-04-22 18:35:54 -0300284
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000285class FakeMethod:
286 def __init__(self, meth_name, action, handle):
287 self.meth_name = meth_name
288 self.handle = handle
289 self.action = action
Facundo Batista244afcf2015-04-22 18:35:54 -0300290
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000291 def __call__(self, *args):
292 return self.handle(self.meth_name, self.action, *args)
293
Facundo Batista244afcf2015-04-22 18:35:54 -0300294
Senthil Kumaran47fff872009-12-20 07:10:31 +0000295class MockHTTPResponse(io.IOBase):
296 def __init__(self, fp, msg, status, reason):
297 self.fp = fp
298 self.msg = msg
299 self.status = status
300 self.reason = reason
301 self.code = 200
302
303 def read(self):
304 return ''
305
306 def info(self):
307 return {}
308
309 def geturl(self):
310 return self.url
311
312
313class MockHTTPClass:
314 def __init__(self):
315 self.level = 0
316 self.req_headers = []
317 self.data = None
318 self.raise_on_endheaders = False
Nadeem Vawdabd26b542012-10-21 17:37:43 +0200319 self.sock = None
Senthil Kumaran47fff872009-12-20 07:10:31 +0000320 self._tunnel_headers = {}
321
322 def __call__(self, host, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
323 self.host = host
324 self.timeout = timeout
325 return self
326
327 def set_debuglevel(self, level):
328 self.level = level
329
330 def set_tunnel(self, host, port=None, headers=None):
331 self._tunnel_host = host
332 self._tunnel_port = port
333 if headers:
334 self._tunnel_headers = headers
335 else:
336 self._tunnel_headers.clear()
337
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000338 def request(self, method, url, body=None, headers=None):
Senthil Kumaran47fff872009-12-20 07:10:31 +0000339 self.method = method
340 self.selector = url
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000341 if headers is not None:
342 self.req_headers += headers.items()
Senthil Kumaran47fff872009-12-20 07:10:31 +0000343 self.req_headers.sort()
344 if body:
345 self.data = body
346 if self.raise_on_endheaders:
Andrew Svetlov0832af62012-12-18 23:10:48 +0200347 raise OSError()
Facundo Batista244afcf2015-04-22 18:35:54 -0300348
Senthil Kumaran47fff872009-12-20 07:10:31 +0000349 def getresponse(self):
350 return MockHTTPResponse(MockFile(), {}, 200, "OK")
351
Victor Stinnera4c45d72011-06-17 14:01:18 +0200352 def close(self):
353 pass
354
Facundo Batista244afcf2015-04-22 18:35:54 -0300355
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000356class MockHandler:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000357 # useful for testing handler machinery
358 # see add_ordered_mock_handlers() docstring
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000359 handler_order = 500
Facundo Batista244afcf2015-04-22 18:35:54 -0300360
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000361 def __init__(self, methods):
362 self._define_methods(methods)
Facundo Batista244afcf2015-04-22 18:35:54 -0300363
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000364 def _define_methods(self, methods):
365 for spec in methods:
Facundo Batista244afcf2015-04-22 18:35:54 -0300366 if len(spec) == 2:
367 name, action = spec
368 else:
369 name, action = spec, None
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000370 meth = FakeMethod(name, action, self.handle)
371 setattr(self.__class__, name, meth)
Facundo Batista244afcf2015-04-22 18:35:54 -0300372
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000373 def handle(self, fn_name, action, *args, **kwds):
374 self.parent.calls.append((self, fn_name, args, kwds))
375 if action is None:
376 return None
377 elif action == "return self":
378 return self
379 elif action == "return response":
380 res = MockResponse(200, "OK", {}, "")
381 return res
382 elif action == "return request":
383 return Request("http://blah/")
384 elif action.startswith("error"):
385 code = action[action.rfind(" ")+1:]
386 try:
387 code = int(code)
388 except ValueError:
389 pass
390 res = MockResponse(200, "OK", {}, "")
391 return self.parent.error("http", args[0], res, code, "", {})
392 elif action == "raise":
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000393 raise urllib.error.URLError("blah")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000394 assert False
Facundo Batista244afcf2015-04-22 18:35:54 -0300395
396 def close(self):
397 pass
398
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000399 def add_parent(self, parent):
400 self.parent = parent
401 self.parent.calls = []
Facundo Batista244afcf2015-04-22 18:35:54 -0300402
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000403 def __lt__(self, other):
404 if not hasattr(other, "handler_order"):
405 # No handler_order, leave in original order. Yuck.
406 return True
407 return self.handler_order < other.handler_order
408
Facundo Batista244afcf2015-04-22 18:35:54 -0300409
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000410def add_ordered_mock_handlers(opener, meth_spec):
411 """Create MockHandlers and add them to an OpenerDirector.
412
413 meth_spec: list of lists of tuples and strings defining methods to define
414 on handlers. eg:
415
416 [["http_error", "ftp_open"], ["http_open"]]
417
418 defines methods .http_error() and .ftp_open() on one handler, and
419 .http_open() on another. These methods just record their arguments and
420 return None. Using a tuple instead of a string causes the method to
421 perform some action (see MockHandler.handle()), eg:
422
423 [["http_error"], [("http_open", "return request")]]
424
425 defines .http_error() on one handler (which simply returns None), and
426 .http_open() on another handler, which returns a Request object.
427
428 """
429 handlers = []
430 count = 0
431 for meths in meth_spec:
Facundo Batista244afcf2015-04-22 18:35:54 -0300432 class MockHandlerSubclass(MockHandler):
433 pass
434
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000435 h = MockHandlerSubclass(meths)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000436 h.handler_order += count
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000437 h.add_parent(opener)
438 count = count + 1
439 handlers.append(h)
440 opener.add_handler(h)
441 return handlers
442
Facundo Batista244afcf2015-04-22 18:35:54 -0300443
Thomas Wouters477c8d52006-05-27 19:21:47 +0000444def build_test_opener(*handler_instances):
445 opener = OpenerDirector()
446 for h in handler_instances:
447 opener.add_handler(h)
448 return opener
449
Facundo Batista244afcf2015-04-22 18:35:54 -0300450
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000451class MockHTTPHandler(urllib.request.BaseHandler):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000452 # useful for testing redirections and auth
453 # sends supplied headers and code as first response
454 # sends 200 OK as second response
455 def __init__(self, code, headers):
456 self.code = code
457 self.headers = headers
458 self.reset()
Facundo Batista244afcf2015-04-22 18:35:54 -0300459
Thomas Wouters477c8d52006-05-27 19:21:47 +0000460 def reset(self):
461 self._count = 0
462 self.requests = []
Facundo Batista244afcf2015-04-22 18:35:54 -0300463
Thomas Wouters477c8d52006-05-27 19:21:47 +0000464 def http_open(self, req):
Martin Panterce6e0682016-05-16 01:07:13 +0000465 import email, copy
Thomas Wouters477c8d52006-05-27 19:21:47 +0000466 self.requests.append(copy.deepcopy(req))
467 if self._count == 0:
468 self._count = self._count + 1
Georg Brandl24420152008-05-26 16:32:26 +0000469 name = http.client.responses[self.code]
Barry Warsaw820c1202008-06-12 04:06:45 +0000470 msg = email.message_from_string(self.headers)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000471 return self.parent.error(
472 "http", req, MockFile(), self.code, name, msg)
473 else:
474 self.req = req
Barry Warsaw820c1202008-06-12 04:06:45 +0000475 msg = email.message_from_string("\r\n\r\n")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000476 return MockResponse(200, "OK", msg, "", req.get_full_url())
477
Facundo Batista244afcf2015-04-22 18:35:54 -0300478
Senthil Kumaran47fff872009-12-20 07:10:31 +0000479class MockHTTPSHandler(urllib.request.AbstractHTTPHandler):
480 # Useful for testing the Proxy-Authorization request by verifying the
481 # properties of httpcon
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000482
Senthil Kumaran9642eed2016-05-13 01:32:42 -0700483 def __init__(self, debuglevel=0):
484 urllib.request.AbstractHTTPHandler.__init__(self, debuglevel=debuglevel)
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000485 self.httpconn = MockHTTPClass()
486
Senthil Kumaran47fff872009-12-20 07:10:31 +0000487 def https_open(self, req):
488 return self.do_open(self.httpconn, req)
489
R David Murray4c7f9952015-04-16 16:36:18 -0400490
491class MockHTTPHandlerCheckAuth(urllib.request.BaseHandler):
492 # useful for testing auth
493 # sends supplied code response
494 # checks if auth header is specified in request
495 def __init__(self, code):
496 self.code = code
497 self.has_auth_header = False
498
499 def reset(self):
500 self.has_auth_header = False
501
502 def http_open(self, req):
503 if req.has_header('Authorization'):
504 self.has_auth_header = True
505 name = http.client.responses[self.code]
506 return MockResponse(self.code, name, MockFile(), "", req.get_full_url())
507
508
Facundo Batista244afcf2015-04-22 18:35:54 -0300509
Thomas Wouters477c8d52006-05-27 19:21:47 +0000510class MockPasswordManager:
511 def add_password(self, realm, uri, user, password):
512 self.realm = realm
513 self.url = uri
514 self.user = user
515 self.password = password
Facundo Batista244afcf2015-04-22 18:35:54 -0300516
Thomas Wouters477c8d52006-05-27 19:21:47 +0000517 def find_user_password(self, realm, authuri):
518 self.target_realm = realm
519 self.target_url = authuri
520 return self.user, self.password
521
522
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000523class OpenerDirectorTests(unittest.TestCase):
524
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000525 def test_add_non_handler(self):
526 class NonHandler(object):
527 pass
528 self.assertRaises(TypeError,
529 OpenerDirector().add_handler, NonHandler())
530
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000531 def test_badly_named_methods(self):
532 # test work-around for three methods that accidentally follow the
533 # naming conventions for handler methods
534 # (*_open() / *_request() / *_response())
535
536 # These used to call the accidentally-named methods, causing a
537 # TypeError in real code; here, returning self from these mock
538 # methods would either cause no exception, or AttributeError.
539
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000540 from urllib.error import URLError
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000541
542 o = OpenerDirector()
543 meth_spec = [
544 [("do_open", "return self"), ("proxy_open", "return self")],
545 [("redirect_request", "return self")],
546 ]
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700547 add_ordered_mock_handlers(o, meth_spec)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000548 o.add_handler(urllib.request.UnknownHandler())
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000549 for scheme in "do", "proxy", "redirect":
550 self.assertRaises(URLError, o.open, scheme+"://example.com/")
551
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000552 def test_handled(self):
553 # handler returning non-None means no more handlers will be called
554 o = OpenerDirector()
555 meth_spec = [
556 ["http_open", "ftp_open", "http_error_302"],
557 ["ftp_open"],
558 [("http_open", "return self")],
559 [("http_open", "return self")],
560 ]
561 handlers = add_ordered_mock_handlers(o, meth_spec)
562
563 req = Request("http://example.com/")
564 r = o.open(req)
565 # Second .http_open() gets called, third doesn't, since second returned
566 # non-None. Handlers without .http_open() never get any methods called
567 # on them.
568 # In fact, second mock handler defining .http_open() returns self
569 # (instead of response), which becomes the OpenerDirector's return
570 # value.
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000571 self.assertEqual(r, handlers[2])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000572 calls = [(handlers[0], "http_open"), (handlers[2], "http_open")]
573 for expected, got in zip(calls, o.calls):
574 handler, name, args, kwds = got
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000575 self.assertEqual((handler, name), expected)
576 self.assertEqual(args, (req,))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000577
578 def test_handler_order(self):
579 o = OpenerDirector()
580 handlers = []
Facundo Batista244afcf2015-04-22 18:35:54 -0300581 for meths, handler_order in [([("http_open", "return self")], 500),
582 (["http_open"], 0)]:
583 class MockHandlerSubclass(MockHandler):
584 pass
585
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000586 h = MockHandlerSubclass(meths)
587 h.handler_order = handler_order
588 handlers.append(h)
589 o.add_handler(h)
590
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700591 o.open("http://example.com/")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000592 # handlers called in reverse order, thanks to their sort order
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000593 self.assertEqual(o.calls[0][0], handlers[1])
594 self.assertEqual(o.calls[1][0], handlers[0])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000595
596 def test_raise(self):
597 # raising URLError stops processing of request
598 o = OpenerDirector()
599 meth_spec = [
600 [("http_open", "raise")],
601 [("http_open", "return self")],
602 ]
603 handlers = add_ordered_mock_handlers(o, meth_spec)
604
605 req = Request("http://example.com/")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000606 self.assertRaises(urllib.error.URLError, o.open, req)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000607 self.assertEqual(o.calls, [(handlers[0], "http_open", (req,), {})])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000608
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000609 def test_http_error(self):
610 # XXX http_error_default
611 # http errors are a special case
612 o = OpenerDirector()
613 meth_spec = [
614 [("http_open", "error 302")],
615 [("http_error_400", "raise"), "http_open"],
616 [("http_error_302", "return response"), "http_error_303",
617 "http_error"],
618 [("http_error_302")],
619 ]
620 handlers = add_ordered_mock_handlers(o, meth_spec)
621
622 class Unknown:
Facundo Batista244afcf2015-04-22 18:35:54 -0300623 def __eq__(self, other):
624 return True
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000625
626 req = Request("http://example.com/")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700627 o.open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000628 assert len(o.calls) == 2
629 calls = [(handlers[0], "http_open", (req,)),
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000630 (handlers[2], "http_error_302",
631 (req, Unknown(), 302, "", {}))]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000632 for expected, got in zip(calls, o.calls):
633 handler, method_name, args = expected
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000634 self.assertEqual((handler, method_name), got[:2])
635 self.assertEqual(args, got[2])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000636
637 def test_processors(self):
638 # *_request / *_response methods get called appropriately
639 o = OpenerDirector()
640 meth_spec = [
641 [("http_request", "return request"),
642 ("http_response", "return response")],
643 [("http_request", "return request"),
644 ("http_response", "return response")],
645 ]
646 handlers = add_ordered_mock_handlers(o, meth_spec)
647
648 req = Request("http://example.com/")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700649 o.open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000650 # processor methods are called on *all* handlers that define them,
651 # not just the first handler that handles the request
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000652 calls = [
653 (handlers[0], "http_request"), (handlers[1], "http_request"),
654 (handlers[0], "http_response"), (handlers[1], "http_response")]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000655
656 for i, (handler, name, args, kwds) in enumerate(o.calls):
657 if i < 2:
658 # *_request
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000659 self.assertEqual((handler, name), calls[i])
660 self.assertEqual(len(args), 1)
Ezio Melottie9615932010-01-24 19:26:24 +0000661 self.assertIsInstance(args[0], Request)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000662 else:
663 # *_response
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000664 self.assertEqual((handler, name), calls[i])
665 self.assertEqual(len(args), 2)
Ezio Melottie9615932010-01-24 19:26:24 +0000666 self.assertIsInstance(args[0], Request)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000667 # response from opener.open is None, because there's no
668 # handler that defines http_open to handle it
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200669 if args[1] is not None:
670 self.assertIsInstance(args[1], MockResponse)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000671
Facundo Batista244afcf2015-04-22 18:35:54 -0300672
Tim Peters58eb11c2004-01-18 20:29:55 +0000673def sanepathname2url(path):
Victor Stinner6c6f8512010-08-07 10:09:35 +0000674 try:
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000675 path.encode("utf-8")
Victor Stinner6c6f8512010-08-07 10:09:35 +0000676 except UnicodeEncodeError:
677 raise unittest.SkipTest("path is not encodable to utf8")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000678 urlpath = urllib.request.pathname2url(path)
Tim Peters58eb11c2004-01-18 20:29:55 +0000679 if os.name == "nt" and urlpath.startswith("///"):
680 urlpath = urlpath[2:]
681 # XXX don't ask me about the mac...
682 return urlpath
683
Facundo Batista244afcf2015-04-22 18:35:54 -0300684
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000685class HandlerTests(unittest.TestCase):
686
687 def test_ftp(self):
688 class MockFTPWrapper:
Facundo Batista244afcf2015-04-22 18:35:54 -0300689 def __init__(self, data):
690 self.data = data
691
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000692 def retrfile(self, filename, filetype):
693 self.filename, self.filetype = filename, filetype
Guido van Rossum34d19282007-08-09 01:03:29 +0000694 return io.StringIO(self.data), len(self.data)
Facundo Batista244afcf2015-04-22 18:35:54 -0300695
696 def close(self):
697 pass
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000698
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000699 class NullFTPHandler(urllib.request.FTPHandler):
Facundo Batista244afcf2015-04-22 18:35:54 -0300700 def __init__(self, data):
701 self.data = data
702
Georg Brandlf78e02b2008-06-10 17:40:04 +0000703 def connect_ftp(self, user, passwd, host, port, dirs,
704 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000705 self.user, self.passwd = user, passwd
706 self.host, self.port = host, port
707 self.dirs = dirs
708 self.ftpwrapper = MockFTPWrapper(self.data)
709 return self.ftpwrapper
710
Georg Brandlf78e02b2008-06-10 17:40:04 +0000711 import ftplib
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000712 data = "rheum rhaponicum"
713 h = NullFTPHandler(data)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700714 h.parent = MockOpener()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000715
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000716 for url, host, port, user, passwd, type_, dirs, filename, mimetype in [
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000717 ("ftp://localhost/foo/bar/baz.html",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000718 "localhost", ftplib.FTP_PORT, "", "", "I",
719 ["foo", "bar"], "baz.html", "text/html"),
720 ("ftp://parrot@localhost/foo/bar/baz.html",
721 "localhost", ftplib.FTP_PORT, "parrot", "", "I",
722 ["foo", "bar"], "baz.html", "text/html"),
723 ("ftp://%25parrot@localhost/foo/bar/baz.html",
724 "localhost", ftplib.FTP_PORT, "%parrot", "", "I",
725 ["foo", "bar"], "baz.html", "text/html"),
726 ("ftp://%2542parrot@localhost/foo/bar/baz.html",
727 "localhost", ftplib.FTP_PORT, "%42parrot", "", "I",
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000728 ["foo", "bar"], "baz.html", "text/html"),
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000729 ("ftp://localhost:80/foo/bar/",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000730 "localhost", 80, "", "", "D",
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000731 ["foo", "bar"], "", None),
732 ("ftp://localhost/baz.gif;type=a",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000733 "localhost", ftplib.FTP_PORT, "", "", "A",
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000734 [], "baz.gif", None), # XXX really this should guess image/gif
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000735 ]:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000736 req = Request(url)
737 req.timeout = None
738 r = h.ftp_open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000739 # ftp authentication not yet implemented by FTPHandler
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000740 self.assertEqual(h.user, user)
741 self.assertEqual(h.passwd, passwd)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000742 self.assertEqual(h.host, socket.gethostbyname(host))
743 self.assertEqual(h.port, port)
744 self.assertEqual(h.dirs, dirs)
745 self.assertEqual(h.ftpwrapper.filename, filename)
746 self.assertEqual(h.ftpwrapper.filetype, type_)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000747 headers = r.info()
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000748 self.assertEqual(headers.get("Content-type"), mimetype)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000749 self.assertEqual(int(headers["Content-length"]), len(data))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000750
751 def test_file(self):
Senthil Kumaranbc07ac52014-07-22 00:15:20 -0700752 import email.utils
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000753 h = urllib.request.FileHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000754 o = h.parent = MockOpener()
755
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000756 TESTFN = support.TESTFN
Tim Peters58eb11c2004-01-18 20:29:55 +0000757 urlpath = sanepathname2url(os.path.abspath(TESTFN))
Guido van Rossum6a2ccd02007-07-16 20:51:57 +0000758 towrite = b"hello, world\n"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000759 urls = [
Tim Peters58eb11c2004-01-18 20:29:55 +0000760 "file://localhost%s" % urlpath,
761 "file://%s" % urlpath,
762 "file://%s%s" % (socket.gethostbyname('localhost'), urlpath),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000763 ]
764 try:
765 localaddr = socket.gethostbyname(socket.gethostname())
766 except socket.gaierror:
767 localaddr = ''
768 if localaddr:
769 urls.append("file://%s%s" % (localaddr, urlpath))
770
771 for url in urls:
Tim Peters58eb11c2004-01-18 20:29:55 +0000772 f = open(TESTFN, "wb")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000773 try:
774 try:
775 f.write(towrite)
776 finally:
777 f.close()
778
779 r = h.file_open(Request(url))
780 try:
781 data = r.read()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000782 headers = r.info()
Senthil Kumaran4fbed102010-05-08 03:29:09 +0000783 respurl = r.geturl()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000784 finally:
785 r.close()
Tim Peters58eb11c2004-01-18 20:29:55 +0000786 stats = os.stat(TESTFN)
Benjamin Petersona0c0a4a2008-06-12 22:15:50 +0000787 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000788 finally:
789 os.remove(TESTFN)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000790 self.assertEqual(data, towrite)
791 self.assertEqual(headers["Content-type"], "text/plain")
792 self.assertEqual(headers["Content-length"], "13")
Tim Peters58eb11c2004-01-18 20:29:55 +0000793 self.assertEqual(headers["Last-modified"], modified)
Senthil Kumaran4fbed102010-05-08 03:29:09 +0000794 self.assertEqual(respurl, url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000795
796 for url in [
Tim Peters58eb11c2004-01-18 20:29:55 +0000797 "file://localhost:80%s" % urlpath,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000798 "file:///file_does_not_exist.txt",
Senthil Kumaranbc07ac52014-07-22 00:15:20 -0700799 "file://not-a-local-host.com//dir/file.txt",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000800 "file://%s:80%s/%s" % (socket.gethostbyname('localhost'),
801 os.getcwd(), TESTFN),
802 "file://somerandomhost.ontheinternet.com%s/%s" %
803 (os.getcwd(), TESTFN),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000804 ]:
805 try:
Tim Peters58eb11c2004-01-18 20:29:55 +0000806 f = open(TESTFN, "wb")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000807 try:
808 f.write(towrite)
809 finally:
810 f.close()
811
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000812 self.assertRaises(urllib.error.URLError,
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000813 h.file_open, Request(url))
814 finally:
815 os.remove(TESTFN)
816
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000817 h = urllib.request.FileHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000818 o = h.parent = MockOpener()
819 # XXXX why does // mean ftp (and /// mean not ftp!), and where
820 # is file: scheme specified? I think this is really a bug, and
821 # what was intended was to distinguish between URLs like:
822 # file:/blah.txt (a file)
823 # file://localhost/blah.txt (a file)
824 # file:///blah.txt (a file)
825 # file://ftp.example.com/blah.txt (an ftp URL)
826 for url, ftp in [
Senthil Kumaran383c32d2010-10-14 11:57:35 +0000827 ("file://ftp.example.com//foo.txt", False),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000828 ("file://ftp.example.com///foo.txt", False),
829# XXXX bug: fails with OSError, should be URLError
830 ("file://ftp.example.com/foo.txt", False),
Senthil Kumaran383c32d2010-10-14 11:57:35 +0000831 ("file://somehost//foo/something.txt", False),
Senthil Kumaran2ef16322010-07-11 03:12:43 +0000832 ("file://localhost//foo/something.txt", False),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000833 ]:
834 req = Request(url)
835 try:
836 h.file_open(req)
837 # XXXX remove OSError when bug fixed
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000838 except (urllib.error.URLError, OSError):
Florent Xicluna419e3842010-08-08 16:16:07 +0000839 self.assertFalse(ftp)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000840 else:
Florent Xicluna419e3842010-08-08 16:16:07 +0000841 self.assertIs(o.req, req)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000842 self.assertEqual(req.type, "ftp")
Łukasz Langad7e81cc2011-01-09 18:18:53 +0000843 self.assertEqual(req.type == "ftp", ftp)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000844
845 def test_http(self):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000846
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000847 h = urllib.request.AbstractHTTPHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000848 o = h.parent = MockOpener()
849
850 url = "http://example.com/"
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000851 for method, data in [("GET", None), ("POST", b"blah")]:
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000852 req = Request(url, data, {"Foo": "bar"})
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000853 req.timeout = None
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000854 req.add_unredirected_header("Spam", "eggs")
855 http = MockHTTPClass()
856 r = h.do_open(http, req)
857
858 # result attributes
859 r.read; r.readline # wrapped MockFile methods
860 r.info; r.geturl # addinfourl methods
861 r.code, r.msg == 200, "OK" # added from MockHTTPClass.getreply()
862 hdrs = r.info()
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000863 hdrs.get; hdrs.__contains__ # r.info() gives dict from .getreply()
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000864 self.assertEqual(r.geturl(), url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000865
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000866 self.assertEqual(http.host, "example.com")
867 self.assertEqual(http.level, 0)
868 self.assertEqual(http.method, method)
869 self.assertEqual(http.selector, "/")
870 self.assertEqual(http.req_headers,
Jeremy Hyltonb3ee6f92004-02-24 19:40:35 +0000871 [("Connection", "close"),
872 ("Foo", "bar"), ("Spam", "eggs")])
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000873 self.assertEqual(http.data, data)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000874
Andrew Svetlov0832af62012-12-18 23:10:48 +0200875 # check OSError converted to URLError
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000876 http.raise_on_endheaders = True
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000877 self.assertRaises(urllib.error.URLError, h.do_open, http, req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000878
Senthil Kumaran29333122011-02-11 11:25:47 +0000879 # Check for TypeError on POST data which is str.
880 req = Request("http://example.com/","badpost")
881 self.assertRaises(TypeError, h.do_request_, req)
882
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000883 # check adding of standard headers
884 o.addheaders = [("Spam", "eggs")]
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000885 for data in b"", None: # POST, GET
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000886 req = Request("http://example.com/", data)
887 r = MockResponse(200, "OK", {}, "")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000888 newreq = h.do_request_(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000889 if data is None: # GET
Benjamin Peterson577473f2010-01-19 00:09:57 +0000890 self.assertNotIn("Content-length", req.unredirected_hdrs)
891 self.assertNotIn("Content-type", req.unredirected_hdrs)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000892 else: # POST
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000893 self.assertEqual(req.unredirected_hdrs["Content-length"], "0")
894 self.assertEqual(req.unredirected_hdrs["Content-type"],
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000895 "application/x-www-form-urlencoded")
896 # XXX the details of Host could be better tested
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000897 self.assertEqual(req.unredirected_hdrs["Host"], "example.com")
898 self.assertEqual(req.unredirected_hdrs["Spam"], "eggs")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000899
900 # don't clobber existing headers
901 req.add_unredirected_header("Content-length", "foo")
902 req.add_unredirected_header("Content-type", "bar")
903 req.add_unredirected_header("Host", "baz")
904 req.add_unredirected_header("Spam", "foo")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000905 newreq = h.do_request_(req)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000906 self.assertEqual(req.unredirected_hdrs["Content-length"], "foo")
907 self.assertEqual(req.unredirected_hdrs["Content-type"], "bar")
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000908 self.assertEqual(req.unredirected_hdrs["Host"], "baz")
909 self.assertEqual(req.unredirected_hdrs["Spam"], "foo")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000910
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000911 # Check iterable body support
912 def iterable_body():
913 yield b"one"
914 yield b"two"
915 yield b"three"
916
917 for headers in {}, {"Content-Length": 11}:
918 req = Request("http://example.com/", iterable_body(), headers)
919 if not headers:
920 # Having an iterable body without a Content-Length should
921 # raise an exception
922 self.assertRaises(ValueError, h.do_request_, req)
923 else:
924 newreq = h.do_request_(req)
925
Senthil Kumaran29333122011-02-11 11:25:47 +0000926 # A file object.
927 # Test only Content-Length attribute of request.
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000928
Senthil Kumaran29333122011-02-11 11:25:47 +0000929 file_obj = io.BytesIO()
930 file_obj.write(b"Something\nSomething\nSomething\n")
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000931
932 for headers in {}, {"Content-Length": 30}:
933 req = Request("http://example.com/", file_obj, headers)
934 if not headers:
935 # Having an iterable body without a Content-Length should
936 # raise an exception
937 self.assertRaises(ValueError, h.do_request_, req)
938 else:
939 newreq = h.do_request_(req)
Facundo Batista244afcf2015-04-22 18:35:54 -0300940 self.assertEqual(int(newreq.get_header('Content-length')), 30)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000941
942 file_obj.close()
943
944 # array.array Iterable - Content Length is calculated
945
946 iterable_array = array.array("I",[1,2,3,4])
947
948 for headers in {}, {"Content-Length": 16}:
949 req = Request("http://example.com/", iterable_array, headers)
950 newreq = h.do_request_(req)
951 self.assertEqual(int(newreq.get_header('Content-length')),16)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000952
Senthil Kumaran9642eed2016-05-13 01:32:42 -0700953 def test_http_handler_debuglevel(self):
954 o = OpenerDirector()
955 h = MockHTTPSHandler(debuglevel=1)
956 o.add_handler(h)
957 o.open("https://www.example.com")
958 self.assertEqual(h._debuglevel, 1)
959
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000960 def test_http_doubleslash(self):
961 # Checks the presence of any unnecessary double slash in url does not
962 # break anything. Previously, a double slash directly after the host
Ezio Melottie130a522011-10-19 10:58:56 +0300963 # could cause incorrect parsing.
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000964 h = urllib.request.AbstractHTTPHandler()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700965 h.parent = MockOpener()
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000966
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000967 data = b""
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000968 ds_urls = [
969 "http://example.com/foo/bar/baz.html",
970 "http://example.com//foo/bar/baz.html",
971 "http://example.com/foo//bar/baz.html",
972 "http://example.com/foo/bar//baz.html"
973 ]
974
975 for ds_url in ds_urls:
976 ds_req = Request(ds_url, data)
977
978 # Check whether host is determined correctly if there is no proxy
979 np_ds_req = h.do_request_(ds_req)
Facundo Batista244afcf2015-04-22 18:35:54 -0300980 self.assertEqual(np_ds_req.unredirected_hdrs["Host"], "example.com")
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000981
982 # Check whether host is determined correctly if there is a proxy
Facundo Batista244afcf2015-04-22 18:35:54 -0300983 ds_req.set_proxy("someproxy:3128", None)
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000984 p_ds_req = h.do_request_(ds_req)
Facundo Batista244afcf2015-04-22 18:35:54 -0300985 self.assertEqual(p_ds_req.unredirected_hdrs["Host"], "example.com")
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000986
Senthil Kumaran52380922013-04-25 05:45:48 -0700987 def test_full_url_setter(self):
988 # Checks to ensure that components are set correctly after setting the
989 # full_url of a Request object
990
991 urls = [
992 'http://example.com?foo=bar#baz',
993 'http://example.com?foo=bar&spam=eggs#bash',
994 'http://example.com',
995 ]
996
997 # testing a reusable request instance, but the url parameter is
998 # required, so just use a dummy one to instantiate
999 r = Request('http://example.com')
1000 for url in urls:
1001 r.full_url = url
Senthil Kumaran83070752013-05-24 09:14:12 -07001002 parsed = urlparse(url)
1003
Senthil Kumaran52380922013-04-25 05:45:48 -07001004 self.assertEqual(r.get_full_url(), url)
Senthil Kumaran83070752013-05-24 09:14:12 -07001005 # full_url setter uses splittag to split into components.
1006 # splittag sets the fragment as None while urlparse sets it to ''
1007 self.assertEqual(r.fragment or '', parsed.fragment)
1008 self.assertEqual(urlparse(r.get_full_url()).query, parsed.query)
Senthil Kumaran52380922013-04-25 05:45:48 -07001009
1010 def test_full_url_deleter(self):
1011 r = Request('http://www.example.com')
1012 del r.full_url
1013 self.assertIsNone(r.full_url)
1014 self.assertIsNone(r.fragment)
1015 self.assertEqual(r.selector, '')
1016
Senthil Kumaranc2958622010-11-22 04:48:26 +00001017 def test_fixpath_in_weirdurls(self):
1018 # Issue4493: urllib2 to supply '/' when to urls where path does not
1019 # start with'/'
1020
1021 h = urllib.request.AbstractHTTPHandler()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001022 h.parent = MockOpener()
Senthil Kumaranc2958622010-11-22 04:48:26 +00001023
1024 weird_url = 'http://www.python.org?getspam'
1025 req = Request(weird_url)
1026 newreq = h.do_request_(req)
Facundo Batista244afcf2015-04-22 18:35:54 -03001027 self.assertEqual(newreq.host, 'www.python.org')
1028 self.assertEqual(newreq.selector, '/?getspam')
Senthil Kumaranc2958622010-11-22 04:48:26 +00001029
1030 url_without_path = 'http://www.python.org'
1031 req = Request(url_without_path)
1032 newreq = h.do_request_(req)
Facundo Batista244afcf2015-04-22 18:35:54 -03001033 self.assertEqual(newreq.host, 'www.python.org')
1034 self.assertEqual(newreq.selector, '')
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001035
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001036 def test_errors(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001037 h = urllib.request.HTTPErrorProcessor()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001038 o = h.parent = MockOpener()
1039
1040 url = "http://example.com/"
1041 req = Request(url)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001042 # all 2xx are passed through
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001043 r = MockResponse(200, "OK", {}, "", url)
1044 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +00001045 self.assertIs(r, newr)
1046 self.assertFalse(hasattr(o, "proto")) # o.error not called
Guido van Rossumd8faa362007-04-27 19:54:29 +00001047 r = MockResponse(202, "Accepted", {}, "", url)
1048 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +00001049 self.assertIs(r, newr)
1050 self.assertFalse(hasattr(o, "proto")) # o.error not called
Guido van Rossumd8faa362007-04-27 19:54:29 +00001051 r = MockResponse(206, "Partial content", {}, "", url)
1052 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +00001053 self.assertIs(r, newr)
1054 self.assertFalse(hasattr(o, "proto")) # o.error not called
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001055 # anything else calls o.error (and MockOpener returns None, here)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001056 r = MockResponse(502, "Bad gateway", {}, "", url)
Florent Xicluna419e3842010-08-08 16:16:07 +00001057 self.assertIsNone(h.http_response(req, r))
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001058 self.assertEqual(o.proto, "http") # o.error called
Guido van Rossumd8faa362007-04-27 19:54:29 +00001059 self.assertEqual(o.args, (req, r, 502, "Bad gateway", {}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001060
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001061 def test_cookies(self):
1062 cj = MockCookieJar()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001063 h = urllib.request.HTTPCookieProcessor(cj)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001064 h.parent = MockOpener()
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001065
1066 req = Request("http://example.com/")
1067 r = MockResponse(200, "OK", {}, "")
1068 newreq = h.http_request(req)
Florent Xicluna419e3842010-08-08 16:16:07 +00001069 self.assertIs(cj.ach_req, req)
1070 self.assertIs(cj.ach_req, newreq)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001071 self.assertEqual(req.origin_req_host, "example.com")
1072 self.assertFalse(req.unverifiable)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001073 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +00001074 self.assertIs(cj.ec_req, req)
1075 self.assertIs(cj.ec_r, r)
1076 self.assertIs(r, newr)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001077
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001078 def test_redirect(self):
1079 from_url = "http://example.com/a.html"
1080 to_url = "http://example.com/b.html"
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001081 h = urllib.request.HTTPRedirectHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001082 o = h.parent = MockOpener()
1083
1084 # ordinary redirect behaviour
1085 for code in 301, 302, 303, 307:
1086 for data in None, "blah\nblah\n":
1087 method = getattr(h, "http_error_%s" % code)
1088 req = Request(from_url, data)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001089 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001090 req.add_header("Nonsense", "viking=withhold")
Christian Heimes77c02eb2008-02-09 02:18:51 +00001091 if data is not None:
1092 req.add_header("Content-Length", str(len(data)))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001093 req.add_unredirected_header("Spam", "spam")
1094 try:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001095 method(req, MockFile(), code, "Blah",
1096 MockHeaders({"location": to_url}))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001097 except urllib.error.HTTPError:
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001098 # 307 in response to POST requires user OK
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001099 self.assertEqual(code, 307)
1100 self.assertIsNotNone(data)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001101 self.assertEqual(o.req.get_full_url(), to_url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001102 try:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001103 self.assertEqual(o.req.get_method(), "GET")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001104 except AttributeError:
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001105 self.assertFalse(o.req.data)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001106
1107 # now it's a GET, there should not be headers regarding content
1108 # (possibly dragged from before being a POST)
1109 headers = [x.lower() for x in o.req.headers]
Benjamin Peterson577473f2010-01-19 00:09:57 +00001110 self.assertNotIn("content-length", headers)
1111 self.assertNotIn("content-type", headers)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001112
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001113 self.assertEqual(o.req.headers["Nonsense"],
1114 "viking=withhold")
Benjamin Peterson577473f2010-01-19 00:09:57 +00001115 self.assertNotIn("Spam", o.req.headers)
1116 self.assertNotIn("Spam", o.req.unredirected_hdrs)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001117
1118 # loop detection
1119 req = Request(from_url)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001120 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Facundo Batista244afcf2015-04-22 18:35:54 -03001121
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001122 def redirect(h, req, url=to_url):
1123 h.http_error_302(req, MockFile(), 302, "Blah",
1124 MockHeaders({"location": url}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001125 # Note that the *original* request shares the same record of
1126 # redirections with the sub-requests caused by the redirections.
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001127
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001128 # detect infinite loop redirect of a URL to itself
1129 req = Request(from_url, origin_req_host="example.com")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001130 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001131 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001132 try:
1133 while 1:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001134 redirect(h, req, "http://example.com/")
1135 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001136 except urllib.error.HTTPError:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001137 # don't stop until max_repeats, because cookies may introduce state
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001138 self.assertEqual(count, urllib.request.HTTPRedirectHandler.max_repeats)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001139
1140 # detect endless non-repeating chain of redirects
1141 req = Request(from_url, origin_req_host="example.com")
1142 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001143 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001144 try:
1145 while 1:
1146 redirect(h, req, "http://example.com/%d" % count)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001147 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001148 except urllib.error.HTTPError:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001149 self.assertEqual(count,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001150 urllib.request.HTTPRedirectHandler.max_redirections)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001151
guido@google.coma119df92011-03-29 11:41:02 -07001152 def test_invalid_redirect(self):
1153 from_url = "http://example.com/a.html"
1154 valid_schemes = ['http','https','ftp']
1155 invalid_schemes = ['file','imap','ldap']
1156 schemeless_url = "example.com/b.html"
1157 h = urllib.request.HTTPRedirectHandler()
1158 o = h.parent = MockOpener()
1159 req = Request(from_url)
1160 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1161
1162 for scheme in invalid_schemes:
1163 invalid_url = scheme + '://' + schemeless_url
1164 self.assertRaises(urllib.error.HTTPError, h.http_error_302,
1165 req, MockFile(), 302, "Security Loophole",
1166 MockHeaders({"location": invalid_url}))
1167
1168 for scheme in valid_schemes:
1169 valid_url = scheme + '://' + schemeless_url
1170 h.http_error_302(req, MockFile(), 302, "That's fine",
1171 MockHeaders({"location": valid_url}))
1172 self.assertEqual(o.req.get_full_url(), valid_url)
1173
Senthil Kumaran6497aa32012-01-04 13:46:59 +08001174 def test_relative_redirect(self):
1175 from_url = "http://example.com/a.html"
1176 relative_url = "/b.html"
1177 h = urllib.request.HTTPRedirectHandler()
1178 o = h.parent = MockOpener()
1179 req = Request(from_url)
1180 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1181
1182 valid_url = urllib.parse.urljoin(from_url,relative_url)
1183 h.http_error_302(req, MockFile(), 302, "That's fine",
1184 MockHeaders({"location": valid_url}))
1185 self.assertEqual(o.req.get_full_url(), valid_url)
1186
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001187 def test_cookie_redirect(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001188 # cookies shouldn't leak into redirected requests
Georg Brandl24420152008-05-26 16:32:26 +00001189 from http.cookiejar import CookieJar
1190 from test.test_http_cookiejar import interact_netscape
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001191
1192 cj = CookieJar()
1193 interact_netscape(cj, "http://www.example.com/", "spam=eggs")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001194 hh = MockHTTPHandler(302, "Location: http://www.cracker.com/\r\n\r\n")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001195 hdeh = urllib.request.HTTPDefaultErrorHandler()
1196 hrh = urllib.request.HTTPRedirectHandler()
1197 cp = urllib.request.HTTPCookieProcessor(cj)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001198 o = build_test_opener(hh, hdeh, hrh, cp)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001199 o.open("http://www.example.com/")
Florent Xicluna419e3842010-08-08 16:16:07 +00001200 self.assertFalse(hh.req.has_header("Cookie"))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001201
Senthil Kumaran26430412011-04-13 07:01:19 +08001202 def test_redirect_fragment(self):
1203 redirected_url = 'http://www.example.com/index.html#OK\r\n\r\n'
1204 hh = MockHTTPHandler(302, 'Location: ' + redirected_url)
1205 hdeh = urllib.request.HTTPDefaultErrorHandler()
1206 hrh = urllib.request.HTTPRedirectHandler()
1207 o = build_test_opener(hh, hdeh, hrh)
1208 fp = o.open('http://www.example.com')
1209 self.assertEqual(fp.geturl(), redirected_url.strip())
1210
Martin Panterce6e0682016-05-16 01:07:13 +00001211 def test_redirect_no_path(self):
1212 # Issue 14132: Relative redirect strips original path
1213 real_class = http.client.HTTPConnection
1214 response1 = b"HTTP/1.1 302 Found\r\nLocation: ?query\r\n\r\n"
1215 http.client.HTTPConnection = test_urllib.fakehttp(response1)
1216 self.addCleanup(setattr, http.client, "HTTPConnection", real_class)
1217 urls = iter(("/path", "/path?query"))
1218 def request(conn, method, url, *pos, **kw):
1219 self.assertEqual(url, next(urls))
1220 real_class.request(conn, method, url, *pos, **kw)
1221 # Change response for subsequent connection
1222 conn.__class__.fakedata = b"HTTP/1.1 200 OK\r\n\r\nHello!"
1223 http.client.HTTPConnection.request = request
1224 fp = urllib.request.urlopen("http://python.org/path")
1225 self.assertEqual(fp.geturl(), "http://python.org/path?query")
1226
Martin Pantere6f06092016-05-16 01:14:20 +00001227 def test_redirect_encoding(self):
1228 # Some characters in the redirect target may need special handling,
1229 # but most ASCII characters should be treated as already encoded
1230 class Handler(urllib.request.HTTPHandler):
1231 def http_open(self, req):
1232 result = self.do_open(self.connection, req)
1233 self.last_buf = self.connection.buf
1234 # Set up a normal response for the next request
1235 self.connection = test_urllib.fakehttp(
1236 b'HTTP/1.1 200 OK\r\n'
1237 b'Content-Length: 3\r\n'
1238 b'\r\n'
1239 b'123'
1240 )
1241 return result
1242 handler = Handler()
1243 opener = urllib.request.build_opener(handler)
1244 tests = (
1245 (b'/p\xC3\xA5-dansk/', b'/p%C3%A5-dansk/'),
1246 (b'/spaced%20path/', b'/spaced%20path/'),
1247 (b'/spaced path/', b'/spaced%20path/'),
1248 (b'/?p\xC3\xA5-dansk', b'/?p%C3%A5-dansk'),
1249 )
1250 for [location, result] in tests:
1251 with self.subTest(repr(location)):
1252 handler.connection = test_urllib.fakehttp(
1253 b'HTTP/1.1 302 Redirect\r\n'
1254 b'Location: ' + location + b'\r\n'
1255 b'\r\n'
1256 )
1257 response = opener.open('http://example.com/')
1258 expected = b'GET ' + result + b' '
1259 request = handler.last_buf
1260 self.assertTrue(request.startswith(expected), repr(request))
1261
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001262 def test_proxy(self):
1263 o = OpenerDirector()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001264 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001265 o.add_handler(ph)
1266 meth_spec = [
1267 [("http_open", "return response")]
1268 ]
1269 handlers = add_ordered_mock_handlers(o, meth_spec)
1270
1271 req = Request("http://acme.example.com/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001272 self.assertEqual(req.host, "acme.example.com")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001273 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001274 self.assertEqual(req.host, "proxy.example.com:3128")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001275
1276 self.assertEqual([(handlers[0], "http_open")],
1277 [tup[0:2] for tup in o.calls])
1278
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001279 def test_proxy_no_proxy(self):
1280 os.environ['no_proxy'] = 'python.org'
1281 o = OpenerDirector()
1282 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1283 o.add_handler(ph)
1284 req = Request("http://www.perl.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001285 self.assertEqual(req.host, "www.perl.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001286 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001287 self.assertEqual(req.host, "proxy.example.com")
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001288 req = Request("http://www.python.org")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001289 self.assertEqual(req.host, "www.python.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001290 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001291 self.assertEqual(req.host, "www.python.org")
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001292 del os.environ['no_proxy']
1293
Ronald Oussorene72e1612011-03-14 18:15:25 -04001294 def test_proxy_no_proxy_all(self):
1295 os.environ['no_proxy'] = '*'
1296 o = OpenerDirector()
1297 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1298 o.add_handler(ph)
1299 req = Request("http://www.python.org")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001300 self.assertEqual(req.host, "www.python.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001301 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001302 self.assertEqual(req.host, "www.python.org")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001303 del os.environ['no_proxy']
1304
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001305 def test_proxy_https(self):
1306 o = OpenerDirector()
1307 ph = urllib.request.ProxyHandler(dict(https="proxy.example.com:3128"))
1308 o.add_handler(ph)
1309 meth_spec = [
1310 [("https_open", "return response")]
1311 ]
1312 handlers = add_ordered_mock_handlers(o, meth_spec)
1313
1314 req = Request("https://www.example.com/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001315 self.assertEqual(req.host, "www.example.com")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001316 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001317 self.assertEqual(req.host, "proxy.example.com:3128")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001318 self.assertEqual([(handlers[0], "https_open")],
1319 [tup[0:2] for tup in o.calls])
1320
Senthil Kumaran47fff872009-12-20 07:10:31 +00001321 def test_proxy_https_proxy_authorization(self):
1322 o = OpenerDirector()
1323 ph = urllib.request.ProxyHandler(dict(https='proxy.example.com:3128'))
1324 o.add_handler(ph)
1325 https_handler = MockHTTPSHandler()
1326 o.add_handler(https_handler)
1327 req = Request("https://www.example.com/")
Facundo Batista244afcf2015-04-22 18:35:54 -03001328 req.add_header("Proxy-Authorization", "FooBar")
1329 req.add_header("User-Agent", "Grail")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001330 self.assertEqual(req.host, "www.example.com")
Senthil Kumaran47fff872009-12-20 07:10:31 +00001331 self.assertIsNone(req._tunnel_host)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001332 o.open(req)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001333 # Verify Proxy-Authorization gets tunneled to request.
1334 # httpsconn req_headers do not have the Proxy-Authorization header but
1335 # the req will have.
Facundo Batista244afcf2015-04-22 18:35:54 -03001336 self.assertNotIn(("Proxy-Authorization", "FooBar"),
Senthil Kumaran47fff872009-12-20 07:10:31 +00001337 https_handler.httpconn.req_headers)
Facundo Batista244afcf2015-04-22 18:35:54 -03001338 self.assertIn(("User-Agent", "Grail"),
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001339 https_handler.httpconn.req_headers)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001340 self.assertIsNotNone(req._tunnel_host)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001341 self.assertEqual(req.host, "proxy.example.com:3128")
Facundo Batista244afcf2015-04-22 18:35:54 -03001342 self.assertEqual(req.get_header("Proxy-authorization"), "FooBar")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001343
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001344 # TODO: This should be only for OSX
1345 @unittest.skipUnless(sys.platform == 'darwin', "only relevant for OSX")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001346 def test_osx_proxy_bypass(self):
1347 bypass = {
1348 'exclude_simple': False,
1349 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.10',
1350 '10.0/16']
1351 }
1352 # Check hosts that should trigger the proxy bypass
1353 for host in ('foo.bar', 'www.bar.com', '127.0.0.1', '10.10.0.1',
1354 '10.0.0.1'):
1355 self.assertTrue(_proxy_bypass_macosx_sysconf(host, bypass),
1356 'expected bypass of %s to be True' % host)
1357 # Check hosts that should not trigger the proxy bypass
R David Murrayfdbe9182014-03-15 12:00:14 -04001358 for host in ('abc.foo.bar', 'bar.com', '127.0.0.2', '10.11.0.1',
1359 'notinbypass'):
Ronald Oussorene72e1612011-03-14 18:15:25 -04001360 self.assertFalse(_proxy_bypass_macosx_sysconf(host, bypass),
1361 'expected bypass of %s to be False' % host)
1362
1363 # Check the exclude_simple flag
1364 bypass = {'exclude_simple': True, 'exceptions': []}
1365 self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass))
1366
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001367 def test_basic_auth(self, quote_char='"'):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001368 opener = OpenerDirector()
1369 password_manager = MockPasswordManager()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001370 auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001371 realm = "ACME Widget Store"
1372 http_handler = MockHTTPHandler(
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001373 401, 'WWW-Authenticate: Basic realm=%s%s%s\r\n\r\n' %
Facundo Batista244afcf2015-04-22 18:35:54 -03001374 (quote_char, realm, quote_char))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001375 opener.add_handler(auth_handler)
1376 opener.add_handler(http_handler)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001377 self._test_basic_auth(opener, auth_handler, "Authorization",
1378 realm, http_handler, password_manager,
1379 "http://acme.example.com/protected",
1380 "http://acme.example.com/protected",
1381 )
1382
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001383 def test_basic_auth_with_single_quoted_realm(self):
1384 self.test_basic_auth(quote_char="'")
1385
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +08001386 def test_basic_auth_with_unquoted_realm(self):
1387 opener = OpenerDirector()
1388 password_manager = MockPasswordManager()
1389 auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
1390 realm = "ACME Widget Store"
1391 http_handler = MockHTTPHandler(
1392 401, 'WWW-Authenticate: Basic realm=%s\r\n\r\n' % realm)
1393 opener.add_handler(auth_handler)
1394 opener.add_handler(http_handler)
Senthil Kumaran0ea91cb2012-05-15 23:59:42 +08001395 with self.assertWarns(UserWarning):
1396 self._test_basic_auth(opener, auth_handler, "Authorization",
1397 realm, http_handler, password_manager,
1398 "http://acme.example.com/protected",
1399 "http://acme.example.com/protected",
1400 )
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +08001401
Thomas Wouters477c8d52006-05-27 19:21:47 +00001402 def test_proxy_basic_auth(self):
1403 opener = OpenerDirector()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001404 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001405 opener.add_handler(ph)
1406 password_manager = MockPasswordManager()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001407 auth_handler = urllib.request.ProxyBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001408 realm = "ACME Networks"
1409 http_handler = MockHTTPHandler(
1410 407, 'Proxy-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001411 opener.add_handler(auth_handler)
1412 opener.add_handler(http_handler)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001413 self._test_basic_auth(opener, auth_handler, "Proxy-authorization",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001414 realm, http_handler, password_manager,
1415 "http://acme.example.com:3128/protected",
1416 "proxy.example.com:3128",
1417 )
1418
1419 def test_basic_and_digest_auth_handlers(self):
Andrew Svetlov7bd61cb2012-12-19 22:49:25 +02001420 # HTTPDigestAuthHandler raised an exception if it couldn't handle a 40*
Thomas Wouters477c8d52006-05-27 19:21:47 +00001421 # response (http://python.org/sf/1479302), where it should instead
1422 # return None to allow another handler (especially
1423 # HTTPBasicAuthHandler) to handle the response.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001424
1425 # Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must
1426 # try digest first (since it's the strongest auth scheme), so we record
1427 # order of calls here to check digest comes first:
1428 class RecordingOpenerDirector(OpenerDirector):
1429 def __init__(self):
1430 OpenerDirector.__init__(self)
1431 self.recorded = []
Facundo Batista244afcf2015-04-22 18:35:54 -03001432
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001433 def record(self, info):
1434 self.recorded.append(info)
Facundo Batista244afcf2015-04-22 18:35:54 -03001435
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001436 class TestDigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001437 def http_error_401(self, *args, **kwds):
1438 self.parent.record("digest")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001439 urllib.request.HTTPDigestAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001440 *args, **kwds)
Facundo Batista244afcf2015-04-22 18:35:54 -03001441
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001442 class TestBasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001443 def http_error_401(self, *args, **kwds):
1444 self.parent.record("basic")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001445 urllib.request.HTTPBasicAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001446 *args, **kwds)
1447
1448 opener = RecordingOpenerDirector()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001449 password_manager = MockPasswordManager()
1450 digest_handler = TestDigestAuthHandler(password_manager)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001451 basic_handler = TestBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001452 realm = "ACME Networks"
1453 http_handler = MockHTTPHandler(
1454 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001455 opener.add_handler(basic_handler)
1456 opener.add_handler(digest_handler)
1457 opener.add_handler(http_handler)
1458
1459 # check basic auth isn't blocked by digest handler failing
Thomas Wouters477c8d52006-05-27 19:21:47 +00001460 self._test_basic_auth(opener, basic_handler, "Authorization",
1461 realm, http_handler, password_manager,
1462 "http://acme.example.com/protected",
1463 "http://acme.example.com/protected",
1464 )
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001465 # check digest was tried before basic (twice, because
1466 # _test_basic_auth called .open() twice)
1467 self.assertEqual(opener.recorded, ["digest", "basic"]*2)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001468
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001469 def test_unsupported_auth_digest_handler(self):
1470 opener = OpenerDirector()
1471 # While using DigestAuthHandler
1472 digest_auth_handler = urllib.request.HTTPDigestAuthHandler(None)
1473 http_handler = MockHTTPHandler(
1474 401, 'WWW-Authenticate: Kerberos\r\n\r\n')
1475 opener.add_handler(digest_auth_handler)
1476 opener.add_handler(http_handler)
Facundo Batista244afcf2015-04-22 18:35:54 -03001477 self.assertRaises(ValueError, opener.open, "http://www.example.com")
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001478
1479 def test_unsupported_auth_basic_handler(self):
1480 # While using BasicAuthHandler
1481 opener = OpenerDirector()
1482 basic_auth_handler = urllib.request.HTTPBasicAuthHandler(None)
1483 http_handler = MockHTTPHandler(
1484 401, 'WWW-Authenticate: NTLM\r\n\r\n')
1485 opener.add_handler(basic_auth_handler)
1486 opener.add_handler(http_handler)
Facundo Batista244afcf2015-04-22 18:35:54 -03001487 self.assertRaises(ValueError, opener.open, "http://www.example.com")
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001488
Thomas Wouters477c8d52006-05-27 19:21:47 +00001489 def _test_basic_auth(self, opener, auth_handler, auth_header,
1490 realm, http_handler, password_manager,
1491 request_url, protected_url):
Christian Heimes05e8be12008-02-23 18:30:17 +00001492 import base64
Thomas Wouters477c8d52006-05-27 19:21:47 +00001493 user, password = "wile", "coyote"
Thomas Wouters477c8d52006-05-27 19:21:47 +00001494
1495 # .add_password() fed through to password manager
1496 auth_handler.add_password(realm, request_url, user, password)
1497 self.assertEqual(realm, password_manager.realm)
1498 self.assertEqual(request_url, password_manager.url)
1499 self.assertEqual(user, password_manager.user)
1500 self.assertEqual(password, password_manager.password)
1501
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001502 opener.open(request_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001503
1504 # should have asked the password manager for the username/password
1505 self.assertEqual(password_manager.target_realm, realm)
1506 self.assertEqual(password_manager.target_url, protected_url)
1507
1508 # expect one request without authorization, then one with
1509 self.assertEqual(len(http_handler.requests), 2)
1510 self.assertFalse(http_handler.requests[0].has_header(auth_header))
Guido van Rossum98b349f2007-08-27 21:47:52 +00001511 userpass = bytes('%s:%s' % (user, password), "ascii")
Guido van Rossum98297ee2007-11-06 21:34:58 +00001512 auth_hdr_value = ('Basic ' +
Georg Brandl706824f2009-06-04 09:42:55 +00001513 base64.encodebytes(userpass).strip().decode())
Thomas Wouters477c8d52006-05-27 19:21:47 +00001514 self.assertEqual(http_handler.requests[1].get_header(auth_header),
1515 auth_hdr_value)
Senthil Kumaranca2fc9e2010-02-24 16:53:16 +00001516 self.assertEqual(http_handler.requests[1].unredirected_hdrs[auth_header],
1517 auth_hdr_value)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001518 # if the password manager can't find a password, the handler won't
1519 # handle the HTTP auth error
1520 password_manager.user = password_manager.password = None
1521 http_handler.reset()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001522 opener.open(request_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001523 self.assertEqual(len(http_handler.requests), 1)
1524 self.assertFalse(http_handler.requests[0].has_header(auth_header))
1525
R David Murray4c7f9952015-04-16 16:36:18 -04001526 def test_basic_prior_auth_auto_send(self):
1527 # Assume already authenticated if is_authenticated=True
1528 # for APIs like Github that don't return 401
1529
1530 user, password = "wile", "coyote"
1531 request_url = "http://acme.example.com/protected"
1532
1533 http_handler = MockHTTPHandlerCheckAuth(200)
1534
1535 pwd_manager = HTTPPasswordMgrWithPriorAuth()
1536 auth_prior_handler = HTTPBasicAuthHandler(pwd_manager)
1537 auth_prior_handler.add_password(
1538 None, request_url, user, password, is_authenticated=True)
1539
1540 is_auth = pwd_manager.is_authenticated(request_url)
1541 self.assertTrue(is_auth)
1542
1543 opener = OpenerDirector()
1544 opener.add_handler(auth_prior_handler)
1545 opener.add_handler(http_handler)
1546
1547 opener.open(request_url)
1548
1549 # expect request to be sent with auth header
1550 self.assertTrue(http_handler.has_auth_header)
1551
1552 def test_basic_prior_auth_send_after_first_success(self):
1553 # Auto send auth header after authentication is successful once
1554
1555 user, password = 'wile', 'coyote'
1556 request_url = 'http://acme.example.com/protected'
1557 realm = 'ACME'
1558
1559 pwd_manager = HTTPPasswordMgrWithPriorAuth()
1560 auth_prior_handler = HTTPBasicAuthHandler(pwd_manager)
1561 auth_prior_handler.add_password(realm, request_url, user, password)
1562
1563 is_auth = pwd_manager.is_authenticated(request_url)
1564 self.assertFalse(is_auth)
1565
1566 opener = OpenerDirector()
1567 opener.add_handler(auth_prior_handler)
1568
1569 http_handler = MockHTTPHandler(
1570 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % None)
1571 opener.add_handler(http_handler)
1572
1573 opener.open(request_url)
1574
1575 is_auth = pwd_manager.is_authenticated(request_url)
1576 self.assertTrue(is_auth)
1577
1578 http_handler = MockHTTPHandlerCheckAuth(200)
1579 self.assertFalse(http_handler.has_auth_header)
1580
1581 opener = OpenerDirector()
1582 opener.add_handler(auth_prior_handler)
1583 opener.add_handler(http_handler)
1584
1585 # After getting 200 from MockHTTPHandler
1586 # Next request sends header in the first request
1587 opener.open(request_url)
1588
1589 # expect request to be sent with auth header
1590 self.assertTrue(http_handler.has_auth_header)
1591
Serhiy Storchakaf54c3502014-09-06 21:41:39 +03001592 def test_http_closed(self):
1593 """Test the connection is cleaned up when the response is closed"""
1594 for (transfer, data) in (
1595 ("Connection: close", b"data"),
1596 ("Transfer-Encoding: chunked", b"4\r\ndata\r\n0\r\n\r\n"),
1597 ("Content-Length: 4", b"data"),
1598 ):
1599 header = "HTTP/1.1 200 OK\r\n{}\r\n\r\n".format(transfer)
1600 conn = test_urllib.fakehttp(header.encode() + data)
1601 handler = urllib.request.AbstractHTTPHandler()
1602 req = Request("http://dummy/")
1603 req.timeout = None
1604 with handler.do_open(conn, req) as resp:
1605 resp.read()
1606 self.assertTrue(conn.fakesock.closed,
1607 "Connection not closed with {!r}".format(transfer))
1608
1609 def test_invalid_closed(self):
1610 """Test the connection is cleaned up after an invalid response"""
1611 conn = test_urllib.fakehttp(b"")
1612 handler = urllib.request.AbstractHTTPHandler()
1613 req = Request("http://dummy/")
1614 req.timeout = None
1615 with self.assertRaises(http.client.BadStatusLine):
1616 handler.do_open(conn, req)
1617 self.assertTrue(conn.fakesock.closed, "Connection not closed")
1618
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001619
Facundo Batista244afcf2015-04-22 18:35:54 -03001620
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001621class MiscTests(unittest.TestCase):
1622
Senthil Kumarane9853da2013-03-19 12:07:43 -07001623 def opener_has_handler(self, opener, handler_class):
1624 self.assertTrue(any(h.__class__ == handler_class
1625 for h in opener.handlers))
1626
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001627 def test_build_opener(self):
Facundo Batista244afcf2015-04-22 18:35:54 -03001628 class MyHTTPHandler(urllib.request.HTTPHandler):
1629 pass
1630
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001631 class FooHandler(urllib.request.BaseHandler):
Facundo Batista244afcf2015-04-22 18:35:54 -03001632 def foo_open(self):
1633 pass
1634
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001635 class BarHandler(urllib.request.BaseHandler):
Facundo Batista244afcf2015-04-22 18:35:54 -03001636 def bar_open(self):
1637 pass
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001638
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001639 build_opener = urllib.request.build_opener
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001640
1641 o = build_opener(FooHandler, BarHandler)
1642 self.opener_has_handler(o, FooHandler)
1643 self.opener_has_handler(o, BarHandler)
1644
1645 # can take a mix of classes and instances
1646 o = build_opener(FooHandler, BarHandler())
1647 self.opener_has_handler(o, FooHandler)
1648 self.opener_has_handler(o, BarHandler)
1649
1650 # subclasses of default handlers override default handlers
1651 o = build_opener(MyHTTPHandler)
1652 self.opener_has_handler(o, MyHTTPHandler)
1653
1654 # a particular case of overriding: default handlers can be passed
1655 # in explicitly
1656 o = build_opener()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001657 self.opener_has_handler(o, urllib.request.HTTPHandler)
1658 o = build_opener(urllib.request.HTTPHandler)
1659 self.opener_has_handler(o, urllib.request.HTTPHandler)
1660 o = build_opener(urllib.request.HTTPHandler())
1661 self.opener_has_handler(o, urllib.request.HTTPHandler)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001662
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001663 # Issue2670: multiple handlers sharing the same base class
Facundo Batista244afcf2015-04-22 18:35:54 -03001664 class MyOtherHTTPHandler(urllib.request.HTTPHandler):
1665 pass
1666
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001667 o = build_opener(MyHTTPHandler, MyOtherHTTPHandler)
1668 self.opener_has_handler(o, MyHTTPHandler)
1669 self.opener_has_handler(o, MyOtherHTTPHandler)
1670
Brett Cannon80512de2013-01-25 22:27:21 -05001671 @unittest.skipUnless(support.is_resource_enabled('network'),
1672 'test requires network access')
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001673 def test_issue16464(self):
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001674 with support.transient_internet("http://www.example.com/"):
1675 opener = urllib.request.build_opener()
1676 request = urllib.request.Request("http://www.example.com/")
1677 self.assertEqual(None, request.data)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001678
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001679 opener.open(request, "1".encode("us-ascii"))
1680 self.assertEqual(b"1", request.data)
1681 self.assertEqual("1", request.get_header("Content-length"))
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001682
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001683 opener.open(request, "1234567890".encode("us-ascii"))
1684 self.assertEqual(b"1234567890", request.data)
1685 self.assertEqual("10", request.get_header("Content-length"))
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001686
Senthil Kumarane9853da2013-03-19 12:07:43 -07001687 def test_HTTPError_interface(self):
1688 """
1689 Issue 13211 reveals that HTTPError didn't implement the URLError
1690 interface even though HTTPError is a subclass of URLError.
Senthil Kumarane9853da2013-03-19 12:07:43 -07001691 """
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001692 msg = 'something bad happened'
1693 url = code = fp = None
1694 hdrs = 'Content-Length: 42'
1695 err = urllib.error.HTTPError(url, code, msg, hdrs, fp)
1696 self.assertTrue(hasattr(err, 'reason'))
1697 self.assertEqual(err.reason, 'something bad happened')
1698 self.assertTrue(hasattr(err, 'headers'))
1699 self.assertEqual(err.headers, 'Content-Length: 42')
1700 expected_errmsg = 'HTTP Error %s: %s' % (err.code, err.msg)
1701 self.assertEqual(str(err), expected_errmsg)
Facundo Batista244afcf2015-04-22 18:35:54 -03001702 expected_errmsg = '<HTTPError %s: %r>' % (err.code, err.msg)
1703 self.assertEqual(repr(err), expected_errmsg)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001704
Senthil Kumarand8e24f12014-04-14 16:32:20 -04001705 def test_parse_proxy(self):
1706 parse_proxy_test_cases = [
1707 ('proxy.example.com',
1708 (None, None, None, 'proxy.example.com')),
1709 ('proxy.example.com:3128',
1710 (None, None, None, 'proxy.example.com:3128')),
1711 ('proxy.example.com', (None, None, None, 'proxy.example.com')),
1712 ('proxy.example.com:3128',
1713 (None, None, None, 'proxy.example.com:3128')),
1714 # The authority component may optionally include userinfo
1715 # (assumed to be # username:password):
1716 ('joe:password@proxy.example.com',
1717 (None, 'joe', 'password', 'proxy.example.com')),
1718 ('joe:password@proxy.example.com:3128',
1719 (None, 'joe', 'password', 'proxy.example.com:3128')),
1720 #Examples with URLS
1721 ('http://proxy.example.com/',
1722 ('http', None, None, 'proxy.example.com')),
1723 ('http://proxy.example.com:3128/',
1724 ('http', None, None, 'proxy.example.com:3128')),
1725 ('http://joe:password@proxy.example.com/',
1726 ('http', 'joe', 'password', 'proxy.example.com')),
1727 ('http://joe:password@proxy.example.com:3128',
1728 ('http', 'joe', 'password', 'proxy.example.com:3128')),
1729 # Everything after the authority is ignored
1730 ('ftp://joe:password@proxy.example.com/rubbish:3128',
1731 ('ftp', 'joe', 'password', 'proxy.example.com')),
1732 # Test for no trailing '/' case
1733 ('http://joe:password@proxy.example.com',
1734 ('http', 'joe', 'password', 'proxy.example.com'))
1735 ]
1736
1737 for tc, expected in parse_proxy_test_cases:
1738 self.assertEqual(_parse_proxy(tc), expected)
1739
1740 self.assertRaises(ValueError, _parse_proxy, 'file:/ftp.example.com'),
1741
Berker Peksage88dd1c2016-03-06 16:16:40 +02001742 def test_unsupported_algorithm(self):
1743 handler = AbstractDigestAuthHandler()
1744 with self.assertRaises(ValueError) as exc:
1745 handler.get_algorithm_impls('invalid')
1746 self.assertEqual(
1747 str(exc.exception),
1748 "Unsupported digest authentication algorithm 'invalid'"
1749 )
1750
Facundo Batista244afcf2015-04-22 18:35:54 -03001751
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001752class RequestTests(unittest.TestCase):
Jason R. Coombs4a652422013-09-08 13:03:40 -04001753 class PutRequest(Request):
Facundo Batista244afcf2015-04-22 18:35:54 -03001754 method = 'PUT'
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001755
1756 def setUp(self):
1757 self.get = Request("http://www.python.org/~jeremy/")
1758 self.post = Request("http://www.python.org/~jeremy/",
1759 "data",
1760 headers={"X-Test": "test"})
Jason R. Coombs4a652422013-09-08 13:03:40 -04001761 self.head = Request("http://www.python.org/~jeremy/", method='HEAD')
1762 self.put = self.PutRequest("http://www.python.org/~jeremy/")
1763 self.force_post = self.PutRequest("http://www.python.org/~jeremy/",
1764 method="POST")
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001765
1766 def test_method(self):
1767 self.assertEqual("POST", self.post.get_method())
1768 self.assertEqual("GET", self.get.get_method())
Senthil Kumaran0b5463f2013-09-09 23:13:06 -07001769 self.assertEqual("HEAD", self.head.get_method())
Jason R. Coombs4a652422013-09-08 13:03:40 -04001770 self.assertEqual("PUT", self.put.get_method())
1771 self.assertEqual("POST", self.force_post.get_method())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001772
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001773 def test_data(self):
1774 self.assertFalse(self.get.data)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001775 self.assertEqual("GET", self.get.get_method())
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001776 self.get.data = "spam"
1777 self.assertTrue(self.get.data)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001778 self.assertEqual("POST", self.get.get_method())
1779
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001780 # issue 16464
1781 # if we change data we need to remove content-length header
1782 # (cause it's most probably calculated for previous value)
1783 def test_setting_data_should_remove_content_length(self):
R David Murray9cc7d452013-03-20 00:10:51 -04001784 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001785 self.get.add_unredirected_header("Content-length", 42)
1786 self.assertEqual(42, self.get.unredirected_hdrs["Content-length"])
1787 self.get.data = "spam"
R David Murray9cc7d452013-03-20 00:10:51 -04001788 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
1789
1790 # issue 17485 same for deleting data.
1791 def test_deleting_data_should_remove_content_length(self):
1792 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
1793 self.get.data = 'foo'
1794 self.get.add_unredirected_header("Content-length", 3)
1795 self.assertEqual(3, self.get.unredirected_hdrs["Content-length"])
1796 del self.get.data
1797 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001798
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001799 def test_get_full_url(self):
1800 self.assertEqual("http://www.python.org/~jeremy/",
1801 self.get.get_full_url())
1802
1803 def test_selector(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001804 self.assertEqual("/~jeremy/", self.get.selector)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001805 req = Request("http://www.python.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001806 self.assertEqual("/", req.selector)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001807
1808 def test_get_type(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001809 self.assertEqual("http", self.get.type)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001810
1811 def test_get_host(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001812 self.assertEqual("www.python.org", self.get.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001813
1814 def test_get_host_unquote(self):
1815 req = Request("http://www.%70ython.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001816 self.assertEqual("www.python.org", req.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001817
1818 def test_proxy(self):
Florent Xicluna419e3842010-08-08 16:16:07 +00001819 self.assertFalse(self.get.has_proxy())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001820 self.get.set_proxy("www.perl.org", "http")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001821 self.assertTrue(self.get.has_proxy())
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001822 self.assertEqual("www.python.org", self.get.origin_req_host)
1823 self.assertEqual("www.perl.org", self.get.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001824
Senthil Kumarand95cc752010-08-08 11:27:53 +00001825 def test_wrapped_url(self):
1826 req = Request("<URL:http://www.python.org>")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001827 self.assertEqual("www.python.org", req.host)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001828
Senthil Kumaran26430412011-04-13 07:01:19 +08001829 def test_url_fragment(self):
Senthil Kumarand95cc752010-08-08 11:27:53 +00001830 req = Request("http://www.python.org/?qs=query#fragment=true")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001831 self.assertEqual("/?qs=query", req.selector)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001832 req = Request("http://www.python.org/#fun=true")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001833 self.assertEqual("/", req.selector)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001834
Senthil Kumaran26430412011-04-13 07:01:19 +08001835 # Issue 11703: geturl() omits fragment in the original URL.
1836 url = 'http://docs.python.org/library/urllib2.html#OK'
1837 req = Request(url)
1838 self.assertEqual(req.get_full_url(), url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001839
Senthil Kumaran83070752013-05-24 09:14:12 -07001840 def test_url_fullurl_get_full_url(self):
1841 urls = ['http://docs.python.org',
1842 'http://docs.python.org/library/urllib2.html#OK',
Facundo Batista244afcf2015-04-22 18:35:54 -03001843 'http://www.python.org/?qs=query#fragment=true']
Senthil Kumaran83070752013-05-24 09:14:12 -07001844 for url in urls:
1845 req = Request(url)
1846 self.assertEqual(req.get_full_url(), req.full_url)
1847
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001848
1849if __name__ == "__main__":
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001850 unittest.main()