~ubuntuone-control-tower/ubuntuone-dev-tools/trunk

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# -*- coding: utf-8 -*-
# Copyright 2012 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# In addition, as a special exception, the copyright holders give
# permission to link the code of portions of this program with the
# OpenSSL library under certain conditions as described in each
# individual source file, and distribute linked combinations
# including the two.
# You must obey the GNU General Public License in all respects
# for all of the code used other than OpenSSL.  If you modify
# file(s) with this exception, you may extend this exception to your
# version of the file(s), but you are not obligated to do so.  If you
# do not wish to do so, delete this exception statement from your
# version.  If you delete this exception statement from all source
# files in the program, then also delete it here.

"""Base test case for twisted servers."""

import os
import shutil
import tempfile

from twisted.internet import defer, endpoints, protocol
from twisted.spread import pb

from ubuntuone.devtools.testcases import BaseTestCase

# no init method + twisted common warnings
# pylint: disable=W0232, C0103, E1101


def server_protocol_factory(cls):
    """Factory to create tidy protocols."""

    if cls is None:
        cls = protocol.Protocol

    class ServerTidyProtocol(cls):
        """A tidy protocol."""

        def connectionLost(self, *args):
            """Lost the connection."""
            cls.connectionLost(self, *args)
            # lets tell everyone
            # pylint: disable=W0212
            if (self.factory._disconnecting
                    and self.factory.testserver_on_connection_lost is not None
                    and not self.factory.testserver_on_connection_lost.called):
                self.factory.testserver_on_connection_lost.callback(self)
            # pylint: enable=W0212

    return ServerTidyProtocol


def server_factory_factory(cls):
    """Factory that creates special types of factories for tests."""

    if cls is None:
        cls = protocol.ServerFactory

    class TidyServerFactory(cls):
        """A tidy factory."""

        testserver_on_connection_lost = None

        def buildProtocol(self, addr):
            prot = cls.buildProtocol(self, addr)
            self.testserver_on_connection_lost = defer.Deferred()
            return prot

    return TidyServerFactory


def client_protocol_factory(cls):
    """Factory to create tidy protocols."""

    if cls is None:
        cls = protocol.Protocol

    class ClientTidyProtocol(cls):
        """A tidy protocol."""

        def connectionLost(self, *a):
            """Connection list."""
            cls.connectionLost(self, *a)
            # pylint: disable=W0212
            if (self.factory._disconnecting
                    and self.factory.testserver_on_connection_lost is not None
                    and not self.factory.testserver_on_connection_lost.called):
                self.factory.testserver_on_connection_lost.callback(self)
            # pylint: enable=W0212

    return ClientTidyProtocol


class TidySocketServer(object):
    """Ensure that twisted servers are correctly managed in tests.

    Closing a twisted server is a complicated matter. In order to do so you
    have to ensure that three different deferreds are fired:

        1. The server must stop listening.
        2. The client connection must disconnect.
        3. The server connection must disconnect.

    This class allows to create a server and a client that will ensure that
    the reactor is left clean by following the pattern described at
    http://mumak.net/stuff/twisted-disconnect.html
    """
    def __init__(self):
        """Create a new instance."""
        self.listener = None
        self.server_factory = None

        self.connector = None
        self.client_factory = None

    def get_server_endpoint(self):
        """Return the server endpoint description."""
        raise NotImplementedError('To be implemented by child classes.')

    def get_client_endpoint(self):
        """Return the client endpoint description."""
        raise NotImplementedError('To be implemented by child classes.')

    @defer.inlineCallbacks
    def listen_server(self, server_class, *args, **kwargs):
        """Start a server in a random port."""
        from twisted.internet import reactor
        tidy_class = server_factory_factory(server_class)
        self.server_factory = tidy_class(*args, **kwargs)
        self.server_factory._disconnecting = False
        self.server_factory.protocol = server_protocol_factory(
            self.server_factory.protocol)
        endpoint = endpoints.serverFromString(reactor,
                                              self.get_server_endpoint())
        self.listener = yield endpoint.listen(self.server_factory)
        defer.returnValue(self.server_factory)

    @defer.inlineCallbacks
    def connect_client(self, client_class, *args, **kwargs):
        """Conect a client to a given server."""
        from twisted.internet import reactor

        if self.server_factory is None:
            raise ValueError('Server Factory was not provided.')
        if self.listener is None:
            raise ValueError('%s has not started listening.',
                             self.server_factory)

        self.client_factory = client_class(*args, **kwargs)
        self.client_factory._disconnecting = False
        self.client_factory.protocol = client_protocol_factory(
            self.client_factory.protocol)
        self.client_factory.testserver_on_connection_lost = defer.Deferred()
        endpoint = endpoints.clientFromString(reactor,
                                              self.get_client_endpoint())
        self.connector = yield endpoint.connect(self.client_factory)
        defer.returnValue(self.client_factory)

    def clean_up(self):
        """Action to be performed for clean up."""
        if self.server_factory is None or self.listener is None:
            # nothing to clean
            return defer.succeed(None)

        if self.listener and self.connector:
            # clean client and server
            self.server_factory._disconnecting = True
            self.client_factory._disconnecting = True
            d = defer.maybeDeferred(self.listener.stopListening)
            self.connector.transport.loseConnection()
            if self.server_factory.testserver_on_connection_lost:
                return defer.gatherResults(
                    [d,
                     self.client_factory.testserver_on_connection_lost,
                     self.server_factory.testserver_on_connection_lost])
            else:
                return defer.gatherResults(
                    [d,
                     self.client_factory.testserver_on_connection_lost])
        if self.listener:
            # just clean the server since there is no client
            # pylint: disable=W0201
            self.server_factory._disconnecting = True
            return defer.maybeDeferred(self.listener.stopListening)
            # pylint: enable=W0201


class TidyTCPServer(TidySocketServer):
    """A tidy tcp domain sockets server."""

    client_endpoint_pattern = 'tcp:host=127.0.0.1:port=%s'
    server_endpoint_pattern = 'tcp:0:interface=127.0.0.1'

    def get_server_endpoint(self):
        """Return the server endpoint description."""
        return self.server_endpoint_pattern

    def get_client_endpoint(self):
        """Return the client endpoint description."""
        if self.server_factory is None:
            raise ValueError('Server Factory was not provided.')
        if self.listener is None:
            raise ValueError('%s has not started listening.',
                             self.server_factory)
        return self.client_endpoint_pattern % self.listener.getHost().port


class TidyUnixServer(TidySocketServer):
    """A tidy unix domain sockets server."""

    client_endpoint_pattern = 'unix:path=%s'
    server_endpoint_pattern = 'unix:%s'

    def __init__(self):
        """Create a new instance."""
        super(TidyUnixServer, self).__init__()
        self.temp_dir = tempfile.mkdtemp()
        self.path = os.path.join(self.temp_dir, 'tidy_unix_server')

    def get_server_endpoint(self):
        """Return the server endpoint description."""
        return self.server_endpoint_pattern % self.path

    def get_client_endpoint(self):
        """Return the client endpoint description."""
        return self.client_endpoint_pattern % self.path

    def clean_up(self):
        """Action to be performed for clean up."""
        result = super(TidyUnixServer, self).clean_up()
        # remove the dir once we are disconnected
        result.addCallback(lambda _: shutil.rmtree(self.temp_dir))
        return result


class ServerTestCase(BaseTestCase):
    """Base test case for tidy servers."""

    @defer.inlineCallbacks
    def setUp(self):
        """Set the diff tests."""
        yield super(ServerTestCase, self).setUp()

        try:
            self.server_runner = self.get_server()
        except NotImplementedError:
            self.server_runner = None

        self.server_factory = None
        self.client_factory = None
        self.server_disconnected = None
        self.client_connected = None
        self.client_disconnected = None
        self.listener = None
        self.connector = None
        self.addCleanup(self.tear_down_server_client)

    def get_server(self):
        """Return the server to be used to run the tests."""
        raise NotImplementedError('To be implemented by child classes.')

    @defer.inlineCallbacks
    def listen_server(self, server_class, *args, **kwargs):
        """Listen a server.

        The method takes the server class and the arguments that should be
        passed to the server constructor.
        """
        self.server_factory = yield self.server_runner.listen_server(
            server_class, *args, **kwargs)
        self.server_disconnected = \
            self.server_factory.testserver_on_connection_lost
        self.listener = self.server_runner.listener

    @defer.inlineCallbacks
    def connect_client(self, client_class, *args, **kwargs):
        """Connect the client.

        The method takes the client factory  class and the arguments that
        should be passed to the client constructor.
        """
        self.client_factory = yield self.server_runner.connect_client(
            client_class, *args, **kwargs)
        self.client_disconnected = \
            self.client_factory.testserver_on_connection_lost
        self.connector = self.server_runner.connector

    def tear_down_server_client(self):
        """Clean the server and client."""
        if self.server_runner:
            return self.server_runner.clean_up()


class TCPServerTestCase(ServerTestCase):
    """Test that uses a single twisted server."""

    def get_server(self):
        """Return the server to be used to run the tests."""
        return TidyTCPServer()


class UnixServerTestCase(ServerTestCase):
    """Test that uses a single twisted server."""

    def get_server(self):
        """Return the server to be used to run the tests."""
        return TidyUnixServer()


class PbServerTestCase(ServerTestCase):
    """Test a pb server."""

    def get_server(self):
        """Return the server to be used to run the tests."""
        raise NotImplementedError('To be implemented by child classes.')

    @defer.inlineCallbacks
    def listen_server(self, *args, **kwargs):
        """Listen a pb server."""
        yield super(PbServerTestCase, self).listen_server(pb.PBServerFactory,
                                                          *args, **kwargs)

    @defer.inlineCallbacks
    def connect_client(self, *args, **kwargs):
        """Connect a pb client."""
        yield super(PbServerTestCase, self).connect_client(pb.PBClientFactory,
                                                           *args, **kwargs)


class TCPPbServerTestCase(PbServerTestCase):
    """Test a pb server over TCP."""

    def get_server(self):
        """Return the server to be used to run the tests."""
        return TidyTCPServer()


class UnixPbServerTestCase(PbServerTestCase):
    """Test a pb server over Unix domain sockets."""

    def get_server(self):
        """Return the server to be used to run the tests."""
        return TidyUnixServer()