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

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