diff --git a/test/functional/test_framework/authproxy.py b/test/functional/test_framework/authproxy.py --- a/test/functional/test_framework/authproxy.py +++ b/test/functional/test_framework/authproxy.py @@ -51,7 +51,7 @@ class JSONRPCException(Exception): def __init__(self, rpc_error): try: - errmsg = '%(message)s (%(code)i)' % rpc_error + errmsg = '{} ({})'.format(rpc_error['message'], rpc_error['code']) except (KeyError, TypeError): errmsg = '' super().__init__(errmsg) @@ -96,7 +96,7 @@ # Python internal stuff raise AttributeError if self._service_name is not None: - name = "%s.%s" % (self._service_name, name) + name = "{}.{}".format(self._service_name, name) return AuthServiceProxy(self.__service_url, name, connection=self.__conn) def _request(self, method, path, postdata): @@ -128,8 +128,9 @@ def get_request(self, *args, **argsn): AuthServiceProxy.__id_count += 1 - log.debug("-%s-> %s %s" % (AuthServiceProxy.__id_count, self._service_name, - json.dumps(args, default=EncodeDecimal, ensure_ascii=self.ensure_ascii))) + log.debug("-{}-> {} {}".format( + AuthServiceProxy.__id_count, self._service_name, json.dumps( + args, default=EncodeDecimal, ensure_ascii=self.ensure_ascii))) if args and argsn: raise ValueError( 'Cannot handle both named and positional arguments') @@ -164,10 +165,10 @@ except socket.timeout as e: raise JSONRPCException({ 'code': -344, - 'message': '%r RPC took longer than %f seconds. Consider ' + 'message': '{!r} RPC took longer than {} seconds. Consider ' 'using larger timeout for calls that take ' - 'longer to return.' % (self._service_name, - self.__conn.timeout)}) + 'longer to return.'.format((self._service_name, + self.__conn.timeout))}) if http_response is None: raise JSONRPCException({ 'code': -342, 'message': 'missing HTTP response from server'}) @@ -175,16 +176,17 @@ content_type = http_response.getheader('Content-Type') if content_type != 'application/json': raise JSONRPCException({ - 'code': -342, 'message': 'non-JSON HTTP response with \'%i %s\' from server' % (http_response.status, http_response.reason)}) + 'code': -342, 'message': 'non-JSON HTTP response with \'{} {}\' from server'.format( + http_response.status, http_response.reason)}) responsedata = http_response.read().decode('utf8') response = json.loads(responsedata, parse_float=decimal.Decimal) elapsed = time.time() - req_start_time if "error" in response and response["error"] is None: - log.debug("<-%s- [%.6f] %s" % (response["id"], elapsed, json.dumps( + log.debug("<-{}- [{:.6f}] {}".format(response["id"], elapsed, json.dumps( response["result"], default=EncodeDecimal, ensure_ascii=self.ensure_ascii))) else: - log.debug("<-- [%.6f] %s" % (elapsed, responsedata)) + log.debug("<-- [{:.6f}] {}".format(elapsed, responsedata)) return response def __truediv__(self, relative_uri): diff --git a/test/functional/test_framework/cdefs.py b/test/functional/test_framework/cdefs.py --- a/test/functional/test_framework/cdefs.py +++ b/test/functional/test_framework/cdefs.py @@ -93,7 +93,7 @@ if __name__ == "__main__": # Output values if run standalone to verify - print("DEFAULT_MAX_BLOCK_SIZE = %d (bytes)" % DEFAULT_MAX_BLOCK_SIZE) - print("MAX_BLOCK_SIGOPS_PER_MB = %d (sigops)" % MAX_BLOCK_SIGOPS_PER_MB) - print("MAX_TX_SIGOPS_COUNT = %d (sigops)" % MAX_TX_SIGOPS_COUNT) - print("COINBASE_MATURITY = %d (blocks)" % COINBASE_MATURITY) + print("DEFAULT_MAX_BLOCK_SIZE = {} (bytes)".format(DEFAULT_MAX_BLOCK_SIZE)) + print("MAX_BLOCK_SIGOPS_PER_MB = {} (sigops)".format(MAX_BLOCK_SIGOPS_PER_MB)) + print("MAX_TX_SIGOPS_COUNT = {} (sigops)".format(MAX_TX_SIGOPS_COUNT)) + print("COINBASE_MATURITY = {} (blocks)".format(COINBASE_MATURITY)) diff --git a/test/functional/test_framework/comptool.py b/test/functional/test_framework/comptool.py --- a/test/functional/test_framework/comptool.py +++ b/test/functional/test_framework/comptool.py @@ -41,7 +41,7 @@ return other.reason.startswith(self.reason) def __repr__(self): - return '%i:%s' % (self.code, self.reason or '*') + return '{}:{}'.format(self.code, self.reason or '*') class TestNode(P2PInterface): @@ -97,7 +97,7 @@ del self.pingMap[message.nonce] except KeyError: raise AssertionError( - "Got pong for unknown ping [%s]" % repr(message)) + "Got pong for unknown ping [{}]".format(repr(message))) def on_reject(self, message): if message.message == b'tx': @@ -264,10 +264,10 @@ return False if blockhash not in c.block_reject_map: logger.error( - 'Block not in reject map: %064x' % (blockhash)) + 'Block not in reject map: {:064x}'.format(blockhash)) return False if not outcome.match(c.block_reject_map[blockhash]): - logger.error('Block rejected with %s instead of expected %s: %064x' % ( + logger.error('Block rejected with {} instead of expected {}: {:064x}'.format( c.block_reject_map[blockhash], outcome, blockhash)) return False elif ((c.bestblockhash == blockhash) != outcome): @@ -292,10 +292,11 @@ if txhash in c.lastInv: return False if txhash not in c.tx_reject_map: - logger.error('Tx not in reject map: %064x' % (txhash)) + logger.error( + 'Tx not in reject map: {:064x}'.format(txhash)) return False if not outcome.match(c.tx_reject_map[txhash]): - logger.error('Tx rejected with %s instead of expected %s: %064x' % ( + logger.error('Tx rejected with {} instead of expected {}: {:064x}'.format( c.tx_reject_map[txhash], outcome, txhash)) return False elif ((txhash in c.lastInv) != outcome): @@ -365,7 +366,7 @@ self.ping_counter += 1 if (not self.check_results(tip, outcome)): raise AssertionError( - "Test failed at test %d" % test_number) + "Test failed at test {}".format(test_number)) else: invqueue.append(CInv(2, block.sha256)) elif isinstance(b_or_t, CBlockHeader): @@ -388,7 +389,7 @@ self.sync_transaction(tx.sha256, 1) if (not self.check_mempool(tx.sha256, outcome)): raise AssertionError( - "Test failed at test %d" % test_number) + "Test failed at test {}".format(test_number)) else: invqueue.append(CInv(1, tx.sha256)) # Ensure we're not overflowing the inv queue @@ -407,7 +408,7 @@ test_instance.blocks_and_transactions)) if (not self.check_results(tip, block_outcome)): raise AssertionError( - "Block test failed at test %d" % test_number) + "Block test failed at test {}".format(test_number)) if (not test_instance.sync_every_tx and tx is not None): if len(invqueue) > 0: [c.send_message(msg_inv(invqueue)) @@ -417,9 +418,9 @@ test_instance.blocks_and_transactions)) if (not self.check_mempool(tx.sha256, tx_outcome)): raise AssertionError( - "Mempool test failed at test %d" % test_number) + "Mempool test failed at test {}".format(test_number)) - logger.info("Test %d: PASS" % test_number) + logger.info("Test {}: PASS".format(test_number)) test_number += 1 [c.disconnect_node() for c in self.p2p_connections] diff --git a/test/functional/test_framework/coverage.py b/test/functional/test_framework/coverage.py --- a/test/functional/test_framework/coverage.py +++ b/test/functional/test_framework/coverage.py @@ -54,7 +54,7 @@ if self.coverage_logfile: with open(self.coverage_logfile, 'a+', encoding='utf8') as f: - f.write("%s\n" % rpc_method) + f.write("{}\n".format(rpc_method)) def __truediv__(self, relative_uri): return AuthServiceProxyWrapper(self.auth_service_proxy_instance / relative_uri, @@ -73,7 +73,7 @@ """ pid = str(os.getpid()) return os.path.join( - dirname, "coverage.pid%s.node%s.txt" % (pid, str(n_node))) + dirname, "coverage.pid{}.node{}.txt".format(pid, str(n_node))) def write_all_rpc_commands(dirname, node): @@ -103,7 +103,7 @@ # Ignore blanks and headers if line and not line.startswith('='): - commands.add("%s\n" % line.split()[0]) + commands.add("{}\n".format(line.split()[0])) with open(filename, 'w', encoding='utf8') as f: f.writelines(list(commands)) diff --git a/test/functional/test_framework/key.py b/test/functional/test_framework/key.py --- a/test/functional/test_framework/key.py +++ b/test/functional/test_framework/key.py @@ -162,8 +162,8 @@ def sign(self, hash, low_s=True): # FIXME: need unit tests for below cases if not isinstance(hash, bytes): - raise TypeError('Hash must be bytes instance; got %r' % - hash.__class__) + raise TypeError( + 'Hash must be bytes instance; got {!r}'.format(hash.__class__)) if len(hash) != 32: raise ValueError('Hash must be exactly 32 bytes long') @@ -243,6 +243,6 @@ # Always have represent as b'' so test cases don't have to # change for py2/3 if sys.version > '3': - return '%s(%s)' % (self.__class__.__name__, super(CPubKey, self).__repr__()) + return '{}({})'.format(self.__class__.__name__, super(CPubKey, self).__repr__()) else: - return '%s(b%s)' % (self.__class__.__name__, super(CPubKey, self).__repr__()) + return '{}(b{})'.format(self.__class__.__name__, super(CPubKey, self).__repr__()) diff --git a/test/functional/test_framework/messages.py b/test/functional/test_framework/messages.py --- a/test/functional/test_framework/messages.py +++ b/test/functional/test_framework/messages.py @@ -240,8 +240,8 @@ return r def __repr__(self): - return "CAddress(nServices=%i ip=%s port=%i)" % (self.nServices, - self.ip, self.port) + return "CAddress(nServices={} ip={} port={})".format( + self.nServices, self.ip, self.port) class CInv(): @@ -267,8 +267,8 @@ return r def __repr__(self): - return "CInv(type=%s hash=%064x)" \ - % (self.typemap[self.type], self.hash) + return "CInv(type={} hash={:064x})".format( + self.typemap[self.type], self.hash) class CBlockLocator(): @@ -287,8 +287,8 @@ return r def __repr__(self): - return "CBlockLocator(nVersion=%i vHave=%s)" \ - % (self.nVersion, repr(self.vHave)) + return "CBlockLocator(nVersion={} vHave={})".format( + self.nVersion, repr(self.vHave)) class COutPoint(): @@ -307,7 +307,7 @@ return r def __repr__(self): - return "COutPoint(hash=%064x n=%i)" % (self.hash, self.n) + return "COutPoint(hash={:064x} n={})".format(self.hash, self.n) class CTxIn(): @@ -333,9 +333,8 @@ return r def __repr__(self): - return "CTxIn(prevout=%s scriptSig=%s nSequence=%i)" \ - % (repr(self.prevout), bytes_to_hex_str(self.scriptSig), - self.nSequence) + return "CTxIn(prevout={} scriptSig={} nSequence={})".format( + repr(self.prevout), bytes_to_hex_str(self.scriptSig), self.nSequence) class CTxOut(): @@ -354,9 +353,9 @@ return r def __repr__(self): - return "CTxOut(nValue=%i.%08i scriptPubKey=%s)" \ - % (self.nValue // COIN, self.nValue % COIN, - bytes_to_hex_str(self.scriptPubKey)) + return "CTxOut(nValue={}.{:08d} scriptPubKey={})".format( + self.nValue // COIN, self.nValue % COIN, + bytes_to_hex_str(self.scriptPubKey)) class CTransaction(): @@ -423,8 +422,8 @@ return True def __repr__(self): - return "CTransaction(nVersion=%i vin=%s vout=%s nLockTime=%i)" \ - % (self.nVersion, repr(self.vin), repr(self.vout), self.nLockTime) + return "CTransaction(nVersion={} vin={} vout={} nLockTime={})".format( + self.nVersion, repr(self.vin), repr(self.vout), self.nLockTime) class CBlockHeader(): @@ -490,9 +489,9 @@ return self.sha256 def __repr__(self): - return "CBlockHeader(nVersion=%i hashPrevBlock=%064x hashMerkleRoot=%064x nTime=%s nBits=%08x nNonce=%08x)" \ - % (self.nVersion, self.hashPrevBlock, self.hashMerkleRoot, - time.ctime(self.nTime), self.nBits, self.nNonce) + return "CBlockHeader(nVersion={} hashPrevBlock={:064x} hashMerkleRoot={:064x} nTime={} nBits={:08x} nNonce={:08x})".format( + self.nVersion, self.hashPrevBlock, self.hashMerkleRoot, + time.ctime(self.nTime), self.nBits, self.nNonce) class CBlock(CBlockHeader): @@ -547,9 +546,9 @@ self.rehash() def __repr__(self): - return "CBlock(nVersion=%i hashPrevBlock=%064x hashMerkleRoot=%064x nTime=%s nBits=%08x nNonce=%08x vtx=%s)" \ - % (self.nVersion, self.hashPrevBlock, self.hashMerkleRoot, - time.ctime(self.nTime), self.nBits, self.nNonce, repr(self.vtx)) + return "CBlock(nVersion={} hashPrevBlock={:064x} hashMerkleRoot={:064x} nTime={} nBits={:08x} nNonce={:08x} vtx={})".format( + self.nVersion, self.hashPrevBlock, self.hashMerkleRoot, + time.ctime(self.nTime), self.nBits, self.nNonce, repr(self.vtx)) class PrefilledTransaction(): @@ -569,7 +568,8 @@ return r def __repr__(self): - return "PrefilledTransaction(index=%d, tx=%s)" % (self.index, repr(self.tx)) + return "PrefilledTransaction(index={}, tx={})".format( + self.index, repr(self.tx)) # This is what we send on the wire, in a cmpctblock message. @@ -607,7 +607,10 @@ return r def __repr__(self): - return "P2PHeaderAndShortIDs(header=%s, nonce=%d, shortids_length=%d, shortids=%s, prefilled_txn_length=%d, prefilledtxn=%s" % (repr(self.header), self.nonce, self.shortids_length, repr(self.shortids), self.prefilled_txn_length, repr(self.prefilled_txn)) + return "P2PHeaderAndShortIDs(header={}, nonce={}, shortids_length={}, shortids={}, prefilled_txn_length={}, prefilledtxn={}".format( + repr(self.header), self.nonce, self.shortids_length, + repr(self.shortids), self.prefilled_txn_length, + repr(self.prefilled_txn)) # Calculate the BIP 152-compact blocks shortid for a given transaction hash @@ -675,7 +678,9 @@ self.shortids.append(calculate_shortid(k0, k1, tx_hash)) def __repr__(self): - return "HeaderAndShortIDs(header=%s, nonce=%d, shortids=%s, prefilledtxn=%s" % (repr(self.header), self.nonce, repr(self.shortids), repr(self.prefilled_txn)) + return "HeaderAndShortIDs(header={}, nonce={}, shortids={}, prefilledtxn={}".format( + repr(self.header), self.nonce, repr(self.shortids), + repr(self.prefilled_txn)) class BlockTransactionsRequest(): @@ -715,7 +720,8 @@ return absolute_indexes def __repr__(self): - return "BlockTransactionsRequest(hash=%064x indexes=%s)" % (self.blockhash, repr(self.indexes)) + return "BlockTransactionsRequest(hash={:064x} indexes={})".format( + self.blockhash, repr(self.indexes)) class BlockTransactions(): @@ -735,7 +741,8 @@ return r def __repr__(self): - return "BlockTransactions(hash=%064x transactions=%s)" % (self.blockhash, repr(self.transactions)) + return "BlockTransactions(hash={:064x} transactions={})".format( + self.blockhash, repr(self.transactions)) # Objects that correspond to messages on the wire @@ -801,10 +808,10 @@ return r def __repr__(self): - return 'msg_version(nVersion=%i nServices=%i nTime=%s addrTo=%s addrFrom=%s nNonce=0x%016X strSubVer=%s nStartingHeight=%i nRelay=%i)' \ - % (self.nVersion, self.nServices, time.ctime(self.nTime), - repr(self.addrTo), repr(self.addrFrom), self.nNonce, - self.strSubVer, self.nStartingHeight, self.nRelay) + return 'msg_version(nVersion={} nServices={} nTime={} addrTo={} addrFrom={} nNonce=0x{:016X} strSubVer={} nStartingHeight={} nRelay={})'.format( + self.nVersion, self.nServices, time.ctime(self.nTime), + repr(self.addrTo), repr(self.addrFrom), self.nNonce, + self.strSubVer, self.nStartingHeight, self.nRelay) class msg_verack(): @@ -836,7 +843,7 @@ return ser_vector(self.addrs) def __repr__(self): - return "msg_addr(addrs=%s)" % (repr(self.addrs)) + return "msg_addr(addrs={})".format(repr(self.addrs)) class msg_inv(): @@ -855,7 +862,7 @@ return ser_vector(self.inv) def __repr__(self): - return "msg_inv(inv=%s)" % (repr(self.inv)) + return "msg_inv(inv={})".format(repr(self.inv)) class msg_getdata(): @@ -871,7 +878,7 @@ return ser_vector(self.inv) def __repr__(self): - return "msg_getdata(inv=%s)" % (repr(self.inv)) + return "msg_getdata(inv={})".format(repr(self.inv)) class msg_getblocks(): @@ -893,8 +900,8 @@ return r def __repr__(self): - return "msg_getblocks(locator=%s hashstop=%064x)" \ - % (repr(self.locator), self.hashstop) + return "msg_getblocks(locator={} hashstop={:064x})".format( + repr(self.locator), self.hashstop) class msg_tx(): @@ -910,7 +917,7 @@ return self.tx.serialize() def __repr__(self): - return "msg_tx(tx=%s)" % (repr(self.tx)) + return "msg_tx(tx={})".format(repr(self.tx)) class msg_block(): @@ -929,7 +936,7 @@ return self.block.serialize() def __repr__(self): - return "msg_block(block=%s)" % (repr(self.block)) + return "msg_block(block={})".format(repr(self.block)) # for cases where a user needs tighter control over what is sent over the wire # note that the user must supply the name of the command, and the data @@ -978,7 +985,7 @@ return r def __repr__(self): - return "msg_ping(nonce=%08x)" % self.nonce + return "msg_ping(nonce={:08x})".format(self.nonce) class msg_pong(): @@ -996,7 +1003,7 @@ return r def __repr__(self): - return "msg_pong(nonce=%08x)" % self.nonce + return "msg_pong(nonce={:08x})".format(self.nonce) class msg_mempool(): @@ -1054,8 +1061,8 @@ return r def __repr__(self): - return "msg_getheaders(locator=%s, stop=%064x)" \ - % (repr(self.locator), self.hashstop) + return "msg_getheaders(locator={}, stop={:064x})".format( + repr(self.locator), self.hashstop) # headers message has @@ -1077,7 +1084,7 @@ return ser_vector(blocks) def __repr__(self): - return "msg_headers(headers=%s)" % repr(self.headers) + return "msg_headers(headers={})".format(repr(self.headers)) class msg_reject(): @@ -1108,8 +1115,8 @@ return r def __repr__(self): - return "msg_reject: %s %d %s [%064x]" \ - % (self.message, self.code, self.reason, self.data) + return "msg_reject: {} {} {} [{:064x}]".format( + self.message, self.code, self.reason, self.data) class msg_feefilter(): @@ -1127,7 +1134,7 @@ return r def __repr__(self): - return "msg_feefilter(feerate=%08x)" % self.feerate + return "msg_feefilter(feerate={:08x})".format(self.feerate) class msg_sendcmpct(): @@ -1148,7 +1155,8 @@ return r def __repr__(self): - return "msg_sendcmpct(announce=%s, version=%lu)" % (self.announce, self.version) + return "msg_sendcmpct(announce={}, version={})".format( + self.announce, self.version) class msg_cmpctblock(): @@ -1167,7 +1175,8 @@ return r def __repr__(self): - return "msg_cmpctblock(HeaderAndShortIDs=%s)" % repr(self.header_and_shortids) + return "msg_cmpctblock(HeaderAndShortIDs={})".format( + repr(self.header_and_shortids)) class msg_getblocktxn(): @@ -1186,7 +1195,8 @@ return r def __repr__(self): - return "msg_getblocktxn(block_txn_request=%s)" % (repr(self.block_txn_request)) + return "msg_getblocktxn(block_txn_request={})".format( + repr(self.block_txn_request)) class msg_blocktxn(): @@ -1204,4 +1214,5 @@ return r def __repr__(self): - return "msg_blocktxn(block_transactions=%s)" % (repr(self.block_transactions)) + return "msg_blocktxn(block_transactions={})".format( + repr(self.block_transactions)) diff --git a/test/functional/test_framework/mininode.py b/test/functional/test_framework/mininode.py --- a/test/functional/test_framework/mininode.py +++ b/test/functional/test_framework/mininode.py @@ -87,8 +87,8 @@ self.network = net self.disconnect = False - logger.info('Connecting to Bitcoin Node: %s:%d' % - (self.dstaddr, self.dstport)) + logger.info('Connecting to Bitcoin Node: {}:{}'.format( + self.dstaddr, self.dstport)) try: self.connect((dstaddr, dstport)) @@ -105,15 +105,15 @@ def handle_connect(self): """asyncore callback when a connection is opened.""" if self.state != "connected": - logger.debug("Connected & Listening: %s:%d" % - (self.dstaddr, self.dstport)) + logger.debug("Connected & Listening: {}:{}".format( + self.dstaddr, self.dstport)) self.state = "connected" self.on_open() def handle_close(self): """asyncore callback when a connection is closed.""" - logger.debug("Closing connection to: %s:%d" % - (self.dstaddr, self.dstport)) + logger.debug("Closing connection to: {}:{}".format( + self.dstaddr, self.dstport)) self.state = "closed" self.recvbuf = b"" self.sendbuf = b"" @@ -156,7 +156,8 @@ if len(self.recvbuf) < 4: return None if self.recvbuf[:4] != MAGIC_BYTES[self.network]: - raise ValueError("got garbage %s" % repr(self.recvbuf)) + raise ValueError( + "got garbage {}".format(repr(self.recvbuf))) if len(self.recvbuf) < 4 + 12 + 4 + 4: return command = self.recvbuf[4:4+12].split(b"\x00", 1)[0] @@ -170,7 +171,7 @@ raise ValueError("got bad checksum " + repr(self.recvbuf)) self.recvbuf = self.recvbuf[4+12+4+4+msglen:] if command not in MESSAGEMAP: - raise ValueError("Received unknown command from %s:%d: '%s' %s" % ( + raise ValueError("Received unknown command from {}:{}: '{}' {}".format( self.dstaddr, self.dstport, command, repr(msg))) f = BytesIO(msg) m = MESSAGEMAP[command]() @@ -261,8 +262,8 @@ log_message = "Send message to " elif direction == "receive": log_message = "Received message from " - log_message += "%s:%d: %s" % (self.dstaddr, - self.dstport, repr(msg)[:500]) + log_message += "{}:{}: {}".format( + self.dstaddr, self.dstport, repr(msg)[:500]) if len(log_message) > 500: log_message += "... (msg truncated)" logger.debug(log_message) @@ -319,8 +320,8 @@ self.last_message[command] = message getattr(self, 'on_' + command)(message) except: - print("ERROR delivering %s (%s)" % (repr(message), - sys.exc_info()[0])) + print("ERROR delivering {} ({})".format( + repr(message), sys.exc_info()[0])) raise # Callback methods. Can be overridden by subclasses in individual test diff --git a/test/functional/test_framework/netutil.py b/test/functional/test_framework/netutil.py --- a/test/functional/test_framework/netutil.py +++ b/test/functional/test_framework/netutil.py @@ -32,7 +32,7 @@ ''' Get list of socket inodes for process pid. ''' - base = '/proc/%i/fd' % pid + base = '/proc/{}/fd'.format(pid) inodes = [] for item in os.listdir(base): target = os.readlink(os.path.join(base, item)) @@ -52,7 +52,7 @@ host_out = '' for x in range(0, len(host) // 4): (val,) = struct.unpack('=I', host[x * 4:(x + 1) * 4]) - host_out += '%08x' % val + host_out += '{:08x}'.format(val) return host_out, int(port, 16) @@ -148,7 +148,7 @@ assert((x == 0 and nullbytes == 0) or (x == 1 and nullbytes > 0)) addr = sub[0] + ([0] * nullbytes) + sub[1] else: - raise ValueError('Could not parse address %s' % addr) + raise ValueError('Could not parse address {}'.format(addr)) return hexlify(bytearray(addr)).decode('ascii') diff --git a/test/functional/test_framework/script.py b/test/functional/test_framework/script.py --- a/test/functional/test_framework/script.py +++ b/test/functional/test_framework/script.py @@ -59,7 +59,7 @@ """Encode a small integer op, returning an opcode""" if not (0 <= n <= 16): raise ValueError( - 'Integer must be in range 0 <= n <= 16, got %d' % n) + 'Integer must be in range 0 <= n <= 16, got {}'.format(n)) if n == 0: return OP_0 @@ -72,7 +72,7 @@ return 0 if not (self == OP_0 or OP_1 <= self <= OP_16): - raise ValueError('op %r is not an OP_N' % self) + raise ValueError('op {!r} is not an OP_N'.format(self)) return int(self - OP_1 + 1) @@ -90,7 +90,7 @@ if self in OPCODE_NAMES: return OPCODE_NAMES[self] else: - return 'CScriptOp(0x%x)' % self + return 'CScriptOp(0x{:x})'.format(self) def __new__(cls, n): try: @@ -453,7 +453,7 @@ return CScript(super(CScript, self).__add__(other)) except TypeError: raise TypeError( - 'Can not add a %r instance to a CScript' % other.__class__) + 'Can not add a {!r} instance to a CScript'.format(other.__class__)) def join(self, iterable): # join makes no sense for a CScript() @@ -489,7 +489,7 @@ datasize = None pushdata_type = None if opcode < OP_PUSHDATA1: - pushdata_type = 'PUSHDATA(%d)' % opcode + pushdata_type = 'PUSHDATA({})'.format(opcode) datasize = opcode elif opcode == OP_PUSHDATA1: @@ -525,7 +525,7 @@ # Check for truncation if len(data) < datasize: raise CScriptTruncatedPushDataError( - '%s: truncated data' % pushdata_type, data) + '{}: truncated data'.format(pushdata_type, data)) i += datasize @@ -556,7 +556,7 @@ # need to change def _repr(o): if isinstance(o, bytes): - return b"x('%s')" % hexlify(o).decode('ascii') + return "x('{}')".format(hexlify(o).decode('ascii')).encode() else: return repr(o) @@ -567,10 +567,10 @@ try: op = _repr(next(i)) except CScriptTruncatedPushDataError as err: - op = '%s...' % (_repr(err.data), err) + op = '{}...'.format(_repr(err.data), err) break except CScriptInvalidError as err: - op = '' % err + op = ''.format(err) break except StopIteration: break @@ -578,7 +578,7 @@ if op is not None: ops.append(op) - return "CScript([%s])" % ', '.join(ops) + return "CScript([{}])".format(', '.join(ops)) def GetSigOpCount(self, fAccurate): """Get the SigOp count. @@ -635,7 +635,7 @@ HASH_ONE = b'\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' if inIdx >= len(txTo.vin): - return (HASH_ONE, "inIdx %d out of range (%d)" % (inIdx, len(txTo.vin))) + return (HASH_ONE, "inIdx {} out of range ({})".format(inIdx, len(txTo.vin))) txtmp = CTransaction(txTo) for txin in txtmp.vin: @@ -653,7 +653,7 @@ elif (hashtype & 0x1f) == SIGHASH_SINGLE: outIdx = inIdx if outIdx >= len(txtmp.vout): - return (HASH_ONE, "outIdx %d out of range (%d)" % (outIdx, len(txtmp.vout))) + return (HASH_ONE, "outIdx {} out of range ({})".format(outIdx, len(txtmp.vout))) tmp = txtmp.vout[outIdx] txtmp.vout = [] diff --git a/test/functional/test_framework/socks5.py b/test/functional/test_framework/socks5.py --- a/test/functional/test_framework/socks5.py +++ b/test/functional/test_framework/socks5.py @@ -62,7 +62,8 @@ self.password = password def __repr__(self): - return 'Socks5Command(%s,%s,%s,%s,%s,%s)' % (self.cmd, self.atyp, self.addr, self.port, self.username, self.password) + return 'Socks5Command({},{},{},{},{},{})'.format( + self.cmd, self.atyp, self.addr, self.port, self.username, self.password) class Socks5Connection(): @@ -77,7 +78,7 @@ # Verify socks version ver = recvall(self.conn, 1)[0] if ver != 0x05: - raise IOError('Invalid socks version %i' % ver) + raise IOError('Invalid socks version {}'.format(ver)) # Choose authentication method nmethods = recvall(self.conn, 1)[0] methods = bytearray(recvall(self.conn, nmethods)) @@ -96,7 +97,7 @@ if method == 0x02: ver = recvall(self.conn, 1)[0] if ver != 0x01: - raise IOError('Invalid auth packet version %i' % ver) + raise IOError('Invalid auth packet version {}'.format(ver)) ulen = recvall(self.conn, 1)[0] username = str(recvall(self.conn, ulen)) plen = recvall(self.conn, 1)[0] @@ -108,9 +109,10 @@ ver, cmd, _, atyp = recvall(self.conn, 4) if ver != 0x05: raise IOError( - 'Invalid socks version %i in connect request' % ver) + 'Invalid socks version {} in connect request'.format(ver)) if cmd != Command.CONNECT: - raise IOError('Unhandled command %i in connect request' % cmd) + raise IOError( + 'Unhandled command {} in connect request'.format(cmd)) if atyp == AddressType.IPV4: addr = recvall(self.conn, 4) @@ -120,7 +122,7 @@ elif atyp == AddressType.IPV6: addr = recvall(self.conn, 16) else: - raise IOError('Unknown address type %i' % atyp) + raise IOError('Unknown address type {}'.format(atyp)) port_hi, port_lo = recvall(self.conn, 2) port = (port_hi << 8) | port_lo @@ -130,7 +132,7 @@ cmdin = Socks5Command(cmd, atyp, addr, port, username, password) self.serv.queue.put(cmdin) - logger.info('Proxy: %s', cmdin) + logger.info('Proxy: {}'.format(cmdin)) # Fall through to disconnect except Exception as e: logger.exception("socks5 request handling failed.") diff --git a/test/functional/test_framework/test_framework.py b/test/functional/test_framework/test_framework.py --- a/test/functional/test_framework/test_framework.py +++ b/test/functional/test_framework/test_framework.py @@ -135,7 +135,7 @@ except JSONRPCException as e: self.log.exception("JSONRPC error") except SkipTest as e: - self.log.warning("Test Skipped: %s" % e.message) + self.log.warning("Test Skipped: {}".format(e.message)) success = TestStatus.SKIPPED except AssertionError as e: self.log.exception("Assertion failed") @@ -162,7 +162,8 @@ self.log.info("Cleaning up") shutil.rmtree(self.options.tmpdir) else: - self.log.warning("Not cleaning up dir %s" % self.options.tmpdir) + self.log.warning( + "Not cleaning up dir {}".format(self.options.tmpdir)) if os.getenv("PYTHON_DEBUG", ""): # Dump the end of the debug logs, to aid in debugging rare # travis failures. @@ -177,7 +178,7 @@ print("From", fn, ":") print("".join(deque(f, MAX_LINES_TO_PRINT))) except OSError: - print("Opening file %s failed." % fn) + print("Opening file {} failed.".format(fn)) traceback.print_exc() if success == TestStatus.PASSED: @@ -188,7 +189,7 @@ sys.exit(TEST_EXIT_SKIPPED) else: self.log.error( - "Test failed. Test logging available at %s/test_framework.log", self.options.tmpdir) + "Test failed. Test logging available at {}/test_framework.log".format(self.options.tmpdir)) logging.shutdown() sys.exit(TEST_EXIT_FAILED) diff --git a/test/functional/test_framework/test_node.py b/test/functional/test_framework/test_node.py --- a/test/functional/test_framework/test_node.py +++ b/test/functional/test_framework/test_node.py @@ -79,7 +79,7 @@ self.rpc = None self.url = None self.relay_fee_cache = None - self.log = logging.getLogger('TestFramework.node%d' % i) + self.log = logging.getLogger('TestFramework.node{}'.format(i)) self.p2ps = [] @@ -126,7 +126,7 @@ poll_per_s = 4 for _ in range(poll_per_s * self.rpc_timeout): assert self.process.poll( - ) is None, "bitcoind exited with status %i during initialization" % self.process.returncode + ) is None, "bitcoind exited with status {} during initialization".format(self.process.returncode) try: self.rpc = get_rpc_proxy(rpc_url(self.datadir, self.host, self.rpc_port), self.index, timeout=self.rpc_timeout, coveragedir=self.coverage_dir) diff --git a/test/functional/test_framework/util.py b/test/functional/test_framework/util.py --- a/test/functional/test_framework/util.py +++ b/test/functional/test_framework/util.py @@ -37,26 +37,26 @@ target_fee = tx_size * fee_per_kB / 1000 if fee < (tx_size - wiggleroom) * fee_per_kB / 1000: raise AssertionError( - "Fee of %s BCH too low! (Should be %s BCH)" % (str(fee), str(target_fee))) + "Fee of {} BCH too low! (Should be {} BCH)".format(str(fee), str(target_fee))) if fee > (tx_size + wiggleroom) * fee_per_kB / 1000: raise AssertionError( - "Fee of %s BCH too high! (Should be %s BCH)" % (str(fee), str(target_fee))) + "Fee of {} BCH too high! (Should be {} BCH)".format(str(fee), str(target_fee))) def assert_equal(thing1, thing2, *args): if thing1 != thing2 or any(thing1 != arg for arg in args): - raise AssertionError("not(%s)" % " == ".join(str(arg) - for arg in (thing1, thing2) + args)) + raise AssertionError("not({})".format(" == ".join(str(arg) + for arg in (thing1, thing2) + args))) def assert_greater_than(thing1, thing2): if thing1 <= thing2: - raise AssertionError("%s <= %s" % (str(thing1), str(thing2))) + raise AssertionError("{} <= {}".format(str(thing1), str(thing2))) def assert_greater_than_or_equal(thing1, thing2): if thing1 < thing2: - raise AssertionError("%s < %s" % (str(thing1), str(thing2))) + raise AssertionError("{} < {}".format(str(thing1), str(thing2))) def assert_raises(exc, fun, *args, **kwds): @@ -98,7 +98,8 @@ fun(*args, **kwds) except CalledProcessError as e: if returncode != e.returncode: - raise AssertionError("Unexpected returncode %i" % e.returncode) + raise AssertionError( + "Unexpected returncode {}".format(e.returncode)) if output not in e.output: raise AssertionError("Expected substring not found:" + e.output) else: @@ -135,7 +136,7 @@ # JSONRPCException was thrown as expected. Check the code and message values are correct. if (code is not None) and (code != e.error["code"]): raise AssertionError( - "Unexpected JSONRPC error code %i" % e.error["code"]) + "Unexpected JSONRPC error code {}".format(e.error["code"])) if (message is not None) and (message not in e.error['message']): raise AssertionError( "Expected substring not found:" + e.error['message']) @@ -152,18 +153,19 @@ int(string, 16) except Exception as e: raise AssertionError( - "Couldn't interpret %r as hexadecimal; raised: %s" % (string, e)) + "Couldn't interpret {!r} as hexadecimal; raised: {}".format(string, e)) def assert_is_hash_string(string, length=64): if not isinstance(string, str): - raise AssertionError("Expected a string, got type %r" % type(string)) + raise AssertionError( + "Expected a string, got type {!r}".format(type(string))) elif length and len(string) != length: raise AssertionError( - "String of length %d expected; got %d" % (length, len(string))) + "String of length {} expected; got {}".format(length, len(string))) elif not re.match('[abcdef0-9]+$', string): raise AssertionError( - "String %r contains invalid characters for a hash." % string) + "String {!r} contains invalid characters for a hash.".format(string)) def assert_array_result(object_array, to_match, expected, should_not_find=False): @@ -188,13 +190,13 @@ num_matched = num_matched + 1 for key, value in expected.items(): if item[key] != value: - raise AssertionError("%s : expected %s=%s" % - (str(item), str(key), str(value))) + raise AssertionError("{} : expected {}={}".format( + str(item), str(key), str(value))) num_matched = num_matched + 1 if num_matched == 0 and not should_not_find: - raise AssertionError("No objects matched %s" % (str(to_match))) + raise AssertionError("No objects matched {}".format(str(to_match))) if num_matched > 0 and should_not_find: - raise AssertionError("Objects were found %s" % (str(to_match))) + raise AssertionError("Objects were found {}".format(str(to_match))) # Utility functions ################### @@ -314,7 +316,7 @@ rpc_u, rpc_p = get_auth_cookie(datadir) if host == None: host = '127.0.0.1' - return "http://%s:%s@%s:%d" % (rpc_u, rpc_p, host, int(port)) + return "http://{}:{}@{}:{}".format(rpc_u, rpc_p, host, int(port)) # Node functions ################ @@ -474,8 +476,8 @@ for i in range(len(txdata["vout"])): if txdata["vout"][i]["value"] == amount: return i - raise RuntimeError("find_output txid %s : %s not found" % - (txid, str(amount))) + raise RuntimeError("find_output txid {} : {} not found".format( + txid, str(amount))) def gather_inputs(from_node, amount_needed, confirmations_required=1): @@ -493,8 +495,8 @@ inputs.append( {"txid": t["txid"], "vout": t["vout"], "address": t["address"]}) if total_in < amount_needed: - raise RuntimeError("Insufficient funds: need %d, have %d" % - (amount_needed, total_in)) + raise RuntimeError("Insufficient funds: need {}, have {}".format( + amount_needed, total_in)) return (total_in, inputs)