~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_test_server.py

  • Committer: Samuel Bronson
  • Date: 2012-08-30 20:36:18 UTC
  • mto: (6015.57.3 2.4)
  • mto: This revision was merged to the branch mainline in revision 6558.
  • Revision ID: naesten@gmail.com-20120830203618-y2dzw91nqpvpgxvx
Update INSTALL for switch to Python 2.6 and up.

Show diffs side-by-side

added added

removed removed

Lines of Context:
19
19
import SocketServer
20
20
import threading
21
21
 
22
 
 
23
22
from bzrlib import (
24
23
    osutils,
25
24
    tests,
31
30
load_tests = load_tests_apply_scenarios
32
31
 
33
32
 
34
 
def portable_socket_pair():
35
 
    """Return a pair of TCP sockets connected to each other.
36
 
 
37
 
    Unlike socket.socketpair, this should work on Windows.
38
 
    """
39
 
    listen_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
40
 
    listen_sock.bind(('127.0.0.1', 0))
41
 
    listen_sock.listen(1)
42
 
    client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
43
 
    client_sock.connect(listen_sock.getsockname())
44
 
    server_sock, addr = listen_sock.accept()
45
 
    listen_sock.close()
46
 
    return server_sock, client_sock
47
 
 
48
 
 
49
33
class TCPClient(object):
50
34
 
51
35
    def __init__(self):
77
61
        return self.sock.recv(bufsize)
78
62
 
79
63
 
80
 
class TCPConnectionHandler(SocketServer.BaseRequestHandler):
 
64
class TCPConnectionHandler(SocketServer.StreamRequestHandler):
81
65
 
82
66
    def handle(self):
83
67
        self.done = False
85
69
        while not self.done:
86
70
            self.handle_connection()
87
71
 
88
 
    def readline(self):
89
 
        # TODO: We should be buffering any extra data sent, etc. However, in
90
 
        #       practice, we don't send extra content, so we haven't bothered
91
 
        #       to implement it yet.
92
 
        req = self.request.recv(4096)
93
 
        # An empty string is allowed, to indicate the end of the connection
94
 
        if not req or (req.endswith('\n') and req.count('\n') == 1):
95
 
            return req
96
 
        raise ValueError('[%r] not a simple line' % (req,))
97
 
 
98
72
    def handle_connection(self):
99
 
        req = self.readline()
 
73
        req = self.rfile.readline()
100
74
        if not req:
101
75
            self.done = True
102
76
        elif req == 'ping\n':
103
 
            self.request.sendall('pong\n')
 
77
            self.wfile.write('pong\n')
104
78
        else:
105
79
            raise ValueError('[%s] not understood' % req)
106
80
 
107
81
 
108
82
class TestTCPServerInAThread(tests.TestCase):
109
83
 
110
 
    scenarios = [
 
84
    scenarios = [ 
111
85
        (name, {'server_class': getattr(test_server, name)})
112
86
        for name in
113
87
        ('TestingTCPServer', 'TestingThreadingTCPServer')]
117
91
            self.server_class = server_class
118
92
        if connection_handler_class is None:
119
93
            connection_handler_class = TCPConnectionHandler
120
 
        server = test_server.TestingTCPServerInAThread(
 
94
        server =  test_server.TestingTCPServerInAThread(
121
95
            ('localhost', 0), self.server_class, connection_handler_class)
122
96
        server.start_server()
123
97
        self.addCleanup(server.stop_server)
181
155
        # The server won't fail until a client connect
182
156
        client = self.get_client()
183
157
        client.connect((server.host, server.port))
184
 
        # We make sure the server wants to handle a request, but the request is
185
 
        # guaranteed to fail. However, the server should make sure that the
186
 
        # connection gets closed, and stop_server should then raise the
187
 
        # original exception.
188
 
        client.write('ping\n')
189
158
        try:
190
 
            self.assertEqual('', client.read())
191
 
        except socket.error, e:
192
 
            # On Windows, failing during 'handle' means we get
193
 
            # 'forced-close-of-connection'. Possibly because we haven't
194
 
            # processed the write request before we close the socket.
195
 
            WSAECONNRESET = 10054
196
 
            if e.errno in (WSAECONNRESET,):
197
 
                pass
 
159
            # Now we must force the server to answer by sending the request and
 
160
            # waiting for some answer. But since we don't control when the
 
161
            # server thread will be given cycles, we don't control either
 
162
            # whether our reads or writes may hang.
 
163
            client.sock.settimeout(0.1)
 
164
            client.write('ping\n')
 
165
            client.read()
 
166
        except socket.error:
 
167
            pass
198
168
        # Now the server has raised the exception in its own thread
199
169
        self.assertRaises(CantConnect, server.stop_server)
200
170
 
212
182
 
213
183
        class FailingDuringResponseHandler(TCPConnectionHandler):
214
184
 
215
 
            # We use 'request' instead of 'self' below because the test matters
216
 
            # more and we need a container to properly set connection_thread.
217
185
            def handle_connection(request):
218
 
                req = request.readline()
 
186
                req = request.rfile.readline()
219
187
                # Capture the thread and make it use 'caught' so we can wait on
220
 
                # the event that will be set when the exception is caught. We
 
188
                # the even that will be set when the exception is caught. We
221
189
                # also capture the thread to know where to look.
222
190
                self.connection_thread = threading.currentThread()
223
191
                self.connection_thread.set_sync_event(caught)
230
198
        client.write('ping\n')
231
199
        # Wait for the exception to be caught
232
200
        caught.wait()
233
 
        self.assertEqual('', client.read()) # connection closed
234
201
        # Check that the connection thread did catch the exception,
235
202
        # http://pad.lv/869366 was wrongly checking the server thread which
236
203
        # works for TestingTCPServer where the connection is handled in the
237
 
        # same thread than the server one but was racy for
238
 
        # TestingThreadingTCPServer. Since the connection thread detaches
239
 
        # itself before handling the request, we are guaranteed that the
240
 
        # exception won't leak into the server thread anymore.
241
 
        self.assertRaises(FailToRespond,
242
 
                          self.connection_thread.pending_exception)
 
204
        # same thread than the server one but is racy for
 
205
        # TestingThreadingTCPServer where the server thread may be in a
 
206
        # blocking accept() call (or not).
 
207
        try:
 
208
            self.connection_thread.pending_exception()
 
209
        except FailToRespond:
 
210
            # Great, the test succeeded
 
211
            pass
 
212
        else:
 
213
            # If the exception is not in the connection thread anymore, it's in
 
214
            # the server's one. 
 
215
            server.server.stopped.wait()
 
216
            # The exception is available now
 
217
            self.assertRaises(FailToRespond, server.pending_exception)
243
218
 
244
219
    def test_exception_swallowed_while_serving(self):
245
220
        # We need to ensure the exception has been caught
254
229
 
255
230
        class FailingWhileServingConnectionHandler(TCPConnectionHandler):
256
231
 
257
 
            # We use 'request' instead of 'self' below because the test matters
258
 
            # more and we need a container to properly set connection_thread.
259
232
            def handle(request):
260
233
                # Capture the thread and make it use 'caught' so we can wait on
261
 
                # the event that will be set when the exception is caught. We
 
234
                # the even that will be set when the exception is caught. We
262
235
                # also capture the thread to know where to look.
263
236
                self.connection_thread = threading.currentThread()
264
237
                self.connection_thread.set_sync_event(caught)
266
239
 
267
240
        server = self.get_server(
268
241
            connection_handler_class=FailingWhileServingConnectionHandler)
269
 
        self.assertEquals(True, server.server.serving)
270
242
        # Install the exception swallower
271
243
        server.set_ignored_exceptions(CantServe)
272
244
        client = self.get_client()
274
246
        client.connect((server.host, server.port))
275
247
        # Wait for the exception to be caught
276
248
        caught.wait()
277
 
        self.assertEqual('', client.read()) # connection closed
278
249
        # The connection wasn't served properly but the exception should have
279
250
        # been swallowed (see test_server_crash_while_responding remark about
280
251
        # http://pad.lv/869366 explaining why we can't check the server thread
281
252
        # here). More precisely, the exception *has* been caught and captured
282
253
        # but it is cleared when joining the thread (or trying to acquire the
283
254
        # exception) and as such won't propagate to the server thread.
284
 
        self.assertIs(None, self.connection_thread.pending_exception())
285
 
        self.assertIs(None, server.pending_exception())
286
 
 
287
 
    def test_handle_request_closes_if_it_doesnt_process(self):
288
 
        server = self.get_server()
289
 
        client = self.get_client()
290
 
        server.server.serving = False
291
 
        client.connect((server.host, server.port))
292
 
        self.assertEqual('', client.read())
293
 
 
294
 
 
295
 
class TestTestingSmartServer(tests.TestCase):
296
 
 
297
 
    def test_sets_client_timeout(self):
298
 
        server = test_server.TestingSmartServer(('localhost', 0), None, None,
299
 
            root_client_path='/no-such-client/path')
300
 
        self.assertEqual(test_server._DEFAULT_TESTING_CLIENT_TIMEOUT,
301
 
                         server._client_timeout)
302
 
        sock = socket.socket()
303
 
        h = server._make_handler(sock)
304
 
        self.assertEqual(test_server._DEFAULT_TESTING_CLIENT_TIMEOUT,
305
 
                         h._client_timeout)
306
 
 
307
 
 
308
 
class FakeServer(object):
309
 
    """Minimal implementation to pass to TestingSmartConnectionHandler"""
310
 
    backing_transport = None
311
 
    root_client_path = '/'
312
 
 
313
 
 
314
 
class TestTestingSmartConnectionHandler(tests.TestCase):
315
 
 
316
 
    def test_connection_timeout_suppressed(self):
317
 
        self.overrideAttr(test_server, '_DEFAULT_TESTING_CLIENT_TIMEOUT', 0.01)
318
 
        s = FakeServer()
319
 
        server_sock, client_sock = portable_socket_pair()
320
 
        # This should timeout quickly, but not generate an exception.
321
 
        handler = test_server.TestingSmartConnectionHandler(server_sock,
322
 
            server_sock.getpeername(), s)
323
 
 
324
 
    def test_connection_shutdown_while_serving_no_error(self):
325
 
        s = FakeServer()
326
 
        server_sock, client_sock = portable_socket_pair()
327
 
        class ShutdownConnectionHandler(
328
 
            test_server.TestingSmartConnectionHandler):
329
 
 
330
 
            def _build_protocol(self):
331
 
                self.finished = True
332
 
                return super(ShutdownConnectionHandler, self)._build_protocol()
333
 
        # This should trigger shutdown after the entering _build_protocol, and
334
 
        # we should exit cleanly, without raising an exception.
335
 
        handler = ShutdownConnectionHandler(server_sock,
336
 
            server_sock.getpeername(), s)
 
255
        self.connection_thread.pending_exception()
 
256
        server.pending_exception()