Skip to content

Commit d138598

Browse files
gavinandresenlaanwj
authored andcommitted
Fix regression tests
Taught bitcoind to close the HTTP connection after it gets a 'stop' command, to make it easier for the regression tests to cleanly stop. Move bitcoinrpc files to correct location. Tidied up the python-based regression tests.
1 parent d3c3210 commit d138598

File tree

8 files changed

+187
-18
lines changed

8 files changed

+187
-18
lines changed

qa/rpc-tests/listtransactions.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,7 @@ def main():
118118
check_json_precision()
119119

120120
success = False
121+
nodes = []
121122
try:
122123
print("Initializing test directory "+options.tmpdir)
123124
if not os.path.isdir(options.tmpdir):
@@ -127,6 +128,7 @@ def main():
127128
nodes = start_nodes(2, options.tmpdir)
128129
connect_nodes(nodes[1], 0)
129130
sync_blocks(nodes)
131+
130132
run_test(nodes)
131133

132134
success = True
@@ -135,12 +137,12 @@ def main():
135137
print("Assertion failed: "+e.message)
136138
except Exception as e:
137139
print("Unexpected exception caught during testing: "+str(e))
138-
stack = traceback.extract_tb(sys.exc_info()[2])
139-
print(stack[-1])
140+
traceback.print_tb(sys.exc_info()[2])
140141

141142
if not options.nocleanup:
142143
print("Cleaning up")
143-
stop_nodes()
144+
stop_nodes(nodes)
145+
wait_bitcoinds()
144146
shutil.rmtree(options.tmpdir)
145147

146148
if success:
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
*.pyc

qa/rpc-tests/python-bitcoinrpc/bitcoinrpc/__init__.py

Whitespace-only changes.
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
2+
"""
3+
Copyright 2011 Jeff Garzik
4+
5+
AuthServiceProxy has the following improvements over python-jsonrpc's
6+
ServiceProxy class:
7+
8+
- HTTP connections persist for the life of the AuthServiceProxy object
9+
(if server supports HTTP/1.1)
10+
- sends protocol 'version', per JSON-RPC 1.1
11+
- sends proper, incrementing 'id'
12+
- sends Basic HTTP authentication headers
13+
- parses all JSON numbers that look like floats as Decimal
14+
- uses standard Python json lib
15+
16+
Previous copyright, from python-jsonrpc/jsonrpc/proxy.py:
17+
18+
Copyright (c) 2007 Jan-Klaas Kollhof
19+
20+
This file is part of jsonrpc.
21+
22+
jsonrpc is free software; you can redistribute it and/or modify
23+
it under the terms of the GNU Lesser General Public License as published by
24+
the Free Software Foundation; either version 2.1 of the License, or
25+
(at your option) any later version.
26+
27+
This software is distributed in the hope that it will be useful,
28+
but WITHOUT ANY WARRANTY; without even the implied warranty of
29+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
30+
GNU Lesser General Public License for more details.
31+
32+
You should have received a copy of the GNU Lesser General Public License
33+
along with this software; if not, write to the Free Software
34+
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
35+
"""
36+
37+
try:
38+
import http.client as httplib
39+
except ImportError:
40+
import httplib
41+
import base64
42+
import json
43+
import decimal
44+
try:
45+
import urllib.parse as urlparse
46+
except ImportError:
47+
import urlparse
48+
49+
USER_AGENT = "AuthServiceProxy/0.1"
50+
51+
HTTP_TIMEOUT = 30
52+
53+
54+
class JSONRPCException(Exception):
55+
def __init__(self, rpc_error):
56+
Exception.__init__(self)
57+
self.error = rpc_error
58+
59+
60+
class AuthServiceProxy(object):
61+
def __init__(self, service_url, service_name=None, timeout=HTTP_TIMEOUT, connection=None):
62+
self.__service_url = service_url
63+
self.__service_name = service_name
64+
self.__url = urlparse.urlparse(service_url)
65+
if self.__url.port is None:
66+
port = 80
67+
else:
68+
port = self.__url.port
69+
self.__id_count = 0
70+
(user, passwd) = (self.__url.username, self.__url.password)
71+
try:
72+
user = user.encode('utf8')
73+
except AttributeError:
74+
pass
75+
try:
76+
passwd = passwd.encode('utf8')
77+
except AttributeError:
78+
pass
79+
authpair = user + b':' + passwd
80+
self.__auth_header = b'Basic ' + base64.b64encode(authpair)
81+
82+
if connection:
83+
# Callables re-use the connection of the original proxy
84+
self.__conn = connection
85+
elif self.__url.scheme == 'https':
86+
self.__conn = httplib.HTTPSConnection(self.__url.hostname, port,
87+
None, None, False,
88+
timeout)
89+
else:
90+
self.__conn = httplib.HTTPConnection(self.__url.hostname, port,
91+
False, timeout)
92+
93+
def __getattr__(self, name):
94+
if name.startswith('__') and name.endswith('__'):
95+
# Python internal stuff
96+
raise AttributeError
97+
if self.__service_name is not None:
98+
name = "%s.%s" % (self.__service_name, name)
99+
return AuthServiceProxy(self.__service_url, name, connection=self.__conn)
100+
101+
def __call__(self, *args):
102+
self.__id_count += 1
103+
104+
postdata = json.dumps({'version': '1.1',
105+
'method': self.__service_name,
106+
'params': args,
107+
'id': self.__id_count})
108+
self.__conn.request('POST', self.__url.path, postdata,
109+
{'Host': self.__url.hostname,
110+
'User-Agent': USER_AGENT,
111+
'Authorization': self.__auth_header,
112+
'Content-type': 'application/json'})
113+
114+
response = self._get_response()
115+
if response['error'] is not None:
116+
raise JSONRPCException(response['error'])
117+
elif 'result' not in response:
118+
raise JSONRPCException({
119+
'code': -343, 'message': 'missing JSON-RPC result'})
120+
else:
121+
return response['result']
122+
123+
def _batch(self, rpc_call_list):
124+
postdata = json.dumps(list(rpc_call_list))
125+
self.__conn.request('POST', self.__url.path, postdata,
126+
{'Host': self.__url.hostname,
127+
'User-Agent': USER_AGENT,
128+
'Authorization': self.__auth_header,
129+
'Content-type': 'application/json'})
130+
131+
return self._get_response()
132+
133+
def _get_response(self):
134+
http_response = self.__conn.getresponse()
135+
if http_response is None:
136+
raise JSONRPCException({
137+
'code': -342, 'message': 'missing HTTP response from server'})
138+
139+
return json.loads(http_response.read().decode('utf8'),
140+
parse_float=decimal.Decimal)
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
#!/usr/bin/env python
2+
3+
from distutils.core import setup
4+
5+
setup(name='python-bitcoinrpc',
6+
version='0.1',
7+
description='Enhanced version of python-jsonrpc for use with Bitcoin',
8+
long_description=open('README').read(),
9+
author='Jeff Garzik',
10+
author_email='<[email protected]>',
11+
maintainer='Jeff Garzik',
12+
maintainer_email='<[email protected]>',
13+
url='http://www.github.com/jgarzik/python-bitcoinrpc',
14+
packages=['bitcoinrpc'],
15+
classifiers=['License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'Operating System :: OS Independent'])

qa/rpc-tests/skeleton.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ def main():
4545
check_json_precision()
4646

4747
success = False
48+
nodes = []
4849
try:
4950
print("Initializing test directory "+options.tmpdir)
5051
if not os.path.isdir(options.tmpdir):
@@ -63,12 +64,12 @@ def main():
6364
print("Assertion failed: "+e.message)
6465
except Exception as e:
6566
print("Unexpected exception caught during testing: "+str(e))
66-
stack = traceback.extract_tb(sys.exc_info()[2])
67-
print(stack[-1])
67+
traceback.print_tb(sys.exc_info()[2])
6868

6969
if not options.nocleanup:
7070
print("Cleaning up")
71-
stop_nodes()
71+
stop_nodes(nodes)
72+
wait_bitcoinds()
7273
shutil.rmtree(options.tmpdir)
7374

7475
if success:

qa/rpc-tests/util.py

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,8 @@ def sync_mempools(rpc_connections):
5555
time.sleep(1)
5656

5757

58+
bitcoind_processes = []
59+
5860
def initialize_chain(test_dir):
5961
"""
6062
Create (or copy from cache) a 200-block-long chain and
@@ -64,7 +66,6 @@ def initialize_chain(test_dir):
6466

6567
if not os.path.isdir(os.path.join("cache", "node0")):
6668
# Create cache directories, run bitcoinds:
67-
bitcoinds = []
6869
for i in range(4):
6970
datadir = os.path.join("cache", "node"+str(i))
7071
os.makedirs(datadir)
@@ -77,7 +78,7 @@ def initialize_chain(test_dir):
7778
args = [ "bitcoind", "-keypool=1", "-datadir="+datadir ]
7879
if i > 0:
7980
args.append("-connect=127.0.0.1:"+str(START_P2P_PORT))
80-
bitcoinds.append(subprocess.Popen(args))
81+
bitcoind_processes.append(subprocess.Popen(args))
8182
subprocess.check_output([ "bitcoin-cli", "-datadir="+datadir,
8283
"-rpcwait", "getblockcount"])
8384

@@ -90,8 +91,6 @@ def initialize_chain(test_dir):
9091
sys.stderr.write("Error connecting to "+url+"\n")
9192
sys.exit(1)
9293

93-
import pdb; pdb.set_trace()
94-
9594
# Create a 200-block-long chain; each of the 4 nodes
9695
# gets 25 mature blocks and 25 immature.
9796
for i in range(4):
@@ -100,17 +99,18 @@ def initialize_chain(test_dir):
10099
for i in range(4):
101100
rpcs[i].setgenerate(True, 25)
102101
sync_blocks(rpcs)
103-
# Shut them down
102+
103+
# Shut them down, and remove debug.logs:
104+
stop_nodes(rpcs)
105+
wait_bitcoinds()
104106
for i in range(4):
105-
rpcs[i].stop()
107+
os.remove(debug_log("cache", i))
106108

107109
for i in range(4):
108110
from_dir = os.path.join("cache", "node"+str(i))
109111
to_dir = os.path.join(test_dir, "node"+str(i))
110112
shutil.copytree(from_dir, to_dir)
111113

112-
bitcoind_processes = []
113-
114114
def start_nodes(num_nodes, dir):
115115
# Start bitcoinds, and wait for RPC interface to be up and running:
116116
for i in range(num_nodes):
@@ -126,9 +126,19 @@ def start_nodes(num_nodes, dir):
126126
rpc_connections.append(AuthServiceProxy(url))
127127
return rpc_connections
128128

129-
def stop_nodes():
130-
for process in bitcoind_processes:
131-
process.kill()
129+
def debug_log(dir, n_node):
130+
return os.path.join(dir, "node"+str(n_node), "regtest", "debug.log")
131+
132+
def stop_nodes(nodes):
133+
for i in range(len(nodes)):
134+
nodes[i].stop()
135+
del nodes[:] # Emptying array closes connections as a side effect
136+
137+
def wait_bitcoinds():
138+
# Wait for all bitcoinds to cleanly exit
139+
for bitcoind in bitcoind_processes:
140+
bitcoind.wait()
141+
del bitcoind_processes[:]
132142

133143
def connect_nodes(from_connection, node_num):
134144
ip_port = "127.0.0.1:"+str(START_P2P_PORT+node_num)

src/rpcserver.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -732,7 +732,7 @@ static string JSONRPCExecBatch(const Array& vReq)
732732
void ServiceConnection(AcceptedConnection *conn)
733733
{
734734
bool fRun = true;
735-
while (fRun)
735+
while (fRun && !ShutdownRequested())
736736
{
737737
int nProto = 0;
738738
map<string, string> mapHeaders;

0 commit comments

Comments
 (0)