Skip to content

Commit 14b860b

Browse files
author
MarcoFalke
committed
Merge #11513: [trivial] [tests] A few Python3 tidy ups
f893085 [tests] Don't subclass from object for Python 3 (John Newbery) 8f9e362 [tests] authproxy.py: tidy up __init__() (John Newbery) 323d8f6 [tests] fix flake8 warnings in authproxy.py (John Newbery) fc0176d [tests] use python3 for authproxy.py (John Newbery) Pull request description: A few trivial tidyups in the test_framework: - the test_framework can only be run in Python3, so remove the py2/3 compatibility workarounds in authproxy.py - while there, do some general tidying up of the module - fix flake8 warnings, make initialization code more compact - All classes in Python3 are new-style. No need to explicitly inherit from `object`. Tree-SHA512: d15c93aa4b47c1ad7d05baa7a564053cf0294932e178c95ef335380113f42e1af314978d07d3b107292a8e3496fd840535b5571a9164182feaa062a1e9ff8b73
2 parents 2c66cea + f893085 commit 14b860b

File tree

12 files changed

+79
-98
lines changed

12 files changed

+79
-98
lines changed

test/functional/p2p-fullblocktest.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
from test_framework.script import *
2121
import struct
2222

23-
class PreviousSpendableOutput(object):
23+
class PreviousSpendableOutput():
2424
def __init__(self, tx = CTransaction(), n = -1):
2525
self.tx = tx
2626
self.n = n # the output we're spending

test/functional/p2p-segwit.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ def test_witness_block(self, block, accepted, with_witness=True):
8989
assert_equal(self.connection.rpc.getbestblockhash() == block.hash, accepted)
9090

9191
# Used to keep track of anyone-can-spend outputs that we can use in the tests
92-
class UTXO(object):
92+
class UTXO():
9393
def __init__(self, sha256, n, nValue):
9494
self.sha256 = sha256
9595
self.n = n

test/functional/test_framework/authproxy.py

Lines changed: 20 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -33,24 +33,17 @@
3333
- uses standard Python json lib
3434
"""
3535

36-
try:
37-
import http.client as httplib
38-
except ImportError:
39-
import httplib
4036
import base64
4137
import decimal
38+
import http.client
4239
import json
4340
import logging
4441
import socket
4542
import time
46-
try:
47-
import urllib.parse as urlparse
48-
except ImportError:
49-
import urlparse
50-
51-
USER_AGENT = "AuthServiceProxy/0.1"
43+
import urllib.parse
5244

5345
HTTP_TIMEOUT = 30
46+
USER_AGENT = "AuthServiceProxy/0.1"
5447

5548
log = logging.getLogger("BitcoinRPC")
5649

@@ -60,7 +53,7 @@ def __init__(self, rpc_error):
6053
errmsg = '%(message)s (%(code)i)' % rpc_error
6154
except (KeyError, TypeError):
6255
errmsg = ''
63-
Exception.__init__(self, errmsg)
56+
super().__init__(errmsg)
6457
self.error = rpc_error
6558

6659

@@ -69,40 +62,28 @@ def EncodeDecimal(o):
6962
return str(o)
7063
raise TypeError(repr(o) + " is not JSON serializable")
7164

72-
class AuthServiceProxy(object):
65+
class AuthServiceProxy():
7366
__id_count = 0
7467

7568
# ensure_ascii: escape unicode as \uXXXX, passed to json.dumps
7669
def __init__(self, service_url, service_name=None, timeout=HTTP_TIMEOUT, connection=None, ensure_ascii=True):
7770
self.__service_url = service_url
7871
self._service_name = service_name
79-
self.ensure_ascii = ensure_ascii # can be toggled on the fly by tests
80-
self.__url = urlparse.urlparse(service_url)
81-
if self.__url.port is None:
82-
port = 80
83-
else:
84-
port = self.__url.port
85-
(user, passwd) = (self.__url.username, self.__url.password)
86-
try:
87-
user = user.encode('utf8')
88-
except AttributeError:
89-
pass
90-
try:
91-
passwd = passwd.encode('utf8')
92-
except AttributeError:
93-
pass
72+
self.ensure_ascii = ensure_ascii # can be toggled on the fly by tests
73+
self.__url = urllib.parse.urlparse(service_url)
74+
port = 80 if self.__url.port is None else self.__url.port
75+
user = None if self.__url.username is None else self.__url.username.encode('utf8')
76+
passwd = None if self.__url.password is None else self.__url.password.encode('utf8')
9477
authpair = user + b':' + passwd
9578
self.__auth_header = b'Basic ' + base64.b64encode(authpair)
9679

9780
if connection:
9881
# Callables re-use the connection of the original proxy
9982
self.__conn = connection
10083
elif self.__url.scheme == 'https':
101-
self.__conn = httplib.HTTPSConnection(self.__url.hostname, port,
102-
timeout=timeout)
84+
self.__conn = http.client.HTTPSConnection(self.__url.hostname, port, timeout=timeout)
10385
else:
104-
self.__conn = httplib.HTTPConnection(self.__url.hostname, port,
105-
timeout=timeout)
86+
self.__conn = http.client.HTTPConnection(self.__url.hostname, port, timeout=timeout)
10687

10788
def __getattr__(self, name):
10889
if name.startswith('__') and name.endswith('__'):
@@ -124,14 +105,14 @@ def _request(self, method, path, postdata):
124105
try:
125106
self.__conn.request(method, path, postdata, headers)
126107
return self._get_response()
127-
except httplib.BadStatusLine as e:
128-
if e.line == "''": # if connection was closed, try again
108+
except http.client.BadStatusLine as e:
109+
if e.line == "''": # if connection was closed, try again
129110
self.__conn.close()
130111
self.__conn.request(method, path, postdata, headers)
131112
return self._get_response()
132113
else:
133114
raise
134-
except (BrokenPipeError,ConnectionResetError):
115+
except (BrokenPipeError, ConnectionResetError):
135116
# Python 3.5+ raises BrokenPipeError instead of BadStatusLine when the connection was reset
136117
# ConnectionResetError happens on FreeBSD with Python 3.4
137118
self.__conn.close()
@@ -141,8 +122,8 @@ def _request(self, method, path, postdata):
141122
def get_request(self, *args, **argsn):
142123
AuthServiceProxy.__id_count += 1
143124

144-
log.debug("-%s-> %s %s"%(AuthServiceProxy.__id_count, self._service_name,
145-
json.dumps(args, default=EncodeDecimal, ensure_ascii=self.ensure_ascii)))
125+
log.debug("-%s-> %s %s" % (AuthServiceProxy.__id_count, self._service_name,
126+
json.dumps(args, default=EncodeDecimal, ensure_ascii=self.ensure_ascii)))
146127
if args and argsn:
147128
raise ValueError('Cannot handle both named and positional arguments')
148129
return {'version': '1.1',
@@ -163,7 +144,7 @@ def __call__(self, *args, **argsn):
163144

164145
def batch(self, rpc_call_list):
165146
postdata = json.dumps(list(rpc_call_list), default=EncodeDecimal, ensure_ascii=self.ensure_ascii)
166-
log.debug("--> "+postdata)
147+
log.debug("--> " + postdata)
167148
return self._request('POST', self.__url.path, postdata.encode('utf-8'))
168149

169150
def _get_response(self):
@@ -190,9 +171,9 @@ def _get_response(self):
190171
response = json.loads(responsedata, parse_float=decimal.Decimal)
191172
elapsed = time.time() - req_start_time
192173
if "error" in response and response["error"] is None:
193-
log.debug("<-%s- [%.6f] %s"%(response["id"], elapsed, json.dumps(response["result"], default=EncodeDecimal, ensure_ascii=self.ensure_ascii)))
174+
log.debug("<-%s- [%.6f] %s" % (response["id"], elapsed, json.dumps(response["result"], default=EncodeDecimal, ensure_ascii=self.ensure_ascii)))
194175
else:
195-
log.debug("<-- [%.6f] %s"%(elapsed,responsedata))
176+
log.debug("<-- [%.6f] %s" % (elapsed, responsedata))
196177
return response
197178

198179
def __truediv__(self, relative_uri):

test/functional/test_framework/blockstore.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
logger = logging.getLogger("TestFramework.blockstore")
1212

13-
class BlockStore(object):
13+
class BlockStore():
1414
"""BlockStore helper class.
1515
1616
BlockStore keeps a map of blocks and implements helper functions for
@@ -127,7 +127,7 @@ def get_locator(self, current_tip=None):
127127
locator.vHave = r
128128
return locator
129129

130-
class TxStore(object):
130+
class TxStore():
131131
def __init__(self, datadir):
132132
self.txDB = dbmd.open(datadir + "/transactions", 'c')
133133

test/functional/test_framework/comptool.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727

2828
global mininode_lock
2929

30-
class RejectResult(object):
30+
class RejectResult():
3131
"""Outcome that expects rejection of a transaction or block."""
3232
def __init__(self, code, reason=b''):
3333
self.code = code
@@ -156,13 +156,13 @@ def send_mempool(self):
156156
# across all connections. (If outcome of final tx is specified as true
157157
# or false, then only the last tx is tested against outcome.)
158158

159-
class TestInstance(object):
159+
class TestInstance():
160160
def __init__(self, objects=None, sync_every_block=True, sync_every_tx=False):
161161
self.blocks_and_transactions = objects if objects else []
162162
self.sync_every_block = sync_every_block
163163
self.sync_every_tx = sync_every_tx
164164

165-
class TestManager(object):
165+
class TestManager():
166166

167167
def __init__(self, testgen, datadir):
168168
self.test_generator = testgen

test/functional/test_framework/coverage.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
REFERENCE_FILENAME = 'rpc_interface.txt'
1515

1616

17-
class AuthServiceProxyWrapper(object):
17+
class AuthServiceProxyWrapper():
1818
"""
1919
An object that wraps AuthServiceProxy to record specific RPC calls.
2020

test/functional/test_framework/key.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ def _check_result(val, func, args):
8484
ssl.EC_KEY_new_by_curve_name.restype = ctypes.c_void_p
8585
ssl.EC_KEY_new_by_curve_name.errcheck = _check_result
8686

87-
class CECKey(object):
87+
class CECKey():
8888
"""Wrapper around OpenSSL's EC_KEY"""
8989

9090
POINT_CONVERSION_COMPRESSED = 2

0 commit comments

Comments
 (0)