Skip to content

Commit 423ca30

Browse files
author
MarcoFalke
committed
Merge bitcoin#7972: [qa] pull-tester: Run rpc test in parallel
ccccc59 [qa] Add option --portseed to test_framework (MarcoFalke) fa494de [qa] pull-tester: Run rpc test in parallel (MarcoFalke)
2 parents 373b50d + ccccc59 commit 423ca30

File tree

5 files changed

+121
-21
lines changed

5 files changed

+121
-21
lines changed

qa/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,9 @@ Run all possible tests with
3535

3636
qa/pull-tester/rpc-tests.py -extended
3737

38+
By default, tests will be run in parallel if you want to specify how many
39+
tests should be run in parallel, append `-paralell=n` (default n=4).
40+
3841
If you want to create a basic coverage report for the rpc test suite, append `--coverage`.
3942

4043
Possible options, which apply to each individual test run:

qa/pull-tester/rpc-tests.py

Lines changed: 80 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -53,10 +53,12 @@
5353

5454
#Create a set to store arguments and create the passon string
5555
opts = set()
56-
passon_args = ""
56+
passon_args = []
5757
PASSON_REGEX = re.compile("^--")
58+
PARALLEL_REGEX = re.compile('^-parallel=')
5859

5960
print_help = False
61+
run_parallel = 4
6062

6163
for arg in sys.argv[1:]:
6264
if arg == "--help" or arg == "-h" or arg == "-?":
@@ -65,7 +67,9 @@
6567
if arg == '--coverage':
6668
ENABLE_COVERAGE = 1
6769
elif PASSON_REGEX.match(arg):
68-
passon_args += " " + arg
70+
passon_args.append(arg)
71+
elif PARALLEL_REGEX.match(arg):
72+
run_parallel = int(arg.split(sep='=', maxsplit=1)[1])
6973
else:
7074
opts.add(arg)
7175

@@ -96,6 +100,7 @@
96100

97101
#Tests
98102
testScripts = [
103+
'walletbackup.py',
99104
'bip68-112-113-p2p.py',
100105
'wallet.py',
101106
'listtransactions.py',
@@ -116,7 +121,6 @@
116121
'merkle_blocks.py',
117122
'fundrawtransaction.py',
118123
'signrawtransactions.py',
119-
'walletbackup.py',
120124
'nodehandling.py',
121125
'reindex.py',
122126
'decodescript.py',
@@ -131,7 +135,7 @@
131135
'abandonconflict.py',
132136
'p2p-versionbits-warning.py',
133137
'importprunedfunds.py',
134-
'signmessages.py'
138+
'signmessages.py',
135139
]
136140
if ENABLE_ZMQ:
137141
testScripts.append('zmq_test.py')
@@ -160,6 +164,7 @@
160164
'pruning.py', # leave pruning last as it takes a REALLY long time
161165
]
162166

167+
163168
def runtests():
164169
test_list = []
165170
if '-extended' in opts:
@@ -173,30 +178,92 @@ def runtests():
173178

174179
if print_help:
175180
# Only print help of the first script and exit
176-
subprocess.check_call(RPC_TESTS_DIR + test_list[0] + ' -h', shell=True)
181+
subprocess.check_call((RPC_TESTS_DIR + test_list[0]).split() + ['-h'])
177182
sys.exit(0)
178183

179184
coverage = None
180185

181186
if ENABLE_COVERAGE:
182187
coverage = RPCCoverage()
183188
print("Initializing coverage directory at %s\n" % coverage.dir)
184-
flags = " --srcdir %s/src %s %s" % (BUILDDIR, coverage.flag if coverage else '', passon_args)
189+
flags = ["--srcdir=%s/src" % BUILDDIR] + passon_args
190+
if coverage:
191+
flags.append(coverage.flag)
192+
193+
if len(test_list) > 1:
194+
# Populate cache
195+
subprocess.check_output([RPC_TESTS_DIR + 'create_cache.py'] + flags)
185196

186197
#Run Tests
187-
for t in test_list:
188-
print("Running testscript %s%s%s ..." % (BOLD[1], t, BOLD[0]))
189-
time0 = time.time()
190-
subprocess.check_call(
191-
RPC_TESTS_DIR + t + flags, shell=True)
192-
print("Duration: %s s\n" % (int(time.time() - time0)))
198+
max_len_name = len(max(test_list, key=len))
199+
time_sum = 0
200+
time0 = time.time()
201+
job_queue = RPCTestHandler(run_parallel, test_list, flags)
202+
results = BOLD[1] + "%s | %s | %s\n\n" % ("TEST".ljust(max_len_name), "PASSED", "DURATION") + BOLD[0]
203+
all_passed = True
204+
for _ in range(len(test_list)):
205+
(name, stdout, stderr, passed, duration) = job_queue.get_next()
206+
all_passed = all_passed and passed
207+
time_sum += duration
208+
209+
print('\n' + BOLD[1] + name + BOLD[0] + ":")
210+
print(stdout)
211+
print('stderr:\n' if not stderr == '' else '', stderr)
212+
results += "%s | %s | %s s\n" % (name.ljust(max_len_name), str(passed).ljust(6), duration)
213+
print("Pass: %s%s%s, Duration: %s s\n" % (BOLD[1], passed, BOLD[0], duration))
214+
results += BOLD[1] + "\n%s | %s | %s s (accumulated)" % ("ALL".ljust(max_len_name), str(all_passed).ljust(6), time_sum) + BOLD[0]
215+
print(results)
216+
print("\nRuntime: %s s" % (int(time.time() - time0)))
193217

194218
if coverage:
195219
coverage.report_rpc_coverage()
196220

197221
print("Cleaning up coverage data")
198222
coverage.cleanup()
199223

224+
sys.exit(not all_passed)
225+
226+
227+
class RPCTestHandler:
228+
"""
229+
Trigger the testscrips passed in via the list.
230+
"""
231+
232+
def __init__(self, num_tests_parallel, test_list=None, flags=None):
233+
assert(num_tests_parallel >= 1)
234+
self.num_jobs = num_tests_parallel
235+
self.test_list = test_list
236+
self.flags = flags
237+
self.num_running = 0
238+
self.jobs = []
239+
240+
def get_next(self):
241+
while self.num_running < self.num_jobs and self.test_list:
242+
# Add tests
243+
self.num_running += 1
244+
t = self.test_list.pop(0)
245+
port_seed = ["--portseed=%s" % len(self.test_list)]
246+
self.jobs.append((t,
247+
time.time(),
248+
subprocess.Popen((RPC_TESTS_DIR + t).split() + self.flags + port_seed,
249+
universal_newlines=True,
250+
stdout=subprocess.PIPE,
251+
stderr=subprocess.PIPE)))
252+
if not self.jobs:
253+
raise IndexError('%s from empty list' % __name__)
254+
while True:
255+
# Return first proc that finishes
256+
time.sleep(.5)
257+
for j in self.jobs:
258+
(name, time0, proc) = j
259+
if proc.poll() is not None:
260+
(stdout, stderr) = proc.communicate(timeout=3)
261+
passed = stderr == "" and proc.returncode == 0
262+
self.num_running -= 1
263+
self.jobs.remove(j)
264+
return name, stdout, stderr, passed, int(time.time() - time0)
265+
print('.', end='', flush=True)
266+
200267

201268
class RPCCoverage(object):
202269
"""
@@ -215,7 +282,7 @@ class RPCCoverage(object):
215282
"""
216283
def __init__(self):
217284
self.dir = tempfile.mkdtemp(prefix="coverage")
218-
self.flag = '--coveragedir %s' % self.dir
285+
self.flag = '--coveragedir=%s' % self.dir
219286

220287
def report_rpc_coverage(self):
221288
"""

qa/rpc-tests/create_cache.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#!/usr/bin/env python3
2+
# Copyright (c) 2016 The Bitcoin Core developers
3+
# Distributed under the MIT software license, see the accompanying
4+
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
5+
6+
#
7+
# Helper script to create the cache
8+
# (see BitcoinTestFramework.setup_chain)
9+
#
10+
11+
from test_framework.test_framework import BitcoinTestFramework
12+
13+
class CreateCache(BitcoinTestFramework):
14+
15+
def setup_network(self):
16+
# Don't setup any test nodes
17+
self.options.noshutdown = True
18+
19+
def run_test(self):
20+
pass
21+
22+
if __name__ == '__main__':
23+
CreateCache().main()

qa/rpc-tests/test_framework/test_framework.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,10 @@
55

66
# Base class for RPC testing
77

8-
# Add python-bitcoinrpc to module search path:
8+
import logging
9+
import optparse
910
import os
1011
import sys
11-
1212
import shutil
1313
import tempfile
1414
import traceback
@@ -25,8 +25,9 @@
2525
enable_coverage,
2626
check_json_precision,
2727
initialize_chain_clean,
28+
PortSeed,
2829
)
29-
from .authproxy import AuthServiceProxy, JSONRPCException
30+
from .authproxy import JSONRPCException
3031

3132

3233
class BitcoinTestFramework(object):
@@ -95,7 +96,6 @@ def join_network(self):
9596
self.setup_network(False)
9697

9798
def main(self):
98-
import optparse
9999

100100
parser = optparse.OptionParser(usage="%prog [options]")
101101
parser.add_option("--nocleanup", dest="nocleanup", default=False, action="store_true",
@@ -108,18 +108,21 @@ def main(self):
108108
help="Root directory for datadirs")
109109
parser.add_option("--tracerpc", dest="trace_rpc", default=False, action="store_true",
110110
help="Print out all RPC calls as they are made")
111+
parser.add_option("--portseed", dest="port_seed", default=os.getpid(), type='int',
112+
help="The seed to use for assigning port numbers (default: current process id)")
111113
parser.add_option("--coveragedir", dest="coveragedir",
112114
help="Write tested RPC commands into this directory")
113115
self.add_options(parser)
114116
(self.options, self.args) = parser.parse_args()
115117

116118
if self.options.trace_rpc:
117-
import logging
118119
logging.basicConfig(level=logging.DEBUG, stream=sys.stdout)
119120

120121
if self.options.coveragedir:
121122
enable_coverage(self.options.coveragedir)
122123

124+
PortSeed.n = self.options.port_seed
125+
123126
os.environ['PATH'] = self.options.srcdir+":"+self.options.srcdir+"/qt:"+os.environ['PATH']
124127

125128
check_json_precision()

qa/rpc-tests/test_framework/util.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
# Helpful routines for regression testing
99
#
1010

11-
# Add python-bitcoinrpc to module search path:
1211
import os
1312
import sys
1413

@@ -36,6 +35,11 @@
3635
# The number of ports to "reserve" for p2p and rpc, each
3736
PORT_RANGE = 5000
3837

38+
39+
class PortSeed:
40+
# Must be initialized with a unique integer for each process
41+
n = None
42+
3943
#Set Mocktime default to OFF.
4044
#MOCKTIME is only needed for scripts that use the
4145
#cached version of the blockchain. If the cached
@@ -91,10 +95,10 @@ def get_rpc_proxy(url, node_number, timeout=None):
9195

9296
def p2p_port(n):
9397
assert(n <= MAX_NODES)
94-
return PORT_MIN + n + (MAX_NODES * os.getpid()) % (PORT_RANGE - 1 - MAX_NODES)
98+
return PORT_MIN + n + (MAX_NODES * PortSeed.n) % (PORT_RANGE - 1 - MAX_NODES)
9599

96100
def rpc_port(n):
97-
return PORT_MIN + PORT_RANGE + n + (MAX_NODES * os.getpid()) % (PORT_RANGE -1 - MAX_NODES)
101+
return PORT_MIN + PORT_RANGE + n + (MAX_NODES * PortSeed.n) % (PORT_RANGE - 1 - MAX_NODES)
98102

99103
def check_json_precision():
100104
"""Make sure json library being used does not lose precision converting BTC values"""

0 commit comments

Comments
 (0)