blob: 008c751f9c6f16522e46fa2fb718028836dec606 [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):
Barry Warsaw820c1202008-06-12 04:06:45 +0000465 import email, http.client, 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
483 def __init__(self):
484 urllib.request.AbstractHTTPHandler.__init__(self)
485 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
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000953 def test_http_doubleslash(self):
954 # Checks the presence of any unnecessary double slash in url does not
955 # break anything. Previously, a double slash directly after the host
Ezio Melottie130a522011-10-19 10:58:56 +0300956 # could cause incorrect parsing.
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000957 h = urllib.request.AbstractHTTPHandler()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700958 h.parent = MockOpener()
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000959
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000960 data = b""
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000961 ds_urls = [
962 "http://example.com/foo/bar/baz.html",
963 "http://example.com//foo/bar/baz.html",
964 "http://example.com/foo//bar/baz.html",
965 "http://example.com/foo/bar//baz.html"
966 ]
967
968 for ds_url in ds_urls:
969 ds_req = Request(ds_url, data)
970
971 # Check whether host is determined correctly if there is no proxy
972 np_ds_req = h.do_request_(ds_req)
Facundo Batista244afcf2015-04-22 18:35:54 -0300973 self.assertEqual(np_ds_req.unredirected_hdrs["Host"], "example.com")
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000974
975 # Check whether host is determined correctly if there is a proxy
Facundo Batista244afcf2015-04-22 18:35:54 -0300976 ds_req.set_proxy("someproxy:3128", None)
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000977 p_ds_req = h.do_request_(ds_req)
Facundo Batista244afcf2015-04-22 18:35:54 -0300978 self.assertEqual(p_ds_req.unredirected_hdrs["Host"], "example.com")
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000979
Senthil Kumaran52380922013-04-25 05:45:48 -0700980 def test_full_url_setter(self):
981 # Checks to ensure that components are set correctly after setting the
982 # full_url of a Request object
983
984 urls = [
985 'http://example.com?foo=bar#baz',
986 'http://example.com?foo=bar&spam=eggs#bash',
987 'http://example.com',
988 ]
989
990 # testing a reusable request instance, but the url parameter is
991 # required, so just use a dummy one to instantiate
992 r = Request('http://example.com')
993 for url in urls:
994 r.full_url = url
Senthil Kumaran83070752013-05-24 09:14:12 -0700995 parsed = urlparse(url)
996
Senthil Kumaran52380922013-04-25 05:45:48 -0700997 self.assertEqual(r.get_full_url(), url)
Senthil Kumaran83070752013-05-24 09:14:12 -0700998 # full_url setter uses splittag to split into components.
999 # splittag sets the fragment as None while urlparse sets it to ''
1000 self.assertEqual(r.fragment or '', parsed.fragment)
1001 self.assertEqual(urlparse(r.get_full_url()).query, parsed.query)
Senthil Kumaran52380922013-04-25 05:45:48 -07001002
1003 def test_full_url_deleter(self):
1004 r = Request('http://www.example.com')
1005 del r.full_url
1006 self.assertIsNone(r.full_url)
1007 self.assertIsNone(r.fragment)
1008 self.assertEqual(r.selector, '')
1009
Senthil Kumaranc2958622010-11-22 04:48:26 +00001010 def test_fixpath_in_weirdurls(self):
1011 # Issue4493: urllib2 to supply '/' when to urls where path does not
1012 # start with'/'
1013
1014 h = urllib.request.AbstractHTTPHandler()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001015 h.parent = MockOpener()
Senthil Kumaranc2958622010-11-22 04:48:26 +00001016
1017 weird_url = 'http://www.python.org?getspam'
1018 req = Request(weird_url)
1019 newreq = h.do_request_(req)
Facundo Batista244afcf2015-04-22 18:35:54 -03001020 self.assertEqual(newreq.host, 'www.python.org')
1021 self.assertEqual(newreq.selector, '/?getspam')
Senthil Kumaranc2958622010-11-22 04:48:26 +00001022
1023 url_without_path = 'http://www.python.org'
1024 req = Request(url_without_path)
1025 newreq = h.do_request_(req)
Facundo Batista244afcf2015-04-22 18:35:54 -03001026 self.assertEqual(newreq.host, 'www.python.org')
1027 self.assertEqual(newreq.selector, '')
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001028
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001029 def test_errors(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001030 h = urllib.request.HTTPErrorProcessor()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001031 o = h.parent = MockOpener()
1032
1033 url = "http://example.com/"
1034 req = Request(url)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001035 # all 2xx are passed through
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001036 r = MockResponse(200, "OK", {}, "", url)
1037 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +00001038 self.assertIs(r, newr)
1039 self.assertFalse(hasattr(o, "proto")) # o.error not called
Guido van Rossumd8faa362007-04-27 19:54:29 +00001040 r = MockResponse(202, "Accepted", {}, "", url)
1041 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +00001042 self.assertIs(r, newr)
1043 self.assertFalse(hasattr(o, "proto")) # o.error not called
Guido van Rossumd8faa362007-04-27 19:54:29 +00001044 r = MockResponse(206, "Partial content", {}, "", url)
1045 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +00001046 self.assertIs(r, newr)
1047 self.assertFalse(hasattr(o, "proto")) # o.error not called
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001048 # anything else calls o.error (and MockOpener returns None, here)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001049 r = MockResponse(502, "Bad gateway", {}, "", url)
Florent Xicluna419e3842010-08-08 16:16:07 +00001050 self.assertIsNone(h.http_response(req, r))
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001051 self.assertEqual(o.proto, "http") # o.error called
Guido van Rossumd8faa362007-04-27 19:54:29 +00001052 self.assertEqual(o.args, (req, r, 502, "Bad gateway", {}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001053
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001054 def test_cookies(self):
1055 cj = MockCookieJar()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001056 h = urllib.request.HTTPCookieProcessor(cj)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001057 h.parent = MockOpener()
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001058
1059 req = Request("http://example.com/")
1060 r = MockResponse(200, "OK", {}, "")
1061 newreq = h.http_request(req)
Florent Xicluna419e3842010-08-08 16:16:07 +00001062 self.assertIs(cj.ach_req, req)
1063 self.assertIs(cj.ach_req, newreq)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001064 self.assertEqual(req.origin_req_host, "example.com")
1065 self.assertFalse(req.unverifiable)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001066 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +00001067 self.assertIs(cj.ec_req, req)
1068 self.assertIs(cj.ec_r, r)
1069 self.assertIs(r, newr)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001070
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001071 def test_redirect(self):
1072 from_url = "http://example.com/a.html"
1073 to_url = "http://example.com/b.html"
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001074 h = urllib.request.HTTPRedirectHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001075 o = h.parent = MockOpener()
1076
1077 # ordinary redirect behaviour
1078 for code in 301, 302, 303, 307:
1079 for data in None, "blah\nblah\n":
1080 method = getattr(h, "http_error_%s" % code)
1081 req = Request(from_url, data)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001082 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001083 req.add_header("Nonsense", "viking=withhold")
Christian Heimes77c02eb2008-02-09 02:18:51 +00001084 if data is not None:
1085 req.add_header("Content-Length", str(len(data)))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001086 req.add_unredirected_header("Spam", "spam")
1087 try:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001088 method(req, MockFile(), code, "Blah",
1089 MockHeaders({"location": to_url}))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001090 except urllib.error.HTTPError:
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001091 # 307 in response to POST requires user OK
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001092 self.assertEqual(code, 307)
1093 self.assertIsNotNone(data)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001094 self.assertEqual(o.req.get_full_url(), to_url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001095 try:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001096 self.assertEqual(o.req.get_method(), "GET")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001097 except AttributeError:
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001098 self.assertFalse(o.req.data)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001099
1100 # now it's a GET, there should not be headers regarding content
1101 # (possibly dragged from before being a POST)
1102 headers = [x.lower() for x in o.req.headers]
Benjamin Peterson577473f2010-01-19 00:09:57 +00001103 self.assertNotIn("content-length", headers)
1104 self.assertNotIn("content-type", headers)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001105
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001106 self.assertEqual(o.req.headers["Nonsense"],
1107 "viking=withhold")
Benjamin Peterson577473f2010-01-19 00:09:57 +00001108 self.assertNotIn("Spam", o.req.headers)
1109 self.assertNotIn("Spam", o.req.unredirected_hdrs)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001110
1111 # loop detection
1112 req = Request(from_url)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001113 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Facundo Batista244afcf2015-04-22 18:35:54 -03001114
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001115 def redirect(h, req, url=to_url):
1116 h.http_error_302(req, MockFile(), 302, "Blah",
1117 MockHeaders({"location": url}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001118 # Note that the *original* request shares the same record of
1119 # redirections with the sub-requests caused by the redirections.
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001120
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001121 # detect infinite loop redirect of a URL to itself
1122 req = Request(from_url, origin_req_host="example.com")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001123 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001124 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001125 try:
1126 while 1:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001127 redirect(h, req, "http://example.com/")
1128 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001129 except urllib.error.HTTPError:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001130 # don't stop until max_repeats, because cookies may introduce state
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001131 self.assertEqual(count, urllib.request.HTTPRedirectHandler.max_repeats)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001132
1133 # detect endless non-repeating chain of redirects
1134 req = Request(from_url, origin_req_host="example.com")
1135 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001136 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001137 try:
1138 while 1:
1139 redirect(h, req, "http://example.com/%d" % count)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001140 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001141 except urllib.error.HTTPError:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001142 self.assertEqual(count,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001143 urllib.request.HTTPRedirectHandler.max_redirections)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001144
guido@google.coma119df92011-03-29 11:41:02 -07001145 def test_invalid_redirect(self):
1146 from_url = "http://example.com/a.html"
1147 valid_schemes = ['http','https','ftp']
1148 invalid_schemes = ['file','imap','ldap']
1149 schemeless_url = "example.com/b.html"
1150 h = urllib.request.HTTPRedirectHandler()
1151 o = h.parent = MockOpener()
1152 req = Request(from_url)
1153 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1154
1155 for scheme in invalid_schemes:
1156 invalid_url = scheme + '://' + schemeless_url
1157 self.assertRaises(urllib.error.HTTPError, h.http_error_302,
1158 req, MockFile(), 302, "Security Loophole",
1159 MockHeaders({"location": invalid_url}))
1160
1161 for scheme in valid_schemes:
1162 valid_url = scheme + '://' + schemeless_url
1163 h.http_error_302(req, MockFile(), 302, "That's fine",
1164 MockHeaders({"location": valid_url}))
1165 self.assertEqual(o.req.get_full_url(), valid_url)
1166
Senthil Kumaran6497aa32012-01-04 13:46:59 +08001167 def test_relative_redirect(self):
1168 from_url = "http://example.com/a.html"
1169 relative_url = "/b.html"
1170 h = urllib.request.HTTPRedirectHandler()
1171 o = h.parent = MockOpener()
1172 req = Request(from_url)
1173 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1174
1175 valid_url = urllib.parse.urljoin(from_url,relative_url)
1176 h.http_error_302(req, MockFile(), 302, "That's fine",
1177 MockHeaders({"location": valid_url}))
1178 self.assertEqual(o.req.get_full_url(), valid_url)
1179
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001180 def test_cookie_redirect(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001181 # cookies shouldn't leak into redirected requests
Georg Brandl24420152008-05-26 16:32:26 +00001182 from http.cookiejar import CookieJar
1183 from test.test_http_cookiejar import interact_netscape
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001184
1185 cj = CookieJar()
1186 interact_netscape(cj, "http://www.example.com/", "spam=eggs")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001187 hh = MockHTTPHandler(302, "Location: http://www.cracker.com/\r\n\r\n")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001188 hdeh = urllib.request.HTTPDefaultErrorHandler()
1189 hrh = urllib.request.HTTPRedirectHandler()
1190 cp = urllib.request.HTTPCookieProcessor(cj)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001191 o = build_test_opener(hh, hdeh, hrh, cp)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001192 o.open("http://www.example.com/")
Florent Xicluna419e3842010-08-08 16:16:07 +00001193 self.assertFalse(hh.req.has_header("Cookie"))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001194
Senthil Kumaran26430412011-04-13 07:01:19 +08001195 def test_redirect_fragment(self):
1196 redirected_url = 'http://www.example.com/index.html#OK\r\n\r\n'
1197 hh = MockHTTPHandler(302, 'Location: ' + redirected_url)
1198 hdeh = urllib.request.HTTPDefaultErrorHandler()
1199 hrh = urllib.request.HTTPRedirectHandler()
1200 o = build_test_opener(hh, hdeh, hrh)
1201 fp = o.open('http://www.example.com')
1202 self.assertEqual(fp.geturl(), redirected_url.strip())
1203
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001204 def test_proxy(self):
1205 o = OpenerDirector()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001206 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001207 o.add_handler(ph)
1208 meth_spec = [
1209 [("http_open", "return response")]
1210 ]
1211 handlers = add_ordered_mock_handlers(o, meth_spec)
1212
1213 req = Request("http://acme.example.com/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001214 self.assertEqual(req.host, "acme.example.com")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001215 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001216 self.assertEqual(req.host, "proxy.example.com:3128")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001217
1218 self.assertEqual([(handlers[0], "http_open")],
1219 [tup[0:2] for tup in o.calls])
1220
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001221 def test_proxy_no_proxy(self):
1222 os.environ['no_proxy'] = 'python.org'
1223 o = OpenerDirector()
1224 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1225 o.add_handler(ph)
1226 req = Request("http://www.perl.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001227 self.assertEqual(req.host, "www.perl.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001228 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001229 self.assertEqual(req.host, "proxy.example.com")
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001230 req = Request("http://www.python.org")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001231 self.assertEqual(req.host, "www.python.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001232 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001233 self.assertEqual(req.host, "www.python.org")
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001234 del os.environ['no_proxy']
1235
Ronald Oussorene72e1612011-03-14 18:15:25 -04001236 def test_proxy_no_proxy_all(self):
1237 os.environ['no_proxy'] = '*'
1238 o = OpenerDirector()
1239 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1240 o.add_handler(ph)
1241 req = Request("http://www.python.org")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001242 self.assertEqual(req.host, "www.python.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001243 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001244 self.assertEqual(req.host, "www.python.org")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001245 del os.environ['no_proxy']
1246
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001247 def test_proxy_https(self):
1248 o = OpenerDirector()
1249 ph = urllib.request.ProxyHandler(dict(https="proxy.example.com:3128"))
1250 o.add_handler(ph)
1251 meth_spec = [
1252 [("https_open", "return response")]
1253 ]
1254 handlers = add_ordered_mock_handlers(o, meth_spec)
1255
1256 req = Request("https://www.example.com/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001257 self.assertEqual(req.host, "www.example.com")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001258 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001259 self.assertEqual(req.host, "proxy.example.com:3128")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001260 self.assertEqual([(handlers[0], "https_open")],
1261 [tup[0:2] for tup in o.calls])
1262
Senthil Kumaran47fff872009-12-20 07:10:31 +00001263 def test_proxy_https_proxy_authorization(self):
1264 o = OpenerDirector()
1265 ph = urllib.request.ProxyHandler(dict(https='proxy.example.com:3128'))
1266 o.add_handler(ph)
1267 https_handler = MockHTTPSHandler()
1268 o.add_handler(https_handler)
1269 req = Request("https://www.example.com/")
Facundo Batista244afcf2015-04-22 18:35:54 -03001270 req.add_header("Proxy-Authorization", "FooBar")
1271 req.add_header("User-Agent", "Grail")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001272 self.assertEqual(req.host, "www.example.com")
Senthil Kumaran47fff872009-12-20 07:10:31 +00001273 self.assertIsNone(req._tunnel_host)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001274 o.open(req)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001275 # Verify Proxy-Authorization gets tunneled to request.
1276 # httpsconn req_headers do not have the Proxy-Authorization header but
1277 # the req will have.
Facundo Batista244afcf2015-04-22 18:35:54 -03001278 self.assertNotIn(("Proxy-Authorization", "FooBar"),
Senthil Kumaran47fff872009-12-20 07:10:31 +00001279 https_handler.httpconn.req_headers)
Facundo Batista244afcf2015-04-22 18:35:54 -03001280 self.assertIn(("User-Agent", "Grail"),
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001281 https_handler.httpconn.req_headers)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001282 self.assertIsNotNone(req._tunnel_host)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001283 self.assertEqual(req.host, "proxy.example.com:3128")
Facundo Batista244afcf2015-04-22 18:35:54 -03001284 self.assertEqual(req.get_header("Proxy-authorization"), "FooBar")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001285
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001286 # TODO: This should be only for OSX
1287 @unittest.skipUnless(sys.platform == 'darwin', "only relevant for OSX")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001288 def test_osx_proxy_bypass(self):
1289 bypass = {
1290 'exclude_simple': False,
1291 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.10',
1292 '10.0/16']
1293 }
1294 # Check hosts that should trigger the proxy bypass
1295 for host in ('foo.bar', 'www.bar.com', '127.0.0.1', '10.10.0.1',
1296 '10.0.0.1'):
1297 self.assertTrue(_proxy_bypass_macosx_sysconf(host, bypass),
1298 'expected bypass of %s to be True' % host)
1299 # Check hosts that should not trigger the proxy bypass
R David Murrayfdbe9182014-03-15 12:00:14 -04001300 for host in ('abc.foo.bar', 'bar.com', '127.0.0.2', '10.11.0.1',
1301 'notinbypass'):
Ronald Oussorene72e1612011-03-14 18:15:25 -04001302 self.assertFalse(_proxy_bypass_macosx_sysconf(host, bypass),
1303 'expected bypass of %s to be False' % host)
1304
1305 # Check the exclude_simple flag
1306 bypass = {'exclude_simple': True, 'exceptions': []}
1307 self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass))
1308
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001309 def test_basic_auth(self, quote_char='"'):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001310 opener = OpenerDirector()
1311 password_manager = MockPasswordManager()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001312 auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001313 realm = "ACME Widget Store"
1314 http_handler = MockHTTPHandler(
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001315 401, 'WWW-Authenticate: Basic realm=%s%s%s\r\n\r\n' %
Facundo Batista244afcf2015-04-22 18:35:54 -03001316 (quote_char, realm, quote_char))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001317 opener.add_handler(auth_handler)
1318 opener.add_handler(http_handler)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001319 self._test_basic_auth(opener, auth_handler, "Authorization",
1320 realm, http_handler, password_manager,
1321 "http://acme.example.com/protected",
1322 "http://acme.example.com/protected",
1323 )
1324
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001325 def test_basic_auth_with_single_quoted_realm(self):
1326 self.test_basic_auth(quote_char="'")
1327
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +08001328 def test_basic_auth_with_unquoted_realm(self):
1329 opener = OpenerDirector()
1330 password_manager = MockPasswordManager()
1331 auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
1332 realm = "ACME Widget Store"
1333 http_handler = MockHTTPHandler(
1334 401, 'WWW-Authenticate: Basic realm=%s\r\n\r\n' % realm)
1335 opener.add_handler(auth_handler)
1336 opener.add_handler(http_handler)
Senthil Kumaran0ea91cb2012-05-15 23:59:42 +08001337 with self.assertWarns(UserWarning):
1338 self._test_basic_auth(opener, auth_handler, "Authorization",
1339 realm, http_handler, password_manager,
1340 "http://acme.example.com/protected",
1341 "http://acme.example.com/protected",
1342 )
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +08001343
Thomas Wouters477c8d52006-05-27 19:21:47 +00001344 def test_proxy_basic_auth(self):
1345 opener = OpenerDirector()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001346 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001347 opener.add_handler(ph)
1348 password_manager = MockPasswordManager()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001349 auth_handler = urllib.request.ProxyBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001350 realm = "ACME Networks"
1351 http_handler = MockHTTPHandler(
1352 407, 'Proxy-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001353 opener.add_handler(auth_handler)
1354 opener.add_handler(http_handler)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001355 self._test_basic_auth(opener, auth_handler, "Proxy-authorization",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001356 realm, http_handler, password_manager,
1357 "http://acme.example.com:3128/protected",
1358 "proxy.example.com:3128",
1359 )
1360
1361 def test_basic_and_digest_auth_handlers(self):
Andrew Svetlov7bd61cb2012-12-19 22:49:25 +02001362 # HTTPDigestAuthHandler raised an exception if it couldn't handle a 40*
Thomas Wouters477c8d52006-05-27 19:21:47 +00001363 # response (http://python.org/sf/1479302), where it should instead
1364 # return None to allow another handler (especially
1365 # HTTPBasicAuthHandler) to handle the response.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001366
1367 # Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must
1368 # try digest first (since it's the strongest auth scheme), so we record
1369 # order of calls here to check digest comes first:
1370 class RecordingOpenerDirector(OpenerDirector):
1371 def __init__(self):
1372 OpenerDirector.__init__(self)
1373 self.recorded = []
Facundo Batista244afcf2015-04-22 18:35:54 -03001374
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001375 def record(self, info):
1376 self.recorded.append(info)
Facundo Batista244afcf2015-04-22 18:35:54 -03001377
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001378 class TestDigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001379 def http_error_401(self, *args, **kwds):
1380 self.parent.record("digest")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001381 urllib.request.HTTPDigestAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001382 *args, **kwds)
Facundo Batista244afcf2015-04-22 18:35:54 -03001383
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001384 class TestBasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001385 def http_error_401(self, *args, **kwds):
1386 self.parent.record("basic")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001387 urllib.request.HTTPBasicAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001388 *args, **kwds)
1389
1390 opener = RecordingOpenerDirector()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001391 password_manager = MockPasswordManager()
1392 digest_handler = TestDigestAuthHandler(password_manager)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001393 basic_handler = TestBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001394 realm = "ACME Networks"
1395 http_handler = MockHTTPHandler(
1396 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001397 opener.add_handler(basic_handler)
1398 opener.add_handler(digest_handler)
1399 opener.add_handler(http_handler)
1400
1401 # check basic auth isn't blocked by digest handler failing
Thomas Wouters477c8d52006-05-27 19:21:47 +00001402 self._test_basic_auth(opener, basic_handler, "Authorization",
1403 realm, http_handler, password_manager,
1404 "http://acme.example.com/protected",
1405 "http://acme.example.com/protected",
1406 )
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001407 # check digest was tried before basic (twice, because
1408 # _test_basic_auth called .open() twice)
1409 self.assertEqual(opener.recorded, ["digest", "basic"]*2)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001410
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001411 def test_unsupported_auth_digest_handler(self):
1412 opener = OpenerDirector()
1413 # While using DigestAuthHandler
1414 digest_auth_handler = urllib.request.HTTPDigestAuthHandler(None)
1415 http_handler = MockHTTPHandler(
1416 401, 'WWW-Authenticate: Kerberos\r\n\r\n')
1417 opener.add_handler(digest_auth_handler)
1418 opener.add_handler(http_handler)
Facundo Batista244afcf2015-04-22 18:35:54 -03001419 self.assertRaises(ValueError, opener.open, "http://www.example.com")
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001420
1421 def test_unsupported_auth_basic_handler(self):
1422 # While using BasicAuthHandler
1423 opener = OpenerDirector()
1424 basic_auth_handler = urllib.request.HTTPBasicAuthHandler(None)
1425 http_handler = MockHTTPHandler(
1426 401, 'WWW-Authenticate: NTLM\r\n\r\n')
1427 opener.add_handler(basic_auth_handler)
1428 opener.add_handler(http_handler)
Facundo Batista244afcf2015-04-22 18:35:54 -03001429 self.assertRaises(ValueError, opener.open, "http://www.example.com")
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001430
Thomas Wouters477c8d52006-05-27 19:21:47 +00001431 def _test_basic_auth(self, opener, auth_handler, auth_header,
1432 realm, http_handler, password_manager,
1433 request_url, protected_url):
Christian Heimes05e8be12008-02-23 18:30:17 +00001434 import base64
Thomas Wouters477c8d52006-05-27 19:21:47 +00001435 user, password = "wile", "coyote"
Thomas Wouters477c8d52006-05-27 19:21:47 +00001436
1437 # .add_password() fed through to password manager
1438 auth_handler.add_password(realm, request_url, user, password)
1439 self.assertEqual(realm, password_manager.realm)
1440 self.assertEqual(request_url, password_manager.url)
1441 self.assertEqual(user, password_manager.user)
1442 self.assertEqual(password, password_manager.password)
1443
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001444 opener.open(request_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001445
1446 # should have asked the password manager for the username/password
1447 self.assertEqual(password_manager.target_realm, realm)
1448 self.assertEqual(password_manager.target_url, protected_url)
1449
1450 # expect one request without authorization, then one with
1451 self.assertEqual(len(http_handler.requests), 2)
1452 self.assertFalse(http_handler.requests[0].has_header(auth_header))
Guido van Rossum98b349f2007-08-27 21:47:52 +00001453 userpass = bytes('%s:%s' % (user, password), "ascii")
Guido van Rossum98297ee2007-11-06 21:34:58 +00001454 auth_hdr_value = ('Basic ' +
Georg Brandl706824f2009-06-04 09:42:55 +00001455 base64.encodebytes(userpass).strip().decode())
Thomas Wouters477c8d52006-05-27 19:21:47 +00001456 self.assertEqual(http_handler.requests[1].get_header(auth_header),
1457 auth_hdr_value)
Senthil Kumaranca2fc9e2010-02-24 16:53:16 +00001458 self.assertEqual(http_handler.requests[1].unredirected_hdrs[auth_header],
1459 auth_hdr_value)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001460 # if the password manager can't find a password, the handler won't
1461 # handle the HTTP auth error
1462 password_manager.user = password_manager.password = None
1463 http_handler.reset()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001464 opener.open(request_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001465 self.assertEqual(len(http_handler.requests), 1)
1466 self.assertFalse(http_handler.requests[0].has_header(auth_header))
1467
R David Murray4c7f9952015-04-16 16:36:18 -04001468 def test_basic_prior_auth_auto_send(self):
1469 # Assume already authenticated if is_authenticated=True
1470 # for APIs like Github that don't return 401
1471
1472 user, password = "wile", "coyote"
1473 request_url = "http://acme.example.com/protected"
1474
1475 http_handler = MockHTTPHandlerCheckAuth(200)
1476
1477 pwd_manager = HTTPPasswordMgrWithPriorAuth()
1478 auth_prior_handler = HTTPBasicAuthHandler(pwd_manager)
1479 auth_prior_handler.add_password(
1480 None, request_url, user, password, is_authenticated=True)
1481
1482 is_auth = pwd_manager.is_authenticated(request_url)
1483 self.assertTrue(is_auth)
1484
1485 opener = OpenerDirector()
1486 opener.add_handler(auth_prior_handler)
1487 opener.add_handler(http_handler)
1488
1489 opener.open(request_url)
1490
1491 # expect request to be sent with auth header
1492 self.assertTrue(http_handler.has_auth_header)
1493
1494 def test_basic_prior_auth_send_after_first_success(self):
1495 # Auto send auth header after authentication is successful once
1496
1497 user, password = 'wile', 'coyote'
1498 request_url = 'http://acme.example.com/protected'
1499 realm = 'ACME'
1500
1501 pwd_manager = HTTPPasswordMgrWithPriorAuth()
1502 auth_prior_handler = HTTPBasicAuthHandler(pwd_manager)
1503 auth_prior_handler.add_password(realm, request_url, user, password)
1504
1505 is_auth = pwd_manager.is_authenticated(request_url)
1506 self.assertFalse(is_auth)
1507
1508 opener = OpenerDirector()
1509 opener.add_handler(auth_prior_handler)
1510
1511 http_handler = MockHTTPHandler(
1512 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % None)
1513 opener.add_handler(http_handler)
1514
1515 opener.open(request_url)
1516
1517 is_auth = pwd_manager.is_authenticated(request_url)
1518 self.assertTrue(is_auth)
1519
1520 http_handler = MockHTTPHandlerCheckAuth(200)
1521 self.assertFalse(http_handler.has_auth_header)
1522
1523 opener = OpenerDirector()
1524 opener.add_handler(auth_prior_handler)
1525 opener.add_handler(http_handler)
1526
1527 # After getting 200 from MockHTTPHandler
1528 # Next request sends header in the first request
1529 opener.open(request_url)
1530
1531 # expect request to be sent with auth header
1532 self.assertTrue(http_handler.has_auth_header)
1533
Serhiy Storchakaf54c3502014-09-06 21:41:39 +03001534 def test_http_closed(self):
1535 """Test the connection is cleaned up when the response is closed"""
1536 for (transfer, data) in (
1537 ("Connection: close", b"data"),
1538 ("Transfer-Encoding: chunked", b"4\r\ndata\r\n0\r\n\r\n"),
1539 ("Content-Length: 4", b"data"),
1540 ):
1541 header = "HTTP/1.1 200 OK\r\n{}\r\n\r\n".format(transfer)
1542 conn = test_urllib.fakehttp(header.encode() + data)
1543 handler = urllib.request.AbstractHTTPHandler()
1544 req = Request("http://dummy/")
1545 req.timeout = None
1546 with handler.do_open(conn, req) as resp:
1547 resp.read()
1548 self.assertTrue(conn.fakesock.closed,
1549 "Connection not closed with {!r}".format(transfer))
1550
1551 def test_invalid_closed(self):
1552 """Test the connection is cleaned up after an invalid response"""
1553 conn = test_urllib.fakehttp(b"")
1554 handler = urllib.request.AbstractHTTPHandler()
1555 req = Request("http://dummy/")
1556 req.timeout = None
1557 with self.assertRaises(http.client.BadStatusLine):
1558 handler.do_open(conn, req)
1559 self.assertTrue(conn.fakesock.closed, "Connection not closed")
1560
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001561
Facundo Batista244afcf2015-04-22 18:35:54 -03001562
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001563class MiscTests(unittest.TestCase):
1564
Senthil Kumarane9853da2013-03-19 12:07:43 -07001565 def opener_has_handler(self, opener, handler_class):
1566 self.assertTrue(any(h.__class__ == handler_class
1567 for h in opener.handlers))
1568
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001569 def test_build_opener(self):
Facundo Batista244afcf2015-04-22 18:35:54 -03001570 class MyHTTPHandler(urllib.request.HTTPHandler):
1571 pass
1572
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001573 class FooHandler(urllib.request.BaseHandler):
Facundo Batista244afcf2015-04-22 18:35:54 -03001574 def foo_open(self):
1575 pass
1576
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001577 class BarHandler(urllib.request.BaseHandler):
Facundo Batista244afcf2015-04-22 18:35:54 -03001578 def bar_open(self):
1579 pass
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001580
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001581 build_opener = urllib.request.build_opener
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001582
1583 o = build_opener(FooHandler, BarHandler)
1584 self.opener_has_handler(o, FooHandler)
1585 self.opener_has_handler(o, BarHandler)
1586
1587 # can take a mix of classes and instances
1588 o = build_opener(FooHandler, BarHandler())
1589 self.opener_has_handler(o, FooHandler)
1590 self.opener_has_handler(o, BarHandler)
1591
1592 # subclasses of default handlers override default handlers
1593 o = build_opener(MyHTTPHandler)
1594 self.opener_has_handler(o, MyHTTPHandler)
1595
1596 # a particular case of overriding: default handlers can be passed
1597 # in explicitly
1598 o = build_opener()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001599 self.opener_has_handler(o, urllib.request.HTTPHandler)
1600 o = build_opener(urllib.request.HTTPHandler)
1601 self.opener_has_handler(o, urllib.request.HTTPHandler)
1602 o = build_opener(urllib.request.HTTPHandler())
1603 self.opener_has_handler(o, urllib.request.HTTPHandler)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001604
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001605 # Issue2670: multiple handlers sharing the same base class
Facundo Batista244afcf2015-04-22 18:35:54 -03001606 class MyOtherHTTPHandler(urllib.request.HTTPHandler):
1607 pass
1608
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001609 o = build_opener(MyHTTPHandler, MyOtherHTTPHandler)
1610 self.opener_has_handler(o, MyHTTPHandler)
1611 self.opener_has_handler(o, MyOtherHTTPHandler)
1612
Brett Cannon80512de2013-01-25 22:27:21 -05001613 @unittest.skipUnless(support.is_resource_enabled('network'),
1614 'test requires network access')
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001615 def test_issue16464(self):
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001616 with support.transient_internet("http://www.example.com/"):
1617 opener = urllib.request.build_opener()
1618 request = urllib.request.Request("http://www.example.com/")
1619 self.assertEqual(None, request.data)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001620
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001621 opener.open(request, "1".encode("us-ascii"))
1622 self.assertEqual(b"1", request.data)
1623 self.assertEqual("1", request.get_header("Content-length"))
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001624
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001625 opener.open(request, "1234567890".encode("us-ascii"))
1626 self.assertEqual(b"1234567890", request.data)
1627 self.assertEqual("10", request.get_header("Content-length"))
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001628
Senthil Kumarane9853da2013-03-19 12:07:43 -07001629 def test_HTTPError_interface(self):
1630 """
1631 Issue 13211 reveals that HTTPError didn't implement the URLError
1632 interface even though HTTPError is a subclass of URLError.
Senthil Kumarane9853da2013-03-19 12:07:43 -07001633 """
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001634 msg = 'something bad happened'
1635 url = code = fp = None
1636 hdrs = 'Content-Length: 42'
1637 err = urllib.error.HTTPError(url, code, msg, hdrs, fp)
1638 self.assertTrue(hasattr(err, 'reason'))
1639 self.assertEqual(err.reason, 'something bad happened')
1640 self.assertTrue(hasattr(err, 'headers'))
1641 self.assertEqual(err.headers, 'Content-Length: 42')
1642 expected_errmsg = 'HTTP Error %s: %s' % (err.code, err.msg)
1643 self.assertEqual(str(err), expected_errmsg)
Facundo Batista244afcf2015-04-22 18:35:54 -03001644 expected_errmsg = '<HTTPError %s: %r>' % (err.code, err.msg)
1645 self.assertEqual(repr(err), expected_errmsg)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001646
Senthil Kumarand8e24f12014-04-14 16:32:20 -04001647 def test_parse_proxy(self):
1648 parse_proxy_test_cases = [
1649 ('proxy.example.com',
1650 (None, None, None, 'proxy.example.com')),
1651 ('proxy.example.com:3128',
1652 (None, None, None, 'proxy.example.com:3128')),
1653 ('proxy.example.com', (None, None, None, 'proxy.example.com')),
1654 ('proxy.example.com:3128',
1655 (None, None, None, 'proxy.example.com:3128')),
1656 # The authority component may optionally include userinfo
1657 # (assumed to be # username:password):
1658 ('joe:password@proxy.example.com',
1659 (None, 'joe', 'password', 'proxy.example.com')),
1660 ('joe:password@proxy.example.com:3128',
1661 (None, 'joe', 'password', 'proxy.example.com:3128')),
1662 #Examples with URLS
1663 ('http://proxy.example.com/',
1664 ('http', None, None, 'proxy.example.com')),
1665 ('http://proxy.example.com:3128/',
1666 ('http', None, None, 'proxy.example.com:3128')),
1667 ('http://joe:password@proxy.example.com/',
1668 ('http', 'joe', 'password', 'proxy.example.com')),
1669 ('http://joe:password@proxy.example.com:3128',
1670 ('http', 'joe', 'password', 'proxy.example.com:3128')),
1671 # Everything after the authority is ignored
1672 ('ftp://joe:password@proxy.example.com/rubbish:3128',
1673 ('ftp', 'joe', 'password', 'proxy.example.com')),
1674 # Test for no trailing '/' case
1675 ('http://joe:password@proxy.example.com',
1676 ('http', 'joe', 'password', 'proxy.example.com'))
1677 ]
1678
1679 for tc, expected in parse_proxy_test_cases:
1680 self.assertEqual(_parse_proxy(tc), expected)
1681
1682 self.assertRaises(ValueError, _parse_proxy, 'file:/ftp.example.com'),
1683
Berker Peksage88dd1c2016-03-06 16:16:40 +02001684 def test_unsupported_algorithm(self):
1685 handler = AbstractDigestAuthHandler()
1686 with self.assertRaises(ValueError) as exc:
1687 handler.get_algorithm_impls('invalid')
1688 self.assertEqual(
1689 str(exc.exception),
1690 "Unsupported digest authentication algorithm 'invalid'"
1691 )
1692
Facundo Batista244afcf2015-04-22 18:35:54 -03001693
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001694class RequestTests(unittest.TestCase):
Jason R. Coombs4a652422013-09-08 13:03:40 -04001695 class PutRequest(Request):
Facundo Batista244afcf2015-04-22 18:35:54 -03001696 method = 'PUT'
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001697
1698 def setUp(self):
1699 self.get = Request("http://www.python.org/~jeremy/")
1700 self.post = Request("http://www.python.org/~jeremy/",
1701 "data",
1702 headers={"X-Test": "test"})
Jason R. Coombs4a652422013-09-08 13:03:40 -04001703 self.head = Request("http://www.python.org/~jeremy/", method='HEAD')
1704 self.put = self.PutRequest("http://www.python.org/~jeremy/")
1705 self.force_post = self.PutRequest("http://www.python.org/~jeremy/",
1706 method="POST")
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001707
1708 def test_method(self):
1709 self.assertEqual("POST", self.post.get_method())
1710 self.assertEqual("GET", self.get.get_method())
Senthil Kumaran0b5463f2013-09-09 23:13:06 -07001711 self.assertEqual("HEAD", self.head.get_method())
Jason R. Coombs4a652422013-09-08 13:03:40 -04001712 self.assertEqual("PUT", self.put.get_method())
1713 self.assertEqual("POST", self.force_post.get_method())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001714
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001715 def test_data(self):
1716 self.assertFalse(self.get.data)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001717 self.assertEqual("GET", self.get.get_method())
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001718 self.get.data = "spam"
1719 self.assertTrue(self.get.data)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001720 self.assertEqual("POST", self.get.get_method())
1721
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001722 # issue 16464
1723 # if we change data we need to remove content-length header
1724 # (cause it's most probably calculated for previous value)
1725 def test_setting_data_should_remove_content_length(self):
R David Murray9cc7d452013-03-20 00:10:51 -04001726 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001727 self.get.add_unredirected_header("Content-length", 42)
1728 self.assertEqual(42, self.get.unredirected_hdrs["Content-length"])
1729 self.get.data = "spam"
R David Murray9cc7d452013-03-20 00:10:51 -04001730 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
1731
1732 # issue 17485 same for deleting data.
1733 def test_deleting_data_should_remove_content_length(self):
1734 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
1735 self.get.data = 'foo'
1736 self.get.add_unredirected_header("Content-length", 3)
1737 self.assertEqual(3, self.get.unredirected_hdrs["Content-length"])
1738 del self.get.data
1739 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001740
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001741 def test_get_full_url(self):
1742 self.assertEqual("http://www.python.org/~jeremy/",
1743 self.get.get_full_url())
1744
1745 def test_selector(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001746 self.assertEqual("/~jeremy/", self.get.selector)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001747 req = Request("http://www.python.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001748 self.assertEqual("/", req.selector)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001749
1750 def test_get_type(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001751 self.assertEqual("http", self.get.type)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001752
1753 def test_get_host(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001754 self.assertEqual("www.python.org", self.get.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001755
1756 def test_get_host_unquote(self):
1757 req = Request("http://www.%70ython.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001758 self.assertEqual("www.python.org", req.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001759
1760 def test_proxy(self):
Florent Xicluna419e3842010-08-08 16:16:07 +00001761 self.assertFalse(self.get.has_proxy())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001762 self.get.set_proxy("www.perl.org", "http")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001763 self.assertTrue(self.get.has_proxy())
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001764 self.assertEqual("www.python.org", self.get.origin_req_host)
1765 self.assertEqual("www.perl.org", self.get.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001766
Senthil Kumarand95cc752010-08-08 11:27:53 +00001767 def test_wrapped_url(self):
1768 req = Request("<URL:http://www.python.org>")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001769 self.assertEqual("www.python.org", req.host)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001770
Senthil Kumaran26430412011-04-13 07:01:19 +08001771 def test_url_fragment(self):
Senthil Kumarand95cc752010-08-08 11:27:53 +00001772 req = Request("http://www.python.org/?qs=query#fragment=true")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001773 self.assertEqual("/?qs=query", req.selector)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001774 req = Request("http://www.python.org/#fun=true")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001775 self.assertEqual("/", req.selector)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001776
Senthil Kumaran26430412011-04-13 07:01:19 +08001777 # Issue 11703: geturl() omits fragment in the original URL.
1778 url = 'http://docs.python.org/library/urllib2.html#OK'
1779 req = Request(url)
1780 self.assertEqual(req.get_full_url(), url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001781
Senthil Kumaran83070752013-05-24 09:14:12 -07001782 def test_url_fullurl_get_full_url(self):
1783 urls = ['http://docs.python.org',
1784 'http://docs.python.org/library/urllib2.html#OK',
Facundo Batista244afcf2015-04-22 18:35:54 -03001785 'http://www.python.org/?qs=query#fragment=true']
Senthil Kumaran83070752013-05-24 09:14:12 -07001786 for url in urls:
1787 req = Request(url)
1788 self.assertEqual(req.get_full_url(), req.full_url)
1789
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001790
1791if __name__ == "__main__":
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001792 unittest.main()