This file is indexed.

/usr/lib/python2.7/dist-packages/crochet/tests/test_setup.py is in python-crochet 1.4.0-0ubuntu2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
"""
Tests for the initial setup.
"""

from __future__ import absolute_import

import threading
import warnings
import subprocess
import sys

from twisted.trial.unittest import TestCase
from twisted.python.log import PythonLoggingObserver
from twisted.python import log
from twisted.python.runtime import platform
from twisted.python import threadable
from twisted.internet.task import Clock

from crochet._eventloop import EventLoop, ThreadLogObserver, _store
from crochet.tests import crochet_directory


class FakeReactor(Clock):
    """
    A fake reactor for testing purposes.
    """
    thread_id = None
    runs = 0
    in_call_from_thread = False

    def __init__(self):
        Clock.__init__(self)
        self.started = threading.Event()
        self.stopping = False
        self.events = []

    def run(self, installSignalHandlers=True):
        self.runs += 1
        self.thread_id = threading.current_thread().ident
        self.installSignalHandlers = installSignalHandlers
        self.started.set()

    def callFromThread(self, f, *args, **kwargs):
        self.in_call_from_thread = True
        f(*args, **kwargs)
        self.in_call_from_thread = False

    def stop(self):
        self.stopping = True

    def addSystemEventTrigger(self, when, event, f):
        self.events.append((when, event, f))


class FakeThread:
    started = False

    def start(self):
        self.started = True


class SetupTests(TestCase):
    """
    Tests for setup().
    """

    def test_first_runs_reactor(self):
        """
        With it first call, setup() runs the reactor in a thread.
        """
        reactor = FakeReactor()
        EventLoop(lambda: reactor, lambda f, *g: None).setup()
        reactor.started.wait(5)
        self.assertNotEqual(reactor.thread_id, None)
        self.assertNotEqual(reactor.thread_id, threading.current_thread().ident)
        self.assertFalse(reactor.installSignalHandlers)

    def test_second_does_nothing(self):
        """
        The second call to setup() does nothing.
        """
        reactor = FakeReactor()
        s = EventLoop(lambda: reactor, lambda f, *g: None)
        s.setup()
        s.setup()
        reactor.started.wait(5)
        self.assertEqual(reactor.runs, 1)

    def test_stop_on_exit(self):
        """
        setup() registers an exit handler that stops the reactor, and an exit
        handler that logs stashed EventualResults.
        """
        atexit = []
        reactor = FakeReactor()
        s = EventLoop(lambda: reactor, lambda f, *args: atexit.append((f, args)))
        s.setup()
        self.assertEqual(len(atexit), 2)
        self.assertFalse(reactor.stopping)
        f, args = atexit[0]
        self.assertEqual(f, reactor.callFromThread)
        self.assertEqual(args, (reactor.stop,))
        f(*args)
        self.assertTrue(reactor.stopping)
        f, args = atexit[1]
        self.assertEqual(f, _store.log_errors)
        self.assertEqual(args, ())
        f(*args) # make sure it doesn't throw an exception

    def test_runs_with_lock(self):
        """
        All code in setup() and no_setup() is protected by a lock.
        """
        self.assertTrue(EventLoop.setup.synchronized)
        self.assertTrue(EventLoop.no_setup.synchronized)

    def test_logging(self):
        """
        setup() registers a PythonLoggingObserver wrapped in a
        ThreadLogObserver, removing the default log observer.
        """
        logging = []
        def fakeStartLoggingWithObserver(observer, setStdout=1):
            self.assertIsInstance(observer, ThreadLogObserver)
            wrapped = observer._observer
            expected = PythonLoggingObserver.emit
            # Python 3 and 2 differ in value of __func__:
            expected = getattr(expected, "__func__", expected)
            self.assertIdentical(wrapped.__func__, expected)
            self.assertEqual(setStdout, False)
            self.assertTrue(reactor.in_call_from_thread)
            logging.append(observer)

        reactor = FakeReactor()
        loop = EventLoop(lambda: reactor, lambda f, *g: None,
                         fakeStartLoggingWithObserver)
        loop.setup()
        self.assertTrue(logging)
        logging[0].stop()

    def test_stop_logging_on_exit(self):
        """
        setup() registers a reactor shutdown event that stops the logging thread.
        """
        observers = []
        reactor = FakeReactor()
        s = EventLoop(lambda: reactor, lambda f, *arg: None,
                      lambda observer, setStdout=1: observers.append(observer))
        s.setup()
        self.addCleanup(observers[0].stop)
        self.assertIn(("after", "shutdown", observers[0].stop), reactor.events)

    def test_warnings_untouched(self):
        """
        setup() ensure the warnings module's showwarning is unmodified,
        overriding the change made by normal Twisted logging setup.
        """
        def fakeStartLoggingWithObserver(observer, setStdout=1):
            warnings.showwarning = log.showwarning
            self.addCleanup(observer.stop)
        original = warnings.showwarning
        reactor = FakeReactor()
        loop = EventLoop(lambda: reactor, lambda f, *g: None,
                         fakeStartLoggingWithObserver)
        loop.setup()
        self.assertIdentical(warnings.showwarning, original)

    def test_start_watchdog_thread(self):
        """
        setup() starts the shutdown watchdog thread.
        """
        thread = FakeThread()
        reactor = FakeReactor()
        loop = EventLoop(lambda: reactor, lambda *args: None,
                         watchdog_thread=thread)
        loop.setup()
        self.assertTrue(thread.started)

    def test_no_setup(self):
        """
        If called first, no_setup() makes subsequent calls to setup() do
        nothing.
        """
        observers = []
        atexit = []
        thread = FakeThread()
        reactor = FakeReactor()
        loop = EventLoop(lambda: reactor, lambda f, *arg: atexit.append(f),
                         lambda observer, *a, **kw: observers.append(observer),
                         watchdog_thread=thread)

        loop.no_setup()
        loop.setup()
        self.assertFalse(observers)
        self.assertFalse(atexit)
        self.assertFalse(reactor.runs)
        self.assertFalse(thread.started)

    def test_no_setup_after_setup(self):
        """
        If called after setup(), no_setup() throws an exception.
        """
        reactor = FakeReactor()
        s = EventLoop(lambda: reactor, lambda f, *g: None)
        s.setup()
        self.assertRaises(RuntimeError, s.no_setup)

    def test_setup_registry_shutdown(self):
        """
        ResultRegistry.stop() is registered to run before reactor shutdown by
        setup().
        """
        reactor = FakeReactor()
        s = EventLoop(lambda: reactor, lambda f, *g: None)
        s.setup()
        self.assertEqual(reactor.events,
                         [("before", "shutdown", s._registry.stop)])


    def test_no_setup_registry_shutdown(self):
        """
        ResultRegistry.stop() is registered to run before reactor shutdown by
        setup().
        """
        reactor = FakeReactor()
        s = EventLoop(lambda: reactor, lambda f, *g: None)
        s.no_setup()
        self.assertEqual(reactor.events,
                         [("before", "shutdown", s._registry.stop)])


class ProcessSetupTests(TestCase):
    """
    setup() enables support for IReactorProcess on POSIX plaforms.
    """
    def test_posix(self):
        """
        On POSIX systems, setup() installs a LoopingCall that runs
        t.i.process.reapAllProcesses() 10 times a second.
        """
        reactor = FakeReactor()
        reaps = []
        s = EventLoop(lambda: reactor, lambda f, *g: None,
                      reapAllProcesses=lambda: reaps.append(1))
        s.setup()
        reactor.advance(0.1)
        self.assertEquals(reaps, [1])
        reactor.advance(0.1)
        self.assertEquals(reaps, [1, 1])
        reactor.advance(0.1)
        self.assertEquals(reaps, [1, 1, 1])
    if platform.type != "posix":
        test_posix.skip = "SIGCHLD is a POSIX-specific issue"

    def test_non_posix(self):
        """
        On POSIX systems, setup() does not install a LoopingCall.
        """
        reactor = FakeReactor()
        s = EventLoop(lambda: reactor, lambda f, *g: None)
        s.setup()
        self.assertFalse(reactor.getDelayedCalls())

    if platform.type == "posix":
        test_non_posix.skip = "SIGCHLD is a POSIX-specific issue"


class ThreadLogObserverTest(TestCase):
    """
    Tests for ThreadLogObserver.
    """
    def test_stop(self):
        """
        ThreadLogObserver.stop() stops the thread started in __init__.
        """
        threadLog = ThreadLogObserver(None)
        self.assertTrue(threadLog._thread.is_alive())
        threadLog.stop()
        threadLog._thread.join()
        self.assertFalse(threadLog._thread.is_alive())

    def test_emit(self):
        """
        ThreadLogObserver.emit runs the wrapped observer's in its thread, with
        the given message.
        """
        messages = []
        def observer(msg):
            messages.append((threading.current_thread().ident, msg))

        threadLog = ThreadLogObserver(observer)
        ident = threadLog._thread.ident
        msg1 = {}
        msg2 = {"a": "b"}
        threadLog(msg1)
        threadLog(msg2)
        threadLog.stop()
        # Wait for writing to finish:
        threadLog._thread.join()
        self.assertEqual(messages, [(ident, msg1), (ident, msg2)])


    def test_ioThreadUnchanged(self):
        """
        ThreadLogObserver does not change the Twisted I/O thread (which is
        supposed to match the thread the main reactor is running in.)
        """
        threadLog = ThreadLogObserver(None)
        threadLog.stop()
        threadLog._thread.join()
        self.assertIn(threadable.ioThread,
                      # Either reactor was never run, or run in thread running
                      # the tests:
                      (None, threading.current_thread().ident))



class ReactorImportTests(TestCase):
    """
    Tests for when the reactor gets imported.

    The reactor should only be imported as part of setup()/no_setup(),
    rather than as side-effect of Crochet import, since daemonization
    doesn't work if reactor is imported
    (https://twistedmatrix.com/trac/ticket/7105).
    """
    def test_crochet_import_no_reactor(self):
        """
        Importing crochet should not import the reactor.
        """
        program = """\
import sys
import crochet

if "twisted.internet.reactor" not in sys.modules:
    sys.exit(23)
"""
        process = subprocess.Popen([sys.executable, "-c", program],
                                   cwd=crochet_directory)
        self.assertEqual(process.wait(), 23)