This file is indexed.

/usr/lib/python3/dist-packages/twisted/test/test_twisted.py is in python3-twisted-experimental 13.2.0-0ubuntu1.

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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Tests for miscellaneous behaviors of the top-level L{twisted} package (ie, for
the code in C{twisted/__init__.py}.
"""

from __future__ import division, absolute_import

import sys
from types import ModuleType, FunctionType

from unittest import TestCase

from twisted import _checkRequirements
from twisted.python.compat import _PY3


# This is somewhat generally useful and should probably be part of a public API
# somewhere.  See #5977.
class SetAsideModule(object):
    """
    L{SetAsideModule} is a context manager for temporarily removing a module
    from C{sys.modules}.

    @ivar name: The name of the module to remove.
    """
    def __init__(self, name):
        self.name = name


    def _unimport(self, name):
        """
        Find the given module and all of its hierarchically inferior modules in
        C{sys.modules}, remove them from it, and return whatever was found.
        """
        modules = dict([
                (name, module)
                for (name, module)
                in list(sys.modules.items())
                if name == self.name or name.startswith(self.name + ".")])
        for name in modules:
            del sys.modules[name]
        return modules


    def __enter__(self):
        self.modules = self._unimport(self.name)


    def __exit__(self, excType, excValue, traceback):
        self._unimport(self.name)
        sys.modules.update(self.modules)



# Copied from 2.7 stdlib.  Delete after Python 2.6 is no longer a
# requirement.  See #5976.
class _AssertRaisesContext(object):
    """A context manager used to implement TestCase.assertRaises* methods."""

    def __init__(self, expected, test_case, expected_regexp=None):
        self.expected = expected
        self.failureException = test_case.failureException
        self.expected_regexp = expected_regexp

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, tb):
        if exc_type is None:
            try:
                exc_name = self.expected.__name__
            except AttributeError:
                exc_name = str(self.expected)
            raise self.failureException(
                "{0} not raised".format(exc_name))
        if not issubclass(exc_type, self.expected):
            # let unexpected exceptions pass through
            return False
        self.exception = exc_value # store for later retrieval
        if self.expected_regexp is None:
            return True

        expected_regexp = self.expected_regexp
        if isinstance(expected_regexp, basestring):
            expected_regexp = re.compile(expected_regexp)
        if not expected_regexp.search(str(exc_value)):
            raise self.failureException('"%s" does not match "%s"' %
                     (expected_regexp.pattern, str(exc_value)))
        return True



def _install(modules):
    """
    Take a mapping defining a package and turn it into real C{ModuleType}
    instances in C{sys.modules}.

    Consider these example::

        a = {"foo": "bar"}
        b = {"twisted": {"__version__": "42.6"}}
        c = {"twisted": {"plugin": {"getPlugins": stub}}}

    C{_install(a)} will place an item into C{sys.modules} with C{"foo"} as the
    key and C{"bar" as the value.

    C{_install(b)} will place an item into C{sys.modules} with C{"twisted"} as
    the key.  The value will be a new module object.  The module will have a
    C{"__version__"} attribute with C{"42.6"} as the value.

    C{_install(c)} will place an item into C{sys.modules} with C{"twisted"} as
    the key.  The value will be a new module object with a C{"plugin"}
    attribute.  An item will also be placed into C{sys.modules} with the key
    C{"twisted.plugin"} which refers to that module object.  That module will
    have an attribute C{"getPlugins"} with a value of C{stub}.

    @param modules: A mapping from names to definitions of modules.  The names
        are native strings like C{"twisted"} or C{"unittest"}.  Values may be
        arbitrary objects.  Any value which is not a dictionary will be added to
        C{sys.modules} unmodified.  Any dictionary value indicates the value is
        a new module and its items define the attributes of that module.  The
        definition of this structure is recursive, so a value in the dictionary
        may be a dictionary to trigger another level of processing.

    @return: C{None}
    """
    result = {}
    _makePackages(None, modules, result)
    sys.modules.update(result)



def _makePackages(parent, attributes, result):
    """
    Construct module objects (for either modules or packages).

    @param parent: C{None} or a module object which is the Python package
        containing all of the modules being created by this function call.  Its
        name will be prepended to the name of all created modules.

    @param attributes: A mapping giving the attributes of the particular module
        object this call is creating.

    @param result: A mapping which is populated with all created module names.
        This is suitable for use in updating C{sys.modules}.

    @return: A mapping of all of the attributes created by this call.  This is
        suitable for populating the dictionary of C{parent}.

    @see: L{_install}.
    """
    attrs = {}
    for (name, value) in list(attributes.items()):
        if parent is None:
            if isinstance(value, dict):
                module = ModuleType(name)
                module.__dict__.update(_makePackages(module, value, result))
                result[name] = module
            else:
                result[name] = value
        else:
            if isinstance(value, dict):
                module = ModuleType(parent.__name__ + '.' + name)
                module.__dict__.update(_makePackages(module, value, result))
                result[parent.__name__ + '.' + name] = module
                attrs[name] = module
            else:
                attrs[name] = value
    return attrs



class RequirementsTests(TestCase):
    """
    Tests for the import-time requirements checking.

    @ivar unsupportedPythonVersion: The newest version of Python 2.x which is
        not supported by Twisted.
    @type unsupportedPythonVersion: C{tuple}

    @ivar supportedPythonVersion: The oldest version of Python 2.x which is
        supported by Twisted.
    @type supportedPythonVersion: C{tuple}

    @ivar supportedZopeInterfaceVersion: The oldest version of C{zope.interface}
        which is supported by Twisted.
    @type supportedZopeInterfaceVersion: C{tuple}
    """
    unsupportedPythonVersion = (2, 5)
    supportedPythonVersion = (2, 6)

    if _PY3:
        supportedZopeInterfaceVersion = (4, 0, 0)
    else:
        supportedZopeInterfaceVersion = (3, 6, 0)

    # Copied from 2.7 stdlib.  Delete after Python 2.6 is no longer a
    # requirement.  See #5976.
    def assertRaises(self, excClass, callableObj=None, *args, **kwargs):
        """Fail unless an exception of class excClass is thrown
           by callableObj when invoked with arguments args and keyword
           arguments kwargs. If a different type of exception is
           thrown, it will not be caught, and the test case will be
           deemed to have suffered an error, exactly as for an
           unexpected exception.

           If called with callableObj omitted or None, will return a
           context object used like this::

                with self.assertRaises(SomeException):
                    do_something()

           The context manager keeps a reference to the exception as
           the 'exception' attribute. This allows you to inspect the
           exception after the assertion::

               with self.assertRaises(SomeException) as cm:
                   do_something()
               the_exception = cm.exception
               self.assertEqual(the_exception.error_code, 3)
        """
        context = _AssertRaisesContext(excClass, self)
        if callableObj is None:
            return context
        with context:
            callableObj(*args, **kwargs)


    def setUp(self):
        """
        Save the original value of C{sys.version_info} so it can be restored
        after the tests mess with it.
        """
        self.version = sys.version_info


    def tearDown(self):
        """
        Restore the original values saved in L{setUp}.
        """
        sys.version_info = self.version


    def test_oldPython(self):
        """
        L{_checkRequirements} raises L{ImportError} when run on a version of
        Python that is too old.
        """
        sys.version_info = self.unsupportedPythonVersion
        with self.assertRaises(ImportError) as raised:
            _checkRequirements()
        self.assertEqual(
            "Twisted requires Python %d.%d or later." % self.supportedPythonVersion,
            str(raised.exception))


    def test_newPython(self):
        """
        L{_checkRequirements} returns C{None} when run on a version of Python
        that is sufficiently new.
        """
        sys.version_info = self.supportedPythonVersion
        self.assertEqual(None, _checkRequirements())


    def test_missingZopeNamespace(self):
        """
        L{_checkRequirements} raises L{ImportError} when the C{zope} namespace
        package is not installed.
        """
        with SetAsideModule("zope"):
            # After an import for a module fails, it gets a None value in
            # sys.modules as a cache of that negative result.  Future import
            # attempts see it and fail fast without checking the system again.
            sys.modules["zope"] = None
            with self.assertRaises(ImportError) as raised:
                _checkRequirements()
            self.assertEqual(
                "Twisted requires zope.interface %d.%d.%d or later: no module "
                "named zope.interface." % self.supportedZopeInterfaceVersion,
                str(raised.exception))


    def test_missingZopeInterface(self):
        """
        L{_checkRequirements} raises L{ImportError} when the C{zope.interface}
        package is not installed.
        """
        with SetAsideModule("zope"):
            # Create a minimal module to represent the zope namespace package,
            # but don't give it an "interface" attribute.
            sys.modules["zope"] = ModuleType("zope")
            with self.assertRaises(ImportError) as raised:
                _checkRequirements()
            self.assertEqual(
                "Twisted requires zope.interface %d.%d.%d or later: no module "
                "named zope.interface." % self.supportedZopeInterfaceVersion,
                str(raised.exception))


    def test_setupNoCheckRequirements(self):
        """
        L{_checkRequirements} doesn't check for C{zope.interface} compliance
        when C{setuptools._TWISTED_NO_CHECK_REQUIREMENTS} is set.
        """
        with SetAsideModule("setuptools"):
            setuptools = ModuleType("setuptools")
            setuptools._TWISTED_NO_CHECK_REQUIREMENTS = True
            sys.modules["setuptools"] = setuptools
            with SetAsideModule("zope"):
                sys.modules["zope"] = None
                _checkRequirements()


    def test_setupCheckRequirements(self):
        """
        L{_checkRequirements} checks for C{zope.interface} compliance when
        C{setuptools} is imported but the C{_TWISTED_NO_CHECK_REQUIREMENTS} is
        not set.
        """
        with SetAsideModule("setuptools"):
            sys.modules["setuptools"] = ModuleType("setuptools")
            with SetAsideModule("zope"):
                sys.modules["zope"] = None
                self.assertRaises(ImportError, _checkRequirements)


    def test_noSetupCheckRequirements(self):
        """
        L{_checkRequirements} checks for C{zope.interface} compliance when
        C{setuptools} is not imported.
        """
        with SetAsideModule("setuptools"):
            sys.modules["setuptools"] = None
            with SetAsideModule("zope"):
                sys.modules["zope"] = None
                self.assertRaises(ImportError, _checkRequirements)


    if _PY3:
        # Python 3 requires a version that isn't tripped up by the __qualname__
        # special attribute.

        def test_oldZopeInterface(self):
            """
            If the installed version of C{zope.interface} does not support the
            C{implementer} class decorator, L{_checkRequirements} raises
            L{ImportError} with a message explaining a newer version is
            required.
            """
            with SetAsideModule("zope"):
                _install(_zope38)
                with self.assertRaises(ImportError) as raised:
                    _checkRequirements()
            self.assertEqual(
                "Twisted requires zope.interface 4.0.0 or later.",
                str(raised.exception))


        def test_newZopeInterface(self):
            """
            If the installed version of C{zope.interface} does support the
            C{implementer} class decorator, L{_checkRequirements} returns
            C{None}.
            """
            with SetAsideModule("zope"):
                _install(_zope40)
                self.assertEqual(None, _checkRequirements())

    else:
        # Python 2 only requires a version that supports the class decorator
        # version of declarations.

        def test_oldZopeInterface(self):
            """
            L{_checkRequirements} raises L{ImportError} when the C{zope.interface}
            package installed is old enough that C{implementer_only} is not included
            (added in zope.interface 3.6).
            """
            with SetAsideModule("zope"):
                _install(_zope35)
                with self.assertRaises(ImportError) as raised:
                    _checkRequirements()
                self.assertEqual(
                    "Twisted requires zope.interface 3.6.0 or later.",
                    str(raised.exception))


        def test_newZopeInterface(self):
            """
            L{_checkRequirements} returns C{None} when C{zope.interface} is
            installed and new enough.
            """
            with SetAsideModule("zope"):
                _install(_zope36)
                self.assertEqual(None, _checkRequirements())



class MakePackagesTests(TestCase):
    """
    Tests for L{_makePackages}, a helper for populating C{sys.modules} with
    fictional modules.
    """
    def test_nonModule(self):
        """
        A non-C{dict} value in the attributes dictionary passed to L{_makePackages}
        is preserved unchanged in the return value.
        """
        modules = {}
        _makePackages(None, dict(reactor='reactor'), modules)
        self.assertEqual(modules, dict(reactor='reactor'))


    def test_moduleWithAttribute(self):
        """
        A C{dict} value in the attributes dictionary passed to L{_makePackages}
        is turned into a L{ModuleType} instance with attributes populated from
        the items of that C{dict} value.
        """
        modules = {}
        _makePackages(None, dict(twisted=dict(version='123')), modules)
        self.assertTrue(isinstance(modules, dict))
        self.assertTrue(isinstance(modules['twisted'], ModuleType))
        self.assertEqual('twisted', modules['twisted'].__name__)
        self.assertEqual('123', modules['twisted'].version)


    def test_packageWithModule(self):
        """
        Processing of the attributes dictionary is recursive, so a C{dict} value
        it contains may itself contain a C{dict} value to the same effect.
        """
        modules = {}
        _makePackages(None, dict(twisted=dict(web=dict(version='321'))), modules)
        self.assertTrue(isinstance(modules, dict))
        self.assertTrue(isinstance(modules['twisted'], ModuleType))
        self.assertEqual('twisted', modules['twisted'].__name__)
        self.assertTrue(isinstance(modules['twisted'].web, ModuleType))
        self.assertEqual('twisted.web', modules['twisted'].web.__name__)
        self.assertEqual('321', modules['twisted'].web.version)



def _functionOnlyImplementer(*interfaces):
    """
    A fake implementation of L{zope.interface.implementer} which always behaves
    like the version of that function provided by zope.interface 3.5 and older.
    """
    def check(obj):
        """
        If the decorated object is not a function, raise an exception.
        """
        if not isinstance(obj, FunctionType):
            raise TypeError(
                "Can't use implementer with classes.  "
                "Use one of the class-declaration functions instead.")
    return check



def _classSupportingImplementer(*interfaces):
    """
    A fake implementation of L{zope.interface.implementer} which always
    succeeds.  For the use it is put to, this is like the version of that
    function provided by zope.interface 3.6 and newer.
    """
    def check(obj):
        """
        Do nothing at all.
        """
    return check



class _SuccessInterface(object):
    """
    A fake implementation of L{zope.interface.Interface} with no behavior.  For
    the use it is put to, this is equivalent to the behavior of the C{Interface}
    provided by all versions of zope.interface.
    """


# Definition of a module somewhat like zope.interface 3.5.
_zope35 = {
    'zope': {
        'interface': {
            'Interface': _SuccessInterface,
            'implementer': _functionOnlyImplementer,
            },
        },
    }


# Definition of a module somewhat like zope.interface 3.6.
_zope36 = {
    'zope': {
        'interface': {
            'Interface': _SuccessInterface,
            'implementer': _classSupportingImplementer,
            },
        },
    }


class _Zope38OnPython3Module(object):
    """
    A pseudo-module which raises an exception when its C{interface} attribute is
    accessed.  This is like the behavior of zope.interface 3.8 and earlier when
    used with Python 3.3.
    """
    __path__ = []
    __name__ = 'zope'

    @property
    def interface(self):
        raise Exception(
            "zope.interface.exceptions.InvalidInterface: "
            "Concrete attribute, __qualname__")

# Definition of a module somewhat like zope.interface 3.8 when it is used on Python 3.
_zope38 = {
    'zope': _Zope38OnPython3Module(),
    }

# Definition of a module somewhat like zope.interface 4.0.
_zope40 = {
    'zope': {
        'interface': {
            'Interface': _SuccessInterface,
            'implementer': _classSupportingImplementer,
            },
        },
    }


class ZopeInterfaceTestsMixin(object):
    """
    Verify the C{zope.interface} fakes, only possible when a specific version of
    the real C{zope.interface} package is installed on the system.

    Subclass this and override C{install} to properly install and then remove
    the given version of C{zope.interface}.
    """
    def test_zope35(self):
        """
        Version 3.5 of L{zope.interface} has a C{implementer} method which
        cannot be used as a class decorator.
        """
        with SetAsideModule("zope"):
            self.install((3, 5))
            from zope.interface import Interface, implementer
            class IDummy(Interface):
                pass
            try:
                @implementer(IDummy)
                class Dummy(object):
                    pass
            except TypeError as exc:
                self.assertEqual(
                    "Can't use implementer with classes.  "
                    "Use one of the class-declaration functions instead.",
                    str(exc))


    def test_zope36(self):
        """
        Version 3.6 of L{zope.interface} has a C{implementer} method which can
        be used as a class decorator.
        """
        with SetAsideModule("zope"):
            self.install((3, 6))
            from zope.interface import Interface, implementer
            class IDummy(Interface):
                pass
            @implementer(IDummy)
            class Dummy(object):
                pass

    if _PY3:
        def test_zope38(self):
            """
            Version 3.8 of L{zope.interface} does not even import on Python 3.
            """
            with SetAsideModule("zope"):
                self.install((3, 8))
                try:
                    from zope import interface
                except Exception as exc:
                    self.assertEqual(
                        "zope.interface.exceptions.InvalidInterface: "
                        "Concrete attribute, __qualname__",
                        str(exc))
                else:
                    self.fail(
                        "InvalidInterface was not raised by zope.interface import")


        def test_zope40(self):
            """
            Version 4.0 of L{zope.interface} can import on Python 3 and, also on
            Python 3, has an C{Interface} class which can be subclassed.
            """
            with SetAsideModule("zope"):
                self.install((4, 0))
                from zope.interface import Interface
                class IDummy(Interface):
                    pass


class FakeZopeInterfaceTests(TestCase, ZopeInterfaceTestsMixin):
    """
    Apply the zope.interface tests to the fakes implemented in this module.
    """
    versions = {
        (3, 5): _zope35,
        (3, 6): _zope36,
        (3, 8): _zope38,
        (4, 0): _zope40,
        }

    def install(self, version):
        """
        Grab one of the fake module implementations and install it into
        C{sys.modules} for use by the test.
        """
        _install(self.versions[version])


# Python 2.6 stdlib unittest does not support skipping.  Use trial's
# SynchronousTestCase instead.  When Python 2.6 support is dropped, this can
# switch back to using the stdlib TestCase with its skip support.
if sys.version_info[:2] == (2, 6):
    from twisted.trial.unittest import SkipTest, SynchronousTestCase as TestCase
else:
    from unittest import SkipTest

class RealZopeInterfaceTests(TestCase, ZopeInterfaceTestsMixin):
    """
    Apply whichever tests from L{ZopeInterfaceTestsMixin} are applicable to the
    system-installed version of zope.interface.
    """
    def install(self, version):
        """
        Check to see if the system-installed version of zope.interface matches
        the version requested.  If so, do nothing.  If not, skip the test (if
        the desired version is not installed, there is no way to test its
        behavior).  If the version of zope.interface cannot be determined
        (because pkg_resources is not installed), skip the test.
        """
        # Use an unrelated, but unreliable, route to try to determine what
        # version of zope.interface is installed on the system.  It's sort of
        # okay to use this unreliable scheme here, since if it fails it only
        # means we won't be able to run the tests.  Hopefully someone else
        # managed to run the tests somewhere else.
        try:
            import pkg_resources
        except ImportError as e:
            raise SkipTest(
                "Cannot determine system version of zope.interface: %s" % (e,))
        else:
            try:
                pkg = pkg_resources.get_distribution("zope.interface")
            except pkg_resources.DistributionNotFound as e:
                raise SkipTest(
                    "Cannot determine system version of zope.interface: %s" % (
                        e,))
            installed = pkg.version
            versionTuple = tuple(
                int(part) for part in installed.split('.')[:len(version)])
            if versionTuple == version:
                pass
            else:
                raise SkipTest("Mismatched system version of zope.interface")