Skip to content

Commit 3de3ccd

Browse files
committed
Refactor rpc-tests.py
- add main() - remove global variables
1 parent afd38e7 commit 3de3ccd

File tree

1 file changed

+100
-85
lines changed

1 file changed

+100
-85
lines changed

qa/pull-tester/rpc-tests.py

Lines changed: 100 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -23,69 +23,8 @@
2323
import tempfile
2424
import re
2525

26-
# Parse arguments and pass through unrecognised args
27-
parser = argparse.ArgumentParser(add_help=False,
28-
usage='%(prog)s [rpc-test.py options] [script options] [scripts]',
29-
description=__doc__,
30-
epilog='''
31-
Help text and arguments for individual test script:''',
32-
formatter_class=argparse.RawTextHelpFormatter)
33-
parser.add_argument('--coverage', action='store_true', help='generate a basic coverage report for the RPC interface')
34-
parser.add_argument('--extended', action='store_true', help='run the extended test suite in addition to the basic tests')
35-
parser.add_argument('--help', '-h', '-?', action='store_true', help='print help text and exit')
36-
parser.add_argument('--jobs', '-j', type=int, default=4, help='how many test scripts to run in parallel. Default=4.')
37-
parser.add_argument('--nozmq', action='store_true', help='do not run the zmq tests')
38-
parser.add_argument('--win', action='store_true', help='signal that this is running in a Windows environment and that we should run the tests')
39-
(args, unknown_args) = parser.parse_known_args()
40-
41-
#Create a set to store arguments and create the passon string
42-
tests = set(arg for arg in unknown_args if arg[:2] != "--")
43-
passon_args = [arg for arg in unknown_args if arg[:2] == "--"]
44-
45-
BOLD = ("","")
46-
if os.name == 'posix':
47-
# primitive formatting on supported
48-
# terminal via ANSI escape sequences:
49-
BOLD = ('\033[0m', '\033[1m')
50-
51-
# Read config generated by configure.
52-
config = configparser.ConfigParser()
53-
config.read_file(open(os.path.dirname(__file__) + "/tests_config.ini"))
54-
55-
ENABLE_WALLET = config["components"]["ENABLE_WALLET"] == "True"
56-
ENABLE_UTILS = config["components"]["ENABLE_UTILS"] == "True"
57-
ENABLE_BITCOIND = config["components"]["ENABLE_BITCOIND"] == "True"
58-
ENABLE_ZMQ = config["components"]["ENABLE_ZMQ"] == "True" and not args.nozmq
59-
60-
RPC_TESTS_DIR = config["environment"]["SRCDIR"] + '/qa/rpc-tests/'
61-
62-
print_help = args.help
63-
jobs = args.jobs
64-
65-
#Set env vars
66-
if "BITCOIND" not in os.environ:
67-
os.environ["BITCOIND"] = config["environment"]["BUILDDIR"] + '/src/bitcoind' + config["environment"]["EXEEXT"]
68-
69-
if config["environment"]["EXEEXT"] == ".exe" and not args.win:
70-
# https://github.com/bitcoin/bitcoin/commit/d52802551752140cf41f0d9a225a43e84404d3e9
71-
# https://github.com/bitcoin/bitcoin/pull/5677#issuecomment-136646964
72-
print("Win tests currently disabled by default. Use --win option to enable")
73-
sys.exit(0)
74-
75-
if not (ENABLE_WALLET and ENABLE_UTILS and ENABLE_BITCOIND):
76-
print("No rpc tests to run. Wallet, utils, and bitcoind must all be enabled")
77-
sys.exit(0)
78-
79-
# python3-zmq may not be installed. Handle this gracefully and with some helpful info
80-
if ENABLE_ZMQ:
81-
try:
82-
import zmq
83-
except ImportError:
84-
print("ERROR: \"import zmq\" failed. Use -nozmq to run without the ZMQ tests."
85-
"To run zmq tests, see dependency info in /qa/README.md.")
86-
raise
87-
8826
BASE_SCRIPTS= [
27+
# Scripts that are run by the travis build process
8928
# longest test should go first, to favor running tests in parallel
9029
'wallet-hd.py',
9130
'walletbackup.py',
@@ -142,9 +81,15 @@
14281
'rpcnamedargs.py',
14382
'listsinceblock.py',
14483
]
145-
ZMQ_SCRIPTS = ["zmq_test.py"]
84+
85+
ZMQ_SCRIPTS = [
86+
# ZMQ test can only be run if bitcoin was built with zmq-enabled.
87+
# call rpc_tests.py with -nozmq to explicitly exclude these tests.
88+
"zmq_test.py"]
14689

14790
EXTENDED_SCRIPTS = [
91+
# These tests are not run by the travis build process.
92+
# Longest test should go first, to favor running tests in parallel
14893
'pruning.py',
14994
# vv Tests less than 20m vv
15095
'smartfees.py',
@@ -175,7 +120,55 @@
175120

176121
ALL_SCRIPTS = BASE_SCRIPTS + ZMQ_SCRIPTS + EXTENDED_SCRIPTS
177122

178-
def runtests():
123+
def main():
124+
# Parse arguments and pass through unrecognised args
125+
parser = argparse.ArgumentParser(add_help=False,
126+
usage='%(prog)s [rpc-test.py options] [script options] [scripts]',
127+
description=__doc__,
128+
epilog='''
129+
Help text and arguments for individual test script:''',
130+
formatter_class=argparse.RawTextHelpFormatter)
131+
parser.add_argument('--coverage', action='store_true', help='generate a basic coverage report for the RPC interface')
132+
parser.add_argument('--extended', action='store_true', help='run the extended test suite in addition to the basic tests')
133+
parser.add_argument('--help', '-h', '-?', action='store_true', help='print help text and exit')
134+
parser.add_argument('--nozmq', action='store_true', help='do not run the zmq tests')
135+
parser.add_argument('--jobs', '-j', type=int, default=4, help='how many test scripts to run in parallel. Default=4.')
136+
parser.add_argument('--win', action='store_true', help='signal that this is running in a Windows environment and that we should run the tests')
137+
(args, unknown_args) = parser.parse_known_args()
138+
139+
# Create a set to store arguments and create the passon string
140+
tests = set(arg for arg in unknown_args if arg[:2] != "--")
141+
passon_args = [arg for arg in unknown_args if arg[:2] == "--"]
142+
143+
# Read config generated by configure.
144+
config = configparser.ConfigParser()
145+
config.read_file(open(os.path.dirname(__file__) + "/tests_config.ini"))
146+
147+
enable_wallet = config["components"]["ENABLE_WALLET"] == "True"
148+
enable_utils = config["components"]["ENABLE_UTILS"] == "True"
149+
enable_bitcoind = config["components"]["ENABLE_BITCOIND"] == "True"
150+
enable_zmq = config["components"]["ENABLE_ZMQ"] == "True" and not args.nozmq
151+
152+
if config["environment"]["EXEEXT"] == ".exe" and not args.win:
153+
# https://github.com/bitcoin/bitcoin/commit/d52802551752140cf41f0d9a225a43e84404d3e9
154+
# https://github.com/bitcoin/bitcoin/pull/5677#issuecomment-136646964
155+
print("Win tests currently disabled by default. Use --win option to enable")
156+
sys.exit(0)
157+
158+
if not (enable_wallet and enable_utils and enable_bitcoind):
159+
print("No rpc tests to run. Wallet, utils, and bitcoind must all be enabled")
160+
print("Rerun `configure` with -enable-wallet, -with-utils and -with-daemon and rerun make")
161+
sys.exit(0)
162+
163+
# python3-zmq may not be installed. Handle this gracefully and with some helpful info
164+
if enable_zmq:
165+
try:
166+
import zmq
167+
except ImportError:
168+
print("ERROR: \"import zmq\" failed. Use -nozmq to run without the ZMQ tests."
169+
"To run zmq tests, see dependency info in /qa/README.md.")
170+
raise
171+
179172
# Build list of tests
180173
if len(tests) != 0:
181174
# Individual tests have been specified. Run specified tests that exist
@@ -185,12 +178,15 @@ def runtests():
185178
if len(test_list) == 0:
186179
print("No valid test scripts specified. Check that your test is in one "
187180
"of the test lists in rpc-tests.py or run rpc-tests.py with no arguments to run all tests")
181+
print("Scripts not found:")
182+
print(tests)
188183
sys.exit(0)
184+
189185
else:
190186
# No individual tests have been specified. Run base tests, and
191187
# optionally ZMQ tests and extended tests.
192188
test_list = BASE_SCRIPTS
193-
if ENABLE_ZMQ:
189+
if enable_zmq:
194190
test_list += ZMQ_SCRIPTS
195191
if args.extended:
196192
test_list += EXTENDED_SCRIPTS
@@ -201,30 +197,47 @@ def runtests():
201197
if args.help:
202198
# Print help for rpc-tests.py, then print help of the first script and exit.
203199
parser.print_help()
204-
subprocess.check_call((RPC_TESTS_DIR + test_list[0]).split() + ['-h'])
200+
subprocess.check_call((config["environment"]["SRCDIR"] + '/qa/rpc-tests/' + test_list[0]).split() + ['-h'])
205201
sys.exit(0)
206202

207-
coverage = None
203+
runtests(test_list, config["environment"]["SRCDIR"], config["environment"]["BUILDDIR"], config["environment"]["EXEEXT"], args.jobs, args.coverage, passon_args)
204+
205+
def runtests(test_list, src_dir, build_dir, exeext, jobs=1, enable_coverage=False, args=[]):
206+
BOLD = ("","")
207+
if os.name == 'posix':
208+
# primitive formatting on supported
209+
# terminal via ANSI escape sequences:
210+
BOLD = ('\033[0m', '\033[1m')
211+
212+
#Set env vars
213+
if "BITCOIND" not in os.environ:
214+
os.environ["BITCOIND"] = build_dir + '/src/bitcoind' + exeext
215+
216+
tests_dir = src_dir + '/qa/rpc-tests/'
208217

209-
if args.coverage:
218+
flags = ["--srcdir=" + src_dir] + args
219+
flags.append("--cachedir=%s/qa/cache" % build_dir)
220+
221+
if enable_coverage:
210222
coverage = RPCCoverage()
211-
print("Initializing coverage directory at %s\n" % coverage.dir)
212-
flags = ["--srcdir=%s/src" % config["environment"]["BUILDDIR"]] + passon_args
213-
flags.append("--cachedir=%s/qa/cache" % config["environment"]["BUILDDIR"])
214-
if coverage:
215223
flags.append(coverage.flag)
224+
print("Initializing coverage directory at %s\n" % coverage.dir)
225+
else:
226+
coverage = None
216227

217228
if len(test_list) > 1 and jobs > 1:
218229
# Populate cache
219-
subprocess.check_output([RPC_TESTS_DIR + 'create_cache.py'] + flags)
230+
subprocess.check_output([tests_dir + 'create_cache.py'] + flags)
220231

221232
#Run Tests
222-
max_len_name = len(max(test_list, key=len))
233+
all_passed = True
223234
time_sum = 0
224235
time0 = time.time()
225-
job_queue = RPCTestHandler(jobs, test_list, flags)
236+
237+
job_queue = RPCTestHandler(jobs, tests_dir, test_list, flags)
238+
239+
max_len_name = len(max(test_list, key=len))
226240
results = BOLD[1] + "%s | %s | %s\n\n" % ("TEST".ljust(max_len_name), "PASSED", "DURATION") + BOLD[0]
227-
all_passed = True
228241
for _ in range(len(test_list)):
229242
(name, stdout, stderr, passed, duration) = job_queue.get_next()
230243
all_passed = all_passed and passed
@@ -233,8 +246,10 @@ def runtests():
233246
print('\n' + BOLD[1] + name + BOLD[0] + ":")
234247
print('' if passed else stdout + '\n', end='')
235248
print('' if stderr == '' else 'stderr:\n' + stderr + '\n', end='')
236-
results += "%s | %s | %s s\n" % (name.ljust(max_len_name), str(passed).ljust(6), duration)
237249
print("Pass: %s%s%s, Duration: %s s\n" % (BOLD[1], passed, BOLD[0], duration))
250+
251+
results += "%s | %s | %s s\n" % (name.ljust(max_len_name), str(passed).ljust(6), duration)
252+
238253
results += BOLD[1] + "\n%s | %s | %s s (accumulated)" % ("ALL".ljust(max_len_name), str(all_passed).ljust(6), time_sum) + BOLD[0]
239254
print(results)
240255
print("\nRuntime: %s s" % (int(time.time() - time0)))
@@ -247,15 +262,15 @@ def runtests():
247262

248263
sys.exit(not all_passed)
249264

250-
251265
class RPCTestHandler:
252266
"""
253267
Trigger the testscrips passed in via the list.
254268
"""
255269

256-
def __init__(self, num_tests_parallel, test_list=None, flags=None):
270+
def __init__(self, num_tests_parallel, tests_dir, test_list=None, flags=None):
257271
assert(num_tests_parallel >= 1)
258272
self.num_jobs = num_tests_parallel
273+
self.tests_dir = tests_dir
259274
self.test_list = test_list
260275
self.flags = flags
261276
self.num_running = 0
@@ -275,7 +290,7 @@ def get_next(self):
275290
log_stderr = tempfile.SpooledTemporaryFile(max_size=2**16)
276291
self.jobs.append((t,
277292
time.time(),
278-
subprocess.Popen((RPC_TESTS_DIR + t).split() + self.flags + port_seed,
293+
subprocess.Popen((self.tests_dir + t).split() + self.flags + port_seed,
279294
universal_newlines=True,
280295
stdout=log_stdout,
281296
stderr=log_stderr),
@@ -340,10 +355,10 @@ def _get_uncovered_rpc_commands(self):
340355
341356
"""
342357
# This is shared from `qa/rpc-tests/test-framework/coverage.py`
343-
REFERENCE_FILENAME = 'rpc_interface.txt'
344-
COVERAGE_FILE_PREFIX = 'coverage.'
358+
reference_filename = 'rpc_interface.txt'
359+
coverage_file_prefix = 'coverage.'
345360

346-
coverage_ref_filename = os.path.join(self.dir, REFERENCE_FILENAME)
361+
coverage_ref_filename = os.path.join(self.dir, reference_filename)
347362
coverage_filenames = set()
348363
all_cmds = set()
349364
covered_cmds = set()
@@ -356,7 +371,7 @@ def _get_uncovered_rpc_commands(self):
356371

357372
for root, dirs, files in os.walk(self.dir):
358373
for filename in files:
359-
if filename.startswith(COVERAGE_FILE_PREFIX):
374+
if filename.startswith(coverage_file_prefix):
360375
coverage_filenames.add(os.path.join(root, filename))
361376

362377
for filename in coverage_filenames:
@@ -367,4 +382,4 @@ def _get_uncovered_rpc_commands(self):
367382

368383

369384
if __name__ == '__main__':
370-
runtests()
385+
main()

0 commit comments

Comments
 (0)