Debian Codegraph @

test/test_browser.py

raw symbols SCIP
1 #!/usr/bin/env python
2 """Tests for mechanize.Browser."""
3
4 import copy
5 import os
6 import re
7 from io import BytesIO
8 from unittest import TestCase
9
10 import mechanize
11 import mechanize._response
12 import mechanize._testcase
13 from mechanize._gzip import HTTPGzipProcessor, compress_readable_output
14 from mechanize.polyglot import (HTTPConnection, addinfourl, codepoint_to_chr,
15 create_response_info, iteritems, unicode_type)
16
17 em_dash = codepoint_to_chr(0x2014)
18
19
20 # XXX these 'mock' classes are badly in need of simplification / removal
21 # (note this stuff is also used by test_useragent.py and test_browser.doctest)
22 class MockMethod:
23 def __init__(self, meth_name, action, handle):
24 self.meth_name = meth_name
25 self.handle = handle
26 self.action = action
27
28 def __call__(self, *args):
29 return self.handle(self.meth_name, self.action, *args)
30
31
32 class MockHeaders(dict):
33 def getheaders(self, name):
34 name = name.lower()
35 return [v for k, v in iteritems(self) if name == k.lower()]
36
37 def __delitem__(self, k):
38 kmap = {q.lower(): q for q in self}
39 k = kmap.get(k.lower())
40 if k is not None:
41 dict.__delitem__(self, k)
42
43
44 class MockResponse:
45 closeable_response = None
46
47 def __init__(self, url="http://example.com/", data=None, info=None):
48 self.url = self._url = url
49 if isinstance(data, type(u'')):
50 data = data.encode('utf-8')
51 self.fp = BytesIO(data)
52 if info is None:
53 info = {}
54 self._info = self._headers = MockHeaders(info)
55 self.close_called = False
56
57 def _set_fp(self, fp):
58 self.fp = fp
59
60 def info(self):
61 return self._info
62
63 def geturl(self):
64 return self.url
65
66 def read(self, size=-1):
67 return self.fp.read(size)
68
69 def seek(self, whence):
70 assert whence == 0
71 self.fp.seek(0)
72
73 def close(self):
74 self.close_called = True
75
76 def get_data(self):
77 pass
78
79
80 def make_mock_handler(response_class=MockResponse):
81 class MockHandler:
82 processor_order = 500
83 handler_order = -1
84
85 def __init__(self, methods):
86 self._define_methods(methods)
87
88 def _define_methods(self, methods):
89 for name, action in methods:
90 if name.endswith("_open"):
91 meth = MockMethod(name, action, self.handle)
92 else:
93 meth = MockMethod(name, action, self.process)
94 setattr(self.__class__, name, meth)
95
96 def handle(self, fn_name, response, *args, **kwds):
97 self.parent.calls.append((self, fn_name, args, kwds))
98 if response:
99 if isinstance(response, mechanize.HTTPError):
100 raise response
101 r = response
102 r.seek(0)
103 else:
104 r = response_class()
105 req = args[0]
106 r.url = req.get_full_url()
107 return r
108
109 def process(self, fn_name, action, *args, **kwds):
110 self.parent.calls.append((self, fn_name, args, kwds))
111 if fn_name.endswith("_request"):
112 return args[0]
113 else:
114 return args[1]
115
116 def close(self):
117 pass
118
119 def add_parent(self, parent):
120 self.parent = parent
121 self.parent.calls = []
122
123 def __lt__(self, other):
124 if not hasattr(other, "handler_order"):
125 # Try to preserve the old behavior of having custom classes
126 # inserted after default ones (works only for custom user
127 # classes which are not aware of handler_order).
128 return True
129 return self.handler_order < other.handler_order
130
131 return MockHandler
132
133
134 class TestBrowser(mechanize.Browser):
135 default_features = []
136 default_others = []
137 default_schemes = []
138
139
140 class TestBrowser2(mechanize.Browser):
141 # XXX better name!
142 # As TestBrowser, this is neutered so doesn't know about protocol handling,
143 # but still knows what to do with unknown schemes, etc., because
144 # UserAgent's default_others list is left intact, including classes like
145 # UnknownHandler
146 default_features = []
147 default_schemes = []
148
149
150 class BrowserTests(TestCase):
151 def test_referer(self):
152 b = TestBrowser()
153 url = "http://www.example.com/"
154 r = MockResponse(url, """<html>
155 <head><title>Title</title></head>
156 <body>
157 <form name="form1">
158 <input type="hidden" name="foo" value="bar"></input>
159 <input type="submit"></input>
160 </form>
161 <a href="http://example.com/foo/bar.html" name="apples"></a>
162 <a href="https://example.com/spam/eggs.html" name="secure"></a>
163 <a href="blah://example.com/" name="pears"></a>
164 </body>
165 </html>
166 """, {"content-type": "text/html"})
167 b.add_handler(make_mock_handler()([("http_open", r)]))
168
169 # Referer not added by .open()...
170 req = mechanize.Request(url)
171 b.open(req)
172 self.assertTrue(req.get_header("Referer") is None)
173 # ...even if we're visiting a document
174 b.open(req)
175 self.assertTrue(req.get_header("Referer") is None)
176 # Referer added by .click_link() and .click()
177 b.select_form("form1")
178 req2 = b.click()
179 self.assertEqual(req2.get_header("Referer"), url)
180 b.open(req2)
181 req3 = b.click_link(name="apples")
182 self.assertEqual(req3.get_header("Referer"), url + "?foo=bar")
183 # Referer not added when going from https to http URL
184 b.add_handler(make_mock_handler()([("https_open", r)]))
185 b.open(req3)
186 req4 = b.click_link(name="secure")
187 self.assertEqual(
188 req4.get_header("Referer"), "http://example.com/foo/bar.html")
189 b.open(req4)
190 req5 = b.click_link(name="apples")
191 self.assertTrue(not req5.has_header("Referer"))
192 # Referer not added for non-http, non-https requests
193 b.add_handler(make_mock_handler()([("blah_open", r)]))
194 req6 = b.click_link(name="pears")
195 self.assertTrue(not req6.has_header("Referer"))
196 # Referer not added when going from non-http, non-https URL
197 b.open(req6)
198 req7 = b.click_link(name="apples")
199 self.assertTrue(not req7.has_header("Referer"))
200
201 # XXX Referer added for redirect
202
203 def test_encoding(self):
204 import mechanize
205 # always take first encoding, since that's the one from the real HTTP
206 # headers, rather than from HTTP-EQUIV
207 b = mechanize.Browser()
208 for s, ct in [
209 ("", mechanize._html.DEFAULT_ENCODING),
210 ("Foo: Bar\r\n\r\n", mechanize._html.DEFAULT_ENCODING),
211 ("Content-Type: text/html; charset=UTF-8\r\n\r\n", "UTF-8"),
212 ("Content-Type: text/html; charset=UTF-8\r\n"
213 "Content-Type: text/html; charset=KOI8-R\r\n\r\n", "UTF-8"),
214 ]:
215 if not isinstance(s, bytes):
216 s = s.encode('ascii')
217 msg = create_response_info(BytesIO(s))
218 r = addinfourl(BytesIO(b""), msg, "http://www.example.com/")
219 b.set_response(r)
220 self.assertEqual(b.encoding(), ct)
221
222 def test_history(self):
223 import mechanize
224 from mechanize import _response
225
226 def same_response(ra, rb):
227 return ra.wrapped is rb.wrapped
228
229 class Handler(mechanize.BaseHandler):
230 def http_open(self, request):
231 r = _response.test_response(url=request.get_full_url())
232 # these tests aren't interested in auto-.reload() behaviour of
233 # .back(), so read the response to prevent that happening
234 r.get_data()
235 return r
236
237 b = TestBrowser2()
238 b.add_handler(Handler())
239 self.assertRaises(mechanize.BrowserStateError, b.back)
240 r1 = b.open("http://example.com/")
241 self.assertRaises(mechanize.BrowserStateError, b.back)
242 b.open("http://example.com/foo")
243 self.assertTrue(same_response(b.back(), r1))
244 r3 = b.open("http://example.com/bar")
245 b.open("http://example.com/spam")
246 self.assertTrue(same_response(b.back(), r3))
247 self.assertTrue(same_response(b.back(), r1))
248 self.assertEqual(b.geturl(), "http://example.com/")
249 self.assertRaises(mechanize.BrowserStateError, b.back)
250 # reloading does a real HTTP fetch rather than using history cache
251 r5 = b.reload()
252 self.assertTrue(not same_response(r5, r1))
253 # .geturl() gets fed through to b.response
254 self.assertEqual(b.geturl(), "http://example.com/")
255 # can go back n times
256 b.open("spam")
257 self.assertEqual(b.geturl(), "http://example.com/spam")
258 r7 = b.open("/spam")
259 self.assertTrue(same_response(b.response(), r7))
260 self.assertEqual(b.geturl(), "http://example.com/spam")
261 self.assertTrue(same_response(b.back(2), r5))
262 self.assertEqual(b.geturl(), "http://example.com/")
263 self.assertRaises(mechanize.BrowserStateError, b.back, 2)
264 r8 = b.open("/spam")
265
266 # even if we get an HTTPError, history, .response() and .request should
267 # still get updated
268 class Handler2(mechanize.BaseHandler):
269 def https_open(self, request):
270 r = mechanize.HTTPError("https://example.com/bad", 503, "Oops",
271 MockHeaders(), BytesIO())
272 return r
273
274 b.add_handler(Handler2())
275 self.assertRaises(mechanize.HTTPError, b.open,
276 "https://example.com/badreq")
277 self.assertEqual(b.response().geturl(), "https://example.com/bad")
278 self.assertEqual(b.request.get_full_url(),
279 "https://example.com/badreq")
280 self.assertTrue(same_response(b.back(), r8))
281
282 # .close() should make use of Browser methods and attributes complain
283 # noisily, since they should not be called after .close()
284 b.form = "blah"
285 b.close()
286 for attr in ("form open error retrieve add_handler "
287 "request response set_response geturl reload back "
288 "clear_history set_cookie links forms viewing_html "
289 "encoding title select_form click submit click_link "
290 "follow_link find_link".split()):
291 self.assertTrue(getattr(b, attr) is None)
292
293 def test_reload_read_incomplete(self):
294 import mechanize
295 from mechanize._response import test_response
296
297 class Browser(TestBrowser):
298 def __init__(self):
299 TestBrowser.__init__(self)
300 self.reloaded = False
301
302 def reload(self):
303 self.reloaded = True
304 TestBrowser.reload(self)
305
306 br = Browser()
307 data = "<html><head><title></title></head><body>%s</body></html>"
308 data = data % ("The quick brown fox jumps over the lazy dog." * 100)
309
310 class Handler(mechanize.BaseHandler):
311 def http_open(self, requst):
312 return test_response(data, [("content-type", "text/html")])
313
314 br.add_handler(Handler())
315
316 # .reload() on .back() if the whole response hasn't already been read
317 # (.read_incomplete is True)
318 r = br.open("http://example.com")
319 r.read(10)
320 br.open('http://www.example.com/blah')
321 self.assertFalse(br.reloaded)
322 br.back()
323 self.assertTrue(br.reloaded)
324
325 # don't reload if already read
326 br.reloaded = False
327 br.response().read()
328 br.open('http://www.example.com/blah')
329 br.back()
330 self.assertFalse(br.reloaded)
331
332 def test_viewing_html(self):
333 # XXX not testing multiple Content-Type headers
334 url = "http://example.com/"
335
336 for allow_xhtml in False, True:
337 for ct, expect in [
338 (None, False),
339 ("text/plain", False),
340 ("text/html", True),
341
342 # don't try to handle XML until we can do it right!
343 ("text/xhtml", allow_xhtml),
344 ("text/xml", allow_xhtml),
345 ("application/xml", allow_xhtml),
346 ("application/xhtml+xml", allow_xhtml),
347 ("text/html; charset=blah", True),
348 (" text/html ; charset=ook ", True),
349 ]:
350 b = TestBrowser(allow_xhtml=allow_xhtml)
351 hdrs = {}
352 if ct is not None:
353 hdrs["Content-Type"] = ct
354 b.add_handler(make_mock_handler()([("http_open", MockResponse(
355 url, "", hdrs))]))
356 b.open(url)
357 self.assertEqual(b.viewing_html(), expect)
358
359 for allow_xhtml in False, True:
360 for ext, expect in [
361 (".htm", True),
362 (".html", True),
363
364 # don't try to handle XML until we can do it right!
365 (".xhtml", allow_xhtml),
366 (".html?foo=bar&a=b;whelk#kool", True),
367 (".txt", False),
368 (".xml", False),
369 ("", False),
370 ]:
371 b = TestBrowser(allow_xhtml=allow_xhtml)
372 url = "http://example.com/foo" + ext
373 b.add_handler(make_mock_handler()([("http_open", MockResponse(
374 url, "", {}))]))
375 b.open(url)
376 self.assertEqual(b.viewing_html(), expect)
377
378 def test_empty(self):
379 import mechanize
380 url = "http://example.com/"
381
382 b = TestBrowser()
383
384 self.assertTrue(b.response() is None)
385
386 # To open a relative reference (often called a "relative URL"), you
387 # have to have already opened a URL for it "to be relative to".
388 self.assertRaises(mechanize.BrowserStateError, b.open, "relative_ref")
389
390 # we can still clear the history even if we've not visited any URL
391 b.clear_history()
392
393 # most methods raise BrowserStateError...
394 def test_state_error(method_names):
395 for attr in method_names:
396 method = getattr(b, attr)
397 # print attr
398 self.assertRaises(mechanize.BrowserStateError, method)
399 self.assertRaises(
400 mechanize.BrowserStateError, b.select_form, name="blah")
401 self.assertRaises(
402 mechanize.BrowserStateError, b.find_link, name="blah")
403
404 # ...if not visiting a URL...
405 test_state_error(("geturl reload back viewing_html encoding "
406 "click links forms title select_form".split()))
407 self.assertRaises(mechanize.BrowserStateError, b.set_cookie, "foo=bar")
408 self.assertRaises(mechanize.BrowserStateError, b.submit, nr=0)
409 self.assertRaises(mechanize.BrowserStateError, b.click_link, nr=0)
410 self.assertRaises(mechanize.BrowserStateError, b.follow_link, nr=0)
411 self.assertRaises(mechanize.BrowserStateError, b.find_link, nr=0)
412 # ...and lots do so if visiting a non-HTML URL
413 b.add_handler(
414 make_mock_handler()([("http_open", MockResponse(url, "", {}))]))
415 r = b.open(url)
416 self.assertTrue(not b.viewing_html())
417 test_state_error("click links forms title select_form".split())
418 self.assertRaises(mechanize.BrowserStateError, b.submit, nr=0)
419 self.assertRaises(mechanize.BrowserStateError, b.click_link, nr=0)
420 self.assertRaises(mechanize.BrowserStateError, b.follow_link, nr=0)
421 self.assertRaises(mechanize.BrowserStateError, b.find_link, nr=0)
422
423 b = TestBrowser()
424 r = MockResponse(url, """<html>
425 <head><title>Title</title></head>
426 <body>
427 </body>
428 </html>
429 """, {"content-type": "text/html"})
430 b.add_handler(make_mock_handler()([("http_open", r)]))
431 r = b.open(url)
432 self.assertEqual(b.title(), "Title")
433 self.assertEqual(len(list(b.links())), 0)
434 self.assertEqual(len(list(b.forms())), 0)
435 self.assertRaises(ValueError, b.select_form)
436 self.assertRaises(
437 mechanize.FormNotFoundError, b.select_form, name="blah")
438 self.assertRaises(
439 mechanize.FormNotFoundError,
440 b.select_form,
441 predicate=lambda form: form is not b.global_form())
442 self.assertRaises(
443 mechanize.LinkNotFoundError, b.find_link, name="blah")
444 self.assertRaises(
445 mechanize.LinkNotFoundError, b.find_link, predicate=lambda x: True)
446
447 def test_forms(self):
448 import mechanize
449
450 b = TestBrowser()
451 b.set_html("""\
452 <html>
453 <head><title>Title</title></head>
454 <body>
455 <form name="form1">
456 <input type="text"></input>
457 <input type="checkbox" name="cheeses" value="cheddar"></input>
458 <input type="checkbox" name="cheeses" value="edam"></input>
459 <input type="submit" name="one"></input>
460 </form>
461 <a href="http://example.com/foo/bar.html" name="apples">
462 <form name="form2">
463 <input type="submit" name="two">
464 </form>
465 </body>
466 </html>
467 """)
468
469 forms = list(b.forms())
470 self.assertEqual(len(forms), 2)
471 for got, expect in zip([f.name for f in forms], ["form1", "form2"]):
472 self.assertEqual(got, expect)
473
474 self.assertRaises(mechanize.FormNotFoundError, b.select_form, "foo")
475
476 # no form is set yet
477 self.assertRaises(AttributeError, getattr, b, "possible_items")
478 b.select_form("form1")
479 # now unknown methods are fed through to selected mechanize.HTMLForm
480 self.assertEqual([i.name for i in b.find_control("cheeses").items],
481 ["cheddar", "edam"])
482 b["cheeses"] = ["cheddar", "edam"]
483 self.assertEqual(b.click_pairs(), [("cheeses", "cheddar"),
484 ("cheeses", "edam"), ("one", "")])
485
486 b.select_form(nr=1)
487 self.assertEqual(b.name, "form2")
488 self.assertEqual(b.click_pairs(), [("two", "")])
489
490 def test_link_encoding(self):
491 import mechanize
492 from mechanize._rfc3986 import clean_url
493 url = "http://example.com/"
494 for encoding in ["UTF-8", "latin-1"]:
495 encoding_decl = "; charset=%s" % encoding
496 b = TestBrowser()
497 r = MockResponse(url, """\
498 <a href="http://example.com/foo/bar&mdash;&#x2014;.html"
499 name="name0&mdash;&#x2014;">blah&mdash;&#x2014;</a>
500 """, {"content-type": "text/html%s" % encoding_decl})
501 b.add_handler(make_mock_handler()([("http_open", r)]))
502 r = b.open(url)
503
504 Link = mechanize.Link
505 mdashx2 = em_dash.encode('utf-8') * 2
506 qmdashx2 = clean_url(mdashx2, encoding)
507 # base_url, url, text, tag, attrs
508 exp = Link(
509 url, "http://example.com/foo/bar%s.html" % qmdashx2,
510 unicode_type("blah") + (em_dash * 2), "a",
511 [("href", unicode_type("http://example.com/foo/bar%s.html") % (
512 em_dash*2)),
513 ("name", unicode_type("name0") + em_dash + em_dash)])
514 # nr
515 link = b.find_link()
516 # print
517 # print exp
518 # print link
519 self.assertEqual(link, exp)
520
521 def test_link_whitespace(self):
522 from mechanize import Link
523 base_url = "http://example.com/"
524 url = " http://example.com/foo.html%20+ "
525 stripped_url = url.strip()
526 html = '<a href="%s"></a>' % url
527 b = TestBrowser()
528 r = MockResponse(base_url, html, {"content-type": "text/html"})
529 b.add_handler(make_mock_handler()([("http_open", r)]))
530 r = b.open(base_url)
531 link = b.find_link(nr=0)
532 self.assertEqual(
533 link, Link(base_url, stripped_url, "", "a", [("href", url)]))
534
535 def test_links(self):
536 import mechanize
537 from mechanize import Link
538 url = "http://example.com/"
539
540 b = TestBrowser()
541 r = MockResponse(url, """<html>
542 <head><title>Title</title></head>
543 <body>
544 <a href="http://example.com/foo/bar.html" name="apples"></a>
545 <a name="pears"></a>
546 <a href="spam" name="pears"></a>
547 <area href="blah" name="foo"></area>
548 <form name="form2">
549 <input type="submit" name="two">
550 </form>
551 <iframe name="name" href="href" src="src"></iframe>
552 <iframe name="name2" href="href" src="src"></iframe>
553 <a name="name3" href="one">yada yada</a>
554 <a name="pears" href="two" weird="stuff">rhubarb</a>
555 <a></a>
556 <iframe src="foo"></iframe>
557 </body>
558 </html>
559 """, {"content-type": "text/html"})
560 b.add_handler(make_mock_handler()([("http_open", r)]))
561 r = b.open(url)
562
563 exp_links = [
564 # base_url, url, text, tag, attrs
565 Link(url, "http://example.com/foo/bar.html", "", "a",
566 [("href", "http://example.com/foo/bar.html"),
567 ("name", "apples")]),
568 Link(url, "spam", "", "a", [("href", "spam"), ("name", "pears")]),
569 Link(url, "blah", '', "area", [("href", "blah"), ("name", "foo")]),
570 Link(url, "src", '', "iframe",
571 [("name", "name"), ("href", "href"), ("src", "src")]),
572 Link(url, "src", '', "iframe",
573 [("name", "name2"), ("href", "href"), ("src", "src")]),
574 Link(url, "one", "yada yada", "a",
575 [("name", "name3"), ("href", "one")]),
576 Link(url, "two", "rhubarb", "a",
577 [("name", "pears"), ("href", "two"), ("weird", "stuff")]),
578 Link(url, "foo", '', "iframe", [("src", "foo")]),
579 ]
580 links = list(b.links())
581 for got, expect in zip(links, exp_links):
582 self.assertEqual(got, expect)
583 self.assertEqual(len(links), len(exp_links))
584 # nr
585 lnk = b.find_link()
586 self.assertEqual(lnk.url, "http://example.com/foo/bar.html")
587 lnk = b.find_link(nr=1)
588 self.assertEqual(lnk.url, "spam")
589 # text
590 lnk = b.find_link(text="yada yada")
591 self.assertEqual(lnk.url, "one")
592 self.assertRaises(
593 mechanize.LinkNotFoundError, b.find_link, text="da ya")
594 lnk = b.find_link(text_regex=re.compile("da ya"))
595 self.assertEqual(lnk.url, "one")
596 lnk = b.find_link(text_regex="da ya")
597 self.assertEqual(lnk.url, "one")
598 # name
599 lnk = b.find_link(name="name3")
600 self.assertEqual(lnk.url, "one")
601 lnk = b.find_link(name_regex=re.compile("oo"))
602 self.assertEqual(lnk.url, "blah")
603 lnk = b.find_link(name_regex="oo")
604 self.assertEqual(lnk.url, "blah")
605 # url
606 lnk = b.find_link(url="spam")
607 self.assertEqual(lnk.url, "spam")
608 lnk = b.find_link(url_regex=re.compile("pam"))
609 self.assertEqual(lnk.url, "spam")
610 lnk = b.find_link(url_regex="pam")
611 self.assertEqual(lnk.url, "spam")
612 # tag
613 lnk = b.find_link(tag="area")
614 self.assertEqual(lnk.url, "blah")
615 # predicate
616 lnk = b.find_link(
617 predicate=lambda lnk: dict(lnk.attrs).get("weird") == "stuff")
618 self.assertEqual(lnk.url, "two")
619 # combinations
620 lnk = b.find_link(name="pears", nr=1)
621 self.assertEqual(lnk.text, "rhubarb")
622 lnk = b.find_link(url="src", nr=0, name="name2")
623 self.assertEqual(lnk.tag, "iframe")
624 self.assertEqual(lnk.url, "src")
625 self.assertRaises(
626 mechanize.LinkNotFoundError,
627 b.find_link,
628 url="src",
629 nr=1,
630 name="name2")
631 lnk = b.find_link(
632 tag="a", predicate=lambda lnk: dict(lnk.attrs).get(
633 "weird") == "stuff")
634 self.assertEqual(lnk.url, "two")
635
636 # .links()
637 self.assertEqual(
638 list(b.links(url="src")), [
639 Link(
640 url,
641 url="src",
642 text='',
643 tag="iframe",
644 attrs=[("name", "name"), ("href", "href"),
645 ("src", "src")]),
646 Link(
647 url,
648 url="src",
649 text='',
650 tag="iframe",
651 attrs=[("name", "name2"), ("href", "href"),
652 ("src", "src")]),
653 ])
654
655 def test_base_uri(self):
656 url = "http://example.com/"
657
658 for html, urls in [
659 ("""<base href="http://www.python.org/foo/">
660 <a href="bar/baz.html"></a>
661 <a href="/bar/baz.html"></a>
662 <a href="http://example.com/bar %2f%2Fblah;/baz@~._-.html"></a>
663 """, [
664 "http://www.python.org/foo/bar/baz.html",
665 "http://www.python.org/bar/baz.html",
666 "http://example.com/bar%20%2f%2Fblah;/baz@~._-.html",
667 ]),
668 ("""<a href="bar/baz.html"></a>
669 <a href="/bar/baz.html"></a>
670 <a href="http://example.com/bar/baz.html"></a>
671 """, [
672 "http://example.com/bar/baz.html",
673 "http://example.com/bar/baz.html",
674 "http://example.com/bar/baz.html",
675 ]),
676 ]:
677 b = TestBrowser()
678 r = MockResponse(url, html, {"content-type": "text/html"})
679 b.add_handler(make_mock_handler()([("http_open", r)]))
680 r = b.open(url)
681 self.assertEqual([link.absolute_url for link in b.links()], urls)
682
683 def test_set_cookie(self):
684 class CookieTestBrowser(TestBrowser):
685 default_features = list(
686 TestBrowser.default_features) + ["_cookies"]
687
688 # have to be visiting HTTP/HTTPS URL
689 url = "ftp://example.com/"
690 br = CookieTestBrowser()
691 r = mechanize.make_response(
692 "<html><head><title>Title</title></head><body></body></html>",
693 [("content-type", "text/html")],
694 url,
695 200,
696 "OK", )
697 br.add_handler(make_mock_handler()([("http_open", r)]))
698 handler = br._ua_handlers["_cookies"]
699 cj = handler.cookiejar
700 self.assertRaises(mechanize.BrowserStateError, br.set_cookie,
701 "foo=bar")
702 self.assertEqual(len(cj), 0)
703
704 url = "http://example.com/"
705 br = CookieTestBrowser()
706 r = mechanize.make_response(
707 "<html><head><title>Title</title></head><body></body></html>",
708 [("content-type", "text/html")],
709 url,
710 200,
711 "OK", )
712 br.add_handler(make_mock_handler()([("http_open", r)]))
713 handler = br._ua_handlers["_cookies"]
714 cj = handler.cookiejar
715
716 # have to be visiting a URL
717 self.assertRaises(mechanize.BrowserStateError, br.set_cookie,
718 "foo=bar")
719 self.assertEqual(len(cj), 0)
720
721 # normal case
722 br.open(url)
723 br.set_cookie("foo=bar")
724 self.assertEqual(len(cj), 1)
725 self.assertEqual(cj._cookies["example.com"]["/"]["foo"].value, "bar")
726
727 def test_clone_browser(self):
728 from mechanize import Browser
729 br = Browser()
730 br.set_handle_refresh(True, max_time=237, honor_time=True)
731 br.set_handle_robots(False)
732 cbr = copy.copy(br)
733 for h, ch in zip(br.handlers, cbr.handlers):
734 self.assertIsNot(h, ch)
735 self.assertIs(ch.parent, cbr)
736 self.assertIs(h.__class__, ch.__class__)
737 self.assertEqual(set(br._ua_handlers), set(cbr._ua_handlers))
738 self.assertIs(br._ua_handlers['_cookies'].cookiejar,
739 cbr._ua_handlers['_cookies'].cookiejar)
740 self.assertIsNot(br.addheaders, cbr.addheaders)
741 self.assertEqual(br.addheaders, cbr.addheaders)
742 self.assertIs(br.finalize_request_headers, cbr.finalize_request_headers)
743 h = cbr._ua_handlers['_refresh']
744 self.assertEqual((h.honor_time, h.max_time), (True, 237))
745
746 def test_gzip(self):
747 p = HTTPGzipProcessor()
748 url = "https://www.example.com/"
749 req = p.https_request(mechanize.Request(url))
750 self.assertIsNone(req.get_header('Accept-Encoding'))
751 p.request_gzip = True
752 req = p.https_request(mechanize.Request(url))
753 self.assertEqual(req.get_header('Accept-Encoding'), 'gzip')
754 req = mechanize.Request(url)
755 req.add_header('Accept-Encoding', 'moo, *')
756 req = p.https_request(req)
757 self.assertEqual(req.get_header('Accept-Encoding'), 'moo, *, gzip')
758 data = os.urandom(1024 * 1024)
759 cdata = b''.join(compress_readable_output(BytesIO(data)))
760 r = MockResponse(
761 url,
762 data=cdata,
763 info={
764 'Content-Encoding': 'gzip',
765 'Content-Length': str(len(cdata))
766 })
767 r = p.https_response(req, r)
768 self.assertEqual(r.read(), data)
769 h = r.info()
770 self.assertFalse(h.getheaders('content-encoding'))
771 self.assertFalse(h.getheaders('content-length'))
772
773
774 class ResponseTests(TestCase):
775 def test_set_response(self):
776 import copy
777 from mechanize import response_seek_wrapper
778
779 br = TestBrowser()
780 url = "http://example.com/"
781 html = b"""<html><body><a href="spam">click me</a></body></html>"""
782 headers = {"content-type": "text/html"}
783 r = response_seek_wrapper(MockResponse(url, html, headers))
784 br.add_handler(make_mock_handler()([("http_open", r)]))
785
786 r = br.open(url)
787 self.assertEqual(r.read(), html)
788 r.seek(0)
789 self.assertEqual(copy.copy(r).read(), html)
790 self.assertEqual(list(br.links())[0].url, "spam")
791
792 newhtml = b"""<html><body><a href="eggs">click me</a></body></html>"""
793
794 r.set_data(newhtml)
795 self.assertEqual(r.read(), newhtml)
796 self.assertEqual(br.response().read(), html)
797 br.response().set_data(newhtml)
798 self.assertEqual(br.response().read(), html)
799 self.assertEqual(list(br.links())[0].url, "spam")
800 r.seek(0)
801
802 br.set_response(r)
803 self.assertEqual(br.response().read(), newhtml)
804 self.assertEqual(list(br.links())[0].url, "eggs")
805
806 def test_select_form(self):
807 from mechanize import _response
808 br = TestBrowser()
809 fp = BytesIO(b'''<html>
810 <form name="a"></form>
811 <form name="b" data-ac="123"></form>
812 <form name="c" class="x"></form>
813 </html>''')
814 headers = create_response_info(
815 BytesIO(b"Content-type: text/html"))
816 response = _response.response_seek_wrapper(
817 _response.closeable_response(fp, headers, "http://example.com/",
818 200, "OK"))
819 br.set_response(response)
820 for i, n in enumerate('abc'):
821 br.select_form(nr=i)
822 self.assertEqual(br.form.name, n)
823 br.select_form(nr=0), br.select_form(name=n)
824 self.assertEqual(br.form.name, n)
825 br.select_form(data_ac=re.compile(r'\d+'))
826 self.assertEqual(br.form.name, 'b')
827 br.select_form(class_=lambda x: x == 'x')
828 self.assertEqual(br.form.name, 'c')
829
830 def test_str(self):
831 from mechanize import _response
832
833 br = TestBrowser()
834 self.assertEqual(str(br), "<TestBrowser (not visiting a URL)>")
835
836 fp = BytesIO(b'<html><form name="f"><input /></form></html>')
837 headers = create_response_info(
838 BytesIO(b"Content-type: text/html"))
839 response = _response.response_seek_wrapper(
840 _response.closeable_response(fp, headers, "http://example.com/",
841 200, "OK"))
842 br.set_response(response)
843 self.assertEqual(str(br), "<TestBrowser visiting http://example.com/>")
844
845 br.select_form(nr=0)
846 self.assertEqual(
847 str(br), """\
848 <TestBrowser visiting http://example.com/
849 selected form:
850 <f GET http://example.com/ application/x-www-form-urlencoded
851 <TextControl(<None>=)>>
852 >""")
853
854
855 class HttplibTests(mechanize._testcase.TestCase):
856 def make_browser(self):
857 class TestBrowser(mechanize.Browser):
858 default_features = []
859 default_schemes = ["http"]
860
861 return TestBrowser()
862
863 def monkey_patch_httplib(self, putheader):
864 def do_nothing(*args, **kwds):
865 return
866
867 def getresponse(self_):
868 class Response(object):
869 msg = create_response_info(BytesIO(b""))
870 status = 200
871 reason = "OK"
872 fp = BytesIO(b'')
873
874 def read(self__, sz=-1):
875 return b""
876
877 def close(self):
878 self.fp = None
879
880 def readinto(self__, b):
881 pass
882
883 return Response()
884
885 self.monkey_patch(HTTPConnection, "putheader", putheader)
886 self.monkey_patch(HTTPConnection, "connect", do_nothing)
887 self.monkey_patch(HTTPConnection, "send", do_nothing)
888 self.monkey_patch(HTTPConnection, "close", do_nothing)
889 self.monkey_patch(HTTPConnection, "getresponse", getresponse)
890
891 def test_add_host_header(self):
892 headers = []
893
894 def putheader(self_, header, value):
895 headers.append((header, value))
896
897 self.monkey_patch_httplib(putheader)
898 browser = self.make_browser()
899 request = mechanize.Request("http://example.com/")
900 browser.addheaders = [("Host", "myway.example.com")]
901 browser.finalize_request_headers = lambda req, headers: headers.__setitem__('Test-Header', 'Yay')
902 browser.open(request)
903 self.assertIn(("Host", "myway.example.com"), headers)
904 self.assertIn(("Test-Header", "Yay"), headers)
905
906 def test_misc_browser_tests(self):
907
908 class TestHttpHandler(mechanize.BaseHandler):
909 def http_open(self, request):
910 return mechanize._response.test_response(
911 url=request.get_full_url())
912
913 class TestHttpBrowser(TestBrowser2):
914 handler_classes = TestBrowser2.handler_classes.copy()
915 handler_classes["http"] = TestHttpHandler
916 default_schemes = ["http"]
917
918 def response_impl(response):
919 return response.wrapped.fp.__class__.__name__
920
921 br = TestHttpBrowser()
922 r = br.open("http://example.com")
923 self.assertEqual('BytesIO', response_impl(r))
924 r2 = br.open("http://example.com")
925 self.assertEqual('BytesIO', response_impl(r2))
926 self.assertEqual('eofresponse', response_impl(r))
927 br.set_response(mechanize._response.test_response())
928 self.assertEqual('eofresponse', response_impl(r2))
929
930 br = TestHttpBrowser()
931 r = br.open("http://example.com")
932 r2 = mechanize._response.test_response(url="http://example.com/2")
933 self.assertEqual(response_impl(r2), 'BytesIO')
934 br.visit_response(r2)
935 self.assertEqual(response_impl(r), 'eofresponse')
936 self.assertEqual(br.geturl(), br.request.get_full_url())
937 self.assertEqual(br.geturl(), "http://example.com/2")
938 br.back()
939 self.assertEqual(br.geturl(), br.request.get_full_url())
940 self.assertEqual(br.geturl(), "http://example.com")
941
942 class ReloadCheckBrowser(TestHttpBrowser):
943 reloaded = False
944
945 def reload(self):
946 self.reloaded = True
947 return TestHttpBrowser.reload(self)
948
949 br = ReloadCheckBrowser()
950 old = br.open("http://example.com")
951 br.open("http://example.com/2")
952 new = br.back()
953 self.assertTrue(br.reloaded)
954 self.assertIsNot(new.wrapped, old.wrapped)
955
956 br = TestBrowser2()
957 self.assertRaises(ValueError, br.set_response, 'blah')
958 self.assertRaises(ValueError, br.set_response, BytesIO())
959 self.assertRaises(mechanize.URLError, br.open, "http://example.com")
960 self.assertRaises(mechanize.URLError, br.reload)
961
962 br = TestBrowser2()
963 br.add_handler(make_mock_handler(mechanize._response.test_response)([("http_open", None)]))
964
965 self.assertIsNone(br.response())
966 self.assertEqual(len(br._history._history), 0)
967 br.open("http://example.com/1")
968 self.assertIsNotNone(br.response())
969 self.assertEqual(len(br._history._history), 0)
970 br.clear_history()
971 self.assertIsNotNone(br.response())
972 self.assertEqual(len(br._history._history), 0)
973 br.open("http://example.com/2")
974 br.response() is not None
975 self.assertIsNotNone(br.response())
976 self.assertEqual(len(br._history._history), 1)
977 br.clear_history()
978 self.assertIsNotNone(br.response())
979 self.assertEqual(len(br._history._history), 0)
980
981 from test.test_urllib2 import MockHTTPHandler
982
983 def make_browser_with_redirect():
984 br = TestBrowser2()
985 hh = MockHTTPHandler(302, "Location: http://example.com/\r\n\r\n")
986 br.add_handler(hh)
987 br.add_handler(mechanize.HTTPRedirectHandler())
988 return br
989
990 def test_state(br):
991 self.assertIsNone(br.request)
992 self.assertIsNone(br.response())
993 self.assertRaises(mechanize.BrowserStateError, br.back)
994
995 br = make_browser_with_redirect()
996 test_state(br)
997 req = mechanize.Request("http://example.com")
998 req.visit = False
999 br.open(req)
1000 test_state(br)
1001
1002 br = make_browser_with_redirect()
1003 test_state(br)
1004
1005 req = mechanize.Request("http://example.com")
1006 self.assertIsNone(req.visit)
1007 br.open_novisit(req)
1008 test_state(br)
1009 self.assertFalse(req.visit)
1010
1011 def test_one_visit(handlers):
1012 br = TestBrowser2()
1013 for handler in handlers:
1014 br.add_handler(handler)
1015 req = mechanize.Request("http://example.com")
1016 req.visit = True
1017 br.open(req)
1018 return br
1019
1020 def test_state(br):
1021 # XXX the _history._history check is needed because of the weird
1022 # throwing-away of history entries by .back() where response is
1023 # None, which makes the .back() check insufficient to tell if a
1024 # history entry was .add()ed. I don't want to change this until
1025 # post-stable.
1026 self.assertTrue(br.response())
1027 self.assertTrue(br.request)
1028 self.assertEqual(len(br._history._history), 0)
1029 self.assertRaises(mechanize.BrowserStateError, br.back)
1030
1031 from test.test_urllib2 import HTTPRedirectHandler
1032 hh = MockHTTPHandler(302, "Location: http://example.com/\r\n\r\n")
1033 br = test_one_visit([hh, HTTPRedirectHandler()])
1034 test_state(br)
1035
1036 class MockPasswordManager:
1037
1038 def add_password(self, realm, uri, user, password):
1039 pass
1040
1041 def find_user_password(self, realm, authuri):
1042 return '', ''
1043
1044 ah = mechanize.HTTPBasicAuthHandler(MockPasswordManager())
1045 hh = MockHTTPHandler(
1046 401, 'WWW-Authenticate: Basic realm="realm"\r\n\r\n')
1047 test_state(test_one_visit([hh, ah]))
1048 ph = mechanize.ProxyHandler(dict(http="proxy.example.com:3128"))
1049 ah = mechanize.ProxyBasicAuthHandler(MockPasswordManager())
1050 hh = MockHTTPHandler(
1051 407, 'Proxy-Authenticate: Basic realm="realm"\r\n\r\n')
1052 test_state(test_one_visit([ph, hh, ah]))
1053
1054 br = TestBrowser2()
1055 html = b"""\
1056 <html><body>
1057 <input type="text" name="a" />
1058 <form><input type="text" name="b" /></form>
1059 </body></html>
1060 """
1061 self.assertRaises(mechanize.BrowserStateError, br.global_form)
1062 br.set_html(html)
1063 self.assertEqual(str(br.global_form().find_control(nr=0).name), 'a')
1064 self.assertEqual(len(list(br.forms())), 1)
1065 self.assertEqual(str(next(iter(br.forms())).find_control(nr=0).name), 'b')
1066
1067 br = TestBrowser2()
1068 br.set_html("""\
1069 <html><head><title></title></head><body>
1070 <input type="text" name="a" value="b"></input>
1071 <form>
1072 <input type="text" name="p" value="q"></input>
1073 </form>
1074 </body></html>""")
1075
1076 def has_a(form):
1077 try:
1078 form.find_control(name="a")
1079 except mechanize.ControlNotFoundError:
1080 return False
1081 else:
1082 return True
1083 br.select_form(predicate=has_a)
1084 self.assertEqual(str(br.form.find_control(name="a").value), 'b')
1085
1086
1087 if __name__ == "__main__":
1088 import unittest
1089 unittest.main()