blob: 876fcd4199fb9235c894aea5f5b60baac19542e3 [file] [log] [blame]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002from test import support
Serhiy Storchakaf54c3502014-09-06 21:41:39 +03003from test import test_urllib
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00004
Christian Heimes05e8be12008-02-23 18:30:17 +00005import os
Guido van Rossum34d19282007-08-09 01:03:29 +00006import io
Georg Brandlf78e02b2008-06-10 17:40:04 +00007import socket
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00008import array
Senthil Kumaran4de00a22011-05-11 21:17:57 +08009import sys
Martin Panter3c0d0ba2016-08-24 06:33:33 +000010import tempfile
11import subprocess
Jeremy Hyltone3e61042001-05-09 15:50:25 +000012
Jeremy Hylton1afc1692008-06-18 20:49:58 +000013import urllib.request
Ronald Oussorene72e1612011-03-14 18:15:25 -040014# The proxy bypass method imported below has logic specific to the OSX
15# proxy config data structure but is testable on all platforms.
R David Murray4c7f9952015-04-16 16:36:18 -040016from urllib.request import (Request, OpenerDirector, HTTPBasicAuthHandler,
17 HTTPPasswordMgrWithPriorAuth, _parse_proxy,
Berker Peksage88dd1c2016-03-06 16:16:40 +020018 _proxy_bypass_macosx_sysconf,
19 AbstractDigestAuthHandler)
Senthil Kumaran83070752013-05-24 09:14:12 -070020from urllib.parse import urlparse
guido@google.coma119df92011-03-29 11:41:02 -070021import urllib.error
Serhiy Storchakaf54c3502014-09-06 21:41:39 +030022import http.client
Jeremy Hyltone3e61042001-05-09 15:50:25 +000023
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000024# XXX
25# Request
26# CacheFTPHandler (hard to write)
Thomas Wouters477c8d52006-05-27 19:21:47 +000027# parse_keqv_list, parse_http_list, HTTPDigestAuthHandler
Jeremy Hyltone3e61042001-05-09 15:50:25 +000028
Facundo Batista244afcf2015-04-22 18:35:54 -030029
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000030class TrivialTests(unittest.TestCase):
Senthil Kumaran6c5bd402011-11-01 23:20:31 +080031
32 def test___all__(self):
33 # Verify which names are exposed
34 for module in 'request', 'response', 'parse', 'error', 'robotparser':
35 context = {}
36 exec('from urllib.%s import *' % module, context)
37 del context['__builtins__']
Florent Xicluna3dbb1f12011-11-04 22:15:37 +010038 if module == 'request' and os.name == 'nt':
39 u, p = context.pop('url2pathname'), context.pop('pathname2url')
40 self.assertEqual(u.__module__, 'nturl2path')
41 self.assertEqual(p.__module__, 'nturl2path')
Senthil Kumaran6c5bd402011-11-01 23:20:31 +080042 for k, v in context.items():
43 self.assertEqual(v.__module__, 'urllib.%s' % module,
44 "%r is exposed in 'urllib.%s' but defined in %r" %
45 (k, module, v.__module__))
46
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000047 def test_trivial(self):
48 # A couple trivial tests
Guido van Rossume2ae77b2001-10-24 20:42:55 +000049
Jeremy Hylton1afc1692008-06-18 20:49:58 +000050 self.assertRaises(ValueError, urllib.request.urlopen, 'bogus url')
Tim Peters861adac2001-07-16 20:49:49 +000051
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000052 # XXX Name hacking to get this to work on Windows.
Serhiy Storchaka5106d042015-01-26 10:26:14 +020053 fname = os.path.abspath(urllib.request.__file__).replace(os.sep, '/')
Senthil Kumarand587e302010-01-10 17:45:52 +000054
Senthil Kumarand587e302010-01-10 17:45:52 +000055 if os.name == 'nt':
56 file_url = "file:///%s" % fname
57 else:
58 file_url = "file://%s" % fname
59
Jeremy Hylton1afc1692008-06-18 20:49:58 +000060 f = urllib.request.urlopen(file_url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000061
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -070062 f.read()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000063 f.close()
Tim Petersf5f32b42005-07-17 23:16:17 +000064
Georg Brandle1b13d22005-08-24 22:20:32 +000065 def test_parse_http_list(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +000066 tests = [
67 ('a,b,c', ['a', 'b', 'c']),
68 ('path"o,l"og"i"cal, example', ['path"o,l"og"i"cal', 'example']),
69 ('a, b, "c", "d", "e,f", g, h',
70 ['a', 'b', '"c"', '"d"', '"e,f"', 'g', 'h']),
71 ('a="b\\"c", d="e\\,f", g="h\\\\i"',
72 ['a="b"c"', 'd="e,f"', 'g="h\\i"'])]
Georg Brandle1b13d22005-08-24 22:20:32 +000073 for string, list in tests:
Florent Xicluna419e3842010-08-08 16:16:07 +000074 self.assertEqual(urllib.request.parse_http_list(string), list)
Georg Brandle1b13d22005-08-24 22:20:32 +000075
Senthil Kumaran843fae92013-03-19 13:43:42 -070076 def test_URLError_reasonstr(self):
77 err = urllib.error.URLError('reason')
78 self.assertIn(err.reason, str(err))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000079
Facundo Batista244afcf2015-04-22 18:35:54 -030080
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -070081class RequestHdrsTests(unittest.TestCase):
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000082
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -070083 def test_request_headers_dict(self):
84 """
85 The Request.headers dictionary is not a documented interface. It
86 should stay that way, because the complete set of headers are only
87 accessible through the .get_header(), .has_header(), .header_items()
88 interface. However, .headers pre-dates those methods, and so real code
89 will be using the dictionary.
90
91 The introduction in 2.4 of those methods was a mistake for the same
92 reason: code that previously saw all (urllib2 user)-provided headers in
93 .headers now sees only a subset.
94
95 """
96 url = "http://example.com"
97 self.assertEqual(Request(url,
98 headers={"Spam-eggs": "blah"}
99 ).headers["Spam-eggs"], "blah")
100 self.assertEqual(Request(url,
101 headers={"spam-EggS": "blah"}
102 ).headers["Spam-eggs"], "blah")
103
104 def test_request_headers_methods(self):
105 """
106 Note the case normalization of header names here, to
107 .capitalize()-case. This should be preserved for
108 backwards-compatibility. (In the HTTP case, normalization to
109 .title()-case is done by urllib2 before sending headers to
110 http.client).
111
112 Note that e.g. r.has_header("spam-EggS") is currently False, and
113 r.get_header("spam-EggS") returns None, but that could be changed in
114 future.
115
116 Method r.remove_header should remove items both from r.headers and
117 r.unredirected_hdrs dictionaries
118 """
119 url = "http://example.com"
120 req = Request(url, headers={"Spam-eggs": "blah"})
121 self.assertTrue(req.has_header("Spam-eggs"))
122 self.assertEqual(req.header_items(), [('Spam-eggs', 'blah')])
123
124 req.add_header("Foo-Bar", "baz")
125 self.assertEqual(sorted(req.header_items()),
126 [('Foo-bar', 'baz'), ('Spam-eggs', 'blah')])
127 self.assertFalse(req.has_header("Not-there"))
128 self.assertIsNone(req.get_header("Not-there"))
129 self.assertEqual(req.get_header("Not-there", "default"), "default")
130
131 req.remove_header("Spam-eggs")
132 self.assertFalse(req.has_header("Spam-eggs"))
133
134 req.add_unredirected_header("Unredirected-spam", "Eggs")
135 self.assertTrue(req.has_header("Unredirected-spam"))
136
137 req.remove_header("Unredirected-spam")
138 self.assertFalse(req.has_header("Unredirected-spam"))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000139
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700140 def test_password_manager(self):
141 mgr = urllib.request.HTTPPasswordMgr()
142 add = mgr.add_password
143 find_user_pass = mgr.find_user_password
Senthil Kumaran1f5425f2017-03-31 22:27:27 -0700144
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700145 add("Some Realm", "http://example.com/", "joe", "password")
146 add("Some Realm", "http://example.com/ni", "ni", "ni")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700147 add("Some Realm", "http://c.example.com:3128", "3", "c")
148 add("Some Realm", "d.example.com", "4", "d")
149 add("Some Realm", "e.example.com:3128", "5", "e")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000150
Senthil Kumaran1f5425f2017-03-31 22:27:27 -0700151 # For the same realm, password set the highest path is the winner.
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700152 self.assertEqual(find_user_pass("Some Realm", "example.com"),
153 ('joe', 'password'))
Senthil Kumaran1f5425f2017-03-31 22:27:27 -0700154 self.assertEqual(find_user_pass("Some Realm", "http://example.com/ni"),
155 ('joe', 'password'))
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700156 self.assertEqual(find_user_pass("Some Realm", "http://example.com"),
157 ('joe', 'password'))
158 self.assertEqual(find_user_pass("Some Realm", "http://example.com/"),
159 ('joe', 'password'))
Senthil Kumaran1f5425f2017-03-31 22:27:27 -0700160 self.assertEqual(find_user_pass("Some Realm",
161 "http://example.com/spam"),
162 ('joe', 'password'))
163
164 self.assertEqual(find_user_pass("Some Realm",
165 "http://example.com/spam/spam"),
166 ('joe', 'password'))
167
168 # You can have different passwords for different paths.
169
170 add("c", "http://example.com/foo", "foo", "ni")
171 add("c", "http://example.com/bar", "bar", "nini")
172
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700173 self.assertEqual(find_user_pass("c", "http://example.com/foo"),
174 ('foo', 'ni'))
Senthil Kumaran1f5425f2017-03-31 22:27:27 -0700175
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700176 self.assertEqual(find_user_pass("c", "http://example.com/bar"),
177 ('bar', 'nini'))
Senthil Kumaran1f5425f2017-03-31 22:27:27 -0700178
179 # For the same path, newer password should be considered.
180
181 add("b", "http://example.com/", "first", "blah")
182 add("b", "http://example.com/", "second", "spam")
183
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700184 self.assertEqual(find_user_pass("b", "http://example.com/"),
185 ('second', 'spam'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000186
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700187 # No special relationship between a.example.com and example.com:
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000188
Senthil Kumaran1f5425f2017-03-31 22:27:27 -0700189 add("a", "http://example.com", "1", "a")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700190 self.assertEqual(find_user_pass("a", "http://example.com/"),
191 ('1', 'a'))
Senthil Kumaran1f5425f2017-03-31 22:27:27 -0700192
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700193 self.assertEqual(find_user_pass("a", "http://a.example.com/"),
194 (None, None))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000195
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700196 # Ports:
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000197
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700198 self.assertEqual(find_user_pass("Some Realm", "c.example.com"),
199 (None, None))
200 self.assertEqual(find_user_pass("Some Realm", "c.example.com:3128"),
201 ('3', 'c'))
202 self.assertEqual(
203 find_user_pass("Some Realm", "http://c.example.com:3128"),
204 ('3', 'c'))
205 self.assertEqual(find_user_pass("Some Realm", "d.example.com"),
206 ('4', 'd'))
207 self.assertEqual(find_user_pass("Some Realm", "e.example.com:3128"),
208 ('5', 'e'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000209
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700210 def test_password_manager_default_port(self):
211 """
212 The point to note here is that we can't guess the default port if
213 there's no scheme. This applies to both add_password and
214 find_user_password.
215 """
216 mgr = urllib.request.HTTPPasswordMgr()
217 add = mgr.add_password
218 find_user_pass = mgr.find_user_password
219 add("f", "http://g.example.com:80", "10", "j")
220 add("g", "http://h.example.com", "11", "k")
221 add("h", "i.example.com:80", "12", "l")
222 add("i", "j.example.com", "13", "m")
223 self.assertEqual(find_user_pass("f", "g.example.com:100"),
224 (None, None))
225 self.assertEqual(find_user_pass("f", "g.example.com:80"),
226 ('10', 'j'))
227 self.assertEqual(find_user_pass("f", "g.example.com"),
228 (None, None))
229 self.assertEqual(find_user_pass("f", "http://g.example.com:100"),
230 (None, None))
231 self.assertEqual(find_user_pass("f", "http://g.example.com:80"),
232 ('10', 'j'))
233 self.assertEqual(find_user_pass("f", "http://g.example.com"),
234 ('10', 'j'))
235 self.assertEqual(find_user_pass("g", "h.example.com"), ('11', 'k'))
236 self.assertEqual(find_user_pass("g", "h.example.com:80"), ('11', 'k'))
237 self.assertEqual(find_user_pass("g", "http://h.example.com:80"),
238 ('11', 'k'))
239 self.assertEqual(find_user_pass("h", "i.example.com"), (None, None))
240 self.assertEqual(find_user_pass("h", "i.example.com:80"), ('12', 'l'))
241 self.assertEqual(find_user_pass("h", "http://i.example.com:80"),
242 ('12', 'l'))
243 self.assertEqual(find_user_pass("i", "j.example.com"), ('13', 'm'))
244 self.assertEqual(find_user_pass("i", "j.example.com:80"),
245 (None, None))
246 self.assertEqual(find_user_pass("i", "http://j.example.com"),
247 ('13', 'm'))
248 self.assertEqual(find_user_pass("i", "http://j.example.com:80"),
249 (None, None))
Andrew Svetlovbff98fe2012-11-27 23:06:19 +0200250
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000251
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000252class MockOpener:
253 addheaders = []
Facundo Batista244afcf2015-04-22 18:35:54 -0300254
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000255 def open(self, req, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
256 self.req, self.data, self.timeout = req, data, timeout
Facundo Batista244afcf2015-04-22 18:35:54 -0300257
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000258 def error(self, proto, *args):
259 self.proto, self.args = proto, args
260
Facundo Batista244afcf2015-04-22 18:35:54 -0300261
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000262class MockFile:
Facundo Batista244afcf2015-04-22 18:35:54 -0300263 def read(self, count=None):
264 pass
265
266 def readline(self, count=None):
267 pass
268
269 def close(self):
270 pass
271
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000272
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000273class MockHeaders(dict):
274 def getheaders(self, name):
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000275 return list(self.values())
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000276
Facundo Batista244afcf2015-04-22 18:35:54 -0300277
Guido van Rossum34d19282007-08-09 01:03:29 +0000278class MockResponse(io.StringIO):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000279 def __init__(self, code, msg, headers, data, url=None):
Guido van Rossum34d19282007-08-09 01:03:29 +0000280 io.StringIO.__init__(self, data)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000281 self.code, self.msg, self.headers, self.url = code, msg, headers, url
Facundo Batista244afcf2015-04-22 18:35:54 -0300282
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000283 def info(self):
284 return self.headers
Facundo Batista244afcf2015-04-22 18:35:54 -0300285
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000286 def geturl(self):
287 return self.url
288
Facundo Batista244afcf2015-04-22 18:35:54 -0300289
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000290class MockCookieJar:
291 def add_cookie_header(self, request):
292 self.ach_req = request
Facundo Batista244afcf2015-04-22 18:35:54 -0300293
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000294 def extract_cookies(self, response, request):
295 self.ec_req, self.ec_r = request, response
296
Facundo Batista244afcf2015-04-22 18:35:54 -0300297
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000298class FakeMethod:
299 def __init__(self, meth_name, action, handle):
300 self.meth_name = meth_name
301 self.handle = handle
302 self.action = action
Facundo Batista244afcf2015-04-22 18:35:54 -0300303
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000304 def __call__(self, *args):
305 return self.handle(self.meth_name, self.action, *args)
306
Facundo Batista244afcf2015-04-22 18:35:54 -0300307
Senthil Kumaran47fff872009-12-20 07:10:31 +0000308class MockHTTPResponse(io.IOBase):
309 def __init__(self, fp, msg, status, reason):
310 self.fp = fp
311 self.msg = msg
312 self.status = status
313 self.reason = reason
314 self.code = 200
315
316 def read(self):
317 return ''
318
319 def info(self):
320 return {}
321
322 def geturl(self):
323 return self.url
324
325
326class MockHTTPClass:
327 def __init__(self):
328 self.level = 0
329 self.req_headers = []
330 self.data = None
331 self.raise_on_endheaders = False
Nadeem Vawdabd26b542012-10-21 17:37:43 +0200332 self.sock = None
Senthil Kumaran47fff872009-12-20 07:10:31 +0000333 self._tunnel_headers = {}
334
335 def __call__(self, host, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
336 self.host = host
337 self.timeout = timeout
338 return self
339
340 def set_debuglevel(self, level):
341 self.level = level
342
343 def set_tunnel(self, host, port=None, headers=None):
344 self._tunnel_host = host
345 self._tunnel_port = port
346 if headers:
347 self._tunnel_headers = headers
348 else:
349 self._tunnel_headers.clear()
350
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000351 def request(self, method, url, body=None, headers=None, *,
352 encode_chunked=False):
Senthil Kumaran47fff872009-12-20 07:10:31 +0000353 self.method = method
354 self.selector = url
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000355 if headers is not None:
356 self.req_headers += headers.items()
Senthil Kumaran47fff872009-12-20 07:10:31 +0000357 self.req_headers.sort()
358 if body:
359 self.data = body
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000360 self.encode_chunked = encode_chunked
Senthil Kumaran47fff872009-12-20 07:10:31 +0000361 if self.raise_on_endheaders:
Andrew Svetlov0832af62012-12-18 23:10:48 +0200362 raise OSError()
Facundo Batista244afcf2015-04-22 18:35:54 -0300363
Senthil Kumaran47fff872009-12-20 07:10:31 +0000364 def getresponse(self):
365 return MockHTTPResponse(MockFile(), {}, 200, "OK")
366
Victor Stinnera4c45d72011-06-17 14:01:18 +0200367 def close(self):
368 pass
369
Facundo Batista244afcf2015-04-22 18:35:54 -0300370
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000371class MockHandler:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000372 # useful for testing handler machinery
373 # see add_ordered_mock_handlers() docstring
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000374 handler_order = 500
Facundo Batista244afcf2015-04-22 18:35:54 -0300375
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000376 def __init__(self, methods):
377 self._define_methods(methods)
Facundo Batista244afcf2015-04-22 18:35:54 -0300378
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000379 def _define_methods(self, methods):
380 for spec in methods:
Facundo Batista244afcf2015-04-22 18:35:54 -0300381 if len(spec) == 2:
382 name, action = spec
383 else:
384 name, action = spec, None
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000385 meth = FakeMethod(name, action, self.handle)
386 setattr(self.__class__, name, meth)
Facundo Batista244afcf2015-04-22 18:35:54 -0300387
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000388 def handle(self, fn_name, action, *args, **kwds):
389 self.parent.calls.append((self, fn_name, args, kwds))
390 if action is None:
391 return None
392 elif action == "return self":
393 return self
394 elif action == "return response":
395 res = MockResponse(200, "OK", {}, "")
396 return res
397 elif action == "return request":
398 return Request("http://blah/")
399 elif action.startswith("error"):
400 code = action[action.rfind(" ")+1:]
401 try:
402 code = int(code)
403 except ValueError:
404 pass
405 res = MockResponse(200, "OK", {}, "")
406 return self.parent.error("http", args[0], res, code, "", {})
407 elif action == "raise":
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000408 raise urllib.error.URLError("blah")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000409 assert False
Facundo Batista244afcf2015-04-22 18:35:54 -0300410
411 def close(self):
412 pass
413
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000414 def add_parent(self, parent):
415 self.parent = parent
416 self.parent.calls = []
Facundo Batista244afcf2015-04-22 18:35:54 -0300417
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000418 def __lt__(self, other):
419 if not hasattr(other, "handler_order"):
420 # No handler_order, leave in original order. Yuck.
421 return True
422 return self.handler_order < other.handler_order
423
Facundo Batista244afcf2015-04-22 18:35:54 -0300424
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000425def add_ordered_mock_handlers(opener, meth_spec):
426 """Create MockHandlers and add them to an OpenerDirector.
427
428 meth_spec: list of lists of tuples and strings defining methods to define
429 on handlers. eg:
430
431 [["http_error", "ftp_open"], ["http_open"]]
432
433 defines methods .http_error() and .ftp_open() on one handler, and
434 .http_open() on another. These methods just record their arguments and
435 return None. Using a tuple instead of a string causes the method to
436 perform some action (see MockHandler.handle()), eg:
437
438 [["http_error"], [("http_open", "return request")]]
439
440 defines .http_error() on one handler (which simply returns None), and
441 .http_open() on another handler, which returns a Request object.
442
443 """
444 handlers = []
445 count = 0
446 for meths in meth_spec:
Facundo Batista244afcf2015-04-22 18:35:54 -0300447 class MockHandlerSubclass(MockHandler):
448 pass
449
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000450 h = MockHandlerSubclass(meths)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000451 h.handler_order += count
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000452 h.add_parent(opener)
453 count = count + 1
454 handlers.append(h)
455 opener.add_handler(h)
456 return handlers
457
Facundo Batista244afcf2015-04-22 18:35:54 -0300458
Thomas Wouters477c8d52006-05-27 19:21:47 +0000459def build_test_opener(*handler_instances):
460 opener = OpenerDirector()
461 for h in handler_instances:
462 opener.add_handler(h)
463 return opener
464
Facundo Batista244afcf2015-04-22 18:35:54 -0300465
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000466class MockHTTPHandler(urllib.request.BaseHandler):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000467 # useful for testing redirections and auth
468 # sends supplied headers and code as first response
469 # sends 200 OK as second response
470 def __init__(self, code, headers):
471 self.code = code
472 self.headers = headers
473 self.reset()
Facundo Batista244afcf2015-04-22 18:35:54 -0300474
Thomas Wouters477c8d52006-05-27 19:21:47 +0000475 def reset(self):
476 self._count = 0
477 self.requests = []
Facundo Batista244afcf2015-04-22 18:35:54 -0300478
Thomas Wouters477c8d52006-05-27 19:21:47 +0000479 def http_open(self, req):
Martin Panterce6e0682016-05-16 01:07:13 +0000480 import email, copy
Thomas Wouters477c8d52006-05-27 19:21:47 +0000481 self.requests.append(copy.deepcopy(req))
482 if self._count == 0:
483 self._count = self._count + 1
Georg Brandl24420152008-05-26 16:32:26 +0000484 name = http.client.responses[self.code]
Barry Warsaw820c1202008-06-12 04:06:45 +0000485 msg = email.message_from_string(self.headers)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000486 return self.parent.error(
487 "http", req, MockFile(), self.code, name, msg)
488 else:
489 self.req = req
Barry Warsaw820c1202008-06-12 04:06:45 +0000490 msg = email.message_from_string("\r\n\r\n")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000491 return MockResponse(200, "OK", msg, "", req.get_full_url())
492
Facundo Batista244afcf2015-04-22 18:35:54 -0300493
Senthil Kumaran47fff872009-12-20 07:10:31 +0000494class MockHTTPSHandler(urllib.request.AbstractHTTPHandler):
495 # Useful for testing the Proxy-Authorization request by verifying the
496 # properties of httpcon
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000497
Senthil Kumaran9642eed2016-05-13 01:32:42 -0700498 def __init__(self, debuglevel=0):
499 urllib.request.AbstractHTTPHandler.__init__(self, debuglevel=debuglevel)
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000500 self.httpconn = MockHTTPClass()
501
Senthil Kumaran47fff872009-12-20 07:10:31 +0000502 def https_open(self, req):
503 return self.do_open(self.httpconn, req)
504
R David Murray4c7f9952015-04-16 16:36:18 -0400505
506class MockHTTPHandlerCheckAuth(urllib.request.BaseHandler):
507 # useful for testing auth
508 # sends supplied code response
509 # checks if auth header is specified in request
510 def __init__(self, code):
511 self.code = code
512 self.has_auth_header = False
513
514 def reset(self):
515 self.has_auth_header = False
516
517 def http_open(self, req):
518 if req.has_header('Authorization'):
519 self.has_auth_header = True
520 name = http.client.responses[self.code]
521 return MockResponse(self.code, name, MockFile(), "", req.get_full_url())
522
523
Facundo Batista244afcf2015-04-22 18:35:54 -0300524
Thomas Wouters477c8d52006-05-27 19:21:47 +0000525class MockPasswordManager:
526 def add_password(self, realm, uri, user, password):
527 self.realm = realm
528 self.url = uri
529 self.user = user
530 self.password = password
Facundo Batista244afcf2015-04-22 18:35:54 -0300531
Thomas Wouters477c8d52006-05-27 19:21:47 +0000532 def find_user_password(self, realm, authuri):
533 self.target_realm = realm
534 self.target_url = authuri
535 return self.user, self.password
536
537
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000538class OpenerDirectorTests(unittest.TestCase):
539
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000540 def test_add_non_handler(self):
541 class NonHandler(object):
542 pass
543 self.assertRaises(TypeError,
544 OpenerDirector().add_handler, NonHandler())
545
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000546 def test_badly_named_methods(self):
547 # test work-around for three methods that accidentally follow the
548 # naming conventions for handler methods
549 # (*_open() / *_request() / *_response())
550
551 # These used to call the accidentally-named methods, causing a
552 # TypeError in real code; here, returning self from these mock
553 # methods would either cause no exception, or AttributeError.
554
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000555 from urllib.error import URLError
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000556
557 o = OpenerDirector()
558 meth_spec = [
559 [("do_open", "return self"), ("proxy_open", "return self")],
560 [("redirect_request", "return self")],
561 ]
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700562 add_ordered_mock_handlers(o, meth_spec)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000563 o.add_handler(urllib.request.UnknownHandler())
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000564 for scheme in "do", "proxy", "redirect":
565 self.assertRaises(URLError, o.open, scheme+"://example.com/")
566
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000567 def test_handled(self):
568 # handler returning non-None means no more handlers will be called
569 o = OpenerDirector()
570 meth_spec = [
571 ["http_open", "ftp_open", "http_error_302"],
572 ["ftp_open"],
573 [("http_open", "return self")],
574 [("http_open", "return self")],
575 ]
576 handlers = add_ordered_mock_handlers(o, meth_spec)
577
578 req = Request("http://example.com/")
579 r = o.open(req)
580 # Second .http_open() gets called, third doesn't, since second returned
581 # non-None. Handlers without .http_open() never get any methods called
582 # on them.
583 # In fact, second mock handler defining .http_open() returns self
584 # (instead of response), which becomes the OpenerDirector's return
585 # value.
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000586 self.assertEqual(r, handlers[2])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000587 calls = [(handlers[0], "http_open"), (handlers[2], "http_open")]
588 for expected, got in zip(calls, o.calls):
589 handler, name, args, kwds = got
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000590 self.assertEqual((handler, name), expected)
591 self.assertEqual(args, (req,))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000592
593 def test_handler_order(self):
594 o = OpenerDirector()
595 handlers = []
Facundo Batista244afcf2015-04-22 18:35:54 -0300596 for meths, handler_order in [([("http_open", "return self")], 500),
597 (["http_open"], 0)]:
598 class MockHandlerSubclass(MockHandler):
599 pass
600
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000601 h = MockHandlerSubclass(meths)
602 h.handler_order = handler_order
603 handlers.append(h)
604 o.add_handler(h)
605
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700606 o.open("http://example.com/")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000607 # handlers called in reverse order, thanks to their sort order
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000608 self.assertEqual(o.calls[0][0], handlers[1])
609 self.assertEqual(o.calls[1][0], handlers[0])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000610
611 def test_raise(self):
612 # raising URLError stops processing of request
613 o = OpenerDirector()
614 meth_spec = [
615 [("http_open", "raise")],
616 [("http_open", "return self")],
617 ]
618 handlers = add_ordered_mock_handlers(o, meth_spec)
619
620 req = Request("http://example.com/")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000621 self.assertRaises(urllib.error.URLError, o.open, req)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000622 self.assertEqual(o.calls, [(handlers[0], "http_open", (req,), {})])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000623
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000624 def test_http_error(self):
625 # XXX http_error_default
626 # http errors are a special case
627 o = OpenerDirector()
628 meth_spec = [
629 [("http_open", "error 302")],
630 [("http_error_400", "raise"), "http_open"],
631 [("http_error_302", "return response"), "http_error_303",
632 "http_error"],
633 [("http_error_302")],
634 ]
635 handlers = add_ordered_mock_handlers(o, meth_spec)
636
637 class Unknown:
Facundo Batista244afcf2015-04-22 18:35:54 -0300638 def __eq__(self, other):
639 return True
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000640
641 req = Request("http://example.com/")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700642 o.open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000643 assert len(o.calls) == 2
644 calls = [(handlers[0], "http_open", (req,)),
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000645 (handlers[2], "http_error_302",
646 (req, Unknown(), 302, "", {}))]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000647 for expected, got in zip(calls, o.calls):
648 handler, method_name, args = expected
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000649 self.assertEqual((handler, method_name), got[:2])
650 self.assertEqual(args, got[2])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000651
652 def test_processors(self):
653 # *_request / *_response methods get called appropriately
654 o = OpenerDirector()
655 meth_spec = [
656 [("http_request", "return request"),
657 ("http_response", "return response")],
658 [("http_request", "return request"),
659 ("http_response", "return response")],
660 ]
661 handlers = add_ordered_mock_handlers(o, meth_spec)
662
663 req = Request("http://example.com/")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700664 o.open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000665 # processor methods are called on *all* handlers that define them,
666 # not just the first handler that handles the request
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000667 calls = [
668 (handlers[0], "http_request"), (handlers[1], "http_request"),
669 (handlers[0], "http_response"), (handlers[1], "http_response")]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000670
671 for i, (handler, name, args, kwds) in enumerate(o.calls):
672 if i < 2:
673 # *_request
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000674 self.assertEqual((handler, name), calls[i])
675 self.assertEqual(len(args), 1)
Ezio Melottie9615932010-01-24 19:26:24 +0000676 self.assertIsInstance(args[0], Request)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000677 else:
678 # *_response
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000679 self.assertEqual((handler, name), calls[i])
680 self.assertEqual(len(args), 2)
Ezio Melottie9615932010-01-24 19:26:24 +0000681 self.assertIsInstance(args[0], Request)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000682 # response from opener.open is None, because there's no
683 # handler that defines http_open to handle it
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200684 if args[1] is not None:
685 self.assertIsInstance(args[1], MockResponse)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000686
Facundo Batista244afcf2015-04-22 18:35:54 -0300687
Tim Peters58eb11c2004-01-18 20:29:55 +0000688def sanepathname2url(path):
Victor Stinner6c6f8512010-08-07 10:09:35 +0000689 try:
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000690 path.encode("utf-8")
Victor Stinner6c6f8512010-08-07 10:09:35 +0000691 except UnicodeEncodeError:
692 raise unittest.SkipTest("path is not encodable to utf8")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000693 urlpath = urllib.request.pathname2url(path)
Tim Peters58eb11c2004-01-18 20:29:55 +0000694 if os.name == "nt" and urlpath.startswith("///"):
695 urlpath = urlpath[2:]
696 # XXX don't ask me about the mac...
697 return urlpath
698
Facundo Batista244afcf2015-04-22 18:35:54 -0300699
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000700class HandlerTests(unittest.TestCase):
701
702 def test_ftp(self):
703 class MockFTPWrapper:
Facundo Batista244afcf2015-04-22 18:35:54 -0300704 def __init__(self, data):
705 self.data = data
706
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000707 def retrfile(self, filename, filetype):
708 self.filename, self.filetype = filename, filetype
Guido van Rossum34d19282007-08-09 01:03:29 +0000709 return io.StringIO(self.data), len(self.data)
Facundo Batista244afcf2015-04-22 18:35:54 -0300710
711 def close(self):
712 pass
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000713
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000714 class NullFTPHandler(urllib.request.FTPHandler):
Facundo Batista244afcf2015-04-22 18:35:54 -0300715 def __init__(self, data):
716 self.data = data
717
Georg Brandlf78e02b2008-06-10 17:40:04 +0000718 def connect_ftp(self, user, passwd, host, port, dirs,
719 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000720 self.user, self.passwd = user, passwd
721 self.host, self.port = host, port
722 self.dirs = dirs
723 self.ftpwrapper = MockFTPWrapper(self.data)
724 return self.ftpwrapper
725
Georg Brandlf78e02b2008-06-10 17:40:04 +0000726 import ftplib
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000727 data = "rheum rhaponicum"
728 h = NullFTPHandler(data)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700729 h.parent = MockOpener()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000730
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000731 for url, host, port, user, passwd, type_, dirs, filename, mimetype in [
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000732 ("ftp://localhost/foo/bar/baz.html",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000733 "localhost", ftplib.FTP_PORT, "", "", "I",
734 ["foo", "bar"], "baz.html", "text/html"),
735 ("ftp://parrot@localhost/foo/bar/baz.html",
736 "localhost", ftplib.FTP_PORT, "parrot", "", "I",
737 ["foo", "bar"], "baz.html", "text/html"),
738 ("ftp://%25parrot@localhost/foo/bar/baz.html",
739 "localhost", ftplib.FTP_PORT, "%parrot", "", "I",
740 ["foo", "bar"], "baz.html", "text/html"),
741 ("ftp://%2542parrot@localhost/foo/bar/baz.html",
742 "localhost", ftplib.FTP_PORT, "%42parrot", "", "I",
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000743 ["foo", "bar"], "baz.html", "text/html"),
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000744 ("ftp://localhost:80/foo/bar/",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000745 "localhost", 80, "", "", "D",
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000746 ["foo", "bar"], "", None),
747 ("ftp://localhost/baz.gif;type=a",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000748 "localhost", ftplib.FTP_PORT, "", "", "A",
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000749 [], "baz.gif", None), # XXX really this should guess image/gif
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000750 ]:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000751 req = Request(url)
752 req.timeout = None
753 r = h.ftp_open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000754 # ftp authentication not yet implemented by FTPHandler
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000755 self.assertEqual(h.user, user)
756 self.assertEqual(h.passwd, passwd)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000757 self.assertEqual(h.host, socket.gethostbyname(host))
758 self.assertEqual(h.port, port)
759 self.assertEqual(h.dirs, dirs)
760 self.assertEqual(h.ftpwrapper.filename, filename)
761 self.assertEqual(h.ftpwrapper.filetype, type_)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000762 headers = r.info()
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000763 self.assertEqual(headers.get("Content-type"), mimetype)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000764 self.assertEqual(int(headers["Content-length"]), len(data))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000765
766 def test_file(self):
Senthil Kumaranbc07ac52014-07-22 00:15:20 -0700767 import email.utils
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000768 h = urllib.request.FileHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000769 o = h.parent = MockOpener()
770
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000771 TESTFN = support.TESTFN
Tim Peters58eb11c2004-01-18 20:29:55 +0000772 urlpath = sanepathname2url(os.path.abspath(TESTFN))
Guido van Rossum6a2ccd02007-07-16 20:51:57 +0000773 towrite = b"hello, world\n"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000774 urls = [
Tim Peters58eb11c2004-01-18 20:29:55 +0000775 "file://localhost%s" % urlpath,
776 "file://%s" % urlpath,
777 "file://%s%s" % (socket.gethostbyname('localhost'), urlpath),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000778 ]
779 try:
780 localaddr = socket.gethostbyname(socket.gethostname())
781 except socket.gaierror:
782 localaddr = ''
783 if localaddr:
784 urls.append("file://%s%s" % (localaddr, urlpath))
785
786 for url in urls:
Tim Peters58eb11c2004-01-18 20:29:55 +0000787 f = open(TESTFN, "wb")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000788 try:
789 try:
790 f.write(towrite)
791 finally:
792 f.close()
793
794 r = h.file_open(Request(url))
795 try:
796 data = r.read()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000797 headers = r.info()
Senthil Kumaran4fbed102010-05-08 03:29:09 +0000798 respurl = r.geturl()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000799 finally:
800 r.close()
Tim Peters58eb11c2004-01-18 20:29:55 +0000801 stats = os.stat(TESTFN)
Benjamin Petersona0c0a4a2008-06-12 22:15:50 +0000802 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000803 finally:
804 os.remove(TESTFN)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000805 self.assertEqual(data, towrite)
806 self.assertEqual(headers["Content-type"], "text/plain")
807 self.assertEqual(headers["Content-length"], "13")
Tim Peters58eb11c2004-01-18 20:29:55 +0000808 self.assertEqual(headers["Last-modified"], modified)
Senthil Kumaran4fbed102010-05-08 03:29:09 +0000809 self.assertEqual(respurl, url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000810
811 for url in [
Tim Peters58eb11c2004-01-18 20:29:55 +0000812 "file://localhost:80%s" % urlpath,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000813 "file:///file_does_not_exist.txt",
Senthil Kumaranbc07ac52014-07-22 00:15:20 -0700814 "file://not-a-local-host.com//dir/file.txt",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000815 "file://%s:80%s/%s" % (socket.gethostbyname('localhost'),
816 os.getcwd(), TESTFN),
817 "file://somerandomhost.ontheinternet.com%s/%s" %
818 (os.getcwd(), TESTFN),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000819 ]:
820 try:
Tim Peters58eb11c2004-01-18 20:29:55 +0000821 f = open(TESTFN, "wb")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000822 try:
823 f.write(towrite)
824 finally:
825 f.close()
826
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000827 self.assertRaises(urllib.error.URLError,
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000828 h.file_open, Request(url))
829 finally:
830 os.remove(TESTFN)
831
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000832 h = urllib.request.FileHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000833 o = h.parent = MockOpener()
834 # XXXX why does // mean ftp (and /// mean not ftp!), and where
835 # is file: scheme specified? I think this is really a bug, and
836 # what was intended was to distinguish between URLs like:
837 # file:/blah.txt (a file)
838 # file://localhost/blah.txt (a file)
839 # file:///blah.txt (a file)
840 # file://ftp.example.com/blah.txt (an ftp URL)
841 for url, ftp in [
Senthil Kumaran383c32d2010-10-14 11:57:35 +0000842 ("file://ftp.example.com//foo.txt", False),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000843 ("file://ftp.example.com///foo.txt", False),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000844 ("file://ftp.example.com/foo.txt", False),
Senthil Kumaran383c32d2010-10-14 11:57:35 +0000845 ("file://somehost//foo/something.txt", False),
Senthil Kumaran2ef16322010-07-11 03:12:43 +0000846 ("file://localhost//foo/something.txt", False),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000847 ]:
848 req = Request(url)
849 try:
850 h.file_open(req)
Senthil Kumaraned3dd1c2017-03-30 22:43:05 -0700851 except urllib.error.URLError:
Florent Xicluna419e3842010-08-08 16:16:07 +0000852 self.assertFalse(ftp)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000853 else:
Florent Xicluna419e3842010-08-08 16:16:07 +0000854 self.assertIs(o.req, req)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000855 self.assertEqual(req.type, "ftp")
Łukasz Langad7e81cc2011-01-09 18:18:53 +0000856 self.assertEqual(req.type == "ftp", ftp)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000857
858 def test_http(self):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000859
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000860 h = urllib.request.AbstractHTTPHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000861 o = h.parent = MockOpener()
862
863 url = "http://example.com/"
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000864 for method, data in [("GET", None), ("POST", b"blah")]:
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000865 req = Request(url, data, {"Foo": "bar"})
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000866 req.timeout = None
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000867 req.add_unredirected_header("Spam", "eggs")
868 http = MockHTTPClass()
869 r = h.do_open(http, req)
870
871 # result attributes
872 r.read; r.readline # wrapped MockFile methods
873 r.info; r.geturl # addinfourl methods
874 r.code, r.msg == 200, "OK" # added from MockHTTPClass.getreply()
875 hdrs = r.info()
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000876 hdrs.get; hdrs.__contains__ # r.info() gives dict from .getreply()
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000877 self.assertEqual(r.geturl(), url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000878
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000879 self.assertEqual(http.host, "example.com")
880 self.assertEqual(http.level, 0)
881 self.assertEqual(http.method, method)
882 self.assertEqual(http.selector, "/")
883 self.assertEqual(http.req_headers,
Jeremy Hyltonb3ee6f92004-02-24 19:40:35 +0000884 [("Connection", "close"),
885 ("Foo", "bar"), ("Spam", "eggs")])
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000886 self.assertEqual(http.data, data)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000887
Andrew Svetlov0832af62012-12-18 23:10:48 +0200888 # check OSError converted to URLError
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000889 http.raise_on_endheaders = True
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000890 self.assertRaises(urllib.error.URLError, h.do_open, http, req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000891
Senthil Kumaran29333122011-02-11 11:25:47 +0000892 # Check for TypeError on POST data which is str.
893 req = Request("http://example.com/","badpost")
894 self.assertRaises(TypeError, h.do_request_, req)
895
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000896 # check adding of standard headers
897 o.addheaders = [("Spam", "eggs")]
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000898 for data in b"", None: # POST, GET
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000899 req = Request("http://example.com/", data)
900 r = MockResponse(200, "OK", {}, "")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000901 newreq = h.do_request_(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000902 if data is None: # GET
Benjamin Peterson577473f2010-01-19 00:09:57 +0000903 self.assertNotIn("Content-length", req.unredirected_hdrs)
904 self.assertNotIn("Content-type", req.unredirected_hdrs)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000905 else: # POST
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000906 self.assertEqual(req.unredirected_hdrs["Content-length"], "0")
907 self.assertEqual(req.unredirected_hdrs["Content-type"],
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000908 "application/x-www-form-urlencoded")
909 # XXX the details of Host could be better tested
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000910 self.assertEqual(req.unredirected_hdrs["Host"], "example.com")
911 self.assertEqual(req.unredirected_hdrs["Spam"], "eggs")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000912
913 # don't clobber existing headers
914 req.add_unredirected_header("Content-length", "foo")
915 req.add_unredirected_header("Content-type", "bar")
916 req.add_unredirected_header("Host", "baz")
917 req.add_unredirected_header("Spam", "foo")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000918 newreq = h.do_request_(req)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000919 self.assertEqual(req.unredirected_hdrs["Content-length"], "foo")
920 self.assertEqual(req.unredirected_hdrs["Content-type"], "bar")
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000921 self.assertEqual(req.unredirected_hdrs["Host"], "baz")
922 self.assertEqual(req.unredirected_hdrs["Spam"], "foo")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000923
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000924 def test_http_body_file(self):
Martin Panteref91bb22016-08-27 01:39:26 +0000925 # A regular file - chunked encoding is used unless Content Length is
926 # already set.
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000927
928 h = urllib.request.AbstractHTTPHandler()
929 o = h.parent = MockOpener()
930
931 file_obj = tempfile.NamedTemporaryFile(mode='w+b', delete=False)
932 file_path = file_obj.name
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000933 file_obj.close()
Martin Panteref91bb22016-08-27 01:39:26 +0000934 self.addCleanup(os.unlink, file_path)
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000935
Martin Panteref91bb22016-08-27 01:39:26 +0000936 with open(file_path, "rb") as f:
937 req = Request("http://example.com/", f, {})
938 newreq = h.do_request_(req)
939 te = newreq.get_header('Transfer-encoding')
940 self.assertEqual(te, "chunked")
941 self.assertFalse(newreq.has_header('Content-length'))
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000942
Martin Panteref91bb22016-08-27 01:39:26 +0000943 with open(file_path, "rb") as f:
944 req = Request("http://example.com/", f, {"Content-Length": 30})
945 newreq = h.do_request_(req)
946 self.assertEqual(int(newreq.get_header('Content-length')), 30)
947 self.assertFalse(newreq.has_header("Transfer-encoding"))
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000948
949 def test_http_body_fileobj(self):
Martin Panteref91bb22016-08-27 01:39:26 +0000950 # A file object - chunked encoding is used
951 # unless Content Length is already set.
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000952 # (Note that there are some subtle differences to a regular
953 # file, that is why we are testing both cases.)
954
955 h = urllib.request.AbstractHTTPHandler()
956 o = h.parent = MockOpener()
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000957 file_obj = io.BytesIO()
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000958
Martin Panteref91bb22016-08-27 01:39:26 +0000959 req = Request("http://example.com/", file_obj, {})
960 newreq = h.do_request_(req)
961 self.assertEqual(newreq.get_header('Transfer-encoding'), 'chunked')
962 self.assertFalse(newreq.has_header('Content-length'))
963
964 headers = {"Content-Length": 30}
965 req = Request("http://example.com/", file_obj, headers)
966 newreq = h.do_request_(req)
967 self.assertEqual(int(newreq.get_header('Content-length')), 30)
968 self.assertFalse(newreq.has_header("Transfer-encoding"))
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000969
970 file_obj.close()
971
972 def test_http_body_pipe(self):
973 # A file reading from a pipe.
974 # A pipe cannot be seek'ed. There is no way to determine the
975 # content length up front. Thus, do_request_() should fall
976 # back to Transfer-encoding chunked.
977
978 h = urllib.request.AbstractHTTPHandler()
979 o = h.parent = MockOpener()
980
Martin Panteref91bb22016-08-27 01:39:26 +0000981 cmd = [sys.executable, "-c", r"pass"]
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000982 for headers in {}, {"Content-Length": 30}:
983 with subprocess.Popen(cmd, stdout=subprocess.PIPE) as proc:
984 req = Request("http://example.com/", proc.stdout, headers)
985 newreq = h.do_request_(req)
986 if not headers:
987 self.assertEqual(newreq.get_header('Content-length'), None)
988 self.assertEqual(newreq.get_header('Transfer-encoding'),
989 'chunked')
990 else:
991 self.assertEqual(int(newreq.get_header('Content-length')),
992 30)
993
994 def test_http_body_iterable(self):
995 # Generic iterable. There is no way to determine the content
996 # length up front. Fall back to Transfer-encoding chunked.
997
998 h = urllib.request.AbstractHTTPHandler()
999 o = h.parent = MockOpener()
1000
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001001 def iterable_body():
1002 yield b"one"
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001003
1004 for headers in {}, {"Content-Length": 11}:
1005 req = Request("http://example.com/", iterable_body(), headers)
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001006 newreq = h.do_request_(req)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001007 if not headers:
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001008 self.assertEqual(newreq.get_header('Content-length'), None)
1009 self.assertEqual(newreq.get_header('Transfer-encoding'),
1010 'chunked')
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001011 else:
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001012 self.assertEqual(int(newreq.get_header('Content-length')), 11)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001013
Martin Panteref91bb22016-08-27 01:39:26 +00001014 def test_http_body_empty_seq(self):
1015 # Zero-length iterable body should be treated like any other iterable
1016 h = urllib.request.AbstractHTTPHandler()
1017 h.parent = MockOpener()
1018 req = h.do_request_(Request("http://example.com/", ()))
1019 self.assertEqual(req.get_header("Transfer-encoding"), "chunked")
1020 self.assertFalse(req.has_header("Content-length"))
1021
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001022 def test_http_body_array(self):
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001023 # array.array Iterable - Content Length is calculated
1024
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001025 h = urllib.request.AbstractHTTPHandler()
1026 o = h.parent = MockOpener()
1027
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001028 iterable_array = array.array("I",[1,2,3,4])
1029
1030 for headers in {}, {"Content-Length": 16}:
1031 req = Request("http://example.com/", iterable_array, headers)
1032 newreq = h.do_request_(req)
1033 self.assertEqual(int(newreq.get_header('Content-length')),16)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001034
Senthil Kumaran9642eed2016-05-13 01:32:42 -07001035 def test_http_handler_debuglevel(self):
1036 o = OpenerDirector()
1037 h = MockHTTPSHandler(debuglevel=1)
1038 o.add_handler(h)
1039 o.open("https://www.example.com")
1040 self.assertEqual(h._debuglevel, 1)
1041
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001042 def test_http_doubleslash(self):
1043 # Checks the presence of any unnecessary double slash in url does not
1044 # break anything. Previously, a double slash directly after the host
Ezio Melottie130a522011-10-19 10:58:56 +03001045 # could cause incorrect parsing.
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001046 h = urllib.request.AbstractHTTPHandler()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001047 h.parent = MockOpener()
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001048
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001049 data = b""
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001050 ds_urls = [
1051 "http://example.com/foo/bar/baz.html",
1052 "http://example.com//foo/bar/baz.html",
1053 "http://example.com/foo//bar/baz.html",
1054 "http://example.com/foo/bar//baz.html"
1055 ]
1056
1057 for ds_url in ds_urls:
1058 ds_req = Request(ds_url, data)
1059
1060 # Check whether host is determined correctly if there is no proxy
1061 np_ds_req = h.do_request_(ds_req)
Facundo Batista244afcf2015-04-22 18:35:54 -03001062 self.assertEqual(np_ds_req.unredirected_hdrs["Host"], "example.com")
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001063
1064 # Check whether host is determined correctly if there is a proxy
Facundo Batista244afcf2015-04-22 18:35:54 -03001065 ds_req.set_proxy("someproxy:3128", None)
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001066 p_ds_req = h.do_request_(ds_req)
Facundo Batista244afcf2015-04-22 18:35:54 -03001067 self.assertEqual(p_ds_req.unredirected_hdrs["Host"], "example.com")
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001068
Senthil Kumaran52380922013-04-25 05:45:48 -07001069 def test_full_url_setter(self):
1070 # Checks to ensure that components are set correctly after setting the
1071 # full_url of a Request object
1072
1073 urls = [
1074 'http://example.com?foo=bar#baz',
1075 'http://example.com?foo=bar&spam=eggs#bash',
1076 'http://example.com',
1077 ]
1078
1079 # testing a reusable request instance, but the url parameter is
1080 # required, so just use a dummy one to instantiate
1081 r = Request('http://example.com')
1082 for url in urls:
1083 r.full_url = url
Senthil Kumaran83070752013-05-24 09:14:12 -07001084 parsed = urlparse(url)
1085
Senthil Kumaran52380922013-04-25 05:45:48 -07001086 self.assertEqual(r.get_full_url(), url)
Senthil Kumaran83070752013-05-24 09:14:12 -07001087 # full_url setter uses splittag to split into components.
1088 # splittag sets the fragment as None while urlparse sets it to ''
1089 self.assertEqual(r.fragment or '', parsed.fragment)
1090 self.assertEqual(urlparse(r.get_full_url()).query, parsed.query)
Senthil Kumaran52380922013-04-25 05:45:48 -07001091
1092 def test_full_url_deleter(self):
1093 r = Request('http://www.example.com')
1094 del r.full_url
1095 self.assertIsNone(r.full_url)
1096 self.assertIsNone(r.fragment)
1097 self.assertEqual(r.selector, '')
1098
Senthil Kumaranc2958622010-11-22 04:48:26 +00001099 def test_fixpath_in_weirdurls(self):
1100 # Issue4493: urllib2 to supply '/' when to urls where path does not
1101 # start with'/'
1102
1103 h = urllib.request.AbstractHTTPHandler()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001104 h.parent = MockOpener()
Senthil Kumaranc2958622010-11-22 04:48:26 +00001105
1106 weird_url = 'http://www.python.org?getspam'
1107 req = Request(weird_url)
1108 newreq = h.do_request_(req)
Facundo Batista244afcf2015-04-22 18:35:54 -03001109 self.assertEqual(newreq.host, 'www.python.org')
1110 self.assertEqual(newreq.selector, '/?getspam')
Senthil Kumaranc2958622010-11-22 04:48:26 +00001111
1112 url_without_path = 'http://www.python.org'
1113 req = Request(url_without_path)
1114 newreq = h.do_request_(req)
Facundo Batista244afcf2015-04-22 18:35:54 -03001115 self.assertEqual(newreq.host, 'www.python.org')
1116 self.assertEqual(newreq.selector, '')
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001117
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001118 def test_errors(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001119 h = urllib.request.HTTPErrorProcessor()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001120 o = h.parent = MockOpener()
1121
1122 url = "http://example.com/"
1123 req = Request(url)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001124 # all 2xx are passed through
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001125 r = MockResponse(200, "OK", {}, "", url)
1126 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +00001127 self.assertIs(r, newr)
1128 self.assertFalse(hasattr(o, "proto")) # o.error not called
Guido van Rossumd8faa362007-04-27 19:54:29 +00001129 r = MockResponse(202, "Accepted", {}, "", url)
1130 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +00001131 self.assertIs(r, newr)
1132 self.assertFalse(hasattr(o, "proto")) # o.error not called
Guido van Rossumd8faa362007-04-27 19:54:29 +00001133 r = MockResponse(206, "Partial content", {}, "", url)
1134 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +00001135 self.assertIs(r, newr)
1136 self.assertFalse(hasattr(o, "proto")) # o.error not called
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001137 # anything else calls o.error (and MockOpener returns None, here)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001138 r = MockResponse(502, "Bad gateway", {}, "", url)
Florent Xicluna419e3842010-08-08 16:16:07 +00001139 self.assertIsNone(h.http_response(req, r))
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001140 self.assertEqual(o.proto, "http") # o.error called
Guido van Rossumd8faa362007-04-27 19:54:29 +00001141 self.assertEqual(o.args, (req, r, 502, "Bad gateway", {}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001142
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001143 def test_cookies(self):
1144 cj = MockCookieJar()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001145 h = urllib.request.HTTPCookieProcessor(cj)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001146 h.parent = MockOpener()
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001147
1148 req = Request("http://example.com/")
1149 r = MockResponse(200, "OK", {}, "")
1150 newreq = h.http_request(req)
Florent Xicluna419e3842010-08-08 16:16:07 +00001151 self.assertIs(cj.ach_req, req)
1152 self.assertIs(cj.ach_req, newreq)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001153 self.assertEqual(req.origin_req_host, "example.com")
1154 self.assertFalse(req.unverifiable)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001155 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +00001156 self.assertIs(cj.ec_req, req)
1157 self.assertIs(cj.ec_r, r)
1158 self.assertIs(r, newr)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001159
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001160 def test_redirect(self):
1161 from_url = "http://example.com/a.html"
1162 to_url = "http://example.com/b.html"
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001163 h = urllib.request.HTTPRedirectHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001164 o = h.parent = MockOpener()
1165
1166 # ordinary redirect behaviour
1167 for code in 301, 302, 303, 307:
1168 for data in None, "blah\nblah\n":
1169 method = getattr(h, "http_error_%s" % code)
1170 req = Request(from_url, data)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001171 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001172 req.add_header("Nonsense", "viking=withhold")
Christian Heimes77c02eb2008-02-09 02:18:51 +00001173 if data is not None:
1174 req.add_header("Content-Length", str(len(data)))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001175 req.add_unredirected_header("Spam", "spam")
1176 try:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001177 method(req, MockFile(), code, "Blah",
1178 MockHeaders({"location": to_url}))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001179 except urllib.error.HTTPError:
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001180 # 307 in response to POST requires user OK
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001181 self.assertEqual(code, 307)
1182 self.assertIsNotNone(data)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001183 self.assertEqual(o.req.get_full_url(), to_url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001184 try:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001185 self.assertEqual(o.req.get_method(), "GET")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001186 except AttributeError:
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001187 self.assertFalse(o.req.data)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001188
1189 # now it's a GET, there should not be headers regarding content
1190 # (possibly dragged from before being a POST)
1191 headers = [x.lower() for x in o.req.headers]
Benjamin Peterson577473f2010-01-19 00:09:57 +00001192 self.assertNotIn("content-length", headers)
1193 self.assertNotIn("content-type", headers)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001194
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001195 self.assertEqual(o.req.headers["Nonsense"],
1196 "viking=withhold")
Benjamin Peterson577473f2010-01-19 00:09:57 +00001197 self.assertNotIn("Spam", o.req.headers)
1198 self.assertNotIn("Spam", o.req.unredirected_hdrs)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001199
1200 # loop detection
1201 req = Request(from_url)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001202 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Facundo Batista244afcf2015-04-22 18:35:54 -03001203
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001204 def redirect(h, req, url=to_url):
1205 h.http_error_302(req, MockFile(), 302, "Blah",
1206 MockHeaders({"location": url}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001207 # Note that the *original* request shares the same record of
1208 # redirections with the sub-requests caused by the redirections.
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001209
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001210 # detect infinite loop redirect of a URL to itself
1211 req = Request(from_url, origin_req_host="example.com")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001212 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001213 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001214 try:
1215 while 1:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001216 redirect(h, req, "http://example.com/")
1217 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001218 except urllib.error.HTTPError:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001219 # don't stop until max_repeats, because cookies may introduce state
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001220 self.assertEqual(count, urllib.request.HTTPRedirectHandler.max_repeats)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001221
1222 # detect endless non-repeating chain of redirects
1223 req = Request(from_url, origin_req_host="example.com")
1224 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001225 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001226 try:
1227 while 1:
1228 redirect(h, req, "http://example.com/%d" % count)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001229 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001230 except urllib.error.HTTPError:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001231 self.assertEqual(count,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001232 urllib.request.HTTPRedirectHandler.max_redirections)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001233
guido@google.coma119df92011-03-29 11:41:02 -07001234 def test_invalid_redirect(self):
1235 from_url = "http://example.com/a.html"
1236 valid_schemes = ['http','https','ftp']
1237 invalid_schemes = ['file','imap','ldap']
1238 schemeless_url = "example.com/b.html"
1239 h = urllib.request.HTTPRedirectHandler()
1240 o = h.parent = MockOpener()
1241 req = Request(from_url)
1242 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1243
1244 for scheme in invalid_schemes:
1245 invalid_url = scheme + '://' + schemeless_url
1246 self.assertRaises(urllib.error.HTTPError, h.http_error_302,
1247 req, MockFile(), 302, "Security Loophole",
1248 MockHeaders({"location": invalid_url}))
1249
1250 for scheme in valid_schemes:
1251 valid_url = scheme + '://' + schemeless_url
1252 h.http_error_302(req, MockFile(), 302, "That's fine",
1253 MockHeaders({"location": valid_url}))
1254 self.assertEqual(o.req.get_full_url(), valid_url)
1255
Senthil Kumaran6497aa32012-01-04 13:46:59 +08001256 def test_relative_redirect(self):
1257 from_url = "http://example.com/a.html"
1258 relative_url = "/b.html"
1259 h = urllib.request.HTTPRedirectHandler()
1260 o = h.parent = MockOpener()
1261 req = Request(from_url)
1262 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1263
1264 valid_url = urllib.parse.urljoin(from_url,relative_url)
1265 h.http_error_302(req, MockFile(), 302, "That's fine",
1266 MockHeaders({"location": valid_url}))
1267 self.assertEqual(o.req.get_full_url(), valid_url)
1268
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001269 def test_cookie_redirect(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001270 # cookies shouldn't leak into redirected requests
Georg Brandl24420152008-05-26 16:32:26 +00001271 from http.cookiejar import CookieJar
1272 from test.test_http_cookiejar import interact_netscape
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001273
1274 cj = CookieJar()
1275 interact_netscape(cj, "http://www.example.com/", "spam=eggs")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001276 hh = MockHTTPHandler(302, "Location: http://www.cracker.com/\r\n\r\n")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001277 hdeh = urllib.request.HTTPDefaultErrorHandler()
1278 hrh = urllib.request.HTTPRedirectHandler()
1279 cp = urllib.request.HTTPCookieProcessor(cj)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001280 o = build_test_opener(hh, hdeh, hrh, cp)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001281 o.open("http://www.example.com/")
Florent Xicluna419e3842010-08-08 16:16:07 +00001282 self.assertFalse(hh.req.has_header("Cookie"))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001283
Senthil Kumaran26430412011-04-13 07:01:19 +08001284 def test_redirect_fragment(self):
1285 redirected_url = 'http://www.example.com/index.html#OK\r\n\r\n'
1286 hh = MockHTTPHandler(302, 'Location: ' + redirected_url)
1287 hdeh = urllib.request.HTTPDefaultErrorHandler()
1288 hrh = urllib.request.HTTPRedirectHandler()
1289 o = build_test_opener(hh, hdeh, hrh)
1290 fp = o.open('http://www.example.com')
1291 self.assertEqual(fp.geturl(), redirected_url.strip())
1292
Martin Panterce6e0682016-05-16 01:07:13 +00001293 def test_redirect_no_path(self):
1294 # Issue 14132: Relative redirect strips original path
1295 real_class = http.client.HTTPConnection
1296 response1 = b"HTTP/1.1 302 Found\r\nLocation: ?query\r\n\r\n"
1297 http.client.HTTPConnection = test_urllib.fakehttp(response1)
1298 self.addCleanup(setattr, http.client, "HTTPConnection", real_class)
1299 urls = iter(("/path", "/path?query"))
1300 def request(conn, method, url, *pos, **kw):
1301 self.assertEqual(url, next(urls))
1302 real_class.request(conn, method, url, *pos, **kw)
1303 # Change response for subsequent connection
1304 conn.__class__.fakedata = b"HTTP/1.1 200 OK\r\n\r\nHello!"
1305 http.client.HTTPConnection.request = request
1306 fp = urllib.request.urlopen("http://python.org/path")
1307 self.assertEqual(fp.geturl(), "http://python.org/path?query")
1308
Martin Pantere6f06092016-05-16 01:14:20 +00001309 def test_redirect_encoding(self):
1310 # Some characters in the redirect target may need special handling,
1311 # but most ASCII characters should be treated as already encoded
1312 class Handler(urllib.request.HTTPHandler):
1313 def http_open(self, req):
1314 result = self.do_open(self.connection, req)
1315 self.last_buf = self.connection.buf
1316 # Set up a normal response for the next request
1317 self.connection = test_urllib.fakehttp(
1318 b'HTTP/1.1 200 OK\r\n'
1319 b'Content-Length: 3\r\n'
1320 b'\r\n'
1321 b'123'
1322 )
1323 return result
1324 handler = Handler()
1325 opener = urllib.request.build_opener(handler)
1326 tests = (
1327 (b'/p\xC3\xA5-dansk/', b'/p%C3%A5-dansk/'),
1328 (b'/spaced%20path/', b'/spaced%20path/'),
1329 (b'/spaced path/', b'/spaced%20path/'),
1330 (b'/?p\xC3\xA5-dansk', b'/?p%C3%A5-dansk'),
1331 )
1332 for [location, result] in tests:
1333 with self.subTest(repr(location)):
1334 handler.connection = test_urllib.fakehttp(
1335 b'HTTP/1.1 302 Redirect\r\n'
1336 b'Location: ' + location + b'\r\n'
1337 b'\r\n'
1338 )
1339 response = opener.open('http://example.com/')
1340 expected = b'GET ' + result + b' '
1341 request = handler.last_buf
1342 self.assertTrue(request.startswith(expected), repr(request))
1343
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001344 def test_proxy(self):
1345 o = OpenerDirector()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001346 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001347 o.add_handler(ph)
1348 meth_spec = [
1349 [("http_open", "return response")]
1350 ]
1351 handlers = add_ordered_mock_handlers(o, meth_spec)
1352
1353 req = Request("http://acme.example.com/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001354 self.assertEqual(req.host, "acme.example.com")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001355 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001356 self.assertEqual(req.host, "proxy.example.com:3128")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001357
1358 self.assertEqual([(handlers[0], "http_open")],
1359 [tup[0:2] for tup in o.calls])
1360
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001361 def test_proxy_no_proxy(self):
1362 os.environ['no_proxy'] = 'python.org'
1363 o = OpenerDirector()
1364 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1365 o.add_handler(ph)
1366 req = Request("http://www.perl.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001367 self.assertEqual(req.host, "www.perl.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001368 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001369 self.assertEqual(req.host, "proxy.example.com")
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001370 req = Request("http://www.python.org")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001371 self.assertEqual(req.host, "www.python.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001372 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001373 self.assertEqual(req.host, "www.python.org")
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001374 del os.environ['no_proxy']
1375
Ronald Oussorene72e1612011-03-14 18:15:25 -04001376 def test_proxy_no_proxy_all(self):
1377 os.environ['no_proxy'] = '*'
1378 o = OpenerDirector()
1379 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1380 o.add_handler(ph)
1381 req = Request("http://www.python.org")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001382 self.assertEqual(req.host, "www.python.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001383 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001384 self.assertEqual(req.host, "www.python.org")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001385 del os.environ['no_proxy']
1386
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001387 def test_proxy_https(self):
1388 o = OpenerDirector()
1389 ph = urllib.request.ProxyHandler(dict(https="proxy.example.com:3128"))
1390 o.add_handler(ph)
1391 meth_spec = [
1392 [("https_open", "return response")]
1393 ]
1394 handlers = add_ordered_mock_handlers(o, meth_spec)
1395
1396 req = Request("https://www.example.com/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001397 self.assertEqual(req.host, "www.example.com")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001398 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001399 self.assertEqual(req.host, "proxy.example.com:3128")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001400 self.assertEqual([(handlers[0], "https_open")],
1401 [tup[0:2] for tup in o.calls])
1402
Senthil Kumaran47fff872009-12-20 07:10:31 +00001403 def test_proxy_https_proxy_authorization(self):
1404 o = OpenerDirector()
1405 ph = urllib.request.ProxyHandler(dict(https='proxy.example.com:3128'))
1406 o.add_handler(ph)
1407 https_handler = MockHTTPSHandler()
1408 o.add_handler(https_handler)
1409 req = Request("https://www.example.com/")
Facundo Batista244afcf2015-04-22 18:35:54 -03001410 req.add_header("Proxy-Authorization", "FooBar")
1411 req.add_header("User-Agent", "Grail")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001412 self.assertEqual(req.host, "www.example.com")
Senthil Kumaran47fff872009-12-20 07:10:31 +00001413 self.assertIsNone(req._tunnel_host)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001414 o.open(req)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001415 # Verify Proxy-Authorization gets tunneled to request.
1416 # httpsconn req_headers do not have the Proxy-Authorization header but
1417 # the req will have.
Facundo Batista244afcf2015-04-22 18:35:54 -03001418 self.assertNotIn(("Proxy-Authorization", "FooBar"),
Senthil Kumaran47fff872009-12-20 07:10:31 +00001419 https_handler.httpconn.req_headers)
Facundo Batista244afcf2015-04-22 18:35:54 -03001420 self.assertIn(("User-Agent", "Grail"),
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001421 https_handler.httpconn.req_headers)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001422 self.assertIsNotNone(req._tunnel_host)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001423 self.assertEqual(req.host, "proxy.example.com:3128")
Facundo Batista244afcf2015-04-22 18:35:54 -03001424 self.assertEqual(req.get_header("Proxy-authorization"), "FooBar")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001425
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001426 @unittest.skipUnless(sys.platform == 'darwin', "only relevant for OSX")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001427 def test_osx_proxy_bypass(self):
1428 bypass = {
1429 'exclude_simple': False,
1430 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.10',
1431 '10.0/16']
1432 }
1433 # Check hosts that should trigger the proxy bypass
1434 for host in ('foo.bar', 'www.bar.com', '127.0.0.1', '10.10.0.1',
1435 '10.0.0.1'):
1436 self.assertTrue(_proxy_bypass_macosx_sysconf(host, bypass),
1437 'expected bypass of %s to be True' % host)
1438 # Check hosts that should not trigger the proxy bypass
R David Murrayfdbe9182014-03-15 12:00:14 -04001439 for host in ('abc.foo.bar', 'bar.com', '127.0.0.2', '10.11.0.1',
1440 'notinbypass'):
Ronald Oussorene72e1612011-03-14 18:15:25 -04001441 self.assertFalse(_proxy_bypass_macosx_sysconf(host, bypass),
1442 'expected bypass of %s to be False' % host)
1443
1444 # Check the exclude_simple flag
1445 bypass = {'exclude_simple': True, 'exceptions': []}
1446 self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass))
1447
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001448 def test_basic_auth(self, quote_char='"'):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001449 opener = OpenerDirector()
1450 password_manager = MockPasswordManager()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001451 auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001452 realm = "ACME Widget Store"
1453 http_handler = MockHTTPHandler(
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001454 401, 'WWW-Authenticate: Basic realm=%s%s%s\r\n\r\n' %
Facundo Batista244afcf2015-04-22 18:35:54 -03001455 (quote_char, realm, quote_char))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001456 opener.add_handler(auth_handler)
1457 opener.add_handler(http_handler)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001458 self._test_basic_auth(opener, auth_handler, "Authorization",
1459 realm, http_handler, password_manager,
1460 "http://acme.example.com/protected",
1461 "http://acme.example.com/protected",
1462 )
1463
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001464 def test_basic_auth_with_single_quoted_realm(self):
1465 self.test_basic_auth(quote_char="'")
1466
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +08001467 def test_basic_auth_with_unquoted_realm(self):
1468 opener = OpenerDirector()
1469 password_manager = MockPasswordManager()
1470 auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
1471 realm = "ACME Widget Store"
1472 http_handler = MockHTTPHandler(
1473 401, 'WWW-Authenticate: Basic realm=%s\r\n\r\n' % realm)
1474 opener.add_handler(auth_handler)
1475 opener.add_handler(http_handler)
Senthil Kumaran0ea91cb2012-05-15 23:59:42 +08001476 with self.assertWarns(UserWarning):
1477 self._test_basic_auth(opener, auth_handler, "Authorization",
1478 realm, http_handler, password_manager,
1479 "http://acme.example.com/protected",
1480 "http://acme.example.com/protected",
1481 )
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +08001482
Thomas Wouters477c8d52006-05-27 19:21:47 +00001483 def test_proxy_basic_auth(self):
1484 opener = OpenerDirector()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001485 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001486 opener.add_handler(ph)
1487 password_manager = MockPasswordManager()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001488 auth_handler = urllib.request.ProxyBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001489 realm = "ACME Networks"
1490 http_handler = MockHTTPHandler(
1491 407, 'Proxy-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001492 opener.add_handler(auth_handler)
1493 opener.add_handler(http_handler)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001494 self._test_basic_auth(opener, auth_handler, "Proxy-authorization",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001495 realm, http_handler, password_manager,
1496 "http://acme.example.com:3128/protected",
1497 "proxy.example.com:3128",
1498 )
1499
1500 def test_basic_and_digest_auth_handlers(self):
Andrew Svetlov7bd61cb2012-12-19 22:49:25 +02001501 # HTTPDigestAuthHandler raised an exception if it couldn't handle a 40*
Thomas Wouters477c8d52006-05-27 19:21:47 +00001502 # response (http://python.org/sf/1479302), where it should instead
1503 # return None to allow another handler (especially
1504 # HTTPBasicAuthHandler) to handle the response.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001505
1506 # Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must
1507 # try digest first (since it's the strongest auth scheme), so we record
1508 # order of calls here to check digest comes first:
1509 class RecordingOpenerDirector(OpenerDirector):
1510 def __init__(self):
1511 OpenerDirector.__init__(self)
1512 self.recorded = []
Facundo Batista244afcf2015-04-22 18:35:54 -03001513
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001514 def record(self, info):
1515 self.recorded.append(info)
Facundo Batista244afcf2015-04-22 18:35:54 -03001516
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001517 class TestDigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001518 def http_error_401(self, *args, **kwds):
1519 self.parent.record("digest")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001520 urllib.request.HTTPDigestAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001521 *args, **kwds)
Facundo Batista244afcf2015-04-22 18:35:54 -03001522
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001523 class TestBasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001524 def http_error_401(self, *args, **kwds):
1525 self.parent.record("basic")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001526 urllib.request.HTTPBasicAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001527 *args, **kwds)
1528
1529 opener = RecordingOpenerDirector()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001530 password_manager = MockPasswordManager()
1531 digest_handler = TestDigestAuthHandler(password_manager)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001532 basic_handler = TestBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001533 realm = "ACME Networks"
1534 http_handler = MockHTTPHandler(
1535 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001536 opener.add_handler(basic_handler)
1537 opener.add_handler(digest_handler)
1538 opener.add_handler(http_handler)
1539
1540 # check basic auth isn't blocked by digest handler failing
Thomas Wouters477c8d52006-05-27 19:21:47 +00001541 self._test_basic_auth(opener, basic_handler, "Authorization",
1542 realm, http_handler, password_manager,
1543 "http://acme.example.com/protected",
1544 "http://acme.example.com/protected",
1545 )
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001546 # check digest was tried before basic (twice, because
1547 # _test_basic_auth called .open() twice)
1548 self.assertEqual(opener.recorded, ["digest", "basic"]*2)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001549
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001550 def test_unsupported_auth_digest_handler(self):
1551 opener = OpenerDirector()
1552 # While using DigestAuthHandler
1553 digest_auth_handler = urllib.request.HTTPDigestAuthHandler(None)
1554 http_handler = MockHTTPHandler(
1555 401, 'WWW-Authenticate: Kerberos\r\n\r\n')
1556 opener.add_handler(digest_auth_handler)
1557 opener.add_handler(http_handler)
Facundo Batista244afcf2015-04-22 18:35:54 -03001558 self.assertRaises(ValueError, opener.open, "http://www.example.com")
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001559
1560 def test_unsupported_auth_basic_handler(self):
1561 # While using BasicAuthHandler
1562 opener = OpenerDirector()
1563 basic_auth_handler = urllib.request.HTTPBasicAuthHandler(None)
1564 http_handler = MockHTTPHandler(
1565 401, 'WWW-Authenticate: NTLM\r\n\r\n')
1566 opener.add_handler(basic_auth_handler)
1567 opener.add_handler(http_handler)
Facundo Batista244afcf2015-04-22 18:35:54 -03001568 self.assertRaises(ValueError, opener.open, "http://www.example.com")
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001569
Thomas Wouters477c8d52006-05-27 19:21:47 +00001570 def _test_basic_auth(self, opener, auth_handler, auth_header,
1571 realm, http_handler, password_manager,
1572 request_url, protected_url):
Christian Heimes05e8be12008-02-23 18:30:17 +00001573 import base64
Thomas Wouters477c8d52006-05-27 19:21:47 +00001574 user, password = "wile", "coyote"
Thomas Wouters477c8d52006-05-27 19:21:47 +00001575
1576 # .add_password() fed through to password manager
1577 auth_handler.add_password(realm, request_url, user, password)
1578 self.assertEqual(realm, password_manager.realm)
1579 self.assertEqual(request_url, password_manager.url)
1580 self.assertEqual(user, password_manager.user)
1581 self.assertEqual(password, password_manager.password)
1582
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001583 opener.open(request_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001584
1585 # should have asked the password manager for the username/password
1586 self.assertEqual(password_manager.target_realm, realm)
1587 self.assertEqual(password_manager.target_url, protected_url)
1588
1589 # expect one request without authorization, then one with
1590 self.assertEqual(len(http_handler.requests), 2)
1591 self.assertFalse(http_handler.requests[0].has_header(auth_header))
Guido van Rossum98b349f2007-08-27 21:47:52 +00001592 userpass = bytes('%s:%s' % (user, password), "ascii")
Guido van Rossum98297ee2007-11-06 21:34:58 +00001593 auth_hdr_value = ('Basic ' +
Georg Brandl706824f2009-06-04 09:42:55 +00001594 base64.encodebytes(userpass).strip().decode())
Thomas Wouters477c8d52006-05-27 19:21:47 +00001595 self.assertEqual(http_handler.requests[1].get_header(auth_header),
1596 auth_hdr_value)
Senthil Kumaranca2fc9e2010-02-24 16:53:16 +00001597 self.assertEqual(http_handler.requests[1].unredirected_hdrs[auth_header],
1598 auth_hdr_value)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001599 # if the password manager can't find a password, the handler won't
1600 # handle the HTTP auth error
1601 password_manager.user = password_manager.password = None
1602 http_handler.reset()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001603 opener.open(request_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001604 self.assertEqual(len(http_handler.requests), 1)
1605 self.assertFalse(http_handler.requests[0].has_header(auth_header))
1606
R David Murray4c7f9952015-04-16 16:36:18 -04001607 def test_basic_prior_auth_auto_send(self):
1608 # Assume already authenticated if is_authenticated=True
1609 # for APIs like Github that don't return 401
1610
1611 user, password = "wile", "coyote"
1612 request_url = "http://acme.example.com/protected"
1613
1614 http_handler = MockHTTPHandlerCheckAuth(200)
1615
1616 pwd_manager = HTTPPasswordMgrWithPriorAuth()
1617 auth_prior_handler = HTTPBasicAuthHandler(pwd_manager)
1618 auth_prior_handler.add_password(
1619 None, request_url, user, password, is_authenticated=True)
1620
1621 is_auth = pwd_manager.is_authenticated(request_url)
1622 self.assertTrue(is_auth)
1623
1624 opener = OpenerDirector()
1625 opener.add_handler(auth_prior_handler)
1626 opener.add_handler(http_handler)
1627
1628 opener.open(request_url)
1629
1630 # expect request to be sent with auth header
1631 self.assertTrue(http_handler.has_auth_header)
1632
1633 def test_basic_prior_auth_send_after_first_success(self):
1634 # Auto send auth header after authentication is successful once
1635
1636 user, password = 'wile', 'coyote'
1637 request_url = 'http://acme.example.com/protected'
1638 realm = 'ACME'
1639
1640 pwd_manager = HTTPPasswordMgrWithPriorAuth()
1641 auth_prior_handler = HTTPBasicAuthHandler(pwd_manager)
1642 auth_prior_handler.add_password(realm, request_url, user, password)
1643
1644 is_auth = pwd_manager.is_authenticated(request_url)
1645 self.assertFalse(is_auth)
1646
1647 opener = OpenerDirector()
1648 opener.add_handler(auth_prior_handler)
1649
1650 http_handler = MockHTTPHandler(
1651 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % None)
1652 opener.add_handler(http_handler)
1653
1654 opener.open(request_url)
1655
1656 is_auth = pwd_manager.is_authenticated(request_url)
1657 self.assertTrue(is_auth)
1658
1659 http_handler = MockHTTPHandlerCheckAuth(200)
1660 self.assertFalse(http_handler.has_auth_header)
1661
1662 opener = OpenerDirector()
1663 opener.add_handler(auth_prior_handler)
1664 opener.add_handler(http_handler)
1665
1666 # After getting 200 from MockHTTPHandler
1667 # Next request sends header in the first request
1668 opener.open(request_url)
1669
1670 # expect request to be sent with auth header
1671 self.assertTrue(http_handler.has_auth_header)
1672
Serhiy Storchakaf54c3502014-09-06 21:41:39 +03001673 def test_http_closed(self):
1674 """Test the connection is cleaned up when the response is closed"""
1675 for (transfer, data) in (
1676 ("Connection: close", b"data"),
1677 ("Transfer-Encoding: chunked", b"4\r\ndata\r\n0\r\n\r\n"),
1678 ("Content-Length: 4", b"data"),
1679 ):
1680 header = "HTTP/1.1 200 OK\r\n{}\r\n\r\n".format(transfer)
1681 conn = test_urllib.fakehttp(header.encode() + data)
1682 handler = urllib.request.AbstractHTTPHandler()
1683 req = Request("http://dummy/")
1684 req.timeout = None
1685 with handler.do_open(conn, req) as resp:
1686 resp.read()
1687 self.assertTrue(conn.fakesock.closed,
1688 "Connection not closed with {!r}".format(transfer))
1689
1690 def test_invalid_closed(self):
1691 """Test the connection is cleaned up after an invalid response"""
1692 conn = test_urllib.fakehttp(b"")
1693 handler = urllib.request.AbstractHTTPHandler()
1694 req = Request("http://dummy/")
1695 req.timeout = None
1696 with self.assertRaises(http.client.BadStatusLine):
1697 handler.do_open(conn, req)
1698 self.assertTrue(conn.fakesock.closed, "Connection not closed")
1699
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001700
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001701class MiscTests(unittest.TestCase):
1702
Senthil Kumarane9853da2013-03-19 12:07:43 -07001703 def opener_has_handler(self, opener, handler_class):
1704 self.assertTrue(any(h.__class__ == handler_class
1705 for h in opener.handlers))
1706
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001707 def test_build_opener(self):
Facundo Batista244afcf2015-04-22 18:35:54 -03001708 class MyHTTPHandler(urllib.request.HTTPHandler):
1709 pass
1710
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001711 class FooHandler(urllib.request.BaseHandler):
Facundo Batista244afcf2015-04-22 18:35:54 -03001712 def foo_open(self):
1713 pass
1714
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001715 class BarHandler(urllib.request.BaseHandler):
Facundo Batista244afcf2015-04-22 18:35:54 -03001716 def bar_open(self):
1717 pass
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001718
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001719 build_opener = urllib.request.build_opener
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001720
1721 o = build_opener(FooHandler, BarHandler)
1722 self.opener_has_handler(o, FooHandler)
1723 self.opener_has_handler(o, BarHandler)
1724
1725 # can take a mix of classes and instances
1726 o = build_opener(FooHandler, BarHandler())
1727 self.opener_has_handler(o, FooHandler)
1728 self.opener_has_handler(o, BarHandler)
1729
1730 # subclasses of default handlers override default handlers
1731 o = build_opener(MyHTTPHandler)
1732 self.opener_has_handler(o, MyHTTPHandler)
1733
1734 # a particular case of overriding: default handlers can be passed
1735 # in explicitly
1736 o = build_opener()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001737 self.opener_has_handler(o, urllib.request.HTTPHandler)
1738 o = build_opener(urllib.request.HTTPHandler)
1739 self.opener_has_handler(o, urllib.request.HTTPHandler)
1740 o = build_opener(urllib.request.HTTPHandler())
1741 self.opener_has_handler(o, urllib.request.HTTPHandler)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001742
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001743 # Issue2670: multiple handlers sharing the same base class
Facundo Batista244afcf2015-04-22 18:35:54 -03001744 class MyOtherHTTPHandler(urllib.request.HTTPHandler):
1745 pass
1746
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001747 o = build_opener(MyHTTPHandler, MyOtherHTTPHandler)
1748 self.opener_has_handler(o, MyHTTPHandler)
1749 self.opener_has_handler(o, MyOtherHTTPHandler)
1750
Brett Cannon80512de2013-01-25 22:27:21 -05001751 @unittest.skipUnless(support.is_resource_enabled('network'),
1752 'test requires network access')
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001753 def test_issue16464(self):
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001754 with support.transient_internet("http://www.example.com/"):
1755 opener = urllib.request.build_opener()
1756 request = urllib.request.Request("http://www.example.com/")
1757 self.assertEqual(None, request.data)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001758
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001759 opener.open(request, "1".encode("us-ascii"))
1760 self.assertEqual(b"1", request.data)
1761 self.assertEqual("1", request.get_header("Content-length"))
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001762
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001763 opener.open(request, "1234567890".encode("us-ascii"))
1764 self.assertEqual(b"1234567890", request.data)
1765 self.assertEqual("10", request.get_header("Content-length"))
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001766
Senthil Kumarane9853da2013-03-19 12:07:43 -07001767 def test_HTTPError_interface(self):
1768 """
1769 Issue 13211 reveals that HTTPError didn't implement the URLError
1770 interface even though HTTPError is a subclass of URLError.
Senthil Kumarane9853da2013-03-19 12:07:43 -07001771 """
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001772 msg = 'something bad happened'
1773 url = code = fp = None
1774 hdrs = 'Content-Length: 42'
1775 err = urllib.error.HTTPError(url, code, msg, hdrs, fp)
1776 self.assertTrue(hasattr(err, 'reason'))
1777 self.assertEqual(err.reason, 'something bad happened')
1778 self.assertTrue(hasattr(err, 'headers'))
1779 self.assertEqual(err.headers, 'Content-Length: 42')
1780 expected_errmsg = 'HTTP Error %s: %s' % (err.code, err.msg)
1781 self.assertEqual(str(err), expected_errmsg)
Facundo Batista244afcf2015-04-22 18:35:54 -03001782 expected_errmsg = '<HTTPError %s: %r>' % (err.code, err.msg)
1783 self.assertEqual(repr(err), expected_errmsg)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001784
Senthil Kumarand8e24f12014-04-14 16:32:20 -04001785 def test_parse_proxy(self):
1786 parse_proxy_test_cases = [
1787 ('proxy.example.com',
1788 (None, None, None, 'proxy.example.com')),
1789 ('proxy.example.com:3128',
1790 (None, None, None, 'proxy.example.com:3128')),
1791 ('proxy.example.com', (None, None, None, 'proxy.example.com')),
1792 ('proxy.example.com:3128',
1793 (None, None, None, 'proxy.example.com:3128')),
1794 # The authority component may optionally include userinfo
1795 # (assumed to be # username:password):
1796 ('joe:password@proxy.example.com',
1797 (None, 'joe', 'password', 'proxy.example.com')),
1798 ('joe:password@proxy.example.com:3128',
1799 (None, 'joe', 'password', 'proxy.example.com:3128')),
1800 #Examples with URLS
1801 ('http://proxy.example.com/',
1802 ('http', None, None, 'proxy.example.com')),
1803 ('http://proxy.example.com:3128/',
1804 ('http', None, None, 'proxy.example.com:3128')),
1805 ('http://joe:password@proxy.example.com/',
1806 ('http', 'joe', 'password', 'proxy.example.com')),
1807 ('http://joe:password@proxy.example.com:3128',
1808 ('http', 'joe', 'password', 'proxy.example.com:3128')),
1809 # Everything after the authority is ignored
1810 ('ftp://joe:password@proxy.example.com/rubbish:3128',
1811 ('ftp', 'joe', 'password', 'proxy.example.com')),
1812 # Test for no trailing '/' case
1813 ('http://joe:password@proxy.example.com',
1814 ('http', 'joe', 'password', 'proxy.example.com'))
1815 ]
1816
1817 for tc, expected in parse_proxy_test_cases:
1818 self.assertEqual(_parse_proxy(tc), expected)
1819
1820 self.assertRaises(ValueError, _parse_proxy, 'file:/ftp.example.com'),
1821
Berker Peksage88dd1c2016-03-06 16:16:40 +02001822 def test_unsupported_algorithm(self):
1823 handler = AbstractDigestAuthHandler()
1824 with self.assertRaises(ValueError) as exc:
1825 handler.get_algorithm_impls('invalid')
1826 self.assertEqual(
1827 str(exc.exception),
1828 "Unsupported digest authentication algorithm 'invalid'"
1829 )
1830
Facundo Batista244afcf2015-04-22 18:35:54 -03001831
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001832class RequestTests(unittest.TestCase):
Jason R. Coombs4a652422013-09-08 13:03:40 -04001833 class PutRequest(Request):
Facundo Batista244afcf2015-04-22 18:35:54 -03001834 method = 'PUT'
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001835
1836 def setUp(self):
1837 self.get = Request("http://www.python.org/~jeremy/")
1838 self.post = Request("http://www.python.org/~jeremy/",
1839 "data",
1840 headers={"X-Test": "test"})
Jason R. Coombs4a652422013-09-08 13:03:40 -04001841 self.head = Request("http://www.python.org/~jeremy/", method='HEAD')
1842 self.put = self.PutRequest("http://www.python.org/~jeremy/")
1843 self.force_post = self.PutRequest("http://www.python.org/~jeremy/",
1844 method="POST")
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001845
1846 def test_method(self):
1847 self.assertEqual("POST", self.post.get_method())
1848 self.assertEqual("GET", self.get.get_method())
Senthil Kumaran0b5463f2013-09-09 23:13:06 -07001849 self.assertEqual("HEAD", self.head.get_method())
Jason R. Coombs4a652422013-09-08 13:03:40 -04001850 self.assertEqual("PUT", self.put.get_method())
1851 self.assertEqual("POST", self.force_post.get_method())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001852
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001853 def test_data(self):
1854 self.assertFalse(self.get.data)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001855 self.assertEqual("GET", self.get.get_method())
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001856 self.get.data = "spam"
1857 self.assertTrue(self.get.data)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001858 self.assertEqual("POST", self.get.get_method())
1859
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001860 # issue 16464
1861 # if we change data we need to remove content-length header
1862 # (cause it's most probably calculated for previous value)
1863 def test_setting_data_should_remove_content_length(self):
R David Murray9cc7d452013-03-20 00:10:51 -04001864 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001865 self.get.add_unredirected_header("Content-length", 42)
1866 self.assertEqual(42, self.get.unredirected_hdrs["Content-length"])
1867 self.get.data = "spam"
R David Murray9cc7d452013-03-20 00:10:51 -04001868 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
1869
1870 # issue 17485 same for deleting data.
1871 def test_deleting_data_should_remove_content_length(self):
1872 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
1873 self.get.data = 'foo'
1874 self.get.add_unredirected_header("Content-length", 3)
1875 self.assertEqual(3, self.get.unredirected_hdrs["Content-length"])
1876 del self.get.data
1877 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001878
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001879 def test_get_full_url(self):
1880 self.assertEqual("http://www.python.org/~jeremy/",
1881 self.get.get_full_url())
1882
1883 def test_selector(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001884 self.assertEqual("/~jeremy/", self.get.selector)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001885 req = Request("http://www.python.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001886 self.assertEqual("/", req.selector)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001887
1888 def test_get_type(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001889 self.assertEqual("http", self.get.type)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001890
1891 def test_get_host(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001892 self.assertEqual("www.python.org", self.get.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001893
1894 def test_get_host_unquote(self):
1895 req = Request("http://www.%70ython.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001896 self.assertEqual("www.python.org", req.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001897
1898 def test_proxy(self):
Florent Xicluna419e3842010-08-08 16:16:07 +00001899 self.assertFalse(self.get.has_proxy())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001900 self.get.set_proxy("www.perl.org", "http")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001901 self.assertTrue(self.get.has_proxy())
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001902 self.assertEqual("www.python.org", self.get.origin_req_host)
1903 self.assertEqual("www.perl.org", self.get.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001904
Senthil Kumarand95cc752010-08-08 11:27:53 +00001905 def test_wrapped_url(self):
1906 req = Request("<URL:http://www.python.org>")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001907 self.assertEqual("www.python.org", req.host)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001908
Senthil Kumaran26430412011-04-13 07:01:19 +08001909 def test_url_fragment(self):
Senthil Kumarand95cc752010-08-08 11:27:53 +00001910 req = Request("http://www.python.org/?qs=query#fragment=true")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001911 self.assertEqual("/?qs=query", req.selector)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001912 req = Request("http://www.python.org/#fun=true")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001913 self.assertEqual("/", req.selector)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001914
Senthil Kumaran26430412011-04-13 07:01:19 +08001915 # Issue 11703: geturl() omits fragment in the original URL.
1916 url = 'http://docs.python.org/library/urllib2.html#OK'
1917 req = Request(url)
1918 self.assertEqual(req.get_full_url(), url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001919
Senthil Kumaran83070752013-05-24 09:14:12 -07001920 def test_url_fullurl_get_full_url(self):
1921 urls = ['http://docs.python.org',
1922 'http://docs.python.org/library/urllib2.html#OK',
Facundo Batista244afcf2015-04-22 18:35:54 -03001923 'http://www.python.org/?qs=query#fragment=true']
Senthil Kumaran83070752013-05-24 09:14:12 -07001924 for url in urls:
1925 req = Request(url)
1926 self.assertEqual(req.get_full_url(), req.full_url)
1927
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001928
1929if __name__ == "__main__":
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001930 unittest.main()