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