<86>Apr 21 01:30:43 userdel[91375]: delete user 'rooter' <86>Apr 21 01:30:43 userdel[91375]: removed group 'rooter' owned by 'rooter' <86>Apr 21 01:30:43 userdel[91375]: removed shadow group 'rooter' owned by 'rooter' <86>Apr 21 01:30:43 groupadd[91430]: group added to /etc/group: name=rooter, GID=651 <86>Apr 21 01:30:43 groupadd[91430]: group added to /etc/gshadow: name=rooter <86>Apr 21 01:30:43 groupadd[91430]: new group: name=rooter, GID=651 <86>Apr 21 01:30:43 useradd[91437]: new user: name=rooter, UID=651, GID=651, home=/root, shell=/bin/bash <86>Apr 21 01:30:43 userdel[91452]: delete user 'builder' <86>Apr 21 01:30:43 userdel[91452]: removed group 'builder' owned by 'builder' <86>Apr 21 01:30:43 userdel[91452]: removed shadow group 'builder' owned by 'builder' <86>Apr 21 01:30:43 groupadd[91479]: group added to /etc/group: name=builder, GID=652 <86>Apr 21 01:30:43 groupadd[91479]: group added to /etc/gshadow: name=builder <86>Apr 21 01:30:43 groupadd[91479]: new group: name=builder, GID=652 <86>Apr 21 01:30:43 useradd[91491]: new user: name=builder, UID=652, GID=652, home=/usr/src, shell=/bin/bash <13>Apr 21 01:30:45 rpmi: libexpat-2.2.4-alt0.M80P.1 1503871120 installed <13>Apr 21 01:30:45 rpmi: libgdbm-1.8.3-alt10 1454943313 installed <13>Apr 21 01:30:45 rpmi: libtinfo-devel-5.9-alt8 1456756459 installed <13>Apr 21 01:30:45 rpmi: libncurses-devel-5.9-alt8 1456756459 installed <13>Apr 21 01:30:45 rpmi: python-modules-curses-2.7.11-alt6.M80P.1 1527682470 installed <13>Apr 21 01:30:45 rpmi: libverto-0.2.6-alt1_6 1455633234 installed <13>Apr 21 01:30:45 rpmi: libkeyutils-1.5.10-alt0.M80P.2 p8+216694.100.6.1 1547827915 installed <13>Apr 21 01:30:45 rpmi: libcom_err-1.42.13-alt2 1449075846 installed <13>Apr 21 01:30:45 rpmi: ca-certificates-2016.02.25-alt1 1462368370 installed <13>Apr 21 01:30:46 rpmi: libcrypto10-1.0.2n-alt0.M80P.1 1512766129 installed <13>Apr 21 01:30:46 rpmi: libssl10-1.0.2n-alt0.M80P.1 1512766129 installed <86>Apr 21 01:30:46 groupadd[97136]: group added to /etc/group: name=_keytab, GID=499 <86>Apr 21 01:30:46 groupadd[97136]: group added to /etc/gshadow: name=_keytab <86>Apr 21 01:30:46 groupadd[97136]: new group: name=_keytab, GID=499 <13>Apr 21 01:30:46 rpmi: libkrb5-1.14.6-alt1.M80P.1 1525355673 installed <13>Apr 21 01:30:46 rpmi: python3-base-3.5.4-alt2.M80P.1 1527753911 installed <13>Apr 21 01:30:46 rpmi: python-modules-compiler-2.7.11-alt6.M80P.1 1527682470 installed <13>Apr 21 01:30:46 rpmi: python3-module-py-1.4.34-alt0.M80P.1 1503506764 installed <13>Apr 21 01:30:46 rpmi: python-modules-email-2.7.11-alt6.M80P.1 1527682470 installed <13>Apr 21 01:30:46 rpmi: python3-3.5.4-alt2.M80P.1 1527753911 installed <13>Apr 21 01:30:46 rpmi: rpm-build-python3-0.1.10.10-alt1.M80P.1 1530521451 installed <13>Apr 21 01:30:46 rpmi: python-modules-unittest-2.7.11-alt6.M80P.1 1527682470 installed <13>Apr 21 01:30:46 rpmi: python3-module-pytest-3.2.1-alt0.M80P.1 1503499784 installed <13>Apr 21 01:30:46 rpmi: python3-module-setuptools-1:18.5-alt0.M80P.1 1497527461 installed <13>Apr 21 01:30:47 rpmi: python-modules-2.7.11-alt6.M80P.1 1527682470 installed <13>Apr 21 01:30:47 rpmi: python-modules-ctypes-2.7.11-alt6.M80P.1 1527682470 installed <13>Apr 21 01:30:47 rpmi: python-modules-encodings-2.7.11-alt6.M80P.1 1527682470 installed <13>Apr 21 01:30:47 rpmi: python-modules-multiprocessing-2.7.11-alt6.M80P.1 1527682470 installed <13>Apr 21 01:30:47 rpmi: python-modules-logging-2.7.11-alt6.M80P.1 1527682470 installed <13>Apr 21 01:30:47 rpmi: python-tools-2to3-2.7.11-alt6.M80P.1 1527682470 installed <13>Apr 21 01:30:47 rpmi: python-modules-xml-2.7.11-alt6.M80P.1 1527682470 installed <13>Apr 21 01:30:47 rpmi: python-modules-hotshot-2.7.11-alt6.M80P.1 1527682470 installed <13>Apr 21 01:30:47 rpmi: python-modules-bsddb-2.7.11-alt6.M80P.1 1527682470 installed <13>Apr 21 01:30:47 rpmi: python-2.7.11-alt6.M80P.1 1527682470 installed <13>Apr 21 01:30:47 rpmi: python-dev-2.7.11-alt6.M80P.1 1527682470 installed <13>Apr 21 01:30:47 rpmi: python-module-py-1.4.34-alt0.M80P.1 1503506764 installed <13>Apr 21 01:30:47 rpmi: python-modules-json-2.7.11-alt6.M80P.1 1527682470 installed <13>Apr 21 01:30:47 rpmi: python-module-pytest-3.2.1-alt0.M80P.1 1503499784 installed <13>Apr 21 01:30:47 rpmi: python-module-setuptools-1:18.5-alt0.M80P.1 1497527461 installed Installing python-module-mechanize-0.2.5-alt1.1.1.1.src.rpm Building target platforms: x86_64 Building for target x86_64 Executing(%prep): /bin/sh -e /usr/src/tmp/rpm-tmp.90135 + umask 022 + /bin/mkdir -p /usr/src/RPM/BUILD + cd /usr/src/RPM/BUILD + cd /usr/src/RPM/BUILD + rm -rf mechanize-0.2.5 + echo 'Source #0 (mechanize-0.2.5.tar):' Source #0 (mechanize-0.2.5.tar): + /bin/tar -xf /usr/src/RPM/SOURCES/mechanize-0.2.5.tar + cd mechanize-0.2.5 + /bin/chmod -c -Rf u+rwX,go-w . + cp -fR . ../python3 + pushd ../python3 ~/RPM/BUILD/python3 ~/RPM/BUILD/mechanize-0.2.5 + echo 'Patch #0 (mechanize-0.2.5-alt-python3.patch):' Patch #0 (mechanize-0.2.5-alt-python3.patch): + /usr/bin/patch -p2 patching file mechanize/_http.py patching file mechanize/_response.py patching file mechanize/_urllib2_fork.py patching file test/test_browser.py patching file test/test_cookies.py patching file test/test_urllib2.py patching file test/test_urllib2_localnet.py + popd ~/RPM/BUILD/mechanize-0.2.5 + exit 0 Executing(%build): /bin/sh -e /usr/src/tmp/rpm-tmp.90135 + umask 022 + /bin/mkdir -p /usr/src/RPM/BUILD + cd /usr/src/RPM/BUILD + cd mechanize-0.2.5 + CFLAGS='-pipe -Wall -g -O2' + export CFLAGS + CXXFLAGS='-pipe -Wall -g -O2' + export CXXFLAGS + FFLAGS='-pipe -Wall -g -O2' + export FFLAGS + /usr/bin/python2.7 setup.py build running build running build_py creating build creating build/lib creating build/lib/mechanize copying mechanize/_version.py -> build/lib/mechanize copying mechanize/_util.py -> build/lib/mechanize copying mechanize/_useragent.py -> build/lib/mechanize copying mechanize/_urllib2_fork.py -> build/lib/mechanize copying mechanize/_urllib2.py -> build/lib/mechanize copying mechanize/_testcase.py -> build/lib/mechanize copying mechanize/_sockettimeout.py -> build/lib/mechanize copying mechanize/_sgmllib_copy.py -> build/lib/mechanize copying mechanize/_rfc3986.py -> build/lib/mechanize copying mechanize/_response.py -> build/lib/mechanize copying mechanize/_request.py -> build/lib/mechanize copying mechanize/_pullparser.py -> build/lib/mechanize copying mechanize/_opener.py -> build/lib/mechanize copying mechanize/_msiecookiejar.py -> build/lib/mechanize copying mechanize/_mozillacookiejar.py -> build/lib/mechanize copying mechanize/_mechanize.py -> build/lib/mechanize copying mechanize/_markupbase.py -> build/lib/mechanize copying mechanize/_lwpcookiejar.py -> build/lib/mechanize copying mechanize/_http.py -> build/lib/mechanize copying mechanize/_html.py -> build/lib/mechanize copying mechanize/_headersutil.py -> build/lib/mechanize copying mechanize/_gzip.py -> build/lib/mechanize copying mechanize/_form.py -> build/lib/mechanize copying mechanize/_firefox3cookiejar.py -> build/lib/mechanize copying mechanize/_debug.py -> build/lib/mechanize copying mechanize/_clientcookie.py -> build/lib/mechanize copying mechanize/_beautifulsoup.py -> build/lib/mechanize copying mechanize/_auth.py -> build/lib/mechanize copying mechanize/__init__.py -> build/lib/mechanize + pushd ../python3 ~/RPM/BUILD/python3 ~/RPM/BUILD/mechanize-0.2.5 + find -type f -name '*.py' -exec 2to3 -w -n '{}' + RefactoringTool: Skipping optional fixer: buffer RefactoringTool: Skipping optional fixer: idioms RefactoringTool: Skipping optional fixer: set_literal RefactoringTool: Skipping optional fixer: ws_comma RefactoringTool: Refactored ./test/test_urllib2_localnet.py --- ./test/test_urllib2_localnet.py (original) +++ ./test/test_urllib2_localnet.py (refactored) @@ -4,9 +4,9 @@ import email.message import threading -import urlparse +import urllib.parse import mechanize -import BaseHTTPServer +import http.server import unittest from mechanize._testcase import TestCase @@ -17,13 +17,13 @@ # Loopback http server infrastructure -class LoopbackHttpServer(BaseHTTPServer.HTTPServer): +class LoopbackHttpServer(http.server.HTTPServer): """HTTP server w/ a few modifications that make it useful for loopback testing purposes. """ def __init__(self, server_address, RequestHandlerClass): - BaseHTTPServer.HTTPServer.__init__(self, + http.server.HTTPServer.__init__(self, server_address, RequestHandlerClass) @@ -168,13 +168,13 @@ if len(self._users) == 0: return True - if not request_handler.headers.has_key('Proxy-Authorization'): + if 'Proxy-Authorization' not in request_handler.headers: return self._return_auth_challenge(request_handler) else: auth_dict = self._create_auth_dict( request_handler.headers['Proxy-Authorization'] ) - if self._users.has_key(auth_dict["username"]): + if auth_dict["username"] in self._users: password = self._users[ auth_dict["username"] ] else: return self._return_auth_challenge(request_handler) @@ -201,7 +201,7 @@ # Proxy test infrastructure -class FakeProxyHandler(BaseHTTPServer.BaseHTTPRequestHandler): +class FakeProxyHandler(http.server.BaseHTTPRequestHandler): """This is a 'fake proxy' that makes it look like the entire internet has gone down due to a sudden zombie invasion. It main utility is in providing us with authentication support for @@ -214,7 +214,7 @@ # This has to be set before calling our parent's __init__(), which will # try to call do_GET(). self.digest_auth_handler = digest_auth_handler - BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, *args, **kwargs) + http.server.BaseHTTPRequestHandler.__init__(self, *args, **kwargs) def log_message(self, format, *args): # Uncomment the next line for debugging. @@ -222,7 +222,7 @@ pass def do_GET(self): - (scm, netloc, path, params, query, fragment) = urlparse.urlparse( + (scm, netloc, path, params, query, fragment) = urllib.parse.urlparse( self.path, 'http') self.short_path = path if self.digest_auth_handler.handle_request(self): @@ -310,7 +310,7 @@ result.close() -class RecordingHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): +class RecordingHTTPRequestHandler(http.server.BaseHTTPRequestHandler): server_version = "TestHTTP/" protocol_version = "HTTP/1.0" @@ -322,7 +322,7 @@ self._get_next_response = get_next_response self._record_request = record_request self._record_received_headers = record_received_headers - BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, *args, **kwds) + http.server.BaseHTTPRequestHandler.__init__(self, *args, **kwds) def do_GET(self): body = self.send_head() @@ -416,8 +416,8 @@ data = f.read() f.close() - self.assertEquals(data, expected_response) - self.assertEquals(handler.requests, ['/', '/somewhere_else']) + self.assertEqual(data, expected_response) + self.assertEqual(handler.requests, ['/', '/somewhere_else']) def test_404(self): expected_response = 'Bad bad bad...' @@ -425,7 +425,7 @@ try: mechanize.urlopen('http://localhost:%s/weeble' % handler.port) - except mechanize.URLError, f: + except mechanize.URLError as f: pass else: self.fail('404 should raise URLError') @@ -433,8 +433,8 @@ data = f.rRefactoringTool: Refactored ./test/test_urllib2.py ead() f.close() - self.assertEquals(data, expected_response) - self.assertEquals(handler.requests, ['/weeble']) + self.assertEqual(data, expected_response) + self.assertEqual(handler.requests, ['/weeble']) def test_200(self): expected_response = 'pycon 2008...' @@ -444,8 +444,8 @@ data = f.read() f.close() - self.assertEquals(data, expected_response) - self.assertEquals(handler.requests, ['/bizarre']) + self.assertEqual(data, expected_response) + self.assertEqual(handler.requests, ['/bizarre']) def test_200_with_parameters(self): expected_response = 'pycon 2008...' @@ -456,8 +456,8 @@ data = f.read() f.close() - self.assertEquals(data, expected_response) - self.assertEquals(handler.requests, ['/bizarre', 'get=with_feeling']) + self.assertEqual(data, expected_response) + self.assertEqual(handler.requests, ['/bizarre', 'get=with_feeling']) def test_sending_headers(self): handler = self._make_request_handler([(200, [], "we don't care")]) --- ./test/test_urllib2.py (original) +++ ./test/test_urllib2.py (refactored) @@ -10,8 +10,8 @@ # CacheFTPHandler (hard to write) # parse_keqv_list, parse_http_list -import StringIO -import httplib +import io +import http.client import os import sys import unittest @@ -76,7 +76,7 @@ ('a, b, "c", "d", "e,f", g, h', ['a', 'b', '"c"', '"d"', '"e,f"', 'g', 'h']), ('a="b\\"c", d="e\\,f", g="h\\\\i"', ['a="b"c"', 'd="e,f"', 'g="h\\i"'])] for string, list in tests: - self.assertEquals(mechanize._urllib2_fork.parse_http_list(string), + self.assertEqual(mechanize._urllib2_fork.parse_http_list(string), list) @@ -275,15 +275,15 @@ """ f = [] - for kv in mapping.items(): + for kv in list(mapping.items()): f.append("%s: %s" % kv) f.append("") - msg = httplib.HTTPMessage(StringIO.StringIO("\r\n".join(f))) + msg = http.client.HTTPMessage(io.StringIO("\r\n".join(f))) return msg -class MockResponse(StringIO.StringIO): +class MockResponse(io.StringIO): def __init__(self, code, msg, headers, data, url=None): - StringIO.StringIO.__init__(self, data) + io.StringIO.__init__(self, data) self.code, self.msg, self.headers, self.url = code, msg, headers, url def info(self): return self.headers @@ -400,7 +400,7 @@ self.requests = [] def http_open(self, req): import email.message, copy - from StringIO import StringIO + from io import StringIO self.requests.append(copy.deepcopy(req)) if self._count == 0: self._count = self._count + 1 @@ -507,7 +507,7 @@ o.add_handler(p) o._maybe_reindex_handlers() self.assertEqual(o.handle_open, {"http": [h]}) - self.assertEqual(len(o.process_response.keys()), 1) + self.assertEqual(len(list(o.process_response.keys())), 1) self.assertEqual(list(o.process_response["http"]), [p]) self.assertEqual(list(o._any_response), [p]) self.assertEqual(o.handlers, [h, p]) @@ -650,23 +650,23 @@ enumerate(zip(o.calls, calls))): if i < 2: # *_request - self.assert_((handler, name) == calls) - self.assert_(len(args) == 1) - self.assert_(isinstance(args[0], Request)) + self.assertTrue((handler, name) == calls) + self.assertTrue(len(args) == 1) + self.assertTrue(isinstance(args[0], Request)) else: # *_response - self.assert_((handler, name) == calls) - self.assert_(len(args) == 2) - self.assert_(isinstance(args[0], Request)) + self.assertTrue((handler, name) == calls) + self.assertTrue(len(args) == 2) + self.assertTrue(isinstance(args[0], Request)) # response from opener.open is None, because there's no # handler that defines http_open to handle it - self.assert_(args[1] is None or + self.assertTrue(args[1] is None or isinstance(args[1], MockResponse)) def sanepathname2url(path): - import urllib - urlpath = urllib.pathname2url(path) + import urllib.request, urllib.parse, urllib.error + urlpath = urllib.request.pathname2url(path) if os.name == "nt" and urlpath.startswith("///"): urlpath = urlpath[2:] # XXX don't ask me about the mac... @@ -712,7 +712,7 @@ def __init__(self, data): self.data = data def retrfile(self, filename, filetype): self.filename, self.filetype = filename, filetype - return StringIO.StringIO(self.data), len(self.data) + return io.StringIO(self.data), len(self.data) class NullFTPHandler(mechanize.FTPHandler): def __init__(self, data): self.data = data @@ -751,7 +751,7 @@ self.assertEqual(h.port, port) self.assertEqual(h.dirs, dirs) if sys.version_info >= (2, 6): - self.assertEquals(h.timeout, timeout) + self.assertEqual(h.timeout, timeout) self.assertEqual(h.ftpwrapper.filename, filename) self.assertEqual(h.ftpwrapper.filetype, type_) headers = r.info() @@ -851,7 +851,7 @@ def request(self, method, url, body=None, headers={}): self.method = method self.selector = url - self.req_headers += headers.items() + self.req_headers += list(headers.items()) self.req_headers.sort() if body: self.data = body @@ -980,17 +980,17 @@ req = Request(url) r = MockResponse(200, "OK", {}, "", url) newr = h.http_response(req, r) - self.assert_(r is newr) - self.assert_(h.referer == url) + self.assertTrue(r is newr) + self.assertTrue(h.referer == url) newreq = h.http_request(req) - self.assert_(req is newreq) - self.assert_(req.unredirected_hdrs["Referer"] == url) + self.assertTrue(req is newreq) + self.assertTrue(req.unredirected_hdrs["Referer"] == url) # don't clobber existing Referer ref = "http://set.by.user.com/" req.add_unredirected_header("Referer", ref) newreq = h.http_request(req) - self.assert_(req is newreq) - self.assert_(req.unredirected_hdrs["Referer"] == ref) + self.assertTrue(req is newreq) + self.assertTrue(req.unredirected_hdrs["Referer"] == ref) def test_raise_http_errors(self): # HTTPDefaultErrorHandler should raise HTTPError if no error handler @@ -1006,11 +1006,11 @@ try: h.http_error_default( request, response, code, msg, response.info()) - except mechanize.HTTPError, exc: - self.assert_(exc is not response) - self.assert_(exc.fp is response) + except mechanize.HTTPError as exc: + self.assertTrue(exc is not response) + self.assertTrue(exc.fp is response) else: - self.assert_(False) + self.assertTrue(False) # case 2. response object is already an HTTPError, so just re-raise it error = mechanize.HTTPError( @@ -1018,10 +1018,10 @@ try: h.http_error_default( request, error, code, msg, error.info()) - except mechanize.HTTPError, exc: - self.assert_(exc is error) + except mechanize.HTTPError as exc: + self.assertTrue(exc is error) else: - self.assert_(False) + self.assertTrue(False) def test_robots(self): # XXX useragent @@ -1036,7 +1036,7 @@ # first time: initialise anRefactoringTool: Refactored ./test/test_cookies.py d set up robots.txt parser before checking # whether OK to fetch URL h.http_request(req) - self.assertEquals(rfpc.calls, [ + self.assertEqual(rfpc.calls, [ "__call__", ("set_opener", opener), ("set_url", "http://example.com:80/robots.txt"), @@ -1048,7 +1048,7 @@ rfpc.clear() req = Request(url) h.http_request(req) - self.assert_(rfpc.calls == [ + self.assertTrue(rfpc.calls == [ ("can_fetch", "", url), ]) # different URL on same server: same again @@ -1056,7 +1056,7 @@ url = "http://example.com:80/blah.html" req = Request(url) h.http_request(req) - self.assert_(rfpc.calls == [ + self.assertTrue(rfpc.calls == [ ("can_fetch", "", url), ]) # disallowed URL @@ -1066,9 +1066,9 @@ req = Request(url) try: h.http_request(req) - except mechanize.HTTPError, e: - self.assert_(e.request == req) - self.assert_(e.code == 403) + except mechanize.HTTPError as e: + self.assertTrue(e.request == req) + self.assertTrue(e.code == 403) # new host: reload robots.txt (even though the host and port are # unchanged, we treat this as a new host because # "example.com" != "example.com:80") @@ -1077,7 +1077,7 @@ url = "http://example.com/rhubarb.html" req = Request(url) h.http_request(req) - self.assertEquals(rfpc.calls, [ + self.assertEqual(rfpc.calls, [ "__call__", ("set_opener", opener), ("set_url", "http://example.com/robots.txt"), @@ -1090,7 +1090,7 @@ url = "https://example.org/rhubarb.html" req = Request(url) h.http_request(req) - self.assertEquals(rfpc.calls, [ + self.assertEqual(rfpc.calls, [ "__call__", ("set_opener", opener), ("set_url", "https://example.org/robots.txt"), @@ -1103,7 +1103,7 @@ url = "ftp://example.com/" req = Request(url) h.http_request(req) - self.assert_(rfpc.calls == []) + self.assertTrue(rfpc.calls == []) def test_redirected_robots_txt(self): # redirected robots.txt fetch shouldn't result in another attempted @@ -1117,8 +1117,8 @@ def __init__(self): self.requests = [] def http_open(self, req): - import email.message, httplib, copy - from StringIO import StringIO + import email.message, http.client, copy + from io import StringIO self.requests.append(copy.deepcopy(req)) if req.get_full_url() == "http://example.com/robots.txt": hdr = "Location: http://example.com/en/robots.txt\r\n\r\n" @@ -1149,7 +1149,7 @@ r = MockResponse(200, "OK", {}, "") newreq = h.http_request(req) self.assertTrue(cj.ach_req is req is newreq) - self.assertEquals(req.get_origin_req_host(), "example.com") + self.assertEqual(req.get_origin_req_host(), "example.com") self.assertFalse(cj.ach_u) newr = h.http_response(req, r) self.assertTrue(cj.ec_req is req) @@ -1346,7 +1346,7 @@ HTTPCookieProcessor, HTTPError, HTTPDefaultErrorHandler, \ HTTPRedirectHandler - from test_cookies import interact_netscape + from .test_cookies import interact_netscape cj = CookieJar() interact_netscape(cj, "http://www.example.com/", "spam=eggs") @@ -1569,7 +1569,7 @@ []) ] for html, result in htmls: - self.assertEqual(parse_head(StringIO.StringIO(html), HeadParser()), result) + self.assertEqual(parse_head(io.StringIO(html), HeadParser()), result) --- ./test/test_cookies.py (original) +++ ./test/test_cookies.py (refactored) @@ -1,6 +1,6 @@ """Tests for _clientcookie.""" -import StringIO +import io import errno import inspect import email.message @@ -22,7 +22,7 @@ """ headers: list of RFC822-style 'Key: value' strings """ - f = StringIO.StringIO("\n".join(headers)) + f = io.StringIO("\n".join(headers)) self._headers = email.message.Message(f) self._url = url def info(self): return self._headers @@ -55,7 +55,7 @@ for fn in self._tempfiles: try: os.remove(fn) - except IOError, exc: + except IOError as exc: if exc.errno != errno.ENOENT: raise @@ -114,8 +114,8 @@ jar.add_cookie_header(request) expect_called = attribute_names(MockRequest) - set( ["port", "get_header", "header_items", "log_called"]) - self.assertEquals(request.called, expect_called) - self.assertEquals(request.added_headers, [("Cookie", "foo=bar")]) + self.assertEqual(request.called, expect_called) + self.assertEqual(request.added_headers, [("Cookie", "foo=bar")]) def test_extract_cookies(self): from mechanize import CookieJar @@ -151,8 +151,8 @@ jar.extract_cookies(response, request) expect_called = attribute_names(StubRequest) - set( ["port", "log_called"]) - self.assertEquals(request.called, expect_called) - self.assertEquals([(cookie.name, cookie.value) for cookie in jar], + self.assertEqual(request.called, expect_called) + self.assertEqual([(cookie.name, cookie.value) for cookie in jar], [("foo", "bar")]) def test_unverifiable(self): @@ -171,14 +171,14 @@ raise AttributeError(name) request = StubRequest(dict(is_unverifiable=lambda: False)) - self.assertEquals(request_is_unverifiable(request), False) + self.assertEqual(request_is_unverifiable(request), False) request = StubRequest(dict(is_unverifiable=lambda: False, unverifiable=True)) - self.assertEquals(request_is_unverifiable(request), False) + self.assertEqual(request_is_unverifiable(request), False) request = StubRequest(dict(unverifiable=False)) - self.assertEquals(request_is_unverifiable(request), False) + self.assertEqual(request_is_unverifiable(request), False) class CookieTests(unittest.TestCase): @@ -233,7 +233,7 @@ policy = mechanize.DefaultCookiePolicy() jar = mechanize.CookieJar() jar.set_policy(policy) - self.assertEquals(jar.get_policy(), policy) + self.assertEqual(jar.get_policy(), policy) def test_make_cookies_doesnt_change_jar_state(self): from mechanize import CookieJar, Request, Cookie @@ -252,12 +252,12 @@ jar = CookieJar() jar._policy._now = jar._now = int(time.time()) jar.set_cookie(cookie) - self.assertEquals(len(jar), 1) + self.assertEqual(len(jar), 1) set_cookie = "spam=eggs; expires=%s" % time2netscape(time.time()- 1000) url = "http://example.com/" response = test_response(url=url, headers=[("Set-Cookie", set_cookie)]) jar.make_cookies(response, Request(url)) - self.assertEquals(len(jar), 1) + self.assertEqual(len(jar), 1) def test_domain_return_ok(self): # test optimization: .domain_return_ok() should filter out most @@ -287,8 +287,8 @@ ]: request = mechanize.Request(url) r = pol.domain_return_ok(domain, request) - if ok: self.assert_(r) - else: self.assert_(not r) + if ok: self.assertTrue(r) + else: self.assertTrue(not r) def test_missing_name(self): from mechanize import MozillaCookieJar, lwp_cookie_str @@ -336,7 +336,7 @@ c = CookieJar(policy) interact_netscape(c, "http://www.example.com/", "ni=ni; Version=1") cookie = c._cookies["www.example.com"]["/"]["ni"] - self.assert_(cookie.rfc2109) + self.assertTrue(cookie.rfc2109) self.assertEqual(cookie.version, version) def test_ns_parser(self): @@ -387,8 +387,8 @@ interact_netscape(c, "http://www.acme.com/", 'version=eggs; spam=eggs') cookies = c._cookies["www.acme.com"]["/"] - self.assert_(cookies.has_key('expires')) - self.assert_(cookies.has_key('version')) + self.assertTrue('expires' in cookies) + self.assertTrue('version' in cookies) def test_expires(self): from mechanize._util import time2netscape @@ -439,39 +439,39 @@ c = CookieJar(pol) interact_2965(c, "http://www.acme.com/", 'spam="bar"; Version="1"') - assert c._cookies["www.acme.com"].has_key("/") + assert "/" in c._cookies["www.acme.com"] c = CookieJar(pol) interact_2965(c, "http://www.acme.com/blah", 'eggs="bar"; Version="1"') - assert c._cookies["www.acme.com"].has_key("/") + assert "/" in c._cookies["www.acme.com"] c = CookieJar(pol) interact_2965(c, "http://www.acme.com/blah/rhubarb", 'eggs="bar"; Version="1"') - assert c._cookies["www.acme.com"].has_key("/blah/") + assert "/blah/" in c._cookies["www.acme.com"] c = CookieJar(pol) interact_2965(c, "http://www.acme.com/blah/rhubarb/", 'eggs="bar"; Version="1"') - assert c._cookies["www.acme.com"].has_key("/blah/rhubarb/") + assert "/blah/rhubarb/" in c._cookies["www.acme.com"] # Netscape c = CookieJar() interact_netscape(c, "http://www.acme.com/", 'spam="bar"') - assert c._cookies["www.acme.com"].has_key("/") + assert "/" in c._cookies["www.acme.com"] c = CookieJar() interact_netscape(c, "http://www.acme.com/blah", 'eggs="bar"') - assert c._cookies["www.acme.com"].has_key("/") + assert "/" in c._cookies["www.acme.com"] c = CookieJar() interact_netscape(c, "http://www.acme.com/blah/rhubarb", 'eggs="bar"') - assert c._cookies["www.acme.com"].has_key("/blah") + assert "/blah" in c._cookies["www.acme.com"] c = CookieJar() interact_netscape(c, "http://www.acme.com/blah/rhubarb/", 'eggs="bar"') - assert c._cookies["www.acme.com"].has_key("/blah/rhubarb") + assert "/blah/rhubarb" in c._cookies["www.acme.com"] def test_default_path_with_query(self): cj = mechanize.CookieJar() @@ -502,25 +502,25 @@ ("/foo\031/bar", "/foo%19/bar"), ("/\175foo/bar", "/%7Dfoo/bar"), # unicode - (u"/foo/bar\uabcd", "/foo/bar%EA%AF%8D"), # UTF-8 encoded + ("/foo/bar\uabcd", "/foo/bar%EA%AF%8D"), # UTF-8 encoded ] for arg, result in cases: - self.assert_(escape_path(arg) == result) + self.assertTrue(escape_path(arg) == result) def test_request_path(self): from mechanize._clientcookie import request_path # with parameters req = Request("http://www.example.com/rheum/rhaponticum;" "foo=bar;sing=song?apples=pears&spam=eggs#ni") - self.assertEquals(request_path(req), + self.assertEqual(request_path(req), "/rheum/rhaponticum;foo=bar;sing=song") # without parameters req = Request("http://www.example.com/rheum/rhaponticum?" "apples=pears&spam=eggs#ni") - self.assertEquals(request_path(req), "/rheum/rhaponticum") + self.assertEqual(request_path(req), "/rheum/rhaponticum") # missing final slash req = Request("http://www.example.com") - self.assert_(request_path(req) == "/") + self.assertTrue(request_path(req) == "/") def test_request_port(self): from mechanize._clientcookie import request_port, DEFAULT_HTTP_PORT @@ -558,10 +558,10 @@ def test_effective_request_host(self): from mechanize import effective_request_host - self.assertEquals( + self.assertEqual( effective_request_host(Request("http://www.EXAMPLE.com/spam")), "www.EXAMPLE.com") - self.assertEquals( + self.assertEqual( effective_request_host(Request("http://bob/spam")), "bob.local") @@ -646,11 +646,11 @@ interact_netscape(cj, "http://example.co.uk/", 'no=problemo') interact_netscape(cj, "http://example.co.uk/", 'okey=dokey; Domain=.example.co.uk') - self.assertEquals(len(cj), 2) + self.assertEqual(len(cj), 2) for pseudo_tld in [".co.uk", ".org.za", ".tx.us", ".name.us"]: interact_netscape(cj, "http://example.%s/" % pseudo_tld, 'spam=eggs; Domain=.co.uk') - self.assertEquals(len(cj), 2) + self.assertEqual(len(cj), 2) # XXXX This should be compared with the Konqueror (kcookiejar.cpp) and # Mozilla implementations. @@ -1065,11 +1065,11 @@ interact_netscape(cj, "http://example.com/", "short=path") interact_netscape(cj, "http://example.com/longer/path", "longer=path") for_short_path = cj.cookies_for_request(Request("http://example.com/")) - self.assertEquals([cookie.name for cookie in for_short_path], + self.assertEqual([cookie.name for cookie in for_short_path], ["short"]) for_long_path = cj.cookies_for_request(Request( "http://example.com/longer/path")) - self.assertEquals([cookie.name for cookie in for_long_path], + self.assertEqual([cookie.name for cookie in for_long_path], ["longer", "short"]) @@ -1110,11 +1110,11 @@ return cj cj = create_cookiejar() self._interact(cj) - self.assertEquals(len(cj), 6) + self.assertEqual(len(cj), 6) cj.close() cj = create_cookiejar() - self.assert_("name='foo1', value='bar'" in repr(cj)) - self.assertEquals(len(cj), 4) + self.assertTrue("name='foo1', value='bar'" in repr(cj)) + self.assertEqual(len(cj), 4) def test_firefox3_cookiejar_iteration(self): try: @@ -1133,7 +1133,7 @@ cj.connect() self._interact(cj) summary = "\n".join([str(cookie) for cookie in cj]) - self.assertEquals(summary, + self.assertEqual(summary, """\ @@ -1160,7 +1160,7 @@ self._interact(cj) cj.clear("www.acme.com", "/", "foo2") def summary(): return "\n".join([str(cookie) for cookie in cj]) - self.assertEquals(summary(), + self.assertEqual(summary(), """\ @@ -1168,7 +1168,7 @@ """) cj.clear("www.acme.com") - self.assertEquals(summary(), + self.assertEqual(summary(), """\ @@ -1200,11 +1200,11 @@ interact_netscape(cj, "http://www.foo.com/", "foob=bar; %s" % expires) ca, cb = cj - self.assert_(ca.discard) + self.assertTrue(ca.discard) self.assertFalse(cb.discard) request = Request("http://www.foo.com/") cj.add_cookie_header(request) - self.assertEquals(request.get_header("Cookie"), + self.assertEqual(request.get_header("Cookie"), "fooa=bar; foob=bar") def test_mozilla_cookiejar(self): @@ -1248,12 +1248,12 @@ cj = MozillaCookieJar(filename) cj.revert(ignore_discard=True) cookies = cj._cookies["a.com"]["/"] - self.aRefactoringTool: Refactored ./test/test_browser.py ssertEquals(cookies["name"].value, "val\tstillthevalue") - self.assertEquals(cookies["name2"].value, "value") + self.assertEqual(cookies["name"].value, "val\tstillthevalue") + self.assertEqual(cookies["name2"].value, "value") finally: try: os.remove(filename) - except IOError, exc: + except IOError as exc: if exc.errno != errno.ENOENT: raise @@ -1271,7 +1271,7 @@ finally: try: os.remove(filename) - except IOError, exc: + except IOError as exc: if exc.errno != errno.ENOENT: raise @@ -1709,7 +1709,7 @@ assert not cookie # unicode URL doesn't raise exception, as it used to! - cookie = interact_2965(c, u"http://www.acme.com/\xfc") + cookie = interact_2965(c, "http://www.acme.com/\xfc") def test_netscape_misc(self): # Some additional Netscape cookies tests. --- ./test/test_browser.py (original) +++ ./test/test_browser.py (refactored) @@ -1,7 +1,7 @@ #!/usr/bin/env python """Tests for mechanize.Browser.""" -import StringIO +import io from unittest import TestCase import re @@ -18,18 +18,18 @@ self.handle = handle self.action = action def __call__(self, *args): - return apply(self.handle, (self.meth_name, self.action)+args) + return self.handle(*(self.meth_name, self.action)+args) class MockHeaders(dict): def getheaders(self, name): name = name.lower() - return [v for k, v in self.iteritems() if name == k.lower()] + return [v for k, v in self.items() if name == k.lower()] class MockResponse: closeable_response = None def __init__(self, url="http://example.com/", data=None, info=None): self.url = url - self.fp = StringIO.StringIO(data) + self.fp = io.StringIO(data) if info is None: info = {} self._info = MockHeaders(info) def info(self): return self._info @@ -124,10 +124,10 @@ # Referer not added by .open()... req = mechanize.Request(url) b.open(req) - self.assert_(req.get_header("Referer") is None) + self.assertTrue(req.get_header("Referer") is None) # ...even if we're visiting a document b.open(req) - self.assert_(req.get_header("Referer") is None) + self.assertTrue(req.get_header("Referer") is None) # Referer added by .click_link() and .click() b.select_form("form1") req2 = b.click() @@ -143,22 +143,22 @@ "http://example.com/foo/bar.html") r4 = b.open(req4) req5 = b.click_link(name="apples") - self.assert_(not req5.has_header("Referer")) + self.assertTrue(not req5.has_header("Referer")) # Referer not added for non-http, non-https requests b.add_handler(make_mock_handler()([("blah_open", r)])) req6 = b.click_link(name="pears") - self.assert_(not req6.has_header("Referer")) + self.assertTrue(not req6.has_header("Referer")) # Referer not added when going from non-http, non-https URL r4 = b.open(req6) req7 = b.click_link(name="apples") - self.assert_(not req7.has_header("Referer")) + self.assertTrue(not req7.has_header("Referer")) # XXX Referer added for redirect def test_encoding(self): import mechanize - from StringIO import StringIO - import urllib, email.message + from io import StringIO + import urllib.request, urllib.parse, urllib.error, email.message # always take first encoding, since that's the one from the real HTTP # headers, rather than from HTTP-EQUIV b = mechanize.Browser() @@ -199,26 +199,26 @@ r1 = b.open("http://example.com/") self.assertRaises(mechanize.BrowserStateError, b.back) r2 = b.open("http://example.com/foo") - self.assert_(same_response(b.back(), r1)) + self.assertTrue(same_response(b.back(), r1)) r3 = b.open("http://example.com/bar") r4 = b.open("http://example.com/spam") - self.assert_(same_response(b.back(), r3)) - self.assert_(same_response(b.back(), r1)) - self.assertEquals(b.geturl(), "http://example.com/") + self.assertTrue(same_response(b.back(), r3)) + self.assertTrue(same_response(b.back(), r1)) + self.assertEqual(b.geturl(), "http://example.com/") self.assertRaises(mechanize.BrowserStateError, b.back) # reloading does a real HTTP fetch rather than using history cache r5 = b.reload() - self.assert_(not same_response(r5, r1)) + self.assertTrue(not same_response(r5, r1)) # .geturl() gets fed through to b.response - self.assertEquals(b.geturl(), "http://example.com/") + self.assertEqual(b.geturl(), "http://example.com/") # can go back n times r6 = b.open("spam") - self.assertEquals(b.geturl(), "http://example.com/spam") + self.assertEqual(b.geturl(), "http://example.com/spam") r7 = b.open("/spam") - self.assert_(same_response(b.response(), r7)) - self.assertEquals(b.geturl(), "http://example.com/spam") - self.assert_(same_response(b.back(2), r5)) - self.assertEquals(b.geturl(), "http://example.com/") + self.assertTrue(same_response(b.response(), r7)) + self.assertEqual(b.geturl(), "http://example.com/spam") + self.assertTrue(same_response(b.back(2), r5)) + self.assertEqual(b.geturl(), "http://example.com/") self.assertRaises(mechanize.BrowserStateError, b.back, 2) r8 = b.open("/spam") @@ -228,7 +228,7 @@ def https_open(self, request): r = mechanize.HTTPError( "https://example.com/bad", 503, "Oops", - MockHeaders(), StringIO.StringIO()) + MockHeaders(), io.StringIO()) return r b.add_handler(Handler2()) self.assertRaises(mechanize.HTTPError, b.open, @@ -236,7 +236,7 @@ self.assertEqual(b.response().geturl(), "https://example.com/bad") self.assertEqual(b.request.get_full_url(), "https://example.com/badreq") - self.assert_(same_response(b.back(), r8)) + self.assertTrue(same_response(b.back(), r8)) # .close() should make use of Browser methods and attributes complain # noisily, since they should not be called after .close() @@ -248,7 +248,7 @@ "encoding title select_form click submit click_link " "follow_link find_link".split() ): - self.assert_(getattr(b, attr) is None) + self.assertTrue(getattr(b, attr) is None) def test_reload_read_incomplete(self): import mechanize @@ -273,16 +273,16 @@ r = br.open("http://example.com") r.read(10) br.open('http://www.example.com/blah') - self.failIf(br.reloaded) + self.assertFalse(br.reloaded) br.back() - self.assert_(br.reloaded) + self.assertTrue(br.reloaded) # don't reload if already read br.reloaded = False br.response().read() br.open('http://www.example.com/blah') br.back() - self.failIf(br.reloaded) + self.assertFalse(br.reloaded) def test_viewing_html(self): # XXX not testing multiple Content-Type headers @@ -345,7 +345,7 @@ b = TestBrowser(factory=factory) - self.assert_(b.response() is None) + self.assertTrue(b.response() is None) # To open a relative reference (often called a "relative URL"), you # have to have already opened a URL for it "to be relative to". @@ -376,7 +376,7 @@ b.add_handler(make_mock_handler()( [("http_open", MockResponse(url, "", {}))])) r = b.open(url) - self.assert_(not b.viewing_html()) + self.assertTrue(not b.vieRefactoringTool: Refactored ./test/test_useragent.py RefactoringTool: Refactored ./test/test_unittest.py wing_html()) test_state_error("click links forms title select_form".split()) self.assertRaises(mechanize.BrowserStateError, b.submit, nr=0) self.assertRaises(mechanize.BrowserStateError, b.click_link, nr=0) @@ -481,7 +481,7 @@ Link = mechanize.Link try: - mdashx2 = u"\u2014".encode(encoding)*2 + mdashx2 = "\u2014".encode(encoding)*2 except UnicodeError: mdashx2 = '——' qmdashx2 = clean_url(mdashx2, encoding) @@ -746,9 +746,9 @@ "" ) - fp = StringIO.StringIO('
') + fp = io.StringIO('
') headers = email.message.Message( - StringIO.StringIO("Content-type: text/html")) + io.StringIO("Content-type: text/html")) response = _response.response_seek_wrapper( _response.closeable_response( fp, headers, "http://example.com/", 200, "OK")) --- ./test/test_useragent.py (original) +++ ./test/test_useragent.py (refactored) @@ -4,7 +4,7 @@ import mechanize -from test_browser import make_mock_handler +from .test_browser import make_mock_handler class UserAgentTests(TestCase): --- ./test/test_unittest.py (original) +++ ./test/test_unittest.py (refactored) @@ -6,8 +6,8 @@ TestCase.{assert,fail}* methods (some are tested implicitly) """ -from StringIO import StringIO -import __builtin__ +from io import StringIO +import builtins import os import re import sys @@ -15,7 +15,7 @@ from unittest import TestCase, TestProgram import types from copy import deepcopy -from cStringIO import StringIO +from io import StringIO import pickle ### Support code @@ -93,7 +93,7 @@ self.fail("%r and %r do not hash equal" % (obj_1, obj_2)) except KeyboardInterrupt: raise - except Exception, e: + except Exception as e: self.fail("Problem hashing %r and %r: %s" % (obj_1, obj_2, e)) for obj_1, obj_2 in self.ne_pairs: @@ -103,7 +103,7 @@ (obj_1, obj_2)) except KeyboardInterrupt: raise - except Exception, e: + except Exception as e: self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e)) @@ -277,11 +277,11 @@ loader = unittest.TestLoader() suite = loader.loadTestsFromModule(m) - self.assertEquals(load_tests_args, [loader, suite, None]) + self.assertEqual(load_tests_args, [loader, suite, None]) load_tests_args = [] suite = loader.loadTestsFromModule(m, use_load_tests=False) - self.assertEquals(load_tests_args, []) + self.assertEqual(load_tests_args, []) ################################################################ ### /Tests for TestLoader.loadTestsFromModule() @@ -300,7 +300,7 @@ try: loader.loadTestsFromName('') - except ValueError, e: + except ValueError as e: self.assertEqual(str(e), "Empty module name") else: self.fail("TestLoader.loadTestsFromName failed to raise ValueError") @@ -333,7 +333,7 @@ try: loader.loadTestsFromName('sdasfasfasdf') - except ImportError, e: + except ImportError as e: self.assertEqual(str(e), "No module named sdasfasfasdf") else: self.fail("TestLoader.loadTestsFromName failed to raise ImportError") @@ -349,7 +349,7 @@ try: loader.loadTestsFromName('unittest.sdasfasfasdf') - except AttributeError, e: + except AttributeError as e: self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") else: self.fail("TestLoader.loadTestsFromName failed to raise AttributeError") @@ -366,7 +366,7 @@ try: loader.loadTestsFromName('sdasfasfasdf', unittest) - except AttributeError, e: + except AttributeError as e: self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") else: self.fail("TestLoader.loadTestsFromName failed to raise AttributeError") @@ -387,7 +387,7 @@ try: loader.loadTestsFromName('', unittest) - except AttributeError, e: + except AttributeError as e: pass else: self.fail("Failed to raise AttributeError") @@ -520,7 +520,7 @@ loader = unittest.TestLoader() try: loader.loadTestsFromName('testcase_1.testfoo', m) - except AttributeError, e: + except AttributeError as e: self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'") else: self.fail("Failed to raise AttributeError") @@ -683,7 +683,7 @@ try: loader.loadTestsFromNames(['']) - except ValueError, e: + except ValueError as e: self.assertEqual(str(e), "Empty module name") else: self.fail("TestLoader.loadTestsFromNames failed to raise ValueError") @@ -718,7 +718,7 @@ try: loader.loadTestsFromNames(['sdasfasfasdf']) - except ImportError, e: + except ImportError as e: self.assertEqual(str(e), "No module named sdasfasfasdf") else: self.fail("TestLoader.loadTestsFromNames failed to raise ImportError") @@ -734,7 +734,7 @@ try: loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest']) - except AttributeError, e: + except AttributeError as e: self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") else: self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError") @@ -753,7 +753,7 @@ try: loader.loadTestsFromNames(['sdasfasfasdf'], unittest) - except AttributeError, e: + except AttributeError as e: self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") else: self.fail("TestLoader.loadTestsFromName failed to raise AttributeError") @@ -772,7 +772,7 @@ try: loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest) - except AttributeError, e: + except AttributeError as e: self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") else: self.fail("TestLoader.loadTestsFromName failed to raise AttributeError") @@ -921,7 +921,7 @@ loader = unittest.TestLoader() try: loader.loadTestsFromNames(['testcase_1.testfoo'], m) - except AttributeError, e: + except AttributeError as e: self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'") else: self.fail("Failed to raise AttributeError") @@ -1797,7 +1797,7 @@ def test_id(self): test = unittest.FunctionTestCase(lambda: None) - self.assertTrue(isinstance(test.id(), basestring)) + self.assertTrue(isinstance(test.id(), str)) # "Returns a one-line description of the test, or None if no description # has been provided. The default implementation of this method returns @@ -2429,7 +2429,7 @@ def runTest(self): pass - self.assertTrue(isinstance(Foo().id(), basestring)) + self.assertTrue(isinstance(Foo().id(), str)) # "If result is omitted or None, a temporary result object is created # and used, but is not made available to the caller. As TestCase owns the @@ -2747,47 +2747,47 @@ self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant') # Try Unicode - self.assertGreater(u'bug', u'ant') - self.assertGreaterEqual(u'bug', u'ant') - self.assertGreaterEqual(u'ant', u'ant') - self.assertLess(u'ant', u'bug') - self.assertLessEqual(u'ant', u'bug') - self.assertLessEqual(u'ant', u'ant') - self.assertRaises(self.failureException, self.assertGreater, u'ant', u'bug') - self.assertRaises(self.failureException, self.assertGreater, u'ant', u'ant') - self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant', - u'bug') - self.assertRaises(self.failureException, self.assertLess, u'bug', u'ant') - self.assertRaises(self.failureException, self.assertLess, u'ant', u'ant') - self.assertRaises(self.failureException, self.assertLessEqual, u'bug', u'ant') + self.assertGreater('bug', 'ant') + self.assertGreaterEqual('bug', 'ant') + self.assertGreaterEqual('ant', 'ant') + self.assertLess('ant', 'bug') + self.assertLessEqual('ant', 'bug') + self.assertLessEqual('ant', 'ant') + self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug') + self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant') + self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', + 'bug') + self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant') + self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant') + self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant') # Try Mixed String/Unicode - self.assertGreater('bug', u'ant') - self.assertGreater(u'bug', 'ant') - self.assertGreaterEqual('bug', u'ant') - self.assertGreaterEqual(u'bug', 'ant') - self.assertGreaterEqual('ant', u'ant') - self.assertGreaterEqual(u'ant', 'ant') - self.assertLess('ant', u'bug') - self.assertLess(u'ant', 'bug') - self.assertLessEqual('ant', u'bug') - self.assertLessEqual(u'ant', 'bug') - self.assertLessEqual('ant', u'ant') - self.assertLessEqual(u'ant', 'ant') - self.assertRaises(self.failureException, self.assertGreater, 'ant', u'bug') - self.assertRaises(self.failureException, self.assertGreater, u'ant', 'bug') - self.assertRaises(self.failureException, self.assertGreater, 'ant', u'ant') - self.assertRaises(self.failureException, self.assertGreater, u'ant', 'ant') + self.assertGreater('bug', 'ant') + self.assertGreater('bug', 'ant') + self.assertGreaterEqual('bug', 'ant') + self.assertGreaterEqual('bug', 'ant') + self.assertGreaterEqual('ant', 'ant') + self.assertGreaterEqual('ant', 'ant') + self.assertLess('ant', 'bug') + self.assertLess('ant', 'bug') + self.assertLessEqual('ant', 'bug') + self.assertLessEqual('ant', 'bug') + self.assertLessEqual('ant', 'ant') + self.assertLessEqual('ant', 'ant') + self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug') + self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug') + self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant') + self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant') self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', - u'bug') - self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant', 'bug') - self.assertRaises(self.failureException, self.assertLess, 'bug', u'ant') - self.assertRaises(self.failureException, self.assertLess, u'bug', 'ant') - self.assertRaises(self.failureException, self.assertLess, 'ant', u'ant') - self.assertRaises(self.failureException, self.assertLess, u'ant', 'ant') - self.assertRaises(self.failureException, self.assertLessEqual, 'bug', u'ant') - self.assertRaises(self.failureException, self.assertLessEqual, u'bug', 'ant') + self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', + 'bug') + self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant') + self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant') + self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant') + self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant') + self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant') + self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant') def testAssertMultiLineEqual(self): sample_text = """\ @@ -2817,7 +2817,7 @@ try: self.assertMultiLineEqual(type_changer(sample_text), type_changer(revised_sample_text)) - except self.failureException, e: + except self.failureException as e: # no fair testing ourself with ourself, use assertEqual.. self.assertEqual(sample_text_error, str(e).encode('utf8')) @@ -2828,8 +2828,8 @@ self.assertRaises(self.failureException, self.assertIsNotNone, None) def testAssertRegexpMatches(self): - self.assertRegexpMatches('asdfabasdf', r'ab+') - self.assertRaises(self.failureException, self.assertRegexpMatches, + self.assertRegex('asdfabasdf', r'ab+') + self.assertRaises(self.failureException, self.assertRegex, 'saaas', r'aaaa') def testAssertRaisesRegexp(self): @@ -2839,42 +2839,42 @@ def Stub(): raise ExceptionMock('We expect') - self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub) - self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub) - self.assertRaisesRegexp(ExceptionMock, u'expect$', Stub) + self.assertRaisesRegex(ExceptionMock, re.compile('expect$'), Stub) + self.assertRaisesRegex(ExceptionMock, 'expect$', Stub) + self.assertRaisesRegex(ExceptionMock, 'expect$', Stub) def testAssertNotRaisesRegexp(self): - self.assertRaisesRegexp( + self.assertRaisesRegex( self.failureException, '^Exception not raised$', - self.assertRaisesRegexp, Exception, re.compile('x'), + self.assertRaisesRegex, Exception, re.compile('x'), lambda: None) - self.assertRaisesRegexp( + self.assertRaisesRegex( self.failureException, '^Exception not raised$', - self.assertRaisesRegexp, Exception, 'x', + self.assertRaisesRegex, Exception, 'x', lambda: None) - self.assertRaisesRegexp( + self.assertRaisesRegex( self.failureException, '^Exception not raised$', - self.assertRaisesRegexp, Exception, u'x', + self.assertRaisesRegex, Exception, 'x', lambda: None) def testAssertRaisesRegexpMismatch(self): def Stub(): raise Exception('Unexpected') - self.assertRaisesRegexp( + self.assertRaisesRegex( self.failureException, r'"\^Expected\$" does not match "Unexpected"', - self.assertRaisesRegexp, Exception, '^Expected$', + self.assertRaisesRegex, Exception, '^Expected$', Stub) - self.assertRaisesRegexp( + self.assertRaisesRegex( self.failureException, r'"\^Expected\$" does not match "Unexpected"', - self.assertRaisesRegexp, Exception, u'^Expected$', + self.assertRaisesRegex, Exception, '^Expected$', Stub) - self.assertRaisesRegexp( + self.assertRaisesRegex( self.failureException, r'"\^Expected\$" does not match "Unexpected"', - self.assertRaisesRegexp, Exception, + self.assertRaisesRegex, Exception, re.compile('^Expected$'), Stub) # def testAssertRaisesExcValue(self): @@ -2900,24 +2900,24 @@ This test confirms their continued existence and functionality in order tRefactoringTool: Refactored ./test/test_response.py o avoid breaking existing code. """ - self.assertNotEquals(3, 5) - self.assertEquals(3, 3) - self.assertAlmostEquals(2.0, 2.0) - self.assertNotAlmostEquals(3.0, 5.0) - self.assert_(True) + self.assertNotEqual(3, 5) + self.assertEqual(3, 3) + self.assertAlmostEqual(2.0, 2.0) + self.assertNotAlmostEqual(3.0, 5.0) + self.assertTrue(True) def testPendingDeprecationMethodNames(self): """Test fail* methods pending deprecation, they will warn in 3.2. Do not use these methods. They will go away in 3.3. """ - self.failIfEqual(3, 5) - self.failUnlessEqual(3, 3) - self.failUnlessAlmostEqual(2.0, 2.0) - self.failIfAlmostEqual(3.0, 5.0) - self.failUnless(True) - self.failUnlessRaises(TypeError, lambda _: 3.14 + u'spam') - self.failIf(False) + self.assertNotEqual(3, 5) + self.assertEqual(3, 3) + self.assertAlmostEqual(2.0, 2.0) + self.assertNotAlmostEqual(3.0, 5.0) + self.assertTrue(True) + self.assertRaises(TypeError, lambda _: 3.14 + 'spam') + self.assertFalse(False) # not sure why this is broken, don't care # def testDeepcopy(self): @@ -3058,8 +3058,8 @@ self.assertRaises(KeyError, _raise, KeyError("key")) try: self.assertRaises(KeyError, lambda: None) - except self.failureException, e: - self.assert_("KeyError not raised" in e, str(e)) + except self.failureException as e: + self.assertTrue("KeyError not raised" in e, str(e)) else: self.fail("assertRaises() didn't fail") try: @@ -3115,11 +3115,11 @@ self.assertFalse(TestCase.longMessage) def test_formatMsg(self): - self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo") - self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo") - - self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo") - self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo") + self.assertEqual(self.testableFalse._formatMessage(None, "foo"), "foo") + self.assertEqual(self.testableFalse._formatMessage("foo", "bar"), "foo") + + self.assertEqual(self.testableTrue._formatMessage(None, "foo"), "foo") + self.assertEqual(self.testableTrue._formatMessage("foo", "bar"), "bar : foo") def assertMessages(self, methodName, args, errors): def getMethod(i): @@ -3137,7 +3137,7 @@ if withMsg: kwargs = {"msg": "oops"} - self.assertRaisesRegexp(self.failureException, expected_regexp, + self.assertRaisesRegex(self.failureException, expected_regexp, lambda: testMethod(*args, **kwargs)) def testAssertTrue(self): @@ -3483,9 +3483,9 @@ def test_pickle_unpickle(self): # Issue #7197: a TextTestRunner should be (un)pickleable. This is # required by test_multiprocessing under Windows (in verbose mode). - import StringIO + import io # cStringIO objects are not pickleable, but StringIO objects are. - stream = StringIO.StringIO("foo") + stream = io.StringIO("foo") runner = unittest.TextTestRunner(stream) for protocol in range(pickle.HIGHEST_PROTOCOL + 1): s = pickle.dumps(runner, protocol=protocol) --- ./test/test_response.py (original) +++ ./test/test_response.py (refactored) @@ -1,12 +1,12 @@ """Tests for mechanize._response.seek_wrapper and friends.""" import copy -import cStringIO +import io from unittest import TestCase class TestUnSeekable: def __init__(self, text): - self._file = cStringIO.StringIO(text) + self._file = io.StringIO(text) self.log = [] def tell(self): return self._file.tell() @@ -52,7 +52,7 @@ dog. """ - text_lines = map(lambda l: l+"\n", text.split("\n")[:-1]) + text_lines = [l+"\n" for l in text.split("\n")[RefactoringTool: Refactored ./test/test_pullparser.py :-1]] def testSeekable(self): from mechanize._response import seek_wrapper @@ -139,10 +139,10 @@ limit = 10 while count < limit: if count == 5: - self.assertRaises(StopIteration, sfh.next) + self.assertRaises(StopIteration, sfh.__next__) break else: - sfh.next() == text_lines[count] + next(sfh) == text_lines[count] count = count + 1 else: assert False, "StopIteration not raised" @@ -151,9 +151,9 @@ text = self.text sfh.read(10) sfh.seek(5) - self.assert_(sfh.invariant()) + self.assertTrue(sfh.invariant()) sfh.seek(0, 2) - self.assert_(sfh.invariant()) + self.assertTrue(sfh.invariant()) sfh.seek(0) self.assertEqual(sfh.read(), text) @@ -163,9 +163,9 @@ r = TestUnSeekableResponse(self.text, hdrs) rsw = response_seek_wrapper(r) rsw2 = self._testCopy(rsw) - self.assert_(rsw is not rsw2) + self.assertTrue(rsw is not rsw2) self.assertEqual(rsw.info(), rsw2.info()) - self.assert_(rsw.info() is not rsw2.info()) + self.assertTrue(rsw.info() is not rsw2.info()) # should be able to close already-closed object rsw2.close() --- ./test/test_pullparser.py (original) +++ ./test/test_pullparser.py (refactored) @@ -13,7 +13,7 @@ PARSERS = [(PullParser, False), (TolerantPullParser, True)] def data_and_file(self): - from StringIO import StringIO + from io import StringIO data = """ @@ -41,7 +41,7 @@ for pc, tolerant in PullParserTests.PARSERS: self._test_encoding(pc, tolerant) def _test_encoding(self, parser_class, tolerant): - from StringIO import StringIO + from io import StringIO datas = ["ф", "ф"] def get_text(data, encoding): p = _get_parser(data, encoding) @@ -66,10 +66,10 @@ self.assertEqual(get_text(data, "UTF-8"), "\xd1\x84") self.assertEqual(get_text("", "UTF-8"), - u"\u2014".encode('utf8')) + "\u2014".encode('utf8')) self.assertEqual( get_attr('blah', "UTF-8", "a", "name"), - u"\u2014".encode('utf8')) + "\u2014".encode('utf8')) self.assertEqual(get_text("", "ascii"), "—") # response = urllib.addinfourl(f, {"content-type": "text/html; charset=XXX"}, req.get_full_url()) @@ -208,7 +208,7 @@ data, f = self.data_and_file() p = parser_class(f) self.assertEqual(p.get_text(endat=("endtag", "html")), - u"\n\n\nTitle\n\n\nThis is a data blah & a[IMG]" + "\n\n\nTitle\n\n\nThis is a data blah & a[IMG]" " & that was an entityref and this a is\na charref. ." "\n\n\n\n\n\n") f.close() @@ -234,7 +234,7 @@ data, f = self.data_and_file() p = parser_class(f) self.assertEqual(p.get_compressed_text(endat=("endtag", "html")), - u"Title This is a data blah & a[IMG]" + "Title This is a data blah & a[IMG]" " & that was an entityref and this a is a charref. .") f.close() @@ -252,7 +252,7 @@ ] for i, token in enumerate(p.tags()): - self.assertEquals(token.data, expected_tag_names[i]) + self.assertEqual(token.data, expected_tag_names[i]) f.close() # tag name args @@ -266,7 +266,7 @@ ] for i, token in enumerate(p.tags("head", "p")): - self.assertEquals(token, expected_tokens[i]) + self.assertEqual(token, expected_tokens[i]) f.close() def test_tokens(self):RefactoringTool: Refactored ./test/test_pickle.py RefactoringTool: No changes to ./test/test_performance.py RefactoringTool: Refactored ./test/test_opener.py @@ -287,7 +287,7 @@ ] for i, token in enumerate(p.tokens()): - self.assertEquals(token.type, expected_token_types[i]) + self.assertEqual(token.type, expected_token_types[i]) f.close() # token type args @@ -300,7 +300,7 @@ ] for i, token in enumerate(p.tokens("charref", "entityref")): - self.assertEquals(token, expected_tokens[i]) + self.assertEqual(token, expected_tokens[i]) f.close() def test_token_eq(self): @@ -311,9 +311,9 @@ (Token('endtag', 'html', {'woof': 'bark'}), ('endtag', 'html', {'woof': 'bark'})), ]: - self.assertEquals(a, a) - self.assertEquals(a, b) - self.assertEquals(b, a) + self.assertEqual(a, a) + self.assertEqual(a, b) + self.assertEqual(b, a) if __name__ == "__main__": import unittest --- ./test/test_pickle.py (original) +++ ./test/test_pickle.py (refactored) @@ -1,5 +1,5 @@ -import cPickle -import cStringIO as StringIO +import pickle +import io as StringIO import pickle import mechanize --- ./test/test_opener.py (original) +++ ./test/test_opener.py (refactored) @@ -105,12 +105,12 @@ open=fs.open) except mechanize.URLError: pass - fs.verify(self.assertEquals) + fs.verify(self.assertEqual) def test_retrieve_closes_on_success(self): response_verifier = ResponseCloseVerifier() self._check_retrieve(urlopen=response_verifier.open) - response_verifier.verify(self.assertEquals) + response_verifier.verify(self.assertEqual) def test_retrieve_closes_on_failure(self): def fail_to_open(): @@ -122,7 +122,7 @@ raise mechanize.URLError("dummy reason") response_verifier = ResponseCloseVerifier(read=fail_to_read) self._check_retrieve(urlopen=response_verifier.open) - response_verifier.verify(self.assertEquals) + response_verifier.verify(self.assertEqual) def test_retrieve(self): # The .retrieve() method deals with a number of different cases. In @@ -181,7 +181,7 @@ self.assertEqual(verif.count, math.ceil(op.nr_blocks) + 1) op.close() # .close()ing the opener does NOT remove non-temporary files - self.assert_(os.path.isfile(filename)) + self.assertTrue(os.path.isfile(filename)) finally: killfile(filename) @@ -198,9 +198,9 @@ self.assertEqual(open(filename, "rb").read(), op.data) self.assertEqual(len(op.calls), 1) # .close()ing the opener removes temporary files - self.assert_(os.path.exists(filename)) + self.assertTrue(os.path.exists(filename)) op.close() - self.failIf(os.path.exists(filename)) + self.assertFalse(os.path.exists(filename)) self.assertEqual(verif.count, math.ceil(op.nr_blocks) + 1) # case 3: "file:" URL with no filename supplied @@ -224,7 +224,7 @@ self.assertEqual(verif.count, 0) op.close() # .close()ing the opener does NOT remove the file! - self.assert_(os.path.isfile(tifn)) + self.assertTrue(os.path.isfile(tifn)) finally: killfile(tifn) @@ -249,7 +249,7 @@ self.assertEqual(verif.count, math.ceil(op.nr_blocks) + 1) op.close() # .close()ing the opener does NOT remove non-temporary files - self.assert_(os.path.isfile(tfn)) + self.assertTrue(os.path.isfile(tfn)) finally: killfile(tfn) finally: @@ -263,7 +263,7 @@ try: try: op.retrieve(url, reporthook=verif.callback) - except mechanize.ContentTooShortError, exc: + except mechanize.ContentTooShortError as exc: filename, headers = exc.result self.assertNotRefactoringTool: Refactored ./test/test_import.py RefactoringTool: Refactored ./test/test_html.py RefactoringTool: Refactored ./test/test_headers.py Equal(filename, tfn) self.assertEqual(headers["foo"], 'Bar') @@ -273,9 +273,9 @@ self.assertEqual(len(op.calls), 1) self.assertEqual(verif.count, math.ceil(op.nr_blocks) + 1) # cleanup should still take place - self.assert_(os.path.isfile(filename)) + self.assertTrue(os.path.isfile(filename)) op.close() - self.failIf(os.path.isfile(filename)) + self.assertFalse(os.path.isfile(filename)) else: self.fail() finally: --- ./test/test_import.py (original) +++ ./test/test_import.py (refactored) @@ -8,7 +8,7 @@ def test_import_all(self): for name in mechanize.__all__: - exec "from mechanize import %s" % name + exec("from mechanize import %s" % name) if __name__ == "__main__": --- ./test/test_html.py (original) +++ ./test/test_html.py (refactored) @@ -67,54 +67,54 @@ log = [] cgenf = self._get_simple_cgenf(log) for repeat in range(2): - for ii, jj in zip(cgenf(), range(2)): + for ii, jj in zip(cgenf(), list(range(2))): self.assertEqual(ii, jj) - self.assertEqual(log, range(2)) # work only done once + self.assertEqual(log, list(range(2))) # work only done once def test_interleaved(self): log = [] cgenf = self._get_simple_cgenf(log) cgen = cgenf() - self.assertEqual(cgen.next(), 0) + self.assertEqual(next(cgen), 0) self.assertEqual(log, [0]) cgen2 = cgenf() - self.assertEqual(cgen2.next(), 0) + self.assertEqual(next(cgen2), 0) self.assertEqual(log, [0]) - self.assertEqual(cgen.next(), 1) + self.assertEqual(next(cgen), 1) self.assertEqual(log, [0, 1]) - self.assertEqual(cgen2.next(), 1) + self.assertEqual(next(cgen2), 1) self.assertEqual(log, [0, 1]) - self.assertRaises(StopIteration, cgen.next) - self.assertRaises(StopIteration, cgen2.next) + self.assertRaises(StopIteration, cgen.__next__) + self.assertRaises(StopIteration, cgen2.__next__) class UnescapeTests(TestCase): def test_unescape_charref(self): from mechanize._html import unescape_charref - mdash_utf8 = u"\u2014".encode("utf-8") + mdash_utf8 = "\u2014".encode("utf-8") for ref, codepoint, utf8, latin1 in [ - ("38", 38, u"&".encode("utf-8"), "&"), + ("38", 38, "&".encode("utf-8"), "&"), ("x2014", 0x2014, mdash_utf8, "—"), ("8212", 8212, mdash_utf8, "—"), ]: - self.assertEqual(unescape_charref(ref, None), unichr(codepoint)) + self.assertEqual(unescape_charref(ref, None), chr(codepoint)) self.assertEqual(unescape_charref(ref, 'latin-1'), latin1) self.assertEqual(unescape_charref(ref, 'utf-8'), utf8) def test_unescape(self): - import htmlentitydefs + import html.entities from mechanize._html import unescape data = "& < — — —" - mdash_utf8 = u"\u2014".encode("utf-8") - ue = unescape(data, htmlentitydefs.name2codepoint, "utf-8") + mdash_utf8 = "\u2014".encode("utf-8") + ue = unescape(data, html.entities.name2codepoint, "utf-8") self.assertEqual("& < %s %s %s" % ((mdash_utf8,)*3), ue) for text, expect in [ ("&a&", "&a&"), ("a&", "a&"), ]: - got = unescape(text, htmlentitydefs.name2codepoint, "latin-1") + got = unescape(text, html.entities.name2codepoint, "latin-1") self.assertEqual(got, expect) --- ./test/test_headers.py (original) +++ ./test/test_headers.py (refactored) @@ -36,9 +36,9 @@ # quotes should be stripped assert parse_ns_headers(['foo=bar; expires=01 Jan 2040 22:23:32 GMT']) == \ - [[('foo', 'bar'), ('expiresRefactoringTool: Refactored ./test/test_functional.py ', 2209069412L), ('version', '0')]] + [[('foo', 'bar'), ('expires', 2209069412), ('version', '0')]] assert parse_ns_headers(['foo=bar; expires="01 Jan 2040 22:23:32 GMT"']) == \ - [[('foo', 'bar'), ('expires', 2209069412L), ('version', '0')]] + [[('foo', 'bar'), ('expires', 2209069412), ('version', '0')]] def test_parse_ns_headers_version(self): from mechanize._headersutil import parse_ns_headers @@ -49,7 +49,7 @@ 'foo=bar; version="1"', 'foo=bar; Version="1"', ]: - self.assertEquals(parse_ns_headers([hdr]), expected) + self.assertEqual(parse_ns_headers([hdr]), expected) def test_parse_ns_headers_special_names(self): # names such as 'expires' are not special in first name=value pair @@ -59,7 +59,7 @@ # Cookie with name 'expires' hdr = 'expires=01 Jan 2040 22:23:32 GMT' expected = [[("expires", "01 Jan 2040 22:23:32 GMT"), ("version", "0")]] - self.assertEquals(parse_ns_headers([hdr]), expected) + self.assertEqual(parse_ns_headers([hdr]), expected) def test_join_header_words(self): from mechanize._headersutil import join_header_words @@ -96,8 +96,8 @@ try: result = split_header_words([arg]) except: - import traceback, StringIO - f = StringIO.StringIO() + import traceback, io + f = io.StringIO() traceback.print_exc(None, f) result = "(error -- traceback follows)\n\n%s" % f.getvalue() assert result == expect, """ --- ./test/test_functional.py (original) +++ ./test/test_functional.py (refactored) @@ -12,8 +12,8 @@ import subprocess import sys import unittest -import urllib -import urllib2 +import urllib.request, urllib.parse, urllib.error +import urllib.request, urllib.error, urllib.parse import mechanize from mechanize import CookieJar, HTTPCookieProcessor, \ @@ -76,16 +76,16 @@ old_opener_u = urllib2._opener mechanize.install_opener(mechanize.build_opener( mechanize.ProxyHandler(proxies={}))) - urllib2.install_opener(urllib2.build_opener( - urllib2.ProxyHandler(proxies={}))) + urllib.request.install_opener(urllib.request.build_opener( + urllib.request.ProxyHandler(proxies={}))) def revert_install(): mechanize.install_opener(old_opener_m) - urllib2.install_opener(old_opener_u) + urllib.request.install_opener(old_opener_u) self.add_teardown(revert_install) def sanepathname2url(path): - urlpath = urllib.pathname2url(path) + urlpath = urllib.request.pathname2url(path) if os.name == "nt" and urlpath.startswith("///"): urlpath = urlpath[2:] # XXX don't ask me about the mac... @@ -128,7 +128,7 @@ def __getattr__(self, name): return getattr(self._delegate, name) - assertEquals = self.assertEquals + assertEquals = self.assertEqual class TimeoutLog(object): AnyValue = object() @@ -232,7 +232,7 @@ req = mechanize.Request(urljoin(self.test_uri, "test_fixtures"), timeout=timeout) r = self.browser.open(req) - self.assert_("GeneralFAQ.html" in r.read(2048)) + self.assertTrue("GeneralFAQ.html" in r.read(2048)) timeout_log.verify(timeout) def test_302_and_404(self): @@ -273,12 +273,12 @@ r = self.browser.open(urljoin(self.uri, "test_fixtures")) self.assertEqual(r.code, 200) self.assertTrue(301 in codes) - self.assert_("GeneralFAQ.html" in r.read(2048)) + self.assertTrue("GeneralFAQ.html" in r.read(2048)) def test_refresh(self): def refresh_request(seconds): uri = urljoin(self.uri, "/cgi-bin/cookietest.cgi") - val = urllib.quote_plus('%d; url="%s"' % (seconds, self.uri)) + val = urllib.parse.quote_plus('%d; url="%s"' % (seconds, self.uri)) return uri + ("?refresh=%s" % val) self.browser.set_handle_refresh(True, honor_time=False) r = self.browser.open(refresh_request(5)) @@ -300,7 +300,7 @@ url = "file://%s" % sanepathname2url( os.path.abspath(os.path.join("test", "test_functional.py"))) r = self.browser.open(url) - self.assert_("this string appears in this file ;-)" in r.read()) + self.assertTrue("this string appears in this file ;-)" in r.read()) def test_open_local_file(self): # Since the file: URL scheme is not well standardised, Browser has a @@ -312,20 +312,20 @@ def test_open_novisit(self): def test_state(br): - self.assert_(br.request is None) - self.assert_(br.response() is None) + self.assertTrue(br.request is None) + self.assertTrue(br.response() is None) self.assertRaises(mechanize.BrowserStateError, br.back) test_state(self.browser) uri = urljoin(self.uri, "test_fixtures") # note this involves a redirect, which should itself be non-visiting r = self.browser.open_novisit(uri) test_state(self.browser) - self.assert_("GeneralFAQ.html" in r.read(2048)) + self.assertTrue("GeneralFAQ.html" in r.read(2048)) # Request argument instead of URL r = self.browser.open_novisit(mechanize.Request(uri)) test_state(self.browser) - self.assert_("GeneralFAQ.html" in r.read(2048)) + self.assertTrue("GeneralFAQ.html" in r.read(2048)) def test_non_seekable(self): # check everything still works without response_seek_wrapper and @@ -334,9 +334,9 @@ ua.set_seekable_responses(False) ua.set_handle_equiv(False) response = ua.open(self.test_uri) - self.failIf(hasattr(response, "seek")) + self.assertFalse(hasattr(response, "seek")) data = response.read() - self.assert_("Python bits" in data) + self.assertTrue("Python bits" in data) class ResponseTests(TestCase): @@ -364,18 +364,18 @@ opener.set_seekable_responses(True) try: opener.open(urljoin(self.uri, "nonexistent")) - except mechanize.HTTPError, exc: - self.assert_("HTTPError instance" in repr(exc)) + except mechanize.HTTPError as exc: + self.assertTrue("HTTPError instance" in repr(exc)) def test_no_seek(self): # should be possible to turn off UserAgent's .seek() functionality def check_no_seek(opener): r = opener.open(urljoin(self.uri, "test_fixtures/cctest2.txt")) - self.assert_(not hasattr(r, "seek")) + self.assertTrue(not hasattr(r, "seek")) try: opener.open(urljoin(self.uri, "nonexistent")) - except mechanize.HTTPError, exc: - self.assert_(not hasattr(exc, "seek")) + except mechanize.HTTPError as exc: + self.assertTrue(not hasattr(exc, "seek")) # mechanize.UserAgent opener = self.make_user_agent() @@ -399,13 +399,13 @@ self.assertEqual(data, r.read(), r.get_data()) try: opener.open(urljoin(self.uri, "nonexistent")) - except mechanize.HTTPError, exc: + except mechanize.HTTPError as exc: data = exc.read() if excs_also: exc.seek(0) self.assertEqual(data, exc.read(), exc.get_data()) else: - self.assert_(False) + self.assertTrue(False) opener = self.make_user_agent() opener.set_debug_http(False) @@ -489,11 +489,11 @@ referer = urljoin(self.uri, "test_fixtures/referertest.html") info = urljoin(self.uri, "/cgi-bin/cookietest.cgi") r = br.open(info) - self.assert_(referer not in r.get_data()) + self.assertTrue(referer nRefactoringTool: Refactored ./test/test_form_mutation.py ot in r.get_data()) br.open(referer) r = br.follow_link(text="Here") - self.assert_(referer in r.get_data()) + self.assertTrue(referer in r.get_data()) def test_cookies(self): # this test page depends on cookies, and an http-equiv refresh @@ -513,14 +513,14 @@ opener = self.build_opener(handlers) r = opener.open(urljoin(self.uri, "/cgi-bin/cookietest.cgi")) data = r.read() - self.assert_(data.find("Your browser supports cookies!") >= 0) - self.assertEquals(len(cj), 2) + self.assertTrue(data.find("Your browser supports cookies!") >= 0) + self.assertEqual(len(cj), 2) # test response.seek() (added by HTTPEquivProcessor) r.seek(0) samedata = r.read() r.close() - self.assertEquals(samedata, data) + self.assertEqual(samedata, data) def test_robots(self): plain_opener = self.build_opener( @@ -533,7 +533,7 @@ opener.open, urljoin(self.uri, "norobots")) def _check_retrieve(self, url, filename, headers): - from urllib import urlopen + from urllib.request import urlopen self.assertEqual(headers.get('Content-Type'), 'text/html') if self.no_proxies: proxies = {} @@ -550,7 +550,7 @@ filename, headers = opener.retrieve(url, test_filename, verif.callback) self.assertEqual(filename, test_filename) self._check_retrieve(url, filename, headers) - self.assert_(os.path.isfile(filename)) + self.assertTrue(os.path.isfile(filename)) def test_retrieve(self): # not passing an explicit filename downloads to a temporary file @@ -560,11 +560,11 @@ verif = CallbackVerifier(self) request = mechanize.Request(url) filename, headers = opener.retrieve(request, reporthook=verif.callback) - self.assertEquals(request.visit, False) + self.assertEqual(request.visit, False) self._check_retrieve(url, filename, headers) opener.close() # closing the opener removed the temporary file - self.failIf(os.path.isfile(filename)) + self.assertFalse(os.path.isfile(filename)) def test_urlretrieve(self): timeout_log = self._monkey_patch_socket() @@ -585,7 +585,7 @@ # if we don't do anything and go straight to another page, most of the # last page's response won't be .read()... r2 = browser.open(urljoin(self.uri, "mechanize")) - self.assert_(len(r1.get_data()) < 4097) # we only .read() a little bit + self.assertTrue(len(r1.get_data()) < 4097) # we only .read() a little bit # ...so if we then go back, .follow_link() for a link near the end (a # few kb in, past the point that always gets read in HTML files because # of HEAD parsing) will only work if it causes a .reload()... @@ -712,8 +712,8 @@ url = urljoin(self.uri, "/cgi-bin/cookietest.cgi") # no cookie was set on the first request html = br.open(url).read() - self.assertEquals(html.find("Your browser supports cookies!"), -1) - self.assertEquals(len(cookiejar), 2) + self.assertEqual(html.find("Your browser supports cookies!"), -1) + self.assertEqual(len(cookiejar), 2) # ... but now we have the cookie html = br.open(url).read() self.assertIn("Your browser supports cookies!", html) @@ -733,7 +733,7 @@ cj = mechanize.MozillaCookieJar(filename=filename) try: cj.revert() - except IOError, exc: + except IOError as exc: if exc.errno != errno.ENOENT: raise return cj --- ./test/test_form_mutation.py (original) +++ ./test/test_form_mutation.py (refactored) @@ -16,7 +16,7 @@ combined = form.controls + more.controls for control in more.controls: control.add_to_form(form) - self.assertEquals(form.controls, combined) + self.assertEqual(form.coRefactoringTool: Refactored ./test/test_form.py ntrols, combined) if __name__ == "__main__": --- ./test/test_form.py (original) +++ ./test/test_form.py (refactored) @@ -6,7 +6,7 @@ # Copyright 2005 Zope Corporation # Copyright 1998-2000 Gisle Aas. -from cStringIO import StringIO +from io import StringIO import os import string import unittest @@ -78,13 +78,13 @@ def test_unescape_charref(self): unescape_charref = _form.unescape_charref - mdash_utf8 = u"\u2014".encode("utf-8") + mdash_utf8 = "\u2014".encode("utf-8") for ref, codepoint, utf8, latin1 in [ - ("38", 38, u"&".encode("utf-8"), "&"), + ("38", 38, "&".encode("utf-8"), "&"), ("x2014", 0x2014, mdash_utf8, "—"), ("8212", 8212, mdash_utf8, "—"), ]: - self.assertEqual(unescape_charref(ref, None), unichr(codepoint)) + self.assertEqual(unescape_charref(ref, None), chr(codepoint)) self.assertEqual(unescape_charref(ref, 'latin-1'), latin1) self.assertEqual(unescape_charref(ref, 'utf-8'), utf8) @@ -92,11 +92,11 @@ get_entitydefs = _form.get_entitydefs ed = get_entitydefs() for name, char in [ - ("&", u"&"), - ("<", u"<"), - (">", u">"), - ("—", u"\u2014"), - ("♠", u"\u2660"), + ("&", "&"), + ("<", "<"), + (">", ">"), + ("—", "\u2014"), + ("♠", "\u2660"), ]: self.assertEqual(ed[name], char) @@ -104,7 +104,7 @@ unescape = _form.unescape get_entitydefs = _form.get_entitydefs data = "& < — — —" - mdash_utf8 = u"\u2014".encode("utf-8") + mdash_utf8 = "\u2014".encode("utf-8") ue = unescape(data, get_entitydefs(), "utf-8") self.assertEqual("& < %s %s %s" % ((mdash_utf8,)*3), ue) @@ -132,7 +132,7 @@ self.assertEqual(unescape("&", {}), "&") for encoding, expected in [ - ("utf-8", u"&\u06aa\u2014\u2014".encode("utf-8")), + ("utf-8", "&\u06aa\u2014\u2014".encode("utf-8")), ("latin-1", "&ڪ——")]: self.assertEqual( expected, @@ -147,7 +147,7 @@ forms = mechanize.ParseFile(file, "http://localhost/", backwards_compat=False, encoding="utf-8") form = forms[0] - test_string = "&"+(u"\u2014".encode('utf8')*3) + test_string = "&"+("\u2014".encode('utf8')*3) self.assertEqual(form.action, "http://localhost/"+test_string) control = form.find_control(type="textarea", nr=0) self.assertEqual(control.value, "val"+test_string) @@ -164,7 +164,7 @@ """) #" forms = mechanize.ParseFileEx(f, "http://localhost/", encoding="utf-8") form = forms[1] - test_string = "&"+(u"\u2014".encode('utf8')*3) + test_string = "&"+("\u2014".encode('utf8')*3) control = form.find_control(nr=0) for ii in range(len(control.items)): item = control.items[ii] @@ -192,7 +192,7 @@ def testEmptyParse(self): forms = mechanize.ParseFile(StringIO(""), "http://localhost", backwards_compat=False) - self.assert_(len(forms) == 0) + self.assertTrue(len(forms) == 0) def _forms(self): file = StringIO("""
@@ -207,8 +207,8 @@ def testParse(self): forms = self._forms() - self.assert_(len(forms) == 1) - self.assert_(forms[0]["firstname"] == "Gisle") + self.assertTrue(len(forms) == 1) + self.assertTrue(forms[0]["firstname"] == "Gisle") def testFillForm(self): forms = self._forms() @@ -220,8 +220,8 @@ return "POST" else: return "GET" - self.assert_(request_method(req) == "GET") - self.assert_(req.get_full_url() == "http://localhost/abc?firstname=Gisle+Aas") + self.assertTrue(request_method(req) == "GET") + self.assertTrue(req.get_full_url() == "http://localhost/abc?firstname=Gisle+Aas") def get_header(req, name): try: @@ -233,7 +233,7 @@ try: return req.header_items() except AttributeError: - return req.headers.items() + return list(req.headers.items()) class MockResponse: def __init__(self, f, url): @@ -268,7 +268,7 @@ mechanize.ParseError, mechanize.ParseFile, f, base_uri, backwards_compat=False, ) - self.assert_(issubclass(mechanize.ParseError, + self.assertTrue(issubclass(mechanize.ParseError, sgmllib.SGMLParseError)) def test_unknown_control(self): @@ -282,7 +282,7 @@ forms = mechanize.ParseFile(f, base_uri, backwards_compat=False) form = forms[0] for ctl in form.controls: - self.assert_(isinstance(ctl, _form.TextControl)) + self.assertTrue(isinstance(ctl, _form.TextControl)) def test_ParseFileEx(self): # empty "outer form" (where the "outer form" is the form consisting of @@ -384,10 +384,10 @@ base_uri = "http://localhost/" try: mechanize.ParseFile(f, base_uri, backwards_compat=False) - except mechanize.ParseError, e: - self.assert_(e.base_uri == base_uri) + except mechanize.ParseError as e: + self.assertTrue(e.base_uri == base_uri) else: - self.assert_(0) + self.assertTrue(0) def test_base_uri(self): # BASE element takes priority over document URI @@ -400,7 +400,7 @@ forms = mechanize.ParseFile(file, "http://localhost/", backwards_compat=False) form = forms[0] - self.assert_(form.action == "http://example.com/abc") + self.assertTrue(form.action == "http://example.com/abc") file = StringIO( """ @@ -410,7 +410,7 @@ forms = mechanize.ParseFile(file, "http://localhost/", backwards_compat=False) form = forms[0] - self.assert_(form.action == "http://localhost/abc") + self.assertTrue(form.action == "http://localhost/abc") def testTextarea(self): file = StringIO( @@ -431,19 +431,19 @@ """) forms = mechanize.ParseFile(file, "http://localhost/", backwards_compat=False, encoding="utf-8") - self.assert_(len(forms) == 1) + self.assertTrue(len(forms) == 1) form = forms[0] - self.assert_(form.name is None) + self.assertTrue(form.name is None) self.assertEqual( form.action, - "http://localhost/abc&"+u"\u2014".encode('utf8')+"d") + "http://localhost/abc&"+"\u2014".encode('utf8')+"d") control = form.find_control(type="textarea", nr=0) - self.assert_(control.name is None) - self.assert_(control.value == "blah, blah,\r\nRhubarb.\r\n\r\n") + self.assertTrue(control.name is None) + self.assertTrue(control.value == "blah, blah,\r\nRhubarb.\r\n\r\n") empty_control = form.find_control(type="textarea", nr=1) - self.assert_(str(empty_control) == "=)>") - self.assert_(empty_control.value == "") + self.assertTrue(str(empty_control) == "=)>") + self.assertTrue(empty_control.value == "") entity_ctl = form.find_control(type="textarea", nr=2) self.assertEqual(entity_ctl.name, '"ta"') @@ -464,11 +464,11 @@ """) forms = mechanize.ParseFile(file, "http://localhost/", backwards_compat=False) - self.assert_(len(forms) == 1) + self.assertTrue(len(forms) == 1) form = forms[0] entity_ctl = form.find_control(type="select") - self.assert_(entity_ctl.name == "foo") + self.assertTrue(entity_ctl.name == "foo") self.assertEqual(entity_ctl.value[0], "Hello testers & &blah; users!") hide_deprecations() @@ -496,14 +496,14 @@ forms = mechanize.ParseFile(file, "http://localhost/", backwards_compat=False) form = forms[0] - self.assert_(form.name == "myform") + self.assertTrue(form.name == "myform") control = form.find_control(name="b") - self.assert_(control.type == "submitbutton") - self.assert_(control.value == "") - self.assert_(form.find_control("b2").type == "resetbutton") - self.assert_(form.find_control("b3").type == "buttonbutton") + self.assertTrue(control.type == "submitbutton") + self.assertTrue(control.value == "") + self.assertTrue(form.find_control("b2").type == "resetbutton") + self.assertTrue(form.find_control("b3").type == "buttonbutton") pairs = form.click_pairs() - self.assert_(pairs == [("moo", "cow"), ("b", "")]) + self.assertTrue(pairs == [("moo", "cow"), ("b", "")]) def testIsindex(self): file = StringIO( @@ -518,14 +518,14 @@ backwards_compat=False) form = forms[0] control = form.find_control(type="isindex") - self.assert_(control.type == "isindex") - self.assert_(control.name is None) - self.assert_(control.value == "") + self.assertTrue(control.type == "isindex") + self.assertTrue(control.name is None) + self.assertTrue(control.value == "") control.value = "some stuff" - self.assert_(form.click_pairs() == []) - self.assert_(form.click_request_data() == + self.assertTrue(form.click_pairs() == []) + self.assertTrue(form.click_request_data() == ("http://localhost/abc?some+stuff", None, [])) - self.assert_(form.click().get_full_url() == + self.assertTrue(form.click().get_full_url() == "http://localhost/abc?some+stuff") def testEmptySelect(self): @@ -542,11 +542,11 @@ form = forms[0] control0 = form.find_control(type="select", nr=0) control1 = form.find_control(type="select", nr=1) - self.assert_(str(control0) == "") - self.assert_(str(control1) == "") + self.assertTrue(str(control0) == "") + self.assertTrue(str(control1) == "") form.set_value([], "foo") self.assertRaises(ItemNotFoundError, form.set_value, ["oops"], "foo") - self.assert_(form.click_pairs() == []) + self.assertTrue(form.click_pairs() == []) # XXX figure out what to do in these sorts of cases ## def badSelect(self): @@ -645,7 +645,7 @@ forms = mechanize.ParseFile(file, "http://localhost/", backwards_compat=False) form = forms[0] - self.assert_(form.controls[0].name is None) + self.assertTrue(form.controls[0].name is None) def testNamelessListItems(self): # XXX SELECT @@ -673,17 +673,17 @@ backwards_compat=False) form = forms[0] hide_deprecations() - self.assert_(form.possible_items("foo") == ["on"]) - self.assert_(form.possible_items("bar") == ["on"]) + self.assertTrue(form.possible_items("foo") == ["on"]) + self.assertTrue(form.possible_items("bar") == ["on"]) reset_deprecations() #self.assert_(form.possible_items("baz") == []) - self.assert_(form["foo"] == []) - self.assert_(form["bar"] == []) + self.assertTrue(form["foo"] == []) + self.assertTrue(form["bar"] == []) #self.assert_(form["baz"] == []) form["foo"] = ["on"] form["bar"] = ["on"] pairs = form.click_pairs() - self.assert_(pairs == [("foo", "on"), ("bar", "on"), ("submit", "")]) + self.assertTrue(pairs == [("foo", "on"), ("bar", "on"), ("submit", "")]) def testSingleSelectFixup(self): # HTML 4.01 section 17.6.1: single selection SELECT controls shouldn't @@ -755,9 +755,9 @@ backwards_compat=False) form = forms[0] control = form.find_control("a") - self.assert_(control.value == []) + self.assertTrue(control.value == []) single_control = form.find_control("b") - self.assert_(single_control.value == ["1"]) + self.assertTrue(single_control.value == ["1"]) file.seek(0) forms = mechanize.ParseFile(file, "http://localhost/", @@ -765,9 +765,9 @@ form = forms[0] # select_default only affects *multiple* selection select controls control = form.find_control(type="select", nr=0) - self.assert_(control.value == ["1"]) + self.assertTrue(control.value == ["1"]) single_control = form.find_control(type="select", nr=1) - self.assert_(single_control.value == ["1"]) + self.assertTrue(single_control.value == ["1"]) def test_close_base_tag(self): # Benji York: a single newline immediately after a start tag is @@ -814,7 +814,7 @@ backwards_compat=False, ) form = forms[0] - self.assertEquals(len(form.controls), 2) + self.assertEqual(len(form.controls), 2) ctl = form.find_control(name="a", nr=0) self.assertEqual([item.name for item in ctl.items], ["b", "c"]) ctl = form.find_control(name="a", nr=1) @@ -849,7 +849,7 @@ def test_empty_document(self): forms = mechanize.ParseFileEx(StringIO(""), "http://example.com/") - self.assertEquals(len(forms), 1) # just the "global form" + self.assertEqual(len(forms), 1) # just the "global form" def test_missing_closing_body_tag(self): # Even if there is no closing form or body tag, the last form on the @@ -858,8 +858,8 @@ StringIO(''), "http://example.com/", ) - self.assertEquals(len(forms), 2) - self.assertEquals(forms[1].name, "spam") + self.assertEqual(len(forms), 2) + self.assertEqual(forms[1].name, "spam") class DisabledTests(unittest.TestCase): @@ -968,48 +968,48 @@ control = get_control("foo") hide_deprecations() for name in 7, 8, 10: - self.assert_(control.get_item_disabled(str(name))) + self.assertTrue(control.get_item_disabled(str(name))) if not compat: # a disabled option is never "successful" (see above) so never # in value - self.assert_(str(name) not in control.value) + self.assertTrue(str(name) not in control.value) # a disabled option always is always upset if you try to set it self.assertRaises(AttributeError, control.set, True, str(name)) - self.assert_(str(name) not in control.value) + self.assertTrue(str(name) not in control.value) self.assertRaises(AttributeError, control.set, False, str(name)) - self.assert_(str(name) not in control.value) + self.assertTrue(str(name) not in control.value) self.assertRaises(AttributeError, control.toggle, str(name)) - self.assert_(str(name) not in control.value) + self.assertTrue(str(name) not in control.value) else: self.assertRaises(AttributeError, control.set, True, str(name)) control.set(False, str(name)) - self.assert_(str(name) not in control.value) + self.assertTrue(str(name) not in control.value) control.set(False, str(name)) - self.assert_(str(name) not in control.value) + self.assertTrue(str(name) not in control.value) self.assertRaises(AttributeError, control.toggle, str(name)) - self.assert_(str(name) not in control.value) + self.assertTrue(str(name) not in control.value) self.assertRaises(AttributeError, control.set, True, str(name)) - self.assert_(str(name) not in control.value) + self.assertTrue(str(name) not in control.value) control = get_control("foo") for name in 1, 2, 3, 4, 5, 6, 9: - self.assert_(not control.get_item_disabled(str(name))) + self.assertTrue(not control.get_item_disabled(str(name))) control.set(False, str(name)) - self.assert_(str(name) not in control.value) + self.assertTrue(str(name) not in control.value) control.toggle(str(name)) - self.assert_(str(name) in control.value) + self.assertTrue(str(name) in control.value) control.set(True, str(name)) - self.assert_(str(name) in control.value) + self.assertTrue(str(name) in control.value) control.toggle(str(name)) - self.assert_(str(name) not in control.value) + self.assertTrue(str(name) not in control.value) control = get_control("foo") - self.assert_(control.get_item_disabled("7")) + self.assertTrue(control.get_item_disabled("7")) control.set_item_disabled(True, "7") - self.assert_(control.get_item_disabled("7")) + self.assertTrue(control.get_item_disabled("7")) self.assertRaises(AttributeError, control.set, True, "7") control.set_item_disabled(False, "7") - self.assert_(not control.get_item_disabled("7")) + self.assertTrue(not control.get_item_disabled("7")) control.set(True, "7") control.set(False, "7") control.toggle("7") @@ -1042,50 +1042,50 @@ control = get_control("bar") hide_deprecations() for name in 7, 8, 10: - self.assert_(control.get_item_disabled(str(name))) + self.assertTrue(control.get_item_disabled(str(name))) if not compat: # a disabled option is never "successful" (see above) so never in # value - self.assert_(str(name) not in control.value) + self.assertTrue(str(name) not in control.value) # a disabled option always is always upset if you try to set it self.assertRaises(AttributeError, control.set, True, str(name)) - self.assert_(str(name) not in control.value) + self.assertTrue(str(name) not in control.value) self.assertRaises(AttributeError, control.set, False, str(name)) - self.assert_(str(name) not in control.value) + self.assertTrue(str(name) not in control.value) self.assertRaises(AttributeError, control.toggle, str(name)) - self.assert_(str(name) not in control.value) + self.assertTrue(str(name) not in control.value) else: self.assertRaises(AttributeError, control.set, True, str(name)) control.set(False, str(name)) - self.assert_(str(name) != control.value) + self.assertTrue(str(name) != control.value) control.set(False, str(name)) - self.assert_(str(name) != control.value) + self.assertTrue(str(name) != control.value) self.assertRaises(AttributeError, control.toggle, str(name)) - self.assert_(str(name) != control.value) + self.assertTrue(str(name) != control.value) self.assertRaises(AttributeError, control.set, True, str(name)) - self.assert_(str(name) != control.value) + self.assertTrue(str(name) != control.value) control = get_control("bar") for name in 1, 2, 3, 4, 5, 6, 9: - self.assert_(not control.get_item_disabled(str(name))) + self.assertTrue(not control.get_item_disabled(str(name))) control.set(False, str(name)) - self.assert_(str(name) not in control.value) + self.assertTrue(str(name) not in control.value) control.toggle(str(name)) - self.assert_(str(name) == control.value[0]) + self.assertTrue(str(name) == control.value[0]) control.set(True, str(name)) - self.assert_(str(name) == control.value[0]) + self.assertTrue(str(name) == control.value[0]) control.toggle(str(name)) - self.assert_(str(name) not in control.value) + self.assertTrue(str(name) not in control.value) control = get_control("bar") - self.assert_(control.get_item_disabled("7")) + self.assertTrue(control.get_item_disabled("7")) control.set_item_disabled(True, "7") - self.assert_(control.get_item_disabled("7")) + self.assertTrue(control.get_item_disabled("7")) self.assertRaises(AttributeError, control.set, True, "7") self.assertEqual(control.value, value) control.set_item_disabled(False, "7") self.assertEqual(control.value, ["7"]) - self.assert_(not control.get_item_disabled("7")) + self.assertTrue(not control.get_item_disabled("7")) control.set(True, "7") control.set(False, "7") control.toggle("7") @@ -1159,7 +1159,7 @@ hide_deprecations() item = control.get_item_attrs("2") reset_deprecations() - self.assertEqual(bool(item.has_key("disabled")), item_disabled) + self.assertEqual(bool("disabled" in item), item_disabled) def bad_assign(value, control=control): control.value = value hide_deprecations() @@ -1181,9 +1181,9 @@ hide_deprecations() self.assertRaises(TypeError, control.set_item_disabled, "1") # by_label - self.assert_(not control.get_item_disabled("a", by_label=True)) + self.assertTrue(not control.get_item_disabled("a", by_label=True)) control.set_item_disabled(True, "a", by_label=True) - self.assert_(control.get_item_disabled("a", by_label=True)) + self.assertTrue(control.get_item_disabled("a", by_label=True)) reset_deprecations() def testDisabledRadio(self): @@ -1204,7 +1204,7 @@ # since all items are disabled, .fixup() should not select # anything - self.assertEquals( + self.assertEqual( [item.name for item in control.items if item.selected], [], ) @@ -1240,11 +1240,11 @@ ("bar", False, True), ("baz", False, True)]: control = form.find_control(name) - self.assert_(bool(control.disabled) == control_disabled) + self.assertTrue(bool(control.disabled) == control_disabled) hide_deprecations() item = control.get_item_attrs("2") - self.assert_(bool(item.has_key("disabled")) == item_disabled) - self.assert_(control.get_item_disabled("2") == item_disabled) + self.assertTrue(bool("disabled" in item) == item_disabled) + self.assertTrue(control.get_item_disabled("2") == item_disabled) def bad_assign(value, control=control): control.value = value if item_disabled: @@ -1262,10 +1262,10 @@ # missing disabled arg self.assertRaises(TypeError, control.set_item_disabled, "1") # by_label - self.failIf(control.get_item_disabled('a', by_label=True)) - self.assert_(not control.get_item_disabled("1")) + self.assertFalse(control.get_item_disabled('a', by_label=True)) + self.assertTrue(not control.get_item_disabled("1")) control.set_item_disabled(True, 'a', by_label=True) - self.assert_(control.get_item_disabled("1")) + self.assertTrue(control.get_item_disabled("1")) reset_deprecations() @@ -1278,52 +1278,52 @@ "id": "foo"} c = _form.TextControl("texT", "ath_Uname", attrs) c.fixup() - self.assert_(c.type == "text") - self.assert_(c.name == "ath_Uname") - self.assert_(c.id == "foo") - self.assert_(c.value == "") - self.assert_(str(c) == "") - self.assert_(c.pairs() == [("ath_Uname", "")]) + self.assertTrue(c.type == "text") + self.assertTrue(c.name == "ath_Uname") + self.assertTrue(c.id == "foo") + self.assertTrue(c.value == "") + self.assertTrue(str(c) == "") + self.assertTrue(c.pairs() == [("ath_Uname", "")]) def bad_assign(c=c): c.type = "sometype" self.assertRaises(AttributeError, bad_assign) - self.assert_(c.type == "text") + self.assertTrue(c.type == "text") def bad_assign(c=c): c.name = "somename" self.assertRaises(AttributeError, bad_assign) - self.assert_(c.name == "ath_Uname") + self.assertTrue(c.name == "ath_Uname") c.value = "2" - self.assert_(c.value == "2") + self.assertTrue(c.value == "2") c.readonly = True self.assertRaises(AttributeError, c.clear) c.readonly = False c.clear() - self.assert_(c.value is None) + self.assertTrue(c.value is None) - self.assert_(c.pairs() == []) + self.assertTrue(c.pairs() == []) c.value = "2" # reset value... - self.assert_(str(c) == "") + self.assertTrue(str(c) == "") def bad_assign(c=c): c.value = ["foo"] self.assertRaises(TypeError, bad_assign) - self.assert_(c.value == "2") - self.assert_(not c.readonly) + self.assertTrue(c.value == "2") + self.assertTrue(not c.readonly) c.readonly = True def bad_assign(c=c): c.value = "foo" self.assertRaises(AttributeError, bad_assign) - self.assert_(c.value == "2") + self.assertTrue(c.value == "2") c.disabled = True - self.assert_(str(c) == + self.assertTrue(str(c) == "") c.readonly = False - self.assert_(str(c) == "") + self.assertTrue(str(c) == "") self.assertRaises(AttributeError, bad_assign) - self.assert_(c.value == "2") - self.assert_(c.pairs() == []) + self.assertTrue(c.value == "2") + self.assertTrue(c.pairs() == []) c.disabled = False - self.assert_(str(c) == "") - - self.assert_(c.attrs.has_key("maxlength")) + self.assertTrue(str(c) == "") + + self.assertTrue("maxlength" in c.attrs) for key in "name", "type", "value": - self.assert_(c.attrs.has_key(key)) + self.assertTrue(key in c.attrs) # initialisation of readonly and disabled attributes attrs["readonly"] = True @@ -1337,7 +1337,7 @@ self.assertRaises(AttributeError, bad_assign) del attrs["disabled"] c = _form.TextControl("hidden", "ath_Uname", attrs) - self.assert_(c.readonly) + self.assertTrue(c.readonly) def bad_assign(c=c): c.value = "foo" self.assertRaises(AttributeError, bad_assign) @@ -1347,58 +1347,58 @@ c.add_file(fp) fp2 = StringIO() c.add_file(fp2, None, "fp2 file test") - self.assert_(str(c) == ', fp2 file test)>') + self.assertTrue(str(c) == ', fp2 file test)>') c.readonly = True self.assertRaises(AttributeError, c.clear) c.readonly = False c.clear() - self.assert_(str(c) == ')>') + self.assertTrue(str(c) == ')>') def testIsindexControl(self): attrs = {"type": "this is ignored", "prompt": ">>>"} c = _form.IsindexControl("isIndex", None, attrs) c.fixup() - self.assert_(c.type == "isindex") - self.assert_(c.name is None) - self.assert_(c.value == "") - self.assert_(str(c) == "") - self.assert_(c.pairs() == []) + self.assertTrue(c.type == "isindex") + self.assertTrue(c.name is None) + self.assertTrue(c.value == "") + self.assertTrue(str(c) == "") + self.assertTrue(c.pairs() == []) def set_type(c=c): c.type = "sometype" self.assertRaises(AttributeError, set_type) - self.assert_(c.type == "isindex") + self.assertTrue(c.type == "isindex") def set_name(c=c): c.name = "somename" self.assertRaises(AttributeError, set_name) def set_value(value, c=c): c.value = value self.assertRaises(TypeError, set_value, [None]) - self.assert_(c.name is None) + self.assertTrue(c.name is None) c.value = "2" - self.assert_(c.value == "2") - self.assert_(str(c) == "") + self.assertTrue(c.value == "2") + self.assertTrue(str(c) == "") c.disabled = True - self.assert_(str(c) == "") + self.assertTrue(str(c) == "") self.assertRaises(AttributeError, set_value, "foo") - self.assert_(c.value == "2") - self.assert_(c.pairs() == []) + self.assertTrue(c.value == "2") + self.assertTrue(c.pairs() == []) c.readonly = True - self.assert_(str(c) == "") + self.assertTrue(str(c) == "") self.assertRaises(AttributeError, set_value, "foo") c.disabled = False - self.assert_(str(c) == "") + self.assertTrue(str(c) == "") self.assertRaises(AttributeError, set_value, "foo") c.readonly = False - self.assert_(str(c) == "") - - self.assert_(c.attrs.has_key("type")) - self.assert_(c.attrs.has_key("prompt")) - self.assert_(c.attrs["prompt"] == ">>>") + self.assertTrue(str(c) == "") + + self.assertTrue("type" in c.attrs) + self.assertTrue("prompt" in c.attrs) + self.assertTrue(c.attrs["prompt"] == ">>>") for key in "name", "value": - self.assert_(not c.attrs.has_key(key)) + self.assertTrue(key not in c.attrs) c.value = "foo 1 bar 2" class FakeForm: action = "http://localhost/" form = FakeForm() - self.assert_(c._click(form, (1,1), "request_data") == + self.assertTrue(c._click(form, (1,1), "request_data") == ("http://localhost/?foo+1+bar+2", None, [])) c.value = "foo 1 bar 2" @@ -1406,22 +1406,22 @@ self.assertRaises(AttributeError, c.clear) c.readonly = False c.clear() - self.assert_(c.value is None) + self.assertTrue(c.value is None) def testIgnoreControl(self): attrs = {"type": "this is ignored"} c = _form.IgnoreControl("reset", None, attrs) - self.assert_(c.type == "reset") - self.assert_(c.value is None) - self.assert_(str(c) == "=)>") + self.assertTrue(c.type == "reset") + self.assertTrue(c.value is None) + self.assertTrue(str(c) == "=)>") def set_value(value, c=c): c.value = value self.assertRaises(AttributeError, set_value, "foo") - self.assert_(c.value is None) + self.assertTrue(c.value is None) # this is correct, but silly; basically nothing should happen c.clear() - self.assert_(c.value is None) + self.assertTrue(c.value is None) def testSubmitControl(self): attrs = {"type": "this is ignored", @@ -1429,16 +1429,16 @@ "value": "value_value", "img": "foo.gif"} c = _form.SubmitControl("submit", "name_value", attrs) - self.assert_(c.type == "submit") - self.assert_(c.name == "name_value") - self.assert_(c.value == "value_value") - self.assert_(str(c) == "") + self.assertTrue(c.type == "submit") + self.assertTrue(c.name == "name_value") + self.assertTrue(c.value == "value_value") + self.assertTrue(str(c) == "") c.readonly = True self.assertRaises(AttributeError, c.clear) c.readonly = False c.clear() - self.assert_(c.value is None) + self.assertTrue(c.value is None) c.value = "value_value" c.readonly = True @@ -1446,62 +1446,62 @@ self.assertRaises(TypeError, set_value, ["foo"]) c.disabled = True self.assertRaises(AttributeError, set_value, "value_value") - self.assert_(str(c) == "") c.disabled = False c.readonly = False set_value("value_value") - self.assert_(str(c) == "") + self.assertTrue(str(c) == "") c.readonly = True # click on button form = _form.HTMLForm("http://foo.bar.com/") c.add_to_form(form) - self.assert_(c.pairs() == []) + self.assertTrue(c.pairs() == []) pairs = c._click(form, (1,1), "pairs") request = c._click(form, (1,1), "request") data = c._click(form, (1,1), "request_data") - self.assert_(c.pairs() == []) - self.assert_(pairs == [("name_value", "value_value")]) - self.assert_(request.get_full_url() == + self.assertTrue(c.pairs() == []) + self.assertTrue(pairs == [("name_value", "value_value")]) + self.assertTrue(request.get_full_url() == "http://foo.bar.com/?name_value=value_value") - self.assert_(data == + self.assertTrue(data == ("http://foo.bar.com/?name_value=value_value", None, [])) c.disabled = True pairs = c._click(form, (1,1), "pairs") request = c._click(form, (1,1), "request") data = c._click(form, (1,1), "request_data") - self.assert_(pairs == []) + self.assertTrue(pairs == []) # XXX not sure if should have '?' on end of this URL, or if it really matters... - self.assert_(request.get_full_url() == "http://foo.bar.com/") - self.assert_(data == ("http://foo.bar.com/", None, [])) + self.assertTrue(request.get_full_url() == "http://foo.bar.com/") + self.assertTrue(data == ("http://foo.bar.com/", None, [])) def testImageControl(self): attrs = {"type": "this is ignored", "name": "name_value", "img": "foo.gif"} c = _form.ImageControl("image", "name_value", attrs, index=0) - self.assert_(c.type == "image") - self.assert_(c.name == "name_value") - self.assert_(c.value == "") - self.assert_(str(c) == "") + self.assertTrue(c.type == "image") + self.assertTrue(c.name == "name_value") + self.assertTrue(c.value == "") + self.assertTrue(str(c) == "") c.readonly = True self.assertRaises(AttributeError, c.clear) c.readonly = False c.clear() - self.assert_(c.value is None) + self.assertTrue(c.value is None) c.value = "" # click, at coordinate (0, 55), on image form = _form.HTMLForm("http://foo.bar.com/") c.add_to_form(form) - self.assert_(c.pairs() == []) + self.assertTrue(c.pairs() == []) request = c._click(form, (0, 55), "request") - self.assert_(c.pairs() == []) - self.assert_(request.get_full_url() == + self.assertTrue(c.pairs() == []) + self.assertTrue(request.get_full_url() == "http://foo.bar.com/?name_value.x=0&name_value.y=55") - self.assert_(c._click(form, (0,55), return_type="request_data") == + self.assertTrue(c._click(form, (0,55), return_type="request_data") == ("http://foo.bar.com/?name_value.x=0&name_value.y=55", None, [])) c.value = "blah" @@ -1511,17 +1511,17 @@ c.disabled = True self.assertEqual(c.value, "blah") - self.assert_(str(c) == "") + self.assertTrue(str(c) == "") def set_value(value, c=c): c.value = value self.assertRaises(AttributeError, set_value, "blah") - self.assert_(c._click(form, (1,1), return_type="pairs") == []) + self.assertTrue(c._click(form, (1,1), return_type="pairs") == []) c.readonly = True - self.assert_(str(c) == "") self.assertRaises(AttributeError, set_value, "blah") - self.assert_(c._click(form, (1,1), return_type="pairs") == []) + self.assertTrue(c._click(form, (1,1), return_type="pairs") == []) c.disabled = c.readonly = False - self.assert_(c._click(form, (1,1), return_type="pairs") == + self.assertTrue(c._click(form, (1,1), return_type="pairs") == [("name_value.x", "1"), ("name_value.y", "1"), ('name_value', 'blah')]) @@ -1535,18 +1535,18 @@ c = _form.CheckboxControl("checkbox", "name_value", attrs) c.add_to_form(form) c.fixup() - self.assert_(c.type == "checkbox") - self.assert_(c.name == "name_value") - self.assert_(c.value == []) - hide_deprecations() - self.assert_(c.possible_items() == ["value_value"]) + self.assertTrue(c.type == "checkbox") + self.assertTrue(c.name == "name_value") + self.assertTrue(c.value == []) + hide_deprecations() + self.assertTrue(c.possible_items() == ["value_value"]) reset_deprecations() def set_type(c=c): c.type = "sometype" self.assertRaises(AttributeError, set_type) - self.assert_(c.type == "checkbox") + self.assertTrue(c.type == "checkbox") def set_name(c=c): c.name = "somename" self.assertRaises(AttributeError, set_name) - self.assert_(c.name == "name_value") + self.assertTrue(c.name == "name_value") # construct larger list from length-1 lists c = _form.CheckboxControl("checkbox", "name_value", attrs) @@ -1557,88 +1557,88 @@ c.merge_control(c2) c.add_to_form(form) c.fixup() - self.assert_(str(c) == "") hide_deprecations() - self.assert_(c.possible_items() == ["value_value", "value_value2"]) + self.assertTrue(c.possible_items() == ["value_value", "value_value2"]) attrs = c.get_item_attrs("value_value") for key in "alt", "name", "value", "type": - self.assert_(attrs.has_key(key)) + self.assertTrue(key in attrs) self.assertRaises(ItemNotFoundError, c.get_item_attrs, "oops") reset_deprecations() def set_value(value, c=c): c.value = value c.value = ["value_value", "value_value2"] - self.assert_(c.value == ["value_value", "value_value2"]) + self.assertTrue(c.value == ["value_value", "value_value2"]) c.value = ["value_value"] self.assertEqual(c.value, ["value_value"]) self.assertRaises(ItemNotFoundError, set_value, ["oops"]) self.assertRaises(TypeError, set_value, "value_value") c.value = ["value_value2"] - self.assert_(c.value == ["value_value2"]) + self.assertTrue(c.value == ["value_value2"]) hide_deprecations() c.toggle("value_value") - self.assert_(c.value == ["value_value", "value_value2"]) + self.assertTrue(c.value == ["value_value", "value_value2"]) c.toggle("value_value2") reset_deprecations() - self.assert_(c.value == ["value_value"]) + self.assertTrue(c.value == ["value_value"]) hide_deprecations() self.assertRaises(ItemNotFoundError, c.toggle, "oops") reset_deprecations() - self.assert_(c.value == ["value_value"]) + self.assertTrue(c.value == ["value_value"]) c.readonly = True self.assertRaises(AttributeError, c.clear) c.readonly = False c.clear() - self.assert_(c.value == []) + self.assertTrue(c.value == []) # set hide_deprecations() c.set(True, "value_value") - self.assert_(c.value == ["value_value"]) + self.assertTrue(c.value == ["value_value"]) c.set(True, "value_value2") - self.assert_(c.value == ["value_value", "value_value2"]) + self.assertTrue(c.value == ["value_value", "value_value2"]) c.set(True, "value_value2") - self.assert_(c.value == ["value_value", "value_value2"]) + self.assertTrue(c.value == ["value_value", "value_value2"]) c.set(False, "value_value2") - self.assert_(c.value == ["value_value"]) + self.assertTrue(c.value == ["value_value"]) c.set(False, "value_value2") - self.assert_(c.value == ["value_value"]) + self.assertTrue(c.value == ["value_value"]) self.assertRaises(ItemNotFoundError, c.set, True, "oops") self.assertRaises(TypeError, c.set, True, ["value_value"]) self.assertRaises(ItemNotFoundError, c.set, False, "oops") self.assertRaises(TypeError, c.set, False, ["value_value"]) reset_deprecations() - self.assert_(str(c) == "") c.disabled = True self.assertRaises(AttributeError, set_value, ["value_value"]) - self.assert_(str(c) == "") - self.assert_(c.value == ["value_value"]) - self.assert_(c.pairs() == []) + self.assertTrue(c.value == ["value_value"]) + self.assertTrue(c.pairs() == []) c.readonly = True self.assertRaises(AttributeError, set_value, ["value_value"]) - self.assert_(str(c) == "") - self.assert_(c.value == ["value_value"]) - self.assert_(c.pairs() == []) + self.assertTrue(c.value == ["value_value"]) + self.assertTrue(c.pairs() == []) c.disabled = False - self.assert_(str(c) == "") self.assertRaises(AttributeError, set_value, ["value_value"]) - self.assert_(c.value == ["value_value"]) - self.assert_(c.pairs() == [("name_value", "value_value")]) + self.assertTrue(c.value == ["value_value"]) + self.assertTrue(c.pairs() == [("name_value", "value_value")]) c.readonly = False c.value = [] - self.assert_(c.value == []) + self.assertTrue(c.value == []) def testSelectControlMultiple(self): attrs = {"type": "this is ignored", @@ -1656,20 +1656,20 @@ c = _form.SelectControl("select", "select_name", attrs) c.add_to_form(form) c.fixup() - self.assert_(c.type == "select") - self.assert_(c.name == "select_name") - self.assert_(c.value == []) - hide_deprecations() - self.assert_(c.possible_items() == ["value_value"]) - reset_deprecations() - self.assert_(c.attrs.has_key("name")) - self.assert_(c.attrs.has_key("type")) - self.assert_(c.attrs["alt"] == "alt_text") + self.assertTrue(c.type == "select") + self.assertTrue(c.name == "select_name") + self.assertTrue(c.value == []) + hide_deprecations() + self.assertTrue(c.possible_items() == ["value_value"]) + reset_deprecations() + self.assertTrue("name" in c.attrs) + self.assertTrue("type" in c.attrs) + self.assertTrue(c.attrs["alt"] == "alt_text") # ... and with RFC 1866 default selection c = _form.SelectControl("select", "select_name", attrs, select_default=True) c.add_to_form(form) c.fixup() - self.assert_(c.value == ["value_value"]) + self.assertTrue(c.value == ["value_value"]) # construct larger list from length-1 lists c = _form.SelectControl("select", "select_name", attrs) @@ -1680,28 +1680,28 @@ c.merge_control(c2) c.add_to_form(form) c.fixup() - self.assert_(str(c) == "") hide_deprecations() - self.assert_(c.possible_items() == ["value_value", "value_value2"]) + self.assertTrue(c.possible_items() == ["value_value", "value_value2"]) # get_item_attrs attrs3 = c.get_item_attrs("value_value") reset_deprecations() - self.assert_(attrs3.has_key("alt")) - self.assert_(not attrs3.has_key("multiple")) + self.assertTrue("alt" in attrs3) + self.assertTrue("multiple" not in attrs3) # HTML attributes dictionary should have been copied by ListControl # constructor. attrs["new_attr"] = "new" attrs2["new_attr2"] = "new2" for key in ("new_attr", "new_attr2"): - self.assert_(not attrs3.has_key(key)) + self.assertTrue(key not in attrs3) hide_deprecations() self.assertRaises(ItemNotFoundError, c.get_item_attrs, "oops") reset_deprecations() c.value = ["value_value", "value_value2"] - self.assert_(c.value == ["value_value", "value_value2"]) + self.assertTrue(c.value == ["value_value", "value_value2"]) c.value = ["value_value"] self.assertEqual(c.value, ["value_value"]) def set_value(value, c=c): c.value = value @@ -1709,42 +1709,42 @@ self.assertRaises(TypeError, set_value, "value_value") self.assertRaises(TypeError, set_value, None) c.value = ["value_value2"] - self.assert_(c.value == ["value_value2"]) + self.assertTrue(c.value == ["value_value2"]) hide_deprecations() c.toggle("value_value") - self.assert_(c.value == ["value_value", "value_value2"]) + self.assertTrue(c.value == ["value_value", "value_value2"]) c.toggle("value_value2") - self.assert_(c.value == ["value_value"]) + self.assertTrue(c.value == ["value_value"]) self.assertRaises(ItemNotFoundError, c.toggle, "oops") - self.assert_(c.value == ["value_value"]) + self.assertTrue(c.value == ["value_value"]) reset_deprecations() c.readonly = True self.assertRaises(AttributeError, c.clear) c.readonly = False c.clear() - self.assert_(c.value == []) + self.assertTrue(c.value == []) # test ordering of items c.value = ["value_value2", "value_value"] - self.assert_(c.value == ["value_value", "value_value2"]) + self.assertTrue(c.value == ["value_value", "value_value2"]) # set hide_deprecations() c.set(True, "value_value") - self.assert_(c.value == ["value_value", "value_value2"]) + self.assertTrue(c.value == ["value_value", "value_value2"]) c.set(True, "value_value2") - self.assert_(c.value == ["value_value", "value_value2"]) + self.assertTrue(c.value == ["value_value", "value_value2"]) c.set(False, "value_value") - self.assert_(c.value == ["value_value2"]) + self.assertTrue(c.value == ["value_value2"]) c.set(False, "value_value") - self.assert_(c.value == ["value_value2"]) + self.assertTrue(c.value == ["value_value2"]) self.assertRaises(ItemNotFoundError, c.set, True, "oops") self.assertRaises(TypeError, c.set, True, ["value_value"]) self.assertRaises(ItemNotFoundError, c.set, False, "oops") self.assertRaises(TypeError, c.set, False, ["value_value"]) reset_deprecations() c.value = [] - self.assert_(c.value == []) + self.assertTrue(c.value == []) def testSelectControlMultiple_label(self): ##