Skip to content

Commit fa41b0a

Browse files
author
MarcoFalke
committed
pep-8 test/functional/test_framework/util.py
Can be reviewed with --word-diff-regex=. -U0
1 parent faa841b commit fa41b0a

File tree

1 file changed

+48
-10
lines changed
  • test/functional/test_framework

1 file changed

+48
-10
lines changed

test/functional/test_framework/util.py

Lines changed: 48 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,15 @@
2525
# Assert functions
2626
##################
2727

28+
2829
def assert_approx(v, vexp, vspan=0.00001):
2930
"""Assert that `v` is within `vspan` of `vexp`"""
3031
if v < vexp - vspan:
3132
raise AssertionError("%s < [%s..%s]" % (str(v), str(vexp - vspan), str(vexp + vspan)))
3233
if v > vexp + vspan:
3334
raise AssertionError("%s > [%s..%s]" % (str(v), str(vexp - vspan), str(vexp + vspan)))
3435

36+
3537
def assert_fee_amount(fee, tx_size, fee_per_kB):
3638
"""Assert the fee was in range"""
3739
target_fee = round(tx_size * fee_per_kB / 1000, 8)
@@ -41,21 +43,26 @@ def assert_fee_amount(fee, tx_size, fee_per_kB):
4143
if fee > (tx_size + 2) * fee_per_kB / 1000:
4244
raise AssertionError("Fee of %s BTC too high! (Should be %s BTC)" % (str(fee), str(target_fee)))
4345

46+
4447
def assert_equal(thing1, thing2, *args):
4548
if thing1 != thing2 or any(thing1 != arg for arg in args):
4649
raise AssertionError("not(%s)" % " == ".join(str(arg) for arg in (thing1, thing2) + args))
4750

51+
4852
def assert_greater_than(thing1, thing2):
4953
if thing1 <= thing2:
5054
raise AssertionError("%s <= %s" % (str(thing1), str(thing2)))
5155

56+
5257
def assert_greater_than_or_equal(thing1, thing2):
5358
if thing1 < thing2:
5459
raise AssertionError("%s < %s" % (str(thing1), str(thing2)))
5560

61+
5662
def assert_raises(exc, fun, *args, **kwds):
5763
assert_raises_message(exc, None, fun, *args, **kwds)
5864

65+
5966
def assert_raises_message(exc, message, fun, *args, **kwds):
6067
try:
6168
fun(*args, **kwds)
@@ -71,6 +78,7 @@ def assert_raises_message(exc, message, fun, *args, **kwds):
7178
else:
7279
raise AssertionError("No exception raised")
7380

81+
7482
def assert_raises_process_error(returncode, output, fun, *args, **kwds):
7583
"""Execute a process and asserts the process return code and output.
7684
@@ -95,6 +103,7 @@ def assert_raises_process_error(returncode, output, fun, *args, **kwds):
95103
else:
96104
raise AssertionError("No exception raised")
97105

106+
98107
def assert_raises_rpc_error(code, message, fun, *args, **kwds):
99108
"""Run an RPC and verify that a specific JSONRPC exception code and message is raised.
100109
@@ -113,6 +122,7 @@ def assert_raises_rpc_error(code, message, fun, *args, **kwds):
113122
"""
114123
assert try_rpc(code, message, fun, *args, **kwds), "No exception raised"
115124

125+
116126
def try_rpc(code, message, fun, *args, **kwds):
117127
"""Tries to run an rpc command.
118128
@@ -134,22 +144,22 @@ def try_rpc(code, message, fun, *args, **kwds):
134144
else:
135145
return False
136146

147+
137148
def assert_is_hex_string(string):
138149
try:
139150
int(string, 16)
140151
except Exception as e:
141-
raise AssertionError(
142-
"Couldn't interpret %r as hexadecimal; raised: %s" % (string, e))
152+
raise AssertionError("Couldn't interpret %r as hexadecimal; raised: %s" % (string, e))
153+
143154

144155
def assert_is_hash_string(string, length=64):
145156
if not isinstance(string, str):
146157
raise AssertionError("Expected a string, got type %r" % type(string))
147158
elif length and len(string) != length:
148-
raise AssertionError(
149-
"String of length %d expected; got %d" % (length, len(string)))
159+
raise AssertionError("String of length %d expected; got %d" % (length, len(string)))
150160
elif not re.match('[abcdef0-9]+$', string):
151-
raise AssertionError(
152-
"String %r contains invalid characters for a hash." % string)
161+
raise AssertionError("String %r contains invalid characters for a hash." % string)
162+
153163

154164
def assert_array_result(object_array, to_match, expected, should_not_find=False):
155165
"""
@@ -180,34 +190,41 @@ def assert_array_result(object_array, to_match, expected, should_not_find=False)
180190
if num_matched > 0 and should_not_find:
181191
raise AssertionError("Objects were found %s" % (str(to_match)))
182192

193+
183194
# Utility functions
184195
###################
185196

197+
186198
def check_json_precision():
187199
"""Make sure json library being used does not lose precision converting BTC values"""
188200
n = Decimal("20000000.00000003")
189201
satoshis = int(json.loads(json.dumps(float(n))) * 1.0e8)
190202
if satoshis != 2000000000000003:
191203
raise RuntimeError("JSON encode/decode loses precision")
192204

205+
193206
def EncodeDecimal(o):
194207
if isinstance(o, Decimal):
195208
return str(o)
196209
raise TypeError(repr(o) + " is not JSON serializable")
197210

211+
198212
def count_bytes(hex_string):
199213
return len(bytearray.fromhex(hex_string))
200214

201215

202216
def hex_str_to_bytes(hex_str):
203217
return unhexlify(hex_str.encode('ascii'))
204218

219+
205220
def str_to_b64str(string):
206221
return b64encode(string.encode('utf-8')).decode('ascii')
207222

223+
208224
def satoshi_round(amount):
209225
return Decimal(amount).quantize(Decimal('0.00000001'), rounding=ROUND_DOWN)
210226

227+
211228
def wait_until(predicate, *, attempts=float('inf'), timeout=float('inf'), lock=None, timeout_factor=1.0):
212229
if attempts == float('inf') and timeout == float('inf'):
213230
timeout = 60
@@ -235,6 +252,7 @@ def wait_until(predicate, *, attempts=float('inf'), timeout=float('inf'), lock=N
235252
raise AssertionError("Predicate {} not true after {} seconds".format(predicate_source, timeout))
236253
raise RuntimeError('Unreachable')
237254

255+
238256
# RPC/P2P connection constants and functions
239257
############################################
240258

@@ -250,6 +268,7 @@ class PortSeed:
250268
# Must be initialized with a unique integer for each process
251269
n = None
252270

271+
253272
def get_rpc_proxy(url, node_number, *, timeout=None, coveragedir=None):
254273
"""
255274
Args:
@@ -271,18 +290,20 @@ def get_rpc_proxy(url, node_number, *, timeout=None, coveragedir=None):
271290
proxy = AuthServiceProxy(url, **proxy_kwargs)
272291
proxy.url = url # store URL on proxy for info
273292

274-
coverage_logfile = coverage.get_filename(
275-
coveragedir, node_number) if coveragedir else None
293+
coverage_logfile = coverage.get_filename(coveragedir, node_number) if coveragedir else None
276294

277295
return coverage.AuthServiceProxyWrapper(proxy, coverage_logfile)
278296

297+
279298
def p2p_port(n):
280299
assert n <= MAX_NODES
281300
return PORT_MIN + n + (MAX_NODES * PortSeed.n) % (PORT_RANGE - 1 - MAX_NODES)
282301

302+
283303
def rpc_port(n):
284304
return PORT_MIN + PORT_RANGE + n + (MAX_NODES * PortSeed.n) % (PORT_RANGE - 1 - MAX_NODES)
285305

306+
286307
def rpc_url(datadir, i, chain, rpchost):
287308
rpc_u, rpc_p = get_auth_cookie(datadir, chain)
288309
host = '127.0.0.1'
@@ -295,9 +316,11 @@ def rpc_url(datadir, i, chain, rpchost):
295316
host = rpchost
296317
return "http://%s:%s@%s:%d" % (rpc_u, rpc_p, host, int(port))
297318

319+
298320
# Node functions
299321
################
300322

323+
301324
def initialize_datadir(dirname, n, chain):
302325
datadir = get_datadir_path(dirname, n)
303326
if not os.path.isdir(datadir):
@@ -331,11 +354,13 @@ def initialize_datadir(dirname, n, chain):
331354
def get_datadir_path(dirname, n):
332355
return os.path.join(dirname, "node" + str(n))
333356

357+
334358
def append_config(datadir, options):
335359
with open(os.path.join(datadir, "bitcoin.conf"), 'a', encoding='utf8') as f:
336360
for option in options:
337361
f.write(option + "\n")
338362

363+
339364
def get_auth_cookie(datadir, chain):
340365
user = None
341366
password = None
@@ -360,20 +385,24 @@ def get_auth_cookie(datadir, chain):
360385
raise ValueError("No RPC credentials")
361386
return user, password
362387

388+
363389
# If a cookie file exists in the given datadir, delete it.
364390
def delete_cookie_file(datadir, chain):
365391
if os.path.isfile(os.path.join(datadir, chain, ".cookie")):
366392
logger.debug("Deleting leftover cookie file")
367393
os.remove(os.path.join(datadir, chain, ".cookie"))
368394

395+
369396
def softfork_active(node, key):
370397
"""Return whether a softfork is active."""
371398
return node.getblockchaininfo()['softforks'][key]['active']
372399

400+
373401
def set_node_times(nodes, t):
374402
for node in nodes:
375403
node.setmocktime(t)
376404

405+
377406
def disconnect_nodes(from_connection, node_num):
378407
def get_peer_ids():
379408
result = []
@@ -386,7 +415,7 @@ def get_peer_ids():
386415
if not peer_ids:
387416
logger.warning("disconnect_nodes: {} and {} were not connected".format(
388417
from_connection.index,
389-
node_num
418+
node_num,
390419
))
391420
return
392421
for peer_id in peer_ids:
@@ -396,12 +425,13 @@ def get_peer_ids():
396425
# If this node is disconnected between calculating the peer id
397426
# and issuing the disconnect, don't worry about it.
398427
# This avoids a race condition if we're mass-disconnecting peers.
399-
if e.error['code'] != -29: # RPC_CLIENT_NODE_NOT_CONNECTED
428+
if e.error['code'] != -29: # RPC_CLIENT_NODE_NOT_CONNECTED
400429
raise
401430

402431
# wait to disconnect
403432
wait_until(lambda: not get_peer_ids(), timeout=5)
404433

434+
405435
def connect_nodes(from_connection, node_num):
406436
ip_port = "127.0.0.1:" + str(p2p_port(node_num))
407437
from_connection.addnode(ip_port, "onetry")
@@ -473,6 +503,7 @@ def find_output(node, txid, amount, *, blockhash=None):
473503
return i
474504
raise RuntimeError("find_output txid %s : %s not found" % (txid, str(amount)))
475505

506+
476507
def gather_inputs(from_node, amount_needed, confirmations_required=1):
477508
"""
478509
Return a random set of unspent txouts that are enough to pay amount_needed
@@ -490,6 +521,7 @@ def gather_inputs(from_node, amount_needed, confirmations_required=1):
490521
raise RuntimeError("Insufficient funds: need %d, have %d" % (amount_needed, total_in))
491522
return (total_in, inputs)
492523

524+
493525
def make_change(from_node, amount_in, amount_out, fee):
494526
"""
495527
Create change output(s), return them
@@ -507,6 +539,7 @@ def make_change(from_node, amount_in, amount_out, fee):
507539
outputs[from_node.getnewaddress()] = change
508540
return outputs
509541

542+
510543
def random_transaction(nodes, amount, min_fee, fee_increment, fee_variants):
511544
"""
512545
Create a random transaction.
@@ -526,6 +559,7 @@ def random_transaction(nodes, amount, min_fee, fee_increment, fee_variants):
526559

527560
return (txid, signresult["hex"], fee)
528561

562+
529563
# Helper to create at least "count" utxos
530564
# Pass in a fee that is sufficient for relay and mining new transactions.
531565
def create_confirmed_utxos(fee, node, count):
@@ -558,6 +592,7 @@ def create_confirmed_utxos(fee, node, count):
558592
assert len(utxos) >= count
559593
return utxos
560594

595+
561596
# Create large OP_RETURN txouts that can be appended to a transaction
562597
# to make it large (helper for constructing large transactions).
563598
def gen_return_txouts():
@@ -577,6 +612,7 @@ def gen_return_txouts():
577612
txouts.append(txout)
578613
return txouts
579614

615+
580616
# Create a spend of each passed-in utxo, splicing in "txouts" to each raw
581617
# transaction to make it large. See gen_return_txouts() above.
582618
def create_lots_of_big_transactions(node, txouts, utxos, num, fee):
@@ -600,6 +636,7 @@ def create_lots_of_big_transactions(node, txouts, utxos, num, fee):
600636
txids.append(txid)
601637
return txids
602638

639+
603640
def mine_large_block(node, utxos=None):
604641
# generate a 66k transaction,
605642
# and 14 of them is close to the 1MB block limit
@@ -613,6 +650,7 @@ def mine_large_block(node, utxos=None):
613650
create_lots_of_big_transactions(node, txouts, utxos, num, fee=fee)
614651
node.generate(1)
615652

653+
616654
def find_vout_for_address(node, txid, addr):
617655
"""
618656
Locate the vout index of the given transaction sending to the

0 commit comments

Comments
 (0)