Skip to content

Commit c2a5d56

Browse files
committed
test: use f-strings in interface_*.py tests
1 parent 86d9582 commit c2a5d56

File tree

5 files changed

+54
-54
lines changed

5 files changed

+54
-54
lines changed

test/functional/interface_bitcoin_cli.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -87,12 +87,12 @@ def run_test(self):
8787
user, password = get_auth_cookie(self.nodes[0].datadir, self.chain)
8888

8989
self.log.info("Test -stdinrpcpass option")
90-
assert_equal(BLOCKS, self.nodes[0].cli('-rpcuser={}'.format(user), '-stdinrpcpass', input=password).getblockcount())
91-
assert_raises_process_error(1, 'Incorrect rpcuser or rpcpassword', self.nodes[0].cli('-rpcuser={}'.format(user), '-stdinrpcpass', input='foo').echo)
90+
assert_equal(BLOCKS, self.nodes[0].cli(f'-rpcuser={user}', '-stdinrpcpass', input=password).getblockcount())
91+
assert_raises_process_error(1, 'Incorrect rpcuser or rpcpassword', self.nodes[0].cli(f'-rpcuser={user}', '-stdinrpcpass', input='foo').echo)
9292

9393
self.log.info("Test -stdin and -stdinrpcpass")
94-
assert_equal(['foo', 'bar'], self.nodes[0].cli('-rpcuser={}'.format(user), '-stdin', '-stdinrpcpass', input=password + '\nfoo\nbar').echo())
95-
assert_raises_process_error(1, 'Incorrect rpcuser or rpcpassword', self.nodes[0].cli('-rpcuser={}'.format(user), '-stdin', '-stdinrpcpass', input='foo').echo)
94+
assert_equal(['foo', 'bar'], self.nodes[0].cli(f'-rpcuser={user}', '-stdin', '-stdinrpcpass', input=f'{password}\nfoo\nbar').echo())
95+
assert_raises_process_error(1, 'Incorrect rpcuser or rpcpassword', self.nodes[0].cli(f'-rpcuser={user}', '-stdin', '-stdinrpcpass', input='foo').echo)
9696

9797
self.log.info("Test connecting to a non-existing server")
9898
assert_raises_process_error(1, "Could not connect to the server", self.nodes[0].cli('-rpcport=1').echo)
@@ -150,8 +150,8 @@ def run_test(self):
150150
w1 = self.nodes[0].get_wallet_rpc(wallets[0])
151151
w2 = self.nodes[0].get_wallet_rpc(wallets[1])
152152
w3 = self.nodes[0].get_wallet_rpc(wallets[2])
153-
rpcwallet2 = '-rpcwallet={}'.format(wallets[1])
154-
rpcwallet3 = '-rpcwallet={}'.format(wallets[2])
153+
rpcwallet2 = f'-rpcwallet={wallets[1]}'
154+
rpcwallet3 = f'-rpcwallet={wallets[2]}'
155155
w1.walletpassphrase(password, self.rpc_timeout)
156156
w2.encryptwallet(password)
157157
w1.sendtoaddress(w2.getnewaddress(), amounts[1])
@@ -162,7 +162,7 @@ def run_test(self):
162162

163163
self.log.info("Test -getinfo with multiple wallets and -rpcwallet returns specified wallet balance")
164164
for i in range(len(wallets)):
165-
cli_get_info_string = self.nodes[0].cli('-getinfo', '-rpcwallet={}'.format(wallets[i])).send_cli()
165+
cli_get_info_string = self.nodes[0].cli('-getinfo', f'-rpcwallet={wallets[i]}').send_cli()
166166
cli_get_info = cli_get_info_string_to_dict(cli_get_info_string)
167167
assert 'Balances' not in cli_get_info_string
168168
assert_equal(cli_get_info["Wallet"], wallets[i])
@@ -296,7 +296,7 @@ def run_test(self):
296296
self.log.info("Test -version with node stopped")
297297
self.stop_node(0)
298298
cli_response = self.nodes[0].cli('-version').send_cli()
299-
assert "{} RPC client version".format(self.config['environment']['PACKAGE_NAME']) in cli_response
299+
assert f"{self.config['environment']['PACKAGE_NAME']} RPC client version" in cli_response
300300

301301
self.log.info("Test -rpcwait option successfully waits for RPC connection")
302302
self.nodes[0].start() # start node without RPC connection

test/functional/interface_http.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,8 @@ def run_test(self):
2424
# lowlevel check for http persistent connection #
2525
#################################################
2626
url = urllib.parse.urlparse(self.nodes[0].url)
27-
authpair = url.username + ':' + url.password
28-
headers = {"Authorization": "Basic " + str_to_b64str(authpair)}
27+
authpair = f'{url.username}:{url.password}'
28+
headers = {"Authorization": f"Basic {str_to_b64str(authpair)}"}
2929

3030
conn = http.client.HTTPConnection(url.hostname, url.port)
3131
conn.connect()
@@ -42,7 +42,7 @@ def run_test(self):
4242
conn.close()
4343

4444
#same should be if we add keep-alive because this should be the std. behaviour
45-
headers = {"Authorization": "Basic " + str_to_b64str(authpair), "Connection": "keep-alive"}
45+
headers = {"Authorization": f"Basic {str_to_b64str(authpair)}", "Connection": "keep-alive"}
4646

4747
conn = http.client.HTTPConnection(url.hostname, url.port)
4848
conn.connect()
@@ -59,7 +59,7 @@ def run_test(self):
5959
conn.close()
6060

6161
#now do the same with "Connection: close"
62-
headers = {"Authorization": "Basic " + str_to_b64str(authpair), "Connection":"close"}
62+
headers = {"Authorization": f"Basic {str_to_b64str(authpair)}", "Connection":"close"}
6363

6464
conn = http.client.HTTPConnection(url.hostname, url.port)
6565
conn.connect()
@@ -70,8 +70,8 @@ def run_test(self):
7070

7171
#node1 (2nd node) is running with disabled keep-alive option
7272
urlNode1 = urllib.parse.urlparse(self.nodes[1].url)
73-
authpair = urlNode1.username + ':' + urlNode1.password
74-
headers = {"Authorization": "Basic " + str_to_b64str(authpair)}
73+
authpair = f'{urlNode1.username}:{urlNode1.password}'
74+
headers = {"Authorization": f"Basic {str_to_b64str(authpair)}"}
7575

7676
conn = http.client.HTTPConnection(urlNode1.hostname, urlNode1.port)
7777
conn.connect()
@@ -81,8 +81,8 @@ def run_test(self):
8181

8282
#node2 (third node) is running with standard keep-alive parameters which means keep-alive is on
8383
urlNode2 = urllib.parse.urlparse(self.nodes[2].url)
84-
authpair = urlNode2.username + ':' + urlNode2.password
85-
headers = {"Authorization": "Basic " + str_to_b64str(authpair)}
84+
authpair = f'{urlNode2.username}:{urlNode2.password}'
85+
headers = {"Authorization": f"Basic {str_to_b64str(authpair)}"}
8686

8787
conn = http.client.HTTPConnection(urlNode2.hostname, urlNode2.port)
8888
conn.connect()
@@ -94,13 +94,13 @@ def run_test(self):
9494
# Check excessive request size
9595
conn = http.client.HTTPConnection(urlNode2.hostname, urlNode2.port)
9696
conn.connect()
97-
conn.request('GET', '/' + ('x'*1000), '', headers)
97+
conn.request('GET', f'/{"x"*1000}', '', headers)
9898
out1 = conn.getresponse()
9999
assert_equal(out1.status, http.client.NOT_FOUND)
100100

101101
conn = http.client.HTTPConnection(urlNode2.hostname, urlNode2.port)
102102
conn.connect()
103-
conn.request('GET', '/' + ('x'*10000), '', headers)
103+
conn.request('GET', f'/{"x"*10000}', '', headers)
104104
out1 = conn.getresponse()
105105
assert_equal(out1.status, http.client.BAD_REQUEST)
106106

test/functional/interface_rest.py

Lines changed: 31 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ def test_rest_request(self, uri, http_method='GET', req_type=ReqType.JSON, body=
5757
rest_uri += '.hex'
5858

5959
conn = http.client.HTTPConnection(self.url.hostname, self.url.port)
60-
self.log.debug('%s %s %s', http_method, rest_uri, body)
60+
self.log.debug(f'{http_method} {rest_uri} {body}')
6161
if http_method == 'GET':
6262
conn.request('GET', rest_uri)
6363
elif http_method == 'POST':
@@ -92,11 +92,11 @@ def run_test(self):
9292

9393
self.log.info("Test the /tx URI")
9494

95-
json_obj = self.test_rest_request("/tx/{}".format(txid))
95+
json_obj = self.test_rest_request(f"/tx/{txid}")
9696
assert_equal(json_obj['txid'], txid)
9797

9898
# Check hex format response
99-
hex_response = self.test_rest_request("/tx/{}".format(txid), req_type=ReqType.HEX, ret_type=RetType.OBJ)
99+
hex_response = self.test_rest_request(f"/tx/{txid}", req_type=ReqType.HEX, ret_type=RetType.OBJ)
100100
assert_greater_than_or_equal(int(hex_response.getheader('content-length')),
101101
json_obj['size']*2)
102102

@@ -114,7 +114,7 @@ def run_test(self):
114114
assert_equal(self.nodes[1].getbalance(), Decimal("0.1"))
115115

116116
# Check chainTip response
117-
json_obj = self.test_rest_request("/getutxos/{}-{}".format(*spending))
117+
json_obj = self.test_rest_request(f"/getutxos/{spending[0]}-{spending[1]}")
118118
assert_equal(json_obj['chaintipHash'], bb_hash)
119119

120120
# Make sure there is one utxo
@@ -123,7 +123,7 @@ def run_test(self):
123123

124124
self.log.info("Query a spent TXO using the /getutxos URI")
125125

126-
json_obj = self.test_rest_request("/getutxos/{}-{}".format(*spent))
126+
json_obj = self.test_rest_request(f"/getutxos/{spent[0]}-{spent[1]}")
127127

128128
# Check chainTip response
129129
assert_equal(json_obj['chaintipHash'], bb_hash)
@@ -136,7 +136,7 @@ def run_test(self):
136136

137137
self.log.info("Query two TXOs using the /getutxos URI")
138138

139-
json_obj = self.test_rest_request("/getutxos/{}-{}/{}-{}".format(*(spending + spent)))
139+
json_obj = self.test_rest_request(f"/getutxos/{spending[0]}-{spending[1]}/{spent[0]}-{spent[1]}")
140140

141141
assert_equal(len(json_obj['utxos']), 1)
142142
assert_equal(json_obj['bitmap'], "10")
@@ -163,32 +163,32 @@ def run_test(self):
163163

164164
# do a tx and don't sync
165165
txid = self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.1)
166-
json_obj = self.test_rest_request("/tx/{}".format(txid))
166+
json_obj = self.test_rest_request(f"/tx/{txid}")
167167
# get the spent output to later check for utxo (should be spent by then)
168168
spent = (json_obj['vin'][0]['txid'], json_obj['vin'][0]['vout'])
169169
# get n of 0.1 outpoint
170170
n, = filter_output_indices_by_value(json_obj['vout'], Decimal('0.1'))
171171
spending = (txid, n)
172172

173-
json_obj = self.test_rest_request("/getutxos/{}-{}".format(*spending))
173+
json_obj = self.test_rest_request(f"/getutxos/{spending[0]}-{spending[1]}")
174174
assert_equal(len(json_obj['utxos']), 0)
175175

176-
json_obj = self.test_rest_request("/getutxos/checkmempool/{}-{}".format(*spending))
176+
json_obj = self.test_rest_request(f"/getutxos/checkmempool/{spending[0]}-{spending[1]}")
177177
assert_equal(len(json_obj['utxos']), 1)
178178

179-
json_obj = self.test_rest_request("/getutxos/{}-{}".format(*spent))
179+
json_obj = self.test_rest_request(f"/getutxos/{spent[0]}-{spent[1]}")
180180
assert_equal(len(json_obj['utxos']), 1)
181181

182-
json_obj = self.test_rest_request("/getutxos/checkmempool/{}-{}".format(*spent))
182+
json_obj = self.test_rest_request(f"/getutxos/checkmempool/{spent[0]}-{spent[1]}")
183183
assert_equal(len(json_obj['utxos']), 0)
184184

185185
self.nodes[0].generate(1)
186186
self.sync_all()
187187

188-
json_obj = self.test_rest_request("/getutxos/{}-{}".format(*spending))
188+
json_obj = self.test_rest_request(f"/getutxos/{spending[0]}-{spending[1]}")
189189
assert_equal(len(json_obj['utxos']), 1)
190190

191-
json_obj = self.test_rest_request("/getutxos/checkmempool/{}-{}".format(*spending))
191+
json_obj = self.test_rest_request(f"/getutxos/checkmempool/{spending[0]}-{spending[1]}")
192192
assert_equal(len(json_obj['utxos']), 1)
193193

194194
# Do some invalid requests
@@ -197,11 +197,11 @@ def run_test(self):
197197
self.test_rest_request("/getutxos/checkmempool", http_method='POST', req_type=ReqType.JSON, status=400, ret_type=RetType.OBJ)
198198

199199
# Test limits
200-
long_uri = '/'.join(["{}-{}".format(txid, n_) for n_ in range(20)])
201-
self.test_rest_request("/getutxos/checkmempool/{}".format(long_uri), http_method='POST', status=400, ret_type=RetType.OBJ)
200+
long_uri = '/'.join([f"{txid}-{n_}" for n_ in range(20)])
201+
self.test_rest_request(f"/getutxos/checkmempool/{long_uri}", http_method='POST', status=400, ret_type=RetType.OBJ)
202202

203-
long_uri = '/'.join(['{}-{}'.format(txid, n_) for n_ in range(15)])
204-
self.test_rest_request("/getutxos/checkmempool/{}".format(long_uri), http_method='POST', status=200)
203+
long_uri = '/'.join([f'{txid}-{n_}' for n_ in range(15)])
204+
self.test_rest_request(f"/getutxos/checkmempool/{long_uri}", http_method='POST', status=200)
205205

206206
self.nodes[0].generate(1) # generate block to not affect upcoming tests
207207
self.sync_all()
@@ -215,42 +215,42 @@ def run_test(self):
215215

216216
# Check result if block is not in the active chain
217217
self.nodes[0].invalidateblock(bb_hash)
218-
assert_equal(self.test_rest_request('/headers/1/{}'.format(bb_hash)), [])
219-
self.test_rest_request('/block/{}'.format(bb_hash))
218+
assert_equal(self.test_rest_request(f'/headers/1/{bb_hash}'), [])
219+
self.test_rest_request(f'/block/{bb_hash}')
220220
self.nodes[0].reconsiderblock(bb_hash)
221221

222222
# Check binary format
223-
response = self.test_rest_request("/block/{}".format(bb_hash), req_type=ReqType.BIN, ret_type=RetType.OBJ)
223+
response = self.test_rest_request(f"/block/{bb_hash}", req_type=ReqType.BIN, ret_type=RetType.OBJ)
224224
assert_greater_than(int(response.getheader('content-length')), BLOCK_HEADER_SIZE)
225225
response_bytes = response.read()
226226

227227
# Compare with block header
228-
response_header = self.test_rest_request("/headers/1/{}".format(bb_hash), req_type=ReqType.BIN, ret_type=RetType.OBJ)
228+
response_header = self.test_rest_request(f"/headers/1/{bb_hash}", req_type=ReqType.BIN, ret_type=RetType.OBJ)
229229
assert_equal(int(response_header.getheader('content-length')), BLOCK_HEADER_SIZE)
230230
response_header_bytes = response_header.read()
231231
assert_equal(response_bytes[:BLOCK_HEADER_SIZE], response_header_bytes)
232232

233233
# Check block hex format
234-
response_hex = self.test_rest_request("/block/{}".format(bb_hash), req_type=ReqType.HEX, ret_type=RetType.OBJ)
234+
response_hex = self.test_rest_request(f"/block/{bb_hash}", req_type=ReqType.HEX, ret_type=RetType.OBJ)
235235
assert_greater_than(int(response_hex.getheader('content-length')), BLOCK_HEADER_SIZE*2)
236236
response_hex_bytes = response_hex.read().strip(b'\n')
237237
assert_equal(response_bytes.hex().encode(), response_hex_bytes)
238238

239239
# Compare with hex block header
240-
response_header_hex = self.test_rest_request("/headers/1/{}".format(bb_hash), req_type=ReqType.HEX, ret_type=RetType.OBJ)
240+
response_header_hex = self.test_rest_request(f"/headers/1/{bb_hash}", req_type=ReqType.HEX, ret_type=RetType.OBJ)
241241
assert_greater_than(int(response_header_hex.getheader('content-length')), BLOCK_HEADER_SIZE*2)
242242
response_header_hex_bytes = response_header_hex.read(BLOCK_HEADER_SIZE*2)
243243
assert_equal(response_bytes[:BLOCK_HEADER_SIZE].hex().encode(), response_header_hex_bytes)
244244

245245
# Check json format
246-
block_json_obj = self.test_rest_request("/block/{}".format(bb_hash))
246+
block_json_obj = self.test_rest_request(f"/block/{bb_hash}")
247247
assert_equal(block_json_obj['hash'], bb_hash)
248-
assert_equal(self.test_rest_request("/blockhashbyheight/{}".format(block_json_obj['height']))['blockhash'], bb_hash)
248+
assert_equal(self.test_rest_request(f"/blockhashbyheight/{block_json_obj['height']}")['blockhash'], bb_hash)
249249

250250
# Check hex/bin format
251-
resp_hex = self.test_rest_request("/blockhashbyheight/{}".format(block_json_obj['height']), req_type=ReqType.HEX, ret_type=RetType.OBJ)
251+
resp_hex = self.test_rest_request(f"/blockhashbyheight/{block_json_obj['height']}", req_type=ReqType.HEX, ret_type=RetType.OBJ)
252252
assert_equal(resp_hex.read().decode('utf-8').rstrip(), bb_hash)
253-
resp_bytes = self.test_rest_request("/blockhashbyheight/{}".format(block_json_obj['height']), req_type=ReqType.BIN, ret_type=RetType.BYTES)
253+
resp_bytes = self.test_rest_request(f"/blockhashbyheight/{block_json_obj['height']}", req_type=ReqType.BIN, ret_type=RetType.BYTES)
254254
blockhash = resp_bytes[::-1].hex()
255255
assert_equal(blockhash, bb_hash)
256256

@@ -264,7 +264,7 @@ def run_test(self):
264264
self.test_rest_request("/blockhashbyheight/", ret_type=RetType.OBJ, status=400)
265265

266266
# Compare with json block header
267-
json_obj = self.test_rest_request("/headers/1/{}".format(bb_hash))
267+
json_obj = self.test_rest_request(f"/headers/1/{bb_hash}")
268268
assert_equal(len(json_obj), 1) # ensure that there is one header in the json response
269269
assert_equal(json_obj[0]['hash'], bb_hash) # request/response hash should be the same
270270

@@ -276,7 +276,7 @@ def run_test(self):
276276
# See if we can get 5 headers in one response
277277
self.nodes[1].generate(5)
278278
self.sync_all()
279-
json_obj = self.test_rest_request("/headers/5/{}".format(bb_hash))
279+
json_obj = self.test_rest_request(f"/headers/5/{bb_hash}")
280280
assert_equal(len(json_obj), 5) # now we should have 5 header objects
281281

282282
self.log.info("Test tx inclusion in the /mempool and /block URIs")
@@ -306,13 +306,13 @@ def run_test(self):
306306
self.sync_all()
307307

308308
# Check if the 3 tx show up in the new block
309-
json_obj = self.test_rest_request("/block/{}".format(newblockhash[0]))
309+
json_obj = self.test_rest_request(f"/block/{newblockhash[0]}")
310310
non_coinbase_txs = {tx['txid'] for tx in json_obj['tx']
311311
if 'coinbase' not in tx['vin'][0]}
312312
assert_equal(non_coinbase_txs, set(txs))
313313

314314
# Check the same but without tx details
315-
json_obj = self.test_rest_request("/block/notxdetails/{}".format(newblockhash[0]))
315+
json_obj = self.test_rest_request(f"/block/notxdetails/{newblockhash[0]}")
316316
for tx in txs:
317317
assert tx in json_obj['tx']
318318

test/functional/interface_rpc.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ def expect_http_status(expected_http_status, expected_rpc_code,
1616
fcn, *args):
1717
try:
1818
fcn(*args)
19-
raise AssertionError("Expected RPC error %d, got none" % expected_rpc_code)
19+
raise AssertionError(f"Expected RPC error {expected_rpc_code}, got none")
2020
except JSONRPCException as exc:
2121
assert_equal(exc.error["code"], expected_rpc_code)
2222
assert_equal(exc.http_status, expected_http_status)

test/functional/interface_zmq.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ def setup_zmq_test(self, services, *, recv_timeout=60, sync_blocks=True):
132132
socket = self.ctx.socket(zmq.SUB)
133133
subscribers.append(ZMQSubscriber(socket, topic.encode()))
134134

135-
self.restart_node(0, ["-zmqpub%s=%s" % (topic, address) for topic, address in services] +
135+
self.restart_node(0, [f"-zmqpub{topic}={address}" for topic, address in services] +
136136
self.extra_args[0])
137137

138138
for i, sub in enumerate(subscribers):
@@ -184,7 +184,7 @@ def test_basic(self):
184184
rawtx = subs[3]
185185

186186
num_blocks = 5
187-
self.log.info("Generate %(n)d blocks (and %(n)d coinbase txes)" % {"n": num_blocks})
187+
self.log.info(f"Generate {num_blocks} blocks (and {num_blocks} coinbase txes)")
188188
genhashes = self.nodes[0].generatetoaddress(num_blocks, ADDRESS_BCRT1_UNSPENDABLE)
189189

190190
self.sync_all()
@@ -504,7 +504,7 @@ def test_mempool_sync(self):
504504
if mempool_sequence is not None:
505505
zmq_mem_seq = mempool_sequence
506506
if zmq_mem_seq > get_raw_seq:
507-
raise Exception("We somehow jumped mempool sequence numbers! zmq_mem_seq: {} > get_raw_seq: {}".format(zmq_mem_seq, get_raw_seq))
507+
raise Exception(f"We somehow jumped mempool sequence numbers! zmq_mem_seq: {zmq_mem_seq} > get_raw_seq: {get_raw_seq}")
508508

509509
# 4) Moving forward, we apply the delta to our local view
510510
# remaining txs(5) + 1 rbf(A+R) + 1 block connect + 1 final tx
@@ -520,7 +520,7 @@ def test_mempool_sync(self):
520520
assert mempool_sequence > expected_sequence
521521
r_gap += mempool_sequence - expected_sequence
522522
else:
523-
raise Exception("WARNING: txhash has unexpected mempool sequence value: {} vs expected {}".format(mempool_sequence, expected_sequence))
523+
raise Exception(f"WARNING: txhash has unexpected mempool sequence value: {mempool_sequence} vs expected {expected_sequence}")
524524
if label == "A":
525525
assert hash_str not in mempool_view
526526
mempool_view.add(hash_str)

0 commit comments

Comments
 (0)