Debian Codegraph @

lib-python/3/test/test_urllib2.py

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