Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

test_framework.py 6.6KB

6 anos atrás
6 anos atrás
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. #!/usr/bin/env python2
  2. # Copyright (c) 2014 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. # Add python-bitcoinrpc to module search path:
  7. import os
  8. import sys
  9. import shutil
  10. import tempfile
  11. import traceback
  12. from .util import (
  13. initialize_chain,
  14. assert_equal,
  15. start_nodes,
  16. connect_nodes_bi,
  17. sync_blocks,
  18. sync_mempools,
  19. stop_nodes,
  20. wait_bitcoinds,
  21. enable_coverage,
  22. check_json_precision,
  23. initialize_chain_clean,
  24. )
  25. from authproxy import AuthServiceProxy, JSONRPCException
  26. class BitcoinTestFramework(object):
  27. # These may be over-ridden by subclasses:
  28. def run_test(self):
  29. for node in self.nodes:
  30. assert_equal(node.getblockcount(), 200)
  31. assert_equal(node.getbalance(), 25*50)
  32. def add_options(self, parser):
  33. pass
  34. def setup_chain(self):
  35. print("Initializing test directory "+self.options.tmpdir)
  36. initialize_chain(self.options.tmpdir)
  37. def setup_nodes(self):
  38. return start_nodes(4, self.options.tmpdir)
  39. def setup_network(self, split = False):
  40. self.nodes = self.setup_nodes()
  41. # Connect the nodes as a "chain". This allows us
  42. # to split the network between nodes 1 and 2 to get
  43. # two halves that can work on competing chains.
  44. # If we joined network halves, connect the nodes from the joint
  45. # on outward. This ensures that chains are properly reorganised.
  46. if not split:
  47. connect_nodes_bi(self.nodes, 1, 2)
  48. sync_blocks(self.nodes[1:3])
  49. sync_mempools(self.nodes[1:3])
  50. connect_nodes_bi(self.nodes, 0, 1)
  51. connect_nodes_bi(self.nodes, 2, 3)
  52. self.is_network_split = split
  53. self.sync_all()
  54. def split_network(self):
  55. """
  56. Split the network of four nodes into nodes 0/1 and 2/3.
  57. """
  58. assert not self.is_network_split
  59. stop_nodes(self.nodes)
  60. wait_bitcoinds()
  61. self.setup_network(True)
  62. def sync_all(self):
  63. if self.is_network_split:
  64. sync_blocks(self.nodes[:2])
  65. sync_blocks(self.nodes[2:])
  66. sync_mempools(self.nodes[:2])
  67. sync_mempools(self.nodes[2:])
  68. else:
  69. sync_blocks(self.nodes)
  70. sync_mempools(self.nodes)
  71. def join_network(self):
  72. """
  73. Join the (previously split) network halves together.
  74. """
  75. assert self.is_network_split
  76. stop_nodes(self.nodes)
  77. wait_bitcoinds()
  78. self.setup_network(False)
  79. def main(self):
  80. import optparse
  81. parser = optparse.OptionParser(usage="%prog [options]")
  82. parser.add_option("--nocleanup", dest="nocleanup", default=False, action="store_true",
  83. help="Leave bitcoinds and test.* datadir on exit or error")
  84. parser.add_option("--noshutdown", dest="noshutdown", default=False, action="store_true",
  85. help="Don't stop bitcoinds after the test execution")
  86. parser.add_option("--srcdir", dest="srcdir", default="../../src",
  87. help="Source directory containing bitcoind/bitcoin-cli (default: %default)")
  88. parser.add_option("--tmpdir", dest="tmpdir", default=tempfile.mkdtemp(prefix="test"),
  89. help="Root directory for datadirs")
  90. parser.add_option("--tracerpc", dest="trace_rpc", default=False, action="store_true",
  91. help="Print out all RPC calls as they are made")
  92. parser.add_option("--coveragedir", dest="coveragedir",
  93. help="Write tested RPC commands into this directory")
  94. self.add_options(parser)
  95. (self.options, self.args) = parser.parse_args()
  96. if self.options.trace_rpc:
  97. import logging
  98. logging.basicConfig(level=logging.DEBUG)
  99. if self.options.coveragedir:
  100. enable_coverage(self.options.coveragedir)
  101. os.environ['PATH'] = self.options.srcdir+":"+os.environ['PATH']
  102. check_json_precision()
  103. success = False
  104. try:
  105. if not os.path.isdir(self.options.tmpdir):
  106. os.makedirs(self.options.tmpdir)
  107. self.setup_chain()
  108. self.setup_network()
  109. self.run_test()
  110. success = True
  111. except JSONRPCException as e:
  112. print("JSONRPC error: "+e.error['message'])
  113. traceback.print_tb(sys.exc_info()[2])
  114. except AssertionError as e:
  115. print("Assertion failed: "+e.message)
  116. traceback.print_tb(sys.exc_info()[2])
  117. except Exception as e:
  118. print("Unexpected exception caught during testing: "+str(e))
  119. traceback.print_tb(sys.exc_info()[2])
  120. if not self.options.noshutdown:
  121. print("Stopping nodes")
  122. stop_nodes(self.nodes)
  123. wait_bitcoinds()
  124. else:
  125. print("Note: bitcoinds were not stopped and may still be running")
  126. if not self.options.nocleanup and not self.options.noshutdown:
  127. print("Cleaning up")
  128. shutil.rmtree(self.options.tmpdir)
  129. if success:
  130. print("Tests successful")
  131. sys.exit(0)
  132. else:
  133. print("Failed")
  134. sys.exit(1)
  135. # Test framework for doing p2p comparison testing, which sets up some bitcoind
  136. # binaries:
  137. # 1 binary: test binary
  138. # 2 binaries: 1 test binary, 1 ref binary
  139. # n>2 binaries: 1 test binary, n-1 ref binaries
  140. class ComparisonTestFramework(BitcoinTestFramework):
  141. # Can override the num_nodes variable to indicate how many nodes to run.
  142. def __init__(self):
  143. self.num_nodes = 2
  144. def add_options(self, parser):
  145. parser.add_option("--testbinary", dest="testbinary",
  146. default=os.getenv("BITCOIND", "bitcoind"),
  147. help="bitcoind binary to test")
  148. parser.add_option("--refbinary", dest="refbinary",
  149. default=os.getenv("BITCOIND", "bitcoind"),
  150. help="bitcoind binary to use for reference nodes (if any)")
  151. def setup_chain(self):
  152. print "Initializing test directory "+self.options.tmpdir
  153. initialize_chain_clean(self.options.tmpdir, self.num_nodes)
  154. def setup_network(self):
  155. self.nodes = start_nodes(
  156. self.num_nodes, self.options.tmpdir,
  157. extra_args=[['-debug', '-whitelist=127.0.0.1']] * self.num_nodes,
  158. binary=[self.options.testbinary] +
  159. [self.options.refbinary]*(self.num_nodes-1))