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