blob: f202f970ccb38ff889b67a8ce26e15b853902145 [file] [log] [blame]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002from test import support
Hai Shibb0424b2020-08-04 00:47:42 +08003from test.support import os_helper
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03004from test.support import socket_helper
Hai Shibb0424b2020-08-04 00:47:42 +08005from test.support import warnings_helper
Serhiy Storchakaf54c3502014-09-06 21:41:39 +03006from test import test_urllib
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00007
Christian Heimes05e8be12008-02-23 18:30:17 +00008import os
Guido van Rossum34d19282007-08-09 01:03:29 +00009import io
Georg Brandlf78e02b2008-06-10 17:40:04 +000010import socket
Senthil Kumaran7bc0d872010-12-19 10:49:52 +000011import array
Senthil Kumaran4de00a22011-05-11 21:17:57 +080012import sys
Martin Panter3c0d0ba2016-08-24 06:33:33 +000013import tempfile
14import subprocess
Jeremy Hyltone3e61042001-05-09 15:50:25 +000015
Jeremy Hylton1afc1692008-06-18 20:49:58 +000016import urllib.request
Ronald Oussorene72e1612011-03-14 18:15:25 -040017# The proxy bypass method imported below has logic specific to the OSX
18# proxy config data structure but is testable on all platforms.
R David Murray4c7f9952015-04-16 16:36:18 -040019from urllib.request import (Request, OpenerDirector, HTTPBasicAuthHandler,
20 HTTPPasswordMgrWithPriorAuth, _parse_proxy,
Berker Peksage88dd1c2016-03-06 16:16:40 +020021 _proxy_bypass_macosx_sysconf,
22 AbstractDigestAuthHandler)
Senthil Kumaran83070752013-05-24 09:14:12 -070023from urllib.parse import urlparse
guido@google.coma119df92011-03-29 11:41:02 -070024import urllib.error
Serhiy Storchakaf54c3502014-09-06 21:41:39 +030025import http.client
Jeremy Hyltone3e61042001-05-09 15:50:25 +000026
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000027# XXX
28# Request
29# CacheFTPHandler (hard to write)
Thomas Wouters477c8d52006-05-27 19:21:47 +000030# parse_keqv_list, parse_http_list, HTTPDigestAuthHandler
Jeremy Hyltone3e61042001-05-09 15:50:25 +000031
Facundo Batista244afcf2015-04-22 18:35:54 -030032
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000033class TrivialTests(unittest.TestCase):
Senthil Kumaran6c5bd402011-11-01 23:20:31 +080034
35 def test___all__(self):
36 # Verify which names are exposed
37 for module in 'request', 'response', 'parse', 'error', 'robotparser':
38 context = {}
39 exec('from urllib.%s import *' % module, context)
40 del context['__builtins__']
Florent Xicluna3dbb1f12011-11-04 22:15:37 +010041 if module == 'request' and os.name == 'nt':
42 u, p = context.pop('url2pathname'), context.pop('pathname2url')
43 self.assertEqual(u.__module__, 'nturl2path')
44 self.assertEqual(p.__module__, 'nturl2path')
Senthil Kumaran6c5bd402011-11-01 23:20:31 +080045 for k, v in context.items():
46 self.assertEqual(v.__module__, 'urllib.%s' % module,
47 "%r is exposed in 'urllib.%s' but defined in %r" %
48 (k, module, v.__module__))
49
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000050 def test_trivial(self):
51 # A couple trivial tests
Guido van Rossume2ae77b2001-10-24 20:42:55 +000052
Victor Stinner7cb92042019-07-02 14:50:19 +020053 # clear _opener global variable
54 self.addCleanup(urllib.request.urlcleanup)
55
Jeremy Hylton1afc1692008-06-18 20:49:58 +000056 self.assertRaises(ValueError, urllib.request.urlopen, 'bogus url')
Tim Peters861adac2001-07-16 20:49:49 +000057
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000058 # XXX Name hacking to get this to work on Windows.
Serhiy Storchaka5106d042015-01-26 10:26:14 +020059 fname = os.path.abspath(urllib.request.__file__).replace(os.sep, '/')
Senthil Kumarand587e302010-01-10 17:45:52 +000060
Senthil Kumarand587e302010-01-10 17:45:52 +000061 if os.name == 'nt':
62 file_url = "file:///%s" % fname
63 else:
64 file_url = "file://%s" % fname
65
Serhiy Storchaka5b10b982019-03-05 10:06:26 +020066 with urllib.request.urlopen(file_url) as f:
67 f.read()
Tim Petersf5f32b42005-07-17 23:16:17 +000068
Georg Brandle1b13d22005-08-24 22:20:32 +000069 def test_parse_http_list(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +000070 tests = [
71 ('a,b,c', ['a', 'b', 'c']),
72 ('path"o,l"og"i"cal, example', ['path"o,l"og"i"cal', 'example']),
73 ('a, b, "c", "d", "e,f", g, h',
74 ['a', 'b', '"c"', '"d"', '"e,f"', 'g', 'h']),
75 ('a="b\\"c", d="e\\,f", g="h\\\\i"',
76 ['a="b"c"', 'd="e,f"', 'g="h\\i"'])]
Georg Brandle1b13d22005-08-24 22:20:32 +000077 for string, list in tests:
Florent Xicluna419e3842010-08-08 16:16:07 +000078 self.assertEqual(urllib.request.parse_http_list(string), list)
Georg Brandle1b13d22005-08-24 22:20:32 +000079
Senthil Kumaran843fae92013-03-19 13:43:42 -070080 def test_URLError_reasonstr(self):
81 err = urllib.error.URLError('reason')
82 self.assertIn(err.reason, str(err))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +000083
Facundo Batista244afcf2015-04-22 18:35:54 -030084
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -070085class RequestHdrsTests(unittest.TestCase):
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000086
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -070087 def test_request_headers_dict(self):
88 """
89 The Request.headers dictionary is not a documented interface. It
90 should stay that way, because the complete set of headers are only
91 accessible through the .get_header(), .has_header(), .header_items()
92 interface. However, .headers pre-dates those methods, and so real code
93 will be using the dictionary.
94
95 The introduction in 2.4 of those methods was a mistake for the same
96 reason: code that previously saw all (urllib2 user)-provided headers in
97 .headers now sees only a subset.
98
99 """
100 url = "http://example.com"
101 self.assertEqual(Request(url,
102 headers={"Spam-eggs": "blah"}
103 ).headers["Spam-eggs"], "blah")
104 self.assertEqual(Request(url,
105 headers={"spam-EggS": "blah"}
106 ).headers["Spam-eggs"], "blah")
107
108 def test_request_headers_methods(self):
109 """
110 Note the case normalization of header names here, to
111 .capitalize()-case. This should be preserved for
112 backwards-compatibility. (In the HTTP case, normalization to
113 .title()-case is done by urllib2 before sending headers to
114 http.client).
115
116 Note that e.g. r.has_header("spam-EggS") is currently False, and
117 r.get_header("spam-EggS") returns None, but that could be changed in
118 future.
119
120 Method r.remove_header should remove items both from r.headers and
121 r.unredirected_hdrs dictionaries
122 """
123 url = "http://example.com"
124 req = Request(url, headers={"Spam-eggs": "blah"})
125 self.assertTrue(req.has_header("Spam-eggs"))
126 self.assertEqual(req.header_items(), [('Spam-eggs', 'blah')])
127
128 req.add_header("Foo-Bar", "baz")
129 self.assertEqual(sorted(req.header_items()),
130 [('Foo-bar', 'baz'), ('Spam-eggs', 'blah')])
131 self.assertFalse(req.has_header("Not-there"))
132 self.assertIsNone(req.get_header("Not-there"))
133 self.assertEqual(req.get_header("Not-there", "default"), "default")
134
135 req.remove_header("Spam-eggs")
136 self.assertFalse(req.has_header("Spam-eggs"))
137
138 req.add_unredirected_header("Unredirected-spam", "Eggs")
139 self.assertTrue(req.has_header("Unredirected-spam"))
140
141 req.remove_header("Unredirected-spam")
142 self.assertFalse(req.has_header("Unredirected-spam"))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000143
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700144 def test_password_manager(self):
145 mgr = urllib.request.HTTPPasswordMgr()
146 add = mgr.add_password
147 find_user_pass = mgr.find_user_password
Senthil Kumaran1f5425f2017-03-31 22:27:27 -0700148
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700149 add("Some Realm", "http://example.com/", "joe", "password")
150 add("Some Realm", "http://example.com/ni", "ni", "ni")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700151 add("Some Realm", "http://c.example.com:3128", "3", "c")
152 add("Some Realm", "d.example.com", "4", "d")
153 add("Some Realm", "e.example.com:3128", "5", "e")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000154
Senthil Kumaran1f5425f2017-03-31 22:27:27 -0700155 # For the same realm, password set the highest path is the winner.
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700156 self.assertEqual(find_user_pass("Some Realm", "example.com"),
157 ('joe', 'password'))
Senthil Kumaran1f5425f2017-03-31 22:27:27 -0700158 self.assertEqual(find_user_pass("Some Realm", "http://example.com/ni"),
159 ('joe', 'password'))
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700160 self.assertEqual(find_user_pass("Some Realm", "http://example.com"),
161 ('joe', 'password'))
162 self.assertEqual(find_user_pass("Some Realm", "http://example.com/"),
163 ('joe', 'password'))
Senthil Kumaran1f5425f2017-03-31 22:27:27 -0700164 self.assertEqual(find_user_pass("Some Realm",
165 "http://example.com/spam"),
166 ('joe', 'password'))
167
168 self.assertEqual(find_user_pass("Some Realm",
169 "http://example.com/spam/spam"),
170 ('joe', 'password'))
171
172 # You can have different passwords for different paths.
173
174 add("c", "http://example.com/foo", "foo", "ni")
175 add("c", "http://example.com/bar", "bar", "nini")
176
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700177 self.assertEqual(find_user_pass("c", "http://example.com/foo"),
178 ('foo', 'ni'))
Senthil Kumaran1f5425f2017-03-31 22:27:27 -0700179
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700180 self.assertEqual(find_user_pass("c", "http://example.com/bar"),
181 ('bar', 'nini'))
Senthil Kumaran1f5425f2017-03-31 22:27:27 -0700182
183 # For the same path, newer password should be considered.
184
185 add("b", "http://example.com/", "first", "blah")
186 add("b", "http://example.com/", "second", "spam")
187
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700188 self.assertEqual(find_user_pass("b", "http://example.com/"),
189 ('second', 'spam'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000190
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700191 # No special relationship between a.example.com and example.com:
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000192
Senthil Kumaran1f5425f2017-03-31 22:27:27 -0700193 add("a", "http://example.com", "1", "a")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700194 self.assertEqual(find_user_pass("a", "http://example.com/"),
195 ('1', 'a'))
Senthil Kumaran1f5425f2017-03-31 22:27:27 -0700196
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700197 self.assertEqual(find_user_pass("a", "http://a.example.com/"),
198 (None, None))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000199
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700200 # Ports:
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000201
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700202 self.assertEqual(find_user_pass("Some Realm", "c.example.com"),
203 (None, None))
204 self.assertEqual(find_user_pass("Some Realm", "c.example.com:3128"),
205 ('3', 'c'))
206 self.assertEqual(
207 find_user_pass("Some Realm", "http://c.example.com:3128"),
208 ('3', 'c'))
209 self.assertEqual(find_user_pass("Some Realm", "d.example.com"),
210 ('4', 'd'))
211 self.assertEqual(find_user_pass("Some Realm", "e.example.com:3128"),
212 ('5', 'e'))
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000213
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700214 def test_password_manager_default_port(self):
215 """
216 The point to note here is that we can't guess the default port if
217 there's no scheme. This applies to both add_password and
218 find_user_password.
219 """
220 mgr = urllib.request.HTTPPasswordMgr()
221 add = mgr.add_password
222 find_user_pass = mgr.find_user_password
223 add("f", "http://g.example.com:80", "10", "j")
224 add("g", "http://h.example.com", "11", "k")
225 add("h", "i.example.com:80", "12", "l")
226 add("i", "j.example.com", "13", "m")
227 self.assertEqual(find_user_pass("f", "g.example.com:100"),
228 (None, None))
229 self.assertEqual(find_user_pass("f", "g.example.com:80"),
230 ('10', 'j'))
231 self.assertEqual(find_user_pass("f", "g.example.com"),
232 (None, None))
233 self.assertEqual(find_user_pass("f", "http://g.example.com:100"),
234 (None, None))
235 self.assertEqual(find_user_pass("f", "http://g.example.com:80"),
236 ('10', 'j'))
237 self.assertEqual(find_user_pass("f", "http://g.example.com"),
238 ('10', 'j'))
239 self.assertEqual(find_user_pass("g", "h.example.com"), ('11', 'k'))
240 self.assertEqual(find_user_pass("g", "h.example.com:80"), ('11', 'k'))
241 self.assertEqual(find_user_pass("g", "http://h.example.com:80"),
242 ('11', 'k'))
243 self.assertEqual(find_user_pass("h", "i.example.com"), (None, None))
244 self.assertEqual(find_user_pass("h", "i.example.com:80"), ('12', 'l'))
245 self.assertEqual(find_user_pass("h", "http://i.example.com:80"),
246 ('12', 'l'))
247 self.assertEqual(find_user_pass("i", "j.example.com"), ('13', 'm'))
248 self.assertEqual(find_user_pass("i", "j.example.com:80"),
249 (None, None))
250 self.assertEqual(find_user_pass("i", "http://j.example.com"),
251 ('13', 'm'))
252 self.assertEqual(find_user_pass("i", "http://j.example.com:80"),
253 (None, None))
Andrew Svetlovbff98fe2012-11-27 23:06:19 +0200254
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000255
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000256class MockOpener:
257 addheaders = []
Facundo Batista244afcf2015-04-22 18:35:54 -0300258
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +0000259 def open(self, req, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
260 self.req, self.data, self.timeout = req, data, timeout
Facundo Batista244afcf2015-04-22 18:35:54 -0300261
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000262 def error(self, proto, *args):
263 self.proto, self.args = proto, args
264
Facundo Batista244afcf2015-04-22 18:35:54 -0300265
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000266class MockFile:
Facundo Batista244afcf2015-04-22 18:35:54 -0300267 def read(self, count=None):
268 pass
269
270 def readline(self, count=None):
271 pass
272
273 def close(self):
274 pass
275
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000276
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000277class MockHeaders(dict):
278 def getheaders(self, name):
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000279 return list(self.values())
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000280
Facundo Batista244afcf2015-04-22 18:35:54 -0300281
Guido van Rossum34d19282007-08-09 01:03:29 +0000282class MockResponse(io.StringIO):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000283 def __init__(self, code, msg, headers, data, url=None):
Guido van Rossum34d19282007-08-09 01:03:29 +0000284 io.StringIO.__init__(self, data)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000285 self.code, self.msg, self.headers, self.url = code, msg, headers, url
Facundo Batista244afcf2015-04-22 18:35:54 -0300286
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000287 def info(self):
288 return self.headers
Facundo Batista244afcf2015-04-22 18:35:54 -0300289
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000290 def geturl(self):
291 return self.url
292
Facundo Batista244afcf2015-04-22 18:35:54 -0300293
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000294class MockCookieJar:
295 def add_cookie_header(self, request):
296 self.ach_req = request
Facundo Batista244afcf2015-04-22 18:35:54 -0300297
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000298 def extract_cookies(self, response, request):
299 self.ec_req, self.ec_r = request, response
300
Facundo Batista244afcf2015-04-22 18:35:54 -0300301
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000302class FakeMethod:
303 def __init__(self, meth_name, action, handle):
304 self.meth_name = meth_name
305 self.handle = handle
306 self.action = action
Facundo Batista244afcf2015-04-22 18:35:54 -0300307
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000308 def __call__(self, *args):
309 return self.handle(self.meth_name, self.action, *args)
310
Facundo Batista244afcf2015-04-22 18:35:54 -0300311
Senthil Kumaran47fff872009-12-20 07:10:31 +0000312class MockHTTPResponse(io.IOBase):
313 def __init__(self, fp, msg, status, reason):
314 self.fp = fp
315 self.msg = msg
316 self.status = status
317 self.reason = reason
318 self.code = 200
319
320 def read(self):
321 return ''
322
323 def info(self):
324 return {}
325
326 def geturl(self):
327 return self.url
328
329
330class MockHTTPClass:
331 def __init__(self):
332 self.level = 0
333 self.req_headers = []
334 self.data = None
335 self.raise_on_endheaders = False
Nadeem Vawdabd26b542012-10-21 17:37:43 +0200336 self.sock = None
Senthil Kumaran47fff872009-12-20 07:10:31 +0000337 self._tunnel_headers = {}
338
339 def __call__(self, host, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
340 self.host = host
341 self.timeout = timeout
342 return self
343
344 def set_debuglevel(self, level):
345 self.level = level
346
347 def set_tunnel(self, host, port=None, headers=None):
348 self._tunnel_host = host
349 self._tunnel_port = port
350 if headers:
351 self._tunnel_headers = headers
352 else:
353 self._tunnel_headers.clear()
354
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000355 def request(self, method, url, body=None, headers=None, *,
356 encode_chunked=False):
Senthil Kumaran47fff872009-12-20 07:10:31 +0000357 self.method = method
358 self.selector = url
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000359 if headers is not None:
360 self.req_headers += headers.items()
Senthil Kumaran47fff872009-12-20 07:10:31 +0000361 self.req_headers.sort()
362 if body:
363 self.data = body
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000364 self.encode_chunked = encode_chunked
Senthil Kumaran47fff872009-12-20 07:10:31 +0000365 if self.raise_on_endheaders:
Andrew Svetlov0832af62012-12-18 23:10:48 +0200366 raise OSError()
Facundo Batista244afcf2015-04-22 18:35:54 -0300367
Senthil Kumaran47fff872009-12-20 07:10:31 +0000368 def getresponse(self):
369 return MockHTTPResponse(MockFile(), {}, 200, "OK")
370
Victor Stinnera4c45d72011-06-17 14:01:18 +0200371 def close(self):
372 pass
373
Facundo Batista244afcf2015-04-22 18:35:54 -0300374
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000375class MockHandler:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000376 # useful for testing handler machinery
377 # see add_ordered_mock_handlers() docstring
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000378 handler_order = 500
Facundo Batista244afcf2015-04-22 18:35:54 -0300379
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000380 def __init__(self, methods):
381 self._define_methods(methods)
Facundo Batista244afcf2015-04-22 18:35:54 -0300382
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000383 def _define_methods(self, methods):
384 for spec in methods:
Facundo Batista244afcf2015-04-22 18:35:54 -0300385 if len(spec) == 2:
386 name, action = spec
387 else:
388 name, action = spec, None
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000389 meth = FakeMethod(name, action, self.handle)
390 setattr(self.__class__, name, meth)
Facundo Batista244afcf2015-04-22 18:35:54 -0300391
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000392 def handle(self, fn_name, action, *args, **kwds):
393 self.parent.calls.append((self, fn_name, args, kwds))
394 if action is None:
395 return None
396 elif action == "return self":
397 return self
398 elif action == "return response":
399 res = MockResponse(200, "OK", {}, "")
400 return res
401 elif action == "return request":
402 return Request("http://blah/")
403 elif action.startswith("error"):
404 code = action[action.rfind(" ")+1:]
405 try:
406 code = int(code)
407 except ValueError:
408 pass
409 res = MockResponse(200, "OK", {}, "")
410 return self.parent.error("http", args[0], res, code, "", {})
411 elif action == "raise":
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000412 raise urllib.error.URLError("blah")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000413 assert False
Facundo Batista244afcf2015-04-22 18:35:54 -0300414
415 def close(self):
416 pass
417
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000418 def add_parent(self, parent):
419 self.parent = parent
420 self.parent.calls = []
Facundo Batista244afcf2015-04-22 18:35:54 -0300421
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000422 def __lt__(self, other):
423 if not hasattr(other, "handler_order"):
424 # No handler_order, leave in original order. Yuck.
425 return True
426 return self.handler_order < other.handler_order
427
Facundo Batista244afcf2015-04-22 18:35:54 -0300428
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000429def add_ordered_mock_handlers(opener, meth_spec):
430 """Create MockHandlers and add them to an OpenerDirector.
431
432 meth_spec: list of lists of tuples and strings defining methods to define
433 on handlers. eg:
434
435 [["http_error", "ftp_open"], ["http_open"]]
436
437 defines methods .http_error() and .ftp_open() on one handler, and
438 .http_open() on another. These methods just record their arguments and
439 return None. Using a tuple instead of a string causes the method to
440 perform some action (see MockHandler.handle()), eg:
441
442 [["http_error"], [("http_open", "return request")]]
443
444 defines .http_error() on one handler (which simply returns None), and
445 .http_open() on another handler, which returns a Request object.
446
447 """
448 handlers = []
449 count = 0
450 for meths in meth_spec:
Facundo Batista244afcf2015-04-22 18:35:54 -0300451 class MockHandlerSubclass(MockHandler):
452 pass
453
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000454 h = MockHandlerSubclass(meths)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000455 h.handler_order += count
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000456 h.add_parent(opener)
457 count = count + 1
458 handlers.append(h)
459 opener.add_handler(h)
460 return handlers
461
Facundo Batista244afcf2015-04-22 18:35:54 -0300462
Thomas Wouters477c8d52006-05-27 19:21:47 +0000463def build_test_opener(*handler_instances):
464 opener = OpenerDirector()
465 for h in handler_instances:
466 opener.add_handler(h)
467 return opener
468
Facundo Batista244afcf2015-04-22 18:35:54 -0300469
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000470class MockHTTPHandler(urllib.request.BaseHandler):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000471 # useful for testing redirections and auth
472 # sends supplied headers and code as first response
473 # sends 200 OK as second response
474 def __init__(self, code, headers):
475 self.code = code
476 self.headers = headers
477 self.reset()
Facundo Batista244afcf2015-04-22 18:35:54 -0300478
Thomas Wouters477c8d52006-05-27 19:21:47 +0000479 def reset(self):
480 self._count = 0
481 self.requests = []
Facundo Batista244afcf2015-04-22 18:35:54 -0300482
Thomas Wouters477c8d52006-05-27 19:21:47 +0000483 def http_open(self, req):
Martin Panterce6e0682016-05-16 01:07:13 +0000484 import email, copy
Thomas Wouters477c8d52006-05-27 19:21:47 +0000485 self.requests.append(copy.deepcopy(req))
486 if self._count == 0:
487 self._count = self._count + 1
Georg Brandl24420152008-05-26 16:32:26 +0000488 name = http.client.responses[self.code]
Barry Warsaw820c1202008-06-12 04:06:45 +0000489 msg = email.message_from_string(self.headers)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000490 return self.parent.error(
491 "http", req, MockFile(), self.code, name, msg)
492 else:
493 self.req = req
Barry Warsaw820c1202008-06-12 04:06:45 +0000494 msg = email.message_from_string("\r\n\r\n")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000495 return MockResponse(200, "OK", msg, "", req.get_full_url())
496
Facundo Batista244afcf2015-04-22 18:35:54 -0300497
Senthil Kumaran47fff872009-12-20 07:10:31 +0000498class MockHTTPSHandler(urllib.request.AbstractHTTPHandler):
499 # Useful for testing the Proxy-Authorization request by verifying the
500 # properties of httpcon
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000501
Senthil Kumaran9642eed2016-05-13 01:32:42 -0700502 def __init__(self, debuglevel=0):
503 urllib.request.AbstractHTTPHandler.__init__(self, debuglevel=debuglevel)
Benjamin Peterson3d5b8db2009-12-24 01:14:05 +0000504 self.httpconn = MockHTTPClass()
505
Senthil Kumaran47fff872009-12-20 07:10:31 +0000506 def https_open(self, req):
507 return self.do_open(self.httpconn, req)
508
R David Murray4c7f9952015-04-16 16:36:18 -0400509
510class MockHTTPHandlerCheckAuth(urllib.request.BaseHandler):
511 # useful for testing auth
512 # sends supplied code response
513 # checks if auth header is specified in request
514 def __init__(self, code):
515 self.code = code
516 self.has_auth_header = False
517
518 def reset(self):
519 self.has_auth_header = False
520
521 def http_open(self, req):
522 if req.has_header('Authorization'):
523 self.has_auth_header = True
524 name = http.client.responses[self.code]
525 return MockResponse(self.code, name, MockFile(), "", req.get_full_url())
526
527
Facundo Batista244afcf2015-04-22 18:35:54 -0300528
Thomas Wouters477c8d52006-05-27 19:21:47 +0000529class MockPasswordManager:
530 def add_password(self, realm, uri, user, password):
531 self.realm = realm
532 self.url = uri
533 self.user = user
534 self.password = password
Facundo Batista244afcf2015-04-22 18:35:54 -0300535
Thomas Wouters477c8d52006-05-27 19:21:47 +0000536 def find_user_password(self, realm, authuri):
537 self.target_realm = realm
538 self.target_url = authuri
539 return self.user, self.password
540
541
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000542class OpenerDirectorTests(unittest.TestCase):
543
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000544 def test_add_non_handler(self):
545 class NonHandler(object):
546 pass
547 self.assertRaises(TypeError,
548 OpenerDirector().add_handler, NonHandler())
549
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000550 def test_badly_named_methods(self):
551 # test work-around for three methods that accidentally follow the
552 # naming conventions for handler methods
553 # (*_open() / *_request() / *_response())
554
555 # These used to call the accidentally-named methods, causing a
556 # TypeError in real code; here, returning self from these mock
557 # methods would either cause no exception, or AttributeError.
558
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000559 from urllib.error import URLError
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000560
561 o = OpenerDirector()
562 meth_spec = [
563 [("do_open", "return self"), ("proxy_open", "return self")],
564 [("redirect_request", "return self")],
565 ]
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700566 add_ordered_mock_handlers(o, meth_spec)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000567 o.add_handler(urllib.request.UnknownHandler())
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000568 for scheme in "do", "proxy", "redirect":
569 self.assertRaises(URLError, o.open, scheme+"://example.com/")
570
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000571 def test_handled(self):
572 # handler returning non-None means no more handlers will be called
573 o = OpenerDirector()
574 meth_spec = [
575 ["http_open", "ftp_open", "http_error_302"],
576 ["ftp_open"],
577 [("http_open", "return self")],
578 [("http_open", "return self")],
579 ]
580 handlers = add_ordered_mock_handlers(o, meth_spec)
581
582 req = Request("http://example.com/")
583 r = o.open(req)
584 # Second .http_open() gets called, third doesn't, since second returned
585 # non-None. Handlers without .http_open() never get any methods called
586 # on them.
587 # In fact, second mock handler defining .http_open() returns self
588 # (instead of response), which becomes the OpenerDirector's return
589 # value.
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000590 self.assertEqual(r, handlers[2])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000591 calls = [(handlers[0], "http_open"), (handlers[2], "http_open")]
592 for expected, got in zip(calls, o.calls):
593 handler, name, args, kwds = got
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000594 self.assertEqual((handler, name), expected)
595 self.assertEqual(args, (req,))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000596
597 def test_handler_order(self):
598 o = OpenerDirector()
599 handlers = []
Facundo Batista244afcf2015-04-22 18:35:54 -0300600 for meths, handler_order in [([("http_open", "return self")], 500),
601 (["http_open"], 0)]:
602 class MockHandlerSubclass(MockHandler):
603 pass
604
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000605 h = MockHandlerSubclass(meths)
606 h.handler_order = handler_order
607 handlers.append(h)
608 o.add_handler(h)
609
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700610 o.open("http://example.com/")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000611 # handlers called in reverse order, thanks to their sort order
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000612 self.assertEqual(o.calls[0][0], handlers[1])
613 self.assertEqual(o.calls[1][0], handlers[0])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000614
615 def test_raise(self):
616 # raising URLError stops processing of request
617 o = OpenerDirector()
618 meth_spec = [
619 [("http_open", "raise")],
620 [("http_open", "return self")],
621 ]
622 handlers = add_ordered_mock_handlers(o, meth_spec)
623
624 req = Request("http://example.com/")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000625 self.assertRaises(urllib.error.URLError, o.open, req)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000626 self.assertEqual(o.calls, [(handlers[0], "http_open", (req,), {})])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000627
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000628 def test_http_error(self):
629 # XXX http_error_default
630 # http errors are a special case
631 o = OpenerDirector()
632 meth_spec = [
633 [("http_open", "error 302")],
634 [("http_error_400", "raise"), "http_open"],
635 [("http_error_302", "return response"), "http_error_303",
636 "http_error"],
637 [("http_error_302")],
638 ]
639 handlers = add_ordered_mock_handlers(o, meth_spec)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000640 req = Request("http://example.com/")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700641 o.open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000642 assert len(o.calls) == 2
643 calls = [(handlers[0], "http_open", (req,)),
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000644 (handlers[2], "http_error_302",
Serhiy Storchaka7d44e7a2019-08-08 08:43:18 +0300645 (req, support.ALWAYS_EQ, 302, "", {}))]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000646 for expected, got in zip(calls, o.calls):
647 handler, method_name, args = expected
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000648 self.assertEqual((handler, method_name), got[:2])
649 self.assertEqual(args, got[2])
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000650
651 def test_processors(self):
652 # *_request / *_response methods get called appropriately
653 o = OpenerDirector()
654 meth_spec = [
655 [("http_request", "return request"),
656 ("http_response", "return response")],
657 [("http_request", "return request"),
658 ("http_response", "return response")],
659 ]
660 handlers = add_ordered_mock_handlers(o, meth_spec)
661
662 req = Request("http://example.com/")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700663 o.open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000664 # processor methods are called on *all* handlers that define them,
665 # not just the first handler that handles the request
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000666 calls = [
667 (handlers[0], "http_request"), (handlers[1], "http_request"),
668 (handlers[0], "http_response"), (handlers[1], "http_response")]
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000669
670 for i, (handler, name, args, kwds) in enumerate(o.calls):
671 if i < 2:
672 # *_request
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000673 self.assertEqual((handler, name), calls[i])
674 self.assertEqual(len(args), 1)
Ezio Melottie9615932010-01-24 19:26:24 +0000675 self.assertIsInstance(args[0], Request)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000676 else:
677 # *_response
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000678 self.assertEqual((handler, name), calls[i])
679 self.assertEqual(len(args), 2)
Ezio Melottie9615932010-01-24 19:26:24 +0000680 self.assertIsInstance(args[0], Request)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000681 # response from opener.open is None, because there's no
682 # handler that defines http_open to handle it
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200683 if args[1] is not None:
684 self.assertIsInstance(args[1], MockResponse)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000685
Facundo Batista244afcf2015-04-22 18:35:54 -0300686
Tim Peters58eb11c2004-01-18 20:29:55 +0000687def sanepathname2url(path):
Victor Stinner6c6f8512010-08-07 10:09:35 +0000688 try:
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000689 path.encode("utf-8")
Victor Stinner6c6f8512010-08-07 10:09:35 +0000690 except UnicodeEncodeError:
691 raise unittest.SkipTest("path is not encodable to utf8")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000692 urlpath = urllib.request.pathname2url(path)
Tim Peters58eb11c2004-01-18 20:29:55 +0000693 if os.name == "nt" and urlpath.startswith("///"):
694 urlpath = urlpath[2:]
695 # XXX don't ask me about the mac...
696 return urlpath
697
Facundo Batista244afcf2015-04-22 18:35:54 -0300698
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000699class HandlerTests(unittest.TestCase):
700
701 def test_ftp(self):
702 class MockFTPWrapper:
Facundo Batista244afcf2015-04-22 18:35:54 -0300703 def __init__(self, data):
704 self.data = data
705
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000706 def retrfile(self, filename, filetype):
707 self.filename, self.filetype = filename, filetype
Guido van Rossum34d19282007-08-09 01:03:29 +0000708 return io.StringIO(self.data), len(self.data)
Facundo Batista244afcf2015-04-22 18:35:54 -0300709
710 def close(self):
711 pass
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000712
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000713 class NullFTPHandler(urllib.request.FTPHandler):
Facundo Batista244afcf2015-04-22 18:35:54 -0300714 def __init__(self, data):
715 self.data = data
716
Georg Brandlf78e02b2008-06-10 17:40:04 +0000717 def connect_ftp(self, user, passwd, host, port, dirs,
718 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000719 self.user, self.passwd = user, passwd
720 self.host, self.port = host, port
721 self.dirs = dirs
722 self.ftpwrapper = MockFTPWrapper(self.data)
723 return self.ftpwrapper
724
Georg Brandlf78e02b2008-06-10 17:40:04 +0000725 import ftplib
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000726 data = "rheum rhaponicum"
727 h = NullFTPHandler(data)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -0700728 h.parent = MockOpener()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000729
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000730 for url, host, port, user, passwd, type_, dirs, filename, mimetype in [
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000731 ("ftp://localhost/foo/bar/baz.html",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000732 "localhost", ftplib.FTP_PORT, "", "", "I",
733 ["foo", "bar"], "baz.html", "text/html"),
734 ("ftp://parrot@localhost/foo/bar/baz.html",
735 "localhost", ftplib.FTP_PORT, "parrot", "", "I",
736 ["foo", "bar"], "baz.html", "text/html"),
737 ("ftp://%25parrot@localhost/foo/bar/baz.html",
738 "localhost", ftplib.FTP_PORT, "%parrot", "", "I",
739 ["foo", "bar"], "baz.html", "text/html"),
740 ("ftp://%2542parrot@localhost/foo/bar/baz.html",
741 "localhost", ftplib.FTP_PORT, "%42parrot", "", "I",
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000742 ["foo", "bar"], "baz.html", "text/html"),
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000743 ("ftp://localhost:80/foo/bar/",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000744 "localhost", 80, "", "", "D",
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000745 ["foo", "bar"], "", None),
746 ("ftp://localhost/baz.gif;type=a",
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000747 "localhost", ftplib.FTP_PORT, "", "", "A",
Abhilash Raj19a3d872019-10-11 22:41:35 -0700748 [], "baz.gif", None), # XXX really this should guess image/gif
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000749 ]:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000750 req = Request(url)
751 req.timeout = None
752 r = h.ftp_open(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000753 # ftp authentication not yet implemented by FTPHandler
Senthil Kumarandaa29d02010-11-18 15:36:41 +0000754 self.assertEqual(h.user, user)
755 self.assertEqual(h.passwd, passwd)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000756 self.assertEqual(h.host, socket.gethostbyname(host))
757 self.assertEqual(h.port, port)
758 self.assertEqual(h.dirs, dirs)
759 self.assertEqual(h.ftpwrapper.filename, filename)
760 self.assertEqual(h.ftpwrapper.filetype, type_)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000761 headers = r.info()
Kurt B. Kaiser3f7cb5d2004-07-11 17:14:13 +0000762 self.assertEqual(headers.get("Content-type"), mimetype)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000763 self.assertEqual(int(headers["Content-length"]), len(data))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000764
765 def test_file(self):
Senthil Kumaranbc07ac52014-07-22 00:15:20 -0700766 import email.utils
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000767 h = urllib.request.FileHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000768 o = h.parent = MockOpener()
769
Hai Shibb0424b2020-08-04 00:47:42 +0800770 TESTFN = os_helper.TESTFN
Tim Peters58eb11c2004-01-18 20:29:55 +0000771 urlpath = sanepathname2url(os.path.abspath(TESTFN))
Guido van Rossum6a2ccd02007-07-16 20:51:57 +0000772 towrite = b"hello, world\n"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000773 urls = [
Tim Peters58eb11c2004-01-18 20:29:55 +0000774 "file://localhost%s" % urlpath,
775 "file://%s" % urlpath,
776 "file://%s%s" % (socket.gethostbyname('localhost'), urlpath),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000777 ]
778 try:
779 localaddr = socket.gethostbyname(socket.gethostname())
780 except socket.gaierror:
781 localaddr = ''
782 if localaddr:
783 urls.append("file://%s%s" % (localaddr, urlpath))
784
785 for url in urls:
Tim Peters58eb11c2004-01-18 20:29:55 +0000786 f = open(TESTFN, "wb")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000787 try:
788 try:
789 f.write(towrite)
790 finally:
791 f.close()
792
793 r = h.file_open(Request(url))
794 try:
795 data = r.read()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000796 headers = r.info()
Senthil Kumaran4fbed102010-05-08 03:29:09 +0000797 respurl = r.geturl()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000798 finally:
799 r.close()
Tim Peters58eb11c2004-01-18 20:29:55 +0000800 stats = os.stat(TESTFN)
Benjamin Petersona0c0a4a2008-06-12 22:15:50 +0000801 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000802 finally:
803 os.remove(TESTFN)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000804 self.assertEqual(data, towrite)
805 self.assertEqual(headers["Content-type"], "text/plain")
806 self.assertEqual(headers["Content-length"], "13")
Tim Peters58eb11c2004-01-18 20:29:55 +0000807 self.assertEqual(headers["Last-modified"], modified)
Senthil Kumaran4fbed102010-05-08 03:29:09 +0000808 self.assertEqual(respurl, url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000809
810 for url in [
Tim Peters58eb11c2004-01-18 20:29:55 +0000811 "file://localhost:80%s" % urlpath,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000812 "file:///file_does_not_exist.txt",
Senthil Kumaranbc07ac52014-07-22 00:15:20 -0700813 "file://not-a-local-host.com//dir/file.txt",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000814 "file://%s:80%s/%s" % (socket.gethostbyname('localhost'),
815 os.getcwd(), TESTFN),
816 "file://somerandomhost.ontheinternet.com%s/%s" %
817 (os.getcwd(), TESTFN),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000818 ]:
819 try:
Tim Peters58eb11c2004-01-18 20:29:55 +0000820 f = open(TESTFN, "wb")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000821 try:
822 f.write(towrite)
823 finally:
824 f.close()
825
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000826 self.assertRaises(urllib.error.URLError,
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000827 h.file_open, Request(url))
828 finally:
829 os.remove(TESTFN)
830
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000831 h = urllib.request.FileHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000832 o = h.parent = MockOpener()
833 # XXXX why does // mean ftp (and /// mean not ftp!), and where
834 # is file: scheme specified? I think this is really a bug, and
835 # what was intended was to distinguish between URLs like:
836 # file:/blah.txt (a file)
837 # file://localhost/blah.txt (a file)
838 # file:///blah.txt (a file)
839 # file://ftp.example.com/blah.txt (an ftp URL)
840 for url, ftp in [
Senthil Kumaran383c32d2010-10-14 11:57:35 +0000841 ("file://ftp.example.com//foo.txt", False),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000842 ("file://ftp.example.com///foo.txt", False),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000843 ("file://ftp.example.com/foo.txt", False),
Senthil Kumaran383c32d2010-10-14 11:57:35 +0000844 ("file://somehost//foo/something.txt", False),
Senthil Kumaran2ef16322010-07-11 03:12:43 +0000845 ("file://localhost//foo/something.txt", False),
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000846 ]:
847 req = Request(url)
848 try:
849 h.file_open(req)
Senthil Kumaraned3dd1c2017-03-30 22:43:05 -0700850 except urllib.error.URLError:
Florent Xicluna419e3842010-08-08 16:16:07 +0000851 self.assertFalse(ftp)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000852 else:
Florent Xicluna419e3842010-08-08 16:16:07 +0000853 self.assertIs(o.req, req)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000854 self.assertEqual(req.type, "ftp")
Łukasz Langad7e81cc2011-01-09 18:18:53 +0000855 self.assertEqual(req.type == "ftp", ftp)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000856
857 def test_http(self):
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000858
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000859 h = urllib.request.AbstractHTTPHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000860 o = h.parent = MockOpener()
861
862 url = "http://example.com/"
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000863 for method, data in [("GET", None), ("POST", b"blah")]:
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000864 req = Request(url, data, {"Foo": "bar"})
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000865 req.timeout = None
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000866 req.add_unredirected_header("Spam", "eggs")
867 http = MockHTTPClass()
868 r = h.do_open(http, req)
869
870 # result attributes
871 r.read; r.readline # wrapped MockFile methods
872 r.info; r.geturl # addinfourl methods
873 r.code, r.msg == 200, "OK" # added from MockHTTPClass.getreply()
874 hdrs = r.info()
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000875 hdrs.get; hdrs.__contains__ # r.info() gives dict from .getreply()
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000876 self.assertEqual(r.geturl(), url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000877
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000878 self.assertEqual(http.host, "example.com")
879 self.assertEqual(http.level, 0)
880 self.assertEqual(http.method, method)
881 self.assertEqual(http.selector, "/")
882 self.assertEqual(http.req_headers,
Jeremy Hyltonb3ee6f92004-02-24 19:40:35 +0000883 [("Connection", "close"),
884 ("Foo", "bar"), ("Spam", "eggs")])
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000885 self.assertEqual(http.data, data)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000886
Andrew Svetlov0832af62012-12-18 23:10:48 +0200887 # check OSError converted to URLError
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000888 http.raise_on_endheaders = True
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000889 self.assertRaises(urllib.error.URLError, h.do_open, http, req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000890
Senthil Kumaran29333122011-02-11 11:25:47 +0000891 # Check for TypeError on POST data which is str.
892 req = Request("http://example.com/","badpost")
893 self.assertRaises(TypeError, h.do_request_, req)
894
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000895 # check adding of standard headers
896 o.addheaders = [("Spam", "eggs")]
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000897 for data in b"", None: # POST, GET
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000898 req = Request("http://example.com/", data)
899 r = MockResponse(200, "OK", {}, "")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000900 newreq = h.do_request_(req)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000901 if data is None: # GET
Benjamin Peterson577473f2010-01-19 00:09:57 +0000902 self.assertNotIn("Content-length", req.unredirected_hdrs)
903 self.assertNotIn("Content-type", req.unredirected_hdrs)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000904 else: # POST
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000905 self.assertEqual(req.unredirected_hdrs["Content-length"], "0")
906 self.assertEqual(req.unredirected_hdrs["Content-type"],
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000907 "application/x-www-form-urlencoded")
908 # XXX the details of Host could be better tested
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000909 self.assertEqual(req.unredirected_hdrs["Host"], "example.com")
910 self.assertEqual(req.unredirected_hdrs["Spam"], "eggs")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000911
912 # don't clobber existing headers
913 req.add_unredirected_header("Content-length", "foo")
914 req.add_unredirected_header("Content-type", "bar")
915 req.add_unredirected_header("Host", "baz")
916 req.add_unredirected_header("Spam", "foo")
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000917 newreq = h.do_request_(req)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000918 self.assertEqual(req.unredirected_hdrs["Content-length"], "foo")
919 self.assertEqual(req.unredirected_hdrs["Content-type"], "bar")
Jeremy Hyltondf38ea92003-12-17 20:42:38 +0000920 self.assertEqual(req.unredirected_hdrs["Host"], "baz")
921 self.assertEqual(req.unredirected_hdrs["Spam"], "foo")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +0000922
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000923 def test_http_body_file(self):
Martin Panteref91bb22016-08-27 01:39:26 +0000924 # A regular file - chunked encoding is used unless Content Length is
925 # already set.
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000926
927 h = urllib.request.AbstractHTTPHandler()
928 o = h.parent = MockOpener()
929
930 file_obj = tempfile.NamedTemporaryFile(mode='w+b', delete=False)
931 file_path = file_obj.name
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000932 file_obj.close()
Martin Panteref91bb22016-08-27 01:39:26 +0000933 self.addCleanup(os.unlink, file_path)
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000934
Martin Panteref91bb22016-08-27 01:39:26 +0000935 with open(file_path, "rb") as f:
936 req = Request("http://example.com/", f, {})
937 newreq = h.do_request_(req)
938 te = newreq.get_header('Transfer-encoding')
939 self.assertEqual(te, "chunked")
940 self.assertFalse(newreq.has_header('Content-length'))
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000941
Martin Panteref91bb22016-08-27 01:39:26 +0000942 with open(file_path, "rb") as f:
943 req = Request("http://example.com/", f, {"Content-Length": 30})
944 newreq = h.do_request_(req)
945 self.assertEqual(int(newreq.get_header('Content-length')), 30)
946 self.assertFalse(newreq.has_header("Transfer-encoding"))
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000947
948 def test_http_body_fileobj(self):
Martin Panteref91bb22016-08-27 01:39:26 +0000949 # A file object - chunked encoding is used
950 # unless Content Length is already set.
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000951 # (Note that there are some subtle differences to a regular
952 # file, that is why we are testing both cases.)
953
954 h = urllib.request.AbstractHTTPHandler()
955 o = h.parent = MockOpener()
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000956 file_obj = io.BytesIO()
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000957
Martin Panteref91bb22016-08-27 01:39:26 +0000958 req = Request("http://example.com/", file_obj, {})
959 newreq = h.do_request_(req)
960 self.assertEqual(newreq.get_header('Transfer-encoding'), 'chunked')
961 self.assertFalse(newreq.has_header('Content-length'))
962
963 headers = {"Content-Length": 30}
964 req = Request("http://example.com/", file_obj, headers)
965 newreq = h.do_request_(req)
966 self.assertEqual(int(newreq.get_header('Content-length')), 30)
967 self.assertFalse(newreq.has_header("Transfer-encoding"))
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000968
969 file_obj.close()
970
971 def test_http_body_pipe(self):
972 # A file reading from a pipe.
973 # A pipe cannot be seek'ed. There is no way to determine the
974 # content length up front. Thus, do_request_() should fall
975 # back to Transfer-encoding chunked.
976
977 h = urllib.request.AbstractHTTPHandler()
978 o = h.parent = MockOpener()
979
Martin Panteref91bb22016-08-27 01:39:26 +0000980 cmd = [sys.executable, "-c", r"pass"]
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000981 for headers in {}, {"Content-Length": 30}:
982 with subprocess.Popen(cmd, stdout=subprocess.PIPE) as proc:
983 req = Request("http://example.com/", proc.stdout, headers)
984 newreq = h.do_request_(req)
985 if not headers:
986 self.assertEqual(newreq.get_header('Content-length'), None)
987 self.assertEqual(newreq.get_header('Transfer-encoding'),
988 'chunked')
989 else:
990 self.assertEqual(int(newreq.get_header('Content-length')),
991 30)
992
993 def test_http_body_iterable(self):
994 # Generic iterable. There is no way to determine the content
995 # length up front. Fall back to Transfer-encoding chunked.
996
997 h = urllib.request.AbstractHTTPHandler()
998 o = h.parent = MockOpener()
999
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001000 def iterable_body():
1001 yield b"one"
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001002
1003 for headers in {}, {"Content-Length": 11}:
1004 req = Request("http://example.com/", iterable_body(), headers)
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001005 newreq = h.do_request_(req)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001006 if not headers:
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001007 self.assertEqual(newreq.get_header('Content-length'), None)
1008 self.assertEqual(newreq.get_header('Transfer-encoding'),
1009 'chunked')
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001010 else:
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001011 self.assertEqual(int(newreq.get_header('Content-length')), 11)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001012
Martin Panteref91bb22016-08-27 01:39:26 +00001013 def test_http_body_empty_seq(self):
1014 # Zero-length iterable body should be treated like any other iterable
1015 h = urllib.request.AbstractHTTPHandler()
1016 h.parent = MockOpener()
1017 req = h.do_request_(Request("http://example.com/", ()))
1018 self.assertEqual(req.get_header("Transfer-encoding"), "chunked")
1019 self.assertFalse(req.has_header("Content-length"))
1020
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001021 def test_http_body_array(self):
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001022 # array.array Iterable - Content Length is calculated
1023
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001024 h = urllib.request.AbstractHTTPHandler()
1025 o = h.parent = MockOpener()
1026
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001027 iterable_array = array.array("I",[1,2,3,4])
1028
1029 for headers in {}, {"Content-Length": 16}:
1030 req = Request("http://example.com/", iterable_array, headers)
1031 newreq = h.do_request_(req)
1032 self.assertEqual(int(newreq.get_header('Content-length')),16)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001033
Senthil Kumaran9642eed2016-05-13 01:32:42 -07001034 def test_http_handler_debuglevel(self):
1035 o = OpenerDirector()
1036 h = MockHTTPSHandler(debuglevel=1)
1037 o.add_handler(h)
1038 o.open("https://www.example.com")
1039 self.assertEqual(h._debuglevel, 1)
1040
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001041 def test_http_doubleslash(self):
1042 # Checks the presence of any unnecessary double slash in url does not
1043 # break anything. Previously, a double slash directly after the host
Ezio Melottie130a522011-10-19 10:58:56 +03001044 # could cause incorrect parsing.
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001045 h = urllib.request.AbstractHTTPHandler()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001046 h.parent = MockOpener()
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001047
Senthil Kumaran7bc0d872010-12-19 10:49:52 +00001048 data = b""
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001049 ds_urls = [
1050 "http://example.com/foo/bar/baz.html",
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 ]
1055
1056 for ds_url in ds_urls:
1057 ds_req = Request(ds_url, data)
1058
1059 # Check whether host is determined correctly if there is no proxy
1060 np_ds_req = h.do_request_(ds_req)
Facundo Batista244afcf2015-04-22 18:35:54 -03001061 self.assertEqual(np_ds_req.unredirected_hdrs["Host"], "example.com")
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001062
1063 # Check whether host is determined correctly if there is a proxy
Facundo Batista244afcf2015-04-22 18:35:54 -03001064 ds_req.set_proxy("someproxy:3128", None)
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001065 p_ds_req = h.do_request_(ds_req)
Facundo Batista244afcf2015-04-22 18:35:54 -03001066 self.assertEqual(p_ds_req.unredirected_hdrs["Host"], "example.com")
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001067
Senthil Kumaran52380922013-04-25 05:45:48 -07001068 def test_full_url_setter(self):
1069 # Checks to ensure that components are set correctly after setting the
1070 # full_url of a Request object
1071
1072 urls = [
1073 'http://example.com?foo=bar#baz',
1074 'http://example.com?foo=bar&spam=eggs#bash',
1075 'http://example.com',
1076 ]
1077
1078 # testing a reusable request instance, but the url parameter is
1079 # required, so just use a dummy one to instantiate
1080 r = Request('http://example.com')
1081 for url in urls:
1082 r.full_url = url
Senthil Kumaran83070752013-05-24 09:14:12 -07001083 parsed = urlparse(url)
1084
Senthil Kumaran52380922013-04-25 05:45:48 -07001085 self.assertEqual(r.get_full_url(), url)
Senthil Kumaran83070752013-05-24 09:14:12 -07001086 # full_url setter uses splittag to split into components.
1087 # splittag sets the fragment as None while urlparse sets it to ''
1088 self.assertEqual(r.fragment or '', parsed.fragment)
1089 self.assertEqual(urlparse(r.get_full_url()).query, parsed.query)
Senthil Kumaran52380922013-04-25 05:45:48 -07001090
1091 def test_full_url_deleter(self):
1092 r = Request('http://www.example.com')
1093 del r.full_url
1094 self.assertIsNone(r.full_url)
1095 self.assertIsNone(r.fragment)
1096 self.assertEqual(r.selector, '')
1097
Senthil Kumaranc2958622010-11-22 04:48:26 +00001098 def test_fixpath_in_weirdurls(self):
1099 # Issue4493: urllib2 to supply '/' when to urls where path does not
1100 # start with'/'
1101
1102 h = urllib.request.AbstractHTTPHandler()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001103 h.parent = MockOpener()
Senthil Kumaranc2958622010-11-22 04:48:26 +00001104
1105 weird_url = 'http://www.python.org?getspam'
1106 req = Request(weird_url)
1107 newreq = h.do_request_(req)
Facundo Batista244afcf2015-04-22 18:35:54 -03001108 self.assertEqual(newreq.host, 'www.python.org')
1109 self.assertEqual(newreq.selector, '/?getspam')
Senthil Kumaranc2958622010-11-22 04:48:26 +00001110
1111 url_without_path = 'http://www.python.org'
1112 req = Request(url_without_path)
1113 newreq = h.do_request_(req)
Facundo Batista244afcf2015-04-22 18:35:54 -03001114 self.assertEqual(newreq.host, 'www.python.org')
1115 self.assertEqual(newreq.selector, '')
Facundo Batista72dc1ea2008-08-16 14:44:32 +00001116
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001117 def test_errors(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001118 h = urllib.request.HTTPErrorProcessor()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001119 o = h.parent = MockOpener()
1120
1121 url = "http://example.com/"
1122 req = Request(url)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001123 # all 2xx are passed through
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001124 r = MockResponse(200, "OK", {}, "", url)
1125 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +00001126 self.assertIs(r, newr)
1127 self.assertFalse(hasattr(o, "proto")) # o.error not called
Guido van Rossumd8faa362007-04-27 19:54:29 +00001128 r = MockResponse(202, "Accepted", {}, "", url)
1129 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +00001130 self.assertIs(r, newr)
1131 self.assertFalse(hasattr(o, "proto")) # o.error not called
Guido van Rossumd8faa362007-04-27 19:54:29 +00001132 r = MockResponse(206, "Partial content", {}, "", url)
1133 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +00001134 self.assertIs(r, newr)
1135 self.assertFalse(hasattr(o, "proto")) # o.error not called
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001136 # anything else calls o.error (and MockOpener returns None, here)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001137 r = MockResponse(502, "Bad gateway", {}, "", url)
Florent Xicluna419e3842010-08-08 16:16:07 +00001138 self.assertIsNone(h.http_response(req, r))
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001139 self.assertEqual(o.proto, "http") # o.error called
Guido van Rossumd8faa362007-04-27 19:54:29 +00001140 self.assertEqual(o.args, (req, r, 502, "Bad gateway", {}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001141
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001142 def test_cookies(self):
1143 cj = MockCookieJar()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001144 h = urllib.request.HTTPCookieProcessor(cj)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001145 h.parent = MockOpener()
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001146
1147 req = Request("http://example.com/")
1148 r = MockResponse(200, "OK", {}, "")
1149 newreq = h.http_request(req)
Florent Xicluna419e3842010-08-08 16:16:07 +00001150 self.assertIs(cj.ach_req, req)
1151 self.assertIs(cj.ach_req, newreq)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001152 self.assertEqual(req.origin_req_host, "example.com")
1153 self.assertFalse(req.unverifiable)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001154 newr = h.http_response(req, r)
Florent Xicluna419e3842010-08-08 16:16:07 +00001155 self.assertIs(cj.ec_req, req)
1156 self.assertIs(cj.ec_r, r)
1157 self.assertIs(r, newr)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001158
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001159 def test_redirect(self):
1160 from_url = "http://example.com/a.html"
1161 to_url = "http://example.com/b.html"
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001162 h = urllib.request.HTTPRedirectHandler()
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001163 o = h.parent = MockOpener()
1164
1165 # ordinary redirect behaviour
1166 for code in 301, 302, 303, 307:
1167 for data in None, "blah\nblah\n":
1168 method = getattr(h, "http_error_%s" % code)
1169 req = Request(from_url, data)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001170 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001171 req.add_header("Nonsense", "viking=withhold")
Christian Heimes77c02eb2008-02-09 02:18:51 +00001172 if data is not None:
1173 req.add_header("Content-Length", str(len(data)))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001174 req.add_unredirected_header("Spam", "spam")
1175 try:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001176 method(req, MockFile(), code, "Blah",
1177 MockHeaders({"location": to_url}))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001178 except urllib.error.HTTPError:
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001179 # 307 in response to POST requires user OK
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001180 self.assertEqual(code, 307)
1181 self.assertIsNotNone(data)
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001182 self.assertEqual(o.req.get_full_url(), to_url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001183 try:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001184 self.assertEqual(o.req.get_method(), "GET")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001185 except AttributeError:
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001186 self.assertFalse(o.req.data)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001187
1188 # now it's a GET, there should not be headers regarding content
1189 # (possibly dragged from before being a POST)
1190 headers = [x.lower() for x in o.req.headers]
Benjamin Peterson577473f2010-01-19 00:09:57 +00001191 self.assertNotIn("content-length", headers)
1192 self.assertNotIn("content-type", headers)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001193
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001194 self.assertEqual(o.req.headers["Nonsense"],
1195 "viking=withhold")
Benjamin Peterson577473f2010-01-19 00:09:57 +00001196 self.assertNotIn("Spam", o.req.headers)
1197 self.assertNotIn("Spam", o.req.unredirected_hdrs)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001198
1199 # loop detection
1200 req = Request(from_url)
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001201 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Facundo Batista244afcf2015-04-22 18:35:54 -03001202
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001203 def redirect(h, req, url=to_url):
1204 h.http_error_302(req, MockFile(), 302, "Blah",
1205 MockHeaders({"location": url}))
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001206 # Note that the *original* request shares the same record of
1207 # redirections with the sub-requests caused by the redirections.
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001208
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001209 # detect infinite loop redirect of a URL to itself
1210 req = Request(from_url, origin_req_host="example.com")
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001211 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001212 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001213 try:
1214 while 1:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001215 redirect(h, req, "http://example.com/")
1216 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001217 except urllib.error.HTTPError:
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001218 # don't stop until max_repeats, because cookies may introduce state
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001219 self.assertEqual(count, urllib.request.HTTPRedirectHandler.max_repeats)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001220
1221 # detect endless non-repeating chain of redirects
1222 req = Request(from_url, origin_req_host="example.com")
1223 count = 0
Senthil Kumaranfb8cc2f2009-07-19 02:44:19 +00001224 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001225 try:
1226 while 1:
1227 redirect(h, req, "http://example.com/%d" % count)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001228 count = count + 1
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001229 except urllib.error.HTTPError:
Jeremy Hyltondf38ea92003-12-17 20:42:38 +00001230 self.assertEqual(count,
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001231 urllib.request.HTTPRedirectHandler.max_redirections)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001232
guido@google.coma119df92011-03-29 11:41:02 -07001233 def test_invalid_redirect(self):
1234 from_url = "http://example.com/a.html"
1235 valid_schemes = ['http','https','ftp']
1236 invalid_schemes = ['file','imap','ldap']
1237 schemeless_url = "example.com/b.html"
1238 h = urllib.request.HTTPRedirectHandler()
1239 o = h.parent = MockOpener()
1240 req = Request(from_url)
1241 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1242
1243 for scheme in invalid_schemes:
1244 invalid_url = scheme + '://' + schemeless_url
1245 self.assertRaises(urllib.error.HTTPError, h.http_error_302,
1246 req, MockFile(), 302, "Security Loophole",
1247 MockHeaders({"location": invalid_url}))
1248
1249 for scheme in valid_schemes:
1250 valid_url = scheme + '://' + schemeless_url
1251 h.http_error_302(req, MockFile(), 302, "That's fine",
1252 MockHeaders({"location": valid_url}))
1253 self.assertEqual(o.req.get_full_url(), valid_url)
1254
Senthil Kumaran6497aa32012-01-04 13:46:59 +08001255 def test_relative_redirect(self):
1256 from_url = "http://example.com/a.html"
1257 relative_url = "/b.html"
1258 h = urllib.request.HTTPRedirectHandler()
1259 o = h.parent = MockOpener()
1260 req = Request(from_url)
1261 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1262
1263 valid_url = urllib.parse.urljoin(from_url,relative_url)
1264 h.http_error_302(req, MockFile(), 302, "That's fine",
1265 MockHeaders({"location": valid_url}))
1266 self.assertEqual(o.req.get_full_url(), valid_url)
1267
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001268 def test_cookie_redirect(self):
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001269 # cookies shouldn't leak into redirected requests
Georg Brandl24420152008-05-26 16:32:26 +00001270 from http.cookiejar import CookieJar
1271 from test.test_http_cookiejar import interact_netscape
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001272
1273 cj = CookieJar()
1274 interact_netscape(cj, "http://www.example.com/", "spam=eggs")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001275 hh = MockHTTPHandler(302, "Location: http://www.cracker.com/\r\n\r\n")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001276 hdeh = urllib.request.HTTPDefaultErrorHandler()
1277 hrh = urllib.request.HTTPRedirectHandler()
1278 cp = urllib.request.HTTPCookieProcessor(cj)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001279 o = build_test_opener(hh, hdeh, hrh, cp)
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001280 o.open("http://www.example.com/")
Florent Xicluna419e3842010-08-08 16:16:07 +00001281 self.assertFalse(hh.req.has_header("Cookie"))
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001282
Senthil Kumaran26430412011-04-13 07:01:19 +08001283 def test_redirect_fragment(self):
1284 redirected_url = 'http://www.example.com/index.html#OK\r\n\r\n'
1285 hh = MockHTTPHandler(302, 'Location: ' + redirected_url)
1286 hdeh = urllib.request.HTTPDefaultErrorHandler()
1287 hrh = urllib.request.HTTPRedirectHandler()
1288 o = build_test_opener(hh, hdeh, hrh)
1289 fp = o.open('http://www.example.com')
1290 self.assertEqual(fp.geturl(), redirected_url.strip())
1291
Martin Panterce6e0682016-05-16 01:07:13 +00001292 def test_redirect_no_path(self):
1293 # Issue 14132: Relative redirect strips original path
Victor Stinner7cb92042019-07-02 14:50:19 +02001294
1295 # clear _opener global variable
1296 self.addCleanup(urllib.request.urlcleanup)
1297
Martin Panterce6e0682016-05-16 01:07:13 +00001298 real_class = http.client.HTTPConnection
1299 response1 = b"HTTP/1.1 302 Found\r\nLocation: ?query\r\n\r\n"
1300 http.client.HTTPConnection = test_urllib.fakehttp(response1)
1301 self.addCleanup(setattr, http.client, "HTTPConnection", real_class)
1302 urls = iter(("/path", "/path?query"))
1303 def request(conn, method, url, *pos, **kw):
1304 self.assertEqual(url, next(urls))
1305 real_class.request(conn, method, url, *pos, **kw)
1306 # Change response for subsequent connection
1307 conn.__class__.fakedata = b"HTTP/1.1 200 OK\r\n\r\nHello!"
1308 http.client.HTTPConnection.request = request
1309 fp = urllib.request.urlopen("http://python.org/path")
1310 self.assertEqual(fp.geturl(), "http://python.org/path?query")
1311
Martin Pantere6f06092016-05-16 01:14:20 +00001312 def test_redirect_encoding(self):
1313 # Some characters in the redirect target may need special handling,
1314 # but most ASCII characters should be treated as already encoded
1315 class Handler(urllib.request.HTTPHandler):
1316 def http_open(self, req):
1317 result = self.do_open(self.connection, req)
1318 self.last_buf = self.connection.buf
1319 # Set up a normal response for the next request
1320 self.connection = test_urllib.fakehttp(
1321 b'HTTP/1.1 200 OK\r\n'
1322 b'Content-Length: 3\r\n'
1323 b'\r\n'
1324 b'123'
1325 )
1326 return result
1327 handler = Handler()
1328 opener = urllib.request.build_opener(handler)
1329 tests = (
1330 (b'/p\xC3\xA5-dansk/', b'/p%C3%A5-dansk/'),
1331 (b'/spaced%20path/', b'/spaced%20path/'),
1332 (b'/spaced path/', b'/spaced%20path/'),
1333 (b'/?p\xC3\xA5-dansk', b'/?p%C3%A5-dansk'),
1334 )
1335 for [location, result] in tests:
1336 with self.subTest(repr(location)):
1337 handler.connection = test_urllib.fakehttp(
1338 b'HTTP/1.1 302 Redirect\r\n'
1339 b'Location: ' + location + b'\r\n'
1340 b'\r\n'
1341 )
1342 response = opener.open('http://example.com/')
1343 expected = b'GET ' + result + b' '
1344 request = handler.last_buf
1345 self.assertTrue(request.startswith(expected), repr(request))
1346
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001347 def test_proxy(self):
Zackery Spytzb761e3a2019-09-13 08:07:07 -06001348 u = "proxy.example.com:3128"
1349 for d in dict(http=u), dict(HTTP=u):
1350 o = OpenerDirector()
1351 ph = urllib.request.ProxyHandler(d)
1352 o.add_handler(ph)
1353 meth_spec = [
1354 [("http_open", "return response")]
1355 ]
1356 handlers = add_ordered_mock_handlers(o, meth_spec)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001357
Zackery Spytzb761e3a2019-09-13 08:07:07 -06001358 req = Request("http://acme.example.com/")
1359 self.assertEqual(req.host, "acme.example.com")
1360 o.open(req)
1361 self.assertEqual(req.host, u)
1362 self.assertEqual([(handlers[0], "http_open")],
1363 [tup[0:2] for tup in o.calls])
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001364
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001365 def test_proxy_no_proxy(self):
1366 os.environ['no_proxy'] = 'python.org'
1367 o = OpenerDirector()
1368 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1369 o.add_handler(ph)
1370 req = Request("http://www.perl.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001371 self.assertEqual(req.host, "www.perl.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001372 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001373 self.assertEqual(req.host, "proxy.example.com")
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001374 req = Request("http://www.python.org")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001375 self.assertEqual(req.host, "www.python.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001376 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001377 self.assertEqual(req.host, "www.python.org")
Senthil Kumaran7bb04972009-10-11 04:58:55 +00001378 del os.environ['no_proxy']
1379
Ronald Oussorene72e1612011-03-14 18:15:25 -04001380 def test_proxy_no_proxy_all(self):
1381 os.environ['no_proxy'] = '*'
1382 o = OpenerDirector()
1383 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1384 o.add_handler(ph)
1385 req = Request("http://www.python.org")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001386 self.assertEqual(req.host, "www.python.org")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001387 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001388 self.assertEqual(req.host, "www.python.org")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001389 del os.environ['no_proxy']
1390
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001391 def test_proxy_https(self):
1392 o = OpenerDirector()
1393 ph = urllib.request.ProxyHandler(dict(https="proxy.example.com:3128"))
1394 o.add_handler(ph)
1395 meth_spec = [
1396 [("https_open", "return response")]
1397 ]
1398 handlers = add_ordered_mock_handlers(o, meth_spec)
1399
1400 req = Request("https://www.example.com/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001401 self.assertEqual(req.host, "www.example.com")
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001402 o.open(req)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001403 self.assertEqual(req.host, "proxy.example.com:3128")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001404 self.assertEqual([(handlers[0], "https_open")],
1405 [tup[0:2] for tup in o.calls])
1406
Senthil Kumaran47fff872009-12-20 07:10:31 +00001407 def test_proxy_https_proxy_authorization(self):
1408 o = OpenerDirector()
1409 ph = urllib.request.ProxyHandler(dict(https='proxy.example.com:3128'))
1410 o.add_handler(ph)
1411 https_handler = MockHTTPSHandler()
1412 o.add_handler(https_handler)
1413 req = Request("https://www.example.com/")
Facundo Batista244afcf2015-04-22 18:35:54 -03001414 req.add_header("Proxy-Authorization", "FooBar")
1415 req.add_header("User-Agent", "Grail")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001416 self.assertEqual(req.host, "www.example.com")
Senthil Kumaran47fff872009-12-20 07:10:31 +00001417 self.assertIsNone(req._tunnel_host)
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001418 o.open(req)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001419 # Verify Proxy-Authorization gets tunneled to request.
1420 # httpsconn req_headers do not have the Proxy-Authorization header but
1421 # the req will have.
Facundo Batista244afcf2015-04-22 18:35:54 -03001422 self.assertNotIn(("Proxy-Authorization", "FooBar"),
Senthil Kumaran47fff872009-12-20 07:10:31 +00001423 https_handler.httpconn.req_headers)
Facundo Batista244afcf2015-04-22 18:35:54 -03001424 self.assertIn(("User-Agent", "Grail"),
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001425 https_handler.httpconn.req_headers)
Senthil Kumaran47fff872009-12-20 07:10:31 +00001426 self.assertIsNotNone(req._tunnel_host)
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001427 self.assertEqual(req.host, "proxy.example.com:3128")
Facundo Batista244afcf2015-04-22 18:35:54 -03001428 self.assertEqual(req.get_header("Proxy-authorization"), "FooBar")
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +00001429
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001430 @unittest.skipUnless(sys.platform == 'darwin', "only relevant for OSX")
Ronald Oussorene72e1612011-03-14 18:15:25 -04001431 def test_osx_proxy_bypass(self):
1432 bypass = {
1433 'exclude_simple': False,
1434 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.10',
1435 '10.0/16']
1436 }
1437 # Check hosts that should trigger the proxy bypass
1438 for host in ('foo.bar', 'www.bar.com', '127.0.0.1', '10.10.0.1',
1439 '10.0.0.1'):
1440 self.assertTrue(_proxy_bypass_macosx_sysconf(host, bypass),
1441 'expected bypass of %s to be True' % host)
1442 # Check hosts that should not trigger the proxy bypass
R David Murrayfdbe9182014-03-15 12:00:14 -04001443 for host in ('abc.foo.bar', 'bar.com', '127.0.0.2', '10.11.0.1',
1444 'notinbypass'):
Ronald Oussorene72e1612011-03-14 18:15:25 -04001445 self.assertFalse(_proxy_bypass_macosx_sysconf(host, bypass),
1446 'expected bypass of %s to be False' % host)
1447
1448 # Check the exclude_simple flag
1449 bypass = {'exclude_simple': True, 'exceptions': []}
1450 self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass))
1451
Victor Stinner0b297d42020-04-02 02:52:20 +02001452 def check_basic_auth(self, headers, realm):
1453 with self.subTest(realm=realm, headers=headers):
1454 opener = OpenerDirector()
1455 password_manager = MockPasswordManager()
1456 auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
1457 body = '\r\n'.join(headers) + '\r\n\r\n'
1458 http_handler = MockHTTPHandler(401, body)
1459 opener.add_handler(auth_handler)
1460 opener.add_handler(http_handler)
Senthil Kumaran0ea91cb2012-05-15 23:59:42 +08001461 self._test_basic_auth(opener, auth_handler, "Authorization",
Victor Stinner0b297d42020-04-02 02:52:20 +02001462 realm, http_handler, password_manager,
1463 "http://acme.example.com/protected",
1464 "http://acme.example.com/protected")
1465
1466 def test_basic_auth(self):
1467 realm = "realm2@example.com"
1468 realm2 = "realm2@example.com"
1469 basic = f'Basic realm="{realm}"'
1470 basic2 = f'Basic realm="{realm2}"'
1471 other_no_realm = 'Otherscheme xxx'
1472 digest = (f'Digest realm="{realm2}", '
1473 f'qop="auth, auth-int", '
1474 f'nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", '
1475 f'opaque="5ccc069c403ebaf9f0171e9517f40e41"')
1476 for realm_str in (
1477 # test "quote" and 'quote'
1478 f'Basic realm="{realm}"',
1479 f"Basic realm='{realm}'",
1480
1481 # charset is ignored
1482 f'Basic realm="{realm}", charset="UTF-8"',
1483
1484 # Multiple challenges per header
1485 f'{basic}, {basic2}',
1486 f'{basic}, {other_no_realm}',
1487 f'{other_no_realm}, {basic}',
1488 f'{basic}, {digest}',
1489 f'{digest}, {basic}',
1490 ):
1491 headers = [f'WWW-Authenticate: {realm_str}']
1492 self.check_basic_auth(headers, realm)
1493
1494 # no quote: expect a warning
Hai Shibb0424b2020-08-04 00:47:42 +08001495 with warnings_helper.check_warnings(("Basic Auth Realm was unquoted",
Victor Stinner0b297d42020-04-02 02:52:20 +02001496 UserWarning)):
1497 headers = [f'WWW-Authenticate: Basic realm={realm}']
1498 self.check_basic_auth(headers, realm)
1499
1500 # Multiple headers: one challenge per header.
1501 # Use the first Basic realm.
1502 for challenges in (
1503 [basic, basic2],
1504 [basic, digest],
1505 [digest, basic],
1506 ):
1507 headers = [f'WWW-Authenticate: {challenge}'
1508 for challenge in challenges]
1509 self.check_basic_auth(headers, realm)
Senthil Kumaran34f3fcc2012-05-15 22:30:25 +08001510
Thomas Wouters477c8d52006-05-27 19:21:47 +00001511 def test_proxy_basic_auth(self):
1512 opener = OpenerDirector()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001513 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001514 opener.add_handler(ph)
1515 password_manager = MockPasswordManager()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001516 auth_handler = urllib.request.ProxyBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001517 realm = "ACME Networks"
1518 http_handler = MockHTTPHandler(
1519 407, 'Proxy-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001520 opener.add_handler(auth_handler)
1521 opener.add_handler(http_handler)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001522 self._test_basic_auth(opener, auth_handler, "Proxy-authorization",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001523 realm, http_handler, password_manager,
1524 "http://acme.example.com:3128/protected",
1525 "proxy.example.com:3128",
1526 )
1527
1528 def test_basic_and_digest_auth_handlers(self):
Andrew Svetlov7bd61cb2012-12-19 22:49:25 +02001529 # HTTPDigestAuthHandler raised an exception if it couldn't handle a 40*
Thomas Wouters477c8d52006-05-27 19:21:47 +00001530 # response (http://python.org/sf/1479302), where it should instead
1531 # return None to allow another handler (especially
1532 # HTTPBasicAuthHandler) to handle the response.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001533
1534 # Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must
1535 # try digest first (since it's the strongest auth scheme), so we record
1536 # order of calls here to check digest comes first:
1537 class RecordingOpenerDirector(OpenerDirector):
1538 def __init__(self):
1539 OpenerDirector.__init__(self)
1540 self.recorded = []
Facundo Batista244afcf2015-04-22 18:35:54 -03001541
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001542 def record(self, info):
1543 self.recorded.append(info)
Facundo Batista244afcf2015-04-22 18:35:54 -03001544
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001545 class TestDigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001546 def http_error_401(self, *args, **kwds):
1547 self.parent.record("digest")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001548 urllib.request.HTTPDigestAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001549 *args, **kwds)
Facundo Batista244afcf2015-04-22 18:35:54 -03001550
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001551 class TestBasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001552 def http_error_401(self, *args, **kwds):
1553 self.parent.record("basic")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001554 urllib.request.HTTPBasicAuthHandler.http_error_401(self,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001555 *args, **kwds)
1556
1557 opener = RecordingOpenerDirector()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001558 password_manager = MockPasswordManager()
1559 digest_handler = TestDigestAuthHandler(password_manager)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001560 basic_handler = TestBasicAuthHandler(password_manager)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001561 realm = "ACME Networks"
1562 http_handler = MockHTTPHandler(
1563 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001564 opener.add_handler(basic_handler)
1565 opener.add_handler(digest_handler)
1566 opener.add_handler(http_handler)
1567
1568 # check basic auth isn't blocked by digest handler failing
Thomas Wouters477c8d52006-05-27 19:21:47 +00001569 self._test_basic_auth(opener, basic_handler, "Authorization",
1570 realm, http_handler, password_manager,
1571 "http://acme.example.com/protected",
1572 "http://acme.example.com/protected",
1573 )
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001574 # check digest was tried before basic (twice, because
1575 # _test_basic_auth called .open() twice)
1576 self.assertEqual(opener.recorded, ["digest", "basic"]*2)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001577
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001578 def test_unsupported_auth_digest_handler(self):
1579 opener = OpenerDirector()
1580 # While using DigestAuthHandler
1581 digest_auth_handler = urllib.request.HTTPDigestAuthHandler(None)
1582 http_handler = MockHTTPHandler(
1583 401, 'WWW-Authenticate: Kerberos\r\n\r\n')
1584 opener.add_handler(digest_auth_handler)
1585 opener.add_handler(http_handler)
Facundo Batista244afcf2015-04-22 18:35:54 -03001586 self.assertRaises(ValueError, opener.open, "http://www.example.com")
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001587
1588 def test_unsupported_auth_basic_handler(self):
1589 # While using BasicAuthHandler
1590 opener = OpenerDirector()
1591 basic_auth_handler = urllib.request.HTTPBasicAuthHandler(None)
1592 http_handler = MockHTTPHandler(
1593 401, 'WWW-Authenticate: NTLM\r\n\r\n')
1594 opener.add_handler(basic_auth_handler)
1595 opener.add_handler(http_handler)
Facundo Batista244afcf2015-04-22 18:35:54 -03001596 self.assertRaises(ValueError, opener.open, "http://www.example.com")
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001597
Thomas Wouters477c8d52006-05-27 19:21:47 +00001598 def _test_basic_auth(self, opener, auth_handler, auth_header,
1599 realm, http_handler, password_manager,
1600 request_url, protected_url):
Christian Heimes05e8be12008-02-23 18:30:17 +00001601 import base64
Thomas Wouters477c8d52006-05-27 19:21:47 +00001602 user, password = "wile", "coyote"
Thomas Wouters477c8d52006-05-27 19:21:47 +00001603
1604 # .add_password() fed through to password manager
1605 auth_handler.add_password(realm, request_url, user, password)
1606 self.assertEqual(realm, password_manager.realm)
1607 self.assertEqual(request_url, password_manager.url)
1608 self.assertEqual(user, password_manager.user)
1609 self.assertEqual(password, password_manager.password)
1610
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001611 opener.open(request_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001612
1613 # should have asked the password manager for the username/password
1614 self.assertEqual(password_manager.target_realm, realm)
1615 self.assertEqual(password_manager.target_url, protected_url)
1616
1617 # expect one request without authorization, then one with
1618 self.assertEqual(len(http_handler.requests), 2)
1619 self.assertFalse(http_handler.requests[0].has_header(auth_header))
Guido van Rossum98b349f2007-08-27 21:47:52 +00001620 userpass = bytes('%s:%s' % (user, password), "ascii")
Guido van Rossum98297ee2007-11-06 21:34:58 +00001621 auth_hdr_value = ('Basic ' +
Georg Brandl706824f2009-06-04 09:42:55 +00001622 base64.encodebytes(userpass).strip().decode())
Thomas Wouters477c8d52006-05-27 19:21:47 +00001623 self.assertEqual(http_handler.requests[1].get_header(auth_header),
1624 auth_hdr_value)
Senthil Kumaranca2fc9e2010-02-24 16:53:16 +00001625 self.assertEqual(http_handler.requests[1].unredirected_hdrs[auth_header],
1626 auth_hdr_value)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001627 # if the password manager can't find a password, the handler won't
1628 # handle the HTTP auth error
1629 password_manager.user = password_manager.password = None
1630 http_handler.reset()
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001631 opener.open(request_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001632 self.assertEqual(len(http_handler.requests), 1)
1633 self.assertFalse(http_handler.requests[0].has_header(auth_header))
1634
R David Murray4c7f9952015-04-16 16:36:18 -04001635 def test_basic_prior_auth_auto_send(self):
1636 # Assume already authenticated if is_authenticated=True
1637 # for APIs like Github that don't return 401
1638
1639 user, password = "wile", "coyote"
1640 request_url = "http://acme.example.com/protected"
1641
1642 http_handler = MockHTTPHandlerCheckAuth(200)
1643
1644 pwd_manager = HTTPPasswordMgrWithPriorAuth()
1645 auth_prior_handler = HTTPBasicAuthHandler(pwd_manager)
1646 auth_prior_handler.add_password(
1647 None, request_url, user, password, is_authenticated=True)
1648
1649 is_auth = pwd_manager.is_authenticated(request_url)
1650 self.assertTrue(is_auth)
1651
1652 opener = OpenerDirector()
1653 opener.add_handler(auth_prior_handler)
1654 opener.add_handler(http_handler)
1655
1656 opener.open(request_url)
1657
1658 # expect request to be sent with auth header
1659 self.assertTrue(http_handler.has_auth_header)
1660
1661 def test_basic_prior_auth_send_after_first_success(self):
1662 # Auto send auth header after authentication is successful once
1663
1664 user, password = 'wile', 'coyote'
1665 request_url = 'http://acme.example.com/protected'
1666 realm = 'ACME'
1667
1668 pwd_manager = HTTPPasswordMgrWithPriorAuth()
1669 auth_prior_handler = HTTPBasicAuthHandler(pwd_manager)
1670 auth_prior_handler.add_password(realm, request_url, user, password)
1671
1672 is_auth = pwd_manager.is_authenticated(request_url)
1673 self.assertFalse(is_auth)
1674
1675 opener = OpenerDirector()
1676 opener.add_handler(auth_prior_handler)
1677
1678 http_handler = MockHTTPHandler(
1679 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % None)
1680 opener.add_handler(http_handler)
1681
1682 opener.open(request_url)
1683
1684 is_auth = pwd_manager.is_authenticated(request_url)
1685 self.assertTrue(is_auth)
1686
1687 http_handler = MockHTTPHandlerCheckAuth(200)
1688 self.assertFalse(http_handler.has_auth_header)
1689
1690 opener = OpenerDirector()
1691 opener.add_handler(auth_prior_handler)
1692 opener.add_handler(http_handler)
1693
1694 # After getting 200 from MockHTTPHandler
1695 # Next request sends header in the first request
1696 opener.open(request_url)
1697
1698 # expect request to be sent with auth header
1699 self.assertTrue(http_handler.has_auth_header)
1700
Serhiy Storchakaf54c3502014-09-06 21:41:39 +03001701 def test_http_closed(self):
1702 """Test the connection is cleaned up when the response is closed"""
1703 for (transfer, data) in (
1704 ("Connection: close", b"data"),
1705 ("Transfer-Encoding: chunked", b"4\r\ndata\r\n0\r\n\r\n"),
1706 ("Content-Length: 4", b"data"),
1707 ):
1708 header = "HTTP/1.1 200 OK\r\n{}\r\n\r\n".format(transfer)
1709 conn = test_urllib.fakehttp(header.encode() + data)
1710 handler = urllib.request.AbstractHTTPHandler()
1711 req = Request("http://dummy/")
1712 req.timeout = None
1713 with handler.do_open(conn, req) as resp:
1714 resp.read()
1715 self.assertTrue(conn.fakesock.closed,
1716 "Connection not closed with {!r}".format(transfer))
1717
1718 def test_invalid_closed(self):
1719 """Test the connection is cleaned up after an invalid response"""
1720 conn = test_urllib.fakehttp(b"")
1721 handler = urllib.request.AbstractHTTPHandler()
1722 req = Request("http://dummy/")
1723 req.timeout = None
1724 with self.assertRaises(http.client.BadStatusLine):
1725 handler.do_open(conn, req)
1726 self.assertTrue(conn.fakesock.closed, "Connection not closed")
1727
Senthil Kumaran4de00a22011-05-11 21:17:57 +08001728
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001729class MiscTests(unittest.TestCase):
1730
Senthil Kumarane9853da2013-03-19 12:07:43 -07001731 def opener_has_handler(self, opener, handler_class):
1732 self.assertTrue(any(h.__class__ == handler_class
1733 for h in opener.handlers))
1734
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001735 def test_build_opener(self):
Facundo Batista244afcf2015-04-22 18:35:54 -03001736 class MyHTTPHandler(urllib.request.HTTPHandler):
1737 pass
1738
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001739 class FooHandler(urllib.request.BaseHandler):
Facundo Batista244afcf2015-04-22 18:35:54 -03001740 def foo_open(self):
1741 pass
1742
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001743 class BarHandler(urllib.request.BaseHandler):
Facundo Batista244afcf2015-04-22 18:35:54 -03001744 def bar_open(self):
1745 pass
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001746
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001747 build_opener = urllib.request.build_opener
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001748
1749 o = build_opener(FooHandler, BarHandler)
1750 self.opener_has_handler(o, FooHandler)
1751 self.opener_has_handler(o, BarHandler)
1752
1753 # can take a mix of classes and instances
1754 o = build_opener(FooHandler, BarHandler())
1755 self.opener_has_handler(o, FooHandler)
1756 self.opener_has_handler(o, BarHandler)
1757
1758 # subclasses of default handlers override default handlers
1759 o = build_opener(MyHTTPHandler)
1760 self.opener_has_handler(o, MyHTTPHandler)
1761
1762 # a particular case of overriding: default handlers can be passed
1763 # in explicitly
1764 o = build_opener()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001765 self.opener_has_handler(o, urllib.request.HTTPHandler)
1766 o = build_opener(urllib.request.HTTPHandler)
1767 self.opener_has_handler(o, urllib.request.HTTPHandler)
1768 o = build_opener(urllib.request.HTTPHandler())
1769 self.opener_has_handler(o, urllib.request.HTTPHandler)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001770
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001771 # Issue2670: multiple handlers sharing the same base class
Facundo Batista244afcf2015-04-22 18:35:54 -03001772 class MyOtherHTTPHandler(urllib.request.HTTPHandler):
1773 pass
1774
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001775 o = build_opener(MyHTTPHandler, MyOtherHTTPHandler)
1776 self.opener_has_handler(o, MyHTTPHandler)
1777 self.opener_has_handler(o, MyOtherHTTPHandler)
1778
Brett Cannon80512de2013-01-25 22:27:21 -05001779 @unittest.skipUnless(support.is_resource_enabled('network'),
1780 'test requires network access')
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001781 def test_issue16464(self):
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001782 with socket_helper.transient_internet("http://www.example.com/"):
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001783 opener = urllib.request.build_opener()
1784 request = urllib.request.Request("http://www.example.com/")
1785 self.assertEqual(None, request.data)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001786
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001787 opener.open(request, "1".encode("us-ascii"))
1788 self.assertEqual(b"1", request.data)
1789 self.assertEqual("1", request.get_header("Content-length"))
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001790
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001791 opener.open(request, "1234567890".encode("us-ascii"))
1792 self.assertEqual(b"1234567890", request.data)
1793 self.assertEqual("10", request.get_header("Content-length"))
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001794
Senthil Kumarane9853da2013-03-19 12:07:43 -07001795 def test_HTTPError_interface(self):
1796 """
1797 Issue 13211 reveals that HTTPError didn't implement the URLError
1798 interface even though HTTPError is a subclass of URLError.
Senthil Kumarane9853da2013-03-19 12:07:43 -07001799 """
Senthil Kumaranfa1b02a2013-04-08 22:24:17 -07001800 msg = 'something bad happened'
1801 url = code = fp = None
1802 hdrs = 'Content-Length: 42'
1803 err = urllib.error.HTTPError(url, code, msg, hdrs, fp)
1804 self.assertTrue(hasattr(err, 'reason'))
1805 self.assertEqual(err.reason, 'something bad happened')
1806 self.assertTrue(hasattr(err, 'headers'))
1807 self.assertEqual(err.headers, 'Content-Length: 42')
1808 expected_errmsg = 'HTTP Error %s: %s' % (err.code, err.msg)
1809 self.assertEqual(str(err), expected_errmsg)
Facundo Batista244afcf2015-04-22 18:35:54 -03001810 expected_errmsg = '<HTTPError %s: %r>' % (err.code, err.msg)
1811 self.assertEqual(repr(err), expected_errmsg)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001812
Senthil Kumarand8e24f12014-04-14 16:32:20 -04001813 def test_parse_proxy(self):
1814 parse_proxy_test_cases = [
1815 ('proxy.example.com',
1816 (None, None, None, 'proxy.example.com')),
1817 ('proxy.example.com:3128',
1818 (None, None, None, 'proxy.example.com:3128')),
1819 ('proxy.example.com', (None, None, None, 'proxy.example.com')),
1820 ('proxy.example.com:3128',
1821 (None, None, None, 'proxy.example.com:3128')),
1822 # The authority component may optionally include userinfo
1823 # (assumed to be # username:password):
1824 ('joe:password@proxy.example.com',
1825 (None, 'joe', 'password', 'proxy.example.com')),
1826 ('joe:password@proxy.example.com:3128',
1827 (None, 'joe', 'password', 'proxy.example.com:3128')),
1828 #Examples with URLS
1829 ('http://proxy.example.com/',
1830 ('http', None, None, 'proxy.example.com')),
1831 ('http://proxy.example.com:3128/',
1832 ('http', None, None, 'proxy.example.com:3128')),
1833 ('http://joe:password@proxy.example.com/',
1834 ('http', 'joe', 'password', 'proxy.example.com')),
1835 ('http://joe:password@proxy.example.com:3128',
1836 ('http', 'joe', 'password', 'proxy.example.com:3128')),
1837 # Everything after the authority is ignored
1838 ('ftp://joe:password@proxy.example.com/rubbish:3128',
1839 ('ftp', 'joe', 'password', 'proxy.example.com')),
1840 # Test for no trailing '/' case
1841 ('http://joe:password@proxy.example.com',
1842 ('http', 'joe', 'password', 'proxy.example.com'))
1843 ]
1844
1845 for tc, expected in parse_proxy_test_cases:
1846 self.assertEqual(_parse_proxy(tc), expected)
1847
1848 self.assertRaises(ValueError, _parse_proxy, 'file:/ftp.example.com'),
1849
Berker Peksage88dd1c2016-03-06 16:16:40 +02001850 def test_unsupported_algorithm(self):
1851 handler = AbstractDigestAuthHandler()
1852 with self.assertRaises(ValueError) as exc:
1853 handler.get_algorithm_impls('invalid')
1854 self.assertEqual(
1855 str(exc.exception),
1856 "Unsupported digest authentication algorithm 'invalid'"
1857 )
1858
Facundo Batista244afcf2015-04-22 18:35:54 -03001859
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001860class RequestTests(unittest.TestCase):
Jason R. Coombs4a652422013-09-08 13:03:40 -04001861 class PutRequest(Request):
Facundo Batista244afcf2015-04-22 18:35:54 -03001862 method = 'PUT'
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001863
1864 def setUp(self):
1865 self.get = Request("http://www.python.org/~jeremy/")
1866 self.post = Request("http://www.python.org/~jeremy/",
1867 "data",
1868 headers={"X-Test": "test"})
Jason R. Coombs4a652422013-09-08 13:03:40 -04001869 self.head = Request("http://www.python.org/~jeremy/", method='HEAD')
1870 self.put = self.PutRequest("http://www.python.org/~jeremy/")
1871 self.force_post = self.PutRequest("http://www.python.org/~jeremy/",
1872 method="POST")
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001873
1874 def test_method(self):
1875 self.assertEqual("POST", self.post.get_method())
1876 self.assertEqual("GET", self.get.get_method())
Senthil Kumaran0b5463f2013-09-09 23:13:06 -07001877 self.assertEqual("HEAD", self.head.get_method())
Jason R. Coombs4a652422013-09-08 13:03:40 -04001878 self.assertEqual("PUT", self.put.get_method())
1879 self.assertEqual("POST", self.force_post.get_method())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001880
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001881 def test_data(self):
1882 self.assertFalse(self.get.data)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001883 self.assertEqual("GET", self.get.get_method())
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001884 self.get.data = "spam"
1885 self.assertTrue(self.get.data)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001886 self.assertEqual("POST", self.get.get_method())
1887
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001888 # issue 16464
1889 # if we change data we need to remove content-length header
1890 # (cause it's most probably calculated for previous value)
1891 def test_setting_data_should_remove_content_length(self):
R David Murray9cc7d452013-03-20 00:10:51 -04001892 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001893 self.get.add_unredirected_header("Content-length", 42)
1894 self.assertEqual(42, self.get.unredirected_hdrs["Content-length"])
1895 self.get.data = "spam"
R David Murray9cc7d452013-03-20 00:10:51 -04001896 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
1897
1898 # issue 17485 same for deleting data.
1899 def test_deleting_data_should_remove_content_length(self):
1900 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
1901 self.get.data = 'foo'
1902 self.get.add_unredirected_header("Content-length", 3)
1903 self.assertEqual(3, self.get.unredirected_hdrs["Content-length"])
1904 del self.get.data
1905 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
Andrew Svetlovbff98fe2012-11-27 23:06:19 +02001906
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001907 def test_get_full_url(self):
1908 self.assertEqual("http://www.python.org/~jeremy/",
1909 self.get.get_full_url())
1910
1911 def test_selector(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001912 self.assertEqual("/~jeremy/", self.get.selector)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001913 req = Request("http://www.python.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001914 self.assertEqual("/", req.selector)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001915
1916 def test_get_type(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001917 self.assertEqual("http", self.get.type)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001918
1919 def test_get_host(self):
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001920 self.assertEqual("www.python.org", self.get.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001921
1922 def test_get_host_unquote(self):
1923 req = Request("http://www.%70ython.org/")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001924 self.assertEqual("www.python.org", req.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001925
1926 def test_proxy(self):
Florent Xicluna419e3842010-08-08 16:16:07 +00001927 self.assertFalse(self.get.has_proxy())
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001928 self.get.set_proxy("www.perl.org", "http")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001929 self.assertTrue(self.get.has_proxy())
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001930 self.assertEqual("www.python.org", self.get.origin_req_host)
1931 self.assertEqual("www.perl.org", self.get.host)
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001932
Senthil Kumarand95cc752010-08-08 11:27:53 +00001933 def test_wrapped_url(self):
1934 req = Request("<URL:http://www.python.org>")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001935 self.assertEqual("www.python.org", req.host)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001936
Senthil Kumaran26430412011-04-13 07:01:19 +08001937 def test_url_fragment(self):
Senthil Kumarand95cc752010-08-08 11:27:53 +00001938 req = Request("http://www.python.org/?qs=query#fragment=true")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001939 self.assertEqual("/?qs=query", req.selector)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001940 req = Request("http://www.python.org/#fun=true")
Senthil Kumaran77ebfcc2012-08-20 13:43:59 -07001941 self.assertEqual("/", req.selector)
Senthil Kumarand95cc752010-08-08 11:27:53 +00001942
Senthil Kumaran26430412011-04-13 07:01:19 +08001943 # Issue 11703: geturl() omits fragment in the original URL.
1944 url = 'http://docs.python.org/library/urllib2.html#OK'
1945 req = Request(url)
1946 self.assertEqual(req.get_full_url(), url)
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001947
Senthil Kumaran83070752013-05-24 09:14:12 -07001948 def test_url_fullurl_get_full_url(self):
1949 urls = ['http://docs.python.org',
1950 'http://docs.python.org/library/urllib2.html#OK',
Facundo Batista244afcf2015-04-22 18:35:54 -03001951 'http://www.python.org/?qs=query#fragment=true']
Senthil Kumaran83070752013-05-24 09:14:12 -07001952 for url in urls:
1953 req = Request(url)
1954 self.assertEqual(req.get_full_url(), req.full_url)
1955
Jeremy Hyltonc1be59f2003-12-14 05:27:34 +00001956
1957if __name__ == "__main__":
Berker Peksagbcdfc6a2015-03-02 06:01:01 +02001958 unittest.main()