Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame^] | 1 | import unittest |
| 2 | from test import test_support |
| 3 | |
Tim Peters | 861adac | 2001-07-16 20:49:49 +0000 | [diff] [blame] | 4 | import os |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame^] | 5 | import StringIO |
Jeremy Hylton | e3e6104 | 2001-05-09 15:50:25 +0000 | [diff] [blame] | 6 | |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame^] | 7 | import urllib2 |
| 8 | from urllib2 import Request, OpenerDirector |
Jeremy Hylton | e3e6104 | 2001-05-09 15:50:25 +0000 | [diff] [blame] | 9 | |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame^] | 10 | # XXX |
| 11 | # Request |
| 12 | # CacheFTPHandler (hard to write) |
| 13 | # parse_keqv_list, parse_http_list (I'm leaving this for Anthony Baxter |
| 14 | # and Greg Stein, since they're doing Digest Authentication) |
| 15 | # Authentication stuff (ditto) |
| 16 | # ProxyHandler, CustomProxy, CustomProxyHandler (I don't use a proxy) |
| 17 | # GopherHandler (haven't used gopher for a decade or so...) |
Jeremy Hylton | e3e6104 | 2001-05-09 15:50:25 +0000 | [diff] [blame] | 18 | |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame^] | 19 | class TrivialTests(unittest.TestCase): |
| 20 | def test_trivial(self): |
| 21 | # A couple trivial tests |
Guido van Rossum | e2ae77b | 2001-10-24 20:42:55 +0000 | [diff] [blame] | 22 | |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame^] | 23 | self.assertRaises(ValueError, urllib2.urlopen, 'bogus url') |
Tim Peters | 861adac | 2001-07-16 20:49:49 +0000 | [diff] [blame] | 24 | |
Jeremy Hylton | c1be59f | 2003-12-14 05:27:34 +0000 | [diff] [blame^] | 25 | # XXX Name hacking to get this to work on Windows. |
| 26 | fname = os.path.abspath(urllib2.__file__).replace('\\', '/') |
| 27 | if fname[1:2] == ":": |
| 28 | fname = fname[2:] |
| 29 | # And more hacking to get it to work on MacOS. This assumes |
| 30 | # urllib.pathname2url works, unfortunately... |
| 31 | if os.name == 'mac': |
| 32 | fname = '/' + fname.replace(':', '/') |
| 33 | elif os.name == 'riscos': |
| 34 | import string |
| 35 | fname = os.expand(fname) |
| 36 | fname = fname.translate(string.maketrans("/.", "./")) |
| 37 | |
| 38 | file_url = "file://%s" % fname |
| 39 | f = urllib2.urlopen(file_url) |
| 40 | |
| 41 | buf = f.read() |
| 42 | f.close() |
| 43 | |
| 44 | |
| 45 | class MockOpener: |
| 46 | addheaders = [] |
| 47 | def open(self, req, data=None): |
| 48 | self.req, self.data = req, data |
| 49 | def error(self, proto, *args): |
| 50 | self.proto, self.args = proto, args |
| 51 | |
| 52 | class MockFile: |
| 53 | def read(self, count=None): pass |
| 54 | def readline(self, count=None): pass |
| 55 | def close(self): pass |
| 56 | |
| 57 | class MockResponse(StringIO.StringIO): |
| 58 | def __init__(self, code, msg, headers, data, url=None): |
| 59 | StringIO.StringIO.__init__(self, data) |
| 60 | self.code, self.msg, self.headers, self.url = code, msg, headers, url |
| 61 | def info(self): |
| 62 | return self.headers |
| 63 | def geturl(self): |
| 64 | return self.url |
| 65 | |
| 66 | class FakeMethod: |
| 67 | def __init__(self, meth_name, action, handle): |
| 68 | self.meth_name = meth_name |
| 69 | self.handle = handle |
| 70 | self.action = action |
| 71 | def __call__(self, *args): |
| 72 | return self.handle(self.meth_name, self.action, *args) |
| 73 | |
| 74 | class MockHandler: |
| 75 | def __init__(self, methods): |
| 76 | self._define_methods(methods) |
| 77 | def _define_methods(self, methods): |
| 78 | for spec in methods: |
| 79 | if len(spec) == 2: name, action = spec |
| 80 | else: name, action = spec, None |
| 81 | meth = FakeMethod(name, action, self.handle) |
| 82 | setattr(self.__class__, name, meth) |
| 83 | def handle(self, fn_name, action, *args, **kwds): |
| 84 | self.parent.calls.append((self, fn_name, args, kwds)) |
| 85 | if action is None: |
| 86 | return None |
| 87 | elif action == "return self": |
| 88 | return self |
| 89 | elif action == "return response": |
| 90 | res = MockResponse(200, "OK", {}, "") |
| 91 | return res |
| 92 | elif action == "return request": |
| 93 | return Request("http://blah/") |
| 94 | elif action.startswith("error"): |
| 95 | code = action[action.rfind(" ")+1:] |
| 96 | try: |
| 97 | code = int(code) |
| 98 | except ValueError: |
| 99 | pass |
| 100 | res = MockResponse(200, "OK", {}, "") |
| 101 | return self.parent.error("http", args[0], res, code, "", {}) |
| 102 | elif action == "raise": |
| 103 | raise urllib2.URLError("blah") |
| 104 | assert False |
| 105 | def close(self): pass |
| 106 | def add_parent(self, parent): |
| 107 | self.parent = parent |
| 108 | self.parent.calls = [] |
| 109 | def __lt__(self, other): |
| 110 | if not hasattr(other, "handler_order"): |
| 111 | # No handler_order, leave in original order. Yuck. |
| 112 | return True |
| 113 | return self.handler_order < other.handler_order |
| 114 | |
| 115 | def add_ordered_mock_handlers(opener, meth_spec): |
| 116 | """Create MockHandlers and add them to an OpenerDirector. |
| 117 | |
| 118 | meth_spec: list of lists of tuples and strings defining methods to define |
| 119 | on handlers. eg: |
| 120 | |
| 121 | [["http_error", "ftp_open"], ["http_open"]] |
| 122 | |
| 123 | defines methods .http_error() and .ftp_open() on one handler, and |
| 124 | .http_open() on another. These methods just record their arguments and |
| 125 | return None. Using a tuple instead of a string causes the method to |
| 126 | perform some action (see MockHandler.handle()), eg: |
| 127 | |
| 128 | [["http_error"], [("http_open", "return request")]] |
| 129 | |
| 130 | defines .http_error() on one handler (which simply returns None), and |
| 131 | .http_open() on another handler, which returns a Request object. |
| 132 | |
| 133 | """ |
| 134 | handlers = [] |
| 135 | count = 0 |
| 136 | for meths in meth_spec: |
| 137 | class MockHandlerSubclass(MockHandler): pass |
| 138 | h = MockHandlerSubclass(meths) |
| 139 | h.handler_order = count |
| 140 | h.add_parent(opener) |
| 141 | count = count + 1 |
| 142 | handlers.append(h) |
| 143 | opener.add_handler(h) |
| 144 | return handlers |
| 145 | |
| 146 | class OpenerDirectorTests(unittest.TestCase): |
| 147 | |
| 148 | def test_handled(self): |
| 149 | # handler returning non-None means no more handlers will be called |
| 150 | o = OpenerDirector() |
| 151 | meth_spec = [ |
| 152 | ["http_open", "ftp_open", "http_error_302"], |
| 153 | ["ftp_open"], |
| 154 | [("http_open", "return self")], |
| 155 | [("http_open", "return self")], |
| 156 | ] |
| 157 | handlers = add_ordered_mock_handlers(o, meth_spec) |
| 158 | |
| 159 | req = Request("http://example.com/") |
| 160 | r = o.open(req) |
| 161 | # Second .http_open() gets called, third doesn't, since second returned |
| 162 | # non-None. Handlers without .http_open() never get any methods called |
| 163 | # on them. |
| 164 | # In fact, second mock handler defining .http_open() returns self |
| 165 | # (instead of response), which becomes the OpenerDirector's return |
| 166 | # value. |
| 167 | self.assert_(r == handlers[2]) |
| 168 | calls = [(handlers[0], "http_open"), (handlers[2], "http_open")] |
| 169 | for expected, got in zip(calls, o.calls): |
| 170 | handler, name, args, kwds = got |
| 171 | self.assert_((handler, name) == expected) |
| 172 | self.assert_(args == (req,)) |
| 173 | |
| 174 | def test_handler_order(self): |
| 175 | o = OpenerDirector() |
| 176 | handlers = [] |
| 177 | for meths, handler_order in [ |
| 178 | ([("http_open", "return self")], 500), |
| 179 | (["http_open"], 0), |
| 180 | ]: |
| 181 | class MockHandlerSubclass(MockHandler): pass |
| 182 | h = MockHandlerSubclass(meths) |
| 183 | h.handler_order = handler_order |
| 184 | handlers.append(h) |
| 185 | o.add_handler(h) |
| 186 | |
| 187 | r = o.open("http://example.com/") |
| 188 | # handlers called in reverse order, thanks to their sort order |
| 189 | self.assert_(o.calls[0][0] == handlers[1]) |
| 190 | self.assert_(o.calls[1][0] == handlers[0]) |
| 191 | |
| 192 | def test_raise(self): |
| 193 | # raising URLError stops processing of request |
| 194 | o = OpenerDirector() |
| 195 | meth_spec = [ |
| 196 | [("http_open", "raise")], |
| 197 | [("http_open", "return self")], |
| 198 | ] |
| 199 | handlers = add_ordered_mock_handlers(o, meth_spec) |
| 200 | |
| 201 | req = Request("http://example.com/") |
| 202 | self.assertRaises(urllib2.URLError, o.open, req) |
| 203 | self.assert_(o.calls == [(handlers[0], "http_open", (req,), {})]) |
| 204 | |
| 205 | ## def test_error(self): |
| 206 | ## # XXX this doesn't actually seem to be used in standard library, |
| 207 | ## # but should really be tested anyway... |
| 208 | |
| 209 | def test_http_error(self): |
| 210 | # XXX http_error_default |
| 211 | # http errors are a special case |
| 212 | o = OpenerDirector() |
| 213 | meth_spec = [ |
| 214 | [("http_open", "error 302")], |
| 215 | [("http_error_400", "raise"), "http_open"], |
| 216 | [("http_error_302", "return response"), "http_error_303", |
| 217 | "http_error"], |
| 218 | [("http_error_302")], |
| 219 | ] |
| 220 | handlers = add_ordered_mock_handlers(o, meth_spec) |
| 221 | |
| 222 | class Unknown: |
| 223 | def __eq__(self, other): return True |
| 224 | |
| 225 | req = Request("http://example.com/") |
| 226 | r = o.open(req) |
| 227 | assert len(o.calls) == 2 |
| 228 | calls = [(handlers[0], "http_open", (req,)), |
| 229 | (handlers[2], "http_error_302", (req, Unknown(), 302, "", {}))] |
| 230 | for expected, got in zip(calls, o.calls): |
| 231 | handler, method_name, args = expected |
| 232 | self.assert_((handler, method_name) == got[:2]) |
| 233 | assert args == got[2] |
| 234 | |
| 235 | def test_processors(self): |
| 236 | # *_request / *_response methods get called appropriately |
| 237 | o = OpenerDirector() |
| 238 | meth_spec = [ |
| 239 | [("http_request", "return request"), |
| 240 | ("http_response", "return response")], |
| 241 | [("http_request", "return request"), |
| 242 | ("http_response", "return response")], |
| 243 | ] |
| 244 | handlers = add_ordered_mock_handlers(o, meth_spec) |
| 245 | |
| 246 | req = Request("http://example.com/") |
| 247 | r = o.open(req) |
| 248 | # processor methods are called on *all* handlers that define them, |
| 249 | # not just the first handler that handles the request |
| 250 | calls = [(handlers[0], "http_request"), (handlers[1], "http_request"), |
| 251 | (handlers[0], "http_response"), (handlers[1], "http_response")] |
| 252 | |
| 253 | for i, (handler, name, args, kwds) in enumerate(o.calls): |
| 254 | if i < 2: |
| 255 | # *_request |
| 256 | self.assert_((handler, name) == calls[i]) |
| 257 | self.assert_(len(args) == 1) |
| 258 | self.assert_(isinstance(args[0], Request)) |
| 259 | else: |
| 260 | # *_response |
| 261 | self.assert_((handler, name) == calls[i]) |
| 262 | self.assert_(len(args) == 2) |
| 263 | self.assert_(isinstance(args[0], Request)) |
| 264 | # response from opener.open is None, because there's no |
| 265 | # handler that defines http_open to handle it |
| 266 | self.assert_(args[1] is None or |
| 267 | isinstance(args[1], MockResponse)) |
| 268 | |
| 269 | |
| 270 | class HandlerTests(unittest.TestCase): |
| 271 | |
| 272 | def test_ftp(self): |
| 273 | class MockFTPWrapper: |
| 274 | def __init__(self, data): self.data = data |
| 275 | def retrfile(self, filename, filetype): |
| 276 | self.filename, self.filetype = filename, filetype |
| 277 | return StringIO.StringIO(self.data), len(self.data) |
| 278 | |
| 279 | class NullFTPHandler(urllib2.FTPHandler): |
| 280 | def __init__(self, data): self.data = data |
| 281 | def connect_ftp(self, user, passwd, host, port, dirs): |
| 282 | self.user, self.passwd = user, passwd |
| 283 | self.host, self.port = host, port |
| 284 | self.dirs = dirs |
| 285 | self.ftpwrapper = MockFTPWrapper(self.data) |
| 286 | return self.ftpwrapper |
| 287 | |
| 288 | import ftplib, socket |
| 289 | data = "rheum rhaponicum" |
| 290 | h = NullFTPHandler(data) |
| 291 | o = h.parent = MockOpener() |
| 292 | |
| 293 | for url, host, port, type_, dirs, filename, mimetype in [ |
| 294 | ("ftp://localhost/foo/bar/baz.html", |
| 295 | "localhost", ftplib.FTP_PORT, "I", |
| 296 | ["foo", "bar"], "baz.html", "text/html"), |
| 297 | # XXXX Bug: FTPHandler tries to gethostbyname "localhost:80", with the |
| 298 | # port still there. |
| 299 | ## ("ftp://localhost:80/foo/bar/", |
| 300 | ## "localhost", 80, "D", |
| 301 | ## ["foo", "bar"], "", None), |
| 302 | # XXXX bug: second use of splitattr() in FTPHandler should be splitvalue() |
| 303 | ## ("ftp://localhost/baz.gif;type=a", |
| 304 | ## "localhost", ftplib.FTP_PORT, "A", |
| 305 | ## [], "baz.gif", "image/gif"), |
| 306 | ]: |
| 307 | r = h.ftp_open(Request(url)) |
| 308 | # ftp authentication not yet implemented by FTPHandler |
| 309 | self.assert_(h.user == h.passwd == "") |
| 310 | self.assert_(h.host == socket.gethostbyname(host)) |
| 311 | self.assert_(h.port == port) |
| 312 | self.assert_(h.dirs == dirs) |
| 313 | self.assert_(h.ftpwrapper.filename == filename) |
| 314 | self.assert_(h.ftpwrapper.filetype == type_) |
| 315 | headers = r.info() |
| 316 | self.assert_(headers["Content-type"] == mimetype) |
| 317 | self.assert_(int(headers["Content-length"]) == len(data)) |
| 318 | |
| 319 | def test_file(self): |
| 320 | import time, rfc822, socket |
| 321 | h = urllib2.FileHandler() |
| 322 | o = h.parent = MockOpener() |
| 323 | |
| 324 | #from test_support import TESTFN |
| 325 | TESTFN = "test.txt" |
| 326 | towrite = "hello, world\n" |
| 327 | for url in [ |
| 328 | "file://localhost%s/%s" % (os.getcwd(), TESTFN), |
| 329 | "file://%s/%s" % (os.getcwd(), TESTFN), |
| 330 | "file://%s%s/%s" % (socket.gethostbyname('localhost'), |
| 331 | os.getcwd(), TESTFN), |
| 332 | "file://%s%s/%s" % (socket.gethostbyname(socket.gethostname()), |
| 333 | os.getcwd(), TESTFN), |
| 334 | # XXX Windows / Mac format(s), ... ? |
| 335 | ]: |
| 336 | f = open(TESTFN, "w") |
| 337 | try: |
| 338 | try: |
| 339 | f.write(towrite) |
| 340 | finally: |
| 341 | f.close() |
| 342 | |
| 343 | r = h.file_open(Request(url)) |
| 344 | try: |
| 345 | data = r.read() |
| 346 | read_time = time.time() |
| 347 | headers = r.info() |
| 348 | newurl = r.geturl() |
| 349 | finally: |
| 350 | r.close() |
| 351 | finally: |
| 352 | os.remove(TESTFN) |
| 353 | self.assert_(data == towrite) |
| 354 | self.assert_(headers["Content-type"] == "text/plain") |
| 355 | self.assert_(headers["Content-length"] == "13") |
| 356 | # Fudge Last-modified string comparison by one second to |
| 357 | # prevent spurious failure on crossing a second boundary while |
| 358 | # executing this test. |
| 359 | unfudged = rfc822.formatdate(read_time) |
| 360 | fudged = rfc822.formatdate(read_time-1) |
| 361 | self.assert_(headers["Last-modified"] in [unfudged, fudged]) |
| 362 | |
| 363 | for url in [ |
| 364 | "file://localhost:80%s/%s" % (os.getcwd(), TESTFN), |
| 365 | # XXXX bug: these fail with socket.gaierror, should be URLError |
| 366 | ## "file://%s:80%s/%s" % (socket.gethostbyname('localhost'), |
| 367 | ## os.getcwd(), TESTFN), |
| 368 | ## "file://somerandomhost.ontheinternet.com%s/%s" % |
| 369 | ## (os.getcwd(), TESTFN), |
| 370 | ]: |
| 371 | try: |
| 372 | f = open(TESTFN, "w") |
| 373 | try: |
| 374 | f.write(towrite) |
| 375 | finally: |
| 376 | f.close() |
| 377 | |
| 378 | self.assertRaises(urllib2.URLError, |
| 379 | h.file_open, Request(url)) |
| 380 | finally: |
| 381 | os.remove(TESTFN) |
| 382 | |
| 383 | h = urllib2.FileHandler() |
| 384 | o = h.parent = MockOpener() |
| 385 | # XXXX why does // mean ftp (and /// mean not ftp!), and where |
| 386 | # is file: scheme specified? I think this is really a bug, and |
| 387 | # what was intended was to distinguish between URLs like: |
| 388 | # file:/blah.txt (a file) |
| 389 | # file://localhost/blah.txt (a file) |
| 390 | # file:///blah.txt (a file) |
| 391 | # file://ftp.example.com/blah.txt (an ftp URL) |
| 392 | for url, ftp in [ |
| 393 | ("file://ftp.example.com//foo.txt", True), |
| 394 | ("file://ftp.example.com///foo.txt", False), |
| 395 | # XXXX bug: fails with OSError, should be URLError |
| 396 | ("file://ftp.example.com/foo.txt", False), |
| 397 | ]: |
| 398 | req = Request(url) |
| 399 | try: |
| 400 | h.file_open(req) |
| 401 | # XXXX remove OSError when bug fixed |
| 402 | except (urllib2.URLError, OSError): |
| 403 | self.assert_(not ftp) |
| 404 | else: |
| 405 | self.assert_(o.req is req) |
| 406 | self.assert_(req.type == "ftp") |
| 407 | |
| 408 | def test_http(self): |
| 409 | class MockHTTPClass: |
| 410 | def __init__(self): |
| 411 | self.req_headers = [] |
| 412 | self.data = None |
| 413 | self.raise_on_endheaders = False |
| 414 | def __call__(self, host): |
| 415 | self.host = host |
| 416 | return self |
| 417 | def set_debuglevel(self, level): self.level = level |
| 418 | def putrequest(self, method, selector): |
| 419 | self.method, self.selector = method, selector |
| 420 | def putheader(self, key, value): |
| 421 | self.req_headers.append((key, value)) |
| 422 | def endheaders(self): |
| 423 | if self.raise_on_endheaders: |
| 424 | import socket |
| 425 | raise socket.error() |
| 426 | def send(self, data): self.data = data |
| 427 | def getreply(self): return 200, "OK", {} |
| 428 | def getfile(self): return MockFile() |
| 429 | |
| 430 | h = urllib2.AbstractHTTPHandler() |
| 431 | o = h.parent = MockOpener() |
| 432 | |
| 433 | url = "http://example.com/" |
| 434 | for method, data in [("GET", None), ("POST", "blah")]: |
| 435 | req = Request(url, data, {"Foo": "bar"}) |
| 436 | req.add_unredirected_header("Spam", "eggs") |
| 437 | http = MockHTTPClass() |
| 438 | r = h.do_open(http, req) |
| 439 | |
| 440 | # result attributes |
| 441 | r.read; r.readline # wrapped MockFile methods |
| 442 | r.info; r.geturl # addinfourl methods |
| 443 | r.code, r.msg == 200, "OK" # added from MockHTTPClass.getreply() |
| 444 | hdrs = r.info() |
| 445 | hdrs.get; hdrs.has_key # r.info() gives dict from .getreply() |
| 446 | self.assert_(r.geturl() == url) |
| 447 | |
| 448 | self.assert_(http.host == "example.com") |
| 449 | self.assert_(http.level == 0) |
| 450 | self.assert_(http.method == method) |
| 451 | self.assert_(http.selector == "/") |
| 452 | self.assert_(http.req_headers == [("Foo", "bar"), ("Spam", "eggs")]) |
| 453 | self.assert_(http.data == data) |
| 454 | |
| 455 | # check socket.error converted to URLError |
| 456 | http.raise_on_endheaders = True |
| 457 | self.assertRaises(urllib2.URLError, h.do_open, http, req) |
| 458 | |
| 459 | # check adding of standard headers |
| 460 | o.addheaders = [("Spam", "eggs")] |
| 461 | for data in "", None: # POST, GET |
| 462 | req = Request("http://example.com/", data) |
| 463 | r = MockResponse(200, "OK", {}, "") |
| 464 | newreq = h.do_request(req) |
| 465 | if data is None: # GET |
| 466 | self.assert_("Content-length" not in req.unredirected_hdrs) |
| 467 | self.assert_("Content-type" not in req.unredirected_hdrs) |
| 468 | else: # POST |
| 469 | self.assert_(req.unredirected_hdrs["Content-length"] == "0") |
| 470 | self.assert_(req.unredirected_hdrs["Content-type"] == |
| 471 | "application/x-www-form-urlencoded") |
| 472 | # XXX the details of Host could be better tested |
| 473 | self.assert_(req.unredirected_hdrs["Host"] == "example.com") |
| 474 | self.assert_(req.unredirected_hdrs["Spam"] == "eggs") |
| 475 | |
| 476 | # don't clobber existing headers |
| 477 | req.add_unredirected_header("Content-length", "foo") |
| 478 | req.add_unredirected_header("Content-type", "bar") |
| 479 | req.add_unredirected_header("Host", "baz") |
| 480 | req.add_unredirected_header("Spam", "foo") |
| 481 | newreq = h.do_request(req) |
| 482 | self.assert_(req.unredirected_hdrs["Content-length"] == "foo") |
| 483 | self.assert_(req.unredirected_hdrs["Content-type"] == "bar") |
| 484 | self.assert_(req.unredirected_hdrs["Host"] == "baz") |
| 485 | self.assert_(req.unredirected_hdrs["Spam"] == "foo") |
| 486 | |
| 487 | def test_errors(self): |
| 488 | h = urllib2.HTTPErrorProcessor() |
| 489 | o = h.parent = MockOpener() |
| 490 | |
| 491 | url = "http://example.com/" |
| 492 | req = Request(url) |
| 493 | # 200 OK is passed through |
| 494 | r = MockResponse(200, "OK", {}, "", url) |
| 495 | newr = h.http_response(req, r) |
| 496 | self.assert_(r is newr) |
| 497 | self.assert_(not hasattr(o, "proto")) # o.error not called |
| 498 | # anything else calls o.error (and MockOpener returns None, here) |
| 499 | r = MockResponse(201, "Created", {}, "", url) |
| 500 | self.assert_(h.http_response(req, r) is None) |
| 501 | self.assert_(o.proto == "http") # o.error called |
| 502 | self.assert_(o.args == (req, r, 201, "Created", {})) |
| 503 | |
| 504 | def test_redirect(self): |
| 505 | from_url = "http://example.com/a.html" |
| 506 | to_url = "http://example.com/b.html" |
| 507 | h = urllib2.HTTPRedirectHandler() |
| 508 | o = h.parent = MockOpener() |
| 509 | |
| 510 | # ordinary redirect behaviour |
| 511 | for code in 301, 302, 303, 307: |
| 512 | for data in None, "blah\nblah\n": |
| 513 | method = getattr(h, "http_error_%s" % code) |
| 514 | req = Request(from_url, data) |
| 515 | req.add_header("Nonsense", "viking=withhold") |
| 516 | req.add_unredirected_header("Spam", "spam") |
| 517 | try: |
| 518 | method(req, MockFile(), code, "Blah", {"location": to_url}) |
| 519 | except urllib2.HTTPError: |
| 520 | # 307 in response to POST requires user OK |
| 521 | self.assert_(code == 307 and data is not None) |
| 522 | self.assert_(o.req.get_full_url() == to_url) |
| 523 | try: |
| 524 | self.assert_(o.req.get_method() == "GET") |
| 525 | except AttributeError: |
| 526 | self.assert_(not o.req.has_data()) |
| 527 | self.assert_(o.req.headers["Nonsense"] == "viking=withhold") |
| 528 | self.assert_("Spam" not in o.req.headers) |
| 529 | self.assert_("Spam" not in o.req.unredirected_hdrs) |
| 530 | |
| 531 | # loop detection |
| 532 | req = Request(from_url) |
| 533 | req.origin_req_host = "example.com" |
| 534 | def redirect(h, req, code, url=to_url): |
| 535 | method = getattr(h, "http_error_%s" % code) |
| 536 | method(req, MockFile(), code, "Blah", {"location": url}) |
| 537 | # Note that the *original* request shares the same record of |
| 538 | # redirections with the sub-requests caused by the redirections. |
| 539 | # once |
| 540 | redirect(h, req, 302) |
| 541 | # twice: loop detected |
| 542 | self.assertRaises(urllib2.HTTPError, redirect, h, req, 302) |
| 543 | # and again |
| 544 | self.assertRaises(urllib2.HTTPError, redirect, h, req, 302) |
| 545 | # but this is a different redirect code, so OK... |
| 546 | redirect(h, req, 301) |
| 547 | self.assertRaises(urllib2.HTTPError, redirect, h, req, 301) |
| 548 | # order doesn't matter |
| 549 | redirect(h, req, 303) |
| 550 | redirect(h, req, 307) |
| 551 | self.assertRaises(urllib2.HTTPError, redirect, h, req, 303) |
| 552 | |
| 553 | # detect endless non-repeating chain of redirects |
| 554 | req = Request(from_url) |
| 555 | req.origin_req_host = "example.com" |
| 556 | count = 0 |
| 557 | try: |
| 558 | while 1: |
| 559 | redirect(h, req, 302, "http://example.com/%d" % count) |
| 560 | count = count + 1 |
| 561 | except urllib2.HTTPError: |
| 562 | self.assert_(count == urllib2.HTTPRedirectHandler.max_redirections) |
| 563 | |
| 564 | |
| 565 | class MiscTests(unittest.TestCase): |
| 566 | |
| 567 | def test_build_opener(self): |
| 568 | class MyHTTPHandler(urllib2.HTTPHandler): pass |
| 569 | class FooHandler(urllib2.BaseHandler): |
| 570 | def foo_open(self): pass |
| 571 | class BarHandler(urllib2.BaseHandler): |
| 572 | def bar_open(self): pass |
| 573 | |
| 574 | build_opener = urllib2.build_opener |
| 575 | |
| 576 | o = build_opener(FooHandler, BarHandler) |
| 577 | self.opener_has_handler(o, FooHandler) |
| 578 | self.opener_has_handler(o, BarHandler) |
| 579 | |
| 580 | # can take a mix of classes and instances |
| 581 | o = build_opener(FooHandler, BarHandler()) |
| 582 | self.opener_has_handler(o, FooHandler) |
| 583 | self.opener_has_handler(o, BarHandler) |
| 584 | |
| 585 | # subclasses of default handlers override default handlers |
| 586 | o = build_opener(MyHTTPHandler) |
| 587 | self.opener_has_handler(o, MyHTTPHandler) |
| 588 | |
| 589 | # a particular case of overriding: default handlers can be passed |
| 590 | # in explicitly |
| 591 | o = build_opener() |
| 592 | self.opener_has_handler(o, urllib2.HTTPHandler) |
| 593 | o = build_opener(urllib2.HTTPHandler) |
| 594 | self.opener_has_handler(o, urllib2.HTTPHandler) |
| 595 | o = build_opener(urllib2.HTTPHandler()) |
| 596 | self.opener_has_handler(o, urllib2.HTTPHandler) |
| 597 | |
| 598 | def opener_has_handler(self, opener, handler_class): |
| 599 | for h in opener.handlers: |
| 600 | if h.__class__ == handler_class: |
| 601 | break |
| 602 | else: |
| 603 | self.assert_(False) |
| 604 | |
| 605 | |
| 606 | def test_main(verbose=None): |
| 607 | from test import test_sets |
| 608 | test_support.run_unittest( |
| 609 | TrivialTests, |
| 610 | OpenerDirectorTests, |
| 611 | HandlerTests, |
| 612 | MiscTests, |
| 613 | ) |
| 614 | |
| 615 | if __name__ == "__main__": |
| 616 | test_main(verbose=True) |