blob: a5281d864c01650626ea37319754c7114e74d4dd [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,
16 _proxy_bypass_macosx_sysconf)
Senthil Kumaran83070752013-05-24 09:14:12 -070017from urllib.parse import urlparse
guido@google.coma119df92011-03-29 11:41:02 -070018import urllib.error
Serhiy Storchakaf54c3502014-09-06 21:41:39 +030019import http.client
Jeremy Hyltone3e61042001-05-09 15:50:25 +000020
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000021# XXX
22# Request
23# CacheFTPHandler (hard to write)
Thomas Wouters477c8d52006-05-27 19:21:47 +000024# parse_keqv_list, parse_http_list, HTTPDigestAuthHandler
Jeremy Hyltone3e61042001-05-09 15:50:25 +000025
Facundo Batista244afcf2015-04-22 18:35:54 -030026
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000027class TrivialTests(unittest.TestCase):
Senthil Kumaran6c5bd402011-11-01 23:20:31 +080028
29 def test___all__(self):
30 # Verify which names are exposed
31 for module in 'request', 'response', 'parse', 'error', 'robotparser':
32 context = {}
33 exec('from urllib.%s import *' % module, context)
34 del context['__builtins__']
Florent Xicluna3dbb1f12011-11-04 22:15:37 +010035 if module == 'request' and os.name == 'nt':
36 u, p = context.pop('url2pathname'), context.pop('pathname2url')
37 self.assertEqual(u.__module__, 'nturl2path')
38 self.assertEqual(p.__module__, 'nturl2path')
Senthil Kumaran6c5bd402011-11-01 23:20:31 +080039 for k, v in context.items():
40 self.assertEqual(v.__module__, 'urllib.%s' % module,
41 "%r is exposed in 'urllib.%s' but defined in %r" %
42 (k, module, v.__module__))
43
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000044 def test_trivial(self):
45 # A couple trivial tests
Guido van Rossume2ae77b2001-10-24 20:42:55 +000046
Jeremy Hylton1afc1692008-06-18 20:49:58 +000047 self.assertRaises(ValueError, urllib.request.urlopen, 'bogus url')
Tim Peters861adac2001-07-16 20:49:49 +000048
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000049 # XXX Name hacking to get this to work on Windows.
Serhiy Storchaka5106d042015-01-26 10:26:14 +020050 fname = os.path.abspath(urllib.request.__file__).replace(os.sep, '/')
Senthil Kumarand587e302010-01-10 17:45:52 +000051
Senthil Kumarand587e302010-01-10 17:45:52 +000052 if os.name == 'nt':
53 file_url = "file:///%s" % fname
54 else:
55 file_url = "file://%s" % fname
56
Jeremy Hylton1afc1692008-06-18 20:49:58 +000057 f = urllib.request.urlopen(file_url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000058
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -070059 f.read()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000060 f.close()
Tim Petersf5f32b42005-07-17 23:16:17 +000061
Georg Brandle1b13d22005-08-24 22:20:32 +000062 def test_parse_http_list(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +000063 tests = [
64 ('a,b,c', ['a', 'b', 'c']),
65 ('path"o,l"og"i"cal, example', ['path"o,l"og"i"cal', 'example']),
66 ('a, b, "c", "d", "e,f", g, h',
67 ['a', 'b', '"c"', '"d"', '"e,f"', 'g', 'h']),
68 ('a="b\\"c", d="e\\,f", g="h\\\\i"',
69 ['a="b"c"', 'd="e,f"', 'g="h\\i"'])]
Georg Brandle1b13d22005-08-24 22:20:32 +000070 for string, list in tests:
Florent Xicluna419e3842010-08-08 16:16:07 +000071 self.assertEqual(urllib.request.parse_http_list(string), list)
Georg Brandle1b13d22005-08-24 22:20:32 +000072
Senthil Kumaran843fae92013-03-19 13:43:42 -070073 def test_URLError_reasonstr(self):
74 err = urllib.error.URLError('reason')
75 self.assertIn(err.reason, str(err))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000076
Facundo Batista244afcf2015-04-22 18:35:54 -030077
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -070078class RequestHdrsTests(unittest.TestCase):
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000079
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -070080 def test_request_headers_dict(self):
81 """
82 The Request.headers dictionary is not a documented interface. It
83 should stay that way, because the complete set of headers are only
84 accessible through the .get_header(), .has_header(), .header_items()
85 interface. However, .headers pre-dates those methods, and so real code
86 will be using the dictionary.
87
88 The introduction in 2.4 of those methods was a mistake for the same
89 reason: code that previously saw all (urllib2 user)-provided headers in
90 .headers now sees only a subset.
91
92 """
93 url = "http://example.com"
94 self.assertEqual(Request(url,
95 headers={"Spam-eggs": "blah"}
96 ).headers["Spam-eggs"], "blah")
97 self.assertEqual(Request(url,
98 headers={"spam-EggS": "blah"}
99 ).headers["Spam-eggs"], "blah")
100
101 def test_request_headers_methods(self):
102 """
103 Note the case normalization of header names here, to
104 .capitalize()-case. This should be preserved for
105 backwards-compatibility. (In the HTTP case, normalization to
106 .title()-case is done by urllib2 before sending headers to
107 http.client).
108
109 Note that e.g. r.has_header("spam-EggS") is currently False, and
110 r.get_header("spam-EggS") returns None, but that could be changed in
111 future.
112
113 Method r.remove_header should remove items both from r.headers and
114 r.unredirected_hdrs dictionaries
115 """
116 url = "http://example.com"
117 req = Request(url, headers={"Spam-eggs": "blah"})
118 self.assertTrue(req.has_header("Spam-eggs"))
119 self.assertEqual(req.header_items(), [('Spam-eggs', 'blah')])
120
121 req.add_header("Foo-Bar", "baz")
122 self.assertEqual(sorted(req.header_items()),
123 [('Foo-bar', 'baz'), ('Spam-eggs', 'blah')])
124 self.assertFalse(req.has_header("Not-there"))
125 self.assertIsNone(req.get_header("Not-there"))
126 self.assertEqual(req.get_header("Not-there", "default"), "default")
127
128 req.remove_header("Spam-eggs")
129 self.assertFalse(req.has_header("Spam-eggs"))
130
131 req.add_unredirected_header("Unredirected-spam", "Eggs")
132 self.assertTrue(req.has_header("Unredirected-spam"))
133
134 req.remove_header("Unredirected-spam")
135 self.assertFalse(req.has_header("Unredirected-spam"))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000136
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700137 def test_password_manager(self):
138 mgr = urllib.request.HTTPPasswordMgr()
139 add = mgr.add_password
140 find_user_pass = mgr.find_user_password
141 add("Some Realm", "http://example.com/", "joe", "password")
142 add("Some Realm", "http://example.com/ni", "ni", "ni")
143 add("c", "http://example.com/foo", "foo", "ni")
144 add("c", "http://example.com/bar", "bar", "nini")
145 add("b", "http://example.com/", "first", "blah")
146 add("b", "http://example.com/", "second", "spam")
147 add("a", "http://example.com", "1", "a")
148 add("Some Realm", "http://c.example.com:3128", "3", "c")
149 add("Some Realm", "d.example.com", "4", "d")
150 add("Some Realm", "e.example.com:3128", "5", "e")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000151
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700152 self.assertEqual(find_user_pass("Some Realm", "example.com"),
153 ('joe', 'password'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000154
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700155 #self.assertEqual(find_user_pass("Some Realm", "http://example.com/ni"),
156 # ('ni', 'ni'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000157
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700158 self.assertEqual(find_user_pass("Some Realm", "http://example.com"),
159 ('joe', 'password'))
160 self.assertEqual(find_user_pass("Some Realm", "http://example.com/"),
161 ('joe', 'password'))
162 self.assertEqual(
163 find_user_pass("Some Realm", "http://example.com/spam"),
164 ('joe', 'password'))
165 self.assertEqual(
166 find_user_pass("Some Realm", "http://example.com/spam/spam"),
167 ('joe', 'password'))
168 self.assertEqual(find_user_pass("c", "http://example.com/foo"),
169 ('foo', 'ni'))
170 self.assertEqual(find_user_pass("c", "http://example.com/bar"),
171 ('bar', 'nini'))
172 self.assertEqual(find_user_pass("b", "http://example.com/"),
173 ('second', 'spam'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000174
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700175 # No special relationship between a.example.com and example.com:
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000176
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700177 self.assertEqual(find_user_pass("a", "http://example.com/"),
178 ('1', 'a'))
179 self.assertEqual(find_user_pass("a", "http://a.example.com/"),
180 (None, None))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000181
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700182 # Ports:
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000183
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700184 self.assertEqual(find_user_pass("Some Realm", "c.example.com"),
185 (None, None))
186 self.assertEqual(find_user_pass("Some Realm", "c.example.com:3128"),
187 ('3', 'c'))
188 self.assertEqual(
189 find_user_pass("Some Realm", "http://c.example.com:3128"),
190 ('3', 'c'))
191 self.assertEqual(find_user_pass("Some Realm", "d.example.com"),
192 ('4', 'd'))
193 self.assertEqual(find_user_pass("Some Realm", "e.example.com:3128"),
194 ('5', 'e'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000195
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700196 def test_password_manager_default_port(self):
197 """
198 The point to note here is that we can't guess the default port if
199 there's no scheme. This applies to both add_password and
200 find_user_password.
201 """
202 mgr = urllib.request.HTTPPasswordMgr()
203 add = mgr.add_password
204 find_user_pass = mgr.find_user_password
205 add("f", "http://g.example.com:80", "10", "j")
206 add("g", "http://h.example.com", "11", "k")
207 add("h", "i.example.com:80", "12", "l")
208 add("i", "j.example.com", "13", "m")
209 self.assertEqual(find_user_pass("f", "g.example.com:100"),
210 (None, None))
211 self.assertEqual(find_user_pass("f", "g.example.com:80"),
212 ('10', 'j'))
213 self.assertEqual(find_user_pass("f", "g.example.com"),
214 (None, None))
215 self.assertEqual(find_user_pass("f", "http://g.example.com:100"),
216 (None, None))
217 self.assertEqual(find_user_pass("f", "http://g.example.com:80"),
218 ('10', 'j'))
219 self.assertEqual(find_user_pass("f", "http://g.example.com"),
220 ('10', 'j'))
221 self.assertEqual(find_user_pass("g", "h.example.com"), ('11', 'k'))
222 self.assertEqual(find_user_pass("g", "h.example.com:80"), ('11', 'k'))
223 self.assertEqual(find_user_pass("g", "http://h.example.com:80"),
224 ('11', 'k'))
225 self.assertEqual(find_user_pass("h", "i.example.com"), (None, None))
226 self.assertEqual(find_user_pass("h", "i.example.com:80"), ('12', 'l'))
227 self.assertEqual(find_user_pass("h", "http://i.example.com:80"),
228 ('12', 'l'))
229 self.assertEqual(find_user_pass("i", "j.example.com"), ('13', 'm'))
230 self.assertEqual(find_user_pass("i", "j.example.com:80"),
231 (None, None))
232 self.assertEqual(find_user_pass("i", "http://j.example.com"),
233 ('13', 'm'))
234 self.assertEqual(find_user_pass("i", "http://j.example.com:80"),
235 (None, None))
Andrew Svetlovbff98fe2012-11-27 23:06:19 +0200236
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000237
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000238class MockOpener:
239 addheaders = []
Facundo Batista244afcf2015-04-22 18:35:54 -0300240
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000241 def open(self, req, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
242 self.req, self.data, self.timeout = req, data, timeout
Facundo Batista244afcf2015-04-22 18:35:54 -0300243
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000244 def error(self, proto, *args):
245 self.proto, self.args = proto, args
246
Facundo Batista244afcf2015-04-22 18:35:54 -0300247
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000248class MockFile:
Facundo Batista244afcf2015-04-22 18:35:54 -0300249 def read(self, count=None):
250 pass
251
252 def readline(self, count=None):
253 pass
254
255 def close(self):
256 pass
257
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000258
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000259class MockHeaders(dict):
260 def getheaders(self, name):
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000261 return list(self.values())
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000262
Facundo Batista244afcf2015-04-22 18:35:54 -0300263
Guido van Rossum34d19282007-08-09 01:03:29 +0000264class MockResponse(io.StringIO):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000265 def __init__(self, code, msg, headers, data, url=None):
Guido van Rossum34d19282007-08-09 01:03:29 +0000266 io.StringIO.__init__(self, data)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000267 self.code, self.msg, self.headers, self.url = code, msg, headers, url
Facundo Batista244afcf2015-04-22 18:35:54 -0300268
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000269 def info(self):
270 return self.headers
Facundo Batista244afcf2015-04-22 18:35:54 -0300271
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000272 def geturl(self):
273 return self.url
274
Facundo Batista244afcf2015-04-22 18:35:54 -0300275
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000276class MockCookieJar:
277 def add_cookie_header(self, request):
278 self.ach_req = request
Facundo Batista244afcf2015-04-22 18:35:54 -0300279
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000280 def extract_cookies(self, response, request):
281 self.ec_req, self.ec_r = request, response
282
Facundo Batista244afcf2015-04-22 18:35:54 -0300283
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000284class FakeMethod:
285 def __init__(self, meth_name, action, handle):
286 self.meth_name = meth_name
287 self.handle = handle
288 self.action = action
Facundo Batista244afcf2015-04-22 18:35:54 -0300289
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000290 def __call__(self, *args):
291 return self.handle(self.meth_name, self.action, *args)
292
Facundo Batista244afcf2015-04-22 18:35:54 -0300293
Senthil Kumaran47fff872009-12-20 07:10:31 +0000294class MockHTTPResponse(io.IOBase):
295 def __init__(self, fp, msg, status, reason):
296 self.fp = fp
297 self.msg = msg
298 self.status = status
299 self.reason = reason
300 self.code = 200
301
302 def read(self):
303 return ''
304
305 def info(self):
306 return {}
307
308 def geturl(self):
309 return self.url
310
311
312class MockHTTPClass:
313 def __init__(self):
314 self.level = 0
315 self.req_headers = []
316 self.data = None
317 self.raise_on_endheaders = False
Nadeem Vawdabd26b542012-10-21 17:37:43 +0200318 self.sock = None
Senthil Kumaran47fff872009-12-20 07:10:31 +0000319 self._tunnel_headers = {}
320
321 def __call__(self, host, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
322 self.host = host
323 self.timeout = timeout
324 return self
325
326 def set_debuglevel(self, level):
327 self.level = level
328
329 def set_tunnel(self, host, port=None, headers=None):
330 self._tunnel_host = host
331 self._tunnel_port = port
332 if headers:
333 self._tunnel_headers = headers
334 else:
335 self._tunnel_headers.clear()
336
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000337 def request(self, method, url, body=None, headers=None):
Senthil Kumaran47fff872009-12-20 07:10:31 +0000338 self.method = method
339 self.selector = url
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000340 if headers is not None:
341 self.req_headers += headers.items()
Senthil Kumaran47fff872009-12-20 07:10:31 +0000342 self.req_headers.sort()
343 if body:
344 self.data = body
345 if self.raise_on_endheaders:
Andrew Svetlov0832af62012-12-18 23:10:48 +0200346 raise OSError()
Facundo Batista244afcf2015-04-22 18:35:54 -0300347
Senthil Kumaran47fff872009-12-20 07:10:31 +0000348 def getresponse(self):
349 return MockHTTPResponse(MockFile(), {}, 200, "OK")
350
Victor Stinnera4c45d72011-06-17 14:01:18 +0200351 def close(self):
352 pass
353
Facundo Batista244afcf2015-04-22 18:35:54 -0300354
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000355class MockHandler:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000356 # useful for testing handler machinery
357 # see add_ordered_mock_handlers() docstring
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000358 handler_order = 500
Facundo Batista244afcf2015-04-22 18:35:54 -0300359
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000360 def __init__(self, methods):
361 self._define_methods(methods)
Facundo Batista244afcf2015-04-22 18:35:54 -0300362
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000363 def _define_methods(self, methods):
364 for spec in methods:
Facundo Batista244afcf2015-04-22 18:35:54 -0300365 if len(spec) == 2:
366 name, action = spec
367 else:
368 name, action = spec, None
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000369 meth = FakeMethod(name, action, self.handle)
370 setattr(self.__class__, name, meth)
Facundo Batista244afcf2015-04-22 18:35:54 -0300371
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000372 def handle(self, fn_name, action, *args, **kwds):
373 self.parent.calls.append((self, fn_name, args, kwds))
374 if action is None:
375 return None
376 elif action == "return self":
377 return self
378 elif action == "return response":
379 res = MockResponse(200, "OK", {}, "")
380 return res
381 elif action == "return request":
382 return Request("http://blah/")
383 elif action.startswith("error"):
384 code = action[action.rfind(" ")+1:]
385 try:
386 code = int(code)
387 except ValueError:
388 pass
389 res = MockResponse(200, "OK", {}, "")
390 return self.parent.error("http", args[0], res, code, "", {})
391 elif action == "raise":
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000392 raise urllib.error.URLError("blah")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000393 assert False
Facundo Batista244afcf2015-04-22 18:35:54 -0300394
395 def close(self):
396 pass
397
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000398 def add_parent(self, parent):
399 self.parent = parent
400 self.parent.calls = []
Facundo Batista244afcf2015-04-22 18:35:54 -0300401
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000402 def __lt__(self, other):
403 if not hasattr(other, "handler_order"):
404 # No handler_order, leave in original order. Yuck.
405 return True
406 return self.handler_order < other.handler_order
407
Facundo Batista244afcf2015-04-22 18:35:54 -0300408
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000409def add_ordered_mock_handlers(opener, meth_spec):
410 """Create MockHandlers and add them to an OpenerDirector.
411
412 meth_spec: list of lists of tuples and strings defining methods to define
413 on handlers. eg:
414
415 [["http_error", "ftp_open"], ["http_open"]]
416
417 defines methods .http_error() and .ftp_open() on one handler, and
418 .http_open() on another. These methods just record their arguments and
419 return None. Using a tuple instead of a string causes the method to
420 perform some action (see MockHandler.handle()), eg:
421
422 [["http_error"], [("http_open", "return request")]]
423
424 defines .http_error() on one handler (which simply returns None), and
425 .http_open() on another handler, which returns a Request object.
426
427 """
428 handlers = []
429 count = 0
430 for meths in meth_spec:
Facundo Batista244afcf2015-04-22 18:35:54 -0300431 class MockHandlerSubclass(MockHandler):
432 pass
433
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000434 h = MockHandlerSubclass(meths)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000435 h.handler_order += count
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000436 h.add_parent(opener)
437 count = count + 1
438 handlers.append(h)
439 opener.add_handler(h)
440 return handlers
441
Facundo Batista244afcf2015-04-22 18:35:54 -0300442
Thomas Wouters477c8d52006-05-27 19:21:47 +0000443def build_test_opener(*handler_instances):
444 opener = OpenerDirector()
445 for h in handler_instances:
446 opener.add_handler(h)
447 return opener
448
Facundo Batista244afcf2015-04-22 18:35:54 -0300449
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000450class MockHTTPHandler(urllib.request.BaseHandler):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000451 # useful for testing redirections and auth
452 # sends supplied headers and code as first response
453 # sends 200 OK as second response
454 def __init__(self, code, headers):
455 self.code = code
456 self.headers = headers
457 self.reset()
Facundo Batista244afcf2015-04-22 18:35:54 -0300458
Thomas Wouters477c8d52006-05-27 19:21:47 +0000459 def reset(self):
460 self._count = 0
461 self.requests = []
Facundo Batista244afcf2015-04-22 18:35:54 -0300462
Thomas Wouters477c8d52006-05-27 19:21:47 +0000463 def http_open(self, req):
Barry Warsaw820c1202008-06-12 04:06:45 +0000464 import email, http.client, copy
Thomas Wouters477c8d52006-05-27 19:21:47 +0000465 self.requests.append(copy.deepcopy(req))
466 if self._count == 0:
467 self._count = self._count + 1
Georg Brandl24420152008-05-26 16:32:26 +0000468 name = http.client.responses[self.code]
Barry Warsaw820c1202008-06-12 04:06:45 +0000469 msg = email.message_from_string(self.headers)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000470 return self.parent.error(
471 "http", req, MockFile(), self.code, name, msg)
472 else:
473 self.req = req
Barry Warsaw820c1202008-06-12 04:06:45 +0000474 msg = email.message_from_string("\r\n\r\n")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000475 return MockResponse(200, "OK", msg, "", req.get_full_url())
476
Facundo Batista244afcf2015-04-22 18:35:54 -0300477
Senthil Kumaran47fff872009-12-20 07:10:31 +0000478class MockHTTPSHandler(urllib.request.AbstractHTTPHandler):
479 # Useful for testing the Proxy-Authorization request by verifying the
480 # properties of httpcon
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000481
482 def __init__(self):
483 urllib.request.AbstractHTTPHandler.__init__(self)
484 self.httpconn = MockHTTPClass()
485
Senthil Kumaran47fff872009-12-20 07:10:31 +0000486 def https_open(self, req):
487 return self.do_open(self.httpconn, req)
488
R David Murray4c7f9952015-04-16 16:36:18 -0400489
490class MockHTTPHandlerCheckAuth(urllib.request.BaseHandler):
491 # useful for testing auth
492 # sends supplied code response
493 # checks if auth header is specified in request
494 def __init__(self, code):
495 self.code = code
496 self.has_auth_header = False
497
498 def reset(self):
499 self.has_auth_header = False
500
501 def http_open(self, req):
502 if req.has_header('Authorization'):
503 self.has_auth_header = True
504 name = http.client.responses[self.code]
505 return MockResponse(self.code, name, MockFile(), "", req.get_full_url())
506
507
Facundo Batista244afcf2015-04-22 18:35:54 -0300508
Thomas Wouters477c8d52006-05-27 19:21:47 +0000509class MockPasswordManager:
510 def add_password(self, realm, uri, user, password):
511 self.realm = realm
512 self.url = uri
513 self.user = user
514 self.password = password
Facundo Batista244afcf2015-04-22 18:35:54 -0300515
Thomas Wouters477c8d52006-05-27 19:21:47 +0000516 def find_user_password(self, realm, authuri):
517 self.target_realm = realm
518 self.target_url = authuri
519 return self.user, self.password
520
521
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000522class OpenerDirectorTests(unittest.TestCase):
523
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000524 def test_add_non_handler(self):
525 class NonHandler(object):
526 pass
527 self.assertRaises(TypeError,
528 OpenerDirector().add_handler, NonHandler())
529
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000530 def test_badly_named_methods(self):
531 # test work-around for three methods that accidentally follow the
532 # naming conventions for handler methods
533 # (*_open() / *_request() / *_response())
534
535 # These used to call the accidentally-named methods, causing a
536 # TypeError in real code; here, returning self from these mock
537 # methods would either cause no exception, or AttributeError.
538
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000539 from urllib.error import URLError
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000540
541 o = OpenerDirector()
542 meth_spec = [
543 [("do_open", "return self"), ("proxy_open", "return self")],
544 [("redirect_request", "return self")],
545 ]
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700546 add_ordered_mock_handlers(o, meth_spec)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000547 o.add_handler(urllib.request.UnknownHandler())
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000548 for scheme in "do", "proxy", "redirect":
549 self.assertRaises(URLError, o.open, scheme+"://example.com/")
550
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000551 def test_handled(self):
552 # handler returning non-None means no more handlers will be called
553 o = OpenerDirector()
554 meth_spec = [
555 ["http_open", "ftp_open", "http_error_302"],
556 ["ftp_open"],
557 [("http_open", "return self")],
558 [("http_open", "return self")],
559 ]
560 handlers = add_ordered_mock_handlers(o, meth_spec)
561
562 req = Request("http://example.com/")
563 r = o.open(req)
564 # Second .http_open() gets called, third doesn't, since second returned
565 # non-None. Handlers without .http_open() never get any methods called
566 # on them.
567 # In fact, second mock handler defining .http_open() returns self
568 # (instead of response), which becomes the OpenerDirector's return
569 # value.
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000570 self.assertEqual(r, handlers[2])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000571 calls = [(handlers[0], "http_open"), (handlers[2], "http_open")]
572 for expected, got in zip(calls, o.calls):
573 handler, name, args, kwds = got
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000574 self.assertEqual((handler, name), expected)
575 self.assertEqual(args, (req,))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000576
577 def test_handler_order(self):
578 o = OpenerDirector()
579 handlers = []
Facundo Batista244afcf2015-04-22 18:35:54 -0300580 for meths, handler_order in [([("http_open", "return self")], 500),
581 (["http_open"], 0)]:
582 class MockHandlerSubclass(MockHandler):
583 pass
584
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000585 h = MockHandlerSubclass(meths)
586 h.handler_order = handler_order
587 handlers.append(h)
588 o.add_handler(h)
589
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700590 o.open("http://example.com/")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000591 # handlers called in reverse order, thanks to their sort order
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000592 self.assertEqual(o.calls[0][0], handlers[1])
593 self.assertEqual(o.calls[1][0], handlers[0])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000594
595 def test_raise(self):
596 # raising URLError stops processing of request
597 o = OpenerDirector()
598 meth_spec = [
599 [("http_open", "raise")],
600 [("http_open", "return self")],
601 ]
602 handlers = add_ordered_mock_handlers(o, meth_spec)
603
604 req = Request("http://example.com/")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000605 self.assertRaises(urllib.error.URLError, o.open, req)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000606 self.assertEqual(o.calls, [(handlers[0], "http_open", (req,), {})])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000607
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000608 def test_http_error(self):
609 # XXX http_error_default
610 # http errors are a special case
611 o = OpenerDirector()
612 meth_spec = [
613 [("http_open", "error 302")],
614 [("http_error_400", "raise"), "http_open"],
615 [("http_error_302", "return response"), "http_error_303",
616 "http_error"],
617 [("http_error_302")],
618 ]
619 handlers = add_ordered_mock_handlers(o, meth_spec)
620
621 class Unknown:
Facundo Batista244afcf2015-04-22 18:35:54 -0300622 def __eq__(self, other):
623 return True
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000624
625 req = Request("http://example.com/")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700626 o.open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000627 assert len(o.calls) == 2
628 calls = [(handlers[0], "http_open", (req,)),
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000629 (handlers[2], "http_error_302",
630 (req, Unknown(), 302, "", {}))]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000631 for expected, got in zip(calls, o.calls):
632 handler, method_name, args = expected
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000633 self.assertEqual((handler, method_name), got[:2])
634 self.assertEqual(args, got[2])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000635
636 def test_processors(self):
637 # *_request / *_response methods get called appropriately
638 o = OpenerDirector()
639 meth_spec = [
640 [("http_request", "return request"),
641 ("http_response", "return response")],
642 [("http_request", "return request"),
643 ("http_response", "return response")],
644 ]
645 handlers = add_ordered_mock_handlers(o, meth_spec)
646
647 req = Request("http://example.com/")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700648 o.open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000649 # processor methods are called on *all* handlers that define them,
650 # not just the first handler that handles the request
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000651 calls = [
652 (handlers[0], "http_request"), (handlers[1], "http_request"),
653 (handlers[0], "http_response"), (handlers[1], "http_response")]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000654
655 for i, (handler, name, args, kwds) in enumerate(o.calls):
656 if i < 2:
657 # *_request
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000658 self.assertEqual((handler, name), calls[i])
659 self.assertEqual(len(args), 1)
Ezio Melottie9615932010-01-24 19:26:24 +0000660 self.assertIsInstance(args[0], Request)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000661 else:
662 # *_response
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000663 self.assertEqual((handler, name), calls[i])
664 self.assertEqual(len(args), 2)
Ezio Melottie9615932010-01-24 19:26:24 +0000665 self.assertIsInstance(args[0], Request)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000666 # response from opener.open is None, because there's no
667 # handler that defines http_open to handle it
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200668 if args[1] is not None:
669 self.assertIsInstance(args[1], MockResponse)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000670
Facundo Batista244afcf2015-04-22 18:35:54 -0300671
Tim Peters58eb11c2004-01-18 20:29:55 +0000672def sanepathname2url(path):
Victor Stinner6c6f8512010-08-07 10:09:35 +0000673 try:
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000674 path.encode("utf-8")
Victor Stinner6c6f8512010-08-07 10:09:35 +0000675 except UnicodeEncodeError:
676 raise unittest.SkipTest("path is not encodable to utf8")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000677 urlpath = urllib.request.pathname2url(path)
Tim Peters58eb11c2004-01-18 20:29:55 +0000678 if os.name == "nt" and urlpath.startswith("///"):
679 urlpath = urlpath[2:]
680 # XXX don't ask me about the mac...
681 return urlpath
682
Facundo Batista244afcf2015-04-22 18:35:54 -0300683
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000684class HandlerTests(unittest.TestCase):
685
686 def test_ftp(self):
687 class MockFTPWrapper:
Facundo Batista244afcf2015-04-22 18:35:54 -0300688 def __init__(self, data):
689 self.data = data
690
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000691 def retrfile(self, filename, filetype):
692 self.filename, self.filetype = filename, filetype
Guido van Rossum34d19282007-08-09 01:03:29 +0000693 return io.StringIO(self.data), len(self.data)
Facundo Batista244afcf2015-04-22 18:35:54 -0300694
695 def close(self):
696 pass
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000697
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000698 class NullFTPHandler(urllib.request.FTPHandler):
Facundo Batista244afcf2015-04-22 18:35:54 -0300699 def __init__(self, data):
700 self.data = data
701
Georg Brandlf78e02b2008-06-10 17:40:04 +0000702 def connect_ftp(self, user, passwd, host, port, dirs,
703 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000704 self.user, self.passwd = user, passwd
705 self.host, self.port = host, port
706 self.dirs = dirs
707 self.ftpwrapper = MockFTPWrapper(self.data)
708 return self.ftpwrapper
709
Georg Brandlf78e02b2008-06-10 17:40:04 +0000710 import ftplib
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000711 data = "rheum rhaponicum"
712 h = NullFTPHandler(data)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700713 h.parent = MockOpener()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000714
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000715 for url, host, port, user, passwd, type_, dirs, filename, mimetype in [
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000716 ("ftp://localhost/foo/bar/baz.html",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000717 "localhost", ftplib.FTP_PORT, "", "", "I",
718 ["foo", "bar"], "baz.html", "text/html"),
719 ("ftp://parrot@localhost/foo/bar/baz.html",
720 "localhost", ftplib.FTP_PORT, "parrot", "", "I",
721 ["foo", "bar"], "baz.html", "text/html"),
722 ("ftp://%25parrot@localhost/foo/bar/baz.html",
723 "localhost", ftplib.FTP_PORT, "%parrot", "", "I",
724 ["foo", "bar"], "baz.html", "text/html"),
725 ("ftp://%2542parrot@localhost/foo/bar/baz.html",
726 "localhost", ftplib.FTP_PORT, "%42parrot", "", "I",
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000727 ["foo", "bar"], "baz.html", "text/html"),
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000728 ("ftp://localhost:80/foo/bar/",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000729 "localhost", 80, "", "", "D",
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000730 ["foo", "bar"], "", None),
731 ("ftp://localhost/baz.gif;type=a",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000732 "localhost", ftplib.FTP_PORT, "", "", "A",
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000733 [], "baz.gif", None), # XXX really this should guess image/gif
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000734 ]:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000735 req = Request(url)
736 req.timeout = None
737 r = h.ftp_open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000738 # ftp authentication not yet implemented by FTPHandler
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000739 self.assertEqual(h.user, user)
740 self.assertEqual(h.passwd, passwd)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000741 self.assertEqual(h.host, socket.gethostbyname(host))
742 self.assertEqual(h.port, port)
743 self.assertEqual(h.dirs, dirs)
744 self.assertEqual(h.ftpwrapper.filename, filename)
745 self.assertEqual(h.ftpwrapper.filetype, type_)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000746 headers = r.info()
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000747 self.assertEqual(headers.get("Content-type"), mimetype)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000748 self.assertEqual(int(headers["Content-length"]), len(data))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000749
750 def test_file(self):
Senthil Kumaranbc07ac52014-07-22 00:15:20 -0700751 import email.utils
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000752 h = urllib.request.FileHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000753 o = h.parent = MockOpener()
754
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000755 TESTFN = support.TESTFN
Tim Peters58eb11c2004-01-18 20:29:55 +0000756 urlpath = sanepathname2url(os.path.abspath(TESTFN))
Guido van Rossum6a2ccd02007-07-16 20:51:57 +0000757 towrite = b"hello, world\n"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000758 urls = [
Tim Peters58eb11c2004-01-18 20:29:55 +0000759 "file://localhost%s" % urlpath,
760 "file://%s" % urlpath,
761 "file://%s%s" % (socket.gethostbyname('localhost'), urlpath),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000762 ]
763 try:
764 localaddr = socket.gethostbyname(socket.gethostname())
765 except socket.gaierror:
766 localaddr = ''
767 if localaddr:
768 urls.append("file://%s%s" % (localaddr, urlpath))
769
770 for url in urls:
Tim Peters58eb11c2004-01-18 20:29:55 +0000771 f = open(TESTFN, "wb")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000772 try:
773 try:
774 f.write(towrite)
775 finally:
776 f.close()
777
778 r = h.file_open(Request(url))
779 try:
780 data = r.read()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000781 headers = r.info()
Senthil Kumaran4fbed102010-05-08 03:29:09 +0000782 respurl = r.geturl()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000783 finally:
784 r.close()
Tim Peters58eb11c2004-01-18 20:29:55 +0000785 stats = os.stat(TESTFN)
Benjamin Petersona0c0a4a2008-06-12 22:15:50 +0000786 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000787 finally:
788 os.remove(TESTFN)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000789 self.assertEqual(data, towrite)
790 self.assertEqual(headers["Content-type"], "text/plain")
791 self.assertEqual(headers["Content-length"], "13")
Tim Peters58eb11c2004-01-18 20:29:55 +0000792 self.assertEqual(headers["Last-modified"], modified)
Senthil Kumaran4fbed102010-05-08 03:29:09 +0000793 self.assertEqual(respurl, url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000794
795 for url in [
Tim Peters58eb11c2004-01-18 20:29:55 +0000796 "file://localhost:80%s" % urlpath,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000797 "file:///file_does_not_exist.txt",
Senthil Kumaranbc07ac52014-07-22 00:15:20 -0700798 "file://not-a-local-host.com//dir/file.txt",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000799 "file://%s:80%s/%s" % (socket.gethostbyname('localhost'),
800 os.getcwd(), TESTFN),
801 "file://somerandomhost.ontheinternet.com%s/%s" %
802 (os.getcwd(), TESTFN),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000803 ]:
804 try:
Tim Peters58eb11c2004-01-18 20:29:55 +0000805 f = open(TESTFN, "wb")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000806 try:
807 f.write(towrite)
808 finally:
809 f.close()
810
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000811 self.assertRaises(urllib.error.URLError,
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000812 h.file_open, Request(url))
813 finally:
814 os.remove(TESTFN)
815
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000816 h = urllib.request.FileHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000817 o = h.parent = MockOpener()
818 # XXXX why does // mean ftp (and /// mean not ftp!), and where
819 # is file: scheme specified? I think this is really a bug, and
820 # what was intended was to distinguish between URLs like:
821 # file:/blah.txt (a file)
822 # file://localhost/blah.txt (a file)
823 # file:///blah.txt (a file)
824 # file://ftp.example.com/blah.txt (an ftp URL)
825 for url, ftp in [
Senthil Kumaran383c32d2010-10-14 11:57:35 +0000826 ("file://ftp.example.com//foo.txt", False),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000827 ("file://ftp.example.com///foo.txt", False),
828# XXXX bug: fails with OSError, should be URLError
829 ("file://ftp.example.com/foo.txt", False),
Senthil Kumaran383c32d2010-10-14 11:57:35 +0000830 ("file://somehost//foo/something.txt", False),
Senthil Kumaran2ef16322010-07-11 03:12:43 +0000831 ("file://localhost//foo/something.txt", False),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000832 ]:
833 req = Request(url)
834 try:
835 h.file_open(req)
836 # XXXX remove OSError when bug fixed
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000837 except (urllib.error.URLError, OSError):
Florent Xicluna419e3842010-08-08 16:16:07 +0000838 self.assertFalse(ftp)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000839 else:
Florent Xicluna419e3842010-08-08 16:16:07 +0000840 self.assertIs(o.req, req)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000841 self.assertEqual(req.type, "ftp")
Łukasz Langad7e81cc2011-01-09 18:18:53 +0000842 self.assertEqual(req.type == "ftp", ftp)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000843
844 def test_http(self):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000845
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000846 h = urllib.request.AbstractHTTPHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000847 o = h.parent = MockOpener()
848
849 url = "http://example.com/"
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000850 for method, data in [("GET", None), ("POST", b"blah")]:
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000851 req = Request(url, data, {"Foo": "bar"})
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000852 req.timeout = None
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000853 req.add_unredirected_header("Spam", "eggs")
854 http = MockHTTPClass()
855 r = h.do_open(http, req)
856
857 # result attributes
858 r.read; r.readline # wrapped MockFile methods
859 r.info; r.geturl # addinfourl methods
860 r.code, r.msg == 200, "OK" # added from MockHTTPClass.getreply()
861 hdrs = r.info()
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000862 hdrs.get; hdrs.__contains__ # r.info() gives dict from .getreply()
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000863 self.assertEqual(r.geturl(), url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000864
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000865 self.assertEqual(http.host, "example.com")
866 self.assertEqual(http.level, 0)
867 self.assertEqual(http.method, method)
868 self.assertEqual(http.selector, "/")
869 self.assertEqual(http.req_headers,
Jeremy Hyltonb3ee6f92004-02-24 19:40:35 +0000870 [("Connection", "close"),
871 ("Foo", "bar"), ("Spam", "eggs")])
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000872 self.assertEqual(http.data, data)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000873
Andrew Svetlov0832af62012-12-18 23:10:48 +0200874 # check OSError converted to URLError
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000875 http.raise_on_endheaders = True
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000876 self.assertRaises(urllib.error.URLError, h.do_open, http, req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000877
Senthil Kumaran29333122011-02-11 11:25:47 +0000878 # Check for TypeError on POST data which is str.
879 req = Request("http://example.com/","badpost")
880 self.assertRaises(TypeError, h.do_request_, req)
881
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000882 # check adding of standard headers
883 o.addheaders = [("Spam", "eggs")]
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000884 for data in b"", None: # POST, GET
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000885 req = Request("http://example.com/", data)
886 r = MockResponse(200, "OK", {}, "")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000887 newreq = h.do_request_(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000888 if data is None: # GET
Benjamin Peterson577473f2010-01-19 00:09:57 +0000889 self.assertNotIn("Content-length", req.unredirected_hdrs)
890 self.assertNotIn("Content-type", req.unredirected_hdrs)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000891 else: # POST
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000892 self.assertEqual(req.unredirected_hdrs["Content-length"], "0")
893 self.assertEqual(req.unredirected_hdrs["Content-type"],
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000894 "application/x-www-form-urlencoded")
895 # XXX the details of Host could be better tested
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000896 self.assertEqual(req.unredirected_hdrs["Host"], "example.com")
897 self.assertEqual(req.unredirected_hdrs["Spam"], "eggs")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000898
899 # don't clobber existing headers
900 req.add_unredirected_header("Content-length", "foo")
901 req.add_unredirected_header("Content-type", "bar")
902 req.add_unredirected_header("Host", "baz")
903 req.add_unredirected_header("Spam", "foo")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000904 newreq = h.do_request_(req)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000905 self.assertEqual(req.unredirected_hdrs["Content-length"], "foo")
906 self.assertEqual(req.unredirected_hdrs["Content-type"], "bar")
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000907 self.assertEqual(req.unredirected_hdrs["Host"], "baz")
908 self.assertEqual(req.unredirected_hdrs["Spam"], "foo")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000909
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000910 # Check iterable body support
911 def iterable_body():
912 yield b"one"
913 yield b"two"
914 yield b"three"
915
916 for headers in {}, {"Content-Length": 11}:
917 req = Request("http://example.com/", iterable_body(), headers)
918 if not headers:
919 # Having an iterable body without a Content-Length should
920 # raise an exception
921 self.assertRaises(ValueError, h.do_request_, req)
922 else:
923 newreq = h.do_request_(req)
924
Senthil Kumaran29333122011-02-11 11:25:47 +0000925 # A file object.
926 # Test only Content-Length attribute of request.
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000927
Senthil Kumaran29333122011-02-11 11:25:47 +0000928 file_obj = io.BytesIO()
929 file_obj.write(b"Something\nSomething\nSomething\n")
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000930
931 for headers in {}, {"Content-Length": 30}:
932 req = Request("http://example.com/", file_obj, headers)
933 if not headers:
934 # Having an iterable body without a Content-Length should
935 # raise an exception
936 self.assertRaises(ValueError, h.do_request_, req)
937 else:
938 newreq = h.do_request_(req)
Facundo Batista244afcf2015-04-22 18:35:54 -0300939 self.assertEqual(int(newreq.get_header('Content-length')), 30)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000940
941 file_obj.close()
942
943 # array.array Iterable - Content Length is calculated
944
945 iterable_array = array.array("I",[1,2,3,4])
946
947 for headers in {}, {"Content-Length": 16}:
948 req = Request("http://example.com/", iterable_array, headers)
949 newreq = h.do_request_(req)
950 self.assertEqual(int(newreq.get_header('Content-length')),16)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000951
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000952 def test_http_doubleslash(self):
953 # Checks the presence of any unnecessary double slash in url does not
954 # break anything. Previously, a double slash directly after the host
Ezio Melottie130a522011-10-19 10:58:56 +0300955 # could cause incorrect parsing.
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000956 h = urllib.request.AbstractHTTPHandler()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700957 h.parent = MockOpener()
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000958
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000959 data = b""
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000960 ds_urls = [
961 "http://example.com/foo/bar/baz.html",
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 ]
966
967 for ds_url in ds_urls:
968 ds_req = Request(ds_url, data)
969
970 # Check whether host is determined correctly if there is no proxy
971 np_ds_req = h.do_request_(ds_req)
Facundo Batista244afcf2015-04-22 18:35:54 -0300972 self.assertEqual(np_ds_req.unredirected_hdrs["Host"], "example.com")
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000973
974 # Check whether host is determined correctly if there is a proxy
Facundo Batista244afcf2015-04-22 18:35:54 -0300975 ds_req.set_proxy("someproxy:3128", None)
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000976 p_ds_req = h.do_request_(ds_req)
Facundo Batista244afcf2015-04-22 18:35:54 -0300977 self.assertEqual(p_ds_req.unredirected_hdrs["Host"], "example.com")
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000978
Senthil Kumaran52380922013-04-25 05:45:48 -0700979 def test_full_url_setter(self):
980 # Checks to ensure that components are set correctly after setting the
981 # full_url of a Request object
982
983 urls = [
984 'http://example.com?foo=bar#baz',
985 'http://example.com?foo=bar&spam=eggs#bash',
986 'http://example.com',
987 ]
988
989 # testing a reusable request instance, but the url parameter is
990 # required, so just use a dummy one to instantiate
991 r = Request('http://example.com')
992 for url in urls:
993 r.full_url = url
Senthil Kumaran83070752013-05-24 09:14:12 -0700994 parsed = urlparse(url)
995
Senthil Kumaran52380922013-04-25 05:45:48 -0700996 self.assertEqual(r.get_full_url(), url)
Senthil Kumaran83070752013-05-24 09:14:12 -0700997 # full_url setter uses splittag to split into components.
998 # splittag sets the fragment as None while urlparse sets it to ''
999 self.assertEqual(r.fragment or '', parsed.fragment)
1000 self.assertEqual(urlparse(r.get_full_url()).query, parsed.query)
Senthil Kumaran52380922013-04-25 05:45:48 -07001001
1002 def test_full_url_deleter(self):
1003 r = Request('http://www.example.com')
1004 del r.full_url
1005 self.assertIsNone(r.full_url)
1006 self.assertIsNone(r.fragment)
1007 self.assertEqual(r.selector, '')
1008
Senthil Kumaranc2958622010-11-22 04:48:26 +00001009 def test_fixpath_in_weirdurls(self):
1010 # Issue4493: urllib2 to supply '/' when to urls where path does not
1011 # start with'/'
1012
1013 h = urllib.request.AbstractHTTPHandler()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001014 h.parent = MockOpener()
Senthil Kumaranc2958622010-11-22 04:48:26 +00001015
1016 weird_url = 'http://www.python.org?getspam'
1017 req = Request(weird_url)
1018 newreq = h.do_request_(req)
Facundo Batista244afcf2015-04-22 18:35:54 -03001019 self.assertEqual(newreq.host, 'www.python.org')
1020 self.assertEqual(newreq.selector, '/?getspam')
Senthil Kumaranc2958622010-11-22 04:48:26 +00001021
1022 url_without_path = 'http://www.python.org'
1023 req = Request(url_without_path)
1024 newreq = h.do_request_(req)
Facundo Batista244afcf2015-04-22 18:35:54 -03001025 self.assertEqual(newreq.host, 'www.python.org')
1026 self.assertEqual(newreq.selector, '')
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001027
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001028 def test_errors(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001029 h = urllib.request.HTTPErrorProcessor()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001030 o = h.parent = MockOpener()
1031
1032 url = "http://example.com/"
1033 req = Request(url)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001034 # all 2xx are passed through
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001035 r = MockResponse(200, "OK", {}, "", url)
1036 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +00001037 self.assertIs(r, newr)
1038 self.assertFalse(hasattr(o, "proto")) # o.error not called
Guido van Rossumd8faa362007-04-27 19:54:29 +00001039 r = MockResponse(202, "Accepted", {}, "", url)
1040 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +00001041 self.assertIs(r, newr)
1042 self.assertFalse(hasattr(o, "proto")) # o.error not called
Guido van Rossumd8faa362007-04-27 19:54:29 +00001043 r = MockResponse(206, "Partial content", {}, "", url)
1044 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +00001045 self.assertIs(r, newr)
1046 self.assertFalse(hasattr(o, "proto")) # o.error not called
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001047 # anything else calls o.error (and MockOpener returns None, here)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001048 r = MockResponse(502, "Bad gateway", {}, "", url)
Florent Xicluna419e3842010-08-08 16:16:07 +00001049 self.assertIsNone(h.http_response(req, r))
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001050 self.assertEqual(o.proto, "http") # o.error called
Guido van Rossumd8faa362007-04-27 19:54:29 +00001051 self.assertEqual(o.args, (req, r, 502, "Bad gateway", {}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001052
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001053 def test_cookies(self):
1054 cj = MockCookieJar()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001055 h = urllib.request.HTTPCookieProcessor(cj)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001056 h.parent = MockOpener()
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001057
1058 req = Request("http://example.com/")
1059 r = MockResponse(200, "OK", {}, "")
1060 newreq = h.http_request(req)
Florent Xicluna419e3842010-08-08 16:16:07 +00001061 self.assertIs(cj.ach_req, req)
1062 self.assertIs(cj.ach_req, newreq)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001063 self.assertEqual(req.origin_req_host, "example.com")
1064 self.assertFalse(req.unverifiable)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001065 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +00001066 self.assertIs(cj.ec_req, req)
1067 self.assertIs(cj.ec_r, r)
1068 self.assertIs(r, newr)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001069
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001070 def test_redirect(self):
1071 from_url = "http://example.com/a.html"
1072 to_url = "http://example.com/b.html"
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001073 h = urllib.request.HTTPRedirectHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001074 o = h.parent = MockOpener()
1075
1076 # ordinary redirect behaviour
1077 for code in 301, 302, 303, 307:
1078 for data in None, "blah\nblah\n":
1079 method = getattr(h, "http_error_%s" % code)
1080 req = Request(from_url, data)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001081 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001082 req.add_header("Nonsense", "viking=withhold")
Christian Heimes77c02eb2008-02-09 02:18:51 +00001083 if data is not None:
1084 req.add_header("Content-Length", str(len(data)))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001085 req.add_unredirected_header("Spam", "spam")
1086 try:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001087 method(req, MockFile(), code, "Blah",
1088 MockHeaders({"location": to_url}))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001089 except urllib.error.HTTPError:
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001090 # 307 in response to POST requires user OK
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001091 self.assertEqual(code, 307)
1092 self.assertIsNotNone(data)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001093 self.assertEqual(o.req.get_full_url(), to_url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001094 try:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001095 self.assertEqual(o.req.get_method(), "GET")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001096 except AttributeError:
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001097 self.assertFalse(o.req.data)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001098
1099 # now it's a GET, there should not be headers regarding content
1100 # (possibly dragged from before being a POST)
1101 headers = [x.lower() for x in o.req.headers]
Benjamin Peterson577473f2010-01-19 00:09:57 +00001102 self.assertNotIn("content-length", headers)
1103 self.assertNotIn("content-type", headers)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001104
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001105 self.assertEqual(o.req.headers["Nonsense"],
1106 "viking=withhold")
Benjamin Peterson577473f2010-01-19 00:09:57 +00001107 self.assertNotIn("Spam", o.req.headers)
1108 self.assertNotIn("Spam", o.req.unredirected_hdrs)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001109
1110 # loop detection
1111 req = Request(from_url)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001112 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Facundo Batista244afcf2015-04-22 18:35:54 -03001113
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001114 def redirect(h, req, url=to_url):
1115 h.http_error_302(req, MockFile(), 302, "Blah",
1116 MockHeaders({"location": url}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001117 # Note that the *original* request shares the same record of
1118 # redirections with the sub-requests caused by the redirections.
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001119
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001120 # detect infinite loop redirect of a URL to itself
1121 req = Request(from_url, origin_req_host="example.com")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001122 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001123 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001124 try:
1125 while 1:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001126 redirect(h, req, "http://example.com/")
1127 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001128 except urllib.error.HTTPError:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001129 # don't stop until max_repeats, because cookies may introduce state
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001130 self.assertEqual(count, urllib.request.HTTPRedirectHandler.max_repeats)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001131
1132 # detect endless non-repeating chain of redirects
1133 req = Request(from_url, origin_req_host="example.com")
1134 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001135 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001136 try:
1137 while 1:
1138 redirect(h, req, "http://example.com/%d" % count)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001139 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001140 except urllib.error.HTTPError:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001141 self.assertEqual(count,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001142 urllib.request.HTTPRedirectHandler.max_redirections)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001143
guido@google.coma119df92011-03-29 11:41:02 -07001144 def test_invalid_redirect(self):
1145 from_url = "http://example.com/a.html"
1146 valid_schemes = ['http','https','ftp']
1147 invalid_schemes = ['file','imap','ldap']
1148 schemeless_url = "example.com/b.html"
1149 h = urllib.request.HTTPRedirectHandler()
1150 o = h.parent = MockOpener()
1151 req = Request(from_url)
1152 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1153
1154 for scheme in invalid_schemes:
1155 invalid_url = scheme + '://' + schemeless_url
1156 self.assertRaises(urllib.error.HTTPError, h.http_error_302,
1157 req, MockFile(), 302, "Security Loophole",
1158 MockHeaders({"location": invalid_url}))
1159
1160 for scheme in valid_schemes:
1161 valid_url = scheme + '://' + schemeless_url
1162 h.http_error_302(req, MockFile(), 302, "That's fine",
1163 MockHeaders({"location": valid_url}))
1164 self.assertEqual(o.req.get_full_url(), valid_url)
1165
Senthil Kumaran6497aa32012-01-04 13:46:59 +08001166 def test_relative_redirect(self):
1167 from_url = "http://example.com/a.html"
1168 relative_url = "/b.html"
1169 h = urllib.request.HTTPRedirectHandler()
1170 o = h.parent = MockOpener()
1171 req = Request(from_url)
1172 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1173
1174 valid_url = urllib.parse.urljoin(from_url,relative_url)
1175 h.http_error_302(req, MockFile(), 302, "That's fine",
1176 MockHeaders({"location": valid_url}))
1177 self.assertEqual(o.req.get_full_url(), valid_url)
1178
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001179 def test_cookie_redirect(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001180 # cookies shouldn't leak into redirected requests
Georg Brandl24420152008-05-26 16:32:26 +00001181 from http.cookiejar import CookieJar
1182 from test.test_http_cookiejar import interact_netscape
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001183
1184 cj = CookieJar()
1185 interact_netscape(cj, "http://www.example.com/", "spam=eggs")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001186 hh = MockHTTPHandler(302, "Location: http://www.cracker.com/\r\n\r\n")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001187 hdeh = urllib.request.HTTPDefaultErrorHandler()
1188 hrh = urllib.request.HTTPRedirectHandler()
1189 cp = urllib.request.HTTPCookieProcessor(cj)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001190 o = build_test_opener(hh, hdeh, hrh, cp)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001191 o.open("http://www.example.com/")
Florent Xicluna419e3842010-08-08 16:16:07 +00001192 self.assertFalse(hh.req.has_header("Cookie"))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001193
Senthil Kumaran26430412011-04-13 07:01:19 +08001194 def test_redirect_fragment(self):
1195 redirected_url = 'http://www.example.com/index.html#OK\r\n\r\n'
1196 hh = MockHTTPHandler(302, 'Location: ' + redirected_url)
1197 hdeh = urllib.request.HTTPDefaultErrorHandler()
1198 hrh = urllib.request.HTTPRedirectHandler()
1199 o = build_test_opener(hh, hdeh, hrh)
1200 fp = o.open('http://www.example.com')
1201 self.assertEqual(fp.geturl(), redirected_url.strip())
1202
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001203 def test_proxy(self):
1204 o = OpenerDirector()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001205 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001206 o.add_handler(ph)
1207 meth_spec = [
1208 [("http_open", "return response")]
1209 ]
1210 handlers = add_ordered_mock_handlers(o, meth_spec)
1211
1212 req = Request("http://acme.example.com/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001213 self.assertEqual(req.host, "acme.example.com")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001214 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001215 self.assertEqual(req.host, "proxy.example.com:3128")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001216
1217 self.assertEqual([(handlers[0], "http_open")],
1218 [tup[0:2] for tup in o.calls])
1219
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001220 def test_proxy_no_proxy(self):
1221 os.environ['no_proxy'] = 'python.org'
1222 o = OpenerDirector()
1223 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1224 o.add_handler(ph)
1225 req = Request("http://www.perl.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001226 self.assertEqual(req.host, "www.perl.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001227 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001228 self.assertEqual(req.host, "proxy.example.com")
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001229 req = Request("http://www.python.org")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001230 self.assertEqual(req.host, "www.python.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001231 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001232 self.assertEqual(req.host, "www.python.org")
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001233 del os.environ['no_proxy']
1234
Ronald Oussorene72e1612011-03-14 18:15:25 -04001235 def test_proxy_no_proxy_all(self):
1236 os.environ['no_proxy'] = '*'
1237 o = OpenerDirector()
1238 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1239 o.add_handler(ph)
1240 req = Request("http://www.python.org")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001241 self.assertEqual(req.host, "www.python.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001242 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001243 self.assertEqual(req.host, "www.python.org")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001244 del os.environ['no_proxy']
1245
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001246 def test_proxy_https(self):
1247 o = OpenerDirector()
1248 ph = urllib.request.ProxyHandler(dict(https="proxy.example.com:3128"))
1249 o.add_handler(ph)
1250 meth_spec = [
1251 [("https_open", "return response")]
1252 ]
1253 handlers = add_ordered_mock_handlers(o, meth_spec)
1254
1255 req = Request("https://www.example.com/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001256 self.assertEqual(req.host, "www.example.com")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001257 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001258 self.assertEqual(req.host, "proxy.example.com:3128")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001259 self.assertEqual([(handlers[0], "https_open")],
1260 [tup[0:2] for tup in o.calls])
1261
Senthil Kumaran47fff872009-12-20 07:10:31 +00001262 def test_proxy_https_proxy_authorization(self):
1263 o = OpenerDirector()
1264 ph = urllib.request.ProxyHandler(dict(https='proxy.example.com:3128'))
1265 o.add_handler(ph)
1266 https_handler = MockHTTPSHandler()
1267 o.add_handler(https_handler)
1268 req = Request("https://www.example.com/")
Facundo Batista244afcf2015-04-22 18:35:54 -03001269 req.add_header("Proxy-Authorization", "FooBar")
1270 req.add_header("User-Agent", "Grail")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001271 self.assertEqual(req.host, "www.example.com")
Senthil Kumaran47fff872009-12-20 07:10:31 +00001272 self.assertIsNone(req._tunnel_host)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001273 o.open(req)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001274 # Verify Proxy-Authorization gets tunneled to request.
1275 # httpsconn req_headers do not have the Proxy-Authorization header but
1276 # the req will have.
Facundo Batista244afcf2015-04-22 18:35:54 -03001277 self.assertNotIn(("Proxy-Authorization", "FooBar"),
Senthil Kumaran47fff872009-12-20 07:10:31 +00001278 https_handler.httpconn.req_headers)
Facundo Batista244afcf2015-04-22 18:35:54 -03001279 self.assertIn(("User-Agent", "Grail"),
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001280 https_handler.httpconn.req_headers)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001281 self.assertIsNotNone(req._tunnel_host)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001282 self.assertEqual(req.host, "proxy.example.com:3128")
Facundo Batista244afcf2015-04-22 18:35:54 -03001283 self.assertEqual(req.get_header("Proxy-authorization"), "FooBar")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001284
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001285 # TODO: This should be only for OSX
1286 @unittest.skipUnless(sys.platform == 'darwin', "only relevant for OSX")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001287 def test_osx_proxy_bypass(self):
1288 bypass = {
1289 'exclude_simple': False,
1290 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.10',
1291 '10.0/16']
1292 }
1293 # Check hosts that should trigger the proxy bypass
1294 for host in ('foo.bar', 'www.bar.com', '127.0.0.1', '10.10.0.1',
1295 '10.0.0.1'):
1296 self.assertTrue(_proxy_bypass_macosx_sysconf(host, bypass),
1297 'expected bypass of %s to be True' % host)
1298 # Check hosts that should not trigger the proxy bypass
R David Murrayfdbe9182014-03-15 12:00:14 -04001299 for host in ('abc.foo.bar', 'bar.com', '127.0.0.2', '10.11.0.1',
1300 'notinbypass'):
Ronald Oussorene72e1612011-03-14 18:15:25 -04001301 self.assertFalse(_proxy_bypass_macosx_sysconf(host, bypass),
1302 'expected bypass of %s to be False' % host)
1303
1304 # Check the exclude_simple flag
1305 bypass = {'exclude_simple': True, 'exceptions': []}
1306 self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass))
1307
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001308 def test_basic_auth(self, quote_char='"'):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001309 opener = OpenerDirector()
1310 password_manager = MockPasswordManager()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001311 auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001312 realm = "ACME Widget Store"
1313 http_handler = MockHTTPHandler(
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001314 401, 'WWW-Authenticate: Basic realm=%s%s%s\r\n\r\n' %
Facundo Batista244afcf2015-04-22 18:35:54 -03001315 (quote_char, realm, quote_char))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001316 opener.add_handler(auth_handler)
1317 opener.add_handler(http_handler)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001318 self._test_basic_auth(opener, auth_handler, "Authorization",
1319 realm, http_handler, password_manager,
1320 "http://acme.example.com/protected",
1321 "http://acme.example.com/protected",
1322 )
1323
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001324 def test_basic_auth_with_single_quoted_realm(self):
1325 self.test_basic_auth(quote_char="'")
1326
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +08001327 def test_basic_auth_with_unquoted_realm(self):
1328 opener = OpenerDirector()
1329 password_manager = MockPasswordManager()
1330 auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
1331 realm = "ACME Widget Store"
1332 http_handler = MockHTTPHandler(
1333 401, 'WWW-Authenticate: Basic realm=%s\r\n\r\n' % realm)
1334 opener.add_handler(auth_handler)
1335 opener.add_handler(http_handler)
Senthil Kumaran0ea91cb2012-05-15 23:59:42 +08001336 with self.assertWarns(UserWarning):
1337 self._test_basic_auth(opener, auth_handler, "Authorization",
1338 realm, http_handler, password_manager,
1339 "http://acme.example.com/protected",
1340 "http://acme.example.com/protected",
1341 )
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +08001342
Thomas Wouters477c8d52006-05-27 19:21:47 +00001343 def test_proxy_basic_auth(self):
1344 opener = OpenerDirector()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001345 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001346 opener.add_handler(ph)
1347 password_manager = MockPasswordManager()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001348 auth_handler = urllib.request.ProxyBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001349 realm = "ACME Networks"
1350 http_handler = MockHTTPHandler(
1351 407, 'Proxy-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001352 opener.add_handler(auth_handler)
1353 opener.add_handler(http_handler)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001354 self._test_basic_auth(opener, auth_handler, "Proxy-authorization",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001355 realm, http_handler, password_manager,
1356 "http://acme.example.com:3128/protected",
1357 "proxy.example.com:3128",
1358 )
1359
1360 def test_basic_and_digest_auth_handlers(self):
Andrew Svetlov7bd61cb2012-12-19 22:49:25 +02001361 # HTTPDigestAuthHandler raised an exception if it couldn't handle a 40*
Thomas Wouters477c8d52006-05-27 19:21:47 +00001362 # response (http://python.org/sf/1479302), where it should instead
1363 # return None to allow another handler (especially
1364 # HTTPBasicAuthHandler) to handle the response.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001365
1366 # Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must
1367 # try digest first (since it's the strongest auth scheme), so we record
1368 # order of calls here to check digest comes first:
1369 class RecordingOpenerDirector(OpenerDirector):
1370 def __init__(self):
1371 OpenerDirector.__init__(self)
1372 self.recorded = []
Facundo Batista244afcf2015-04-22 18:35:54 -03001373
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001374 def record(self, info):
1375 self.recorded.append(info)
Facundo Batista244afcf2015-04-22 18:35:54 -03001376
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001377 class TestDigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001378 def http_error_401(self, *args, **kwds):
1379 self.parent.record("digest")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001380 urllib.request.HTTPDigestAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001381 *args, **kwds)
Facundo Batista244afcf2015-04-22 18:35:54 -03001382
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001383 class TestBasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001384 def http_error_401(self, *args, **kwds):
1385 self.parent.record("basic")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001386 urllib.request.HTTPBasicAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001387 *args, **kwds)
1388
1389 opener = RecordingOpenerDirector()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001390 password_manager = MockPasswordManager()
1391 digest_handler = TestDigestAuthHandler(password_manager)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001392 basic_handler = TestBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001393 realm = "ACME Networks"
1394 http_handler = MockHTTPHandler(
1395 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001396 opener.add_handler(basic_handler)
1397 opener.add_handler(digest_handler)
1398 opener.add_handler(http_handler)
1399
1400 # check basic auth isn't blocked by digest handler failing
Thomas Wouters477c8d52006-05-27 19:21:47 +00001401 self._test_basic_auth(opener, basic_handler, "Authorization",
1402 realm, http_handler, password_manager,
1403 "http://acme.example.com/protected",
1404 "http://acme.example.com/protected",
1405 )
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001406 # check digest was tried before basic (twice, because
1407 # _test_basic_auth called .open() twice)
1408 self.assertEqual(opener.recorded, ["digest", "basic"]*2)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001409
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001410 def test_unsupported_auth_digest_handler(self):
1411 opener = OpenerDirector()
1412 # While using DigestAuthHandler
1413 digest_auth_handler = urllib.request.HTTPDigestAuthHandler(None)
1414 http_handler = MockHTTPHandler(
1415 401, 'WWW-Authenticate: Kerberos\r\n\r\n')
1416 opener.add_handler(digest_auth_handler)
1417 opener.add_handler(http_handler)
Facundo Batista244afcf2015-04-22 18:35:54 -03001418 self.assertRaises(ValueError, opener.open, "http://www.example.com")
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001419
1420 def test_unsupported_auth_basic_handler(self):
1421 # While using BasicAuthHandler
1422 opener = OpenerDirector()
1423 basic_auth_handler = urllib.request.HTTPBasicAuthHandler(None)
1424 http_handler = MockHTTPHandler(
1425 401, 'WWW-Authenticate: NTLM\r\n\r\n')
1426 opener.add_handler(basic_auth_handler)
1427 opener.add_handler(http_handler)
Facundo Batista244afcf2015-04-22 18:35:54 -03001428 self.assertRaises(ValueError, opener.open, "http://www.example.com")
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001429
Thomas Wouters477c8d52006-05-27 19:21:47 +00001430 def _test_basic_auth(self, opener, auth_handler, auth_header,
1431 realm, http_handler, password_manager,
1432 request_url, protected_url):
Christian Heimes05e8be12008-02-23 18:30:17 +00001433 import base64
Thomas Wouters477c8d52006-05-27 19:21:47 +00001434 user, password = "wile", "coyote"
Thomas Wouters477c8d52006-05-27 19:21:47 +00001435
1436 # .add_password() fed through to password manager
1437 auth_handler.add_password(realm, request_url, user, password)
1438 self.assertEqual(realm, password_manager.realm)
1439 self.assertEqual(request_url, password_manager.url)
1440 self.assertEqual(user, password_manager.user)
1441 self.assertEqual(password, password_manager.password)
1442
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001443 opener.open(request_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001444
1445 # should have asked the password manager for the username/password
1446 self.assertEqual(password_manager.target_realm, realm)
1447 self.assertEqual(password_manager.target_url, protected_url)
1448
1449 # expect one request without authorization, then one with
1450 self.assertEqual(len(http_handler.requests), 2)
1451 self.assertFalse(http_handler.requests[0].has_header(auth_header))
Guido van Rossum98b349f2007-08-27 21:47:52 +00001452 userpass = bytes('%s:%s' % (user, password), "ascii")
Guido van Rossum98297ee2007-11-06 21:34:58 +00001453 auth_hdr_value = ('Basic ' +
Georg Brandl706824f2009-06-04 09:42:55 +00001454 base64.encodebytes(userpass).strip().decode())
Thomas Wouters477c8d52006-05-27 19:21:47 +00001455 self.assertEqual(http_handler.requests[1].get_header(auth_header),
1456 auth_hdr_value)
Senthil Kumaranca2fc9e2010-02-24 16:53:16 +00001457 self.assertEqual(http_handler.requests[1].unredirected_hdrs[auth_header],
1458 auth_hdr_value)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001459 # if the password manager can't find a password, the handler won't
1460 # handle the HTTP auth error
1461 password_manager.user = password_manager.password = None
1462 http_handler.reset()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001463 opener.open(request_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001464 self.assertEqual(len(http_handler.requests), 1)
1465 self.assertFalse(http_handler.requests[0].has_header(auth_header))
1466
R David Murray4c7f9952015-04-16 16:36:18 -04001467 def test_basic_prior_auth_auto_send(self):
1468 # Assume already authenticated if is_authenticated=True
1469 # for APIs like Github that don't return 401
1470
1471 user, password = "wile", "coyote"
1472 request_url = "http://acme.example.com/protected"
1473
1474 http_handler = MockHTTPHandlerCheckAuth(200)
1475
1476 pwd_manager = HTTPPasswordMgrWithPriorAuth()
1477 auth_prior_handler = HTTPBasicAuthHandler(pwd_manager)
1478 auth_prior_handler.add_password(
1479 None, request_url, user, password, is_authenticated=True)
1480
1481 is_auth = pwd_manager.is_authenticated(request_url)
1482 self.assertTrue(is_auth)
1483
1484 opener = OpenerDirector()
1485 opener.add_handler(auth_prior_handler)
1486 opener.add_handler(http_handler)
1487
1488 opener.open(request_url)
1489
1490 # expect request to be sent with auth header
1491 self.assertTrue(http_handler.has_auth_header)
1492
1493 def test_basic_prior_auth_send_after_first_success(self):
1494 # Auto send auth header after authentication is successful once
1495
1496 user, password = 'wile', 'coyote'
1497 request_url = 'http://acme.example.com/protected'
1498 realm = 'ACME'
1499
1500 pwd_manager = HTTPPasswordMgrWithPriorAuth()
1501 auth_prior_handler = HTTPBasicAuthHandler(pwd_manager)
1502 auth_prior_handler.add_password(realm, request_url, user, password)
1503
1504 is_auth = pwd_manager.is_authenticated(request_url)
1505 self.assertFalse(is_auth)
1506
1507 opener = OpenerDirector()
1508 opener.add_handler(auth_prior_handler)
1509
1510 http_handler = MockHTTPHandler(
1511 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % None)
1512 opener.add_handler(http_handler)
1513
1514 opener.open(request_url)
1515
1516 is_auth = pwd_manager.is_authenticated(request_url)
1517 self.assertTrue(is_auth)
1518
1519 http_handler = MockHTTPHandlerCheckAuth(200)
1520 self.assertFalse(http_handler.has_auth_header)
1521
1522 opener = OpenerDirector()
1523 opener.add_handler(auth_prior_handler)
1524 opener.add_handler(http_handler)
1525
1526 # After getting 200 from MockHTTPHandler
1527 # Next request sends header in the first request
1528 opener.open(request_url)
1529
1530 # expect request to be sent with auth header
1531 self.assertTrue(http_handler.has_auth_header)
1532
Serhiy Storchakaf54c3502014-09-06 21:41:39 +03001533 def test_http_closed(self):
1534 """Test the connection is cleaned up when the response is closed"""
1535 for (transfer, data) in (
1536 ("Connection: close", b"data"),
1537 ("Transfer-Encoding: chunked", b"4\r\ndata\r\n0\r\n\r\n"),
1538 ("Content-Length: 4", b"data"),
1539 ):
1540 header = "HTTP/1.1 200 OK\r\n{}\r\n\r\n".format(transfer)
1541 conn = test_urllib.fakehttp(header.encode() + data)
1542 handler = urllib.request.AbstractHTTPHandler()
1543 req = Request("http://dummy/")
1544 req.timeout = None
1545 with handler.do_open(conn, req) as resp:
1546 resp.read()
1547 self.assertTrue(conn.fakesock.closed,
1548 "Connection not closed with {!r}".format(transfer))
1549
1550 def test_invalid_closed(self):
1551 """Test the connection is cleaned up after an invalid response"""
1552 conn = test_urllib.fakehttp(b"")
1553 handler = urllib.request.AbstractHTTPHandler()
1554 req = Request("http://dummy/")
1555 req.timeout = None
1556 with self.assertRaises(http.client.BadStatusLine):
1557 handler.do_open(conn, req)
1558 self.assertTrue(conn.fakesock.closed, "Connection not closed")
1559
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001560
Facundo Batista244afcf2015-04-22 18:35:54 -03001561
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001562class MiscTests(unittest.TestCase):
1563
Senthil Kumarane9853da2013-03-19 12:07:43 -07001564 def opener_has_handler(self, opener, handler_class):
1565 self.assertTrue(any(h.__class__ == handler_class
1566 for h in opener.handlers))
1567
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001568 def test_build_opener(self):
Facundo Batista244afcf2015-04-22 18:35:54 -03001569 class MyHTTPHandler(urllib.request.HTTPHandler):
1570 pass
1571
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001572 class FooHandler(urllib.request.BaseHandler):
Facundo Batista244afcf2015-04-22 18:35:54 -03001573 def foo_open(self):
1574 pass
1575
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001576 class BarHandler(urllib.request.BaseHandler):
Facundo Batista244afcf2015-04-22 18:35:54 -03001577 def bar_open(self):
1578 pass
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001579
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001580 build_opener = urllib.request.build_opener
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001581
1582 o = build_opener(FooHandler, BarHandler)
1583 self.opener_has_handler(o, FooHandler)
1584 self.opener_has_handler(o, BarHandler)
1585
1586 # can take a mix of classes and instances
1587 o = build_opener(FooHandler, BarHandler())
1588 self.opener_has_handler(o, FooHandler)
1589 self.opener_has_handler(o, BarHandler)
1590
1591 # subclasses of default handlers override default handlers
1592 o = build_opener(MyHTTPHandler)
1593 self.opener_has_handler(o, MyHTTPHandler)
1594
1595 # a particular case of overriding: default handlers can be passed
1596 # in explicitly
1597 o = build_opener()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001598 self.opener_has_handler(o, urllib.request.HTTPHandler)
1599 o = build_opener(urllib.request.HTTPHandler)
1600 self.opener_has_handler(o, urllib.request.HTTPHandler)
1601 o = build_opener(urllib.request.HTTPHandler())
1602 self.opener_has_handler(o, urllib.request.HTTPHandler)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001603
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001604 # Issue2670: multiple handlers sharing the same base class
Facundo Batista244afcf2015-04-22 18:35:54 -03001605 class MyOtherHTTPHandler(urllib.request.HTTPHandler):
1606 pass
1607
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001608 o = build_opener(MyHTTPHandler, MyOtherHTTPHandler)
1609 self.opener_has_handler(o, MyHTTPHandler)
1610 self.opener_has_handler(o, MyOtherHTTPHandler)
1611
Brett Cannon80512de2013-01-25 22:27:21 -05001612 @unittest.skipUnless(support.is_resource_enabled('network'),
1613 'test requires network access')
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001614 def test_issue16464(self):
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001615 with support.transient_internet("http://www.example.com/"):
1616 opener = urllib.request.build_opener()
1617 request = urllib.request.Request("http://www.example.com/")
1618 self.assertEqual(None, request.data)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001619
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001620 opener.open(request, "1".encode("us-ascii"))
1621 self.assertEqual(b"1", request.data)
1622 self.assertEqual("1", request.get_header("Content-length"))
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001623
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001624 opener.open(request, "1234567890".encode("us-ascii"))
1625 self.assertEqual(b"1234567890", request.data)
1626 self.assertEqual("10", request.get_header("Content-length"))
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001627
Senthil Kumarane9853da2013-03-19 12:07:43 -07001628 def test_HTTPError_interface(self):
1629 """
1630 Issue 13211 reveals that HTTPError didn't implement the URLError
1631 interface even though HTTPError is a subclass of URLError.
Senthil Kumarane9853da2013-03-19 12:07:43 -07001632 """
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001633 msg = 'something bad happened'
1634 url = code = fp = None
1635 hdrs = 'Content-Length: 42'
1636 err = urllib.error.HTTPError(url, code, msg, hdrs, fp)
1637 self.assertTrue(hasattr(err, 'reason'))
1638 self.assertEqual(err.reason, 'something bad happened')
1639 self.assertTrue(hasattr(err, 'headers'))
1640 self.assertEqual(err.headers, 'Content-Length: 42')
1641 expected_errmsg = 'HTTP Error %s: %s' % (err.code, err.msg)
1642 self.assertEqual(str(err), expected_errmsg)
Facundo Batista244afcf2015-04-22 18:35:54 -03001643 expected_errmsg = '<HTTPError %s: %r>' % (err.code, err.msg)
1644 self.assertEqual(repr(err), expected_errmsg)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001645
Senthil Kumarand8e24f12014-04-14 16:32:20 -04001646 def test_parse_proxy(self):
1647 parse_proxy_test_cases = [
1648 ('proxy.example.com',
1649 (None, None, None, 'proxy.example.com')),
1650 ('proxy.example.com:3128',
1651 (None, None, None, 'proxy.example.com:3128')),
1652 ('proxy.example.com', (None, None, None, 'proxy.example.com')),
1653 ('proxy.example.com:3128',
1654 (None, None, None, 'proxy.example.com:3128')),
1655 # The authority component may optionally include userinfo
1656 # (assumed to be # username:password):
1657 ('joe:password@proxy.example.com',
1658 (None, 'joe', 'password', 'proxy.example.com')),
1659 ('joe:password@proxy.example.com:3128',
1660 (None, 'joe', 'password', 'proxy.example.com:3128')),
1661 #Examples with URLS
1662 ('http://proxy.example.com/',
1663 ('http', None, None, 'proxy.example.com')),
1664 ('http://proxy.example.com:3128/',
1665 ('http', None, None, 'proxy.example.com:3128')),
1666 ('http://joe:password@proxy.example.com/',
1667 ('http', 'joe', 'password', 'proxy.example.com')),
1668 ('http://joe:password@proxy.example.com:3128',
1669 ('http', 'joe', 'password', 'proxy.example.com:3128')),
1670 # Everything after the authority is ignored
1671 ('ftp://joe:password@proxy.example.com/rubbish:3128',
1672 ('ftp', 'joe', 'password', 'proxy.example.com')),
1673 # Test for no trailing '/' case
1674 ('http://joe:password@proxy.example.com',
1675 ('http', 'joe', 'password', 'proxy.example.com'))
1676 ]
1677
1678 for tc, expected in parse_proxy_test_cases:
1679 self.assertEqual(_parse_proxy(tc), expected)
1680
1681 self.assertRaises(ValueError, _parse_proxy, 'file:/ftp.example.com'),
1682
Facundo Batista244afcf2015-04-22 18:35:54 -03001683
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001684class RequestTests(unittest.TestCase):
Jason R. Coombs4a652422013-09-08 13:03:40 -04001685 class PutRequest(Request):
Facundo Batista244afcf2015-04-22 18:35:54 -03001686 method = 'PUT'
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001687
1688 def setUp(self):
1689 self.get = Request("http://www.python.org/~jeremy/")
1690 self.post = Request("http://www.python.org/~jeremy/",
1691 "data",
1692 headers={"X-Test": "test"})
Jason R. Coombs4a652422013-09-08 13:03:40 -04001693 self.head = Request("http://www.python.org/~jeremy/", method='HEAD')
1694 self.put = self.PutRequest("http://www.python.org/~jeremy/")
1695 self.force_post = self.PutRequest("http://www.python.org/~jeremy/",
1696 method="POST")
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001697
1698 def test_method(self):
1699 self.assertEqual("POST", self.post.get_method())
1700 self.assertEqual("GET", self.get.get_method())
Senthil Kumaran0b5463f2013-09-09 23:13:06 -07001701 self.assertEqual("HEAD", self.head.get_method())
Jason R. Coombs4a652422013-09-08 13:03:40 -04001702 self.assertEqual("PUT", self.put.get_method())
1703 self.assertEqual("POST", self.force_post.get_method())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001704
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001705 def test_data(self):
1706 self.assertFalse(self.get.data)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001707 self.assertEqual("GET", self.get.get_method())
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001708 self.get.data = "spam"
1709 self.assertTrue(self.get.data)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001710 self.assertEqual("POST", self.get.get_method())
1711
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001712 # issue 16464
1713 # if we change data we need to remove content-length header
1714 # (cause it's most probably calculated for previous value)
1715 def test_setting_data_should_remove_content_length(self):
R David Murray9cc7d452013-03-20 00:10:51 -04001716 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001717 self.get.add_unredirected_header("Content-length", 42)
1718 self.assertEqual(42, self.get.unredirected_hdrs["Content-length"])
1719 self.get.data = "spam"
R David Murray9cc7d452013-03-20 00:10:51 -04001720 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
1721
1722 # issue 17485 same for deleting data.
1723 def test_deleting_data_should_remove_content_length(self):
1724 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
1725 self.get.data = 'foo'
1726 self.get.add_unredirected_header("Content-length", 3)
1727 self.assertEqual(3, self.get.unredirected_hdrs["Content-length"])
1728 del self.get.data
1729 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001730
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001731 def test_get_full_url(self):
1732 self.assertEqual("http://www.python.org/~jeremy/",
1733 self.get.get_full_url())
1734
1735 def test_selector(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001736 self.assertEqual("/~jeremy/", self.get.selector)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001737 req = Request("http://www.python.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001738 self.assertEqual("/", req.selector)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001739
1740 def test_get_type(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001741 self.assertEqual("http", self.get.type)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001742
1743 def test_get_host(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001744 self.assertEqual("www.python.org", self.get.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001745
1746 def test_get_host_unquote(self):
1747 req = Request("http://www.%70ython.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001748 self.assertEqual("www.python.org", req.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001749
1750 def test_proxy(self):
Florent Xicluna419e3842010-08-08 16:16:07 +00001751 self.assertFalse(self.get.has_proxy())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001752 self.get.set_proxy("www.perl.org", "http")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001753 self.assertTrue(self.get.has_proxy())
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001754 self.assertEqual("www.python.org", self.get.origin_req_host)
1755 self.assertEqual("www.perl.org", self.get.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001756
Senthil Kumarand95cc752010-08-08 11:27:53 +00001757 def test_wrapped_url(self):
1758 req = Request("<URL:http://www.python.org>")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001759 self.assertEqual("www.python.org", req.host)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001760
Senthil Kumaran26430412011-04-13 07:01:19 +08001761 def test_url_fragment(self):
Senthil Kumarand95cc752010-08-08 11:27:53 +00001762 req = Request("http://www.python.org/?qs=query#fragment=true")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001763 self.assertEqual("/?qs=query", req.selector)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001764 req = Request("http://www.python.org/#fun=true")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001765 self.assertEqual("/", req.selector)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001766
Senthil Kumaran26430412011-04-13 07:01:19 +08001767 # Issue 11703: geturl() omits fragment in the original URL.
1768 url = 'http://docs.python.org/library/urllib2.html#OK'
1769 req = Request(url)
1770 self.assertEqual(req.get_full_url(), url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001771
Senthil Kumaran83070752013-05-24 09:14:12 -07001772 def test_url_fullurl_get_full_url(self):
1773 urls = ['http://docs.python.org',
1774 'http://docs.python.org/library/urllib2.html#OK',
Facundo Batista244afcf2015-04-22 18:35:54 -03001775 'http://www.python.org/?qs=query#fragment=true']
Senthil Kumaran83070752013-05-24 09:14:12 -07001776 for url in urls:
1777 req = Request(url)
1778 self.assertEqual(req.get_full_url(), req.full_url)
1779
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001780
1781if __name__ == "__main__":
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001782 unittest.main()