blob: 36d7e872187e82f744fc2b05fa307d1d53a37957 [file] [log] [blame]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002from test import support
Serhiy Storchakaf54c3502014-09-06 21:41:39 +03003from test import test_urllib
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00004
Christian Heimes05e8be12008-02-23 18:30:17 +00005import os
Guido van Rossum34d19282007-08-09 01:03:29 +00006import io
Georg Brandlf78e02b2008-06-10 17:40:04 +00007import socket
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00008import array
Senthil Kumaran4de00a22011-05-11 21:17:57 +08009import sys
Jeremy Hyltone3e61042001-05-09 15:50:25 +000010
Jeremy Hylton1afc1692008-06-18 20:49:58 +000011import urllib.request
Ronald Oussorene72e1612011-03-14 18:15:25 -040012# The proxy bypass method imported below has logic specific to the OSX
13# proxy config data structure but is testable on all platforms.
Senthil Kumarand8e24f12014-04-14 16:32:20 -040014from urllib.request import Request, OpenerDirector, _parse_proxy, _proxy_bypass_macosx_sysconf
Senthil Kumaran83070752013-05-24 09:14:12 -070015from urllib.parse import urlparse
guido@google.coma119df92011-03-29 11:41:02 -070016import urllib.error
Serhiy Storchakaf54c3502014-09-06 21:41:39 +030017import http.client
Jeremy Hyltone3e61042001-05-09 15:50:25 +000018
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000019# XXX
20# Request
21# CacheFTPHandler (hard to write)
Thomas Wouters477c8d52006-05-27 19:21:47 +000022# parse_keqv_list, parse_http_list, HTTPDigestAuthHandler
Jeremy Hyltone3e61042001-05-09 15:50:25 +000023
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000024class TrivialTests(unittest.TestCase):
Senthil Kumaran6c5bd402011-11-01 23:20:31 +080025
26 def test___all__(self):
27 # Verify which names are exposed
28 for module in 'request', 'response', 'parse', 'error', 'robotparser':
29 context = {}
30 exec('from urllib.%s import *' % module, context)
31 del context['__builtins__']
Florent Xicluna3dbb1f12011-11-04 22:15:37 +010032 if module == 'request' and os.name == 'nt':
33 u, p = context.pop('url2pathname'), context.pop('pathname2url')
34 self.assertEqual(u.__module__, 'nturl2path')
35 self.assertEqual(p.__module__, 'nturl2path')
Senthil Kumaran6c5bd402011-11-01 23:20:31 +080036 for k, v in context.items():
37 self.assertEqual(v.__module__, 'urllib.%s' % module,
38 "%r is exposed in 'urllib.%s' but defined in %r" %
39 (k, module, v.__module__))
40
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000041 def test_trivial(self):
42 # A couple trivial tests
Guido van Rossume2ae77b2001-10-24 20:42:55 +000043
Jeremy Hylton1afc1692008-06-18 20:49:58 +000044 self.assertRaises(ValueError, urllib.request.urlopen, 'bogus url')
Tim Peters861adac2001-07-16 20:49:49 +000045
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000046 # XXX Name hacking to get this to work on Windows.
Serhiy Storchaka5106d042015-01-26 10:26:14 +020047 fname = os.path.abspath(urllib.request.__file__).replace(os.sep, '/')
Senthil Kumarand587e302010-01-10 17:45:52 +000048
Senthil Kumarand587e302010-01-10 17:45:52 +000049 if os.name == 'nt':
50 file_url = "file:///%s" % fname
51 else:
52 file_url = "file://%s" % fname
53
Jeremy Hylton1afc1692008-06-18 20:49:58 +000054 f = urllib.request.urlopen(file_url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000055
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -070056 f.read()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000057 f.close()
Tim Petersf5f32b42005-07-17 23:16:17 +000058
Georg Brandle1b13d22005-08-24 22:20:32 +000059 def test_parse_http_list(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +000060 tests = [
61 ('a,b,c', ['a', 'b', 'c']),
62 ('path"o,l"og"i"cal, example', ['path"o,l"og"i"cal', 'example']),
63 ('a, b, "c", "d", "e,f", g, h',
64 ['a', 'b', '"c"', '"d"', '"e,f"', 'g', 'h']),
65 ('a="b\\"c", d="e\\,f", g="h\\\\i"',
66 ['a="b"c"', 'd="e,f"', 'g="h\\i"'])]
Georg Brandle1b13d22005-08-24 22:20:32 +000067 for string, list in tests:
Florent Xicluna419e3842010-08-08 16:16:07 +000068 self.assertEqual(urllib.request.parse_http_list(string), list)
Georg Brandle1b13d22005-08-24 22:20:32 +000069
Senthil Kumaran843fae92013-03-19 13:43:42 -070070 def test_URLError_reasonstr(self):
71 err = urllib.error.URLError('reason')
72 self.assertIn(err.reason, str(err))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000073
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -070074class RequestHdrsTests(unittest.TestCase):
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000075
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -070076 def test_request_headers_dict(self):
77 """
78 The Request.headers dictionary is not a documented interface. It
79 should stay that way, because the complete set of headers are only
80 accessible through the .get_header(), .has_header(), .header_items()
81 interface. However, .headers pre-dates those methods, and so real code
82 will be using the dictionary.
83
84 The introduction in 2.4 of those methods was a mistake for the same
85 reason: code that previously saw all (urllib2 user)-provided headers in
86 .headers now sees only a subset.
87
88 """
89 url = "http://example.com"
90 self.assertEqual(Request(url,
91 headers={"Spam-eggs": "blah"}
92 ).headers["Spam-eggs"], "blah")
93 self.assertEqual(Request(url,
94 headers={"spam-EggS": "blah"}
95 ).headers["Spam-eggs"], "blah")
96
97 def test_request_headers_methods(self):
98 """
99 Note the case normalization of header names here, to
100 .capitalize()-case. This should be preserved for
101 backwards-compatibility. (In the HTTP case, normalization to
102 .title()-case is done by urllib2 before sending headers to
103 http.client).
104
105 Note that e.g. r.has_header("spam-EggS") is currently False, and
106 r.get_header("spam-EggS") returns None, but that could be changed in
107 future.
108
109 Method r.remove_header should remove items both from r.headers and
110 r.unredirected_hdrs dictionaries
111 """
112 url = "http://example.com"
113 req = Request(url, headers={"Spam-eggs": "blah"})
114 self.assertTrue(req.has_header("Spam-eggs"))
115 self.assertEqual(req.header_items(), [('Spam-eggs', 'blah')])
116
117 req.add_header("Foo-Bar", "baz")
118 self.assertEqual(sorted(req.header_items()),
119 [('Foo-bar', 'baz'), ('Spam-eggs', 'blah')])
120 self.assertFalse(req.has_header("Not-there"))
121 self.assertIsNone(req.get_header("Not-there"))
122 self.assertEqual(req.get_header("Not-there", "default"), "default")
123
124 req.remove_header("Spam-eggs")
125 self.assertFalse(req.has_header("Spam-eggs"))
126
127 req.add_unredirected_header("Unredirected-spam", "Eggs")
128 self.assertTrue(req.has_header("Unredirected-spam"))
129
130 req.remove_header("Unredirected-spam")
131 self.assertFalse(req.has_header("Unredirected-spam"))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000132
133
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700134 def test_password_manager(self):
135 mgr = urllib.request.HTTPPasswordMgr()
136 add = mgr.add_password
137 find_user_pass = mgr.find_user_password
138 add("Some Realm", "http://example.com/", "joe", "password")
139 add("Some Realm", "http://example.com/ni", "ni", "ni")
140 add("c", "http://example.com/foo", "foo", "ni")
141 add("c", "http://example.com/bar", "bar", "nini")
142 add("b", "http://example.com/", "first", "blah")
143 add("b", "http://example.com/", "second", "spam")
144 add("a", "http://example.com", "1", "a")
145 add("Some Realm", "http://c.example.com:3128", "3", "c")
146 add("Some Realm", "d.example.com", "4", "d")
147 add("Some Realm", "e.example.com:3128", "5", "e")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000148
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700149 self.assertEqual(find_user_pass("Some Realm", "example.com"),
150 ('joe', 'password'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000151
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700152 #self.assertEqual(find_user_pass("Some Realm", "http://example.com/ni"),
153 # ('ni', 'ni'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000154
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700155 self.assertEqual(find_user_pass("Some Realm", "http://example.com"),
156 ('joe', 'password'))
157 self.assertEqual(find_user_pass("Some Realm", "http://example.com/"),
158 ('joe', 'password'))
159 self.assertEqual(
160 find_user_pass("Some Realm", "http://example.com/spam"),
161 ('joe', 'password'))
162 self.assertEqual(
163 find_user_pass("Some Realm", "http://example.com/spam/spam"),
164 ('joe', 'password'))
165 self.assertEqual(find_user_pass("c", "http://example.com/foo"),
166 ('foo', 'ni'))
167 self.assertEqual(find_user_pass("c", "http://example.com/bar"),
168 ('bar', 'nini'))
169 self.assertEqual(find_user_pass("b", "http://example.com/"),
170 ('second', 'spam'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000171
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700172 # No special relationship between a.example.com and example.com:
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000173
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700174 self.assertEqual(find_user_pass("a", "http://example.com/"),
175 ('1', 'a'))
176 self.assertEqual(find_user_pass("a", "http://a.example.com/"),
177 (None, None))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000178
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700179 # Ports:
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000180
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700181 self.assertEqual(find_user_pass("Some Realm", "c.example.com"),
182 (None, None))
183 self.assertEqual(find_user_pass("Some Realm", "c.example.com:3128"),
184 ('3', 'c'))
185 self.assertEqual(
186 find_user_pass("Some Realm", "http://c.example.com:3128"),
187 ('3', 'c'))
188 self.assertEqual(find_user_pass("Some Realm", "d.example.com"),
189 ('4', 'd'))
190 self.assertEqual(find_user_pass("Some Realm", "e.example.com:3128"),
191 ('5', 'e'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000192
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700193 def test_password_manager_default_port(self):
194 """
195 The point to note here is that we can't guess the default port if
196 there's no scheme. This applies to both add_password and
197 find_user_password.
198 """
199 mgr = urllib.request.HTTPPasswordMgr()
200 add = mgr.add_password
201 find_user_pass = mgr.find_user_password
202 add("f", "http://g.example.com:80", "10", "j")
203 add("g", "http://h.example.com", "11", "k")
204 add("h", "i.example.com:80", "12", "l")
205 add("i", "j.example.com", "13", "m")
206 self.assertEqual(find_user_pass("f", "g.example.com:100"),
207 (None, None))
208 self.assertEqual(find_user_pass("f", "g.example.com:80"),
209 ('10', 'j'))
210 self.assertEqual(find_user_pass("f", "g.example.com"),
211 (None, None))
212 self.assertEqual(find_user_pass("f", "http://g.example.com:100"),
213 (None, None))
214 self.assertEqual(find_user_pass("f", "http://g.example.com:80"),
215 ('10', 'j'))
216 self.assertEqual(find_user_pass("f", "http://g.example.com"),
217 ('10', 'j'))
218 self.assertEqual(find_user_pass("g", "h.example.com"), ('11', 'k'))
219 self.assertEqual(find_user_pass("g", "h.example.com:80"), ('11', 'k'))
220 self.assertEqual(find_user_pass("g", "http://h.example.com:80"),
221 ('11', 'k'))
222 self.assertEqual(find_user_pass("h", "i.example.com"), (None, None))
223 self.assertEqual(find_user_pass("h", "i.example.com:80"), ('12', 'l'))
224 self.assertEqual(find_user_pass("h", "http://i.example.com:80"),
225 ('12', 'l'))
226 self.assertEqual(find_user_pass("i", "j.example.com"), ('13', 'm'))
227 self.assertEqual(find_user_pass("i", "j.example.com:80"),
228 (None, None))
229 self.assertEqual(find_user_pass("i", "http://j.example.com"),
230 ('13', 'm'))
231 self.assertEqual(find_user_pass("i", "http://j.example.com:80"),
232 (None, None))
Andrew Svetlovbff98fe2012-11-27 23:06:19 +0200233
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000234
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000235class MockOpener:
236 addheaders = []
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000237 def open(self, req, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
238 self.req, self.data, self.timeout = req, data, timeout
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000239 def error(self, proto, *args):
240 self.proto, self.args = proto, args
241
242class MockFile:
243 def read(self, count=None): pass
244 def readline(self, count=None): pass
245 def close(self): pass
246
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000247class MockHeaders(dict):
248 def getheaders(self, name):
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000249 return list(self.values())
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000250
Guido van Rossum34d19282007-08-09 01:03:29 +0000251class MockResponse(io.StringIO):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000252 def __init__(self, code, msg, headers, data, url=None):
Guido van Rossum34d19282007-08-09 01:03:29 +0000253 io.StringIO.__init__(self, data)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000254 self.code, self.msg, self.headers, self.url = code, msg, headers, url
255 def info(self):
256 return self.headers
257 def geturl(self):
258 return self.url
259
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000260class MockCookieJar:
261 def add_cookie_header(self, request):
262 self.ach_req = request
263 def extract_cookies(self, response, request):
264 self.ec_req, self.ec_r = request, response
265
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000266class FakeMethod:
267 def __init__(self, meth_name, action, handle):
268 self.meth_name = meth_name
269 self.handle = handle
270 self.action = action
271 def __call__(self, *args):
272 return self.handle(self.meth_name, self.action, *args)
273
Senthil Kumaran47fff872009-12-20 07:10:31 +0000274class MockHTTPResponse(io.IOBase):
275 def __init__(self, fp, msg, status, reason):
276 self.fp = fp
277 self.msg = msg
278 self.status = status
279 self.reason = reason
280 self.code = 200
281
282 def read(self):
283 return ''
284
285 def info(self):
286 return {}
287
288 def geturl(self):
289 return self.url
290
291
292class MockHTTPClass:
293 def __init__(self):
294 self.level = 0
295 self.req_headers = []
296 self.data = None
297 self.raise_on_endheaders = False
Nadeem Vawdabd26b542012-10-21 17:37:43 +0200298 self.sock = None
Senthil Kumaran47fff872009-12-20 07:10:31 +0000299 self._tunnel_headers = {}
300
301 def __call__(self, host, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
302 self.host = host
303 self.timeout = timeout
304 return self
305
306 def set_debuglevel(self, level):
307 self.level = level
308
309 def set_tunnel(self, host, port=None, headers=None):
310 self._tunnel_host = host
311 self._tunnel_port = port
312 if headers:
313 self._tunnel_headers = headers
314 else:
315 self._tunnel_headers.clear()
316
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000317 def request(self, method, url, body=None, headers=None):
Senthil Kumaran47fff872009-12-20 07:10:31 +0000318 self.method = method
319 self.selector = url
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000320 if headers is not None:
321 self.req_headers += headers.items()
Senthil Kumaran47fff872009-12-20 07:10:31 +0000322 self.req_headers.sort()
323 if body:
324 self.data = body
325 if self.raise_on_endheaders:
Andrew Svetlov0832af62012-12-18 23:10:48 +0200326 raise OSError()
Senthil Kumaran47fff872009-12-20 07:10:31 +0000327 def getresponse(self):
328 return MockHTTPResponse(MockFile(), {}, 200, "OK")
329
Victor Stinnera4c45d72011-06-17 14:01:18 +0200330 def close(self):
331 pass
332
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000333class MockHandler:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000334 # useful for testing handler machinery
335 # see add_ordered_mock_handlers() docstring
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000336 handler_order = 500
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000337 def __init__(self, methods):
338 self._define_methods(methods)
339 def _define_methods(self, methods):
340 for spec in methods:
341 if len(spec) == 2: name, action = spec
342 else: name, action = spec, None
343 meth = FakeMethod(name, action, self.handle)
344 setattr(self.__class__, name, meth)
345 def handle(self, fn_name, action, *args, **kwds):
346 self.parent.calls.append((self, fn_name, args, kwds))
347 if action is None:
348 return None
349 elif action == "return self":
350 return self
351 elif action == "return response":
352 res = MockResponse(200, "OK", {}, "")
353 return res
354 elif action == "return request":
355 return Request("http://blah/")
356 elif action.startswith("error"):
357 code = action[action.rfind(" ")+1:]
358 try:
359 code = int(code)
360 except ValueError:
361 pass
362 res = MockResponse(200, "OK", {}, "")
363 return self.parent.error("http", args[0], res, code, "", {})
364 elif action == "raise":
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000365 raise urllib.error.URLError("blah")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000366 assert False
367 def close(self): pass
368 def add_parent(self, parent):
369 self.parent = parent
370 self.parent.calls = []
371 def __lt__(self, other):
372 if not hasattr(other, "handler_order"):
373 # No handler_order, leave in original order. Yuck.
374 return True
375 return self.handler_order < other.handler_order
376
377def add_ordered_mock_handlers(opener, meth_spec):
378 """Create MockHandlers and add them to an OpenerDirector.
379
380 meth_spec: list of lists of tuples and strings defining methods to define
381 on handlers. eg:
382
383 [["http_error", "ftp_open"], ["http_open"]]
384
385 defines methods .http_error() and .ftp_open() on one handler, and
386 .http_open() on another. These methods just record their arguments and
387 return None. Using a tuple instead of a string causes the method to
388 perform some action (see MockHandler.handle()), eg:
389
390 [["http_error"], [("http_open", "return request")]]
391
392 defines .http_error() on one handler (which simply returns None), and
393 .http_open() on another handler, which returns a Request object.
394
395 """
396 handlers = []
397 count = 0
398 for meths in meth_spec:
399 class MockHandlerSubclass(MockHandler): pass
400 h = MockHandlerSubclass(meths)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000401 h.handler_order += count
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000402 h.add_parent(opener)
403 count = count + 1
404 handlers.append(h)
405 opener.add_handler(h)
406 return handlers
407
Thomas Wouters477c8d52006-05-27 19:21:47 +0000408def build_test_opener(*handler_instances):
409 opener = OpenerDirector()
410 for h in handler_instances:
411 opener.add_handler(h)
412 return opener
413
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000414class MockHTTPHandler(urllib.request.BaseHandler):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000415 # useful for testing redirections and auth
416 # sends supplied headers and code as first response
417 # sends 200 OK as second response
418 def __init__(self, code, headers):
419 self.code = code
420 self.headers = headers
421 self.reset()
422 def reset(self):
423 self._count = 0
424 self.requests = []
425 def http_open(self, req):
Barry Warsaw820c1202008-06-12 04:06:45 +0000426 import email, http.client, copy
Thomas Wouters477c8d52006-05-27 19:21:47 +0000427 self.requests.append(copy.deepcopy(req))
428 if self._count == 0:
429 self._count = self._count + 1
Georg Brandl24420152008-05-26 16:32:26 +0000430 name = http.client.responses[self.code]
Barry Warsaw820c1202008-06-12 04:06:45 +0000431 msg = email.message_from_string(self.headers)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000432 return self.parent.error(
433 "http", req, MockFile(), self.code, name, msg)
434 else:
435 self.req = req
Barry Warsaw820c1202008-06-12 04:06:45 +0000436 msg = email.message_from_string("\r\n\r\n")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000437 return MockResponse(200, "OK", msg, "", req.get_full_url())
438
Senthil Kumaran47fff872009-12-20 07:10:31 +0000439class MockHTTPSHandler(urllib.request.AbstractHTTPHandler):
440 # Useful for testing the Proxy-Authorization request by verifying the
441 # properties of httpcon
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000442
443 def __init__(self):
444 urllib.request.AbstractHTTPHandler.__init__(self)
445 self.httpconn = MockHTTPClass()
446
Senthil Kumaran47fff872009-12-20 07:10:31 +0000447 def https_open(self, req):
448 return self.do_open(self.httpconn, req)
449
Thomas Wouters477c8d52006-05-27 19:21:47 +0000450class MockPasswordManager:
451 def add_password(self, realm, uri, user, password):
452 self.realm = realm
453 self.url = uri
454 self.user = user
455 self.password = password
456 def find_user_password(self, realm, authuri):
457 self.target_realm = realm
458 self.target_url = authuri
459 return self.user, self.password
460
461
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000462class OpenerDirectorTests(unittest.TestCase):
463
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000464 def test_add_non_handler(self):
465 class NonHandler(object):
466 pass
467 self.assertRaises(TypeError,
468 OpenerDirector().add_handler, NonHandler())
469
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000470 def test_badly_named_methods(self):
471 # test work-around for three methods that accidentally follow the
472 # naming conventions for handler methods
473 # (*_open() / *_request() / *_response())
474
475 # These used to call the accidentally-named methods, causing a
476 # TypeError in real code; here, returning self from these mock
477 # methods would either cause no exception, or AttributeError.
478
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000479 from urllib.error import URLError
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000480
481 o = OpenerDirector()
482 meth_spec = [
483 [("do_open", "return self"), ("proxy_open", "return self")],
484 [("redirect_request", "return self")],
485 ]
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700486 add_ordered_mock_handlers(o, meth_spec)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000487 o.add_handler(urllib.request.UnknownHandler())
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000488 for scheme in "do", "proxy", "redirect":
489 self.assertRaises(URLError, o.open, scheme+"://example.com/")
490
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000491 def test_handled(self):
492 # handler returning non-None means no more handlers will be called
493 o = OpenerDirector()
494 meth_spec = [
495 ["http_open", "ftp_open", "http_error_302"],
496 ["ftp_open"],
497 [("http_open", "return self")],
498 [("http_open", "return self")],
499 ]
500 handlers = add_ordered_mock_handlers(o, meth_spec)
501
502 req = Request("http://example.com/")
503 r = o.open(req)
504 # Second .http_open() gets called, third doesn't, since second returned
505 # non-None. Handlers without .http_open() never get any methods called
506 # on them.
507 # In fact, second mock handler defining .http_open() returns self
508 # (instead of response), which becomes the OpenerDirector's return
509 # value.
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000510 self.assertEqual(r, handlers[2])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000511 calls = [(handlers[0], "http_open"), (handlers[2], "http_open")]
512 for expected, got in zip(calls, o.calls):
513 handler, name, args, kwds = got
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000514 self.assertEqual((handler, name), expected)
515 self.assertEqual(args, (req,))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000516
517 def test_handler_order(self):
518 o = OpenerDirector()
519 handlers = []
520 for meths, handler_order in [
521 ([("http_open", "return self")], 500),
522 (["http_open"], 0),
523 ]:
524 class MockHandlerSubclass(MockHandler): pass
525 h = MockHandlerSubclass(meths)
526 h.handler_order = handler_order
527 handlers.append(h)
528 o.add_handler(h)
529
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700530 o.open("http://example.com/")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000531 # handlers called in reverse order, thanks to their sort order
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000532 self.assertEqual(o.calls[0][0], handlers[1])
533 self.assertEqual(o.calls[1][0], handlers[0])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000534
535 def test_raise(self):
536 # raising URLError stops processing of request
537 o = OpenerDirector()
538 meth_spec = [
539 [("http_open", "raise")],
540 [("http_open", "return self")],
541 ]
542 handlers = add_ordered_mock_handlers(o, meth_spec)
543
544 req = Request("http://example.com/")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000545 self.assertRaises(urllib.error.URLError, o.open, req)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000546 self.assertEqual(o.calls, [(handlers[0], "http_open", (req,), {})])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000547
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000548 def test_http_error(self):
549 # XXX http_error_default
550 # http errors are a special case
551 o = OpenerDirector()
552 meth_spec = [
553 [("http_open", "error 302")],
554 [("http_error_400", "raise"), "http_open"],
555 [("http_error_302", "return response"), "http_error_303",
556 "http_error"],
557 [("http_error_302")],
558 ]
559 handlers = add_ordered_mock_handlers(o, meth_spec)
560
561 class Unknown:
562 def __eq__(self, other): return True
563
564 req = Request("http://example.com/")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700565 o.open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000566 assert len(o.calls) == 2
567 calls = [(handlers[0], "http_open", (req,)),
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000568 (handlers[2], "http_error_302",
569 (req, Unknown(), 302, "", {}))]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000570 for expected, got in zip(calls, o.calls):
571 handler, method_name, args = expected
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000572 self.assertEqual((handler, method_name), got[:2])
573 self.assertEqual(args, got[2])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000574
Senthil Kumaran38b968b92012-03-14 13:43:53 -0700575
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000576 def test_processors(self):
577 # *_request / *_response methods get called appropriately
578 o = OpenerDirector()
579 meth_spec = [
580 [("http_request", "return request"),
581 ("http_response", "return response")],
582 [("http_request", "return request"),
583 ("http_response", "return response")],
584 ]
585 handlers = add_ordered_mock_handlers(o, meth_spec)
586
587 req = Request("http://example.com/")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700588 o.open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000589 # processor methods are called on *all* handlers that define them,
590 # not just the first handler that handles the request
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000591 calls = [
592 (handlers[0], "http_request"), (handlers[1], "http_request"),
593 (handlers[0], "http_response"), (handlers[1], "http_response")]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000594
595 for i, (handler, name, args, kwds) in enumerate(o.calls):
596 if i < 2:
597 # *_request
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000598 self.assertEqual((handler, name), calls[i])
599 self.assertEqual(len(args), 1)
Ezio Melottie9615932010-01-24 19:26:24 +0000600 self.assertIsInstance(args[0], Request)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000601 else:
602 # *_response
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000603 self.assertEqual((handler, name), calls[i])
604 self.assertEqual(len(args), 2)
Ezio Melottie9615932010-01-24 19:26:24 +0000605 self.assertIsInstance(args[0], Request)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000606 # response from opener.open is None, because there's no
607 # handler that defines http_open to handle it
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200608 if args[1] is not None:
609 self.assertIsInstance(args[1], MockResponse)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000610
Tim Peters58eb11c2004-01-18 20:29:55 +0000611def sanepathname2url(path):
Victor Stinner6c6f8512010-08-07 10:09:35 +0000612 try:
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000613 path.encode("utf-8")
Victor Stinner6c6f8512010-08-07 10:09:35 +0000614 except UnicodeEncodeError:
615 raise unittest.SkipTest("path is not encodable to utf8")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000616 urlpath = urllib.request.pathname2url(path)
Tim Peters58eb11c2004-01-18 20:29:55 +0000617 if os.name == "nt" and urlpath.startswith("///"):
618 urlpath = urlpath[2:]
619 # XXX don't ask me about the mac...
620 return urlpath
621
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000622class HandlerTests(unittest.TestCase):
623
624 def test_ftp(self):
625 class MockFTPWrapper:
626 def __init__(self, data): self.data = data
627 def retrfile(self, filename, filetype):
628 self.filename, self.filetype = filename, filetype
Guido van Rossum34d19282007-08-09 01:03:29 +0000629 return io.StringIO(self.data), len(self.data)
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +0200630 def close(self): pass
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000631
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000632 class NullFTPHandler(urllib.request.FTPHandler):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000633 def __init__(self, data): self.data = data
Georg Brandlf78e02b2008-06-10 17:40:04 +0000634 def connect_ftp(self, user, passwd, host, port, dirs,
635 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000636 self.user, self.passwd = user, passwd
637 self.host, self.port = host, port
638 self.dirs = dirs
639 self.ftpwrapper = MockFTPWrapper(self.data)
640 return self.ftpwrapper
641
Georg Brandlf78e02b2008-06-10 17:40:04 +0000642 import ftplib
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000643 data = "rheum rhaponicum"
644 h = NullFTPHandler(data)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700645 h.parent = MockOpener()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000646
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000647 for url, host, port, user, passwd, type_, dirs, filename, mimetype in [
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000648 ("ftp://localhost/foo/bar/baz.html",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000649 "localhost", ftplib.FTP_PORT, "", "", "I",
650 ["foo", "bar"], "baz.html", "text/html"),
651 ("ftp://parrot@localhost/foo/bar/baz.html",
652 "localhost", ftplib.FTP_PORT, "parrot", "", "I",
653 ["foo", "bar"], "baz.html", "text/html"),
654 ("ftp://%25parrot@localhost/foo/bar/baz.html",
655 "localhost", ftplib.FTP_PORT, "%parrot", "", "I",
656 ["foo", "bar"], "baz.html", "text/html"),
657 ("ftp://%2542parrot@localhost/foo/bar/baz.html",
658 "localhost", ftplib.FTP_PORT, "%42parrot", "", "I",
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000659 ["foo", "bar"], "baz.html", "text/html"),
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000660 ("ftp://localhost:80/foo/bar/",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000661 "localhost", 80, "", "", "D",
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000662 ["foo", "bar"], "", None),
663 ("ftp://localhost/baz.gif;type=a",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000664 "localhost", ftplib.FTP_PORT, "", "", "A",
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000665 [], "baz.gif", None), # XXX really this should guess image/gif
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000666 ]:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000667 req = Request(url)
668 req.timeout = None
669 r = h.ftp_open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000670 # ftp authentication not yet implemented by FTPHandler
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000671 self.assertEqual(h.user, user)
672 self.assertEqual(h.passwd, passwd)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000673 self.assertEqual(h.host, socket.gethostbyname(host))
674 self.assertEqual(h.port, port)
675 self.assertEqual(h.dirs, dirs)
676 self.assertEqual(h.ftpwrapper.filename, filename)
677 self.assertEqual(h.ftpwrapper.filetype, type_)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000678 headers = r.info()
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000679 self.assertEqual(headers.get("Content-type"), mimetype)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000680 self.assertEqual(int(headers["Content-length"]), len(data))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000681
682 def test_file(self):
Senthil Kumaranbc07ac52014-07-22 00:15:20 -0700683 import email.utils
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000684 h = urllib.request.FileHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000685 o = h.parent = MockOpener()
686
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000687 TESTFN = support.TESTFN
Tim Peters58eb11c2004-01-18 20:29:55 +0000688 urlpath = sanepathname2url(os.path.abspath(TESTFN))
Guido van Rossum6a2ccd02007-07-16 20:51:57 +0000689 towrite = b"hello, world\n"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000690 urls = [
Tim Peters58eb11c2004-01-18 20:29:55 +0000691 "file://localhost%s" % urlpath,
692 "file://%s" % urlpath,
693 "file://%s%s" % (socket.gethostbyname('localhost'), urlpath),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000694 ]
695 try:
696 localaddr = socket.gethostbyname(socket.gethostname())
697 except socket.gaierror:
698 localaddr = ''
699 if localaddr:
700 urls.append("file://%s%s" % (localaddr, urlpath))
701
702 for url in urls:
Tim Peters58eb11c2004-01-18 20:29:55 +0000703 f = open(TESTFN, "wb")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000704 try:
705 try:
706 f.write(towrite)
707 finally:
708 f.close()
709
710 r = h.file_open(Request(url))
711 try:
712 data = r.read()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000713 headers = r.info()
Senthil Kumaran4fbed102010-05-08 03:29:09 +0000714 respurl = r.geturl()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000715 finally:
716 r.close()
Tim Peters58eb11c2004-01-18 20:29:55 +0000717 stats = os.stat(TESTFN)
Benjamin Petersona0c0a4a2008-06-12 22:15:50 +0000718 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000719 finally:
720 os.remove(TESTFN)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000721 self.assertEqual(data, towrite)
722 self.assertEqual(headers["Content-type"], "text/plain")
723 self.assertEqual(headers["Content-length"], "13")
Tim Peters58eb11c2004-01-18 20:29:55 +0000724 self.assertEqual(headers["Last-modified"], modified)
Senthil Kumaran4fbed102010-05-08 03:29:09 +0000725 self.assertEqual(respurl, url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000726
727 for url in [
Tim Peters58eb11c2004-01-18 20:29:55 +0000728 "file://localhost:80%s" % urlpath,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000729 "file:///file_does_not_exist.txt",
Senthil Kumaranbc07ac52014-07-22 00:15:20 -0700730 "file://not-a-local-host.com//dir/file.txt",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000731 "file://%s:80%s/%s" % (socket.gethostbyname('localhost'),
732 os.getcwd(), TESTFN),
733 "file://somerandomhost.ontheinternet.com%s/%s" %
734 (os.getcwd(), TESTFN),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000735 ]:
736 try:
Tim Peters58eb11c2004-01-18 20:29:55 +0000737 f = open(TESTFN, "wb")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000738 try:
739 f.write(towrite)
740 finally:
741 f.close()
742
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000743 self.assertRaises(urllib.error.URLError,
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000744 h.file_open, Request(url))
745 finally:
746 os.remove(TESTFN)
747
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000748 h = urllib.request.FileHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000749 o = h.parent = MockOpener()
750 # XXXX why does // mean ftp (and /// mean not ftp!), and where
751 # is file: scheme specified? I think this is really a bug, and
752 # what was intended was to distinguish between URLs like:
753 # file:/blah.txt (a file)
754 # file://localhost/blah.txt (a file)
755 # file:///blah.txt (a file)
756 # file://ftp.example.com/blah.txt (an ftp URL)
757 for url, ftp in [
Senthil Kumaran383c32d2010-10-14 11:57:35 +0000758 ("file://ftp.example.com//foo.txt", False),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000759 ("file://ftp.example.com///foo.txt", False),
760# XXXX bug: fails with OSError, should be URLError
761 ("file://ftp.example.com/foo.txt", False),
Senthil Kumaran383c32d2010-10-14 11:57:35 +0000762 ("file://somehost//foo/something.txt", False),
Senthil Kumaran2ef16322010-07-11 03:12:43 +0000763 ("file://localhost//foo/something.txt", False),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000764 ]:
765 req = Request(url)
766 try:
767 h.file_open(req)
768 # XXXX remove OSError when bug fixed
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000769 except (urllib.error.URLError, OSError):
Florent Xicluna419e3842010-08-08 16:16:07 +0000770 self.assertFalse(ftp)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000771 else:
Florent Xicluna419e3842010-08-08 16:16:07 +0000772 self.assertIs(o.req, req)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000773 self.assertEqual(req.type, "ftp")
Łukasz Langad7e81cc2011-01-09 18:18:53 +0000774 self.assertEqual(req.type == "ftp", ftp)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000775
776 def test_http(self):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000777
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000778 h = urllib.request.AbstractHTTPHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000779 o = h.parent = MockOpener()
780
781 url = "http://example.com/"
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000782 for method, data in [("GET", None), ("POST", b"blah")]:
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000783 req = Request(url, data, {"Foo": "bar"})
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000784 req.timeout = None
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000785 req.add_unredirected_header("Spam", "eggs")
786 http = MockHTTPClass()
787 r = h.do_open(http, req)
788
789 # result attributes
790 r.read; r.readline # wrapped MockFile methods
791 r.info; r.geturl # addinfourl methods
792 r.code, r.msg == 200, "OK" # added from MockHTTPClass.getreply()
793 hdrs = r.info()
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000794 hdrs.get; hdrs.__contains__ # r.info() gives dict from .getreply()
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000795 self.assertEqual(r.geturl(), url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000796
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000797 self.assertEqual(http.host, "example.com")
798 self.assertEqual(http.level, 0)
799 self.assertEqual(http.method, method)
800 self.assertEqual(http.selector, "/")
801 self.assertEqual(http.req_headers,
Jeremy Hyltonb3ee6f92004-02-24 19:40:35 +0000802 [("Connection", "close"),
803 ("Foo", "bar"), ("Spam", "eggs")])
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000804 self.assertEqual(http.data, data)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000805
Andrew Svetlov0832af62012-12-18 23:10:48 +0200806 # check OSError converted to URLError
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000807 http.raise_on_endheaders = True
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000808 self.assertRaises(urllib.error.URLError, h.do_open, http, req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000809
Senthil Kumaran29333122011-02-11 11:25:47 +0000810 # Check for TypeError on POST data which is str.
811 req = Request("http://example.com/","badpost")
812 self.assertRaises(TypeError, h.do_request_, req)
813
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000814 # check adding of standard headers
815 o.addheaders = [("Spam", "eggs")]
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000816 for data in b"", None: # POST, GET
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000817 req = Request("http://example.com/", data)
818 r = MockResponse(200, "OK", {}, "")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000819 newreq = h.do_request_(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000820 if data is None: # GET
Benjamin Peterson577473f2010-01-19 00:09:57 +0000821 self.assertNotIn("Content-length", req.unredirected_hdrs)
822 self.assertNotIn("Content-type", req.unredirected_hdrs)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000823 else: # POST
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000824 self.assertEqual(req.unredirected_hdrs["Content-length"], "0")
825 self.assertEqual(req.unredirected_hdrs["Content-type"],
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000826 "application/x-www-form-urlencoded")
827 # XXX the details of Host could be better tested
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000828 self.assertEqual(req.unredirected_hdrs["Host"], "example.com")
829 self.assertEqual(req.unredirected_hdrs["Spam"], "eggs")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000830
831 # don't clobber existing headers
832 req.add_unredirected_header("Content-length", "foo")
833 req.add_unredirected_header("Content-type", "bar")
834 req.add_unredirected_header("Host", "baz")
835 req.add_unredirected_header("Spam", "foo")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000836 newreq = h.do_request_(req)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000837 self.assertEqual(req.unredirected_hdrs["Content-length"], "foo")
838 self.assertEqual(req.unredirected_hdrs["Content-type"], "bar")
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000839 self.assertEqual(req.unredirected_hdrs["Host"], "baz")
840 self.assertEqual(req.unredirected_hdrs["Spam"], "foo")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000841
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000842 # Check iterable body support
843 def iterable_body():
844 yield b"one"
845 yield b"two"
846 yield b"three"
847
848 for headers in {}, {"Content-Length": 11}:
849 req = Request("http://example.com/", iterable_body(), headers)
850 if not headers:
851 # Having an iterable body without a Content-Length should
852 # raise an exception
853 self.assertRaises(ValueError, h.do_request_, req)
854 else:
855 newreq = h.do_request_(req)
856
Senthil Kumaran29333122011-02-11 11:25:47 +0000857 # A file object.
858 # Test only Content-Length attribute of request.
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000859
Senthil Kumaran29333122011-02-11 11:25:47 +0000860 file_obj = io.BytesIO()
861 file_obj.write(b"Something\nSomething\nSomething\n")
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000862
863 for headers in {}, {"Content-Length": 30}:
864 req = Request("http://example.com/", file_obj, headers)
865 if not headers:
866 # Having an iterable body without a Content-Length should
867 # raise an exception
868 self.assertRaises(ValueError, h.do_request_, req)
869 else:
870 newreq = h.do_request_(req)
871 self.assertEqual(int(newreq.get_header('Content-length')),30)
872
873 file_obj.close()
874
875 # array.array Iterable - Content Length is calculated
876
877 iterable_array = array.array("I",[1,2,3,4])
878
879 for headers in {}, {"Content-Length": 16}:
880 req = Request("http://example.com/", iterable_array, headers)
881 newreq = h.do_request_(req)
882 self.assertEqual(int(newreq.get_header('Content-length')),16)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000883
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000884 def test_http_doubleslash(self):
885 # Checks the presence of any unnecessary double slash in url does not
886 # break anything. Previously, a double slash directly after the host
Ezio Melottie130a522011-10-19 10:58:56 +0300887 # could cause incorrect parsing.
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000888 h = urllib.request.AbstractHTTPHandler()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700889 h.parent = MockOpener()
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000890
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000891 data = b""
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000892 ds_urls = [
893 "http://example.com/foo/bar/baz.html",
894 "http://example.com//foo/bar/baz.html",
895 "http://example.com/foo//bar/baz.html",
896 "http://example.com/foo/bar//baz.html"
897 ]
898
899 for ds_url in ds_urls:
900 ds_req = Request(ds_url, data)
901
902 # Check whether host is determined correctly if there is no proxy
903 np_ds_req = h.do_request_(ds_req)
904 self.assertEqual(np_ds_req.unredirected_hdrs["Host"],"example.com")
905
906 # Check whether host is determined correctly if there is a proxy
907 ds_req.set_proxy("someproxy:3128",None)
908 p_ds_req = h.do_request_(ds_req)
909 self.assertEqual(p_ds_req.unredirected_hdrs["Host"],"example.com")
910
Senthil Kumaran52380922013-04-25 05:45:48 -0700911 def test_full_url_setter(self):
912 # Checks to ensure that components are set correctly after setting the
913 # full_url of a Request object
914
915 urls = [
916 'http://example.com?foo=bar#baz',
917 'http://example.com?foo=bar&spam=eggs#bash',
918 'http://example.com',
919 ]
920
921 # testing a reusable request instance, but the url parameter is
922 # required, so just use a dummy one to instantiate
923 r = Request('http://example.com')
924 for url in urls:
925 r.full_url = url
Senthil Kumaran83070752013-05-24 09:14:12 -0700926 parsed = urlparse(url)
927
Senthil Kumaran52380922013-04-25 05:45:48 -0700928 self.assertEqual(r.get_full_url(), url)
Senthil Kumaran83070752013-05-24 09:14:12 -0700929 # full_url setter uses splittag to split into components.
930 # splittag sets the fragment as None while urlparse sets it to ''
931 self.assertEqual(r.fragment or '', parsed.fragment)
932 self.assertEqual(urlparse(r.get_full_url()).query, parsed.query)
Senthil Kumaran52380922013-04-25 05:45:48 -0700933
934 def test_full_url_deleter(self):
935 r = Request('http://www.example.com')
936 del r.full_url
937 self.assertIsNone(r.full_url)
938 self.assertIsNone(r.fragment)
939 self.assertEqual(r.selector, '')
940
Senthil Kumaranc2958622010-11-22 04:48:26 +0000941 def test_fixpath_in_weirdurls(self):
942 # Issue4493: urllib2 to supply '/' when to urls where path does not
943 # start with'/'
944
945 h = urllib.request.AbstractHTTPHandler()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700946 h.parent = MockOpener()
Senthil Kumaranc2958622010-11-22 04:48:26 +0000947
948 weird_url = 'http://www.python.org?getspam'
949 req = Request(weird_url)
950 newreq = h.do_request_(req)
951 self.assertEqual(newreq.host,'www.python.org')
952 self.assertEqual(newreq.selector,'/?getspam')
953
954 url_without_path = 'http://www.python.org'
955 req = Request(url_without_path)
956 newreq = h.do_request_(req)
957 self.assertEqual(newreq.host,'www.python.org')
958 self.assertEqual(newreq.selector,'')
959
Facundo Batista72dc1ea2008-08-16 14:44:32 +0000960
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000961 def test_errors(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000962 h = urllib.request.HTTPErrorProcessor()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000963 o = h.parent = MockOpener()
964
965 url = "http://example.com/"
966 req = Request(url)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000967 # all 2xx are passed through
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000968 r = MockResponse(200, "OK", {}, "", url)
969 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +0000970 self.assertIs(r, newr)
971 self.assertFalse(hasattr(o, "proto")) # o.error not called
Guido van Rossumd8faa362007-04-27 19:54:29 +0000972 r = MockResponse(202, "Accepted", {}, "", url)
973 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +0000974 self.assertIs(r, newr)
975 self.assertFalse(hasattr(o, "proto")) # o.error not called
Guido van Rossumd8faa362007-04-27 19:54:29 +0000976 r = MockResponse(206, "Partial content", {}, "", url)
977 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +0000978 self.assertIs(r, newr)
979 self.assertFalse(hasattr(o, "proto")) # o.error not called
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000980 # anything else calls o.error (and MockOpener returns None, here)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000981 r = MockResponse(502, "Bad gateway", {}, "", url)
Florent Xicluna419e3842010-08-08 16:16:07 +0000982 self.assertIsNone(h.http_response(req, r))
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000983 self.assertEqual(o.proto, "http") # o.error called
Guido van Rossumd8faa362007-04-27 19:54:29 +0000984 self.assertEqual(o.args, (req, r, 502, "Bad gateway", {}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000985
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000986 def test_cookies(self):
987 cj = MockCookieJar()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000988 h = urllib.request.HTTPCookieProcessor(cj)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700989 h.parent = MockOpener()
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000990
991 req = Request("http://example.com/")
992 r = MockResponse(200, "OK", {}, "")
993 newreq = h.http_request(req)
Florent Xicluna419e3842010-08-08 16:16:07 +0000994 self.assertIs(cj.ach_req, req)
995 self.assertIs(cj.ach_req, newreq)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -0700996 self.assertEqual(req.origin_req_host, "example.com")
997 self.assertFalse(req.unverifiable)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000998 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +0000999 self.assertIs(cj.ec_req, req)
1000 self.assertIs(cj.ec_r, r)
1001 self.assertIs(r, newr)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001002
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001003 def test_redirect(self):
1004 from_url = "http://example.com/a.html"
1005 to_url = "http://example.com/b.html"
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001006 h = urllib.request.HTTPRedirectHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001007 o = h.parent = MockOpener()
1008
1009 # ordinary redirect behaviour
1010 for code in 301, 302, 303, 307:
1011 for data in None, "blah\nblah\n":
1012 method = getattr(h, "http_error_%s" % code)
1013 req = Request(from_url, data)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001014 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001015 req.add_header("Nonsense", "viking=withhold")
Christian Heimes77c02eb2008-02-09 02:18:51 +00001016 if data is not None:
1017 req.add_header("Content-Length", str(len(data)))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001018 req.add_unredirected_header("Spam", "spam")
1019 try:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001020 method(req, MockFile(), code, "Blah",
1021 MockHeaders({"location": to_url}))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001022 except urllib.error.HTTPError:
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001023 # 307 in response to POST requires user OK
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001024 self.assertEqual(code, 307)
1025 self.assertIsNotNone(data)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001026 self.assertEqual(o.req.get_full_url(), to_url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001027 try:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001028 self.assertEqual(o.req.get_method(), "GET")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001029 except AttributeError:
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001030 self.assertFalse(o.req.data)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001031
1032 # now it's a GET, there should not be headers regarding content
1033 # (possibly dragged from before being a POST)
1034 headers = [x.lower() for x in o.req.headers]
Benjamin Peterson577473f2010-01-19 00:09:57 +00001035 self.assertNotIn("content-length", headers)
1036 self.assertNotIn("content-type", headers)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001037
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001038 self.assertEqual(o.req.headers["Nonsense"],
1039 "viking=withhold")
Benjamin Peterson577473f2010-01-19 00:09:57 +00001040 self.assertNotIn("Spam", o.req.headers)
1041 self.assertNotIn("Spam", o.req.unredirected_hdrs)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001042
1043 # loop detection
1044 req = Request(from_url)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001045 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001046 def redirect(h, req, url=to_url):
1047 h.http_error_302(req, MockFile(), 302, "Blah",
1048 MockHeaders({"location": url}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001049 # Note that the *original* request shares the same record of
1050 # redirections with the sub-requests caused by the redirections.
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001051
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001052 # detect infinite loop redirect of a URL to itself
1053 req = Request(from_url, origin_req_host="example.com")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001054 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001055 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001056 try:
1057 while 1:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001058 redirect(h, req, "http://example.com/")
1059 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001060 except urllib.error.HTTPError:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001061 # don't stop until max_repeats, because cookies may introduce state
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001062 self.assertEqual(count, urllib.request.HTTPRedirectHandler.max_repeats)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001063
1064 # detect endless non-repeating chain of redirects
1065 req = Request(from_url, origin_req_host="example.com")
1066 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001067 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001068 try:
1069 while 1:
1070 redirect(h, req, "http://example.com/%d" % count)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001071 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001072 except urllib.error.HTTPError:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001073 self.assertEqual(count,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001074 urllib.request.HTTPRedirectHandler.max_redirections)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001075
guido@google.coma119df92011-03-29 11:41:02 -07001076
1077 def test_invalid_redirect(self):
1078 from_url = "http://example.com/a.html"
1079 valid_schemes = ['http','https','ftp']
1080 invalid_schemes = ['file','imap','ldap']
1081 schemeless_url = "example.com/b.html"
1082 h = urllib.request.HTTPRedirectHandler()
1083 o = h.parent = MockOpener()
1084 req = Request(from_url)
1085 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1086
1087 for scheme in invalid_schemes:
1088 invalid_url = scheme + '://' + schemeless_url
1089 self.assertRaises(urllib.error.HTTPError, h.http_error_302,
1090 req, MockFile(), 302, "Security Loophole",
1091 MockHeaders({"location": invalid_url}))
1092
1093 for scheme in valid_schemes:
1094 valid_url = scheme + '://' + schemeless_url
1095 h.http_error_302(req, MockFile(), 302, "That's fine",
1096 MockHeaders({"location": valid_url}))
1097 self.assertEqual(o.req.get_full_url(), valid_url)
1098
Senthil Kumaran6497aa32012-01-04 13:46:59 +08001099 def test_relative_redirect(self):
1100 from_url = "http://example.com/a.html"
1101 relative_url = "/b.html"
1102 h = urllib.request.HTTPRedirectHandler()
1103 o = h.parent = MockOpener()
1104 req = Request(from_url)
1105 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1106
1107 valid_url = urllib.parse.urljoin(from_url,relative_url)
1108 h.http_error_302(req, MockFile(), 302, "That's fine",
1109 MockHeaders({"location": valid_url}))
1110 self.assertEqual(o.req.get_full_url(), valid_url)
1111
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001112 def test_cookie_redirect(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001113 # cookies shouldn't leak into redirected requests
Georg Brandl24420152008-05-26 16:32:26 +00001114 from http.cookiejar import CookieJar
1115 from test.test_http_cookiejar import interact_netscape
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001116
1117 cj = CookieJar()
1118 interact_netscape(cj, "http://www.example.com/", "spam=eggs")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001119 hh = MockHTTPHandler(302, "Location: http://www.cracker.com/\r\n\r\n")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001120 hdeh = urllib.request.HTTPDefaultErrorHandler()
1121 hrh = urllib.request.HTTPRedirectHandler()
1122 cp = urllib.request.HTTPCookieProcessor(cj)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001123 o = build_test_opener(hh, hdeh, hrh, cp)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001124 o.open("http://www.example.com/")
Florent Xicluna419e3842010-08-08 16:16:07 +00001125 self.assertFalse(hh.req.has_header("Cookie"))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001126
Senthil Kumaran26430412011-04-13 07:01:19 +08001127 def test_redirect_fragment(self):
1128 redirected_url = 'http://www.example.com/index.html#OK\r\n\r\n'
1129 hh = MockHTTPHandler(302, 'Location: ' + redirected_url)
1130 hdeh = urllib.request.HTTPDefaultErrorHandler()
1131 hrh = urllib.request.HTTPRedirectHandler()
1132 o = build_test_opener(hh, hdeh, hrh)
1133 fp = o.open('http://www.example.com')
1134 self.assertEqual(fp.geturl(), redirected_url.strip())
1135
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001136 def test_proxy(self):
1137 o = OpenerDirector()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001138 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001139 o.add_handler(ph)
1140 meth_spec = [
1141 [("http_open", "return response")]
1142 ]
1143 handlers = add_ordered_mock_handlers(o, meth_spec)
1144
1145 req = Request("http://acme.example.com/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001146 self.assertEqual(req.host, "acme.example.com")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001147 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001148 self.assertEqual(req.host, "proxy.example.com:3128")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001149
1150 self.assertEqual([(handlers[0], "http_open")],
1151 [tup[0:2] for tup in o.calls])
1152
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001153 def test_proxy_no_proxy(self):
1154 os.environ['no_proxy'] = 'python.org'
1155 o = OpenerDirector()
1156 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1157 o.add_handler(ph)
1158 req = Request("http://www.perl.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001159 self.assertEqual(req.host, "www.perl.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001160 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001161 self.assertEqual(req.host, "proxy.example.com")
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001162 req = Request("http://www.python.org")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001163 self.assertEqual(req.host, "www.python.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001164 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001165 self.assertEqual(req.host, "www.python.org")
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001166 del os.environ['no_proxy']
1167
Ronald Oussorene72e1612011-03-14 18:15:25 -04001168 def test_proxy_no_proxy_all(self):
1169 os.environ['no_proxy'] = '*'
1170 o = OpenerDirector()
1171 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1172 o.add_handler(ph)
1173 req = Request("http://www.python.org")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001174 self.assertEqual(req.host, "www.python.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001175 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001176 self.assertEqual(req.host, "www.python.org")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001177 del os.environ['no_proxy']
1178
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001179
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001180 def test_proxy_https(self):
1181 o = OpenerDirector()
1182 ph = urllib.request.ProxyHandler(dict(https="proxy.example.com:3128"))
1183 o.add_handler(ph)
1184 meth_spec = [
1185 [("https_open", "return response")]
1186 ]
1187 handlers = add_ordered_mock_handlers(o, meth_spec)
1188
1189 req = Request("https://www.example.com/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001190 self.assertEqual(req.host, "www.example.com")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001191 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001192 self.assertEqual(req.host, "proxy.example.com:3128")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001193 self.assertEqual([(handlers[0], "https_open")],
1194 [tup[0:2] for tup in o.calls])
1195
Senthil Kumaran47fff872009-12-20 07:10:31 +00001196 def test_proxy_https_proxy_authorization(self):
1197 o = OpenerDirector()
1198 ph = urllib.request.ProxyHandler(dict(https='proxy.example.com:3128'))
1199 o.add_handler(ph)
1200 https_handler = MockHTTPSHandler()
1201 o.add_handler(https_handler)
1202 req = Request("https://www.example.com/")
1203 req.add_header("Proxy-Authorization","FooBar")
1204 req.add_header("User-Agent","Grail")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001205 self.assertEqual(req.host, "www.example.com")
Senthil Kumaran47fff872009-12-20 07:10:31 +00001206 self.assertIsNone(req._tunnel_host)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001207 o.open(req)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001208 # Verify Proxy-Authorization gets tunneled to request.
1209 # httpsconn req_headers do not have the Proxy-Authorization header but
1210 # the req will have.
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001211 self.assertNotIn(("Proxy-Authorization","FooBar"),
Senthil Kumaran47fff872009-12-20 07:10:31 +00001212 https_handler.httpconn.req_headers)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001213 self.assertIn(("User-Agent","Grail"),
1214 https_handler.httpconn.req_headers)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001215 self.assertIsNotNone(req._tunnel_host)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001216 self.assertEqual(req.host, "proxy.example.com:3128")
Senthil Kumaran47fff872009-12-20 07:10:31 +00001217 self.assertEqual(req.get_header("Proxy-authorization"),"FooBar")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001218
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001219 # TODO: This should be only for OSX
1220 @unittest.skipUnless(sys.platform == 'darwin', "only relevant for OSX")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001221 def test_osx_proxy_bypass(self):
1222 bypass = {
1223 'exclude_simple': False,
1224 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.10',
1225 '10.0/16']
1226 }
1227 # Check hosts that should trigger the proxy bypass
1228 for host in ('foo.bar', 'www.bar.com', '127.0.0.1', '10.10.0.1',
1229 '10.0.0.1'):
1230 self.assertTrue(_proxy_bypass_macosx_sysconf(host, bypass),
1231 'expected bypass of %s to be True' % host)
1232 # Check hosts that should not trigger the proxy bypass
R David Murrayfdbe9182014-03-15 12:00:14 -04001233 for host in ('abc.foo.bar', 'bar.com', '127.0.0.2', '10.11.0.1',
1234 'notinbypass'):
Ronald Oussorene72e1612011-03-14 18:15:25 -04001235 self.assertFalse(_proxy_bypass_macosx_sysconf(host, bypass),
1236 'expected bypass of %s to be False' % host)
1237
1238 # Check the exclude_simple flag
1239 bypass = {'exclude_simple': True, 'exceptions': []}
1240 self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass))
1241
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001242 def test_basic_auth(self, quote_char='"'):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001243 opener = OpenerDirector()
1244 password_manager = MockPasswordManager()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001245 auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001246 realm = "ACME Widget Store"
1247 http_handler = MockHTTPHandler(
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001248 401, 'WWW-Authenticate: Basic realm=%s%s%s\r\n\r\n' %
1249 (quote_char, realm, quote_char) )
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001250 opener.add_handler(auth_handler)
1251 opener.add_handler(http_handler)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001252 self._test_basic_auth(opener, auth_handler, "Authorization",
1253 realm, http_handler, password_manager,
1254 "http://acme.example.com/protected",
1255 "http://acme.example.com/protected",
1256 )
1257
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001258 def test_basic_auth_with_single_quoted_realm(self):
1259 self.test_basic_auth(quote_char="'")
1260
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +08001261 def test_basic_auth_with_unquoted_realm(self):
1262 opener = OpenerDirector()
1263 password_manager = MockPasswordManager()
1264 auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
1265 realm = "ACME Widget Store"
1266 http_handler = MockHTTPHandler(
1267 401, 'WWW-Authenticate: Basic realm=%s\r\n\r\n' % realm)
1268 opener.add_handler(auth_handler)
1269 opener.add_handler(http_handler)
Senthil Kumaran0ea91cb2012-05-15 23:59:42 +08001270 with self.assertWarns(UserWarning):
1271 self._test_basic_auth(opener, auth_handler, "Authorization",
1272 realm, http_handler, password_manager,
1273 "http://acme.example.com/protected",
1274 "http://acme.example.com/protected",
1275 )
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +08001276
Thomas Wouters477c8d52006-05-27 19:21:47 +00001277 def test_proxy_basic_auth(self):
1278 opener = OpenerDirector()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001279 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001280 opener.add_handler(ph)
1281 password_manager = MockPasswordManager()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001282 auth_handler = urllib.request.ProxyBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001283 realm = "ACME Networks"
1284 http_handler = MockHTTPHandler(
1285 407, 'Proxy-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001286 opener.add_handler(auth_handler)
1287 opener.add_handler(http_handler)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001288 self._test_basic_auth(opener, auth_handler, "Proxy-authorization",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001289 realm, http_handler, password_manager,
1290 "http://acme.example.com:3128/protected",
1291 "proxy.example.com:3128",
1292 )
1293
1294 def test_basic_and_digest_auth_handlers(self):
Andrew Svetlov7bd61cb2012-12-19 22:49:25 +02001295 # HTTPDigestAuthHandler raised an exception if it couldn't handle a 40*
Thomas Wouters477c8d52006-05-27 19:21:47 +00001296 # response (http://python.org/sf/1479302), where it should instead
1297 # return None to allow another handler (especially
1298 # HTTPBasicAuthHandler) to handle the response.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001299
1300 # Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must
1301 # try digest first (since it's the strongest auth scheme), so we record
1302 # order of calls here to check digest comes first:
1303 class RecordingOpenerDirector(OpenerDirector):
1304 def __init__(self):
1305 OpenerDirector.__init__(self)
1306 self.recorded = []
1307 def record(self, info):
1308 self.recorded.append(info)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001309 class TestDigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001310 def http_error_401(self, *args, **kwds):
1311 self.parent.record("digest")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001312 urllib.request.HTTPDigestAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001313 *args, **kwds)
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001314 class TestBasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001315 def http_error_401(self, *args, **kwds):
1316 self.parent.record("basic")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001317 urllib.request.HTTPBasicAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001318 *args, **kwds)
1319
1320 opener = RecordingOpenerDirector()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001321 password_manager = MockPasswordManager()
1322 digest_handler = TestDigestAuthHandler(password_manager)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001323 basic_handler = TestBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001324 realm = "ACME Networks"
1325 http_handler = MockHTTPHandler(
1326 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001327 opener.add_handler(basic_handler)
1328 opener.add_handler(digest_handler)
1329 opener.add_handler(http_handler)
1330
1331 # check basic auth isn't blocked by digest handler failing
Thomas Wouters477c8d52006-05-27 19:21:47 +00001332 self._test_basic_auth(opener, basic_handler, "Authorization",
1333 realm, http_handler, password_manager,
1334 "http://acme.example.com/protected",
1335 "http://acme.example.com/protected",
1336 )
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001337 # check digest was tried before basic (twice, because
1338 # _test_basic_auth called .open() twice)
1339 self.assertEqual(opener.recorded, ["digest", "basic"]*2)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001340
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001341 def test_unsupported_auth_digest_handler(self):
1342 opener = OpenerDirector()
1343 # While using DigestAuthHandler
1344 digest_auth_handler = urllib.request.HTTPDigestAuthHandler(None)
1345 http_handler = MockHTTPHandler(
1346 401, 'WWW-Authenticate: Kerberos\r\n\r\n')
1347 opener.add_handler(digest_auth_handler)
1348 opener.add_handler(http_handler)
1349 self.assertRaises(ValueError,opener.open,"http://www.example.com")
1350
1351 def test_unsupported_auth_basic_handler(self):
1352 # While using BasicAuthHandler
1353 opener = OpenerDirector()
1354 basic_auth_handler = urllib.request.HTTPBasicAuthHandler(None)
1355 http_handler = MockHTTPHandler(
1356 401, 'WWW-Authenticate: NTLM\r\n\r\n')
1357 opener.add_handler(basic_auth_handler)
1358 opener.add_handler(http_handler)
1359 self.assertRaises(ValueError,opener.open,"http://www.example.com")
1360
Thomas Wouters477c8d52006-05-27 19:21:47 +00001361 def _test_basic_auth(self, opener, auth_handler, auth_header,
1362 realm, http_handler, password_manager,
1363 request_url, protected_url):
Christian Heimes05e8be12008-02-23 18:30:17 +00001364 import base64
Thomas Wouters477c8d52006-05-27 19:21:47 +00001365 user, password = "wile", "coyote"
Thomas Wouters477c8d52006-05-27 19:21:47 +00001366
1367 # .add_password() fed through to password manager
1368 auth_handler.add_password(realm, request_url, user, password)
1369 self.assertEqual(realm, password_manager.realm)
1370 self.assertEqual(request_url, password_manager.url)
1371 self.assertEqual(user, password_manager.user)
1372 self.assertEqual(password, password_manager.password)
1373
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001374 opener.open(request_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001375
1376 # should have asked the password manager for the username/password
1377 self.assertEqual(password_manager.target_realm, realm)
1378 self.assertEqual(password_manager.target_url, protected_url)
1379
1380 # expect one request without authorization, then one with
1381 self.assertEqual(len(http_handler.requests), 2)
1382 self.assertFalse(http_handler.requests[0].has_header(auth_header))
Guido van Rossum98b349f2007-08-27 21:47:52 +00001383 userpass = bytes('%s:%s' % (user, password), "ascii")
Guido van Rossum98297ee2007-11-06 21:34:58 +00001384 auth_hdr_value = ('Basic ' +
Georg Brandl706824f2009-06-04 09:42:55 +00001385 base64.encodebytes(userpass).strip().decode())
Thomas Wouters477c8d52006-05-27 19:21:47 +00001386 self.assertEqual(http_handler.requests[1].get_header(auth_header),
1387 auth_hdr_value)
Senthil Kumaranca2fc9e2010-02-24 16:53:16 +00001388 self.assertEqual(http_handler.requests[1].unredirected_hdrs[auth_header],
1389 auth_hdr_value)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001390 # if the password manager can't find a password, the handler won't
1391 # handle the HTTP auth error
1392 password_manager.user = password_manager.password = None
1393 http_handler.reset()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001394 opener.open(request_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001395 self.assertEqual(len(http_handler.requests), 1)
1396 self.assertFalse(http_handler.requests[0].has_header(auth_header))
1397
Serhiy Storchakaf54c3502014-09-06 21:41:39 +03001398 def test_http_closed(self):
1399 """Test the connection is cleaned up when the response is closed"""
1400 for (transfer, data) in (
1401 ("Connection: close", b"data"),
1402 ("Transfer-Encoding: chunked", b"4\r\ndata\r\n0\r\n\r\n"),
1403 ("Content-Length: 4", b"data"),
1404 ):
1405 header = "HTTP/1.1 200 OK\r\n{}\r\n\r\n".format(transfer)
1406 conn = test_urllib.fakehttp(header.encode() + data)
1407 handler = urllib.request.AbstractHTTPHandler()
1408 req = Request("http://dummy/")
1409 req.timeout = None
1410 with handler.do_open(conn, req) as resp:
1411 resp.read()
1412 self.assertTrue(conn.fakesock.closed,
1413 "Connection not closed with {!r}".format(transfer))
1414
1415 def test_invalid_closed(self):
1416 """Test the connection is cleaned up after an invalid response"""
1417 conn = test_urllib.fakehttp(b"")
1418 handler = urllib.request.AbstractHTTPHandler()
1419 req = Request("http://dummy/")
1420 req.timeout = None
1421 with self.assertRaises(http.client.BadStatusLine):
1422 handler.do_open(conn, req)
1423 self.assertTrue(conn.fakesock.closed, "Connection not closed")
1424
Nick Coghlanc216c482014-11-12 23:33:50 +10001425 def test_auth_prior_handler(self):
1426 pwd_manager = MockPasswordManager()
1427 pwd_manager.add_password(None, 'https://example.com',
1428 'somebody', 'verysecret')
1429 auth_prior_handler = urllib.request.HTTPBasicPriorAuthHandler(
1430 pwd_manager)
1431 http_hand = MockHTTPSHandler()
1432
1433 opener = OpenerDirector()
1434 opener.add_handler(http_hand)
1435 opener.add_handler(auth_prior_handler)
1436
1437 req = Request("https://example.com")
1438 opener.open(req)
1439 self.assertNotIn('Authorization', http_hand.httpconn.req_headers)
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001440
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001441class MiscTests(unittest.TestCase):
1442
Senthil Kumarane9853da2013-03-19 12:07:43 -07001443 def opener_has_handler(self, opener, handler_class):
1444 self.assertTrue(any(h.__class__ == handler_class
1445 for h in opener.handlers))
1446
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001447 def test_build_opener(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001448 class MyHTTPHandler(urllib.request.HTTPHandler): pass
1449 class FooHandler(urllib.request.BaseHandler):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001450 def foo_open(self): pass
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001451 class BarHandler(urllib.request.BaseHandler):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001452 def bar_open(self): pass
1453
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001454 build_opener = urllib.request.build_opener
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001455
1456 o = build_opener(FooHandler, BarHandler)
1457 self.opener_has_handler(o, FooHandler)
1458 self.opener_has_handler(o, BarHandler)
1459
1460 # can take a mix of classes and instances
1461 o = build_opener(FooHandler, BarHandler())
1462 self.opener_has_handler(o, FooHandler)
1463 self.opener_has_handler(o, BarHandler)
1464
1465 # subclasses of default handlers override default handlers
1466 o = build_opener(MyHTTPHandler)
1467 self.opener_has_handler(o, MyHTTPHandler)
1468
1469 # a particular case of overriding: default handlers can be passed
1470 # in explicitly
1471 o = build_opener()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001472 self.opener_has_handler(o, urllib.request.HTTPHandler)
1473 o = build_opener(urllib.request.HTTPHandler)
1474 self.opener_has_handler(o, urllib.request.HTTPHandler)
1475 o = build_opener(urllib.request.HTTPHandler())
1476 self.opener_has_handler(o, urllib.request.HTTPHandler)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001477
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001478 # Issue2670: multiple handlers sharing the same base class
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001479 class MyOtherHTTPHandler(urllib.request.HTTPHandler): pass
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001480 o = build_opener(MyHTTPHandler, MyOtherHTTPHandler)
1481 self.opener_has_handler(o, MyHTTPHandler)
1482 self.opener_has_handler(o, MyOtherHTTPHandler)
1483
Brett Cannon80512de2013-01-25 22:27:21 -05001484 @unittest.skipUnless(support.is_resource_enabled('network'),
1485 'test requires network access')
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001486 def test_issue16464(self):
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001487 with support.transient_internet("http://www.example.com/"):
1488 opener = urllib.request.build_opener()
1489 request = urllib.request.Request("http://www.example.com/")
1490 self.assertEqual(None, request.data)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001491
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001492 opener.open(request, "1".encode("us-ascii"))
1493 self.assertEqual(b"1", request.data)
1494 self.assertEqual("1", request.get_header("Content-length"))
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001495
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001496 opener.open(request, "1234567890".encode("us-ascii"))
1497 self.assertEqual(b"1234567890", request.data)
1498 self.assertEqual("10", request.get_header("Content-length"))
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001499
Senthil Kumarane9853da2013-03-19 12:07:43 -07001500 def test_HTTPError_interface(self):
1501 """
1502 Issue 13211 reveals that HTTPError didn't implement the URLError
1503 interface even though HTTPError is a subclass of URLError.
Senthil Kumarane9853da2013-03-19 12:07:43 -07001504 """
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001505 msg = 'something bad happened'
1506 url = code = fp = None
1507 hdrs = 'Content-Length: 42'
1508 err = urllib.error.HTTPError(url, code, msg, hdrs, fp)
1509 self.assertTrue(hasattr(err, 'reason'))
1510 self.assertEqual(err.reason, 'something bad happened')
1511 self.assertTrue(hasattr(err, 'headers'))
1512 self.assertEqual(err.headers, 'Content-Length: 42')
1513 expected_errmsg = 'HTTP Error %s: %s' % (err.code, err.msg)
1514 self.assertEqual(str(err), expected_errmsg)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001515
Senthil Kumarand8e24f12014-04-14 16:32:20 -04001516 def test_parse_proxy(self):
1517 parse_proxy_test_cases = [
1518 ('proxy.example.com',
1519 (None, None, None, 'proxy.example.com')),
1520 ('proxy.example.com:3128',
1521 (None, None, None, 'proxy.example.com:3128')),
1522 ('proxy.example.com', (None, None, None, 'proxy.example.com')),
1523 ('proxy.example.com:3128',
1524 (None, None, None, 'proxy.example.com:3128')),
1525 # The authority component may optionally include userinfo
1526 # (assumed to be # username:password):
1527 ('joe:password@proxy.example.com',
1528 (None, 'joe', 'password', 'proxy.example.com')),
1529 ('joe:password@proxy.example.com:3128',
1530 (None, 'joe', 'password', 'proxy.example.com:3128')),
1531 #Examples with URLS
1532 ('http://proxy.example.com/',
1533 ('http', None, None, 'proxy.example.com')),
1534 ('http://proxy.example.com:3128/',
1535 ('http', None, None, 'proxy.example.com:3128')),
1536 ('http://joe:password@proxy.example.com/',
1537 ('http', 'joe', 'password', 'proxy.example.com')),
1538 ('http://joe:password@proxy.example.com:3128',
1539 ('http', 'joe', 'password', 'proxy.example.com:3128')),
1540 # Everything after the authority is ignored
1541 ('ftp://joe:password@proxy.example.com/rubbish:3128',
1542 ('ftp', 'joe', 'password', 'proxy.example.com')),
1543 # Test for no trailing '/' case
1544 ('http://joe:password@proxy.example.com',
1545 ('http', 'joe', 'password', 'proxy.example.com'))
1546 ]
1547
1548 for tc, expected in parse_proxy_test_cases:
1549 self.assertEqual(_parse_proxy(tc), expected)
1550
1551 self.assertRaises(ValueError, _parse_proxy, 'file:/ftp.example.com'),
1552
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001553class RequestTests(unittest.TestCase):
Jason R. Coombs4a652422013-09-08 13:03:40 -04001554 class PutRequest(Request):
1555 method='PUT'
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001556
1557 def setUp(self):
1558 self.get = Request("http://www.python.org/~jeremy/")
1559 self.post = Request("http://www.python.org/~jeremy/",
1560 "data",
1561 headers={"X-Test": "test"})
Jason R. Coombs4a652422013-09-08 13:03:40 -04001562 self.head = Request("http://www.python.org/~jeremy/", method='HEAD')
1563 self.put = self.PutRequest("http://www.python.org/~jeremy/")
1564 self.force_post = self.PutRequest("http://www.python.org/~jeremy/",
1565 method="POST")
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001566
1567 def test_method(self):
1568 self.assertEqual("POST", self.post.get_method())
1569 self.assertEqual("GET", self.get.get_method())
Senthil Kumaran0b5463f2013-09-09 23:13:06 -07001570 self.assertEqual("HEAD", self.head.get_method())
Jason R. Coombs4a652422013-09-08 13:03:40 -04001571 self.assertEqual("PUT", self.put.get_method())
1572 self.assertEqual("POST", self.force_post.get_method())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001573
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001574 def test_data(self):
1575 self.assertFalse(self.get.data)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001576 self.assertEqual("GET", self.get.get_method())
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001577 self.get.data = "spam"
1578 self.assertTrue(self.get.data)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001579 self.assertEqual("POST", self.get.get_method())
1580
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001581 # issue 16464
1582 # if we change data we need to remove content-length header
1583 # (cause it's most probably calculated for previous value)
1584 def test_setting_data_should_remove_content_length(self):
R David Murray9cc7d452013-03-20 00:10:51 -04001585 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001586 self.get.add_unredirected_header("Content-length", 42)
1587 self.assertEqual(42, self.get.unredirected_hdrs["Content-length"])
1588 self.get.data = "spam"
R David Murray9cc7d452013-03-20 00:10:51 -04001589 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
1590
1591 # issue 17485 same for deleting data.
1592 def test_deleting_data_should_remove_content_length(self):
1593 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
1594 self.get.data = 'foo'
1595 self.get.add_unredirected_header("Content-length", 3)
1596 self.assertEqual(3, self.get.unredirected_hdrs["Content-length"])
1597 del self.get.data
1598 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001599
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001600 def test_get_full_url(self):
1601 self.assertEqual("http://www.python.org/~jeremy/",
1602 self.get.get_full_url())
1603
1604 def test_selector(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001605 self.assertEqual("/~jeremy/", self.get.selector)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001606 req = Request("http://www.python.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001607 self.assertEqual("/", req.selector)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001608
1609 def test_get_type(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001610 self.assertEqual("http", self.get.type)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001611
1612 def test_get_host(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001613 self.assertEqual("www.python.org", self.get.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001614
1615 def test_get_host_unquote(self):
1616 req = Request("http://www.%70ython.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001617 self.assertEqual("www.python.org", req.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001618
1619 def test_proxy(self):
Florent Xicluna419e3842010-08-08 16:16:07 +00001620 self.assertFalse(self.get.has_proxy())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001621 self.get.set_proxy("www.perl.org", "http")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001622 self.assertTrue(self.get.has_proxy())
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001623 self.assertEqual("www.python.org", self.get.origin_req_host)
1624 self.assertEqual("www.perl.org", self.get.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001625
Senthil Kumarand95cc752010-08-08 11:27:53 +00001626 def test_wrapped_url(self):
1627 req = Request("<URL:http://www.python.org>")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001628 self.assertEqual("www.python.org", req.host)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001629
Senthil Kumaran26430412011-04-13 07:01:19 +08001630 def test_url_fragment(self):
Senthil Kumarand95cc752010-08-08 11:27:53 +00001631 req = Request("http://www.python.org/?qs=query#fragment=true")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001632 self.assertEqual("/?qs=query", req.selector)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001633 req = Request("http://www.python.org/#fun=true")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001634 self.assertEqual("/", req.selector)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001635
Senthil Kumaran26430412011-04-13 07:01:19 +08001636 # Issue 11703: geturl() omits fragment in the original URL.
1637 url = 'http://docs.python.org/library/urllib2.html#OK'
1638 req = Request(url)
1639 self.assertEqual(req.get_full_url(), url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001640
Senthil Kumaran83070752013-05-24 09:14:12 -07001641 def test_url_fullurl_get_full_url(self):
1642 urls = ['http://docs.python.org',
1643 'http://docs.python.org/library/urllib2.html#OK',
1644 'http://www.python.org/?qs=query#fragment=true' ]
1645 for url in urls:
1646 req = Request(url)
1647 self.assertEqual(req.get_full_url(), req.full_url)
1648
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001649
1650if __name__ == "__main__":
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001651 unittest.main()