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_framework.py 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2014-2017 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. """Base class for RPC testing."""
  6. from enum import Enum
  7. import logging
  8. import optparse
  9. import os
  10. import pdb
  11. import shutil
  12. import sys
  13. import tempfile
  14. import time
  15. from .authproxy import JSONRPCException
  16. from . import coverage
  17. from .test_node import TestNode
  18. from .util import (
  19. MAX_NODES,
  20. PortSeed,
  21. assert_equal,
  22. check_json_precision,
  23. connect_nodes_bi,
  24. disconnect_nodes,
  25. initialize_datadir,
  26. log_filename,
  27. p2p_port,
  28. set_node_times,
  29. sync_blocks,
  30. sync_mempools,
  31. )
  32. class TestStatus(Enum):
  33. PASSED = 1
  34. FAILED = 2
  35. SKIPPED = 3
  36. TEST_EXIT_PASSED = 0
  37. TEST_EXIT_FAILED = 1
  38. TEST_EXIT_SKIPPED = 77
  39. class BitcoinTestFramework():
  40. """Base class for a bitcoin test script.
  41. Individual bitcoin test scripts should subclass this class and override the set_test_params() and run_test() methods.
  42. Individual tests can also override the following methods to customize the test setup:
  43. - add_options()
  44. - setup_chain()
  45. - setup_network()
  46. - setup_nodes()
  47. The __init__() and main() methods should not be overridden.
  48. This class also contains various public and private helper methods."""
  49. def __init__(self):
  50. """Sets test framework defaults. Do not override this method. Instead, override the set_test_params() method"""
  51. self.setup_clean_chain = False
  52. self.nodes = []
  53. self.mocktime = 0
  54. self.supports_cli = False
  55. self.set_test_params()
  56. assert hasattr(self, "num_nodes"), "Test must set self.num_nodes in set_test_params()"
  57. def main(self):
  58. """Main function. This should not be overridden by the subclass test scripts."""
  59. parser = optparse.OptionParser(usage="%prog [options]")
  60. parser.add_option("--nocleanup", dest="nocleanup", default=False, action="store_true",
  61. help="Leave bitcoinds and test.* datadir on exit or error")
  62. parser.add_option("--noshutdown", dest="noshutdown", default=False, action="store_true",
  63. help="Don't stop bitcoinds after the test execution")
  64. parser.add_option("--srcdir", dest="srcdir", default=os.path.normpath(os.path.dirname(os.path.realpath(__file__)) + "/../../../src"),
  65. help="Source directory containing bitcoind/bitcoin-cli (default: %default)")
  66. parser.add_option("--cachedir", dest="cachedir", default=os.path.normpath(os.path.dirname(os.path.realpath(__file__)) + "/../../cache"),
  67. help="Directory for caching pregenerated datadirs")
  68. parser.add_option("--tmpdir", dest="tmpdir", help="Root directory for datadirs")
  69. parser.add_option("-l", "--loglevel", dest="loglevel", default="INFO",
  70. help="log events at this level and higher to the console. Can be set to DEBUG, INFO, WARNING, ERROR or CRITICAL. Passing --loglevel DEBUG will output all logs to console. Note that logs at all levels are always written to the test_framework.log file in the temporary test directory.")
  71. parser.add_option("--tracerpc", dest="trace_rpc", default=False, action="store_true",
  72. help="Print out all RPC calls as they are made")
  73. parser.add_option("--portseed", dest="port_seed", default=os.getpid(), type='int',
  74. help="The seed to use for assigning port numbers (default: current process id)")
  75. parser.add_option("--coveragedir", dest="coveragedir",
  76. help="Write tested RPC commands into this directory")
  77. parser.add_option("--configfile", dest="configfile",
  78. help="Location of the test framework config file")
  79. parser.add_option("--pdbonfailure", dest="pdbonfailure", default=False, action="store_true",
  80. help="Attach a python debugger if test fails")
  81. parser.add_option("--usecli", dest="usecli", default=False, action="store_true",
  82. help="use bitcoin-cli instead of RPC for all commands")
  83. self.add_options(parser)
  84. (self.options, self.args) = parser.parse_args()
  85. PortSeed.n = self.options.port_seed
  86. os.environ['PATH'] = self.options.srcdir + ":" + self.options.srcdir + "/qt:" + os.environ['PATH']
  87. check_json_precision()
  88. self.options.cachedir = os.path.abspath(self.options.cachedir)
  89. # Set up temp directory and start logging
  90. if self.options.tmpdir:
  91. self.options.tmpdir = os.path.abspath(self.options.tmpdir)
  92. os.makedirs(self.options.tmpdir, exist_ok=False)
  93. else:
  94. self.options.tmpdir = tempfile.mkdtemp(prefix="test")
  95. self._start_logging()
  96. success = TestStatus.FAILED
  97. try:
  98. if self.options.usecli and not self.supports_cli:
  99. raise SkipTest("--usecli specified but test does not support using CLI")
  100. self.setup_chain()
  101. self.setup_network()
  102. self.run_test()
  103. success = TestStatus.PASSED
  104. except JSONRPCException as e:
  105. self.log.exception("JSONRPC error")
  106. except SkipTest as e:
  107. self.log.warning("Test Skipped: %s" % e.message)
  108. success = TestStatus.SKIPPED
  109. except AssertionError as e:
  110. self.log.exception("Assertion failed")
  111. except KeyError as e:
  112. self.log.exception("Key error")
  113. except Exception as e:
  114. self.log.exception("Unexpected exception caught during testing")
  115. except KeyboardInterrupt as e:
  116. self.log.warning("Exiting after keyboard interrupt")
  117. if success == TestStatus.FAILED and self.options.pdbonfailure:
  118. print("Testcase failed. Attaching python debugger. Enter ? for help")
  119. pdb.set_trace()
  120. if not self.options.noshutdown:
  121. self.log.info("Stopping nodes")
  122. if self.nodes:
  123. self.stop_nodes()
  124. else:
  125. for node in self.nodes:
  126. node.cleanup_on_exit = False
  127. self.log.info("Note: bitcoinds were not stopped and may still be running")
  128. if not self.options.nocleanup and not self.options.noshutdown and success != TestStatus.FAILED:
  129. self.log.info("Cleaning up")
  130. shutil.rmtree(self.options.tmpdir)
  131. else:
  132. self.log.warning("Not cleaning up dir %s" % self.options.tmpdir)
  133. if success == TestStatus.PASSED:
  134. self.log.info("Tests successful")
  135. exit_code = TEST_EXIT_PASSED
  136. elif success == TestStatus.SKIPPED:
  137. self.log.info("Test skipped")
  138. exit_code = TEST_EXIT_SKIPPED
  139. else:
  140. self.log.error("Test failed. Test logging available at %s/test_framework.log", self.options.tmpdir)
  141. self.log.error("Hint: Call {} '{}' to consolidate all logs".format(os.path.normpath(os.path.dirname(os.path.realpath(__file__)) + "/../combine_logs.py"), self.options.tmpdir))
  142. exit_code = TEST_EXIT_FAILED
  143. logging.shutdown()
  144. sys.exit(exit_code)
  145. # Methods to override in subclass test scripts.
  146. def set_test_params(self):
  147. """Tests must this method to change default values for number of nodes, topology, etc"""
  148. raise NotImplementedError
  149. def add_options(self, parser):
  150. """Override this method to add command-line options to the test"""
  151. pass
  152. def setup_chain(self):
  153. """Override this method to customize blockchain setup"""
  154. self.log.info("Initializing test directory " + self.options.tmpdir)
  155. if self.setup_clean_chain:
  156. self._initialize_chain_clean()
  157. else:
  158. self._initialize_chain()
  159. def setup_network(self):
  160. """Override this method to customize test network topology"""
  161. self.setup_nodes()
  162. # Connect the nodes as a "chain". This allows us
  163. # to split the network between nodes 1 and 2 to get
  164. # two halves that can work on competing chains.
  165. for i in range(self.num_nodes - 1):
  166. connect_nodes_bi(self.nodes, i, i + 1)
  167. self.sync_all()
  168. def setup_nodes(self):
  169. """Override this method to customize test node setup"""
  170. extra_args = None
  171. if hasattr(self, "extra_args"):
  172. extra_args = self.extra_args
  173. self.add_nodes(self.num_nodes, extra_args)
  174. self.start_nodes()
  175. def run_test(self):
  176. """Tests must override this method to define test logic"""
  177. raise NotImplementedError
  178. # Public helper methods. These can be accessed by the subclass test scripts.
  179. def add_nodes(self, num_nodes, extra_args=None, rpchost=None, timewait=None, binary=None):
  180. """Instantiate TestNode objects"""
  181. if extra_args is None:
  182. extra_args = [[]] * num_nodes
  183. if binary is None:
  184. binary = [None] * num_nodes
  185. assert_equal(len(extra_args), num_nodes)
  186. assert_equal(len(binary), num_nodes)
  187. for i in range(num_nodes):
  188. self.nodes.append(TestNode(i, self.options.tmpdir, extra_args[i], rpchost, timewait=timewait, binary=binary[i], stderr=None, mocktime=self.mocktime, coverage_dir=self.options.coveragedir, use_cli=self.options.usecli))
  189. def start_node(self, i, *args, **kwargs):
  190. """Start a bitcoind"""
  191. node = self.nodes[i]
  192. node.start(*args, **kwargs)
  193. node.wait_for_rpc_connection()
  194. if self.options.coveragedir is not None:
  195. coverage.write_all_rpc_commands(self.options.coveragedir, node.rpc)
  196. def start_nodes(self, extra_args=None, *args, **kwargs):
  197. """Start multiple bitcoinds"""
  198. if extra_args is None:
  199. extra_args = [None] * self.num_nodes
  200. assert_equal(len(extra_args), self.num_nodes)
  201. try:
  202. for i, node in enumerate(self.nodes):
  203. node.start(extra_args[i], *args, **kwargs)
  204. for node in self.nodes:
  205. node.wait_for_rpc_connection()
  206. except:
  207. # If one node failed to start, stop the others
  208. self.stop_nodes()
  209. raise
  210. if self.options.coveragedir is not None:
  211. for node in self.nodes:
  212. coverage.write_all_rpc_commands(self.options.coveragedir, node.rpc)
  213. def stop_node(self, i):
  214. """Stop a bitcoind test node"""
  215. self.nodes[i].stop_node()
  216. self.nodes[i].wait_until_stopped()
  217. def stop_nodes(self):
  218. """Stop multiple bitcoind test nodes"""
  219. for node in self.nodes:
  220. # Issue RPC to stop nodes
  221. node.stop_node()
  222. for node in self.nodes:
  223. # Wait for nodes to stop
  224. node.wait_until_stopped()
  225. def restart_node(self, i, extra_args=None):
  226. """Stop and start a test node"""
  227. self.stop_node(i)
  228. self.start_node(i, extra_args)
  229. def assert_start_raises_init_error(self, i, extra_args=None, expected_msg=None, *args, **kwargs):
  230. with tempfile.SpooledTemporaryFile(max_size=2**16) as log_stderr:
  231. try:
  232. self.start_node(i, extra_args, stderr=log_stderr, *args, **kwargs)
  233. self.stop_node(i)
  234. except Exception as e:
  235. assert 'bitcoind exited' in str(e) # node must have shutdown
  236. self.nodes[i].running = False
  237. self.nodes[i].process = None
  238. if expected_msg is not None:
  239. log_stderr.seek(0)
  240. stderr = log_stderr.read().decode('utf-8')
  241. if expected_msg not in stderr:
  242. raise AssertionError("Expected error \"" + expected_msg + "\" not found in:\n" + stderr)
  243. else:
  244. if expected_msg is None:
  245. assert_msg = "bitcoind should have exited with an error"
  246. else:
  247. assert_msg = "bitcoind should have exited with expected error " + expected_msg
  248. raise AssertionError(assert_msg)
  249. def wait_for_node_exit(self, i, timeout):
  250. self.nodes[i].process.wait(timeout)
  251. def split_network(self):
  252. """
  253. Split the network of four nodes into nodes 0/1 and 2/3.
  254. """
  255. disconnect_nodes(self.nodes[1], 2)
  256. disconnect_nodes(self.nodes[2], 1)
  257. self.sync_all([self.nodes[:2], self.nodes[2:]])
  258. def join_network(self):
  259. """
  260. Join the (previously split) network halves together.
  261. """
  262. connect_nodes_bi(self.nodes, 1, 2)
  263. self.sync_all()
  264. def sync_all(self, node_groups=None):
  265. if not node_groups:
  266. node_groups = [self.nodes]
  267. for group in node_groups:
  268. sync_blocks(group)
  269. sync_mempools(group)
  270. def enable_mocktime(self):
  271. """Enable mocktime for the script.
  272. mocktime may be needed for scripts that use the cached version of the
  273. blockchain. If the cached version of the blockchain is used without
  274. mocktime then the mempools will not sync due to IBD.
  275. For backwared compatibility of the python scripts with previous
  276. versions of the cache, this helper function sets mocktime to Jan 1,
  277. 2014 + (201 * 10 * 60)"""
  278. self.mocktime = 1388534400 + (201 * 10 * 60)
  279. def disable_mocktime(self):
  280. self.mocktime = 0
  281. # Private helper methods. These should not be accessed by the subclass test scripts.
  282. def _start_logging(self):
  283. # Add logger and logging handlers
  284. self.log = logging.getLogger('TestFramework')
  285. self.log.setLevel(logging.DEBUG)
  286. # Create file handler to log all messages
  287. fh = logging.FileHandler(self.options.tmpdir + '/test_framework.log')
  288. fh.setLevel(logging.DEBUG)
  289. # Create console handler to log messages to stderr. By default this logs only error messages, but can be configured with --loglevel.
  290. ch = logging.StreamHandler(sys.stdout)
  291. # User can provide log level as a number or string (eg DEBUG). loglevel was caught as a string, so try to convert it to an int
  292. ll = int(self.options.loglevel) if self.options.loglevel.isdigit() else self.options.loglevel.upper()
  293. ch.setLevel(ll)
  294. # Format logs the same as bitcoind's debug.log with microprecision (so log files can be concatenated and sorted)
  295. formatter = logging.Formatter(fmt='%(asctime)s.%(msecs)03d000 %(name)s (%(levelname)s): %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
  296. formatter.converter = time.gmtime
  297. fh.setFormatter(formatter)
  298. ch.setFormatter(formatter)
  299. # add the handlers to the logger
  300. self.log.addHandler(fh)
  301. self.log.addHandler(ch)
  302. if self.options.trace_rpc:
  303. rpc_logger = logging.getLogger("BitcoinRPC")
  304. rpc_logger.setLevel(logging.DEBUG)
  305. rpc_handler = logging.StreamHandler(sys.stdout)
  306. rpc_handler.setLevel(logging.DEBUG)
  307. rpc_logger.addHandler(rpc_handler)
  308. def _initialize_chain(self):
  309. """Initialize a pre-mined blockchain for use by the test.
  310. Create a cache of a 200-block-long chain (with wallet) for MAX_NODES
  311. Afterward, create num_nodes copies from the cache."""
  312. assert self.num_nodes <= MAX_NODES
  313. create_cache = False
  314. for i in range(MAX_NODES):
  315. if not os.path.isdir(os.path.join(self.options.cachedir, 'node' + str(i))):
  316. create_cache = True
  317. break
  318. if create_cache:
  319. self.log.debug("Creating data directories from cached datadir")
  320. # find and delete old cache directories if any exist
  321. for i in range(MAX_NODES):
  322. if os.path.isdir(os.path.join(self.options.cachedir, "node" + str(i))):
  323. shutil.rmtree(os.path.join(self.options.cachedir, "node" + str(i)))
  324. # Create cache directories, run bitcoinds:
  325. for i in range(MAX_NODES):
  326. datadir = initialize_datadir(self.options.cachedir, i)
  327. args = [os.getenv("BITCOIND", "bitcoind"), "-server", "-keypool=1", "-datadir=" + datadir, "-discover=0"]
  328. if i > 0:
  329. args.append("-connect=127.0.0.1:" + str(p2p_port(0)))
  330. self.nodes.append(TestNode(i, self.options.cachedir, extra_args=[], rpchost=None, timewait=None, binary=None, stderr=None, mocktime=self.mocktime, coverage_dir=None))
  331. self.nodes[i].args = args
  332. self.start_node(i)
  333. # Wait for RPC connections to be ready
  334. for node in self.nodes:
  335. node.wait_for_rpc_connection()
  336. # Create a 200-block-long chain; each of the 4 first nodes
  337. # gets 25 mature blocks and 25 immature.
  338. # Note: To preserve compatibility with older versions of
  339. # initialize_chain, only 4 nodes will generate coins.
  340. #
  341. # blocks are created with timestamps 10 minutes apart
  342. # starting from 2010 minutes in the past
  343. self.enable_mocktime()
  344. block_time = self.mocktime - (201 * 10 * 60)
  345. for i in range(2):
  346. for peer in range(4):
  347. for j in range(25):
  348. set_node_times(self.nodes, block_time)
  349. self.nodes[peer].generate(1)
  350. block_time += 10 * 60
  351. # Must sync before next peer starts generating blocks
  352. sync_blocks(self.nodes)
  353. # Shut them down, and clean up cache directories:
  354. self.stop_nodes()
  355. self.nodes = []
  356. self.disable_mocktime()
  357. for i in range(MAX_NODES):
  358. os.remove(log_filename(self.options.cachedir, i, "debug.log"))
  359. os.remove(log_filename(self.options.cachedir, i, "wallets/db.log"))
  360. os.remove(log_filename(self.options.cachedir, i, "peers.dat"))
  361. os.remove(log_filename(self.options.cachedir, i, "fee_estimates.dat"))
  362. for i in range(self.num_nodes):
  363. from_dir = os.path.join(self.options.cachedir, "node" + str(i))
  364. to_dir = os.path.join(self.options.tmpdir, "node" + str(i))
  365. shutil.copytree(from_dir, to_dir)
  366. initialize_datadir(self.options.tmpdir, i) # Overwrite port/rpcport in bitcoin.conf
  367. def _initialize_chain_clean(self):
  368. """Initialize empty blockchain for use by the test.
  369. Create an empty blockchain and num_nodes wallets.
  370. Useful if a test case wants complete control over initialization."""
  371. for i in range(self.num_nodes):
  372. initialize_datadir(self.options.tmpdir, i)
  373. class ComparisonTestFramework(BitcoinTestFramework):
  374. """Test framework for doing p2p comparison testing
  375. Sets up some bitcoind binaries:
  376. - 1 binary: test binary
  377. - 2 binaries: 1 test binary, 1 ref binary
  378. - n>2 binaries: 1 test binary, n-1 ref binaries"""
  379. def set_test_params(self):
  380. self.num_nodes = 2
  381. self.setup_clean_chain = True
  382. def add_options(self, parser):
  383. parser.add_option("--testbinary", dest="testbinary",
  384. default=os.getenv("BITCOIND", "bitcoind"),
  385. help="bitcoind binary to test")
  386. parser.add_option("--refbinary", dest="refbinary",
  387. default=os.getenv("BITCOIND", "bitcoind"),
  388. help="bitcoind binary to use for reference nodes (if any)")
  389. def setup_network(self):
  390. extra_args = [['-whitelist=127.0.0.1']] * self.num_nodes
  391. if hasattr(self, "extra_args"):
  392. extra_args = self.extra_args
  393. self.add_nodes(self.num_nodes, extra_args,
  394. binary=[self.options.testbinary] +
  395. [self.options.refbinary] * (self.num_nodes - 1))
  396. self.start_nodes()
  397. class SkipTest(Exception):
  398. """This exception is raised to skip a test"""
  399. def __init__(self, message):
  400. self.message = message