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.

test_runner.py 18KB

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