Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 1 | import unittest |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 2 | from test import support |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 3 | |
Christian Heimes | 05e8be1 | 2008-02-23 18:30:17 +0000 | [diff] [blame] | 4 | import os |
Guido van Rossum | 34d1928 | 2007-08-09 01:03:29 +0000 | [diff] [blame] | 5 | import io |
Georg Brandl | f78e02b | 2008-06-10 17:40:04 +0000 | [diff] [blame] | 6 | import socket |
Senthil Kumaran | 7bc0d87 | 2010-12-19 10:49:52 +0000 | [diff] [blame] | 7 | import array |
Senthil Kumaran | 4de00a2 | 2011-05-11 21:17:57 +0800 | [diff] [blame] | 8 | import sys |
Jeremy Hylton | e3e6104 | 2001-05-09 15:50:25 +0000 | [diff] [blame] | 9 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 10 | import urllib.request |
Ronald Oussoren | e72e161 | 2011-03-14 18:15:25 -0400 | [diff] [blame] | 11 | # The proxy bypass method imported below has logic specific to the OSX |
| 12 | # proxy config data structure but is testable on all platforms. |
| 13 | from urllib.request import Request, OpenerDirector, _proxy_bypass_macosx_sysconf |
guido@google.com | a119df9 | 2011-03-29 11:41:02 -0700 | [diff] [blame] | 14 | import urllib.error |
Jeremy Hylton | e3e6104 | 2001-05-09 15:50:25 +0000 | [diff] [blame] | 15 | |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 16 | # XXX |
| 17 | # Request |
| 18 | # CacheFTPHandler (hard to write) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 19 | # parse_keqv_list, parse_http_list, HTTPDigestAuthHandler |
Jeremy Hylton | e3e6104 | 2001-05-09 15:50:25 +0000 | [diff] [blame] | 20 | |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 21 | class TrivialTests(unittest.TestCase): |
Senthil Kumaran | 6c5bd40 | 2011-11-01 23:20:31 +0800 | [diff] [blame] | 22 | |
| 23 | def test___all__(self): |
| 24 | # Verify which names are exposed |
| 25 | for module in 'request', 'response', 'parse', 'error', 'robotparser': |
| 26 | context = {} |
| 27 | exec('from urllib.%s import *' % module, context) |
| 28 | del context['__builtins__'] |
Florent Xicluna | 3dbb1f1 | 2011-11-04 22:15:37 +0100 | [diff] [blame] | 29 | if module == 'request' and os.name == 'nt': |
| 30 | u, p = context.pop('url2pathname'), context.pop('pathname2url') |
| 31 | self.assertEqual(u.__module__, 'nturl2path') |
| 32 | self.assertEqual(p.__module__, 'nturl2path') |
Senthil Kumaran | 6c5bd40 | 2011-11-01 23:20:31 +0800 | [diff] [blame] | 33 | for k, v in context.items(): |
| 34 | self.assertEqual(v.__module__, 'urllib.%s' % module, |
| 35 | "%r is exposed in 'urllib.%s' but defined in %r" % |
| 36 | (k, module, v.__module__)) |
| 37 | |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 38 | def test_trivial(self): |
| 39 | # A couple trivial tests |
Guido van Rossum | e2ae77b | 2001-10-24 20:42:55 +0000 | [diff] [blame] | 40 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 41 | self.assertRaises(ValueError, urllib.request.urlopen, 'bogus url') |
Tim Peters | 861adac | 2001-07-16 20:49:49 +0000 | [diff] [blame] | 42 | |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 43 | # XXX Name hacking to get this to work on Windows. |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 44 | fname = os.path.abspath(urllib.request.__file__).replace('\\', '/') |
Senthil Kumaran | d587e30 | 2010-01-10 17:45:52 +0000 | [diff] [blame] | 45 | |
Senthil Kumaran | d587e30 | 2010-01-10 17:45:52 +0000 | [diff] [blame] | 46 | if os.name == 'nt': |
| 47 | file_url = "file:///%s" % fname |
| 48 | else: |
| 49 | file_url = "file://%s" % fname |
| 50 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 51 | f = urllib.request.urlopen(file_url) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 52 | |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 53 | f.read() |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 54 | f.close() |
Tim Peters | f5f32b4 | 2005-07-17 23:16:17 +0000 | [diff] [blame] | 55 | |
Georg Brandl | e1b13d2 | 2005-08-24 22:20:32 +0000 | [diff] [blame] | 56 | def test_parse_http_list(self): |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 57 | tests = [ |
| 58 | ('a,b,c', ['a', 'b', 'c']), |
| 59 | ('path"o,l"og"i"cal, example', ['path"o,l"og"i"cal', 'example']), |
| 60 | ('a, b, "c", "d", "e,f", g, h', |
| 61 | ['a', 'b', '"c"', '"d"', '"e,f"', 'g', 'h']), |
| 62 | ('a="b\\"c", d="e\\,f", g="h\\\\i"', |
| 63 | ['a="b"c"', 'd="e,f"', 'g="h\\i"'])] |
Georg Brandl | e1b13d2 | 2005-08-24 22:20:32 +0000 | [diff] [blame] | 64 | for string, list in tests: |
Florent Xicluna | 419e384 | 2010-08-08 16:16:07 +0000 | [diff] [blame] | 65 | self.assertEqual(urllib.request.parse_http_list(string), list) |
Georg Brandl | e1b13d2 | 2005-08-24 22:20:32 +0000 | [diff] [blame] | 66 | |
Senthil Kumaran | 843fae9 | 2013-03-19 13:43:42 -0700 | [diff] [blame] | 67 | def test_URLError_reasonstr(self): |
| 68 | err = urllib.error.URLError('reason') |
| 69 | self.assertIn(err.reason, str(err)) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 70 | |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 71 | class RequestHdrsTests(unittest.TestCase): |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 72 | |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 73 | def test_request_headers_dict(self): |
| 74 | """ |
| 75 | The Request.headers dictionary is not a documented interface. It |
| 76 | should stay that way, because the complete set of headers are only |
| 77 | accessible through the .get_header(), .has_header(), .header_items() |
| 78 | interface. However, .headers pre-dates those methods, and so real code |
| 79 | will be using the dictionary. |
| 80 | |
| 81 | The introduction in 2.4 of those methods was a mistake for the same |
| 82 | reason: code that previously saw all (urllib2 user)-provided headers in |
| 83 | .headers now sees only a subset. |
| 84 | |
| 85 | """ |
| 86 | url = "http://example.com" |
| 87 | self.assertEqual(Request(url, |
| 88 | headers={"Spam-eggs": "blah"} |
| 89 | ).headers["Spam-eggs"], "blah") |
| 90 | self.assertEqual(Request(url, |
| 91 | headers={"spam-EggS": "blah"} |
| 92 | ).headers["Spam-eggs"], "blah") |
| 93 | |
| 94 | def test_request_headers_methods(self): |
| 95 | """ |
| 96 | Note the case normalization of header names here, to |
| 97 | .capitalize()-case. This should be preserved for |
| 98 | backwards-compatibility. (In the HTTP case, normalization to |
| 99 | .title()-case is done by urllib2 before sending headers to |
| 100 | http.client). |
| 101 | |
| 102 | Note that e.g. r.has_header("spam-EggS") is currently False, and |
| 103 | r.get_header("spam-EggS") returns None, but that could be changed in |
| 104 | future. |
| 105 | |
| 106 | Method r.remove_header should remove items both from r.headers and |
| 107 | r.unredirected_hdrs dictionaries |
| 108 | """ |
| 109 | url = "http://example.com" |
| 110 | req = Request(url, headers={"Spam-eggs": "blah"}) |
| 111 | self.assertTrue(req.has_header("Spam-eggs")) |
| 112 | self.assertEqual(req.header_items(), [('Spam-eggs', 'blah')]) |
| 113 | |
| 114 | req.add_header("Foo-Bar", "baz") |
| 115 | self.assertEqual(sorted(req.header_items()), |
| 116 | [('Foo-bar', 'baz'), ('Spam-eggs', 'blah')]) |
| 117 | self.assertFalse(req.has_header("Not-there")) |
| 118 | self.assertIsNone(req.get_header("Not-there")) |
| 119 | self.assertEqual(req.get_header("Not-there", "default"), "default") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 120 | |
| 121 | |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 122 | def test_password_manager(self): |
| 123 | mgr = urllib.request.HTTPPasswordMgr() |
| 124 | add = mgr.add_password |
| 125 | find_user_pass = mgr.find_user_password |
| 126 | add("Some Realm", "http://example.com/", "joe", "password") |
| 127 | add("Some Realm", "http://example.com/ni", "ni", "ni") |
| 128 | add("c", "http://example.com/foo", "foo", "ni") |
| 129 | add("c", "http://example.com/bar", "bar", "nini") |
| 130 | add("b", "http://example.com/", "first", "blah") |
| 131 | add("b", "http://example.com/", "second", "spam") |
| 132 | add("a", "http://example.com", "1", "a") |
| 133 | add("Some Realm", "http://c.example.com:3128", "3", "c") |
| 134 | add("Some Realm", "d.example.com", "4", "d") |
| 135 | add("Some Realm", "e.example.com:3128", "5", "e") |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 136 | |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 137 | self.assertEqual(find_user_pass("Some Realm", "example.com"), |
| 138 | ('joe', 'password')) |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 139 | |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 140 | #self.assertEqual(find_user_pass("Some Realm", "http://example.com/ni"), |
| 141 | # ('ni', 'ni')) |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 142 | |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 143 | self.assertEqual(find_user_pass("Some Realm", "http://example.com"), |
| 144 | ('joe', 'password')) |
| 145 | self.assertEqual(find_user_pass("Some Realm", "http://example.com/"), |
| 146 | ('joe', 'password')) |
| 147 | self.assertEqual( |
| 148 | find_user_pass("Some Realm", "http://example.com/spam"), |
| 149 | ('joe', 'password')) |
| 150 | self.assertEqual( |
| 151 | find_user_pass("Some Realm", "http://example.com/spam/spam"), |
| 152 | ('joe', 'password')) |
| 153 | self.assertEqual(find_user_pass("c", "http://example.com/foo"), |
| 154 | ('foo', 'ni')) |
| 155 | self.assertEqual(find_user_pass("c", "http://example.com/bar"), |
| 156 | ('bar', 'nini')) |
| 157 | self.assertEqual(find_user_pass("b", "http://example.com/"), |
| 158 | ('second', 'spam')) |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 159 | |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 160 | # No special relationship between a.example.com and example.com: |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 161 | |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 162 | self.assertEqual(find_user_pass("a", "http://example.com/"), |
| 163 | ('1', 'a')) |
| 164 | self.assertEqual(find_user_pass("a", "http://a.example.com/"), |
| 165 | (None, None)) |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 166 | |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 167 | # Ports: |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 168 | |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 169 | self.assertEqual(find_user_pass("Some Realm", "c.example.com"), |
| 170 | (None, None)) |
| 171 | self.assertEqual(find_user_pass("Some Realm", "c.example.com:3128"), |
| 172 | ('3', 'c')) |
| 173 | self.assertEqual( |
| 174 | find_user_pass("Some Realm", "http://c.example.com:3128"), |
| 175 | ('3', 'c')) |
| 176 | self.assertEqual(find_user_pass("Some Realm", "d.example.com"), |
| 177 | ('4', 'd')) |
| 178 | self.assertEqual(find_user_pass("Some Realm", "e.example.com:3128"), |
| 179 | ('5', 'e')) |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 180 | |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 181 | def test_password_manager_default_port(self): |
| 182 | """ |
| 183 | The point to note here is that we can't guess the default port if |
| 184 | there's no scheme. This applies to both add_password and |
| 185 | find_user_password. |
| 186 | """ |
| 187 | mgr = urllib.request.HTTPPasswordMgr() |
| 188 | add = mgr.add_password |
| 189 | find_user_pass = mgr.find_user_password |
| 190 | add("f", "http://g.example.com:80", "10", "j") |
| 191 | add("g", "http://h.example.com", "11", "k") |
| 192 | add("h", "i.example.com:80", "12", "l") |
| 193 | add("i", "j.example.com", "13", "m") |
| 194 | self.assertEqual(find_user_pass("f", "g.example.com:100"), |
| 195 | (None, None)) |
| 196 | self.assertEqual(find_user_pass("f", "g.example.com:80"), |
| 197 | ('10', 'j')) |
| 198 | self.assertEqual(find_user_pass("f", "g.example.com"), |
| 199 | (None, None)) |
| 200 | self.assertEqual(find_user_pass("f", "http://g.example.com:100"), |
| 201 | (None, None)) |
| 202 | self.assertEqual(find_user_pass("f", "http://g.example.com:80"), |
| 203 | ('10', 'j')) |
| 204 | self.assertEqual(find_user_pass("f", "http://g.example.com"), |
| 205 | ('10', 'j')) |
| 206 | self.assertEqual(find_user_pass("g", "h.example.com"), ('11', 'k')) |
| 207 | self.assertEqual(find_user_pass("g", "h.example.com:80"), ('11', 'k')) |
| 208 | self.assertEqual(find_user_pass("g", "http://h.example.com:80"), |
| 209 | ('11', 'k')) |
| 210 | self.assertEqual(find_user_pass("h", "i.example.com"), (None, None)) |
| 211 | self.assertEqual(find_user_pass("h", "i.example.com:80"), ('12', 'l')) |
| 212 | self.assertEqual(find_user_pass("h", "http://i.example.com:80"), |
| 213 | ('12', 'l')) |
| 214 | self.assertEqual(find_user_pass("i", "j.example.com"), ('13', 'm')) |
| 215 | self.assertEqual(find_user_pass("i", "j.example.com:80"), |
| 216 | (None, None)) |
| 217 | self.assertEqual(find_user_pass("i", "http://j.example.com"), |
| 218 | ('13', 'm')) |
| 219 | self.assertEqual(find_user_pass("i", "http://j.example.com:80"), |
| 220 | (None, None)) |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 221 | |
| 222 | |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 223 | class MockOpener: |
| 224 | addheaders = [] |
Senthil Kumaran | fb8cc2f | 2009-07-19 02:44:19 +0000 | [diff] [blame] | 225 | def open(self, req, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): |
| 226 | self.req, self.data, self.timeout = req, data, timeout |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 227 | def error(self, proto, *args): |
| 228 | self.proto, self.args = proto, args |
| 229 | |
| 230 | class MockFile: |
| 231 | def read(self, count=None): pass |
| 232 | def readline(self, count=None): pass |
| 233 | def close(self): pass |
| 234 | |
Martin v. Löwis | 2a6ba90 | 2004-05-31 18:22:40 +0000 | [diff] [blame] | 235 | class MockHeaders(dict): |
| 236 | def getheaders(self, name): |
Guido van Rossum | cc2b016 | 2007-02-11 06:12:03 +0000 | [diff] [blame] | 237 | return list(self.values()) |
Martin v. Löwis | 2a6ba90 | 2004-05-31 18:22:40 +0000 | [diff] [blame] | 238 | |
Guido van Rossum | 34d1928 | 2007-08-09 01:03:29 +0000 | [diff] [blame] | 239 | class MockResponse(io.StringIO): |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 240 | def __init__(self, code, msg, headers, data, url=None): |
Guido van Rossum | 34d1928 | 2007-08-09 01:03:29 +0000 | [diff] [blame] | 241 | io.StringIO.__init__(self, data) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 242 | self.code, self.msg, self.headers, self.url = code, msg, headers, url |
| 243 | def info(self): |
| 244 | return self.headers |
| 245 | def geturl(self): |
| 246 | return self.url |
| 247 | |
Martin v. Löwis | 2a6ba90 | 2004-05-31 18:22:40 +0000 | [diff] [blame] | 248 | class MockCookieJar: |
| 249 | def add_cookie_header(self, request): |
| 250 | self.ach_req = request |
| 251 | def extract_cookies(self, response, request): |
| 252 | self.ec_req, self.ec_r = request, response |
| 253 | |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 254 | class FakeMethod: |
| 255 | def __init__(self, meth_name, action, handle): |
| 256 | self.meth_name = meth_name |
| 257 | self.handle = handle |
| 258 | self.action = action |
| 259 | def __call__(self, *args): |
| 260 | return self.handle(self.meth_name, self.action, *args) |
| 261 | |
Senthil Kumaran | 47fff87 | 2009-12-20 07:10:31 +0000 | [diff] [blame] | 262 | class MockHTTPResponse(io.IOBase): |
| 263 | def __init__(self, fp, msg, status, reason): |
| 264 | self.fp = fp |
| 265 | self.msg = msg |
| 266 | self.status = status |
| 267 | self.reason = reason |
| 268 | self.code = 200 |
| 269 | |
| 270 | def read(self): |
| 271 | return '' |
| 272 | |
| 273 | def info(self): |
| 274 | return {} |
| 275 | |
| 276 | def geturl(self): |
| 277 | return self.url |
| 278 | |
| 279 | |
| 280 | class MockHTTPClass: |
| 281 | def __init__(self): |
| 282 | self.level = 0 |
| 283 | self.req_headers = [] |
| 284 | self.data = None |
| 285 | self.raise_on_endheaders = False |
| 286 | self._tunnel_headers = {} |
| 287 | |
| 288 | def __call__(self, host, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): |
| 289 | self.host = host |
| 290 | self.timeout = timeout |
| 291 | return self |
| 292 | |
| 293 | def set_debuglevel(self, level): |
| 294 | self.level = level |
| 295 | |
| 296 | def set_tunnel(self, host, port=None, headers=None): |
| 297 | self._tunnel_host = host |
| 298 | self._tunnel_port = port |
| 299 | if headers: |
| 300 | self._tunnel_headers = headers |
| 301 | else: |
| 302 | self._tunnel_headers.clear() |
| 303 | |
Benjamin Peterson | 3d5b8db | 2009-12-24 01:14:05 +0000 | [diff] [blame] | 304 | def request(self, method, url, body=None, headers=None): |
Senthil Kumaran | 47fff87 | 2009-12-20 07:10:31 +0000 | [diff] [blame] | 305 | self.method = method |
| 306 | self.selector = url |
Benjamin Peterson | 3d5b8db | 2009-12-24 01:14:05 +0000 | [diff] [blame] | 307 | if headers is not None: |
| 308 | self.req_headers += headers.items() |
Senthil Kumaran | 47fff87 | 2009-12-20 07:10:31 +0000 | [diff] [blame] | 309 | self.req_headers.sort() |
| 310 | if body: |
| 311 | self.data = body |
| 312 | if self.raise_on_endheaders: |
| 313 | import socket |
| 314 | raise socket.error() |
| 315 | def getresponse(self): |
| 316 | return MockHTTPResponse(MockFile(), {}, 200, "OK") |
| 317 | |
Victor Stinner | a4c45d7 | 2011-06-17 14:01:18 +0200 | [diff] [blame] | 318 | def close(self): |
| 319 | pass |
| 320 | |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 321 | class MockHandler: |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 322 | # useful for testing handler machinery |
| 323 | # see add_ordered_mock_handlers() docstring |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 324 | handler_order = 500 |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 325 | def __init__(self, methods): |
| 326 | self._define_methods(methods) |
| 327 | def _define_methods(self, methods): |
| 328 | for spec in methods: |
| 329 | if len(spec) == 2: name, action = spec |
| 330 | else: name, action = spec, None |
| 331 | meth = FakeMethod(name, action, self.handle) |
| 332 | setattr(self.__class__, name, meth) |
| 333 | def handle(self, fn_name, action, *args, **kwds): |
| 334 | self.parent.calls.append((self, fn_name, args, kwds)) |
| 335 | if action is None: |
| 336 | return None |
| 337 | elif action == "return self": |
| 338 | return self |
| 339 | elif action == "return response": |
| 340 | res = MockResponse(200, "OK", {}, "") |
| 341 | return res |
| 342 | elif action == "return request": |
| 343 | return Request("http://blah/") |
| 344 | elif action.startswith("error"): |
| 345 | code = action[action.rfind(" ")+1:] |
| 346 | try: |
| 347 | code = int(code) |
| 348 | except ValueError: |
| 349 | pass |
| 350 | res = MockResponse(200, "OK", {}, "") |
| 351 | return self.parent.error("http", args[0], res, code, "", {}) |
| 352 | elif action == "raise": |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 353 | raise urllib.error.URLError("blah") |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 354 | assert False |
| 355 | def close(self): pass |
| 356 | def add_parent(self, parent): |
| 357 | self.parent = parent |
| 358 | self.parent.calls = [] |
| 359 | def __lt__(self, other): |
| 360 | if not hasattr(other, "handler_order"): |
| 361 | # No handler_order, leave in original order. Yuck. |
| 362 | return True |
| 363 | return self.handler_order < other.handler_order |
| 364 | |
| 365 | def add_ordered_mock_handlers(opener, meth_spec): |
| 366 | """Create MockHandlers and add them to an OpenerDirector. |
| 367 | |
| 368 | meth_spec: list of lists of tuples and strings defining methods to define |
| 369 | on handlers. eg: |
| 370 | |
| 371 | [["http_error", "ftp_open"], ["http_open"]] |
| 372 | |
| 373 | defines methods .http_error() and .ftp_open() on one handler, and |
| 374 | .http_open() on another. These methods just record their arguments and |
| 375 | return None. Using a tuple instead of a string causes the method to |
| 376 | perform some action (see MockHandler.handle()), eg: |
| 377 | |
| 378 | [["http_error"], [("http_open", "return request")]] |
| 379 | |
| 380 | defines .http_error() on one handler (which simply returns None), and |
| 381 | .http_open() on another handler, which returns a Request object. |
| 382 | |
| 383 | """ |
| 384 | handlers = [] |
| 385 | count = 0 |
| 386 | for meths in meth_spec: |
| 387 | class MockHandlerSubclass(MockHandler): pass |
| 388 | h = MockHandlerSubclass(meths) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 389 | h.handler_order += count |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 390 | h.add_parent(opener) |
| 391 | count = count + 1 |
| 392 | handlers.append(h) |
| 393 | opener.add_handler(h) |
| 394 | return handlers |
| 395 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 396 | def build_test_opener(*handler_instances): |
| 397 | opener = OpenerDirector() |
| 398 | for h in handler_instances: |
| 399 | opener.add_handler(h) |
| 400 | return opener |
| 401 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 402 | class MockHTTPHandler(urllib.request.BaseHandler): |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 403 | # useful for testing redirections and auth |
| 404 | # sends supplied headers and code as first response |
| 405 | # sends 200 OK as second response |
| 406 | def __init__(self, code, headers): |
| 407 | self.code = code |
| 408 | self.headers = headers |
| 409 | self.reset() |
| 410 | def reset(self): |
| 411 | self._count = 0 |
| 412 | self.requests = [] |
| 413 | def http_open(self, req): |
Barry Warsaw | 820c120 | 2008-06-12 04:06:45 +0000 | [diff] [blame] | 414 | import email, http.client, copy |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 415 | self.requests.append(copy.deepcopy(req)) |
| 416 | if self._count == 0: |
| 417 | self._count = self._count + 1 |
Georg Brandl | 2442015 | 2008-05-26 16:32:26 +0000 | [diff] [blame] | 418 | name = http.client.responses[self.code] |
Barry Warsaw | 820c120 | 2008-06-12 04:06:45 +0000 | [diff] [blame] | 419 | msg = email.message_from_string(self.headers) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 420 | return self.parent.error( |
| 421 | "http", req, MockFile(), self.code, name, msg) |
| 422 | else: |
| 423 | self.req = req |
Barry Warsaw | 820c120 | 2008-06-12 04:06:45 +0000 | [diff] [blame] | 424 | msg = email.message_from_string("\r\n\r\n") |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 425 | return MockResponse(200, "OK", msg, "", req.get_full_url()) |
| 426 | |
Senthil Kumaran | 47fff87 | 2009-12-20 07:10:31 +0000 | [diff] [blame] | 427 | class MockHTTPSHandler(urllib.request.AbstractHTTPHandler): |
| 428 | # Useful for testing the Proxy-Authorization request by verifying the |
| 429 | # properties of httpcon |
Benjamin Peterson | 3d5b8db | 2009-12-24 01:14:05 +0000 | [diff] [blame] | 430 | |
| 431 | def __init__(self): |
| 432 | urllib.request.AbstractHTTPHandler.__init__(self) |
| 433 | self.httpconn = MockHTTPClass() |
| 434 | |
Senthil Kumaran | 47fff87 | 2009-12-20 07:10:31 +0000 | [diff] [blame] | 435 | def https_open(self, req): |
| 436 | return self.do_open(self.httpconn, req) |
| 437 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 438 | class MockPasswordManager: |
| 439 | def add_password(self, realm, uri, user, password): |
| 440 | self.realm = realm |
| 441 | self.url = uri |
| 442 | self.user = user |
| 443 | self.password = password |
| 444 | def find_user_password(self, realm, authuri): |
| 445 | self.target_realm = realm |
| 446 | self.target_url = authuri |
| 447 | return self.user, self.password |
| 448 | |
| 449 | |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 450 | class OpenerDirectorTests(unittest.TestCase): |
| 451 | |
Guido van Rossum | b5a755e | 2007-07-18 18:15:48 +0000 | [diff] [blame] | 452 | def test_add_non_handler(self): |
| 453 | class NonHandler(object): |
| 454 | pass |
| 455 | self.assertRaises(TypeError, |
| 456 | OpenerDirector().add_handler, NonHandler()) |
| 457 | |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 458 | def test_badly_named_methods(self): |
| 459 | # test work-around for three methods that accidentally follow the |
| 460 | # naming conventions for handler methods |
| 461 | # (*_open() / *_request() / *_response()) |
| 462 | |
| 463 | # These used to call the accidentally-named methods, causing a |
| 464 | # TypeError in real code; here, returning self from these mock |
| 465 | # methods would either cause no exception, or AttributeError. |
| 466 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 467 | from urllib.error import URLError |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 468 | |
| 469 | o = OpenerDirector() |
| 470 | meth_spec = [ |
| 471 | [("do_open", "return self"), ("proxy_open", "return self")], |
| 472 | [("redirect_request", "return self")], |
| 473 | ] |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 474 | add_ordered_mock_handlers(o, meth_spec) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 475 | o.add_handler(urllib.request.UnknownHandler()) |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 476 | for scheme in "do", "proxy", "redirect": |
| 477 | self.assertRaises(URLError, o.open, scheme+"://example.com/") |
| 478 | |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 479 | def test_handled(self): |
| 480 | # handler returning non-None means no more handlers will be called |
| 481 | o = OpenerDirector() |
| 482 | meth_spec = [ |
| 483 | ["http_open", "ftp_open", "http_error_302"], |
| 484 | ["ftp_open"], |
| 485 | [("http_open", "return self")], |
| 486 | [("http_open", "return self")], |
| 487 | ] |
| 488 | handlers = add_ordered_mock_handlers(o, meth_spec) |
| 489 | |
| 490 | req = Request("http://example.com/") |
| 491 | r = o.open(req) |
| 492 | # Second .http_open() gets called, third doesn't, since second returned |
| 493 | # non-None. Handlers without .http_open() never get any methods called |
| 494 | # on them. |
| 495 | # In fact, second mock handler defining .http_open() returns self |
| 496 | # (instead of response), which becomes the OpenerDirector's return |
| 497 | # value. |
Jeremy Hylton | df38ea9 | 2003-12-17 20:42:38 +0000 | [diff] [blame] | 498 | self.assertEqual(r, handlers[2]) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 499 | calls = [(handlers[0], "http_open"), (handlers[2], "http_open")] |
| 500 | for expected, got in zip(calls, o.calls): |
| 501 | handler, name, args, kwds = got |
Jeremy Hylton | df38ea9 | 2003-12-17 20:42:38 +0000 | [diff] [blame] | 502 | self.assertEqual((handler, name), expected) |
| 503 | self.assertEqual(args, (req,)) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 504 | |
| 505 | def test_handler_order(self): |
| 506 | o = OpenerDirector() |
| 507 | handlers = [] |
| 508 | for meths, handler_order in [ |
| 509 | ([("http_open", "return self")], 500), |
| 510 | (["http_open"], 0), |
| 511 | ]: |
| 512 | class MockHandlerSubclass(MockHandler): pass |
| 513 | h = MockHandlerSubclass(meths) |
| 514 | h.handler_order = handler_order |
| 515 | handlers.append(h) |
| 516 | o.add_handler(h) |
| 517 | |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 518 | o.open("http://example.com/") |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 519 | # handlers called in reverse order, thanks to their sort order |
Jeremy Hylton | df38ea9 | 2003-12-17 20:42:38 +0000 | [diff] [blame] | 520 | self.assertEqual(o.calls[0][0], handlers[1]) |
| 521 | self.assertEqual(o.calls[1][0], handlers[0]) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 522 | |
| 523 | def test_raise(self): |
| 524 | # raising URLError stops processing of request |
| 525 | o = OpenerDirector() |
| 526 | meth_spec = [ |
| 527 | [("http_open", "raise")], |
| 528 | [("http_open", "return self")], |
| 529 | ] |
| 530 | handlers = add_ordered_mock_handlers(o, meth_spec) |
| 531 | |
| 532 | req = Request("http://example.com/") |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 533 | self.assertRaises(urllib.error.URLError, o.open, req) |
Jeremy Hylton | df38ea9 | 2003-12-17 20:42:38 +0000 | [diff] [blame] | 534 | self.assertEqual(o.calls, [(handlers[0], "http_open", (req,), {})]) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 535 | |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 536 | def test_http_error(self): |
| 537 | # XXX http_error_default |
| 538 | # http errors are a special case |
| 539 | o = OpenerDirector() |
| 540 | meth_spec = [ |
| 541 | [("http_open", "error 302")], |
| 542 | [("http_error_400", "raise"), "http_open"], |
| 543 | [("http_error_302", "return response"), "http_error_303", |
| 544 | "http_error"], |
| 545 | [("http_error_302")], |
| 546 | ] |
| 547 | handlers = add_ordered_mock_handlers(o, meth_spec) |
| 548 | |
| 549 | class Unknown: |
| 550 | def __eq__(self, other): return True |
| 551 | |
| 552 | req = Request("http://example.com/") |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 553 | o.open(req) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 554 | assert len(o.calls) == 2 |
| 555 | calls = [(handlers[0], "http_open", (req,)), |
Jeremy Hylton | df38ea9 | 2003-12-17 20:42:38 +0000 | [diff] [blame] | 556 | (handlers[2], "http_error_302", |
| 557 | (req, Unknown(), 302, "", {}))] |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 558 | for expected, got in zip(calls, o.calls): |
| 559 | handler, method_name, args = expected |
Jeremy Hylton | df38ea9 | 2003-12-17 20:42:38 +0000 | [diff] [blame] | 560 | self.assertEqual((handler, method_name), got[:2]) |
| 561 | self.assertEqual(args, got[2]) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 562 | |
Senthil Kumaran | 38b968b9 | 2012-03-14 13:43:53 -0700 | [diff] [blame] | 563 | |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 564 | def test_processors(self): |
| 565 | # *_request / *_response methods get called appropriately |
| 566 | o = OpenerDirector() |
| 567 | meth_spec = [ |
| 568 | [("http_request", "return request"), |
| 569 | ("http_response", "return response")], |
| 570 | [("http_request", "return request"), |
| 571 | ("http_response", "return response")], |
| 572 | ] |
| 573 | handlers = add_ordered_mock_handlers(o, meth_spec) |
| 574 | |
| 575 | req = Request("http://example.com/") |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 576 | o.open(req) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 577 | # processor methods are called on *all* handlers that define them, |
| 578 | # not just the first handler that handles the request |
Jeremy Hylton | df38ea9 | 2003-12-17 20:42:38 +0000 | [diff] [blame] | 579 | calls = [ |
| 580 | (handlers[0], "http_request"), (handlers[1], "http_request"), |
| 581 | (handlers[0], "http_response"), (handlers[1], "http_response")] |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 582 | |
| 583 | for i, (handler, name, args, kwds) in enumerate(o.calls): |
| 584 | if i < 2: |
| 585 | # *_request |
Jeremy Hylton | df38ea9 | 2003-12-17 20:42:38 +0000 | [diff] [blame] | 586 | self.assertEqual((handler, name), calls[i]) |
| 587 | self.assertEqual(len(args), 1) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 588 | self.assertIsInstance(args[0], Request) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 589 | else: |
| 590 | # *_response |
Jeremy Hylton | df38ea9 | 2003-12-17 20:42:38 +0000 | [diff] [blame] | 591 | self.assertEqual((handler, name), calls[i]) |
| 592 | self.assertEqual(len(args), 2) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 593 | self.assertIsInstance(args[0], Request) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 594 | # response from opener.open is None, because there's no |
| 595 | # handler that defines http_open to handle it |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 596 | self.assertTrue(args[1] is None or |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 597 | isinstance(args[1], MockResponse)) |
| 598 | |
Senthil Kumaran | 38b968b9 | 2012-03-14 13:43:53 -0700 | [diff] [blame] | 599 | def test_method_deprecations(self): |
| 600 | req = Request("http://www.example.com") |
Senthil Kumaran | 08bd4aa | 2012-04-11 23:05:49 +0800 | [diff] [blame] | 601 | |
Senthil Kumaran | 80a133b | 2012-04-12 19:28:07 +0800 | [diff] [blame] | 602 | with self.assertWarns(DeprecationWarning): |
Senthil Kumaran | 38b968b9 | 2012-03-14 13:43:53 -0700 | [diff] [blame] | 603 | req.add_data("data") |
Senthil Kumaran | 80a133b | 2012-04-12 19:28:07 +0800 | [diff] [blame] | 604 | with self.assertWarns(DeprecationWarning): |
Senthil Kumaran | 38b968b9 | 2012-03-14 13:43:53 -0700 | [diff] [blame] | 605 | req.get_data() |
Senthil Kumaran | 80a133b | 2012-04-12 19:28:07 +0800 | [diff] [blame] | 606 | with self.assertWarns(DeprecationWarning): |
Senthil Kumaran | 77ebfcc | 2012-08-20 13:43:59 -0700 | [diff] [blame] | 607 | req.has_data() |
| 608 | with self.assertWarns(DeprecationWarning): |
Senthil Kumaran | 38b968b9 | 2012-03-14 13:43:53 -0700 | [diff] [blame] | 609 | req.get_host() |
Senthil Kumaran | 80a133b | 2012-04-12 19:28:07 +0800 | [diff] [blame] | 610 | with self.assertWarns(DeprecationWarning): |
Senthil Kumaran | 38b968b9 | 2012-03-14 13:43:53 -0700 | [diff] [blame] | 611 | req.get_selector() |
Senthil Kumaran | 80a133b | 2012-04-12 19:28:07 +0800 | [diff] [blame] | 612 | with self.assertWarns(DeprecationWarning): |
Senthil Kumaran | 38b968b9 | 2012-03-14 13:43:53 -0700 | [diff] [blame] | 613 | req.is_unverifiable() |
Senthil Kumaran | 80a133b | 2012-04-12 19:28:07 +0800 | [diff] [blame] | 614 | with self.assertWarns(DeprecationWarning): |
Senthil Kumaran | 38b968b9 | 2012-03-14 13:43:53 -0700 | [diff] [blame] | 615 | req.get_origin_req_host() |
Senthil Kumaran | 77ebfcc | 2012-08-20 13:43:59 -0700 | [diff] [blame] | 616 | with self.assertWarns(DeprecationWarning): |
| 617 | req.get_type() |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 618 | |
Senthil Kumaran | 08bd4aa | 2012-04-11 23:05:49 +0800 | [diff] [blame] | 619 | |
Tim Peters | 58eb11c | 2004-01-18 20:29:55 +0000 | [diff] [blame] | 620 | def sanepathname2url(path): |
Victor Stinner | 6c6f851 | 2010-08-07 10:09:35 +0000 | [diff] [blame] | 621 | try: |
Marc-André Lemburg | 8f36af7 | 2011-02-25 15:42:01 +0000 | [diff] [blame] | 622 | path.encode("utf-8") |
Victor Stinner | 6c6f851 | 2010-08-07 10:09:35 +0000 | [diff] [blame] | 623 | except UnicodeEncodeError: |
| 624 | raise unittest.SkipTest("path is not encodable to utf8") |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 625 | urlpath = urllib.request.pathname2url(path) |
Tim Peters | 58eb11c | 2004-01-18 20:29:55 +0000 | [diff] [blame] | 626 | if os.name == "nt" and urlpath.startswith("///"): |
| 627 | urlpath = urlpath[2:] |
| 628 | # XXX don't ask me about the mac... |
| 629 | return urlpath |
| 630 | |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 631 | class HandlerTests(unittest.TestCase): |
| 632 | |
| 633 | def test_ftp(self): |
| 634 | class MockFTPWrapper: |
| 635 | def __init__(self, data): self.data = data |
| 636 | def retrfile(self, filename, filetype): |
| 637 | self.filename, self.filetype = filename, filetype |
Guido van Rossum | 34d1928 | 2007-08-09 01:03:29 +0000 | [diff] [blame] | 638 | return io.StringIO(self.data), len(self.data) |
Nadeem Vawda | 08f5f7a | 2011-07-23 14:03:00 +0200 | [diff] [blame] | 639 | def close(self): pass |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 640 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 641 | class NullFTPHandler(urllib.request.FTPHandler): |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 642 | def __init__(self, data): self.data = data |
Georg Brandl | f78e02b | 2008-06-10 17:40:04 +0000 | [diff] [blame] | 643 | def connect_ftp(self, user, passwd, host, port, dirs, |
| 644 | timeout=socket._GLOBAL_DEFAULT_TIMEOUT): |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 645 | self.user, self.passwd = user, passwd |
| 646 | self.host, self.port = host, port |
| 647 | self.dirs = dirs |
| 648 | self.ftpwrapper = MockFTPWrapper(self.data) |
| 649 | return self.ftpwrapper |
| 650 | |
Georg Brandl | f78e02b | 2008-06-10 17:40:04 +0000 | [diff] [blame] | 651 | import ftplib |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 652 | data = "rheum rhaponicum" |
| 653 | h = NullFTPHandler(data) |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 654 | h.parent = MockOpener() |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 655 | |
Senthil Kumaran | daa29d0 | 2010-11-18 15:36:41 +0000 | [diff] [blame] | 656 | for url, host, port, user, passwd, type_, dirs, filename, mimetype in [ |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 657 | ("ftp://localhost/foo/bar/baz.html", |
Senthil Kumaran | daa29d0 | 2010-11-18 15:36:41 +0000 | [diff] [blame] | 658 | "localhost", ftplib.FTP_PORT, "", "", "I", |
| 659 | ["foo", "bar"], "baz.html", "text/html"), |
| 660 | ("ftp://parrot@localhost/foo/bar/baz.html", |
| 661 | "localhost", ftplib.FTP_PORT, "parrot", "", "I", |
| 662 | ["foo", "bar"], "baz.html", "text/html"), |
| 663 | ("ftp://%25parrot@localhost/foo/bar/baz.html", |
| 664 | "localhost", ftplib.FTP_PORT, "%parrot", "", "I", |
| 665 | ["foo", "bar"], "baz.html", "text/html"), |
| 666 | ("ftp://%2542parrot@localhost/foo/bar/baz.html", |
| 667 | "localhost", ftplib.FTP_PORT, "%42parrot", "", "I", |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 668 | ["foo", "bar"], "baz.html", "text/html"), |
Kurt B. Kaiser | 3f7cb5d | 2004-07-11 17:14:13 +0000 | [diff] [blame] | 669 | ("ftp://localhost:80/foo/bar/", |
Senthil Kumaran | daa29d0 | 2010-11-18 15:36:41 +0000 | [diff] [blame] | 670 | "localhost", 80, "", "", "D", |
Kurt B. Kaiser | 3f7cb5d | 2004-07-11 17:14:13 +0000 | [diff] [blame] | 671 | ["foo", "bar"], "", None), |
| 672 | ("ftp://localhost/baz.gif;type=a", |
Senthil Kumaran | daa29d0 | 2010-11-18 15:36:41 +0000 | [diff] [blame] | 673 | "localhost", ftplib.FTP_PORT, "", "", "A", |
Kurt B. Kaiser | 3f7cb5d | 2004-07-11 17:14:13 +0000 | [diff] [blame] | 674 | [], "baz.gif", None), # XXX really this should guess image/gif |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 675 | ]: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 676 | req = Request(url) |
| 677 | req.timeout = None |
| 678 | r = h.ftp_open(req) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 679 | # ftp authentication not yet implemented by FTPHandler |
Senthil Kumaran | daa29d0 | 2010-11-18 15:36:41 +0000 | [diff] [blame] | 680 | self.assertEqual(h.user, user) |
| 681 | self.assertEqual(h.passwd, passwd) |
Jeremy Hylton | df38ea9 | 2003-12-17 20:42:38 +0000 | [diff] [blame] | 682 | self.assertEqual(h.host, socket.gethostbyname(host)) |
| 683 | self.assertEqual(h.port, port) |
| 684 | self.assertEqual(h.dirs, dirs) |
| 685 | self.assertEqual(h.ftpwrapper.filename, filename) |
| 686 | self.assertEqual(h.ftpwrapper.filetype, type_) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 687 | headers = r.info() |
Kurt B. Kaiser | 3f7cb5d | 2004-07-11 17:14:13 +0000 | [diff] [blame] | 688 | self.assertEqual(headers.get("Content-type"), mimetype) |
Jeremy Hylton | df38ea9 | 2003-12-17 20:42:38 +0000 | [diff] [blame] | 689 | self.assertEqual(int(headers["Content-length"]), len(data)) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 690 | |
| 691 | def test_file(self): |
Benjamin Peterson | a0c0a4a | 2008-06-12 22:15:50 +0000 | [diff] [blame] | 692 | import email.utils, socket |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 693 | h = urllib.request.FileHandler() |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 694 | o = h.parent = MockOpener() |
| 695 | |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 696 | TESTFN = support.TESTFN |
Tim Peters | 58eb11c | 2004-01-18 20:29:55 +0000 | [diff] [blame] | 697 | urlpath = sanepathname2url(os.path.abspath(TESTFN)) |
Guido van Rossum | 6a2ccd0 | 2007-07-16 20:51:57 +0000 | [diff] [blame] | 698 | towrite = b"hello, world\n" |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 699 | urls = [ |
Tim Peters | 58eb11c | 2004-01-18 20:29:55 +0000 | [diff] [blame] | 700 | "file://localhost%s" % urlpath, |
| 701 | "file://%s" % urlpath, |
| 702 | "file://%s%s" % (socket.gethostbyname('localhost'), urlpath), |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 703 | ] |
| 704 | try: |
| 705 | localaddr = socket.gethostbyname(socket.gethostname()) |
| 706 | except socket.gaierror: |
| 707 | localaddr = '' |
| 708 | if localaddr: |
| 709 | urls.append("file://%s%s" % (localaddr, urlpath)) |
| 710 | |
| 711 | for url in urls: |
Tim Peters | 58eb11c | 2004-01-18 20:29:55 +0000 | [diff] [blame] | 712 | f = open(TESTFN, "wb") |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 713 | try: |
| 714 | try: |
| 715 | f.write(towrite) |
| 716 | finally: |
| 717 | f.close() |
| 718 | |
| 719 | r = h.file_open(Request(url)) |
| 720 | try: |
| 721 | data = r.read() |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 722 | headers = r.info() |
Senthil Kumaran | 4fbed10 | 2010-05-08 03:29:09 +0000 | [diff] [blame] | 723 | respurl = r.geturl() |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 724 | finally: |
| 725 | r.close() |
Tim Peters | 58eb11c | 2004-01-18 20:29:55 +0000 | [diff] [blame] | 726 | stats = os.stat(TESTFN) |
Benjamin Peterson | a0c0a4a | 2008-06-12 22:15:50 +0000 | [diff] [blame] | 727 | modified = email.utils.formatdate(stats.st_mtime, usegmt=True) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 728 | finally: |
| 729 | os.remove(TESTFN) |
Jeremy Hylton | df38ea9 | 2003-12-17 20:42:38 +0000 | [diff] [blame] | 730 | self.assertEqual(data, towrite) |
| 731 | self.assertEqual(headers["Content-type"], "text/plain") |
| 732 | self.assertEqual(headers["Content-length"], "13") |
Tim Peters | 58eb11c | 2004-01-18 20:29:55 +0000 | [diff] [blame] | 733 | self.assertEqual(headers["Last-modified"], modified) |
Senthil Kumaran | 4fbed10 | 2010-05-08 03:29:09 +0000 | [diff] [blame] | 734 | self.assertEqual(respurl, url) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 735 | |
| 736 | for url in [ |
Tim Peters | 58eb11c | 2004-01-18 20:29:55 +0000 | [diff] [blame] | 737 | "file://localhost:80%s" % urlpath, |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 738 | "file:///file_does_not_exist.txt", |
| 739 | "file://%s:80%s/%s" % (socket.gethostbyname('localhost'), |
| 740 | os.getcwd(), TESTFN), |
| 741 | "file://somerandomhost.ontheinternet.com%s/%s" % |
| 742 | (os.getcwd(), TESTFN), |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 743 | ]: |
| 744 | try: |
Tim Peters | 58eb11c | 2004-01-18 20:29:55 +0000 | [diff] [blame] | 745 | f = open(TESTFN, "wb") |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 746 | try: |
| 747 | f.write(towrite) |
| 748 | finally: |
| 749 | f.close() |
| 750 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 751 | self.assertRaises(urllib.error.URLError, |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 752 | h.file_open, Request(url)) |
| 753 | finally: |
| 754 | os.remove(TESTFN) |
| 755 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 756 | h = urllib.request.FileHandler() |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 757 | o = h.parent = MockOpener() |
| 758 | # XXXX why does // mean ftp (and /// mean not ftp!), and where |
| 759 | # is file: scheme specified? I think this is really a bug, and |
| 760 | # what was intended was to distinguish between URLs like: |
| 761 | # file:/blah.txt (a file) |
| 762 | # file://localhost/blah.txt (a file) |
| 763 | # file:///blah.txt (a file) |
| 764 | # file://ftp.example.com/blah.txt (an ftp URL) |
| 765 | for url, ftp in [ |
Senthil Kumaran | 383c32d | 2010-10-14 11:57:35 +0000 | [diff] [blame] | 766 | ("file://ftp.example.com//foo.txt", False), |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 767 | ("file://ftp.example.com///foo.txt", False), |
| 768 | # XXXX bug: fails with OSError, should be URLError |
| 769 | ("file://ftp.example.com/foo.txt", False), |
Senthil Kumaran | 383c32d | 2010-10-14 11:57:35 +0000 | [diff] [blame] | 770 | ("file://somehost//foo/something.txt", False), |
Senthil Kumaran | 2ef1632 | 2010-07-11 03:12:43 +0000 | [diff] [blame] | 771 | ("file://localhost//foo/something.txt", False), |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 772 | ]: |
| 773 | req = Request(url) |
| 774 | try: |
| 775 | h.file_open(req) |
| 776 | # XXXX remove OSError when bug fixed |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 777 | except (urllib.error.URLError, OSError): |
Florent Xicluna | 419e384 | 2010-08-08 16:16:07 +0000 | [diff] [blame] | 778 | self.assertFalse(ftp) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 779 | else: |
Florent Xicluna | 419e384 | 2010-08-08 16:16:07 +0000 | [diff] [blame] | 780 | self.assertIs(o.req, req) |
Jeremy Hylton | df38ea9 | 2003-12-17 20:42:38 +0000 | [diff] [blame] | 781 | self.assertEqual(req.type, "ftp") |
Łukasz Langa | d7e81cc | 2011-01-09 18:18:53 +0000 | [diff] [blame] | 782 | self.assertEqual(req.type == "ftp", ftp) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 783 | |
| 784 | def test_http(self): |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 785 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 786 | h = urllib.request.AbstractHTTPHandler() |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 787 | o = h.parent = MockOpener() |
| 788 | |
| 789 | url = "http://example.com/" |
Senthil Kumaran | 7bc0d87 | 2010-12-19 10:49:52 +0000 | [diff] [blame] | 790 | for method, data in [("GET", None), ("POST", b"blah")]: |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 791 | req = Request(url, data, {"Foo": "bar"}) |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 792 | req.timeout = None |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 793 | req.add_unredirected_header("Spam", "eggs") |
| 794 | http = MockHTTPClass() |
| 795 | r = h.do_open(http, req) |
| 796 | |
| 797 | # result attributes |
| 798 | r.read; r.readline # wrapped MockFile methods |
| 799 | r.info; r.geturl # addinfourl methods |
| 800 | r.code, r.msg == 200, "OK" # added from MockHTTPClass.getreply() |
| 801 | hdrs = r.info() |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 802 | hdrs.get; hdrs.__contains__ # r.info() gives dict from .getreply() |
Jeremy Hylton | df38ea9 | 2003-12-17 20:42:38 +0000 | [diff] [blame] | 803 | self.assertEqual(r.geturl(), url) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 804 | |
Jeremy Hylton | df38ea9 | 2003-12-17 20:42:38 +0000 | [diff] [blame] | 805 | self.assertEqual(http.host, "example.com") |
| 806 | self.assertEqual(http.level, 0) |
| 807 | self.assertEqual(http.method, method) |
| 808 | self.assertEqual(http.selector, "/") |
| 809 | self.assertEqual(http.req_headers, |
Jeremy Hylton | b3ee6f9 | 2004-02-24 19:40:35 +0000 | [diff] [blame] | 810 | [("Connection", "close"), |
| 811 | ("Foo", "bar"), ("Spam", "eggs")]) |
Jeremy Hylton | df38ea9 | 2003-12-17 20:42:38 +0000 | [diff] [blame] | 812 | self.assertEqual(http.data, data) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 813 | |
| 814 | # check socket.error converted to URLError |
| 815 | http.raise_on_endheaders = True |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 816 | self.assertRaises(urllib.error.URLError, h.do_open, http, req) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 817 | |
Senthil Kumaran | 2933312 | 2011-02-11 11:25:47 +0000 | [diff] [blame] | 818 | # Check for TypeError on POST data which is str. |
| 819 | req = Request("http://example.com/","badpost") |
| 820 | self.assertRaises(TypeError, h.do_request_, req) |
| 821 | |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 822 | # check adding of standard headers |
| 823 | o.addheaders = [("Spam", "eggs")] |
Senthil Kumaran | 7bc0d87 | 2010-12-19 10:49:52 +0000 | [diff] [blame] | 824 | for data in b"", None: # POST, GET |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 825 | req = Request("http://example.com/", data) |
| 826 | r = MockResponse(200, "OK", {}, "") |
Martin v. Löwis | 2a6ba90 | 2004-05-31 18:22:40 +0000 | [diff] [blame] | 827 | newreq = h.do_request_(req) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 828 | if data is None: # GET |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 829 | self.assertNotIn("Content-length", req.unredirected_hdrs) |
| 830 | self.assertNotIn("Content-type", req.unredirected_hdrs) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 831 | else: # POST |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 832 | self.assertEqual(req.unredirected_hdrs["Content-length"], "0") |
| 833 | self.assertEqual(req.unredirected_hdrs["Content-type"], |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 834 | "application/x-www-form-urlencoded") |
| 835 | # XXX the details of Host could be better tested |
Jeremy Hylton | df38ea9 | 2003-12-17 20:42:38 +0000 | [diff] [blame] | 836 | self.assertEqual(req.unredirected_hdrs["Host"], "example.com") |
| 837 | self.assertEqual(req.unredirected_hdrs["Spam"], "eggs") |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 838 | |
| 839 | # don't clobber existing headers |
| 840 | req.add_unredirected_header("Content-length", "foo") |
| 841 | req.add_unredirected_header("Content-type", "bar") |
| 842 | req.add_unredirected_header("Host", "baz") |
| 843 | req.add_unredirected_header("Spam", "foo") |
Martin v. Löwis | 2a6ba90 | 2004-05-31 18:22:40 +0000 | [diff] [blame] | 844 | newreq = h.do_request_(req) |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 845 | self.assertEqual(req.unredirected_hdrs["Content-length"], "foo") |
| 846 | self.assertEqual(req.unredirected_hdrs["Content-type"], "bar") |
Jeremy Hylton | df38ea9 | 2003-12-17 20:42:38 +0000 | [diff] [blame] | 847 | self.assertEqual(req.unredirected_hdrs["Host"], "baz") |
| 848 | self.assertEqual(req.unredirected_hdrs["Spam"], "foo") |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 849 | |
Senthil Kumaran | 7bc0d87 | 2010-12-19 10:49:52 +0000 | [diff] [blame] | 850 | # Check iterable body support |
| 851 | def iterable_body(): |
| 852 | yield b"one" |
| 853 | yield b"two" |
| 854 | yield b"three" |
| 855 | |
| 856 | for headers in {}, {"Content-Length": 11}: |
| 857 | req = Request("http://example.com/", iterable_body(), headers) |
| 858 | if not headers: |
| 859 | # Having an iterable body without a Content-Length should |
| 860 | # raise an exception |
| 861 | self.assertRaises(ValueError, h.do_request_, req) |
| 862 | else: |
| 863 | newreq = h.do_request_(req) |
| 864 | |
Senthil Kumaran | 2933312 | 2011-02-11 11:25:47 +0000 | [diff] [blame] | 865 | # A file object. |
| 866 | # Test only Content-Length attribute of request. |
Senthil Kumaran | 7bc0d87 | 2010-12-19 10:49:52 +0000 | [diff] [blame] | 867 | |
Senthil Kumaran | 2933312 | 2011-02-11 11:25:47 +0000 | [diff] [blame] | 868 | file_obj = io.BytesIO() |
| 869 | file_obj.write(b"Something\nSomething\nSomething\n") |
Senthil Kumaran | 7bc0d87 | 2010-12-19 10:49:52 +0000 | [diff] [blame] | 870 | |
| 871 | for headers in {}, {"Content-Length": 30}: |
| 872 | req = Request("http://example.com/", file_obj, headers) |
| 873 | if not headers: |
| 874 | # Having an iterable body without a Content-Length should |
| 875 | # raise an exception |
| 876 | self.assertRaises(ValueError, h.do_request_, req) |
| 877 | else: |
| 878 | newreq = h.do_request_(req) |
| 879 | self.assertEqual(int(newreq.get_header('Content-length')),30) |
| 880 | |
| 881 | file_obj.close() |
| 882 | |
| 883 | # array.array Iterable - Content Length is calculated |
| 884 | |
| 885 | iterable_array = array.array("I",[1,2,3,4]) |
| 886 | |
| 887 | for headers in {}, {"Content-Length": 16}: |
| 888 | req = Request("http://example.com/", iterable_array, headers) |
| 889 | newreq = h.do_request_(req) |
| 890 | self.assertEqual(int(newreq.get_header('Content-length')),16) |
Senthil Kumaran | 7bc0d87 | 2010-12-19 10:49:52 +0000 | [diff] [blame] | 891 | |
Facundo Batista | 72dc1ea | 2008-08-16 14:44:32 +0000 | [diff] [blame] | 892 | def test_http_doubleslash(self): |
| 893 | # Checks the presence of any unnecessary double slash in url does not |
| 894 | # break anything. Previously, a double slash directly after the host |
Ezio Melotti | e130a52 | 2011-10-19 10:58:56 +0300 | [diff] [blame] | 895 | # could cause incorrect parsing. |
Facundo Batista | 72dc1ea | 2008-08-16 14:44:32 +0000 | [diff] [blame] | 896 | h = urllib.request.AbstractHTTPHandler() |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 897 | h.parent = MockOpener() |
Facundo Batista | 72dc1ea | 2008-08-16 14:44:32 +0000 | [diff] [blame] | 898 | |
Senthil Kumaran | 7bc0d87 | 2010-12-19 10:49:52 +0000 | [diff] [blame] | 899 | data = b"" |
Facundo Batista | 72dc1ea | 2008-08-16 14:44:32 +0000 | [diff] [blame] | 900 | ds_urls = [ |
| 901 | "http://example.com/foo/bar/baz.html", |
| 902 | "http://example.com//foo/bar/baz.html", |
| 903 | "http://example.com/foo//bar/baz.html", |
| 904 | "http://example.com/foo/bar//baz.html" |
| 905 | ] |
| 906 | |
| 907 | for ds_url in ds_urls: |
| 908 | ds_req = Request(ds_url, data) |
| 909 | |
| 910 | # Check whether host is determined correctly if there is no proxy |
| 911 | np_ds_req = h.do_request_(ds_req) |
| 912 | self.assertEqual(np_ds_req.unredirected_hdrs["Host"],"example.com") |
| 913 | |
| 914 | # Check whether host is determined correctly if there is a proxy |
| 915 | ds_req.set_proxy("someproxy:3128",None) |
| 916 | p_ds_req = h.do_request_(ds_req) |
| 917 | self.assertEqual(p_ds_req.unredirected_hdrs["Host"],"example.com") |
| 918 | |
Senthil Kumaran | c295862 | 2010-11-22 04:48:26 +0000 | [diff] [blame] | 919 | def test_fixpath_in_weirdurls(self): |
| 920 | # Issue4493: urllib2 to supply '/' when to urls where path does not |
| 921 | # start with'/' |
| 922 | |
| 923 | h = urllib.request.AbstractHTTPHandler() |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 924 | h.parent = MockOpener() |
Senthil Kumaran | c295862 | 2010-11-22 04:48:26 +0000 | [diff] [blame] | 925 | |
| 926 | weird_url = 'http://www.python.org?getspam' |
| 927 | req = Request(weird_url) |
| 928 | newreq = h.do_request_(req) |
| 929 | self.assertEqual(newreq.host,'www.python.org') |
| 930 | self.assertEqual(newreq.selector,'/?getspam') |
| 931 | |
| 932 | url_without_path = 'http://www.python.org' |
| 933 | req = Request(url_without_path) |
| 934 | newreq = h.do_request_(req) |
| 935 | self.assertEqual(newreq.host,'www.python.org') |
| 936 | self.assertEqual(newreq.selector,'') |
| 937 | |
Facundo Batista | 72dc1ea | 2008-08-16 14:44:32 +0000 | [diff] [blame] | 938 | |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 939 | def test_errors(self): |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 940 | h = urllib.request.HTTPErrorProcessor() |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 941 | o = h.parent = MockOpener() |
| 942 | |
| 943 | url = "http://example.com/" |
| 944 | req = Request(url) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 945 | # all 2xx are passed through |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 946 | r = MockResponse(200, "OK", {}, "", url) |
| 947 | newr = h.http_response(req, r) |
Florent Xicluna | 419e384 | 2010-08-08 16:16:07 +0000 | [diff] [blame] | 948 | self.assertIs(r, newr) |
| 949 | self.assertFalse(hasattr(o, "proto")) # o.error not called |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 950 | r = MockResponse(202, "Accepted", {}, "", url) |
| 951 | newr = h.http_response(req, r) |
Florent Xicluna | 419e384 | 2010-08-08 16:16:07 +0000 | [diff] [blame] | 952 | self.assertIs(r, newr) |
| 953 | self.assertFalse(hasattr(o, "proto")) # o.error not called |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 954 | r = MockResponse(206, "Partial content", {}, "", url) |
| 955 | newr = h.http_response(req, r) |
Florent Xicluna | 419e384 | 2010-08-08 16:16:07 +0000 | [diff] [blame] | 956 | self.assertIs(r, newr) |
| 957 | self.assertFalse(hasattr(o, "proto")) # o.error not called |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 958 | # anything else calls o.error (and MockOpener returns None, here) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 959 | r = MockResponse(502, "Bad gateway", {}, "", url) |
Florent Xicluna | 419e384 | 2010-08-08 16:16:07 +0000 | [diff] [blame] | 960 | self.assertIsNone(h.http_response(req, r)) |
Jeremy Hylton | df38ea9 | 2003-12-17 20:42:38 +0000 | [diff] [blame] | 961 | self.assertEqual(o.proto, "http") # o.error called |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 962 | self.assertEqual(o.args, (req, r, 502, "Bad gateway", {})) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 963 | |
Martin v. Löwis | 2a6ba90 | 2004-05-31 18:22:40 +0000 | [diff] [blame] | 964 | def test_cookies(self): |
| 965 | cj = MockCookieJar() |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 966 | h = urllib.request.HTTPCookieProcessor(cj) |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 967 | h.parent = MockOpener() |
Martin v. Löwis | 2a6ba90 | 2004-05-31 18:22:40 +0000 | [diff] [blame] | 968 | |
| 969 | req = Request("http://example.com/") |
| 970 | r = MockResponse(200, "OK", {}, "") |
| 971 | newreq = h.http_request(req) |
Florent Xicluna | 419e384 | 2010-08-08 16:16:07 +0000 | [diff] [blame] | 972 | self.assertIs(cj.ach_req, req) |
| 973 | self.assertIs(cj.ach_req, newreq) |
Senthil Kumaran | 77ebfcc | 2012-08-20 13:43:59 -0700 | [diff] [blame] | 974 | self.assertEqual(req.origin_req_host, "example.com") |
| 975 | self.assertFalse(req.unverifiable) |
Martin v. Löwis | 2a6ba90 | 2004-05-31 18:22:40 +0000 | [diff] [blame] | 976 | newr = h.http_response(req, r) |
Florent Xicluna | 419e384 | 2010-08-08 16:16:07 +0000 | [diff] [blame] | 977 | self.assertIs(cj.ec_req, req) |
| 978 | self.assertIs(cj.ec_r, r) |
| 979 | self.assertIs(r, newr) |
Martin v. Löwis | 2a6ba90 | 2004-05-31 18:22:40 +0000 | [diff] [blame] | 980 | |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 981 | def test_redirect(self): |
| 982 | from_url = "http://example.com/a.html" |
| 983 | to_url = "http://example.com/b.html" |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 984 | h = urllib.request.HTTPRedirectHandler() |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 985 | o = h.parent = MockOpener() |
| 986 | |
| 987 | # ordinary redirect behaviour |
| 988 | for code in 301, 302, 303, 307: |
| 989 | for data in None, "blah\nblah\n": |
| 990 | method = getattr(h, "http_error_%s" % code) |
| 991 | req = Request(from_url, data) |
Senthil Kumaran | fb8cc2f | 2009-07-19 02:44:19 +0000 | [diff] [blame] | 992 | req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 993 | req.add_header("Nonsense", "viking=withhold") |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 994 | if data is not None: |
| 995 | req.add_header("Content-Length", str(len(data))) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 996 | req.add_unredirected_header("Spam", "spam") |
| 997 | try: |
Martin v. Löwis | 2a6ba90 | 2004-05-31 18:22:40 +0000 | [diff] [blame] | 998 | method(req, MockFile(), code, "Blah", |
| 999 | MockHeaders({"location": to_url})) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1000 | except urllib.error.HTTPError: |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 1001 | # 307 in response to POST requires user OK |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1002 | self.assertTrue(code == 307 and data is not None) |
Jeremy Hylton | df38ea9 | 2003-12-17 20:42:38 +0000 | [diff] [blame] | 1003 | self.assertEqual(o.req.get_full_url(), to_url) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 1004 | try: |
Jeremy Hylton | df38ea9 | 2003-12-17 20:42:38 +0000 | [diff] [blame] | 1005 | self.assertEqual(o.req.get_method(), "GET") |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 1006 | except AttributeError: |
Senthil Kumaran | 77ebfcc | 2012-08-20 13:43:59 -0700 | [diff] [blame] | 1007 | self.assertFalse(o.req.data) |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 1008 | |
| 1009 | # now it's a GET, there should not be headers regarding content |
| 1010 | # (possibly dragged from before being a POST) |
| 1011 | headers = [x.lower() for x in o.req.headers] |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 1012 | self.assertNotIn("content-length", headers) |
| 1013 | self.assertNotIn("content-type", headers) |
Christian Heimes | 77c02eb | 2008-02-09 02:18:51 +0000 | [diff] [blame] | 1014 | |
Jeremy Hylton | df38ea9 | 2003-12-17 20:42:38 +0000 | [diff] [blame] | 1015 | self.assertEqual(o.req.headers["Nonsense"], |
| 1016 | "viking=withhold") |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 1017 | self.assertNotIn("Spam", o.req.headers) |
| 1018 | self.assertNotIn("Spam", o.req.unredirected_hdrs) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 1019 | |
| 1020 | # loop detection |
| 1021 | req = Request(from_url) |
Senthil Kumaran | fb8cc2f | 2009-07-19 02:44:19 +0000 | [diff] [blame] | 1022 | req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT |
Martin v. Löwis | 2a6ba90 | 2004-05-31 18:22:40 +0000 | [diff] [blame] | 1023 | def redirect(h, req, url=to_url): |
| 1024 | h.http_error_302(req, MockFile(), 302, "Blah", |
| 1025 | MockHeaders({"location": url})) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 1026 | # Note that the *original* request shares the same record of |
| 1027 | # redirections with the sub-requests caused by the redirections. |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 1028 | |
Martin v. Löwis | 2a6ba90 | 2004-05-31 18:22:40 +0000 | [diff] [blame] | 1029 | # detect infinite loop redirect of a URL to itself |
| 1030 | req = Request(from_url, origin_req_host="example.com") |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 1031 | count = 0 |
Senthil Kumaran | fb8cc2f | 2009-07-19 02:44:19 +0000 | [diff] [blame] | 1032 | req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 1033 | try: |
| 1034 | while 1: |
Martin v. Löwis | 2a6ba90 | 2004-05-31 18:22:40 +0000 | [diff] [blame] | 1035 | redirect(h, req, "http://example.com/") |
| 1036 | count = count + 1 |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1037 | except urllib.error.HTTPError: |
Martin v. Löwis | 2a6ba90 | 2004-05-31 18:22:40 +0000 | [diff] [blame] | 1038 | # don't stop until max_repeats, because cookies may introduce state |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1039 | self.assertEqual(count, urllib.request.HTTPRedirectHandler.max_repeats) |
Martin v. Löwis | 2a6ba90 | 2004-05-31 18:22:40 +0000 | [diff] [blame] | 1040 | |
| 1041 | # detect endless non-repeating chain of redirects |
| 1042 | req = Request(from_url, origin_req_host="example.com") |
| 1043 | count = 0 |
Senthil Kumaran | fb8cc2f | 2009-07-19 02:44:19 +0000 | [diff] [blame] | 1044 | req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT |
Martin v. Löwis | 2a6ba90 | 2004-05-31 18:22:40 +0000 | [diff] [blame] | 1045 | try: |
| 1046 | while 1: |
| 1047 | redirect(h, req, "http://example.com/%d" % count) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 1048 | count = count + 1 |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1049 | except urllib.error.HTTPError: |
Jeremy Hylton | df38ea9 | 2003-12-17 20:42:38 +0000 | [diff] [blame] | 1050 | self.assertEqual(count, |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1051 | urllib.request.HTTPRedirectHandler.max_redirections) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 1052 | |
guido@google.com | a119df9 | 2011-03-29 11:41:02 -0700 | [diff] [blame] | 1053 | |
| 1054 | def test_invalid_redirect(self): |
| 1055 | from_url = "http://example.com/a.html" |
| 1056 | valid_schemes = ['http','https','ftp'] |
| 1057 | invalid_schemes = ['file','imap','ldap'] |
| 1058 | schemeless_url = "example.com/b.html" |
| 1059 | h = urllib.request.HTTPRedirectHandler() |
| 1060 | o = h.parent = MockOpener() |
| 1061 | req = Request(from_url) |
| 1062 | req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT |
| 1063 | |
| 1064 | for scheme in invalid_schemes: |
| 1065 | invalid_url = scheme + '://' + schemeless_url |
| 1066 | self.assertRaises(urllib.error.HTTPError, h.http_error_302, |
| 1067 | req, MockFile(), 302, "Security Loophole", |
| 1068 | MockHeaders({"location": invalid_url})) |
| 1069 | |
| 1070 | for scheme in valid_schemes: |
| 1071 | valid_url = scheme + '://' + schemeless_url |
| 1072 | h.http_error_302(req, MockFile(), 302, "That's fine", |
| 1073 | MockHeaders({"location": valid_url})) |
| 1074 | self.assertEqual(o.req.get_full_url(), valid_url) |
| 1075 | |
Senthil Kumaran | 6497aa3 | 2012-01-04 13:46:59 +0800 | [diff] [blame] | 1076 | def test_relative_redirect(self): |
| 1077 | from_url = "http://example.com/a.html" |
| 1078 | relative_url = "/b.html" |
| 1079 | h = urllib.request.HTTPRedirectHandler() |
| 1080 | o = h.parent = MockOpener() |
| 1081 | req = Request(from_url) |
| 1082 | req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT |
| 1083 | |
| 1084 | valid_url = urllib.parse.urljoin(from_url,relative_url) |
| 1085 | h.http_error_302(req, MockFile(), 302, "That's fine", |
| 1086 | MockHeaders({"location": valid_url})) |
| 1087 | self.assertEqual(o.req.get_full_url(), valid_url) |
| 1088 | |
Martin v. Löwis | 2a6ba90 | 2004-05-31 18:22:40 +0000 | [diff] [blame] | 1089 | def test_cookie_redirect(self): |
Martin v. Löwis | 2a6ba90 | 2004-05-31 18:22:40 +0000 | [diff] [blame] | 1090 | # cookies shouldn't leak into redirected requests |
Georg Brandl | 2442015 | 2008-05-26 16:32:26 +0000 | [diff] [blame] | 1091 | from http.cookiejar import CookieJar |
| 1092 | from test.test_http_cookiejar import interact_netscape |
Martin v. Löwis | 2a6ba90 | 2004-05-31 18:22:40 +0000 | [diff] [blame] | 1093 | |
| 1094 | cj = CookieJar() |
| 1095 | interact_netscape(cj, "http://www.example.com/", "spam=eggs") |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1096 | hh = MockHTTPHandler(302, "Location: http://www.cracker.com/\r\n\r\n") |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1097 | hdeh = urllib.request.HTTPDefaultErrorHandler() |
| 1098 | hrh = urllib.request.HTTPRedirectHandler() |
| 1099 | cp = urllib.request.HTTPCookieProcessor(cj) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1100 | o = build_test_opener(hh, hdeh, hrh, cp) |
Martin v. Löwis | 2a6ba90 | 2004-05-31 18:22:40 +0000 | [diff] [blame] | 1101 | o.open("http://www.example.com/") |
Florent Xicluna | 419e384 | 2010-08-08 16:16:07 +0000 | [diff] [blame] | 1102 | self.assertFalse(hh.req.has_header("Cookie")) |
Martin v. Löwis | 2a6ba90 | 2004-05-31 18:22:40 +0000 | [diff] [blame] | 1103 | |
Senthil Kumaran | 2643041 | 2011-04-13 07:01:19 +0800 | [diff] [blame] | 1104 | def test_redirect_fragment(self): |
| 1105 | redirected_url = 'http://www.example.com/index.html#OK\r\n\r\n' |
| 1106 | hh = MockHTTPHandler(302, 'Location: ' + redirected_url) |
| 1107 | hdeh = urllib.request.HTTPDefaultErrorHandler() |
| 1108 | hrh = urllib.request.HTTPRedirectHandler() |
| 1109 | o = build_test_opener(hh, hdeh, hrh) |
| 1110 | fp = o.open('http://www.example.com') |
| 1111 | self.assertEqual(fp.geturl(), redirected_url.strip()) |
| 1112 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 1113 | def test_proxy(self): |
| 1114 | o = OpenerDirector() |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1115 | ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128")) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 1116 | o.add_handler(ph) |
| 1117 | meth_spec = [ |
| 1118 | [("http_open", "return response")] |
| 1119 | ] |
| 1120 | handlers = add_ordered_mock_handlers(o, meth_spec) |
| 1121 | |
| 1122 | req = Request("http://acme.example.com/") |
Senthil Kumaran | 77ebfcc | 2012-08-20 13:43:59 -0700 | [diff] [blame] | 1123 | self.assertEqual(req.host, "acme.example.com") |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 1124 | o.open(req) |
Senthil Kumaran | 77ebfcc | 2012-08-20 13:43:59 -0700 | [diff] [blame] | 1125 | self.assertEqual(req.host, "proxy.example.com:3128") |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 1126 | |
| 1127 | self.assertEqual([(handlers[0], "http_open")], |
| 1128 | [tup[0:2] for tup in o.calls]) |
| 1129 | |
Senthil Kumaran | 7bb0497 | 2009-10-11 04:58:55 +0000 | [diff] [blame] | 1130 | def test_proxy_no_proxy(self): |
| 1131 | os.environ['no_proxy'] = 'python.org' |
| 1132 | o = OpenerDirector() |
| 1133 | ph = urllib.request.ProxyHandler(dict(http="proxy.example.com")) |
| 1134 | o.add_handler(ph) |
| 1135 | req = Request("http://www.perl.org/") |
Senthil Kumaran | 77ebfcc | 2012-08-20 13:43:59 -0700 | [diff] [blame] | 1136 | self.assertEqual(req.host, "www.perl.org") |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 1137 | o.open(req) |
Senthil Kumaran | 77ebfcc | 2012-08-20 13:43:59 -0700 | [diff] [blame] | 1138 | self.assertEqual(req.host, "proxy.example.com") |
Senthil Kumaran | 7bb0497 | 2009-10-11 04:58:55 +0000 | [diff] [blame] | 1139 | req = Request("http://www.python.org") |
Senthil Kumaran | 77ebfcc | 2012-08-20 13:43:59 -0700 | [diff] [blame] | 1140 | self.assertEqual(req.host, "www.python.org") |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 1141 | o.open(req) |
Senthil Kumaran | 77ebfcc | 2012-08-20 13:43:59 -0700 | [diff] [blame] | 1142 | self.assertEqual(req.host, "www.python.org") |
Senthil Kumaran | 7bb0497 | 2009-10-11 04:58:55 +0000 | [diff] [blame] | 1143 | del os.environ['no_proxy'] |
| 1144 | |
Ronald Oussoren | e72e161 | 2011-03-14 18:15:25 -0400 | [diff] [blame] | 1145 | def test_proxy_no_proxy_all(self): |
| 1146 | os.environ['no_proxy'] = '*' |
| 1147 | o = OpenerDirector() |
| 1148 | ph = urllib.request.ProxyHandler(dict(http="proxy.example.com")) |
| 1149 | o.add_handler(ph) |
| 1150 | req = Request("http://www.python.org") |
Senthil Kumaran | 77ebfcc | 2012-08-20 13:43:59 -0700 | [diff] [blame] | 1151 | self.assertEqual(req.host, "www.python.org") |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 1152 | o.open(req) |
Senthil Kumaran | 77ebfcc | 2012-08-20 13:43:59 -0700 | [diff] [blame] | 1153 | self.assertEqual(req.host, "www.python.org") |
Ronald Oussoren | e72e161 | 2011-03-14 18:15:25 -0400 | [diff] [blame] | 1154 | del os.environ['no_proxy'] |
| 1155 | |
Senthil Kumaran | 7bb0497 | 2009-10-11 04:58:55 +0000 | [diff] [blame] | 1156 | |
Senthil Kumaran | 97f0c6b | 2009-07-25 04:24:38 +0000 | [diff] [blame] | 1157 | def test_proxy_https(self): |
| 1158 | o = OpenerDirector() |
| 1159 | ph = urllib.request.ProxyHandler(dict(https="proxy.example.com:3128")) |
| 1160 | o.add_handler(ph) |
| 1161 | meth_spec = [ |
| 1162 | [("https_open", "return response")] |
| 1163 | ] |
| 1164 | handlers = add_ordered_mock_handlers(o, meth_spec) |
| 1165 | |
| 1166 | req = Request("https://www.example.com/") |
Senthil Kumaran | 77ebfcc | 2012-08-20 13:43:59 -0700 | [diff] [blame] | 1167 | self.assertEqual(req.host, "www.example.com") |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 1168 | o.open(req) |
Senthil Kumaran | 77ebfcc | 2012-08-20 13:43:59 -0700 | [diff] [blame] | 1169 | self.assertEqual(req.host, "proxy.example.com:3128") |
Senthil Kumaran | 97f0c6b | 2009-07-25 04:24:38 +0000 | [diff] [blame] | 1170 | self.assertEqual([(handlers[0], "https_open")], |
| 1171 | [tup[0:2] for tup in o.calls]) |
| 1172 | |
Senthil Kumaran | 47fff87 | 2009-12-20 07:10:31 +0000 | [diff] [blame] | 1173 | def test_proxy_https_proxy_authorization(self): |
| 1174 | o = OpenerDirector() |
| 1175 | ph = urllib.request.ProxyHandler(dict(https='proxy.example.com:3128')) |
| 1176 | o.add_handler(ph) |
| 1177 | https_handler = MockHTTPSHandler() |
| 1178 | o.add_handler(https_handler) |
| 1179 | req = Request("https://www.example.com/") |
| 1180 | req.add_header("Proxy-Authorization","FooBar") |
| 1181 | req.add_header("User-Agent","Grail") |
Senthil Kumaran | 77ebfcc | 2012-08-20 13:43:59 -0700 | [diff] [blame] | 1182 | self.assertEqual(req.host, "www.example.com") |
Senthil Kumaran | 47fff87 | 2009-12-20 07:10:31 +0000 | [diff] [blame] | 1183 | self.assertIsNone(req._tunnel_host) |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 1184 | o.open(req) |
Senthil Kumaran | 47fff87 | 2009-12-20 07:10:31 +0000 | [diff] [blame] | 1185 | # Verify Proxy-Authorization gets tunneled to request. |
| 1186 | # httpsconn req_headers do not have the Proxy-Authorization header but |
| 1187 | # the req will have. |
Ezio Melotti | b58e0bd | 2010-01-23 15:40:09 +0000 | [diff] [blame] | 1188 | self.assertNotIn(("Proxy-Authorization","FooBar"), |
Senthil Kumaran | 47fff87 | 2009-12-20 07:10:31 +0000 | [diff] [blame] | 1189 | https_handler.httpconn.req_headers) |
Ezio Melotti | b58e0bd | 2010-01-23 15:40:09 +0000 | [diff] [blame] | 1190 | self.assertIn(("User-Agent","Grail"), |
| 1191 | https_handler.httpconn.req_headers) |
Senthil Kumaran | 47fff87 | 2009-12-20 07:10:31 +0000 | [diff] [blame] | 1192 | self.assertIsNotNone(req._tunnel_host) |
Senthil Kumaran | 77ebfcc | 2012-08-20 13:43:59 -0700 | [diff] [blame] | 1193 | self.assertEqual(req.host, "proxy.example.com:3128") |
Senthil Kumaran | 47fff87 | 2009-12-20 07:10:31 +0000 | [diff] [blame] | 1194 | self.assertEqual(req.get_header("Proxy-authorization"),"FooBar") |
Senthil Kumaran | 97f0c6b | 2009-07-25 04:24:38 +0000 | [diff] [blame] | 1195 | |
Senthil Kumaran | 4de00a2 | 2011-05-11 21:17:57 +0800 | [diff] [blame] | 1196 | # TODO: This should be only for OSX |
| 1197 | @unittest.skipUnless(sys.platform == 'darwin', "only relevant for OSX") |
Ronald Oussoren | e72e161 | 2011-03-14 18:15:25 -0400 | [diff] [blame] | 1198 | def test_osx_proxy_bypass(self): |
| 1199 | bypass = { |
| 1200 | 'exclude_simple': False, |
| 1201 | 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.10', |
| 1202 | '10.0/16'] |
| 1203 | } |
| 1204 | # Check hosts that should trigger the proxy bypass |
| 1205 | for host in ('foo.bar', 'www.bar.com', '127.0.0.1', '10.10.0.1', |
| 1206 | '10.0.0.1'): |
| 1207 | self.assertTrue(_proxy_bypass_macosx_sysconf(host, bypass), |
| 1208 | 'expected bypass of %s to be True' % host) |
| 1209 | # Check hosts that should not trigger the proxy bypass |
| 1210 | for host in ('abc.foo.bar', 'bar.com', '127.0.0.2', '10.11.0.1', 'test'): |
| 1211 | self.assertFalse(_proxy_bypass_macosx_sysconf(host, bypass), |
| 1212 | 'expected bypass of %s to be False' % host) |
| 1213 | |
| 1214 | # Check the exclude_simple flag |
| 1215 | bypass = {'exclude_simple': True, 'exceptions': []} |
| 1216 | self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass)) |
| 1217 | |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 1218 | def test_basic_auth(self, quote_char='"'): |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1219 | opener = OpenerDirector() |
| 1220 | password_manager = MockPasswordManager() |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1221 | auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1222 | realm = "ACME Widget Store" |
| 1223 | http_handler = MockHTTPHandler( |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 1224 | 401, 'WWW-Authenticate: Basic realm=%s%s%s\r\n\r\n' % |
| 1225 | (quote_char, realm, quote_char) ) |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 1226 | opener.add_handler(auth_handler) |
| 1227 | opener.add_handler(http_handler) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1228 | self._test_basic_auth(opener, auth_handler, "Authorization", |
| 1229 | realm, http_handler, password_manager, |
| 1230 | "http://acme.example.com/protected", |
| 1231 | "http://acme.example.com/protected", |
| 1232 | ) |
| 1233 | |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 1234 | def test_basic_auth_with_single_quoted_realm(self): |
| 1235 | self.test_basic_auth(quote_char="'") |
| 1236 | |
Senthil Kumaran | 34f3fcc | 2012-05-15 22:30:25 +0800 | [diff] [blame] | 1237 | def test_basic_auth_with_unquoted_realm(self): |
| 1238 | opener = OpenerDirector() |
| 1239 | password_manager = MockPasswordManager() |
| 1240 | auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager) |
| 1241 | realm = "ACME Widget Store" |
| 1242 | http_handler = MockHTTPHandler( |
| 1243 | 401, 'WWW-Authenticate: Basic realm=%s\r\n\r\n' % realm) |
| 1244 | opener.add_handler(auth_handler) |
| 1245 | opener.add_handler(http_handler) |
Senthil Kumaran | 0ea91cb | 2012-05-15 23:59:42 +0800 | [diff] [blame] | 1246 | with self.assertWarns(UserWarning): |
| 1247 | self._test_basic_auth(opener, auth_handler, "Authorization", |
| 1248 | realm, http_handler, password_manager, |
| 1249 | "http://acme.example.com/protected", |
| 1250 | "http://acme.example.com/protected", |
| 1251 | ) |
Senthil Kumaran | 34f3fcc | 2012-05-15 22:30:25 +0800 | [diff] [blame] | 1252 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1253 | def test_proxy_basic_auth(self): |
| 1254 | opener = OpenerDirector() |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1255 | ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128")) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1256 | opener.add_handler(ph) |
| 1257 | password_manager = MockPasswordManager() |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1258 | auth_handler = urllib.request.ProxyBasicAuthHandler(password_manager) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1259 | realm = "ACME Networks" |
| 1260 | http_handler = MockHTTPHandler( |
| 1261 | 407, 'Proxy-Authenticate: Basic realm="%s"\r\n\r\n' % realm) |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 1262 | opener.add_handler(auth_handler) |
| 1263 | opener.add_handler(http_handler) |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 1264 | self._test_basic_auth(opener, auth_handler, "Proxy-authorization", |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1265 | realm, http_handler, password_manager, |
| 1266 | "http://acme.example.com:3128/protected", |
| 1267 | "proxy.example.com:3128", |
| 1268 | ) |
| 1269 | |
| 1270 | def test_basic_and_digest_auth_handlers(self): |
Andrew Svetlov | 7bd61cb | 2012-12-19 22:49:25 +0200 | [diff] [blame] | 1271 | # HTTPDigestAuthHandler raised an exception if it couldn't handle a 40* |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1272 | # response (http://python.org/sf/1479302), where it should instead |
| 1273 | # return None to allow another handler (especially |
| 1274 | # HTTPBasicAuthHandler) to handle the response. |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 1275 | |
| 1276 | # Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must |
| 1277 | # try digest first (since it's the strongest auth scheme), so we record |
| 1278 | # order of calls here to check digest comes first: |
| 1279 | class RecordingOpenerDirector(OpenerDirector): |
| 1280 | def __init__(self): |
| 1281 | OpenerDirector.__init__(self) |
| 1282 | self.recorded = [] |
| 1283 | def record(self, info): |
| 1284 | self.recorded.append(info) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1285 | class TestDigestAuthHandler(urllib.request.HTTPDigestAuthHandler): |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 1286 | def http_error_401(self, *args, **kwds): |
| 1287 | self.parent.record("digest") |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1288 | urllib.request.HTTPDigestAuthHandler.http_error_401(self, |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 1289 | *args, **kwds) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1290 | class TestBasicAuthHandler(urllib.request.HTTPBasicAuthHandler): |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 1291 | def http_error_401(self, *args, **kwds): |
| 1292 | self.parent.record("basic") |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1293 | urllib.request.HTTPBasicAuthHandler.http_error_401(self, |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 1294 | *args, **kwds) |
| 1295 | |
| 1296 | opener = RecordingOpenerDirector() |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1297 | password_manager = MockPasswordManager() |
| 1298 | digest_handler = TestDigestAuthHandler(password_manager) |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 1299 | basic_handler = TestBasicAuthHandler(password_manager) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1300 | realm = "ACME Networks" |
| 1301 | http_handler = MockHTTPHandler( |
| 1302 | 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm) |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 1303 | opener.add_handler(basic_handler) |
| 1304 | opener.add_handler(digest_handler) |
| 1305 | opener.add_handler(http_handler) |
| 1306 | |
| 1307 | # check basic auth isn't blocked by digest handler failing |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1308 | self._test_basic_auth(opener, basic_handler, "Authorization", |
| 1309 | realm, http_handler, password_manager, |
| 1310 | "http://acme.example.com/protected", |
| 1311 | "http://acme.example.com/protected", |
| 1312 | ) |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 1313 | # check digest was tried before basic (twice, because |
| 1314 | # _test_basic_auth called .open() twice) |
| 1315 | self.assertEqual(opener.recorded, ["digest", "basic"]*2) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1316 | |
Senthil Kumaran | 4de00a2 | 2011-05-11 21:17:57 +0800 | [diff] [blame] | 1317 | def test_unsupported_auth_digest_handler(self): |
| 1318 | opener = OpenerDirector() |
| 1319 | # While using DigestAuthHandler |
| 1320 | digest_auth_handler = urllib.request.HTTPDigestAuthHandler(None) |
| 1321 | http_handler = MockHTTPHandler( |
| 1322 | 401, 'WWW-Authenticate: Kerberos\r\n\r\n') |
| 1323 | opener.add_handler(digest_auth_handler) |
| 1324 | opener.add_handler(http_handler) |
| 1325 | self.assertRaises(ValueError,opener.open,"http://www.example.com") |
| 1326 | |
| 1327 | def test_unsupported_auth_basic_handler(self): |
| 1328 | # While using BasicAuthHandler |
| 1329 | opener = OpenerDirector() |
| 1330 | basic_auth_handler = urllib.request.HTTPBasicAuthHandler(None) |
| 1331 | http_handler = MockHTTPHandler( |
| 1332 | 401, 'WWW-Authenticate: NTLM\r\n\r\n') |
| 1333 | opener.add_handler(basic_auth_handler) |
| 1334 | opener.add_handler(http_handler) |
| 1335 | self.assertRaises(ValueError,opener.open,"http://www.example.com") |
| 1336 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1337 | def _test_basic_auth(self, opener, auth_handler, auth_header, |
| 1338 | realm, http_handler, password_manager, |
| 1339 | request_url, protected_url): |
Christian Heimes | 05e8be1 | 2008-02-23 18:30:17 +0000 | [diff] [blame] | 1340 | import base64 |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1341 | user, password = "wile", "coyote" |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1342 | |
| 1343 | # .add_password() fed through to password manager |
| 1344 | auth_handler.add_password(realm, request_url, user, password) |
| 1345 | self.assertEqual(realm, password_manager.realm) |
| 1346 | self.assertEqual(request_url, password_manager.url) |
| 1347 | self.assertEqual(user, password_manager.user) |
| 1348 | self.assertEqual(password, password_manager.password) |
| 1349 | |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 1350 | opener.open(request_url) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1351 | |
| 1352 | # should have asked the password manager for the username/password |
| 1353 | self.assertEqual(password_manager.target_realm, realm) |
| 1354 | self.assertEqual(password_manager.target_url, protected_url) |
| 1355 | |
| 1356 | # expect one request without authorization, then one with |
| 1357 | self.assertEqual(len(http_handler.requests), 2) |
| 1358 | self.assertFalse(http_handler.requests[0].has_header(auth_header)) |
Guido van Rossum | 98b349f | 2007-08-27 21:47:52 +0000 | [diff] [blame] | 1359 | userpass = bytes('%s:%s' % (user, password), "ascii") |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 1360 | auth_hdr_value = ('Basic ' + |
Georg Brandl | 706824f | 2009-06-04 09:42:55 +0000 | [diff] [blame] | 1361 | base64.encodebytes(userpass).strip().decode()) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1362 | self.assertEqual(http_handler.requests[1].get_header(auth_header), |
| 1363 | auth_hdr_value) |
Senthil Kumaran | ca2fc9e | 2010-02-24 16:53:16 +0000 | [diff] [blame] | 1364 | self.assertEqual(http_handler.requests[1].unredirected_hdrs[auth_header], |
| 1365 | auth_hdr_value) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1366 | # if the password manager can't find a password, the handler won't |
| 1367 | # handle the HTTP auth error |
| 1368 | password_manager.user = password_manager.password = None |
| 1369 | http_handler.reset() |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 1370 | opener.open(request_url) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1371 | self.assertEqual(len(http_handler.requests), 1) |
| 1372 | self.assertFalse(http_handler.requests[0].has_header(auth_header)) |
| 1373 | |
Senthil Kumaran | 4de00a2 | 2011-05-11 21:17:57 +0800 | [diff] [blame] | 1374 | |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 1375 | class MiscTests(unittest.TestCase): |
| 1376 | |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 1377 | def opener_has_handler(self, opener, handler_class): |
| 1378 | self.assertTrue(any(h.__class__ == handler_class |
| 1379 | for h in opener.handlers)) |
| 1380 | |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 1381 | def test_build_opener(self): |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1382 | class MyHTTPHandler(urllib.request.HTTPHandler): pass |
| 1383 | class FooHandler(urllib.request.BaseHandler): |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 1384 | def foo_open(self): pass |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1385 | class BarHandler(urllib.request.BaseHandler): |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 1386 | def bar_open(self): pass |
| 1387 | |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1388 | build_opener = urllib.request.build_opener |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 1389 | |
| 1390 | o = build_opener(FooHandler, BarHandler) |
| 1391 | self.opener_has_handler(o, FooHandler) |
| 1392 | self.opener_has_handler(o, BarHandler) |
| 1393 | |
| 1394 | # can take a mix of classes and instances |
| 1395 | o = build_opener(FooHandler, BarHandler()) |
| 1396 | self.opener_has_handler(o, FooHandler) |
| 1397 | self.opener_has_handler(o, BarHandler) |
| 1398 | |
| 1399 | # subclasses of default handlers override default handlers |
| 1400 | o = build_opener(MyHTTPHandler) |
| 1401 | self.opener_has_handler(o, MyHTTPHandler) |
| 1402 | |
| 1403 | # a particular case of overriding: default handlers can be passed |
| 1404 | # in explicitly |
| 1405 | o = build_opener() |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1406 | self.opener_has_handler(o, urllib.request.HTTPHandler) |
| 1407 | o = build_opener(urllib.request.HTTPHandler) |
| 1408 | self.opener_has_handler(o, urllib.request.HTTPHandler) |
| 1409 | o = build_opener(urllib.request.HTTPHandler()) |
| 1410 | self.opener_has_handler(o, urllib.request.HTTPHandler) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 1411 | |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 1412 | # Issue2670: multiple handlers sharing the same base class |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1413 | class MyOtherHTTPHandler(urllib.request.HTTPHandler): pass |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 1414 | o = build_opener(MyHTTPHandler, MyOtherHTTPHandler) |
| 1415 | self.opener_has_handler(o, MyHTTPHandler) |
| 1416 | self.opener_has_handler(o, MyOtherHTTPHandler) |
| 1417 | |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 1418 | def test_HTTPError_interface(self): |
| 1419 | """ |
| 1420 | Issue 13211 reveals that HTTPError didn't implement the URLError |
| 1421 | interface even though HTTPError is a subclass of URLError. |
| 1422 | """ |
| 1423 | msg = 'something bad happened' |
| 1424 | url = code = fp = None |
| 1425 | hdrs = 'Content-Length: 42' |
| 1426 | err = urllib.error.HTTPError(url, code, msg, hdrs, fp) |
| 1427 | self.assertTrue(hasattr(err, 'reason')) |
| 1428 | self.assertEqual(err.reason, 'something bad happened') |
| 1429 | self.assertTrue(hasattr(err, 'hdrs')) |
| 1430 | self.assertEqual(err.hdrs, 'Content-Length: 42') |
| 1431 | expected_errmsg = 'HTTP Error %s: %s' % (err.code, err.msg) |
| 1432 | self.assertEqual(str(err), expected_errmsg) |
| 1433 | |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 1434 | |
Benjamin Peterson | 6ebe78f | 2008-12-21 00:06:59 +0000 | [diff] [blame] | 1435 | class RequestTests(unittest.TestCase): |
| 1436 | |
| 1437 | def setUp(self): |
| 1438 | self.get = Request("http://www.python.org/~jeremy/") |
| 1439 | self.post = Request("http://www.python.org/~jeremy/", |
| 1440 | "data", |
| 1441 | headers={"X-Test": "test"}) |
| 1442 | |
| 1443 | def test_method(self): |
| 1444 | self.assertEqual("POST", self.post.get_method()) |
| 1445 | self.assertEqual("GET", self.get.get_method()) |
| 1446 | |
Senthil Kumaran | 77ebfcc | 2012-08-20 13:43:59 -0700 | [diff] [blame] | 1447 | def test_data(self): |
| 1448 | self.assertFalse(self.get.data) |
Benjamin Peterson | 6ebe78f | 2008-12-21 00:06:59 +0000 | [diff] [blame] | 1449 | self.assertEqual("GET", self.get.get_method()) |
Senthil Kumaran | 77ebfcc | 2012-08-20 13:43:59 -0700 | [diff] [blame] | 1450 | self.get.data = "spam" |
| 1451 | self.assertTrue(self.get.data) |
Benjamin Peterson | 6ebe78f | 2008-12-21 00:06:59 +0000 | [diff] [blame] | 1452 | self.assertEqual("POST", self.get.get_method()) |
| 1453 | |
| 1454 | def test_get_full_url(self): |
| 1455 | self.assertEqual("http://www.python.org/~jeremy/", |
| 1456 | self.get.get_full_url()) |
| 1457 | |
| 1458 | def test_selector(self): |
Senthil Kumaran | 77ebfcc | 2012-08-20 13:43:59 -0700 | [diff] [blame] | 1459 | self.assertEqual("/~jeremy/", self.get.selector) |
Benjamin Peterson | 6ebe78f | 2008-12-21 00:06:59 +0000 | [diff] [blame] | 1460 | req = Request("http://www.python.org/") |
Senthil Kumaran | 77ebfcc | 2012-08-20 13:43:59 -0700 | [diff] [blame] | 1461 | self.assertEqual("/", req.selector) |
Benjamin Peterson | 6ebe78f | 2008-12-21 00:06:59 +0000 | [diff] [blame] | 1462 | |
| 1463 | def test_get_type(self): |
Senthil Kumaran | 77ebfcc | 2012-08-20 13:43:59 -0700 | [diff] [blame] | 1464 | self.assertEqual("http", self.get.type) |
Benjamin Peterson | 6ebe78f | 2008-12-21 00:06:59 +0000 | [diff] [blame] | 1465 | |
| 1466 | def test_get_host(self): |
Senthil Kumaran | 77ebfcc | 2012-08-20 13:43:59 -0700 | [diff] [blame] | 1467 | self.assertEqual("www.python.org", self.get.host) |
Benjamin Peterson | 6ebe78f | 2008-12-21 00:06:59 +0000 | [diff] [blame] | 1468 | |
| 1469 | def test_get_host_unquote(self): |
| 1470 | req = Request("http://www.%70ython.org/") |
Senthil Kumaran | 77ebfcc | 2012-08-20 13:43:59 -0700 | [diff] [blame] | 1471 | self.assertEqual("www.python.org", req.host) |
Benjamin Peterson | 6ebe78f | 2008-12-21 00:06:59 +0000 | [diff] [blame] | 1472 | |
| 1473 | def test_proxy(self): |
Florent Xicluna | 419e384 | 2010-08-08 16:16:07 +0000 | [diff] [blame] | 1474 | self.assertFalse(self.get.has_proxy()) |
Benjamin Peterson | 6ebe78f | 2008-12-21 00:06:59 +0000 | [diff] [blame] | 1475 | self.get.set_proxy("www.perl.org", "http") |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1476 | self.assertTrue(self.get.has_proxy()) |
Senthil Kumaran | 77ebfcc | 2012-08-20 13:43:59 -0700 | [diff] [blame] | 1477 | self.assertEqual("www.python.org", self.get.origin_req_host) |
| 1478 | self.assertEqual("www.perl.org", self.get.host) |
Benjamin Peterson | 6ebe78f | 2008-12-21 00:06:59 +0000 | [diff] [blame] | 1479 | |
Senthil Kumaran | d95cc75 | 2010-08-08 11:27:53 +0000 | [diff] [blame] | 1480 | def test_wrapped_url(self): |
| 1481 | req = Request("<URL:http://www.python.org>") |
Senthil Kumaran | 77ebfcc | 2012-08-20 13:43:59 -0700 | [diff] [blame] | 1482 | self.assertEqual("www.python.org", req.host) |
Senthil Kumaran | d95cc75 | 2010-08-08 11:27:53 +0000 | [diff] [blame] | 1483 | |
Senthil Kumaran | 2643041 | 2011-04-13 07:01:19 +0800 | [diff] [blame] | 1484 | def test_url_fragment(self): |
Senthil Kumaran | d95cc75 | 2010-08-08 11:27:53 +0000 | [diff] [blame] | 1485 | req = Request("http://www.python.org/?qs=query#fragment=true") |
Senthil Kumaran | 77ebfcc | 2012-08-20 13:43:59 -0700 | [diff] [blame] | 1486 | self.assertEqual("/?qs=query", req.selector) |
Senthil Kumaran | d95cc75 | 2010-08-08 11:27:53 +0000 | [diff] [blame] | 1487 | req = Request("http://www.python.org/#fun=true") |
Senthil Kumaran | 77ebfcc | 2012-08-20 13:43:59 -0700 | [diff] [blame] | 1488 | self.assertEqual("/", req.selector) |
Senthil Kumaran | d95cc75 | 2010-08-08 11:27:53 +0000 | [diff] [blame] | 1489 | |
Senthil Kumaran | 2643041 | 2011-04-13 07:01:19 +0800 | [diff] [blame] | 1490 | # Issue 11703: geturl() omits fragment in the original URL. |
| 1491 | url = 'http://docs.python.org/library/urllib2.html#OK' |
| 1492 | req = Request(url) |
| 1493 | self.assertEqual(req.get_full_url(), url) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 1494 | |
Senthil Kumaran | 41e66a2 | 2012-12-23 09:04:24 -0800 | [diff] [blame] | 1495 | def test_HTTPError_interface_call(self): |
| 1496 | """ |
| 1497 | Issue 15701 - HTTPError interface has info method available from URLError |
| 1498 | """ |
| 1499 | err = urllib.request.HTTPError(msg="something bad happened", url=None, |
| 1500 | code=None, hdrs='Content-Length:42', fp=None) |
| 1501 | self.assertTrue(hasattr(err, 'reason')) |
| 1502 | assert hasattr(err, 'reason') |
| 1503 | assert hasattr(err, 'info') |
| 1504 | assert callable(err.info) |
| 1505 | try: |
| 1506 | err.info() |
| 1507 | except AttributeError: |
| 1508 | self.fail('err.info call failed.') |
| 1509 | self.assertEqual(err.info(), "Content-Length:42") |
Jason R. Coombs | aa204db | 2011-11-07 10:50:32 -0500 | [diff] [blame] | 1510 | |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 1511 | def test_main(verbose=None): |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1512 | from test import test_urllib2 |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1513 | support.run_doctest(test_urllib2, verbose) |
Jeremy Hylton | 1afc169 | 2008-06-18 20:49:58 +0000 | [diff] [blame] | 1514 | support.run_doctest(urllib.request, verbose) |
Andrew M. Kuchling | bd3200f | 2004-06-29 13:15:46 +0000 | [diff] [blame] | 1515 | tests = (TrivialTests, |
| 1516 | OpenerDirectorTests, |
| 1517 | HandlerTests, |
Benjamin Peterson | 6ebe78f | 2008-12-21 00:06:59 +0000 | [diff] [blame] | 1518 | MiscTests, |
Senthil Kumaran | d281c73 | 2013-04-09 06:00:16 -0700 | [diff] [blame] | 1519 | RequestTests, |
| 1520 | RequestHdrsTests) |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1521 | support.run_unittest(*tests) |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame] | 1522 | |
| 1523 | if __name__ == "__main__": |
| 1524 | test_main(verbose=True) |