summaryrefslogtreecommitdiffstats
path: root/Tools/Scripts/webkitpy/layout_tests/layout_package/manager_worker_broker_unittest.py
blob: c32f88039f4b80928114dbc28158892f0237ce0f (plain)
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
# Copyright (C) 2010 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
#     * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
#     * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import optparse
import Queue
import sys
import unittest

try:
    import multiprocessing
except ImportError:
    multiprocessing = None


from webkitpy.common.system import outputcapture

from webkitpy.layout_tests import port
from webkitpy.layout_tests.layout_package import manager_worker_broker
from webkitpy.layout_tests.layout_package import message_broker2

# In order to reliably control when child workers are starting and stopping,
# we use a pair of global variables to hold queues used for messaging. Ideally
# we wouldn't need globals, but we can't pass these through a lexical closure
# because those can't be Pickled and sent to a subprocess, and we'd prefer not
# to have to pass extra arguments to the worker in the start_worker() call.
starting_queue = None
stopping_queue = None


def make_broker(manager, worker_model, start_queue=None, stop_queue=None):
    global starting_queue
    global stopping_queue
    starting_queue = start_queue
    stopping_queue = stop_queue
    options = get_options(worker_model)
    return manager_worker_broker.get(port.get("test"), options, manager, _TestWorker)


class _TestWorker(manager_worker_broker.AbstractWorker):
    def __init__(self, broker_connection, worker_number, options):
        self._broker_connection = broker_connection
        self._options = options
        self._worker_number = worker_number
        self._name = 'TestWorker/%d' % worker_number
        self._stopped = False
        self._canceled = False
        self._starting_queue = starting_queue
        self._stopping_queue = stopping_queue

    def handle_stop(self, src):
        self._stopped = True

    def handle_test(self, src, an_int, a_str):
        assert an_int == 1
        assert a_str == "hello, world"
        self._broker_connection.post_message('test', 2, 'hi, everybody')

    def is_done(self):
        return self._stopped or self._canceled

    def name(self):
        return self._name

    def cancel(self):
        self._canceled = True

    def run(self, port):
        if self._starting_queue:
            self._starting_queue.put('')

        if self._stopping_queue:
            self._stopping_queue.get()
        try:
            self._broker_connection.run_message_loop()
            self._broker_connection.yield_to_broker()
            self._broker_connection.post_message('done')
        except Exception, e:
            self._broker_connection.post_message('exception', (type(e), str(e), None))


def get_options(worker_model):
    option_list = manager_worker_broker.runtime_options()
    parser = optparse.OptionParser(option_list=option_list)
    options, args = parser.parse_args(args=['--worker-model', worker_model])
    return options



class FunctionTests(unittest.TestCase):
    def test_get__inline(self):
        self.assertTrue(make_broker(self, 'inline') is not None)

    def test_get__threads(self):
        self.assertTrue(make_broker(self, 'threads') is not None)

    def test_get__processes(self):
        # This test sometimes fails on Windows. See <http://webkit.org/b/55087>.
        if sys.platform in ('cygwin', 'win32'):
            return

        if multiprocessing:
            self.assertTrue(make_broker(self, 'processes') is not None)
        else:
            self.assertRaises(ValueError, make_broker, self, 'processes')

    def test_get__unknown(self):
        self.assertRaises(ValueError, make_broker, self, 'unknown')


class _TestsMixin(object):
    """Mixin class that implements a series of tests to enforce the
    contract all implementations must follow."""

    def name(self):
        return 'Tester'

    def is_done(self):
        return self._done

    def handle_done(self, src):
        self._done = True

    def handle_test(self, src, an_int, a_str):
        self._an_int = an_int
        self._a_str = a_str

    def handle_exception(self, src, exc_info):
        self._exception = exc_info
        self._done = True

    def setUp(self):
        self._an_int = None
        self._a_str = None
        self._broker = None
        self._done = False
        self._exception = None
        self._worker_model = None

    def make_broker(self, starting_queue=None, stopping_queue=None):
        self._broker = make_broker(self, self._worker_model, starting_queue,
                                   stopping_queue)

    def test_cancel(self):
        self.make_broker()
        worker = self._broker.start_worker(0)
        worker.cancel()
        self._broker.post_message('test', 1, 'hello, world')
        worker.join(0.5)
        self.assertFalse(worker.is_alive())

    def test_done(self):
        self.make_broker()
        worker = self._broker.start_worker(0)
        self._broker.post_message('test', 1, 'hello, world')
        self._broker.post_message('stop')
        self._broker.run_message_loop()
        worker.join(0.5)
        self.assertFalse(worker.is_alive())
        self.assertTrue(self.is_done())
        self.assertEqual(self._an_int, 2)
        self.assertEqual(self._a_str, 'hi, everybody')

    def test_log_wedged_worker(self):
        starting_queue = self.queue()
        stopping_queue = self.queue()
        self.make_broker(starting_queue, stopping_queue)
        oc = outputcapture.OutputCapture()
        oc.capture_output()
        try:
            worker = self._broker.start_worker(0)
            starting_queue.get()
            worker.log_wedged_worker('test_name')
            stopping_queue.put('')
            self._broker.post_message('stop')
            self._broker.run_message_loop()
            worker.join(0.5)
            self.assertFalse(worker.is_alive())
            self.assertTrue(self.is_done())
        finally:
            oc.restore_output()

    def test_unknown_message(self):
        self.make_broker()
        worker = self._broker.start_worker(0)
        self._broker.post_message('unknown')
        self._broker.run_message_loop()
        worker.join(0.5)

        self.assertTrue(self.is_done())
        self.assertFalse(worker.is_alive())
        self.assertEquals(self._exception[0], ValueError)
        self.assertEquals(self._exception[1],
            "TestWorker/0: received message 'unknown' it couldn't handle")


class InlineBrokerTests(_TestsMixin, unittest.TestCase):
    def setUp(self):
        _TestsMixin.setUp(self)
        self._worker_model = 'inline'

    def test_log_wedged_worker(self):
        self.make_broker()
        worker = self._broker.start_worker(0)
        self.assertRaises(AssertionError, worker.log_wedged_worker, None)


# FIXME: https://bugs.webkit.org/show_bug.cgi?id=54520.
if multiprocessing and sys.platform not in ('cygwin', 'win32'):

    class MultiProcessBrokerTests(_TestsMixin, unittest.TestCase):
        def setUp(self):
            _TestsMixin.setUp(self)
            self._worker_model = 'processes'

        def queue(self):
            return multiprocessing.Queue()


class ThreadedBrokerTests(_TestsMixin, unittest.TestCase):
    def setUp(self):
        _TestsMixin.setUp(self)
        self._worker_model = 'threads'

    def queue(self):
        return Queue.Queue()


class FunctionsTest(unittest.TestCase):
    def test_runtime_options(self):
        option_list = manager_worker_broker.runtime_options()
        parser = optparse.OptionParser(option_list=option_list)
        options, args = parser.parse_args([])
        self.assertTrue(options)


class InterfaceTest(unittest.TestCase):
    # These tests mostly exist to pacify coverage.

    # FIXME: There must be a better way to do this and also verify
    # that classes do implement every abstract method in an interface.
    def test_managerconnection_is_abstract(self):
        # Test that all the base class methods are abstract and have the
        # signature we expect.
        broker = make_broker(self, 'inline')
        obj = manager_worker_broker._ManagerConnection(broker._broker, None, self, None)
        self.assertRaises(NotImplementedError, obj.start_worker, 0)

    def test_workerconnection_is_abstract(self):
        # Test that all the base class methods are abstract and have the
        # signature we expect.
        broker = make_broker(self, 'inline')
        obj = manager_worker_broker._WorkerConnection(broker._broker, _TestWorker, 0, None)
        self.assertRaises(NotImplementedError, obj.cancel)
        self.assertRaises(NotImplementedError, obj.is_alive)
        self.assertRaises(NotImplementedError, obj.join, None)
        self.assertRaises(NotImplementedError, obj.log_wedged_worker, None)


if __name__ == '__main__':
    unittest.main()