You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rpc-tests.py 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2014-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. rpc-tests.py - run regression test suite
  7. This module calls down into individual test cases via subprocess. It will
  8. forward all unrecognized arguments onto the individual test scripts.
  9. Functional tests are disabled on Windows by default. Use --force to run them anyway.
  10. For a description of arguments recognized by test scripts, see
  11. `test/pull-tester/test_framework/test_framework.py:BitcoinTestFramework.main`.
  12. """
  13. import argparse
  14. import configparser
  15. import os
  16. import time
  17. import shutil
  18. import sys
  19. import subprocess
  20. import tempfile
  21. import re
  22. BASE_SCRIPTS= [
  23. # Scripts that are run by the travis build process.
  24. # Longest test should go first, to favor running tests in parallel
  25. 'wallet-hd.py',
  26. 'walletbackup.py',
  27. # vv Tests less than 5m vv
  28. 'p2p-fullblocktest.py',
  29. 'fundrawtransaction.py',
  30. 'p2p-compactblocks.py',
  31. 'segwit.py',
  32. # vv Tests less than 2m vv
  33. 'wallet.py',
  34. 'wallet-accounts.py',
  35. 'p2p-segwit.py',
  36. 'wallet-dump.py',
  37. 'listtransactions.py',
  38. # vv Tests less than 60s vv
  39. 'sendheaders.py',
  40. 'zapwallettxes.py',
  41. 'importmulti.py',
  42. 'mempool_limit.py',
  43. 'merkle_blocks.py',
  44. 'receivedby.py',
  45. 'abandonconflict.py',
  46. 'bip68-112-113-p2p.py',
  47. 'rawtransactions.py',
  48. 'reindex.py',
  49. # vv Tests less than 30s vv
  50. 'mempool_resurrect_test.py',
  51. 'txn_doublespend.py --mineblock',
  52. 'txn_clone.py',
  53. 'getchaintips.py',
  54. 'rest.py',
  55. 'mempool_spendcoinbase.py',
  56. 'mempool_reorg.py',
  57. 'httpbasics.py',
  58. 'multi_rpc.py',
  59. 'proxy_test.py',
  60. 'signrawtransactions.py',
  61. 'nodehandling.py',
  62. 'decodescript.py',
  63. 'blockchain.py',
  64. 'disablewallet.py',
  65. 'keypool.py',
  66. 'p2p-mempool.py',
  67. 'prioritise_transaction.py',
  68. 'invalidblockrequest.py',
  69. 'invalidtxrequest.py',
  70. 'p2p-versionbits-warning.py',
  71. 'preciousblock.py',
  72. 'importprunedfunds.py',
  73. 'signmessages.py',
  74. 'nulldummy.py',
  75. 'import-rescan.py',
  76. 'bumpfee.py',
  77. 'rpcnamedargs.py',
  78. 'listsinceblock.py',
  79. 'p2p-leaktests.py',
  80. ]
  81. ZMQ_SCRIPTS = [
  82. # ZMQ test can only be run if bitcoin was built with zmq-enabled.
  83. # call rpc_tests.py with -nozmq to explicitly exclude these tests.
  84. "zmq_test.py"]
  85. EXTENDED_SCRIPTS = [
  86. # These tests are not run by the travis build process.
  87. # Longest test should go first, to favor running tests in parallel
  88. 'pruning.py',
  89. # vv Tests less than 20m vv
  90. 'smartfees.py',
  91. # vv Tests less than 5m vv
  92. 'maxuploadtarget.py',
  93. 'mempool_packages.py',
  94. # vv Tests less than 2m vv
  95. 'bip68-sequence.py',
  96. 'getblocktemplate_longpoll.py',
  97. 'p2p-timeouts.py',
  98. # vv Tests less than 60s vv
  99. 'bip9-softforks.py',
  100. 'p2p-feefilter.py',
  101. 'rpcbind_test.py',
  102. # vv Tests less than 30s vv
  103. 'bip65-cltv.py',
  104. 'bip65-cltv-p2p.py',
  105. 'bipdersig-p2p.py',
  106. 'bipdersig.py',
  107. 'getblocktemplate_proposals.py',
  108. 'txn_doublespend.py',
  109. 'txn_clone.py --mineblock',
  110. 'forknotify.py',
  111. 'invalidateblock.py',
  112. 'maxblocksinflight.py',
  113. 'p2p-acceptblock.py',
  114. 'replace-by-fee.py',
  115. ]
  116. ALL_SCRIPTS = BASE_SCRIPTS + ZMQ_SCRIPTS + EXTENDED_SCRIPTS
  117. def main():
  118. # Parse arguments and pass through unrecognised args
  119. parser = argparse.ArgumentParser(add_help=False,
  120. usage='%(prog)s [rpc-test.py options] [script options] [scripts]',
  121. description=__doc__,
  122. epilog='''
  123. Help text and arguments for individual test script:''',
  124. formatter_class=argparse.RawTextHelpFormatter)
  125. parser.add_argument('--coverage', action='store_true', help='generate a basic coverage report for the RPC interface')
  126. parser.add_argument('--exclude', '-x', help='specify a comma-seperated-list of scripts to exclude. Do not include the .py extension in the name.')
  127. parser.add_argument('--extended', action='store_true', help='run the extended test suite in addition to the basic tests')
  128. parser.add_argument('--force', '-f', action='store_true', help='run tests even on platforms where they are disabled by default (e.g. windows).')
  129. parser.add_argument('--help', '-h', '-?', action='store_true', help='print help text and exit')
  130. parser.add_argument('--jobs', '-j', type=int, default=4, help='how many test scripts to run in parallel. Default=4.')
  131. parser.add_argument('--nozmq', action='store_true', help='do not run the zmq tests')
  132. args, unknown_args = parser.parse_known_args()
  133. # Create a set to store arguments and create the passon string
  134. tests = set(arg for arg in unknown_args if arg[:2] != "--")
  135. passon_args = [arg for arg in unknown_args if arg[:2] == "--"]
  136. # Read config generated by configure.
  137. config = configparser.ConfigParser()
  138. config.read_file(open(os.path.dirname(__file__) + "/tests_config.ini"))
  139. enable_wallet = config["components"].getboolean("ENABLE_WALLET")
  140. enable_utils = config["components"].getboolean("ENABLE_UTILS")
  141. enable_bitcoind = config["components"].getboolean("ENABLE_BITCOIND")
  142. enable_zmq = config["components"].getboolean("ENABLE_ZMQ") and not args.nozmq
  143. if config["environment"]["EXEEXT"] == ".exe" and not args.force:
  144. # https://github.com/bitcoin/bitcoin/commit/d52802551752140cf41f0d9a225a43e84404d3e9
  145. # https://github.com/bitcoin/bitcoin/pull/5677#issuecomment-136646964
  146. print("Tests currently disabled on Windows by default. Use --force option to enable")
  147. sys.exit(0)
  148. if not (enable_wallet and enable_utils and enable_bitcoind):
  149. print("No functional tests to run. Wallet, utils, and bitcoind must all be enabled")
  150. print("Rerun `configure` with -enable-wallet, -with-utils and -with-daemon and rerun make")
  151. sys.exit(0)
  152. # python3-zmq may not be installed. Handle this gracefully and with some helpful info
  153. if enable_zmq:
  154. try:
  155. import zmq
  156. except ImportError:
  157. print("ERROR: \"import zmq\" failed. Use -nozmq to run without the ZMQ tests."
  158. "To run zmq tests, see dependency info in /test/README.md.")
  159. raise
  160. # Build list of tests
  161. if tests:
  162. # Individual tests have been specified. Run specified tests that exist
  163. # in the ALL_SCRIPTS list. Accept the name with or without .py extension.
  164. test_list = [t for t in ALL_SCRIPTS if
  165. (t in tests or re.sub(".py$", "", t) in tests)]
  166. else:
  167. # No individual tests have been specified. Run base tests, and
  168. # optionally ZMQ tests and extended tests.
  169. test_list = BASE_SCRIPTS
  170. if enable_zmq:
  171. test_list += ZMQ_SCRIPTS
  172. if args.extended:
  173. test_list += EXTENDED_SCRIPTS
  174. # TODO: BASE_SCRIPTS and EXTENDED_SCRIPTS are sorted by runtime
  175. # (for parallel running efficiency). This combined list will is no
  176. # longer sorted.
  177. # Remove the test cases that the user has explicitly asked to exclude.
  178. if args.exclude:
  179. for exclude_test in args.exclude.split(','):
  180. if exclude_test + ".py" in test_list:
  181. test_list.remove(exclude_test + ".py")
  182. if not test_list:
  183. print("No valid test scripts specified. Check that your test is in one "
  184. "of the test lists in rpc-tests.py, or run rpc-tests.py with no arguments to run all tests")
  185. sys.exit(0)
  186. if args.help:
  187. # Print help for rpc-tests.py, then print help of the first script and exit.
  188. parser.print_help()
  189. subprocess.check_call((config["environment"]["SRCDIR"] + '/test/functional/' + test_list[0]).split() + ['-h'])
  190. sys.exit(0)
  191. run_tests(test_list, config["environment"]["SRCDIR"], config["environment"]["BUILDDIR"], config["environment"]["EXEEXT"], args.jobs, args.coverage, passon_args)
  192. def run_tests(test_list, src_dir, build_dir, exeext, jobs=1, enable_coverage=False, args=[]):
  193. BOLD = ("","")
  194. if os.name == 'posix':
  195. # primitive formatting on supported
  196. # terminal via ANSI escape sequences:
  197. BOLD = ('\033[0m', '\033[1m')
  198. #Set env vars
  199. if "BITCOIND" not in os.environ:
  200. os.environ["BITCOIND"] = build_dir + '/src/bitcoind' + exeext
  201. tests_dir = src_dir + '/test/functional/'
  202. flags = ["--srcdir={}/src".format(build_dir)] + args
  203. flags.append("--cachedir=%s/test/cache" % build_dir)
  204. if enable_coverage:
  205. coverage = RPCCoverage()
  206. flags.append(coverage.flag)
  207. print("Initializing coverage directory at %s\n" % coverage.dir)
  208. else:
  209. coverage = None
  210. if len(test_list) > 1 and jobs > 1:
  211. # Populate cache
  212. subprocess.check_output([tests_dir + 'create_cache.py'] + flags)
  213. #Run Tests
  214. all_passed = True
  215. time_sum = 0
  216. time0 = time.time()
  217. job_queue = TestHandler(jobs, tests_dir, test_list, flags)
  218. max_len_name = len(max(test_list, key=len))
  219. results = BOLD[1] + "%s | %s | %s\n\n" % ("TEST".ljust(max_len_name), "PASSED", "DURATION") + BOLD[0]
  220. for _ in range(len(test_list)):
  221. (name, stdout, stderr, passed, duration) = job_queue.get_next()
  222. all_passed = all_passed and passed
  223. time_sum += duration
  224. print('\n' + BOLD[1] + name + BOLD[0] + ":")
  225. print('' if passed else stdout + '\n', end='')
  226. print('' if stderr == '' else 'stderr:\n' + stderr + '\n', end='')
  227. print("Pass: %s%s%s, Duration: %s s\n" % (BOLD[1], passed, BOLD[0], duration))
  228. results += "%s | %s | %s s\n" % (name.ljust(max_len_name), str(passed).ljust(6), duration)
  229. results += BOLD[1] + "\n%s | %s | %s s (accumulated)" % ("ALL".ljust(max_len_name), str(all_passed).ljust(6), time_sum) + BOLD[0]
  230. print(results)
  231. print("\nRuntime: %s s" % (int(time.time() - time0)))
  232. if coverage:
  233. coverage.report_rpc_coverage()
  234. print("Cleaning up coverage data")
  235. coverage.cleanup()
  236. sys.exit(not all_passed)
  237. class TestHandler:
  238. """
  239. Trigger the testscrips passed in via the list.
  240. """
  241. def __init__(self, num_tests_parallel, tests_dir, test_list=None, flags=None):
  242. assert(num_tests_parallel >= 1)
  243. self.num_jobs = num_tests_parallel
  244. self.tests_dir = tests_dir
  245. self.test_list = test_list
  246. self.flags = flags
  247. self.num_running = 0
  248. # In case there is a graveyard of zombie bitcoinds, we can apply a
  249. # pseudorandom offset to hopefully jump over them.
  250. # (625 is PORT_RANGE/MAX_NODES)
  251. self.portseed_offset = int(time.time() * 1000) % 625
  252. self.jobs = []
  253. def get_next(self):
  254. while self.num_running < self.num_jobs and self.test_list:
  255. # Add tests
  256. self.num_running += 1
  257. t = self.test_list.pop(0)
  258. port_seed = ["--portseed={}".format(len(self.test_list) + self.portseed_offset)]
  259. log_stdout = tempfile.SpooledTemporaryFile(max_size=2**16)
  260. log_stderr = tempfile.SpooledTemporaryFile(max_size=2**16)
  261. self.jobs.append((t,
  262. time.time(),
  263. subprocess.Popen((self.tests_dir + t).split() + self.flags + port_seed,
  264. universal_newlines=True,
  265. stdout=log_stdout,
  266. stderr=log_stderr),
  267. log_stdout,
  268. log_stderr))
  269. if not self.jobs:
  270. raise IndexError('pop from empty list')
  271. while True:
  272. # Return first proc that finishes
  273. time.sleep(.5)
  274. for j in self.jobs:
  275. (name, time0, proc, log_out, log_err) = j
  276. if proc.poll() is not None:
  277. log_out.seek(0), log_err.seek(0)
  278. [stdout, stderr] = [l.read().decode('utf-8') for l in (log_out, log_err)]
  279. log_out.close(), log_err.close()
  280. passed = stderr == "" and proc.returncode == 0
  281. self.num_running -= 1
  282. self.jobs.remove(j)
  283. return name, stdout, stderr, passed, int(time.time() - time0)
  284. print('.', end='', flush=True)
  285. class RPCCoverage(object):
  286. """
  287. Coverage reporting utilities for pull-tester.
  288. Coverage calculation works by having each test script subprocess write
  289. coverage files into a particular directory. These files contain the RPC
  290. commands invoked during testing, as well as a complete listing of RPC
  291. commands per `bitcoin-cli help` (`rpc_interface.txt`).
  292. After all tests complete, the commands run are combined and diff'd against
  293. the complete list to calculate uncovered RPC commands.
  294. See also: test/functional/test_framework/coverage.py
  295. """
  296. def __init__(self):
  297. self.dir = tempfile.mkdtemp(prefix="coverage")
  298. self.flag = '--coveragedir=%s' % self.dir
  299. def report_rpc_coverage(self):
  300. """
  301. Print out RPC commands that were unexercised by tests.
  302. """
  303. uncovered = self._get_uncovered_rpc_commands()
  304. if uncovered:
  305. print("Uncovered RPC commands:")
  306. print("".join((" - %s\n" % i) for i in sorted(uncovered)))
  307. else:
  308. print("All RPC commands covered.")
  309. def cleanup(self):
  310. return shutil.rmtree(self.dir)
  311. def _get_uncovered_rpc_commands(self):
  312. """
  313. Return a set of currently untested RPC commands.
  314. """
  315. # This is shared from `test/functional/test-framework/coverage.py`
  316. reference_filename = 'rpc_interface.txt'
  317. coverage_file_prefix = 'coverage.'
  318. coverage_ref_filename = os.path.join(self.dir, reference_filename)
  319. coverage_filenames = set()
  320. all_cmds = set()
  321. covered_cmds = set()
  322. if not os.path.isfile(coverage_ref_filename):
  323. raise RuntimeError("No coverage reference found")
  324. with open(coverage_ref_filename, 'r') as f:
  325. all_cmds.update([i.strip() for i in f.readlines()])
  326. for root, dirs, files in os.walk(self.dir):
  327. for filename in files:
  328. if filename.startswith(coverage_file_prefix):
  329. coverage_filenames.add(os.path.join(root, filename))
  330. for filename in coverage_filenames:
  331. with open(filename, 'r') as f:
  332. covered_cmds.update([i.strip() for i in f.readlines()])
  333. return all_cmds - covered_cmds
  334. if __name__ == '__main__':
  335. main()