Debian Codegraph @

Lib/test/test_urllib2.py

raw
1 import unittest
2 from test import support
3 from test.support import os_helper
4 from test.support import requires_subprocess
5 from test.support import warnings_helper
6 from test.support.testcase import ExtraAssertions
7 from test import test_urllib
8 from unittest import mock
9
10 import os
11 import io
12 import socket
13 import array
14 import sys
15 import tempfile
16 import subprocess
17
18 import urllib.request
19 # The proxy bypass method imported below has logic specific to the
20 # corresponding system but is testable on all platforms.
21 from urllib.request import (Request, OpenerDirector, HTTPBasicAuthHandler,
22 HTTPPasswordMgrWithPriorAuth, _parse_proxy,
23 _proxy_bypass_winreg_override,
24 _proxy_bypass_macosx_sysconf,
25 AbstractDigestAuthHandler)
26 from urllib.parse import urlparse
27 import urllib.error
28 import http.client
29
30 support.requires_working_socket(module=True)
31
32 # XXX
33 # Request
34 # CacheFTPHandler (hard to write)
35 # parse_keqv_list, parse_http_list, HTTPDigestAuthHandler
36
37
38 class TrivialTests(unittest.TestCase):
39
40 def test___all__(self):
41 # Verify which names are exposed
42 for module in 'request', 'response', 'parse', 'error', 'robotparser':
43 context = {}
44 exec('from urllib.%s import *' % module, context)
45 del context['__builtins__']
46 if module == 'request' and os.name == 'nt':
47 u, p = context.pop('url2pathname'), context.pop('pathname2url')
48 self.assertEqual(u.__module__, 'nturl2path')
49 self.assertEqual(p.__module__, 'nturl2path')
50 for k, v in context.items():
51 self.assertEqual(v.__module__, 'urllib.%s' % module,
52 "%r is exposed in 'urllib.%s' but defined in %r" %
53 (k, module, v.__module__))
54
55 def test_trivial(self):
56 # A couple trivial tests
57
58 # clear _opener global variable
59 self.addCleanup(urllib.request.urlcleanup)
60
61 self.assertRaises(ValueError, urllib.request.urlopen, 'bogus url')
62
63 # XXX Name hacking to get this to work on Windows.
64 fname = os.path.abspath(urllib.request.__file__).replace(os.sep, '/')
65
66 if os.name == 'nt':
67 file_url = "file:///%s" % fname
68 else:
69 file_url = "file://%s" % fname
70
71 with urllib.request.urlopen(file_url) as f:
72 f.read()
73
74 def test_parse_http_list(self):
75 tests = [
76 ('a,b,c', ['a', 'b', 'c']),
77 ('path"o,l"og"i"cal, example', ['path"o,l"og"i"cal', 'example']),
78 ('a, b, "c", "d", "e,f", g, h',
79 ['a', 'b', '"c"', '"d"', '"e,f"', 'g', 'h']),
80 ('a="b\\"c", d="e\\,f", g="h\\\\i"',
81 ['a="b"c"', 'd="e,f"', 'g="h\\i"'])]
82 for string, list in tests:
83 self.assertEqual(urllib.request.parse_http_list(string), list)
84
85 def test_URLError_reasonstr(self):
86 err = urllib.error.URLError('reason')
87 self.assertIn(err.reason, str(err))
88
89
90 class RequestHdrsTests(unittest.TestCase):
91
92 def test_request_headers_dict(self):
93 """
94 The Request.headers dictionary is not a documented interface. It
95 should stay that way, because the complete set of headers are only
96 accessible through the .get_header(), .has_header(), .header_items()
97 interface. However, .headers pre-dates those methods, and so real code
98 will be using the dictionary.
99
100 The introduction in 2.4 of those methods was a mistake for the same
101 reason: code that previously saw all (urllib2 user)-provided headers in
102 .headers now sees only a subset.
103
104 """
105 url = "http://example.com"
106 self.assertEqual(Request(url,
107 headers={"Spam-eggs": "blah"}
108 ).headers["Spam-eggs"], "blah")
109 self.assertEqual(Request(url,
110 headers={"spam-EggS": "blah"}
111 ).headers["Spam-eggs"], "blah")
112
113 def test_request_headers_methods(self):
114 """
115 Note the case normalization of header names here, to
116 .capitalize()-case. This should be preserved for
117 backwards-compatibility. (In the HTTP case, normalization to
118 .title()-case is done by urllib2 before sending headers to
119 http.client).
120
121 Note that e.g. r.has_header("spam-EggS") is currently False, and
122 r.get_header("spam-EggS") returns None, but that could be changed in
123 future.
124
125 Method r.remove_header should remove items both from r.headers and
126 r.unredirected_hdrs dictionaries
127 """
128 url = "http://example.com"
129 req = Request(url, headers={"Spam-eggs": "blah"})
130 self.assertTrue(req.has_header("Spam-eggs"))
131 self.assertEqual(req.header_items(), [('Spam-eggs', 'blah')])
132
133 req.add_header("Foo-Bar", "baz")
134 self.assertEqual(sorted(req.header_items()),
135 [('Foo-bar', 'baz'), ('Spam-eggs', 'blah')])
136 self.assertFalse(req.has_header("Not-there"))
137 self.assertIsNone(req.get_header("Not-there"))
138 self.assertEqual(req.get_header("Not-there", "default"), "default")
139
140 req.remove_header("Spam-eggs")
141 self.assertFalse(req.has_header("Spam-eggs"))
142
143 req.add_unredirected_header("Unredirected-spam", "Eggs")
144 self.assertTrue(req.has_header("Unredirected-spam"))
145
146 req.remove_header("Unredirected-spam")
147 self.assertFalse(req.has_header("Unredirected-spam"))
148
149 def test_password_manager(self):
150 mgr = urllib.request.HTTPPasswordMgr()
151 add = mgr.add_password
152 find_user_pass = mgr.find_user_password
153
154 add("Some Realm", "http://example.com/", "joe", "password")
155 add("Some Realm", "http://example.com/ni", "ni", "ni")
156 add("Some Realm", "http://c.example.com:3128", "3", "c")
157 add("Some Realm", "d.example.com", "4", "d")
158 add("Some Realm", "e.example.com:3128", "5", "e")
159
160 # For the same realm, password set the highest path is the winner.
161 self.assertEqual(find_user_pass("Some Realm", "example.com"),
162 ('joe', 'password'))
163 self.assertEqual(find_user_pass("Some Realm", "http://example.com/ni"),
164 ('joe', 'password'))
165 self.assertEqual(find_user_pass("Some Realm", "http://example.com"),
166 ('joe', 'password'))
167 self.assertEqual(find_user_pass("Some Realm", "http://example.com/"),
168 ('joe', 'password'))
169 self.assertEqual(find_user_pass("Some Realm",
170 "http://example.com/spam"),
171 ('joe', 'password'))
172 self.assertEqual(find_user_pass("Some Realm",
173 "http://example.com/spam/spam"),
174 ('joe', 'password'))
175
176 # You can have different passwords for different paths.
177
178 add("c", "http://example.com/foo", "foo", "ni")
179 add("c", "http://example.com/bar", "bar", "nini")
180 add("c", "http://example.com/foo/bar", "foobar", "nibar")
181
182 self.assertEqual(find_user_pass("c", "http://example.com/foo"),
183 ('foo', 'ni'))
184 self.assertEqual(find_user_pass("c", "http://example.com/bar"),
185 ('bar', 'nini'))
186 self.assertEqual(find_user_pass("c", "http://example.com/foo/"),
187 ('foo', 'ni'))
188 self.assertEqual(find_user_pass("c", "http://example.com/foo/bar"),
189 ('foo', 'ni'))
190 self.assertEqual(find_user_pass("c", "http://example.com/foo/baz"),
191 ('foo', 'ni'))
192 self.assertEqual(find_user_pass("c", "http://example.com/foobar"),
193 (None, None))
194
195 add("c", "http://example.com/baz/", "baz", "ninini")
196
197 self.assertEqual(find_user_pass("c", "http://example.com/baz"),
198 (None, None))
199 self.assertEqual(find_user_pass("c", "http://example.com/baz/"),
200 ('baz', 'ninini'))
201 self.assertEqual(find_user_pass("c", "http://example.com/baz/bar"),
202 ('baz', 'ninini'))
203
204 # For the same path, newer password should be considered.
205
206 add("b", "http://example.com/", "first", "blah")
207 add("b", "http://example.com/", "second", "spam")
208
209 self.assertEqual(find_user_pass("b", "http://example.com/"),
210 ('second', 'spam'))
211
212 # No special relationship between a.example.com and example.com:
213
214 add("a", "http://example.com", "1", "a")
215 self.assertEqual(find_user_pass("a", "http://example.com/"),
216 ('1', 'a'))
217
218 self.assertEqual(find_user_pass("a", "http://a.example.com/"),
219 (None, None))
220
221 # Ports:
222
223 self.assertEqual(find_user_pass("Some Realm", "c.example.com"),
224 (None, None))
225 self.assertEqual(find_user_pass("Some Realm", "c.example.com:3128"),
226 ('3', 'c'))
227 self.assertEqual(
228 find_user_pass("Some Realm", "http://c.example.com:3128"),
229 ('3', 'c'))
230 self.assertEqual(find_user_pass("Some Realm", "d.example.com"),
231 ('4', 'd'))
232 self.assertEqual(find_user_pass("Some Realm", "e.example.com:3128"),
233 ('5', 'e'))
234
235 def test_password_manager_default_port(self):
236 """
237 The point to note here is that we can't guess the default port if
238 there's no scheme. This applies to both add_password and
239 find_user_password.
240 """
241 mgr = urllib.request.HTTPPasswordMgr()
242 add = mgr.add_password
243 find_user_pass = mgr.find_user_password
244 add("f", "http://g.example.com:80", "10", "j")
245 add("g", "http://h.example.com", "11", "k")
246 add("h", "i.example.com:80", "12", "l")
247 add("i", "j.example.com", "13", "m")
248 self.assertEqual(find_user_pass("f", "g.example.com:100"),
249 (None, None))
250 self.assertEqual(find_user_pass("f", "g.example.com:80"),
251 ('10', 'j'))
252 self.assertEqual(find_user_pass("f", "g.example.com"),
253 (None, None))
254 self.assertEqual(find_user_pass("f", "http://g.example.com:100"),
255 (None, None))
256 self.assertEqual(find_user_pass("f", "http://g.example.com:80"),
257 ('10', 'j'))
258 self.assertEqual(find_user_pass("f", "http://g.example.com"),
259 ('10', 'j'))
260 self.assertEqual(find_user_pass("g", "h.example.com"), ('11', 'k'))
261 self.assertEqual(find_user_pass("g", "h.example.com:80"), ('11', 'k'))
262 self.assertEqual(find_user_pass("g", "http://h.example.com:80"),
263 ('11', 'k'))
264 self.assertEqual(find_user_pass("h", "i.example.com"), (None, None))
265 self.assertEqual(find_user_pass("h", "i.example.com:80"), ('12', 'l'))
266 self.assertEqual(find_user_pass("h", "http://i.example.com:80"),
267 ('12', 'l'))
268 self.assertEqual(find_user_pass("i", "j.example.com"), ('13', 'm'))
269 self.assertEqual(find_user_pass("i", "j.example.com:80"),
270 (None, None))
271 self.assertEqual(find_user_pass("i", "http://j.example.com"),
272 ('13', 'm'))
273 self.assertEqual(find_user_pass("i", "http://j.example.com:80"),
274 (None, None))
275
276
277 class MockOpener:
278 addheaders = []
279
280 def open(self, req, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
281 self.req, self.data, self.timeout = req, data, timeout
282
283 def error(self, proto, *args):
284 self.proto, self.args = proto, args
285
286
287 class MockFile:
288 def read(self, count=None):
289 pass
290
291 def readline(self, count=None):
292 pass
293
294 def close(self):
295 pass
296
297
298 class MockHeaders(dict):
299 def getheaders(self, name):
300 return list(self.values())
301
302
303 class MockResponse(io.StringIO):
304 def __init__(self, code, msg, headers, data, url=None):
305 io.StringIO.__init__(self, data)
306 self.code, self.msg, self.headers, self.url = code, msg, headers, url
307
308 def info(self):
309 return self.headers
310
311 def geturl(self):
312 return self.url
313
314
315 class MockCookieJar:
316 def add_cookie_header(self, request):
317 self.ach_req = request
318
319 def extract_cookies(self, response, request):
320 self.ec_req, self.ec_r = request, response
321
322
323 class FakeMethod:
324 def __init__(self, meth_name, action, handle):
325 self.meth_name = meth_name
326 self.handle = handle
327 self.action = action
328
329 def __call__(self, *args):
330 return self.handle(self.meth_name, self.action, *args)
331
332
333 class MockHTTPResponse(io.IOBase):
334 def __init__(self, fp, msg, status, reason):
335 self.fp = fp
336 self.msg = msg
337 self.status = status
338 self.reason = reason
339 self.code = 200
340
341 def read(self):
342 return ''
343
344 def info(self):
345 return {}
346
347 def geturl(self):
348 return self.url
349
350
351 class MockHTTPClass:
352 def __init__(self):
353 self.level = 0
354 self.req_headers = []
355 self.data = None
356 self.raise_on_endheaders = False
357 self.sock = None
358 self._tunnel_headers = {}
359
360 def __call__(self, host, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
361 self.host = host
362 self.timeout = timeout
363 return self
364
365 def set_debuglevel(self, level):
366 self.level = level
367
368 def set_tunnel(self, host, port=None, headers=None):
369 self._tunnel_host = host
370 self._tunnel_port = port
371 if headers:
372 self._tunnel_headers = headers
373 else:
374 self._tunnel_headers.clear()
375
376 def request(self, method, url, body=None, headers=None, *,
377 encode_chunked=False):
378 self.method = method
379 self.selector = url
380 if headers is not None:
381 self.req_headers += headers.items()
382 self.req_headers.sort()
383 if body:
384 self.data = body
385 self.encode_chunked = encode_chunked
386 if self.raise_on_endheaders:
387 raise OSError()
388
389 def getresponse(self):
390 return MockHTTPResponse(MockFile(), {}, 200, "OK")
391
392 def close(self):
393 pass
394
395
396 class MockHandler:
397 # useful for testing handler machinery
398 # see add_ordered_mock_handlers() docstring
399 handler_order = 500
400
401 def __init__(self, methods):
402 self._define_methods(methods)
403
404 def _define_methods(self, methods):
405 for spec in methods:
406 if len(spec) == 2:
407 name, action = spec
408 else:
409 name, action = spec, None
410 meth = FakeMethod(name, action, self.handle)
411 setattr(self.__class__, name, meth)
412
413 def handle(self, fn_name, action, *args, **kwds):
414 self.parent.calls.append((self, fn_name, args, kwds))
415 if action is None:
416 return None
417 elif action == "return self":
418 return self
419 elif action == "return response":
420 res = MockResponse(200, "OK", {}, "")
421 return res
422 elif action == "return request":
423 return Request("http://blah/")
424 elif action.startswith("error"):
425 code = action[action.rfind(" ")+1:]
426 try:
427 code = int(code)
428 except ValueError:
429 pass
430 res = MockResponse(200, "OK", {}, "")
431 return self.parent.error("http", args[0], res, code, "", {})
432 elif action == "raise":
433 raise urllib.error.URLError("blah")
434 assert False
435
436 def close(self):
437 pass
438
439 def add_parent(self, parent):
440 self.parent = parent
441 self.parent.calls = []
442
443 def __lt__(self, other):
444 if not hasattr(other, "handler_order"):
445 # No handler_order, leave in original order. Yuck.
446 return True
447 return self.handler_order < other.handler_order
448
449
450 def add_ordered_mock_handlers(opener, meth_spec):
451 """Create MockHandlers and add them to an OpenerDirector.
452
453 meth_spec: list of lists of tuples and strings defining methods to define
454 on handlers. eg:
455
456 [["http_error", "ftp_open"], ["http_open"]]
457
458 defines methods .http_error() and .ftp_open() on one handler, and
459 .http_open() on another. These methods just record their arguments and
460 return None. Using a tuple instead of a string causes the method to
461 perform some action (see MockHandler.handle()), eg:
462
463 [["http_error"], [("http_open", "return request")]]
464
465 defines .http_error() on one handler (which simply returns None), and
466 .http_open() on another handler, which returns a Request object.
467
468 """
469 handlers = []
470 count = 0
471 for meths in meth_spec:
472 class MockHandlerSubclass(MockHandler):
473 pass
474
475 h = MockHandlerSubclass(meths)
476 h.handler_order += count
477 h.add_parent(opener)
478 count = count + 1
479 handlers.append(h)
480 opener.add_handler(h)
481 return handlers
482
483
484 def build_test_opener(*handler_instances):
485 opener = OpenerDirector()
486 for h in handler_instances:
487 opener.add_handler(h)
488 return opener
489
490
491 class MockHTTPHandler(urllib.request.HTTPHandler):
492 # Very simple mock HTTP handler with no special behavior other than using a mock HTTP connection
493
494 def __init__(self, debuglevel=None):
495 super(MockHTTPHandler, self).__init__(debuglevel=debuglevel)
496 self.httpconn = MockHTTPClass()
497
498 def http_open(self, req):
499 return self.do_open(self.httpconn, req)
500
501
502 class MockHTTPHandlerRedirect(urllib.request.BaseHandler):
503 # useful for testing redirections and auth
504 # sends supplied headers and code as first response
505 # sends 200 OK as second response
506 def __init__(self, code, headers):
507 self.code = code
508 self.headers = headers
509 self.reset()
510
511 def reset(self):
512 self._count = 0
513 self.requests = []
514
515 def http_open(self, req):
516 import email, copy
517 self.requests.append(copy.deepcopy(req))
518 if self._count == 0:
519 self._count = self._count + 1
520 name = http.client.responses[self.code]
521 msg = email.message_from_string(self.headers)
522 return self.parent.error(
523 "http", req, MockFile(), self.code, name, msg)
524 else:
525 self.req = req
526 msg = email.message_from_string("\r\n\r\n")
527 return MockResponse(200, "OK", msg, "", req.get_full_url())
528
529
530 if hasattr(http.client, 'HTTPSConnection'):
531 class MockHTTPSHandler(urllib.request.HTTPSHandler):
532 # Useful for testing the Proxy-Authorization request by verifying the
533 # properties of httpcon
534
535 def __init__(self, debuglevel=None, context=None, check_hostname=None):
536 super(MockHTTPSHandler, self).__init__(debuglevel, context, check_hostname)
537 self.httpconn = MockHTTPClass()
538
539 def https_open(self, req):
540 return self.do_open(self.httpconn, req)
541
542
543 class MockHTTPHandlerCheckAuth(urllib.request.BaseHandler):
544 # useful for testing auth
545 # sends supplied code response
546 # checks if auth header is specified in request
547 def __init__(self, code):
548 self.code = code
549 self.has_auth_header = False
550
551 def reset(self):
552 self.has_auth_header = False
553
554 def http_open(self, req):
555 if req.has_header('Authorization'):
556 self.has_auth_header = True
557 name = http.client.responses[self.code]
558 return MockResponse(self.code, name, MockFile(), "", req.get_full_url())
559
560
561
562 class MockPasswordManager:
563 def add_password(self, realm, uri, user, password):
564 self.realm = realm
565 self.url = uri
566 self.user = user
567 self.password = password
568
569 def find_user_password(self, realm, authuri):
570 self.target_realm = realm
571 self.target_url = authuri
572 return self.user, self.password
573
574
575 class OpenerDirectorTests(unittest.TestCase):
576
577 def test_add_non_handler(self):
578 class NonHandler(object):
579 pass
580 self.assertRaises(TypeError,
581 OpenerDirector().add_handler, NonHandler())
582
583 def test_badly_named_methods(self):
584 # test work-around for three methods that accidentally follow the
585 # naming conventions for handler methods
586 # (*_open() / *_request() / *_response())
587
588 # These used to call the accidentally-named methods, causing a
589 # TypeError in real code; here, returning self from these mock
590 # methods would either cause no exception, or AttributeError.
591
592 from urllib.error import URLError
593
594 o = OpenerDirector()
595 meth_spec = [
596 [("do_open", "return self"), ("proxy_open", "return self")],
597 [("redirect_request", "return self")],
598 ]
599 add_ordered_mock_handlers(o, meth_spec)
600 o.add_handler(urllib.request.UnknownHandler())
601 for scheme in "do", "proxy", "redirect":
602 self.assertRaises(URLError, o.open, scheme+"://example.com/")
603
604 def test_handled(self):
605 # handler returning non-None means no more handlers will be called
606 o = OpenerDirector()
607 meth_spec = [
608 ["http_open", "ftp_open", "http_error_302"],
609 ["ftp_open"],
610 [("http_open", "return self")],
611 [("http_open", "return self")],
612 ]
613 handlers = add_ordered_mock_handlers(o, meth_spec)
614
615 req = Request("http://example.com/")
616 r = o.open(req)
617 # Second .http_open() gets called, third doesn't, since second returned
618 # non-None. Handlers without .http_open() never get any methods called
619 # on them.
620 # In fact, second mock handler defining .http_open() returns self
621 # (instead of response), which becomes the OpenerDirector's return
622 # value.
623 self.assertEqual(r, handlers[2])
624 calls = [(handlers[0], "http_open"), (handlers[2], "http_open")]
625 for expected, got in zip(calls, o.calls):
626 handler, name, args, kwds = got
627 self.assertEqual((handler, name), expected)
628 self.assertEqual(args, (req,))
629
630 def test_handler_order(self):
631 o = OpenerDirector()
632 handlers = []
633 for meths, handler_order in [([("http_open", "return self")], 500),
634 (["http_open"], 0)]:
635 class MockHandlerSubclass(MockHandler):
636 pass
637
638 h = MockHandlerSubclass(meths)
639 h.handler_order = handler_order
640 handlers.append(h)
641 o.add_handler(h)
642
643 o.open("http://example.com/")
644 # handlers called in reverse order, thanks to their sort order
645 self.assertEqual(o.calls[0][0], handlers[1])
646 self.assertEqual(o.calls[1][0], handlers[0])
647
648 def test_raise(self):
649 # raising URLError stops processing of request
650 o = OpenerDirector()
651 meth_spec = [
652 [("http_open", "raise")],
653 [("http_open", "return self")],
654 ]
655 handlers = add_ordered_mock_handlers(o, meth_spec)
656
657 req = Request("http://example.com/")
658 self.assertRaises(urllib.error.URLError, o.open, req)
659 self.assertEqual(o.calls, [(handlers[0], "http_open", (req,), {})])
660
661 def test_http_error(self):
662 # XXX http_error_default
663 # http errors are a special case
664 o = OpenerDirector()
665 meth_spec = [
666 [("http_open", "error 302")],
667 [("http_error_400", "raise"), "http_open"],
668 [("http_error_302", "return response"), "http_error_303",
669 "http_error"],
670 [("http_error_302")],
671 ]
672 handlers = add_ordered_mock_handlers(o, meth_spec)
673 req = Request("http://example.com/")
674 o.open(req)
675 assert len(o.calls) == 2
676 calls = [(handlers[0], "http_open", (req,)),
677 (handlers[2], "http_error_302",
678 (req, support.ALWAYS_EQ, 302, "", {}))]
679 for expected, got in zip(calls, o.calls):
680 handler, method_name, args = expected
681 self.assertEqual((handler, method_name), got[:2])
682 self.assertEqual(args, got[2])
683
684 def test_processors(self):
685 # *_request / *_response methods get called appropriately
686 o = OpenerDirector()
687 meth_spec = [
688 [("http_request", "return request"),
689 ("http_response", "return response")],
690 [("http_request", "return request"),
691 ("http_response", "return response")],
692 ]
693 handlers = add_ordered_mock_handlers(o, meth_spec)
694
695 req = Request("http://example.com/")
696 o.open(req)
697 # processor methods are called on *all* handlers that define them,
698 # not just the first handler that handles the request
699 calls = [
700 (handlers[0], "http_request"), (handlers[1], "http_request"),
701 (handlers[0], "http_response"), (handlers[1], "http_response")]
702
703 for i, (handler, name, args, kwds) in enumerate(o.calls):
704 if i < 2:
705 # *_request
706 self.assertEqual((handler, name), calls[i])
707 self.assertEqual(len(args), 1)
708 self.assertIsInstance(args[0], Request)
709 else:
710 # *_response
711 self.assertEqual((handler, name), calls[i])
712 self.assertEqual(len(args), 2)
713 self.assertIsInstance(args[0], Request)
714 # response from opener.open is None, because there's no
715 # handler that defines http_open to handle it
716 if args[1] is not None:
717 self.assertIsInstance(args[1], MockResponse)
718
719
720 def sanepathname2url(path):
721 urlpath = urllib.request.pathname2url(path)
722 if os.name == "nt" and urlpath.startswith("///"):
723 urlpath = urlpath[2:]
724 # XXX don't ask me about the mac...
725 return urlpath
726
727
728 class HandlerTests(unittest.TestCase, ExtraAssertions):
729
730 def test_ftp(self):
731 class MockFTPWrapper:
732 def __init__(self, data):
733 self.data = data
734
735 def retrfile(self, filename, filetype):
736 self.filename, self.filetype = filename, filetype
737 return io.StringIO(self.data), len(self.data)
738
739 def close(self):
740 pass
741
742 class NullFTPHandler(urllib.request.FTPHandler):
743 def __init__(self, data):
744 self.data = data
745
746 def connect_ftp(self, user, passwd, host, port, dirs,
747 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
748 self.user, self.passwd = user, passwd
749 self.host, self.port = host, port
750 self.dirs = dirs
751 self.ftpwrapper = MockFTPWrapper(self.data)
752 return self.ftpwrapper
753
754 import ftplib
755 data = "rheum rhaponicum"
756 h = NullFTPHandler(data)
757 h.parent = MockOpener()
758
759 for url, host, port, user, passwd, type_, dirs, filename, mimetype in [
760 ("ftp://localhost/foo/bar/baz.html",
761 "localhost", ftplib.FTP_PORT, "", "", "I",
762 ["foo", "bar"], "baz.html", "text/html"),
763 ("ftp://parrot@localhost/foo/bar/baz.html",
764 "localhost", ftplib.FTP_PORT, "parrot", "", "I",
765 ["foo", "bar"], "baz.html", "text/html"),
766 ("ftp://%25parrot@localhost/foo/bar/baz.html",
767 "localhost", ftplib.FTP_PORT, "%parrot", "", "I",
768 ["foo", "bar"], "baz.html", "text/html"),
769 ("ftp://%2542parrot@localhost/foo/bar/baz.html",
770 "localhost", ftplib.FTP_PORT, "%42parrot", "", "I",
771 ["foo", "bar"], "baz.html", "text/html"),
772 ("ftp://localhost:80/foo/bar/",
773 "localhost", 80, "", "", "D",
774 ["foo", "bar"], "", None),
775 ("ftp://localhost/baz.gif;type=a",
776 "localhost", ftplib.FTP_PORT, "", "", "A",
777 [], "baz.gif", "image/gif"),
778 ]:
779 req = Request(url)
780 req.timeout = None
781 r = h.ftp_open(req)
782 # ftp authentication not yet implemented by FTPHandler
783 self.assertEqual(h.user, user)
784 self.assertEqual(h.passwd, passwd)
785 self.assertEqual(h.host, socket.gethostbyname(host))
786 self.assertEqual(h.port, port)
787 self.assertEqual(h.dirs, dirs)
788 self.assertEqual(h.ftpwrapper.filename, filename)
789 self.assertEqual(h.ftpwrapper.filetype, type_)
790 headers = r.info()
791 self.assertEqual(headers.get("Content-type"), mimetype)
792 self.assertEqual(int(headers["Content-length"]), len(data))
793 r.close()
794
795 def test_file(self):
796 import email.utils
797 h = urllib.request.FileHandler()
798 o = h.parent = MockOpener()
799
800 TESTFN = os_helper.TESTFN
801 urlpath = sanepathname2url(os.path.abspath(TESTFN))
802 towrite = b"hello, world\n"
803 urls = [
804 "file://localhost%s" % urlpath,
805 "file://%s" % urlpath,
806 "file://%s%s" % (socket.gethostbyname('localhost'), urlpath),
807 ]
808 try:
809 localaddr = socket.gethostbyname(socket.gethostname())
810 except socket.gaierror:
811 localaddr = ''
812 if localaddr:
813 urls.append("file://%s%s" % (localaddr, urlpath))
814
815 for url in urls:
816 f = open(TESTFN, "wb")
817 try:
818 try:
819 f.write(towrite)
820 finally:
821 f.close()
822
823 r = h.file_open(Request(url))
824 try:
825 data = r.read()
826 headers = r.info()
827 respurl = r.geturl()
828 finally:
829 r.close()
830 stats = os.stat(TESTFN)
831 modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
832 finally:
833 os.remove(TESTFN)
834 self.assertEqual(data, towrite)
835 self.assertEqual(headers["Content-type"], "text/plain")
836 self.assertEqual(headers["Content-length"], "13")
837 self.assertEqual(headers["Last-modified"], modified)
838 self.assertEqual(respurl, url)
839
840 for url in [
841 "file://localhost:80%s" % urlpath,
842 "file:///file_does_not_exist.txt",
843 "file://not-a-local-host.com//dir/file.txt",
844 "file://%s:80%s/%s" % (socket.gethostbyname('localhost'),
845 os.getcwd(), TESTFN),
846 "file://somerandomhost.ontheinternet.com%s/%s" %
847 (os.getcwd(), TESTFN),
848 ]:
849 try:
850 f = open(TESTFN, "wb")
851 try:
852 f.write(towrite)
853 finally:
854 f.close()
855
856 self.assertRaises(urllib.error.URLError,
857 h.file_open, Request(url))
858 finally:
859 os.remove(TESTFN)
860
861 h = urllib.request.FileHandler()
862 o = h.parent = MockOpener()
863 # XXXX why does // mean ftp (and /// mean not ftp!), and where
864 # is file: scheme specified? I think this is really a bug, and
865 # what was intended was to distinguish between URLs like:
866 # file:/blah.txt (a file)
867 # file://localhost/blah.txt (a file)
868 # file:///blah.txt (a file)
869 # file://ftp.example.com/blah.txt (an ftp URL)
870 for url, ftp in [
871 ("file://ftp.example.com//foo.txt", False),
872 ("file://ftp.example.com///foo.txt", False),
873 ("file://ftp.example.com/foo.txt", False),
874 ("file://somehost//foo/something.txt", False),
875 ("file://localhost//foo/something.txt", False),
876 ]:
877 req = Request(url)
878 try:
879 h.file_open(req)
880 except urllib.error.URLError:
881 self.assertFalse(ftp)
882 else:
883 self.assertIs(o.req, req)
884 self.assertEqual(req.type, "ftp")
885 self.assertEqual(req.type == "ftp", ftp)
886
887 def test_http(self):
888
889 h = urllib.request.AbstractHTTPHandler()
890 o = h.parent = MockOpener()
891
892 url = "http://example.com/"
893 for method, data in [("GET", None), ("POST", b"blah")]:
894 req = Request(url, data, {"Foo": "bar"})
895 req.timeout = None
896 req.add_unredirected_header("Spam", "eggs")
897 http = MockHTTPClass()
898 r = h.do_open(http, req)
899
900 # result attributes
901 r.read; r.readline # wrapped MockFile methods
902 r.info; r.geturl # addinfourl methods
903 r.code, r.msg == 200, "OK" # added from MockHTTPClass.getreply()
904 hdrs = r.info()
905 hdrs.get; hdrs.__contains__ # r.info() gives dict from .getreply()
906 self.assertEqual(r.geturl(), url)
907
908 self.assertEqual(http.host, "example.com")
909 self.assertEqual(http.level, 0)
910 self.assertEqual(http.method, method)
911 self.assertEqual(http.selector, "/")
912 self.assertEqual(http.req_headers,
913 [("Connection", "close"),
914 ("Foo", "bar"), ("Spam", "eggs")])
915 self.assertEqual(http.data, data)
916
917 # check OSError converted to URLError
918 http.raise_on_endheaders = True
919 self.assertRaises(urllib.error.URLError, h.do_open, http, req)
920
921 # Check for TypeError on POST data which is str.
922 req = Request("http://example.com/","badpost")
923 self.assertRaises(TypeError, h.do_request_, req)
924
925 # check adding of standard headers
926 o.addheaders = [("Spam", "eggs")]
927 for data in b"", None: # POST, GET
928 req = Request("http://example.com/", data)
929 r = MockResponse(200, "OK", {}, "")
930 newreq = h.do_request_(req)
931 if data is None: # GET
932 self.assertNotIn("Content-length", req.unredirected_hdrs)
933 self.assertNotIn("Content-type", req.unredirected_hdrs)
934 else: # POST
935 self.assertEqual(req.unredirected_hdrs["Content-length"], "0")
936 self.assertEqual(req.unredirected_hdrs["Content-type"],
937 "application/x-www-form-urlencoded")
938 # XXX the details of Host could be better tested
939 self.assertEqual(req.unredirected_hdrs["Host"], "example.com")
940 self.assertEqual(req.unredirected_hdrs["Spam"], "eggs")
941
942 # don't clobber existing headers
943 req.add_unredirected_header("Content-length", "foo")
944 req.add_unredirected_header("Content-type", "bar")
945 req.add_unredirected_header("Host", "baz")
946 req.add_unredirected_header("Spam", "foo")
947 newreq = h.do_request_(req)
948 self.assertEqual(req.unredirected_hdrs["Content-length"], "foo")
949 self.assertEqual(req.unredirected_hdrs["Content-type"], "bar")
950 self.assertEqual(req.unredirected_hdrs["Host"], "baz")
951 self.assertEqual(req.unredirected_hdrs["Spam"], "foo")
952
953 def test_http_body_file(self):
954 # A regular file - chunked encoding is used unless Content Length is
955 # already set.
956
957 h = urllib.request.AbstractHTTPHandler()
958 o = h.parent = MockOpener()
959
960 file_obj = tempfile.NamedTemporaryFile(mode='w+b', delete=False)
961 file_path = file_obj.name
962 file_obj.close()
963 self.addCleanup(os.unlink, file_path)
964
965 with open(file_path, "rb") as f:
966 req = Request("http://example.com/", f, {})
967 newreq = h.do_request_(req)
968 te = newreq.get_header('Transfer-encoding')
969 self.assertEqual(te, "chunked")
970 self.assertFalse(newreq.has_header('Content-length'))
971
972 with open(file_path, "rb") as f:
973 req = Request("http://example.com/", f, {"Content-Length": 30})
974 newreq = h.do_request_(req)
975 self.assertEqual(int(newreq.get_header('Content-length')), 30)
976 self.assertFalse(newreq.has_header("Transfer-encoding"))
977
978 def test_http_body_fileobj(self):
979 # A file object - chunked encoding is used
980 # unless Content Length is already set.
981 # (Note that there are some subtle differences to a regular
982 # file, that is why we are testing both cases.)
983
984 h = urllib.request.AbstractHTTPHandler()
985 o = h.parent = MockOpener()
986 file_obj = io.BytesIO()
987
988 req = Request("http://example.com/", file_obj, {})
989 newreq = h.do_request_(req)
990 self.assertEqual(newreq.get_header('Transfer-encoding'), 'chunked')
991 self.assertFalse(newreq.has_header('Content-length'))
992
993 headers = {"Content-Length": 30}
994 req = Request("http://example.com/", file_obj, headers)
995 newreq = h.do_request_(req)
996 self.assertEqual(int(newreq.get_header('Content-length')), 30)
997 self.assertFalse(newreq.has_header("Transfer-encoding"))
998
999 file_obj.close()
1000
1001 @requires_subprocess()
1002 def test_http_body_pipe(self):
1003 # A file reading from a pipe.
1004 # A pipe cannot be seek'ed. There is no way to determine the
1005 # content length up front. Thus, do_request_() should fall
1006 # back to Transfer-encoding chunked.
1007
1008 h = urllib.request.AbstractHTTPHandler()
1009 o = h.parent = MockOpener()
1010
1011 cmd = [sys.executable, "-c", r"pass"]
1012 for headers in {}, {"Content-Length": 30}:
1013 with subprocess.Popen(cmd, stdout=subprocess.PIPE) as proc:
1014 req = Request("http://example.com/", proc.stdout, headers)
1015 newreq = h.do_request_(req)
1016 if not headers:
1017 self.assertEqual(newreq.get_header('Content-length'), None)
1018 self.assertEqual(newreq.get_header('Transfer-encoding'),
1019 'chunked')
1020 else:
1021 self.assertEqual(int(newreq.get_header('Content-length')),
1022 30)
1023
1024 def test_http_body_iterable(self):
1025 # Generic iterable. There is no way to determine the content
1026 # length up front. Fall back to Transfer-encoding chunked.
1027
1028 h = urllib.request.AbstractHTTPHandler()
1029 o = h.parent = MockOpener()
1030
1031 def iterable_body():
1032 yield b"one"
1033
1034 for headers in {}, {"Content-Length": 11}:
1035 req = Request("http://example.com/", iterable_body(), headers)
1036 newreq = h.do_request_(req)
1037 if not headers:
1038 self.assertEqual(newreq.get_header('Content-length'), None)
1039 self.assertEqual(newreq.get_header('Transfer-encoding'),
1040 'chunked')
1041 else:
1042 self.assertEqual(int(newreq.get_header('Content-length')), 11)
1043
1044 def test_http_body_empty_seq(self):
1045 # Zero-length iterable body should be treated like any other iterable
1046 h = urllib.request.AbstractHTTPHandler()
1047 h.parent = MockOpener()
1048 req = h.do_request_(Request("http://example.com/", ()))
1049 self.assertEqual(req.get_header("Transfer-encoding"), "chunked")
1050 self.assertFalse(req.has_header("Content-length"))
1051
1052 def test_http_body_array(self):
1053 # array.array Iterable - Content Length is calculated
1054
1055 h = urllib.request.AbstractHTTPHandler()
1056 o = h.parent = MockOpener()
1057
1058 iterable_array = array.array("I",[1,2,3,4])
1059
1060 for headers in {}, {"Content-Length": 16}:
1061 req = Request("http://example.com/", iterable_array, headers)
1062 newreq = h.do_request_(req)
1063 self.assertEqual(int(newreq.get_header('Content-length')),16)
1064
1065 def test_http_handler_global_debuglevel(self):
1066 with mock.patch.object(http.client.HTTPConnection, 'debuglevel', 6):
1067 o = OpenerDirector()
1068 h = MockHTTPHandler()
1069 o.add_handler(h)
1070 o.open("http://www.example.com")
1071 self.assertEqual(h._debuglevel, 6)
1072
1073 def test_http_handler_local_debuglevel(self):
1074 o = OpenerDirector()
1075 h = MockHTTPHandler(debuglevel=5)
1076 o.add_handler(h)
1077 o.open("http://www.example.com")
1078 self.assertEqual(h._debuglevel, 5)
1079
1080 @unittest.skipUnless(hasattr(http.client, 'HTTPSConnection'), 'HTTPSConnection required for HTTPS tests.')
1081 def test_https_handler_global_debuglevel(self):
1082 with mock.patch.object(http.client.HTTPSConnection, 'debuglevel', 7):
1083 o = OpenerDirector()
1084 h = MockHTTPSHandler()
1085 o.add_handler(h)
1086 o.open("https://www.example.com")
1087 self.assertEqual(h._debuglevel, 7)
1088
1089 @unittest.skipUnless(hasattr(http.client, 'HTTPSConnection'), 'HTTPSConnection required for HTTPS tests.')
1090 def test_https_handler_local_debuglevel(self):
1091 o = OpenerDirector()
1092 h = MockHTTPSHandler(debuglevel=4)
1093 o.add_handler(h)
1094 o.open("https://www.example.com")
1095 self.assertEqual(h._debuglevel, 4)
1096
1097 def test_http_doubleslash(self):
1098 # Checks the presence of any unnecessary double slash in url does not
1099 # break anything. Previously, a double slash directly after the host
1100 # could cause incorrect parsing.
1101 h = urllib.request.AbstractHTTPHandler()
1102 h.parent = MockOpener()
1103
1104 data = b""
1105 ds_urls = [
1106 "http://example.com/foo/bar/baz.html",
1107 "http://example.com//foo/bar/baz.html",
1108 "http://example.com/foo//bar/baz.html",
1109 "http://example.com/foo/bar//baz.html"
1110 ]
1111
1112 for ds_url in ds_urls:
1113 ds_req = Request(ds_url, data)
1114
1115 # Check whether host is determined correctly if there is no proxy
1116 np_ds_req = h.do_request_(ds_req)
1117 self.assertEqual(np_ds_req.unredirected_hdrs["Host"], "example.com")
1118
1119 # Check whether host is determined correctly if there is a proxy
1120 ds_req.set_proxy("someproxy:3128", None)
1121 p_ds_req = h.do_request_(ds_req)
1122 self.assertEqual(p_ds_req.unredirected_hdrs["Host"], "example.com")
1123
1124 def test_full_url_setter(self):
1125 # Checks to ensure that components are set correctly after setting the
1126 # full_url of a Request object
1127
1128 urls = [
1129 'http://example.com?foo=bar#baz',
1130 'http://example.com?foo=bar&spam=eggs#bash',
1131 'http://example.com',
1132 ]
1133
1134 # testing a reusable request instance, but the url parameter is
1135 # required, so just use a dummy one to instantiate
1136 r = Request('http://example.com')
1137 for url in urls:
1138 r.full_url = url
1139 parsed = urlparse(url)
1140
1141 self.assertEqual(r.get_full_url(), url)
1142 # full_url setter uses splittag to split into components.
1143 # splittag sets the fragment as None while urlparse sets it to ''
1144 self.assertEqual(r.fragment or '', parsed.fragment)
1145 self.assertEqual(urlparse(r.get_full_url()).query, parsed.query)
1146
1147 def test_full_url_deleter(self):
1148 r = Request('http://www.example.com')
1149 del r.full_url
1150 self.assertIsNone(r.full_url)
1151 self.assertIsNone(r.fragment)
1152 self.assertEqual(r.selector, '')
1153
1154 def test_fixpath_in_weirdurls(self):
1155 # Issue4493: urllib2 to supply '/' when to urls where path does not
1156 # start with'/'
1157
1158 h = urllib.request.AbstractHTTPHandler()
1159 h.parent = MockOpener()
1160
1161 weird_url = 'http://www.python.org?getspam'
1162 req = Request(weird_url)
1163 newreq = h.do_request_(req)
1164 self.assertEqual(newreq.host, 'www.python.org')
1165 self.assertEqual(newreq.selector, '/?getspam')
1166
1167 url_without_path = 'http://www.python.org'
1168 req = Request(url_without_path)
1169 newreq = h.do_request_(req)
1170 self.assertEqual(newreq.host, 'www.python.org')
1171 self.assertEqual(newreq.selector, '')
1172
1173 def test_errors(self):
1174 h = urllib.request.HTTPErrorProcessor()
1175 o = h.parent = MockOpener()
1176
1177 url = "http://example.com/"
1178 req = Request(url)
1179 # all 2xx are passed through
1180 r = MockResponse(200, "OK", {}, "", url)
1181 newr = h.http_response(req, r)
1182 self.assertIs(r, newr)
1183 self.assertNotHasAttr(o, "proto") # o.error not called
1184 r = MockResponse(202, "Accepted", {}, "", url)
1185 newr = h.http_response(req, r)
1186 self.assertIs(r, newr)
1187 self.assertNotHasAttr(o, "proto") # o.error not called
1188 r = MockResponse(206, "Partial content", {}, "", url)
1189 newr = h.http_response(req, r)
1190 self.assertIs(r, newr)
1191 self.assertNotHasAttr(o, "proto") # o.error not called
1192 # anything else calls o.error (and MockOpener returns None, here)
1193 r = MockResponse(502, "Bad gateway", {}, "", url)
1194 self.assertIsNone(h.http_response(req, r))
1195 self.assertEqual(o.proto, "http") # o.error called
1196 self.assertEqual(o.args, (req, r, 502, "Bad gateway", {}))
1197
1198 def test_cookies(self):
1199 cj = MockCookieJar()
1200 h = urllib.request.HTTPCookieProcessor(cj)
1201 h.parent = MockOpener()
1202
1203 req = Request("http://example.com/")
1204 r = MockResponse(200, "OK", {}, "")
1205 newreq = h.http_request(req)
1206 self.assertIs(cj.ach_req, req)
1207 self.assertIs(cj.ach_req, newreq)
1208 self.assertEqual(req.origin_req_host, "example.com")
1209 self.assertFalse(req.unverifiable)
1210 newr = h.http_response(req, r)
1211 self.assertIs(cj.ec_req, req)
1212 self.assertIs(cj.ec_r, r)
1213 self.assertIs(r, newr)
1214
1215 def test_redirect(self):
1216 from_url = "http://example.com/a.html"
1217 to_url = "http://example.com/b.html"
1218 h = urllib.request.HTTPRedirectHandler()
1219 o = h.parent = MockOpener()
1220
1221 # ordinary redirect behaviour
1222 for code in 301, 302, 303, 307, 308:
1223 for data in None, "blah\nblah\n":
1224 method = getattr(h, "http_error_%s" % code)
1225 req = Request(from_url, data)
1226 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1227 req.add_header("Nonsense", "viking=withhold")
1228 if data is not None:
1229 req.add_header("Content-Length", str(len(data)))
1230 req.add_unredirected_header("Spam", "spam")
1231 try:
1232 method(req, MockFile(), code, "Blah",
1233 MockHeaders({"location": to_url}))
1234 except urllib.error.HTTPError as err:
1235 # 307 and 308 in response to POST require user OK
1236 self.assertIn(code, (307, 308))
1237 self.assertIsNotNone(data)
1238 err.close()
1239 self.assertEqual(o.req.get_full_url(), to_url)
1240 try:
1241 self.assertEqual(o.req.get_method(), "GET")
1242 except AttributeError:
1243 self.assertFalse(o.req.data)
1244
1245 # now it's a GET, there should not be headers regarding content
1246 # (possibly dragged from before being a POST)
1247 headers = [x.lower() for x in o.req.headers]
1248 self.assertNotIn("content-length", headers)
1249 self.assertNotIn("content-type", headers)
1250
1251 self.assertEqual(o.req.headers["Nonsense"],
1252 "viking=withhold")
1253 self.assertNotIn("Spam", o.req.headers)
1254 self.assertNotIn("Spam", o.req.unredirected_hdrs)
1255
1256 # loop detection
1257 req = Request(from_url)
1258 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1259
1260 def redirect(h, req, url=to_url):
1261 h.http_error_302(req, MockFile(), 302, "Blah",
1262 MockHeaders({"location": url}))
1263 # Note that the *original* request shares the same record of
1264 # redirections with the sub-requests caused by the redirections.
1265
1266 # detect infinite loop redirect of a URL to itself
1267 req = Request(from_url, origin_req_host="example.com")
1268 count = 0
1269 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1270 try:
1271 while 1:
1272 redirect(h, req, "http://example.com/")
1273 count = count + 1
1274 except urllib.error.HTTPError as err:
1275 # don't stop until max_repeats, because cookies may introduce state
1276 self.assertEqual(count, urllib.request.HTTPRedirectHandler.max_repeats)
1277 err.close()
1278
1279 # detect endless non-repeating chain of redirects
1280 req = Request(from_url, origin_req_host="example.com")
1281 count = 0
1282 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1283 try:
1284 while 1:
1285 redirect(h, req, "http://example.com/%d" % count)
1286 count = count + 1
1287 except urllib.error.HTTPError as err:
1288 self.assertEqual(count,
1289 urllib.request.HTTPRedirectHandler.max_redirections)
1290 err.close()
1291
1292 def test_invalid_redirect(self):
1293 from_url = "http://example.com/a.html"
1294 valid_schemes = ['http','https','ftp']
1295 invalid_schemes = ['file','imap','ldap']
1296 schemeless_url = "example.com/b.html"
1297 h = urllib.request.HTTPRedirectHandler()
1298 o = h.parent = MockOpener()
1299 req = Request(from_url)
1300 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1301
1302 for scheme in invalid_schemes:
1303 invalid_url = scheme + '://' + schemeless_url
1304 with self.assertRaises(urllib.error.HTTPError) as cm:
1305 h.http_error_302(
1306 req, MockFile(), 302, "Security Loophole",
1307 MockHeaders({"location": invalid_url}))
1308 cm.exception.close()
1309
1310 for scheme in valid_schemes:
1311 valid_url = scheme + '://' + schemeless_url
1312 h.http_error_302(req, MockFile(), 302, "That's fine",
1313 MockHeaders({"location": valid_url}))
1314 self.assertEqual(o.req.get_full_url(), valid_url)
1315
1316 def test_relative_redirect(self):
1317 from_url = "http://example.com/a.html"
1318 relative_url = "/b.html"
1319 h = urllib.request.HTTPRedirectHandler()
1320 o = h.parent = MockOpener()
1321 req = Request(from_url)
1322 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1323
1324 valid_url = urllib.parse.urljoin(from_url,relative_url)
1325 h.http_error_302(req, MockFile(), 302, "That's fine",
1326 MockHeaders({"location": valid_url}))
1327 self.assertEqual(o.req.get_full_url(), valid_url)
1328
1329 def test_cookie_redirect(self):
1330 # cookies shouldn't leak into redirected requests
1331 from http.cookiejar import CookieJar
1332 from test.test_http_cookiejar import interact_netscape
1333
1334 cj = CookieJar()
1335 interact_netscape(cj, "http://www.example.com/", "spam=eggs")
1336 hh = MockHTTPHandlerRedirect(302, "Location: http://www.cracker.com/\r\n\r\n")
1337 hdeh = urllib.request.HTTPDefaultErrorHandler()
1338 hrh = urllib.request.HTTPRedirectHandler()
1339 cp = urllib.request.HTTPCookieProcessor(cj)
1340 o = build_test_opener(hh, hdeh, hrh, cp)
1341 o.open("http://www.example.com/")
1342 self.assertFalse(hh.req.has_header("Cookie"))
1343
1344 def test_redirect_fragment(self):
1345 redirected_url = 'http://www.example.com/index.html#OK\r\n\r\n'
1346 hh = MockHTTPHandlerRedirect(302, 'Location: ' + redirected_url)
1347 hdeh = urllib.request.HTTPDefaultErrorHandler()
1348 hrh = urllib.request.HTTPRedirectHandler()
1349 o = build_test_opener(hh, hdeh, hrh)
1350 fp = o.open('http://www.example.com')
1351 self.assertEqual(fp.geturl(), redirected_url.strip())
1352
1353 def test_redirect_no_path(self):
1354 # Issue 14132: Relative redirect strips original path
1355
1356 # clear _opener global variable
1357 self.addCleanup(urllib.request.urlcleanup)
1358
1359 real_class = http.client.HTTPConnection
1360 response1 = b"HTTP/1.1 302 Found\r\nLocation: ?query\r\n\r\n"
1361 http.client.HTTPConnection = test_urllib.fakehttp(response1)
1362 self.addCleanup(setattr, http.client, "HTTPConnection", real_class)
1363 urls = iter(("/path", "/path?query"))
1364 def request(conn, method, url, *pos, **kw):
1365 self.assertEqual(url, next(urls))
1366 real_class.request(conn, method, url, *pos, **kw)
1367 # Change response for subsequent connection
1368 conn.__class__.fakedata = b"HTTP/1.1 200 OK\r\n\r\nHello!"
1369 http.client.HTTPConnection.request = request
1370 fp = urllib.request.urlopen("http://python.org/path")
1371 self.assertEqual(fp.geturl(), "http://python.org/path?query")
1372
1373 def test_redirect_encoding(self):
1374 # Some characters in the redirect target may need special handling,
1375 # but most ASCII characters should be treated as already encoded
1376 class Handler(urllib.request.HTTPHandler):
1377 def http_open(self, req):
1378 result = self.do_open(self.connection, req)
1379 self.last_buf = self.connection.buf
1380 # Set up a normal response for the next request
1381 self.connection = test_urllib.fakehttp(
1382 b'HTTP/1.1 200 OK\r\n'
1383 b'Content-Length: 3\r\n'
1384 b'\r\n'
1385 b'123'
1386 )
1387 return result
1388 handler = Handler()
1389 opener = urllib.request.build_opener(handler)
1390 tests = (
1391 (b'/p\xC3\xA5-dansk/', b'/p%C3%A5-dansk/'),
1392 (b'/spaced%20path/', b'/spaced%20path/'),
1393 (b'/spaced path/', b'/spaced%20path/'),
1394 (b'/?p\xC3\xA5-dansk', b'/?p%C3%A5-dansk'),
1395 )
1396 for [location, result] in tests:
1397 with self.subTest(repr(location)):
1398 handler.connection = test_urllib.fakehttp(
1399 b'HTTP/1.1 302 Redirect\r\n'
1400 b'Location: ' + location + b'\r\n'
1401 b'\r\n'
1402 )
1403 response = opener.open('http://example.com/')
1404 expected = b'GET ' + result + b' '
1405 request = handler.last_buf
1406 self.assertStartsWith(request, expected)
1407
1408 def test_redirect_head_request(self):
1409 from_url = "http://example.com/a.html"
1410 to_url = "http://example.com/b.html"
1411 h = urllib.request.HTTPRedirectHandler()
1412 req = Request(from_url, method="HEAD")
1413 fp = MockFile()
1414 new_req = h.redirect_request(req, fp, 302, "Found", {}, to_url)
1415 self.assertEqual(new_req.get_method(), "HEAD")
1416
1417 def test_proxy(self):
1418 u = "proxy.example.com:3128"
1419 for d in dict(http=u), dict(HTTP=u):
1420 o = OpenerDirector()
1421 ph = urllib.request.ProxyHandler(d)
1422 o.add_handler(ph)
1423 meth_spec = [
1424 [("http_open", "return response")]
1425 ]
1426 handlers = add_ordered_mock_handlers(o, meth_spec)
1427
1428 req = Request("http://acme.example.com/")
1429 self.assertEqual(req.host, "acme.example.com")
1430 o.open(req)
1431 self.assertEqual(req.host, u)
1432 self.assertEqual([(handlers[0], "http_open")],
1433 [tup[0:2] for tup in o.calls])
1434
1435 def test_proxy_no_proxy(self):
1436 env = self.enterContext(os_helper.EnvironmentVarGuard())
1437 env['no_proxy'] = 'python.org'
1438 o = OpenerDirector()
1439 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1440 o.add_handler(ph)
1441 req = Request("http://www.perl.org/")
1442 self.assertEqual(req.host, "www.perl.org")
1443 o.open(req)
1444 self.assertEqual(req.host, "proxy.example.com")
1445 req = Request("http://www.python.org")
1446 self.assertEqual(req.host, "www.python.org")
1447 o.open(req)
1448 self.assertEqual(req.host, "www.python.org")
1449
1450 def test_proxy_no_proxy_all(self):
1451 env = self.enterContext(os_helper.EnvironmentVarGuard())
1452 env['no_proxy'] = '*'
1453 o = OpenerDirector()
1454 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com"))
1455 o.add_handler(ph)
1456 req = Request("http://www.python.org")
1457 self.assertEqual(req.host, "www.python.org")
1458 o.open(req)
1459 self.assertEqual(req.host, "www.python.org")
1460
1461 def test_proxy_https(self):
1462 o = OpenerDirector()
1463 ph = urllib.request.ProxyHandler(dict(https="proxy.example.com:3128"))
1464 o.add_handler(ph)
1465 meth_spec = [
1466 [("https_open", "return response")]
1467 ]
1468 handlers = add_ordered_mock_handlers(o, meth_spec)
1469
1470 req = Request("https://www.example.com/")
1471 self.assertEqual(req.host, "www.example.com")
1472 o.open(req)
1473 self.assertEqual(req.host, "proxy.example.com:3128")
1474 self.assertEqual([(handlers[0], "https_open")],
1475 [tup[0:2] for tup in o.calls])
1476
1477 @unittest.skipUnless(hasattr(http.client, 'HTTPSConnection'), 'HTTPSConnection required for HTTPS tests.')
1478 def test_proxy_https_proxy_authorization(self):
1479 o = OpenerDirector()
1480 ph = urllib.request.ProxyHandler(dict(https='proxy.example.com:3128'))
1481 o.add_handler(ph)
1482 https_handler = MockHTTPSHandler()
1483 o.add_handler(https_handler)
1484 req = Request("https://www.example.com/")
1485 req.add_header("Proxy-Authorization", "FooBar")
1486 req.add_header("User-Agent", "Grail")
1487 self.assertEqual(req.host, "www.example.com")
1488 self.assertIsNone(req._tunnel_host)
1489 o.open(req)
1490 # Verify Proxy-Authorization gets tunneled to request.
1491 # httpsconn req_headers do not have the Proxy-Authorization header but
1492 # the req will have.
1493 self.assertNotIn(("Proxy-Authorization", "FooBar"),
1494 https_handler.httpconn.req_headers)
1495 self.assertIn(("User-Agent", "Grail"),
1496 https_handler.httpconn.req_headers)
1497 self.assertIsNotNone(req._tunnel_host)
1498 self.assertEqual(req.host, "proxy.example.com:3128")
1499 self.assertEqual(req.get_header("Proxy-authorization"), "FooBar")
1500
1501 @unittest.skipUnless(os.name == "nt", "only relevant for Windows")
1502 def test_winreg_proxy_bypass(self):
1503 proxy_override = "www.example.com;*.example.net; 192.168.0.1"
1504 proxy_bypass = _proxy_bypass_winreg_override
1505 for host in ("www.example.com", "www.example.net", "192.168.0.1"):
1506 self.assertTrue(proxy_bypass(host, proxy_override),
1507 "expected bypass of %s to be true" % host)
1508
1509 for host in ("example.com", "www.example.org", "example.net",
1510 "192.168.0.2"):
1511 self.assertFalse(proxy_bypass(host, proxy_override),
1512 "expected bypass of %s to be False" % host)
1513
1514 # check intranet address bypass
1515 proxy_override = "example.com; <local>"
1516 self.assertTrue(proxy_bypass("example.com", proxy_override),
1517 "expected bypass of %s to be true" % host)
1518 self.assertFalse(proxy_bypass("example.net", proxy_override),
1519 "expected bypass of %s to be False" % host)
1520 for host in ("test", "localhost"):
1521 self.assertTrue(proxy_bypass(host, proxy_override),
1522 "expect <local> to bypass intranet address '%s'"
1523 % host)
1524
1525 @unittest.skipUnless(sys.platform == 'darwin', "only relevant for OSX")
1526 def test_osx_proxy_bypass(self):
1527 bypass = {
1528 'exclude_simple': False,
1529 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.10',
1530 '10.0/16']
1531 }
1532 # Check hosts that should trigger the proxy bypass
1533 for host in ('foo.bar', 'www.bar.com', '127.0.0.1', '10.10.0.1',
1534 '10.0.0.1'):
1535 self.assertTrue(_proxy_bypass_macosx_sysconf(host, bypass),
1536 'expected bypass of %s to be True' % host)
1537 # Check hosts that should not trigger the proxy bypass
1538 for host in ('abc.foo.bar', 'bar.com', '127.0.0.2', '10.11.0.1',
1539 'notinbypass'):
1540 self.assertFalse(_proxy_bypass_macosx_sysconf(host, bypass),
1541 'expected bypass of %s to be False' % host)
1542
1543 # Check the exclude_simple flag
1544 bypass = {'exclude_simple': True, 'exceptions': []}
1545 self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass))
1546
1547 # Check that invalid prefix lengths are ignored
1548 bypass = {
1549 'exclude_simple': False,
1550 'exceptions': [ '10.0.0.0/40', '172.19.10.0/24' ]
1551 }
1552 host = '172.19.10.5'
1553 self.assertTrue(_proxy_bypass_macosx_sysconf(host, bypass),
1554 'expected bypass of %s to be True' % host)
1555 host = '10.0.1.5'
1556 self.assertFalse(_proxy_bypass_macosx_sysconf(host, bypass),
1557 'expected bypass of %s to be False' % host)
1558
1559 def check_basic_auth(self, headers, realm):
1560 with self.subTest(realm=realm, headers=headers):
1561 opener = OpenerDirector()
1562 password_manager = MockPasswordManager()
1563 auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
1564 body = '\r\n'.join(headers) + '\r\n\r\n'
1565 http_handler = MockHTTPHandlerRedirect(401, body)
1566 opener.add_handler(auth_handler)
1567 opener.add_handler(http_handler)
1568 self._test_basic_auth(opener, auth_handler, "Authorization",
1569 realm, http_handler, password_manager,
1570 "http://acme.example.com/protected",
1571 "http://acme.example.com/protected")
1572
1573 def test_basic_auth(self):
1574 realm = "[email protected]"
1575 realm2 = "[email protected]"
1576 basic = f'Basic realm="{realm}"'
1577 basic2 = f'Basic realm="{realm2}"'
1578 other_no_realm = 'Otherscheme xxx'
1579 digest = (f'Digest realm="{realm2}", '
1580 f'qop="auth, auth-int", '
1581 f'nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", '
1582 f'opaque="5ccc069c403ebaf9f0171e9517f40e41"')
1583 for realm_str in (
1584 # test "quote" and 'quote'
1585 f'Basic realm="{realm}"',
1586 f"Basic realm='{realm}'",
1587
1588 # charset is ignored
1589 f'Basic realm="{realm}", charset="UTF-8"',
1590
1591 # Multiple challenges per header
1592 f'{basic}, {basic2}',
1593 f'{basic}, {other_no_realm}',
1594 f'{other_no_realm}, {basic}',
1595 f'{basic}, {digest}',
1596 f'{digest}, {basic}',
1597 ):
1598 headers = [f'WWW-Authenticate: {realm_str}']
1599 self.check_basic_auth(headers, realm)
1600
1601 # no quote: expect a warning
1602 with warnings_helper.check_warnings(("Basic Auth Realm was unquoted",
1603 UserWarning)):
1604 headers = [f'WWW-Authenticate: Basic realm={realm}']
1605 self.check_basic_auth(headers, realm)
1606
1607 # Multiple headers: one challenge per header.
1608 # Use the first Basic realm.
1609 for challenges in (
1610 [basic, basic2],
1611 [basic, digest],
1612 [digest, basic],
1613 ):
1614 headers = [f'WWW-Authenticate: {challenge}'
1615 for challenge in challenges]
1616 self.check_basic_auth(headers, realm)
1617
1618 def test_proxy_basic_auth(self):
1619 opener = OpenerDirector()
1620 ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128"))
1621 opener.add_handler(ph)
1622 password_manager = MockPasswordManager()
1623 auth_handler = urllib.request.ProxyBasicAuthHandler(password_manager)
1624 realm = "ACME Networks"
1625 http_handler = MockHTTPHandlerRedirect(
1626 407, 'Proxy-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
1627 opener.add_handler(auth_handler)
1628 opener.add_handler(http_handler)
1629 self._test_basic_auth(opener, auth_handler, "Proxy-authorization",
1630 realm, http_handler, password_manager,
1631 "http://acme.example.com:3128/protected",
1632 "proxy.example.com:3128",
1633 )
1634
1635 def test_basic_and_digest_auth_handlers(self):
1636 # HTTPDigestAuthHandler raised an exception if it couldn't handle a 40*
1637 # response (https://bugs.python.org/issue1479302), where it should instead
1638 # return None to allow another handler (especially
1639 # HTTPBasicAuthHandler) to handle the response.
1640
1641 # Also (https://bugs.python.org/issue14797027, RFC 2617 section 1.2), we must
1642 # try digest first (since it's the strongest auth scheme), so we record
1643 # order of calls here to check digest comes first:
1644 class RecordingOpenerDirector(OpenerDirector):
1645 def __init__(self):
1646 OpenerDirector.__init__(self)
1647 self.recorded = []
1648
1649 def record(self, info):
1650 self.recorded.append(info)
1651
1652 class TestDigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
1653 def http_error_401(self, *args, **kwds):
1654 self.parent.record("digest")
1655 urllib.request.HTTPDigestAuthHandler.http_error_401(self,
1656 *args, **kwds)
1657
1658 class TestBasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
1659 def http_error_401(self, *args, **kwds):
1660 self.parent.record("basic")
1661 urllib.request.HTTPBasicAuthHandler.http_error_401(self,
1662 *args, **kwds)
1663
1664 opener = RecordingOpenerDirector()
1665 password_manager = MockPasswordManager()
1666 digest_handler = TestDigestAuthHandler(password_manager)
1667 basic_handler = TestBasicAuthHandler(password_manager)
1668 realm = "ACME Networks"
1669 http_handler = MockHTTPHandlerRedirect(
1670 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
1671 opener.add_handler(basic_handler)
1672 opener.add_handler(digest_handler)
1673 opener.add_handler(http_handler)
1674
1675 # check basic auth isn't blocked by digest handler failing
1676 self._test_basic_auth(opener, basic_handler, "Authorization",
1677 realm, http_handler, password_manager,
1678 "http://acme.example.com/protected",
1679 "http://acme.example.com/protected",
1680 )
1681 # check digest was tried before basic (twice, because
1682 # _test_basic_auth called .open() twice)
1683 self.assertEqual(opener.recorded, ["digest", "basic"]*2)
1684
1685 def test_unsupported_auth_digest_handler(self):
1686 opener = OpenerDirector()
1687 # While using DigestAuthHandler
1688 digest_auth_handler = urllib.request.HTTPDigestAuthHandler(None)
1689 http_handler = MockHTTPHandlerRedirect(
1690 401, 'WWW-Authenticate: Kerberos\r\n\r\n')
1691 opener.add_handler(digest_auth_handler)
1692 opener.add_handler(http_handler)
1693 self.assertRaises(ValueError, opener.open, "http://www.example.com")
1694
1695 def test_unsupported_auth_basic_handler(self):
1696 # While using BasicAuthHandler
1697 opener = OpenerDirector()
1698 basic_auth_handler = urllib.request.HTTPBasicAuthHandler(None)
1699 http_handler = MockHTTPHandlerRedirect(
1700 401, 'WWW-Authenticate: NTLM\r\n\r\n')
1701 opener.add_handler(basic_auth_handler)
1702 opener.add_handler(http_handler)
1703 self.assertRaises(ValueError, opener.open, "http://www.example.com")
1704
1705 def _test_basic_auth(self, opener, auth_handler, auth_header,
1706 realm, http_handler, password_manager,
1707 request_url, protected_url):
1708 import base64
1709 user, password = "wile", "coyote"
1710
1711 # .add_password() fed through to password manager
1712 auth_handler.add_password(realm, request_url, user, password)
1713 self.assertEqual(realm, password_manager.realm)
1714 self.assertEqual(request_url, password_manager.url)
1715 self.assertEqual(user, password_manager.user)
1716 self.assertEqual(password, password_manager.password)
1717
1718 opener.open(request_url)
1719
1720 # should have asked the password manager for the username/password
1721 self.assertEqual(password_manager.target_realm, realm)
1722 self.assertEqual(password_manager.target_url, protected_url)
1723
1724 # expect one request without authorization, then one with
1725 self.assertEqual(len(http_handler.requests), 2)
1726 self.assertFalse(http_handler.requests[0].has_header(auth_header))
1727 userpass = bytes('%s:%s' % (user, password), "ascii")
1728 auth_hdr_value = ('Basic ' +
1729 base64.encodebytes(userpass).strip().decode())
1730 self.assertEqual(http_handler.requests[1].get_header(auth_header),
1731 auth_hdr_value)
1732 self.assertEqual(http_handler.requests[1].unredirected_hdrs[auth_header],
1733 auth_hdr_value)
1734 # if the password manager can't find a password, the handler won't
1735 # handle the HTTP auth error
1736 password_manager.user = password_manager.password = None
1737 http_handler.reset()
1738 opener.open(request_url)
1739 self.assertEqual(len(http_handler.requests), 1)
1740 self.assertFalse(http_handler.requests[0].has_header(auth_header))
1741
1742 def test_basic_prior_auth_auto_send(self):
1743 # Assume already authenticated if is_authenticated=True
1744 # for APIs like Github that don't return 401
1745
1746 user, password = "wile", "coyote"
1747 request_url = "http://acme.example.com/protected"
1748
1749 http_handler = MockHTTPHandlerCheckAuth(200)
1750
1751 pwd_manager = HTTPPasswordMgrWithPriorAuth()
1752 auth_prior_handler = HTTPBasicAuthHandler(pwd_manager)
1753 auth_prior_handler.add_password(
1754 None, request_url, user, password, is_authenticated=True)
1755
1756 self.assertTrue(pwd_manager.is_authenticated(request_url))
1757 self.assertTrue(pwd_manager.is_authenticated(request_url + '/nested'))
1758 self.assertFalse(pwd_manager.is_authenticated(request_url + 'plain'))
1759
1760 opener = OpenerDirector()
1761 opener.add_handler(auth_prior_handler)
1762 opener.add_handler(http_handler)
1763
1764 opener.open(request_url)
1765
1766 # expect request to be sent with auth header
1767 self.assertTrue(http_handler.has_auth_header)
1768
1769 def test_basic_prior_auth_send_after_first_success(self):
1770 # Auto send auth header after authentication is successful once
1771
1772 user, password = 'wile', 'coyote'
1773 request_url = 'http://acme.example.com/protected'
1774 realm = 'ACME'
1775
1776 pwd_manager = HTTPPasswordMgrWithPriorAuth()
1777 auth_prior_handler = HTTPBasicAuthHandler(pwd_manager)
1778 auth_prior_handler.add_password(realm, request_url, user, password)
1779
1780 is_auth = pwd_manager.is_authenticated(request_url)
1781 self.assertFalse(is_auth)
1782
1783 opener = OpenerDirector()
1784 opener.add_handler(auth_prior_handler)
1785
1786 http_handler = MockHTTPHandlerRedirect(
1787 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % None)
1788 opener.add_handler(http_handler)
1789
1790 opener.open(request_url)
1791
1792 is_auth = pwd_manager.is_authenticated(request_url)
1793 self.assertTrue(is_auth)
1794
1795 http_handler = MockHTTPHandlerCheckAuth(200)
1796 self.assertFalse(http_handler.has_auth_header)
1797
1798 opener = OpenerDirector()
1799 opener.add_handler(auth_prior_handler)
1800 opener.add_handler(http_handler)
1801
1802 # After getting 200 from MockHTTPHandler
1803 # Next request sends header in the first request
1804 opener.open(request_url)
1805
1806 # expect request to be sent with auth header
1807 self.assertTrue(http_handler.has_auth_header)
1808
1809 def test_http_closed(self):
1810 """Test the connection is cleaned up when the response is closed"""
1811 for (transfer, data) in (
1812 ("Connection: close", b"data"),
1813 ("Transfer-Encoding: chunked", b"4\r\ndata\r\n0\r\n\r\n"),
1814 ("Content-Length: 4", b"data"),
1815 ):
1816 header = "HTTP/1.1 200 OK\r\n{}\r\n\r\n".format(transfer)
1817 conn = test_urllib.fakehttp(header.encode() + data)
1818 handler = urllib.request.AbstractHTTPHandler()
1819 req = Request("http://dummy/")
1820 req.timeout = None
1821 with handler.do_open(conn, req) as resp:
1822 resp.read()
1823 self.assertTrue(conn.fakesock.closed,
1824 "Connection not closed with {!r}".format(transfer))
1825
1826 def test_invalid_closed(self):
1827 """Test the connection is cleaned up after an invalid response"""
1828 conn = test_urllib.fakehttp(b"")
1829 handler = urllib.request.AbstractHTTPHandler()
1830 req = Request("http://dummy/")
1831 req.timeout = None
1832 with self.assertRaises(http.client.BadStatusLine):
1833 handler.do_open(conn, req)
1834 self.assertTrue(conn.fakesock.closed, "Connection not closed")
1835
1836
1837 class MiscTests(unittest.TestCase, ExtraAssertions):
1838
1839 def opener_has_handler(self, opener, handler_class):
1840 self.assertTrue(any(h.__class__ == handler_class
1841 for h in opener.handlers))
1842
1843 def test_build_opener(self):
1844 class MyHTTPHandler(urllib.request.HTTPHandler):
1845 pass
1846
1847 class FooHandler(urllib.request.BaseHandler):
1848 def foo_open(self):
1849 pass
1850
1851 class BarHandler(urllib.request.BaseHandler):
1852 def bar_open(self):
1853 pass
1854
1855 build_opener = urllib.request.build_opener
1856
1857 o = build_opener(FooHandler, BarHandler)
1858 self.opener_has_handler(o, FooHandler)
1859 self.opener_has_handler(o, BarHandler)
1860
1861 # can take a mix of classes and instances
1862 o = build_opener(FooHandler, BarHandler())
1863 self.opener_has_handler(o, FooHandler)
1864 self.opener_has_handler(o, BarHandler)
1865
1866 # subclasses of default handlers override default handlers
1867 o = build_opener(MyHTTPHandler)
1868 self.opener_has_handler(o, MyHTTPHandler)
1869
1870 # a particular case of overriding: default handlers can be passed
1871 # in explicitly
1872 o = build_opener()
1873 self.opener_has_handler(o, urllib.request.HTTPHandler)
1874 o = build_opener(urllib.request.HTTPHandler)
1875 self.opener_has_handler(o, urllib.request.HTTPHandler)
1876 o = build_opener(urllib.request.HTTPHandler())
1877 self.opener_has_handler(o, urllib.request.HTTPHandler)
1878
1879 # Issue2670: multiple handlers sharing the same base class
1880 class MyOtherHTTPHandler(urllib.request.HTTPHandler):
1881 pass
1882
1883 o = build_opener(MyHTTPHandler, MyOtherHTTPHandler)
1884 self.opener_has_handler(o, MyHTTPHandler)
1885 self.opener_has_handler(o, MyOtherHTTPHandler)
1886
1887 def test_HTTPError_interface(self):
1888 """
1889 Issue 13211 reveals that HTTPError didn't implement the URLError
1890 interface even though HTTPError is a subclass of URLError.
1891 """
1892 msg = 'something bad happened'
1893 url = code = fp = None
1894 hdrs = 'Content-Length: 42'
1895 err = urllib.error.HTTPError(url, code, msg, hdrs, fp)
1896 self.assertHasAttr(err, 'reason')
1897 self.assertEqual(err.reason, 'something bad happened')
1898 self.assertHasAttr(err, 'headers')
1899 self.assertEqual(err.headers, 'Content-Length: 42')
1900 expected_errmsg = 'HTTP Error %s: %s' % (err.code, err.msg)
1901 self.assertEqual(str(err), expected_errmsg)
1902 expected_errmsg = '<HTTPError %s: %r>' % (err.code, err.msg)
1903 self.assertEqual(repr(err), expected_errmsg)
1904 err.close()
1905
1906 def test_gh_98778(self):
1907 x = urllib.error.HTTPError("url", 405, "METHOD NOT ALLOWED", None, None)
1908 self.assertEqual(getattr(x, "__notes__", ()), ())
1909 self.assertIsInstance(x.fp.read(), bytes)
1910 x.close()
1911
1912 def test_parse_proxy(self):
1913 parse_proxy_test_cases = [
1914 ('proxy.example.com',
1915 (None, None, None, 'proxy.example.com')),
1916 ('proxy.example.com:3128',
1917 (None, None, None, 'proxy.example.com:3128')),
1918 ('proxy.example.com', (None, None, None, 'proxy.example.com')),
1919 ('proxy.example.com:3128',
1920 (None, None, None, 'proxy.example.com:3128')),
1921 # The authority component may optionally include userinfo
1922 # (assumed to be # username:password):
1923 ('joe:[email protected]',
1924 (None, 'joe', 'password', 'proxy.example.com')),
1925 ('joe:[email protected]:3128',
1926 (None, 'joe', 'password', 'proxy.example.com:3128')),
1927 #Examples with URLS
1928 ('http://proxy.example.com/',
1929 ('http', None, None, 'proxy.example.com')),
1930 ('http://proxy.example.com:3128/',
1931 ('http', None, None, 'proxy.example.com:3128')),
1932 ('http://joe:[email protected]/',
1933 ('http', 'joe', 'password', 'proxy.example.com')),
1934 ('http://joe:[email protected]:3128',
1935 ('http', 'joe', 'password', 'proxy.example.com:3128')),
1936 # Everything after the authority is ignored
1937 ('ftp://joe:[email protected]/rubbish:3128',
1938 ('ftp', 'joe', 'password', 'proxy.example.com')),
1939 # Test for no trailing '/' case
1940 ('http://joe:[email protected]',
1941 ('http', 'joe', 'password', 'proxy.example.com')),
1942 # Testcases with '/' character in username, password
1943 ('http://user/name:password@localhost:22',
1944 ('http', 'user/name', 'password', 'localhost:22')),
1945 ('http://username:pass/word@localhost:22',
1946 ('http', 'username', 'pass/word', 'localhost:22')),
1947 ('http://user/name:pass/word@localhost:22',
1948 ('http', 'user/name', 'pass/word', 'localhost:22')),
1949 ]
1950
1951
1952 for tc, expected in parse_proxy_test_cases:
1953 self.assertEqual(_parse_proxy(tc), expected)
1954
1955 self.assertRaises(ValueError, _parse_proxy, 'file:/ftp.example.com'),
1956
1957 def test_unsupported_algorithm(self):
1958 handler = AbstractDigestAuthHandler()
1959 with self.assertRaises(ValueError) as exc:
1960 handler.get_algorithm_impls('invalid')
1961 self.assertEqual(
1962 str(exc.exception),
1963 "Unsupported digest authentication algorithm 'invalid'"
1964 )
1965
1966
1967 class RequestTests(unittest.TestCase):
1968 class PutRequest(Request):
1969 method = 'PUT'
1970
1971 def setUp(self):
1972 self.get = Request("http://www.python.org/~jeremy/")
1973 self.post = Request("http://www.python.org/~jeremy/",
1974 "data",
1975 headers={"X-Test": "test"})
1976 self.head = Request("http://www.python.org/~jeremy/", method='HEAD')
1977 self.put = self.PutRequest("http://www.python.org/~jeremy/")
1978 self.force_post = self.PutRequest("http://www.python.org/~jeremy/",
1979 method="POST")
1980
1981 def test_method(self):
1982 self.assertEqual("POST", self.post.get_method())
1983 self.assertEqual("GET", self.get.get_method())
1984 self.assertEqual("HEAD", self.head.get_method())
1985 self.assertEqual("PUT", self.put.get_method())
1986 self.assertEqual("POST", self.force_post.get_method())
1987
1988 def test_data(self):
1989 self.assertFalse(self.get.data)
1990 self.assertEqual("GET", self.get.get_method())
1991 self.get.data = "spam"
1992 self.assertTrue(self.get.data)
1993 self.assertEqual("POST", self.get.get_method())
1994
1995 # issue 16464
1996 # if we change data we need to remove content-length header
1997 # (cause it's most probably calculated for previous value)
1998 def test_setting_data_should_remove_content_length(self):
1999 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
2000 self.get.add_unredirected_header("Content-length", 42)
2001 self.assertEqual(42, self.get.unredirected_hdrs["Content-length"])
2002 self.get.data = "spam"
2003 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
2004
2005 # issue 17485 same for deleting data.
2006 def test_deleting_data_should_remove_content_length(self):
2007 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
2008 self.get.data = 'foo'
2009 self.get.add_unredirected_header("Content-length", 3)
2010 self.assertEqual(3, self.get.unredirected_hdrs["Content-length"])
2011 del self.get.data
2012 self.assertNotIn("Content-length", self.get.unredirected_hdrs)
2013
2014 def test_get_full_url(self):
2015 self.assertEqual("http://www.python.org/~jeremy/",
2016 self.get.get_full_url())
2017
2018 def test_selector(self):
2019 self.assertEqual("/~jeremy/", self.get.selector)
2020 req = Request("http://www.python.org/")
2021 self.assertEqual("/", req.selector)
2022
2023 def test_get_type(self):
2024 self.assertEqual("http", self.get.type)
2025
2026 def test_get_host(self):
2027 self.assertEqual("www.python.org", self.get.host)
2028
2029 def test_get_host_unquote(self):
2030 req = Request("http://www.%70ython.org/")
2031 self.assertEqual("www.python.org", req.host)
2032
2033 def test_proxy(self):
2034 self.assertFalse(self.get.has_proxy())
2035 self.get.set_proxy("www.perl.org", "http")
2036 self.assertTrue(self.get.has_proxy())
2037 self.assertEqual("www.python.org", self.get.origin_req_host)
2038 self.assertEqual("www.perl.org", self.get.host)
2039
2040 def test_wrapped_url(self):
2041 req = Request("<URL:http://www.python.org>")
2042 self.assertEqual("www.python.org", req.host)
2043
2044 def test_url_fragment(self):
2045 req = Request("http://www.python.org/?qs=query#fragment=true")
2046 self.assertEqual("/?qs=query", req.selector)
2047 req = Request("http://www.python.org/#fun=true")
2048 self.assertEqual("/", req.selector)
2049
2050 # Issue 11703: geturl() omits fragment in the original URL.
2051 url = 'http://docs.python.org/library/urllib2.html#OK'
2052 req = Request(url)
2053 self.assertEqual(req.get_full_url(), url)
2054
2055 def test_url_fullurl_get_full_url(self):
2056 urls = ['http://docs.python.org',
2057 'http://docs.python.org/library/urllib2.html#OK',
2058 'http://www.python.org/?qs=query#fragment=true']
2059 for url in urls:
2060 req = Request(url)
2061 self.assertEqual(req.get_full_url(), req.full_url)
2062
2063
2064 if __name__ == "__main__":
2065 unittest.main()