Changeset 391 for python/trunk/Lib/test/test_urllib2.py
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
python/trunk
-
Property svn:mergeinfo
set to
/python/vendor/Python-2.7.6 merged eligible /python/vendor/current merged eligible
-
Property svn:mergeinfo
set to
-
python/trunk/Lib/test/test_urllib2.py
r2 r391 25 25 # And more hacking to get it to work on MacOS. This assumes 26 26 # urllib.pathname2url works, unfortunately... 27 if os.name == 'mac': 28 fname = '/' + fname.replace(':', '/') 29 elif os.name == 'riscos': 27 if os.name == 'riscos': 30 28 import string 31 29 fname = os.expand(fname) … … 48 46 ('a="b\\"c", d="e\\,f", g="h\\\\i"', ['a="b"c"', 'd="e,f"', 'g="h\\i"'])] 49 47 for string, list in tests: 50 self.assertEqual s(urllib2.parse_http_list(string), list)48 self.assertEqual(urllib2.parse_http_list(string), list) 51 49 52 50 … … 289 287 self.level = level 290 288 291 def _set_tunnel(self, host, port=None, headers=None):289 def set_tunnel(self, host, port=None, headers=None): 292 290 self._tunnel_host = host 293 291 self._tunnel_port = port … … 296 294 else: 297 295 self._tunnel_headers.clear() 296 298 297 def request(self, method, url, body=None, headers=None): 299 298 self.method = method … … 307 306 import socket 308 307 raise socket.error() 308 309 309 def getresponse(self): 310 310 return MockHTTPResponse(MockFile(), {}, 200, "OK") 311 312 def close(self): 313 pass 311 314 312 315 class MockHandler: … … 581 584 self.assertEqual((handler, name), calls[i]) 582 585 self.assertEqual(len(args), 1) 583 self.assert _(isinstance(args[0], Request))586 self.assertIsInstance(args[0], Request) 584 587 else: 585 588 # *_response 586 589 self.assertEqual((handler, name), calls[i]) 587 590 self.assertEqual(len(args), 2) 588 self.assert _(isinstance(args[0], Request))591 self.assertIsInstance(args[0], Request) 589 592 # response from opener.open is None, because there's no 590 593 # handler that defines http_open to handle it 591 self.assert _(args[1] is None or594 self.assertTrue(args[1] is None or 592 595 isinstance(args[1], MockResponse)) 593 596 … … 609 612 self.filename, self.filetype = filename, filetype 610 613 return StringIO.StringIO(self.data), len(self.data) 614 def close(self): pass 611 615 612 616 class NullFTPHandler(urllib2.FTPHandler): … … 625 629 o = h.parent = MockOpener() 626 630 627 for url, host, port, type_, dirs, filename, mimetype in [631 for url, host, port, user, passwd, type_, dirs, filename, mimetype in [ 628 632 ("ftp://localhost/foo/bar/baz.html", 629 "localhost", ftplib.FTP_PORT, "I", 633 "localhost", ftplib.FTP_PORT, "", "", "I", 634 ["foo", "bar"], "baz.html", "text/html"), 635 ("ftp://parrot@localhost/foo/bar/baz.html", 636 "localhost", ftplib.FTP_PORT, "parrot", "", "I", 637 ["foo", "bar"], "baz.html", "text/html"), 638 ("ftp://%25parrot@localhost/foo/bar/baz.html", 639 "localhost", ftplib.FTP_PORT, "%parrot", "", "I", 640 ["foo", "bar"], "baz.html", "text/html"), 641 ("ftp://%2542parrot@localhost/foo/bar/baz.html", 642 "localhost", ftplib.FTP_PORT, "%42parrot", "", "I", 630 643 ["foo", "bar"], "baz.html", "text/html"), 631 644 ("ftp://localhost:80/foo/bar/", 632 "localhost", 80, " D",645 "localhost", 80, "", "", "D", 633 646 ["foo", "bar"], "", None), 634 647 ("ftp://localhost/baz.gif;type=a", 635 "localhost", ftplib.FTP_PORT, " A",648 "localhost", ftplib.FTP_PORT, "", "", "A", 636 649 [], "baz.gif", None), # XXX really this should guess image/gif 637 650 ]: … … 640 653 r = h.ftp_open(req) 641 654 # ftp authentication not yet implemented by FTPHandler 642 self.assert_(h.user == h.passwd == "") 655 self.assertEqual(h.user, user) 656 self.assertEqual(h.passwd, passwd) 643 657 self.assertEqual(h.host, socket.gethostbyname(host)) 644 658 self.assertEqual(h.port, port) … … 682 696 data = r.read() 683 697 headers = r.info() 684 newurl = r.geturl()698 respurl = r.geturl() 685 699 finally: 686 700 r.close() … … 693 707 self.assertEqual(headers["Content-length"], "13") 694 708 self.assertEqual(headers["Last-modified"], modified) 709 self.assertEqual(respurl, url) 695 710 696 711 for url in [ … … 728 743 # XXXX bug: fails with OSError, should be URLError 729 744 ("file://ftp.example.com/foo.txt", False), 745 ("file://somehost//foo/something.txt", True), 746 ("file://localhost//foo/something.txt", False), 730 747 ]: 731 748 req = Request(url) … … 734 751 # XXXX remove OSError when bug fixed 735 752 except (urllib2.URLError, OSError): 736 self.assert _(not ftp)753 self.assertTrue(not ftp) 737 754 else: 738 self.assert _(o.req is req)755 self.assertTrue(o.req is req) 739 756 self.assertEqual(req.type, "ftp") 757 self.assertEqual(req.type == "ftp", ftp) 740 758 741 759 def test_http(self): … … 780 798 newreq = h.do_request_(req) 781 799 if data is None: # GET 782 self.assert _("Content-length" not inreq.unredirected_hdrs)783 self.assert _("Content-type" not inreq.unredirected_hdrs)800 self.assertNotIn("Content-length", req.unredirected_hdrs) 801 self.assertNotIn("Content-type", req.unredirected_hdrs) 784 802 else: # POST 785 803 self.assertEqual(req.unredirected_hdrs["Content-length"], "0") … … 827 845 self.assertEqual(p_ds_req.unredirected_hdrs["Host"],"example.com") 828 846 847 def test_fixpath_in_weirdurls(self): 848 # Issue4493: urllib2 to supply '/' when to urls where path does not 849 # start with'/' 850 851 h = urllib2.AbstractHTTPHandler() 852 o = h.parent = MockOpener() 853 854 weird_url = 'http://www.python.org?getspam' 855 req = Request(weird_url) 856 newreq = h.do_request_(req) 857 self.assertEqual(newreq.get_host(),'www.python.org') 858 self.assertEqual(newreq.get_selector(),'/?getspam') 859 860 url_without_path = 'http://www.python.org' 861 req = Request(url_without_path) 862 newreq = h.do_request_(req) 863 self.assertEqual(newreq.get_host(),'www.python.org') 864 self.assertEqual(newreq.get_selector(),'') 865 829 866 def test_errors(self): 830 867 h = urllib2.HTTPErrorProcessor() … … 836 873 r = MockResponse(200, "OK", {}, "", url) 837 874 newr = h.http_response(req, r) 838 self.assert _(r is newr)839 self.assert _(not hasattr(o, "proto")) # o.error not called875 self.assertTrue(r is newr) 876 self.assertTrue(not hasattr(o, "proto")) # o.error not called 840 877 r = MockResponse(202, "Accepted", {}, "", url) 841 878 newr = h.http_response(req, r) 842 self.assert _(r is newr)843 self.assert _(not hasattr(o, "proto")) # o.error not called879 self.assertTrue(r is newr) 880 self.assertTrue(not hasattr(o, "proto")) # o.error not called 844 881 r = MockResponse(206, "Partial content", {}, "", url) 845 882 newr = h.http_response(req, r) 846 self.assert _(r is newr)847 self.assert _(not hasattr(o, "proto")) # o.error not called883 self.assertTrue(r is newr) 884 self.assertTrue(not hasattr(o, "proto")) # o.error not called 848 885 # anything else calls o.error (and MockOpener returns None, here) 849 886 r = MockResponse(502, "Bad gateway", {}, "", url) 850 self.assert _(h.http_response(req, r) is None)887 self.assertTrue(h.http_response(req, r) is None) 851 888 self.assertEqual(o.proto, "http") # o.error called 852 889 self.assertEqual(o.args, (req, r, 502, "Bad gateway", {})) … … 860 897 r = MockResponse(200, "OK", {}, "") 861 898 newreq = h.http_request(req) 862 self.assert _(cj.ach_req is req is newreq)863 self.assertEqual s(req.get_origin_req_host(), "example.com")864 self.assert _(not req.is_unverifiable())899 self.assertTrue(cj.ach_req is req is newreq) 900 self.assertEqual(req.get_origin_req_host(), "example.com") 901 self.assertTrue(not req.is_unverifiable()) 865 902 newr = h.http_response(req, r) 866 self.assert _(cj.ec_req is req)867 self.assert _(cj.ec_r is r is newr)903 self.assertTrue(cj.ec_req is req) 904 self.assertTrue(cj.ec_r is r is newr) 868 905 869 906 def test_redirect(self): … … 888 925 except urllib2.HTTPError: 889 926 # 307 in response to POST requires user OK 890 self.assert _(code == 307 and data is not None)927 self.assertTrue(code == 307 and data is not None) 891 928 self.assertEqual(o.req.get_full_url(), to_url) 892 929 try: 893 930 self.assertEqual(o.req.get_method(), "GET") 894 931 except AttributeError: 895 self.assert _(not o.req.has_data())932 self.assertTrue(not o.req.has_data()) 896 933 897 934 # now it's a GET, there should not be headers regarding content 898 935 # (possibly dragged from before being a POST) 899 936 headers = [x.lower() for x in o.req.headers] 900 self.assert True("content-length" not inheaders)901 self.assert True("content-type" not inheaders)937 self.assertNotIn("content-length", headers) 938 self.assertNotIn("content-type", headers) 902 939 903 940 self.assertEqual(o.req.headers["Nonsense"], 904 941 "viking=withhold") 905 self.assert _("Spam" not ino.req.headers)906 self.assert _("Spam" not ino.req.unredirected_hdrs)942 self.assertNotIn("Spam", o.req.headers) 943 self.assertNotIn("Spam", o.req.unredirected_hdrs) 907 944 908 945 # loop detection … … 939 976 urllib2.HTTPRedirectHandler.max_redirections) 940 977 978 def test_invalid_redirect(self): 979 from_url = "http://example.com/a.html" 980 valid_schemes = ['http', 'https', 'ftp'] 981 invalid_schemes = ['file', 'imap', 'ldap'] 982 schemeless_url = "example.com/b.html" 983 h = urllib2.HTTPRedirectHandler() 984 o = h.parent = MockOpener() 985 req = Request(from_url) 986 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT 987 988 for scheme in invalid_schemes: 989 invalid_url = scheme + '://' + schemeless_url 990 self.assertRaises(urllib2.HTTPError, h.http_error_302, 991 req, MockFile(), 302, "Security Loophole", 992 MockHeaders({"location": invalid_url})) 993 994 for scheme in valid_schemes: 995 valid_url = scheme + '://' + schemeless_url 996 h.http_error_302(req, MockFile(), 302, "That's fine", 997 MockHeaders({"location": valid_url})) 998 self.assertEqual(o.req.get_full_url(), valid_url) 999 941 1000 def test_cookie_redirect(self): 942 1001 # cookies shouldn't leak into redirected requests … … 953 1012 o = build_test_opener(hh, hdeh, hrh, cp) 954 1013 o.open("http://www.example.com/") 955 self.assert_(not hh.req.has_header("Cookie")) 1014 self.assertTrue(not hh.req.has_header("Cookie")) 1015 1016 def test_redirect_fragment(self): 1017 redirected_url = 'http://www.example.com/index.html#OK\r\n\r\n' 1018 hh = MockHTTPHandler(302, 'Location: ' + redirected_url) 1019 hdeh = urllib2.HTTPDefaultErrorHandler() 1020 hrh = urllib2.HTTPRedirectHandler() 1021 o = build_test_opener(hh, hdeh, hrh) 1022 fp = o.open('http://www.example.com') 1023 self.assertEqual(fp.geturl(), redirected_url.strip()) 956 1024 957 1025 def test_proxy(self): … … 1013 1081 req.add_header("User-Agent","Grail") 1014 1082 self.assertEqual(req.get_host(), "www.example.com") 1015 self.assert True(req._tunnel_host is None)1083 self.assertIsNone(req._tunnel_host) 1016 1084 r = o.open(req) 1017 1085 # Verify Proxy-Authorization gets tunneled to request. 1018 1086 # httpsconn req_headers do not have the Proxy-Authorization header but 1019 1087 # the req will have. 1020 self.assert False(("Proxy-Authorization","FooBar") in1088 self.assertNotIn(("Proxy-Authorization","FooBar"), 1021 1089 https_handler.httpconn.req_headers) 1022 self.assert True(("User-Agent","Grail") in1023 1024 self.assert False(req._tunnel_host is None)1090 self.assertIn(("User-Agent","Grail"), 1091 https_handler.httpconn.req_headers) 1092 self.assertIsNotNone(req._tunnel_host) 1025 1093 self.assertEqual(req.get_host(), "proxy.example.com:3128") 1026 1094 self.assertEqual(req.get_header("Proxy-authorization"),"FooBar") … … 1039 1107 realm, http_handler, password_manager, 1040 1108 "http://acme.example.com/protected", 1041 "http://acme.example.com/protected" ,1042 1109 "http://acme.example.com/protected" 1110 ) 1043 1111 1044 1112 def test_basic_auth_with_single_quoted_realm(self): 1045 1113 self.test_basic_auth(quote_char="'") 1114 1115 def test_basic_auth_with_unquoted_realm(self): 1116 opener = OpenerDirector() 1117 password_manager = MockPasswordManager() 1118 auth_handler = urllib2.HTTPBasicAuthHandler(password_manager) 1119 realm = "ACME Widget Store" 1120 http_handler = MockHTTPHandler( 1121 401, 'WWW-Authenticate: Basic realm=%s\r\n\r\n' % realm) 1122 opener.add_handler(auth_handler) 1123 opener.add_handler(http_handler) 1124 msg = "Basic Auth Realm was unquoted" 1125 with test_support.check_warnings((msg, UserWarning)): 1126 self._test_basic_auth(opener, auth_handler, "Authorization", 1127 realm, http_handler, password_manager, 1128 "http://acme.example.com/protected", 1129 "http://acme.example.com/protected" 1130 ) 1131 1046 1132 1047 1133 def test_proxy_basic_auth(self): … … 1063 1149 1064 1150 def test_basic_and_digest_auth_handlers(self): 1065 # HTTPDigestAuthHandler threwan exception if it couldn't handle a 40*1151 # HTTPDigestAuthHandler raised an exception if it couldn't handle a 40* 1066 1152 # response (http://python.org/sf/1479302), where it should instead 1067 1153 # return None to allow another handler (especially … … 1145 1231 self.assertFalse(http_handler.requests[0].has_header(auth_header)) 1146 1232 1147 1148 1233 class MiscTests(unittest.TestCase): 1149 1234 … … 1190 1275 break 1191 1276 else: 1192 self.assert _(False)1277 self.assertTrue(False) 1193 1278 1194 1279 class RequestTests(unittest.TestCase): … … 1205 1290 1206 1291 def test_add_data(self): 1207 self.assert _(not self.get.has_data())1292 self.assertTrue(not self.get.has_data()) 1208 1293 self.assertEqual("GET", self.get.get_method()) 1209 1294 self.get.add_data("spam") 1210 self.assert _(self.get.has_data())1295 self.assertTrue(self.get.has_data()) 1211 1296 self.assertEqual("POST", self.get.get_method()) 1212 1297 … … 1231 1316 1232 1317 def test_proxy(self): 1233 self.assert _(not self.get.has_proxy())1318 self.assertTrue(not self.get.has_proxy()) 1234 1319 self.get.set_proxy("www.perl.org", "http") 1235 self.assert _(self.get.has_proxy())1320 self.assertTrue(self.get.has_proxy()) 1236 1321 self.assertEqual("www.python.org", self.get.get_origin_req_host()) 1237 1322 self.assertEqual("www.perl.org", self.get.get_host()) 1238 1323 1324 def test_wrapped_url(self): 1325 req = Request("<URL:http://www.python.org>") 1326 self.assertEqual("www.python.org", req.get_host()) 1327 1328 def test_url_fragment(self): 1329 req = Request("http://www.python.org/?qs=query#fragment=true") 1330 self.assertEqual("/?qs=query", req.get_selector()) 1331 req = Request("http://www.python.org/#fun=true") 1332 self.assertEqual("/", req.get_selector()) 1333 1334 # Issue 11703: geturl() omits fragment in the original URL. 1335 url = 'http://docs.python.org/library/urllib2.html#OK' 1336 req = Request(url) 1337 self.assertEqual(req.get_full_url(), url) 1338 1339 def test_HTTPError_interface(self): 1340 """ 1341 Issue 13211 reveals that HTTPError didn't implement the URLError 1342 interface even though HTTPError is a subclass of URLError. 1343 1344 >>> err = urllib2.HTTPError(msg='something bad happened', url=None, code=None, hdrs=None, fp=None) 1345 >>> assert hasattr(err, 'reason') 1346 >>> err.reason 1347 'something bad happened' 1348 """ 1349 1350 def test_HTTPError_interface_call(self): 1351 """ 1352 Issue 15701= - HTTPError interface has info method available from URLError. 1353 """ 1354 err = urllib2.HTTPError(msg='something bad happened', url=None, 1355 code=None, hdrs='Content-Length:42', fp=None) 1356 self.assertTrue(hasattr(err, 'reason')) 1357 assert hasattr(err, 'reason') 1358 assert hasattr(err, 'info') 1359 assert callable(err.info) 1360 try: 1361 err.info() 1362 except AttributeError: 1363 self.fail("err.info() failed") 1364 self.assertEqual(err.info(), "Content-Length:42") 1239 1365 1240 1366 def test_main(verbose=None):
Note:
See TracChangeset
for help on using the changeset viewer.