aboutsummaryrefslogtreecommitdiff
path: root/test
diff options
context:
space:
mode:
Diffstat (limited to 'test')
-rwxr-xr-xtest/functional/blockchain.py20
-rwxr-xr-xtest/functional/bumpfee.py2
-rwxr-xr-xtest/functional/multi_rpc.py58
-rwxr-xr-xtest/functional/p2p-segwit.py12
-rwxr-xr-xtest/functional/pruning.py6
-rwxr-xr-xtest/functional/rest.py22
-rwxr-xr-xtest/functional/rpcbind_test.py2
-rwxr-xr-xtest/functional/smartfees.py2
-rwxr-xr-xtest/functional/test_framework/mininode.py2
-rwxr-xr-xtest/functional/test_framework/test_framework.py5
-rw-r--r--test/functional/test_framework/util.py50
-rwxr-xr-xtest/functional/test_runner.py8
-rwxr-xr-xtest/functional/uptime.py32
-rwxr-xr-xtest/functional/zapwallettxes.py2
-rwxr-xr-xtest/functional/zmq_test.py65
15 files changed, 208 insertions, 80 deletions
diff --git a/test/functional/blockchain.py b/test/functional/blockchain.py
index 6aef6d4489..e205c6400c 100755
--- a/test/functional/blockchain.py
+++ b/test/functional/blockchain.py
@@ -18,13 +18,16 @@ Tests correspond to code in rpc/blockchain.cpp.
"""
from decimal import Decimal
+import subprocess
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
+ assert_raises,
assert_raises_jsonrpc,
assert_is_hex_string,
assert_is_hash_string,
+ bitcoind_processes,
)
@@ -34,6 +37,7 @@ class BlockchainTest(BitcoinTestFramework):
super().__init__()
self.setup_clean_chain = False
self.num_nodes = 1
+ self.extra_args = [['-stopatheight=207']]
def run_test(self):
self._test_getchaintxstats()
@@ -41,7 +45,8 @@ class BlockchainTest(BitcoinTestFramework):
self._test_getblockheader()
self._test_getdifficulty()
self._test_getnetworkhashps()
- self.nodes[0].verifychain(4, 0)
+ self._test_stopatheight()
+ assert self.nodes[0].verifychain(4, 0)
def _test_getchaintxstats(self):
chaintxstats = self.nodes[0].getchaintxstats(1)
@@ -129,5 +134,18 @@ class BlockchainTest(BitcoinTestFramework):
# This should be 2 hashes every 10 minutes or 1/300
assert abs(hashes_per_second * 300 - 1) < 0.0001
+ def _test_stopatheight(self):
+ assert_equal(self.nodes[0].getblockcount(), 200)
+ self.nodes[0].generate(6)
+ assert_equal(self.nodes[0].getblockcount(), 206)
+ self.log.debug('Node should not stop at this height')
+ assert_raises(subprocess.TimeoutExpired, lambda: bitcoind_processes[0].wait(timeout=3))
+ self.nodes[0].generate(1)
+ self.log.debug('Node should stop at this height...')
+ bitcoind_processes[0].wait(timeout=3)
+ self.nodes[0] = self.start_node(0, self.options.tmpdir)
+ assert_equal(self.nodes[0].getblockcount(), 207)
+
+
if __name__ == '__main__':
BlockchainTest().main()
diff --git a/test/functional/bumpfee.py b/test/functional/bumpfee.py
index d42bab6cbf..569db7ced5 100755
--- a/test/functional/bumpfee.py
+++ b/test/functional/bumpfee.py
@@ -10,7 +10,7 @@ its preconditions are met, and returns appropriate errors in other cases.
This module consists of around a dozen individual test cases implemented in the
top-level functions named as test_<test_case_description>. The test functions
can be disabled or reordered if needed for debugging. If new test cases are
-added in the the future, they should try to follow the same convention and not
+added in the future, they should try to follow the same convention and not
make assumptions about execution order.
"""
diff --git a/test/functional/multi_rpc.py b/test/functional/multi_rpc.py
index 6ff91a960b..a30e15ace9 100755
--- a/test/functional/multi_rpc.py
+++ b/test/functional/multi_rpc.py
@@ -16,16 +16,21 @@ class HTTPBasicsTest (BitcoinTestFramework):
def __init__(self):
super().__init__()
self.setup_clean_chain = False
- self.num_nodes = 1
+ self.num_nodes = 2
def setup_chain(self):
super().setup_chain()
#Append rpcauth to bitcoin.conf before initialization
rpcauth = "rpcauth=rt:93648e835a54c573682c2eb19f882535$7681e9c5b74bdd85e78166031d2058e1069b3ed7ed967c93fc63abba06f31144"
rpcauth2 = "rpcauth=rt2:f8607b1a88861fac29dfccf9b52ff9f$ff36a0c23c8c62b4846112e50fa888416e94c17bfd4c42f88fd8f55ec6a3137e"
+ rpcuser = "rpcuser=rpcuser💻"
+ rpcpassword = "rpcpassword=rpcpassword🔑"
with open(os.path.join(self.options.tmpdir+"/node0", "bitcoin.conf"), 'a', encoding='utf8') as f:
f.write(rpcauth+"\n")
f.write(rpcauth2+"\n")
+ with open(os.path.join(self.options.tmpdir+"/node1", "bitcoin.conf"), 'a', encoding='utf8') as f:
+ f.write(rpcuser+"\n")
+ f.write(rpcpassword+"\n")
def run_test(self):
@@ -50,7 +55,7 @@ class HTTPBasicsTest (BitcoinTestFramework):
conn.connect()
conn.request('POST', '/', '{"method": "getbestblockhash"}', headers)
resp = conn.getresponse()
- assert_equal(resp.status==401, False)
+ assert_equal(resp.status, 200)
conn.close()
#Use new authpair to confirm both work
@@ -60,7 +65,7 @@ class HTTPBasicsTest (BitcoinTestFramework):
conn.connect()
conn.request('POST', '/', '{"method": "getbestblockhash"}', headers)
resp = conn.getresponse()
- assert_equal(resp.status==401, False)
+ assert_equal(resp.status, 200)
conn.close()
#Wrong login name with rt's password
@@ -71,7 +76,7 @@ class HTTPBasicsTest (BitcoinTestFramework):
conn.connect()
conn.request('POST', '/', '{"method": "getbestblockhash"}', headers)
resp = conn.getresponse()
- assert_equal(resp.status==401, True)
+ assert_equal(resp.status, 401)
conn.close()
#Wrong password for rt
@@ -82,7 +87,7 @@ class HTTPBasicsTest (BitcoinTestFramework):
conn.connect()
conn.request('POST', '/', '{"method": "getbestblockhash"}', headers)
resp = conn.getresponse()
- assert_equal(resp.status==401, True)
+ assert_equal(resp.status, 401)
conn.close()
#Correct for rt2
@@ -93,7 +98,7 @@ class HTTPBasicsTest (BitcoinTestFramework):
conn.connect()
conn.request('POST', '/', '{"method": "getbestblockhash"}', headers)
resp = conn.getresponse()
- assert_equal(resp.status==401, False)
+ assert_equal(resp.status, 200)
conn.close()
#Wrong password for rt2
@@ -104,7 +109,46 @@ class HTTPBasicsTest (BitcoinTestFramework):
conn.connect()
conn.request('POST', '/', '{"method": "getbestblockhash"}', headers)
resp = conn.getresponse()
- assert_equal(resp.status==401, True)
+ assert_equal(resp.status, 401)
+ conn.close()
+
+ ###############################################################
+ # Check correctness of the rpcuser/rpcpassword config options #
+ ###############################################################
+ url = urllib.parse.urlparse(self.nodes[1].url)
+
+ # rpcuser and rpcpassword authpair
+ rpcuserauthpair = "rpcuser💻:rpcpassword🔑"
+
+ headers = {"Authorization": "Basic " + str_to_b64str(rpcuserauthpair)}
+
+ conn = http.client.HTTPConnection(url.hostname, url.port)
+ conn.connect()
+ conn.request('POST', '/', '{"method": "getbestblockhash"}', headers)
+ resp = conn.getresponse()
+ assert_equal(resp.status, 200)
+ conn.close()
+
+ #Wrong login name with rpcuser's password
+ rpcuserauthpair = "rpcuserwrong:rpcpassword"
+ headers = {"Authorization": "Basic " + str_to_b64str(rpcuserauthpair)}
+
+ conn = http.client.HTTPConnection(url.hostname, url.port)
+ conn.connect()
+ conn.request('POST', '/', '{"method": "getbestblockhash"}', headers)
+ resp = conn.getresponse()
+ assert_equal(resp.status, 401)
+ conn.close()
+
+ #Wrong password for rpcuser
+ rpcuserauthpair = "rpcuser:rpcpasswordwrong"
+ headers = {"Authorization": "Basic " + str_to_b64str(rpcuserauthpair)}
+
+ conn = http.client.HTTPConnection(url.hostname, url.port)
+ conn.connect()
+ conn.request('POST', '/', '{"method": "getbestblockhash"}', headers)
+ resp = conn.getresponse()
+ assert_equal(resp.status, 401)
conn.close()
diff --git a/test/functional/p2p-segwit.py b/test/functional/p2p-segwit.py
index dbc61d21fc..63dfbb8ae6 100755
--- a/test/functional/p2p-segwit.py
+++ b/test/functional/p2p-segwit.py
@@ -1486,7 +1486,7 @@ class SegWitTest(BitcoinTestFramework):
# nodes would have stored, this requires special handling.
# To enable this test, pass --oldbinary=<path-to-pre-segwit-bitcoind> to
# the test.
- def test_upgrade_after_activation(self, node, node_id):
+ def test_upgrade_after_activation(self, node_id):
self.log.info("Testing software upgrade after softfork activation")
assert(node_id != 0) # node0 is assumed to be a segwit-active bitcoind
@@ -1502,14 +1502,14 @@ class SegWitTest(BitcoinTestFramework):
sync_blocks(self.nodes)
# Make sure that this peer thinks segwit has activated.
- assert(get_bip9_status(node, 'segwit')['status'] == "active")
+ assert(get_bip9_status(self.nodes[node_id], 'segwit')['status'] == "active")
# Make sure this peers blocks match those of node0.
- height = node.getblockcount()
+ height = self.nodes[node_id].getblockcount()
while height >= 0:
- block_hash = node.getblockhash(height)
+ block_hash = self.nodes[node_id].getblockhash(height)
assert_equal(block_hash, self.nodes[0].getblockhash(height))
- assert_equal(self.nodes[0].getblock(block_hash), node.getblock(block_hash))
+ assert_equal(self.nodes[0].getblock(block_hash), self.nodes[node_id].getblock(block_hash))
height -= 1
@@ -1944,7 +1944,7 @@ class SegWitTest(BitcoinTestFramework):
self.test_signature_version_1()
self.test_non_standard_witness()
sync_blocks(self.nodes)
- self.test_upgrade_after_activation(self.nodes[2], 2)
+ self.test_upgrade_after_activation(node_id=2)
self.test_witness_sigops()
diff --git a/test/functional/pruning.py b/test/functional/pruning.py
index 4c3501ad77..0af91e0658 100755
--- a/test/functional/pruning.py
+++ b/test/functional/pruning.py
@@ -315,17 +315,17 @@ class PruneTest(BitcoinTestFramework):
# check that the pruning node's wallet is still in good shape
self.log.info("Stop and start pruning node to trigger wallet rescan")
self.stop_node(2)
- self.start_node(2, self.options.tmpdir, ["-prune=550"])
+ self.nodes[2] = self.start_node(2, self.options.tmpdir, ["-prune=550"])
self.log.info("Success")
- # check that wallet loads loads successfully when restarting a pruned node after IBD.
+ # check that wallet loads successfully when restarting a pruned node after IBD.
# this was reported to fail in #7494.
self.log.info("Syncing node 5 to test wallet")
connect_nodes(self.nodes[0], 5)
nds = [self.nodes[0], self.nodes[5]]
sync_blocks(nds, wait=5, timeout=300)
self.stop_node(5) #stop and start to trigger rescan
- self.start_node(5, self.options.tmpdir, ["-prune=550"])
+ self.nodes[5] = self.start_node(5, self.options.tmpdir, ["-prune=550"])
self.log.info("Success")
def run_test(self):
diff --git a/test/functional/rest.py b/test/functional/rest.py
index fbcceba0fa..a69dbb5013 100755
--- a/test/functional/rest.py
+++ b/test/functional/rest.py
@@ -82,9 +82,9 @@ class RESTTest (BitcoinTestFramework):
n = vout['n']
- ######################################
- # GETUTXOS: query a unspent outpoint #
- ######################################
+ #######################################
+ # GETUTXOS: query an unspent outpoint #
+ #######################################
json_request = '/checkmempool/'+txid+'-'+str(n)
json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json')
json_obj = json.loads(json_string)
@@ -97,9 +97,9 @@ class RESTTest (BitcoinTestFramework):
assert_equal(json_obj['utxos'][0]['value'], 0.1)
- ################################################
- # GETUTXOS: now query a already spent outpoint #
- ################################################
+ #################################################
+ # GETUTXOS: now query an already spent outpoint #
+ #################################################
json_request = '/checkmempool/'+vintx+'-0'
json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json')
json_obj = json.loads(json_string)
@@ -161,24 +161,24 @@ class RESTTest (BitcoinTestFramework):
json_request = '/'+txid+'-'+str(n)
json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json')
json_obj = json.loads(json_string)
- assert_equal(len(json_obj['utxos']), 0) #there should be a outpoint because it has just added to the mempool
+ assert_equal(len(json_obj['utxos']), 0) #there should be an outpoint because it has just added to the mempool
json_request = '/checkmempool/'+txid+'-'+str(n)
json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json')
json_obj = json.loads(json_string)
- assert_equal(len(json_obj['utxos']), 1) #there should be a outpoint because it has just added to the mempool
+ assert_equal(len(json_obj['utxos']), 1) #there should be an outpoint because it has just added to the mempool
#do some invalid requests
json_request = '{"checkmempool'
response = http_post_call(url.hostname, url.port, '/rest/getutxos'+self.FORMAT_SEPARATOR+'json', json_request, True)
- assert_equal(response.status, 400) #must be a 400 because we send a invalid json request
+ assert_equal(response.status, 400) #must be a 400 because we send an invalid json request
json_request = '{"checkmempool'
response = http_post_call(url.hostname, url.port, '/rest/getutxos'+self.FORMAT_SEPARATOR+'bin', json_request, True)
- assert_equal(response.status, 400) #must be a 400 because we send a invalid bin request
+ assert_equal(response.status, 400) #must be a 400 because we send an invalid bin request
response = http_post_call(url.hostname, url.port, '/rest/getutxos/checkmempool'+self.FORMAT_SEPARATOR+'bin', '', True)
- assert_equal(response.status, 400) #must be a 400 because we send a invalid bin request
+ assert_equal(response.status, 400) #must be a 400 because we send an invalid bin request
#test limits
json_request = '/checkmempool/'
diff --git a/test/functional/rpcbind_test.py b/test/functional/rpcbind_test.py
index 5336cf2ec8..198599010e 100755
--- a/test/functional/rpcbind_test.py
+++ b/test/functional/rpcbind_test.py
@@ -49,7 +49,7 @@ class RPCBindTest(BitcoinTestFramework):
base_args = ['-disablewallet', '-nolisten'] + ['-rpcallowip='+x for x in allow_ips]
self.nodes = self.start_nodes(self.num_nodes, self.options.tmpdir, [base_args])
# connect to node through non-loopback interface
- node = get_rpc_proxy(rpc_url(0, "%s:%d" % (rpchost, rpcport)), 0)
+ node = get_rpc_proxy(rpc_url(get_datadir_path(self.options.tmpdir, 0), 0, "%s:%d" % (rpchost, rpcport)), 0)
node.getnetworkinfo()
self.stop_nodes()
diff --git a/test/functional/smartfees.py b/test/functional/smartfees.py
index 482c77863f..bc42a319df 100755
--- a/test/functional/smartfees.py
+++ b/test/functional/smartfees.py
@@ -10,7 +10,7 @@ from test_framework.script import CScript, OP_1, OP_DROP, OP_2, OP_HASH160, OP_E
from test_framework.mininode import CTransaction, CTxIn, CTxOut, COutPoint, ToHex, COIN
# Construct 2 trivial P2SH's and the ScriptSigs that spend them
-# So we can create many many transactions without needing to spend
+# So we can create many transactions without needing to spend
# time signing.
redeem_script_1 = CScript([OP_1, OP_DROP])
redeem_script_2 = CScript([OP_2, OP_DROP])
diff --git a/test/functional/test_framework/mininode.py b/test/functional/test_framework/mininode.py
index fb3ed1473a..688347a68f 100755
--- a/test/functional/test_framework/mininode.py
+++ b/test/functional/test_framework/mininode.py
@@ -61,7 +61,7 @@ mininode_socket_map = dict()
# One lock for synchronizing all data access between the networking thread (see
# NetworkThread below) and the thread running the test logic. For simplicity,
-# NodeConn acquires this lock whenever delivering a message to to a NodeConnCB,
+# NodeConn acquires this lock whenever delivering a message to a NodeConnCB,
# and whenever adding anything to the send buffer (in send_message()). This
# lock should be acquired in the thread running the test logic to synchronize
# access to any data shared with the NodeConnCB or NodeConn.
diff --git a/test/functional/test_framework/test_framework.py b/test/functional/test_framework/test_framework.py
index 67abf35687..c7fd44b81c 100755
--- a/test/functional/test_framework/test_framework.py
+++ b/test/functional/test_framework/test_framework.py
@@ -28,6 +28,7 @@ from .util import (
get_mocktime,
get_rpc_proxy,
initialize_datadir,
+ get_datadir_path,
log_filename,
p2p_port,
rpc_url,
@@ -300,13 +301,13 @@ class BitcoinTestFramework(object):
args.append("-connect=127.0.0.1:" + str(p2p_port(0)))
bitcoind_processes[i] = subprocess.Popen(args)
self.log.debug("initialize_chain: bitcoind started, waiting for RPC to come up")
- wait_for_bitcoind_start(bitcoind_processes[i], rpc_url(i), i)
+ wait_for_bitcoind_start(bitcoind_processes[i], datadir, i)
self.log.debug("initialize_chain: RPC successfully started")
self.nodes = []
for i in range(MAX_NODES):
try:
- self.nodes.append(get_rpc_proxy(rpc_url(i), i))
+ self.nodes.append(get_rpc_proxy(rpc_url(get_datadir_path(cachedir, i), i), i))
except:
self.log.exception("Error connecting to node %d" % i)
sys.exit(1)
diff --git a/test/functional/test_framework/util.py b/test/functional/test_framework/util.py
index 2b0f32c2b6..fa6388bf96 100644
--- a/test/functional/test_framework/util.py
+++ b/test/functional/test_framework/util.py
@@ -181,21 +181,40 @@ def initialize_datadir(dirname, n):
datadir = os.path.join(dirname, "node"+str(n))
if not os.path.isdir(datadir):
os.makedirs(datadir)
- rpc_u, rpc_p = rpc_auth_pair(n)
with open(os.path.join(datadir, "bitcoin.conf"), 'w', encoding='utf8') as f:
f.write("regtest=1\n")
- f.write("rpcuser=" + rpc_u + "\n")
- f.write("rpcpassword=" + rpc_p + "\n")
f.write("port="+str(p2p_port(n))+"\n")
f.write("rpcport="+str(rpc_port(n))+"\n")
f.write("listenonion=0\n")
return datadir
-def rpc_auth_pair(n):
- return 'rpcuser💻' + str(n), 'rpcpass🔑' + str(n)
-
-def rpc_url(i, rpchost=None):
- rpc_u, rpc_p = rpc_auth_pair(i)
+def get_datadir_path(dirname, n):
+ return os.path.join(dirname, "node"+str(n))
+
+def get_auth_cookie(datadir, n):
+ user = None
+ password = None
+ if os.path.isfile(os.path.join(datadir, "bitcoin.conf")):
+ with open(os.path.join(datadir, "bitcoin.conf"), 'r') as f:
+ for line in f:
+ if line.startswith("rpcuser="):
+ assert user is None # Ensure that there is only one rpcuser line
+ user = line.split("=")[1].strip("\n")
+ if line.startswith("rpcpassword="):
+ assert password is None # Ensure that there is only one rpcpassword line
+ password = line.split("=")[1].strip("\n")
+ if os.path.isfile(os.path.join(datadir, "regtest", ".cookie")):
+ with open(os.path.join(datadir, "regtest", ".cookie"), 'r') as f:
+ userpass = f.read()
+ split_userpass = userpass.split(':')
+ user = split_userpass[0]
+ password = split_userpass[1]
+ if user is None or password is None:
+ raise ValueError("No RPC credentials")
+ return user, password
+
+def rpc_url(datadir, i, rpchost=None):
+ rpc_u, rpc_p = get_auth_cookie(datadir, i)
host = '127.0.0.1'
port = rpc_port(i)
if rpchost:
@@ -206,7 +225,7 @@ def rpc_url(i, rpchost=None):
host = rpchost
return "http://%s:%s@%s:%d" % (rpc_u, rpc_p, host, int(port))
-def wait_for_bitcoind_start(process, url, i):
+def wait_for_bitcoind_start(process, datadir, i, rpchost=None):
'''
Wait for bitcoind to start. This means that RPC is accessible and fully initialized.
Raise an exception if bitcoind exits during initialization.
@@ -215,7 +234,8 @@ def wait_for_bitcoind_start(process, url, i):
if process.poll() is not None:
raise Exception('bitcoind exited with status %i during initialization' % process.returncode)
try:
- rpc = get_rpc_proxy(url, i)
+ # Check if .cookie file to be created
+ rpc = get_rpc_proxy(rpc_url(datadir, i, rpchost), i)
blocks = rpc.getblockcount()
break # break out of loop on success
except IOError as e:
@@ -224,6 +244,9 @@ def wait_for_bitcoind_start(process, url, i):
except JSONRPCException as e: # Initialization phase
if e.error['code'] != -28: # RPC in warmup?
raise # unknown JSON RPC exception
+ except ValueError as e: # cookie file not found and no rpcuser or rpcassword. bitcoind still starting
+ if "No RPC credentials" not in str(e):
+ raise
time.sleep(0.25)
@@ -239,10 +262,9 @@ def _start_node(i, dirname, extra_args=None, rpchost=None, timewait=None, binary
if extra_args is not None: args.extend(extra_args)
bitcoind_processes[i] = subprocess.Popen(args, stderr=stderr)
logger.debug("initialize_chain: bitcoind started, waiting for RPC to come up")
- url = rpc_url(i, rpchost)
- wait_for_bitcoind_start(bitcoind_processes[i], url, i)
+ wait_for_bitcoind_start(bitcoind_processes[i], datadir, i, rpchost)
logger.debug("initialize_chain: RPC successfully started")
- proxy = get_rpc_proxy(url, i, timeout=timewait)
+ proxy = get_rpc_proxy(rpc_url(datadir, i, rpchost), i, timeout=timewait)
if COVERAGE_DIR:
coverage.write_all_rpc_commands(COVERAGE_DIR, proxy)
@@ -300,8 +322,8 @@ def _stop_node(node, i):
except http.client.CannotSendRequest as e:
logger.exception("Unable to stop node")
return_code = bitcoind_processes[i].wait(timeout=BITCOIND_PROC_WAIT_TIMEOUT)
- assert_equal(return_code, 0)
del bitcoind_processes[i]
+ assert_equal(return_code, 0)
def _stop_nodes(nodes):
"""Stop multiple bitcoind test nodes
diff --git a/test/functional/test_runner.py b/test/functional/test_runner.py
index 1cac61d909..9952835951 100755
--- a/test/functional/test_runner.py
+++ b/test/functional/test_runner.py
@@ -20,6 +20,7 @@ import datetime
import os
import time
import shutil
+import signal
import sys
import subprocess
import tempfile
@@ -78,7 +79,7 @@ BASE_SCRIPTS= [
'rawtransactions.py',
'reindex.py',
# vv Tests less than 30s vv
- "zmq_test.py",
+ 'zmq_test.py',
'mempool_resurrect_test.py',
'txn_doublespend.py --mineblock',
'txn_clone.py',
@@ -112,6 +113,7 @@ BASE_SCRIPTS= [
'listsinceblock.py',
'p2p-leaktests.py',
'wallet-encryption.py',
+ 'uptime.py',
]
EXTENDED_SCRIPTS = [
@@ -391,6 +393,10 @@ class TestHandler:
time.sleep(.5)
for j in self.jobs:
(name, time0, proc, log_out, log_err) = j
+ if os.getenv('TRAVIS') == 'true' and int(time.time() - time0) > 20 * 60:
+ # In travis, timeout individual tests after 20 minutes (to stop tests hanging and not
+ # providing useful output.
+ proc.send_signal(signal.SIGINT)
if proc.poll() is not None:
log_out.seek(0), log_err.seek(0)
[stdout, stderr] = [l.read().decode('utf-8') for l in (log_out, log_err)]
diff --git a/test/functional/uptime.py b/test/functional/uptime.py
new file mode 100755
index 0000000000..b20d6f5cb6
--- /dev/null
+++ b/test/functional/uptime.py
@@ -0,0 +1,32 @@
+#!/usr/bin/env python3
+# Copyright (c) 2017 The Bitcoin Core developers
+# Distributed under the MIT software license, see the accompanying
+# file COPYING or http://www.opensource.org/licenses/mit-license.php.
+"""Test the RPC call related to the uptime command.
+
+Test corresponds to code in rpc/server.cpp.
+"""
+
+import time
+
+from test_framework.test_framework import BitcoinTestFramework
+
+
+class UptimeTest(BitcoinTestFramework):
+ def __init__(self):
+ super().__init__()
+
+ self.num_nodes = 1
+ self.setup_clean_chain = True
+
+ def run_test(self):
+ self._test_uptime()
+
+ def _test_uptime(self):
+ wait_time = 10
+ self.nodes[0].setmocktime(int(time.time() + wait_time))
+ assert(self.nodes[0].uptime() >= wait_time)
+
+
+if __name__ == '__main__':
+ UptimeTest().main()
diff --git a/test/functional/zapwallettxes.py b/test/functional/zapwallettxes.py
index a8600e82f6..e4d40520ef 100755
--- a/test/functional/zapwallettxes.py
+++ b/test/functional/zapwallettxes.py
@@ -70,7 +70,7 @@ class ZapWalletTXesTest (BitcoinTestFramework):
self.nodes[0] = self.start_node(0,self.options.tmpdir, ["-zapwallettxes=1"])
assert_raises(JSONRPCException, self.nodes[0].gettransaction, [txid3])
- #there must be a expection because the unconfirmed wallettx0 must be gone by now
+ #there must be an exception because the unconfirmed wallettx0 must be gone by now
tx0 = self.nodes[0].gettransaction(txid0)
assert_equal(tx0['txid'], txid0) #tx0 (confirmed) must still be available because it was confirmed
diff --git a/test/functional/zmq_test.py b/test/functional/zmq_test.py
index ce39cfefdc..26c946d215 100755
--- a/test/functional/zmq_test.py
+++ b/test/functional/zmq_test.py
@@ -8,15 +8,15 @@ import os
import struct
from test_framework.test_framework import BitcoinTestFramework, SkipTest
-from test_framework.util import *
+from test_framework.util import (assert_equal,
+ bytes_to_hex_str,
+ )
class ZMQTest (BitcoinTestFramework):
def __init__(self):
super().__init__()
- self.num_nodes = 4
-
- port = 28332
+ self.num_nodes = 2
def setup_nodes(self):
# Try to import python3-zmq. Skip this test if the import fails.
@@ -28,7 +28,7 @@ class ZMQTest (BitcoinTestFramework):
# Check that bitcoin has been built with ZMQ enabled
config = configparser.ConfigParser()
if not self.options.configfile:
- self.options.configfile = os.path.dirname(__file__) + "/config.ini"
+ self.options.configfile = os.path.dirname(__file__) + "/../config.ini"
config.read_file(open(self.options.configfile))
if not config["components"].getboolean("ENABLE_ZMQ"):
@@ -36,59 +36,66 @@ class ZMQTest (BitcoinTestFramework):
self.zmqContext = zmq.Context()
self.zmqSubSocket = self.zmqContext.socket(zmq.SUB)
+ self.zmqSubSocket.set(zmq.RCVTIMEO, 60000)
self.zmqSubSocket.setsockopt(zmq.SUBSCRIBE, b"hashblock")
self.zmqSubSocket.setsockopt(zmq.SUBSCRIBE, b"hashtx")
- self.zmqSubSocket.connect("tcp://127.0.0.1:%i" % self.port)
- self.nodes = self.start_nodes(self.num_nodes, self.options.tmpdir, extra_args=[
- ['-zmqpubhashtx=tcp://127.0.0.1:'+str(self.port), '-zmqpubhashblock=tcp://127.0.0.1:'+str(self.port)],
- [],
- [],
- []
- ])
+ ip_address = "tcp://127.0.0.1:28332"
+ self.zmqSubSocket.connect(ip_address)
+ extra_args = [['-zmqpubhashtx=%s' % ip_address, '-zmqpubhashblock=%s' % ip_address], []]
+ self.nodes = self.start_nodes(self.num_nodes, self.options.tmpdir, extra_args)
def run_test(self):
- self.sync_all()
+ try:
+ self._zmq_test()
+ finally:
+ # Destroy the zmq context
+ self.log.debug("Destroying zmq context")
+ self.zmqContext.destroy(linger=None)
+ def _zmq_test(self):
genhashes = self.nodes[0].generate(1)
self.sync_all()
- self.log.info("listen...")
+ self.log.info("Wait for tx")
msg = self.zmqSubSocket.recv_multipart()
topic = msg[0]
assert_equal(topic, b"hashtx")
body = msg[1]
msgSequence = struct.unpack('<I', msg[-1])[-1]
- assert_equal(msgSequence, 0) #must be sequence 0 on hashtx
+ assert_equal(msgSequence, 0) # must be sequence 0 on hashtx
+ self.log.info("Wait for block")
msg = self.zmqSubSocket.recv_multipart()
topic = msg[0]
body = msg[1]
msgSequence = struct.unpack('<I', msg[-1])[-1]
- assert_equal(msgSequence, 0) #must be sequence 0 on hashblock
+ assert_equal(msgSequence, 0) # must be sequence 0 on hashblock
blkhash = bytes_to_hex_str(body)
- assert_equal(genhashes[0], blkhash) #blockhash from generate must be equal to the hash received over zmq
+ assert_equal(genhashes[0], blkhash) # blockhash from generate must be equal to the hash received over zmq
+ self.log.info("Generate 10 blocks (and 10 coinbase txes)")
n = 10
genhashes = self.nodes[1].generate(n)
self.sync_all()
zmqHashes = []
blockcount = 0
- for x in range(0,n*2):
+ for x in range(n * 2):
msg = self.zmqSubSocket.recv_multipart()
topic = msg[0]
body = msg[1]
if topic == b"hashblock":
zmqHashes.append(bytes_to_hex_str(body))
msgSequence = struct.unpack('<I', msg[-1])[-1]
- assert_equal(msgSequence, blockcount+1)
+ assert_equal(msgSequence, blockcount + 1)
blockcount += 1
- for x in range(0,n):
- assert_equal(genhashes[x], zmqHashes[x]) #blockhash from generate must be equal to the hash received over zmq
+ for x in range(n):
+ assert_equal(genhashes[x], zmqHashes[x]) # blockhash from generate must be equal to the hash received over zmq
- #test tx from a second node
+ self.log.info("Wait for tx from second node")
+ # test tx from a second node
hashRPC = self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), 1.0)
self.sync_all()
@@ -96,14 +103,12 @@ class ZMQTest (BitcoinTestFramework):
msg = self.zmqSubSocket.recv_multipart()
topic = msg[0]
body = msg[1]
- hashZMQ = ""
- if topic == b"hashtx":
- hashZMQ = bytes_to_hex_str(body)
- msgSequence = struct.unpack('<I', msg[-1])[-1]
- assert_equal(msgSequence, blockcount+1)
-
- assert_equal(hashRPC, hashZMQ) #blockhash from generate must be equal to the hash received over zmq
+ assert_equal(topic, b"hashtx")
+ hashZMQ = bytes_to_hex_str(body)
+ msgSequence = struct.unpack('<I', msg[-1])[-1]
+ assert_equal(msgSequence, blockcount + 1)
+ assert_equal(hashRPC, hashZMQ) # txid from sendtoaddress must be equal to the hash received over zmq
if __name__ == '__main__':
- ZMQTest ().main ()
+ ZMQTest().main()