86>Nov 17 12:22:22 userdel[37166]: delete user 'rooter'
<86>Nov 17 12:22:22 userdel[37166]: removed group 'rooter' owned by 'rooter'
<86>Nov 17 12:22:22 groupadd[37171]: group added to /etc/group: name=rooter, GID=645
<86>Nov 17 12:22:22 groupadd[37171]: group added to /etc/gshadow: name=rooter
<86>Nov 17 12:22:22 groupadd[37171]: new group: name=rooter, GID=645
<86>Nov 17 12:22:22 useradd[37176]: new user: name=rooter, UID=645, GID=645, home=/root, shell=/bin/bash
<86>Nov 17 12:22:22 userdel[37183]: delete user 'builder'
<86>Nov 17 12:22:22 userdel[37183]: removed group 'builder' owned by 'builder'
<86>Nov 17 12:22:22 userdel[37183]: removed shadow group 'builder' owned by 'builder'
<86>Nov 17 12:22:22 groupadd[37188]: group added to /etc/group: name=builder, GID=646
<86>Nov 17 12:22:22 groupadd[37188]: group added to /etc/gshadow: name=builder
<86>Nov 17 12:22:22 groupadd[37188]: new group: name=builder, GID=646
<86>Nov 17 12:22:22 useradd[37192]: new user: name=builder, UID=646, GID=646, home=/usr/src, shell=/bin/bash
<13>Nov 17 12:22:24 rpmi: libgdbm-1.8.3-alt10 1454943334 installed
<13>Nov 17 12:22:24 rpmi: libexpat-2.2.4-alt1 1503305345 installed
<13>Nov 17 12:22:24 rpmi: libp11-kit-0.23.15-alt1 sisyphus+226408.100.2.1 1554288204 installed
<13>Nov 17 12:22:24 rpmi: libtasn1-4.14-alt1 p9+235792.100.2.1 1565425233 installed
<13>Nov 17 12:22:24 rpmi: rpm-macros-alternatives-0.5.1-alt1 sisyphus+226946.100.1.1 1554830426 installed
<13>Nov 17 12:22:25 rpmi: alternatives-0.5.1-alt1 sisyphus+226946.100.1.1 1554830426 installed
<13>Nov 17 12:22:25 rpmi: ca-certificates-2019.10.28-alt1 p9+240634.100.1.1 1573575926 installed
<13>Nov 17 12:22:25 rpmi: ca-trust-0.1.2-alt1 p9+233349.100.1.1 1561655062 installed
<13>Nov 17 12:22:25 rpmi: p11-kit-trust-0.23.15-alt1 sisyphus+226408.100.2.1 1554288204 installed
<13>Nov 17 12:22:25 rpmi: libcrypto1.1-1.1.1d-alt1.1 p9+237853.200.3.1 1569251834 installed
<13>Nov 17 12:22:25 rpmi: libssl1.1-1.1.1d-alt1.1 p9+237853.200.3.1 1569251834 installed
<13>Nov 17 12:22:25 rpmi: python3-3.7.4-alt2 p9+239459.100.1.1 1571444790 installed
<13>Nov 17 12:22:25 rpmi: libpython3-3.7.4-alt2 p9+239459.100.1.1 1571444790 installed
<13>Nov 17 12:22:26 rpmi: python3-base-3.7.4-alt2 p9+239459.100.1.1 1571444790 installed
<13>Nov 17 12:22:26 rpmi: tests-for-installed-python3-pkgs-0.1.13.1-alt2 1535450458 installed
<13>Nov 17 12:22:26 rpmi: rpm-build-python3-0.1.13.1-alt2 1535450458 installed
<13>Nov 17 12:22:32 rpmi: python3-module-pkg_resources-1:40.8.0-alt2 sisyphus+229158.200.2.1 1557735221 installed
<13>Nov 17 12:22:32 rpmi: python-modules-curses-2.7.16-alt1 sisyphus+226365.200.2.1 1554143304 installed
<13>Nov 17 12:22:32 rpmi: libtinfo-devel-6.1.20180407-alt2 sisyphus+222164.200.1.1 1550686226 installed
<13>Nov 17 12:22:32 rpmi: libncurses-devel-6.1.20180407-alt2 sisyphus+222164.200.1.1 1550686226 installed
<13>Nov 17 12:22:32 rpmi: python3-dev-3.7.4-alt2 p9+239459.100.1.1 1571444790 installed
<13>Nov 17 12:22:32 rpmi: libverto-0.3.0-alt1_7 sisyphus+225932.100.1.1 1553994919 installed
<13>Nov 17 12:22:32 rpmi: libkeyutils-1.6-alt2 sisyphus+226520.100.2.1 1554512089 installed
<13>Nov 17 12:22:32 rpmi: libcom_err-1.44.6-alt1 sisyphus+224154.100.1.1 1552091678 installed
<86>Nov 17 12:22:32 groupadd[58801]: group added to /etc/group: name=_keytab, GID=499
<86>Nov 17 12:22:32 groupadd[58801]: group added to /etc/gshadow: name=_keytab
<86>Nov 17 12:22:32 groupadd[58801]: new group: name=_keytab, GID=499
<13>Nov 17 12:22:32 rpmi: libkrb5-1.16.3-alt1 sisyphus+223678.100.1.1 1551746516 installed
<13>Nov 17 12:22:32 rpmi: libtirpc-1.0.3-alt1 1532008017 installed
<13>Nov 17 12:22:32 rpmi: libnsl2-1.1.0-alt1_1 1511548749 installed
<13>Nov 17 12:22:32 rpmi: python-modules-compiler-2.7.16-alt1 sisyphus+226365.200.2.1 1554143304 installed
<13>Nov 17 12:22:32 rpmi: python-modules-email-2.7.16-alt1 sisyphus+226365.200.2.1 1554143304 installed
<13>Nov 17 12:22:32 rpmi: python-modules-unittest-2.7.16-alt1 sisyphus+226365.200.2.1 1554143304 installed
<13>Nov 17 12:22:32 rpmi: python-modules-encodings-2.7.16-alt1 sisyphus+226365.200.2.1 1554143304 installed
<13>Nov 17 12:22:32 rpmi: python-modules-2.7.16-alt1 sisyphus+226365.200.2.1 1554143304 installed
<13>Nov 17 12:22:32 rpmi: python-modules-nis-2.7.16-alt1 sisyphus+226365.200.2.1 1554143304 installed
<13>Nov 17 12:22:32 rpmi: python-modules-ctypes-2.7.16-alt1 sisyphus+226365.200.2.1 1554143304 installed
<13>Nov 17 12:22:32 rpmi: python-modules-multiprocessing-2.7.16-alt1 sisyphus+226365.200.2.1 1554143304 installed
<13>Nov 17 12:22:32 rpmi: python-modules-logging-2.7.16-alt1 sisyphus+226365.200.2.1 1554143304 installed
<13>Nov 17 12:22:32 rpmi: python-tools-2to3-2.7.16-alt1 sisyphus+226365.200.2.1 1554143304 installed
<13>Nov 17 12:22:32 rpmi: python-modules-xml-2.7.16-alt1 sisyphus+226365.200.2.1 1554143304 installed
<13>Nov 17 12:22:32 rpmi: python-modules-hotshot-2.7.16-alt1 sisyphus+226365.200.2.1 1554143304 installed
<13>Nov 17 12:22:32 rpmi: python-modules-bsddb-2.7.16-alt1 sisyphus+226365.200.2.1 1554143304 installed
<13>Nov 17 12:22:32 rpmi: python-2.7.16-alt1 sisyphus+226365.200.2.1 1554143304 installed
<13>Nov 17 12:22:32 rpmi: python-modules-distutils-2.7.16-alt1 sisyphus+226365.200.2.1 1554143304 installed
<13>Nov 17 12:22:32 rpmi: python-module-pkg_resources-1:40.8.0-alt2 sisyphus+229158.200.2.1 1557735221 installed
<13>Nov 17 12:22:32 rpmi: libnsl2-devel-1.1.0-alt1_1 1511548749 installed
<13>Nov 17 12:22:32 rpmi: python-dev-2.7.16-alt1 sisyphus+226365.200.2.1 1554143304 installed
<13>Nov 17 12:22:32 rpmi: python-module-setuptools-1:40.8.0-alt2 sisyphus+229158.200.2.1 1557735221 installed
<13>Nov 17 12:22:33 rpmi: python3-module-setuptools-1:40.8.0-alt2 sisyphus+229158.200.2.1 1557735221 installed
Building target platforms: i586
Building for target i586
Wrote: /usr/src/in/nosrpm/python-module-mechanize-0.2.5-alt1.1.1.2.nosrc.rpm
Installing python-module-mechanize-0.2.5-alt1.1.1.2.src.rpm
Building target platforms: i586
Building for target i586
Executing(%prep): /bin/sh -e /usr/src/tmp/rpm-tmp.85656
+ 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.85656
+ umask 022
+ /bin/mkdir -p /usr/src/RPM/BUILD
+ cd /usr/src/RPM/BUILD
+ cd mechanize-0.2.5
+ CFLAGS='-pipe -frecord-gcc-switches -Wall -g -O2 -march=i586 -mtune=generic'
+ export CFLAGS
+ CXXFLAGS='-pipe -frecord-gcc-switches -Wall -g -O2 -march=i586 -mtune=generic'
+ export CXXFLAGS
+ FFLAGS='-pipe -frecord-gcc-switches -Wall -g -O2 -march=i586 -mtune=generic'
+ 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("""