This file is indexed.

/usr/lib/python3/dist-packages/nose2/util.py is in python3-nose2 0.7.4-1.

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
# This module contains some code copied from unittest2/loader.py and other
# code developed in reference to that module and others within unittest2.

# unittest2 is Copyright (c) 2001-2010 Python Software Foundation; All
# Rights Reserved. See: http://docs.python.org/license.html

import logging
import os
import types
import re
import sys
import traceback
import platform
import six
import inspect
from inspect import isgeneratorfunction  # new in 2.6


__unittest = True
IDENT_RE = re.compile(r'^[_a-zA-Z]\w*$', re.UNICODE)
VALID_MODULE_RE = re.compile(r'[_a-zA-Z]\w*\.py$', re.UNICODE)


def ln(label, char='-', width=70):
    """Draw a divider, with ``label`` in the middle.

    >>> ln('hello there')
    '---------------------------- hello there -----------------------------'

    ``width`` and divider ``char`` may be specified. Defaults are ``70`` and ``'-'``,
    respectively.

    """
    label_len = len(label) + 2
    chunk = (width - label_len) // 2
    out = '%s %s %s' % (char * chunk, label, char * chunk)
    pad = width - len(out)
    if pad > 0:
        out = out + (char * pad)
    return out


def valid_module_name(path):
    """Is ``path`` a valid module name?"""
    return VALID_MODULE_RE.search(path)


def name_from_path(path):
    """Translate ``path`` into module name

    Returns a two-element tuple:

    1. a dotted module name that can be used in an import statement
       (e.g., ``pkg1.test.test_things``)

    2. a full path to filesystem directory, which must be on ``sys.path``
       for the import to succeed.

    """
    # back up to find module root
    parts = []
    path = os.path.normpath(path)
    base = os.path.splitext(path)[0]
    candidate, top = os.path.split(base)
    parts.append(top)
    while candidate:
        if ispackage(candidate):
            candidate, top = os.path.split(candidate)
            parts.append(top)
        else:
            break
    return '.'.join(reversed(parts)), candidate


def module_from_name(name):
    """Import module from ``name``"""
    __import__(name)
    return sys.modules[name]


def test_from_name(name, module):
    """Import test from ``name``"""
    pos = name.find(':')
    index = None
    if pos != -1:
        real_name, digits = name[:pos], name[pos + 1:]
        try:
            index = int(digits)
        except ValueError:
            pass
        else:
            name = real_name
    parent, obj = object_from_name(name, module)
    return parent, obj, name, index


def object_from_name(name, module=None):
    """
    Given a dotted name, return the corresponding object.

    Getting the object can fail for two reason:

        - the object is a module that cannot be imported.
        - the object is a class or a function that does not exists.

    Since we cannot distinguish between these two cases, we assume we are in
    the first one. We expect the stacktrace is explicit enough for the user to
    understand the error.
    """
    import_error = None
    parts = name.split('.')
    if module is None:
        (module, import_error) = try_import_module_from_name(parts[:])
        parts = parts[1:]
    parent = None
    obj = module
    for part in parts:
        try:
            parent, obj = obj, getattr(obj, part)
        except AttributeError as e:
            if is_package_or_module(obj) and import_error:
                # Re-raise the import error which got us here, since
                # it probably better describes the issue.
                _raise_custom_attribute_error(obj, part, e, import_error)
            else:
                raise

    return parent, obj


def _raise_custom_attribute_error(obj, attr, attr_error_exc, prev_exc):

    if sys.version_info >= (3, 0):
        six.raise_from(attr_error_exc, prev_exc[1])

    # for python 2, do exception chaining manually
    raise AttributeError(
        "'%s' has not attribute '%s'\n\nMaybe caused by\n\n%s" % (
            obj, attr, '\n'.join(traceback.format_exception(*prev_exc))))


def is_package_or_module(obj):
    if hasattr(obj, '__path__') or isinstance(obj, types.ModuleType):
        return True
    return False


def try_import_module_from_name(splitted_name):
    """
    Try to find the longest importable from the ``splitted_name``, and return
    the corresponding module, as well as the potential ``ImportError``
    exception that occurs when trying to import a longer name.

    For instance, if ``splitted_name`` is ['a', 'b', 'c'] but only ``a.b`` is
    importable, this function:
    
        1. tries to import ``a.b.c`` and fails
        2. tries to import ``a.b`` and succeeds
        3. return ``a.b`` and the exception that occured at step 1.
    """
    module = None
    import_error = None
    while splitted_name:
        try:
            module = __import__('.'.join(splitted_name))
            break
        except:
            import_error = sys.exc_info()
            del splitted_name[-1]
            if not splitted_name:
                six.reraise(*sys.exc_info())
    return (module, import_error)


def name_from_args(name, index, args):
    """Create test name from test args"""
    summary = ', '.join(repr(arg) for arg in args)
    return '%s:%s\n%s' % (name, index + 1, summary[:79])


def test_name(test, qualname=True):
    # XXX does not work for test funcs; test.id() lacks module
    if hasattr(test, '_funcName'):
        tid = test._funcName
    elif hasattr(test, '_testFunc'):
        tid = "%s.%s" % (test._testFunc.__module__, test._testFunc.__name__)
    else:
        if sys.version_info >= (3, 5) and not qualname:
            test_module = test.__class__.__module__
            test_class = test.__class__.__name__
            test_method = test._testMethodName
            tid = "%s.%s.%s" % (test_module, test_class, test_method)
        else:
            tid = test.id()
    if '\n' in tid:
        tid = tid.split('\n')[0]
    return tid


def ispackage(path):
    """Is this path a package directory?"""
    if os.path.isdir(path):
        # at least the end of the path must be a legal python identifier
        # and __init__.py[co] must exist
        end = os.path.basename(path)
        if IDENT_RE.match(end):
            for init in ('__init__.py', '__init__.pyc', '__init__.pyo'):
                if os.path.isfile(os.path.join(path, init)):
                    return True
            if sys.platform.startswith('java') and \
                    os.path.isfile(os.path.join(path, '__init__$py.class')):
                return True
    return False


def ensure_importable(dirname):
    """Ensure a directory is on ``sys.path``."""
    if dirname not in sys.path:
        sys.path.insert(0, dirname)


def isgenerator(obj):
    """Is this object a generator?"""
    return (isgeneratorfunction(obj)
            or getattr(obj, 'testGenerator', None) is not None)


def has_module_fixtures(test):
    """Does this test live in a module with module fixtures?"""
    modname = test.__class__.__module__
    try:
        mod = sys.modules[modname]
    except KeyError:
        return
    return hasattr(mod, 'setUpModule') or hasattr(mod, 'tearDownModule')


def has_class_fixtures(test):
    # hasattr would be the obvious thing to use here. Unfortunately, all tests
    # inherit from unittest2.case.TestCase, and that *always* has setUpClass and
    # tearDownClass methods. Thus, exclude the unitest and unittest2 base
    # classes from the lookup.
    def is_not_base_class(c):
        return (
            "unittest.case" not in c.__module__ and
            "unittest2.case" not in c.__module__)
    has_class_setups = any(
        'setUpClass' in c.__dict__ for c in test.__class__.__mro__ if is_not_base_class(c))
    has_class_teardowns = any(
        'tearDownClass' in c.__dict__ for c in test.__class__.__mro__ if is_not_base_class(c))
    return has_class_setups or has_class_teardowns


def safe_decode(string):
    """Safely decode a byte string into unicode"""
    if string is None:
        return string
    try:
        return string.decode()
    except AttributeError:
        return string
    except UnicodeDecodeError:
        pass
    try:
        return string.decode('utf-8')
    except UnicodeDecodeError:
        return six.u('<unable to decode>')


def safe_encode(string, encoding='utf-8'):
    if string is None:
        return string
    if encoding is None:
        encoding = 'utf-8'
    try:
        return string.encode(encoding)
    except AttributeError:
        return string
    except UnicodeDecodeError:
        # already encoded
        return string
    except UnicodeEncodeError:
        return six.u('<unable to encode>')


def exc_info_to_string(err, test):
    """Format exception info for output"""
    formatTraceback = getattr(test, 'formatTraceback', None)
    if formatTraceback is not None:
        return test.formatTraceback(err)
    else:
        return format_traceback(test, err)


def format_traceback(test, err):
    """Converts a :func:`sys.exc_info` -style tuple of values into a string."""
    exctype, value, tb = err
    if not hasattr(tb, 'tb_next'):
        msgLines = tb
    else:
        # Skip test runner traceback levels
        while tb and _is_relevant_tb_level(tb):
            tb = tb.tb_next
        failure = getattr(test, 'failureException', AssertionError)
        if exctype is failure:
            # Skip assert*() traceback levels
            length = _count_relevant_tb_levels(tb)
            msgLines = traceback.format_exception(exctype, value, tb, length)
        else:
            msgLines = traceback.format_exception(exctype, value, tb)

    return ''.join(msgLines)


def transplant_class(cls, module):
    """Make ``cls`` appear to reside in ``module``.

    :param cls: A class
    :param module: A module name
    :returns: A subclass of ``cls`` that appears to have been defined in ``module``.

    The returned class's ``__name__`` will be equal to
    ``cls.__name__``, and its ``__module__`` equal to ``module``.

    """
    class C(cls):
        pass
    C.__module__ = module
    C.__name__ = cls.__name__
    return C


def parse_log_level(lvl):
    """Return numeric log level given a string"""
    try:
        return int(lvl)
    except ValueError:
        pass
    return getattr(logging, lvl.upper(), logging.WARN)


def _is_relevant_tb_level(tb):
    return '__unittest' in tb.tb_frame.f_globals


def _count_relevant_tb_levels(tb):
    length = 0
    while tb and not _is_relevant_tb_level(tb):
        length += 1
        tb = tb.tb_next
    return length


class _WritelnDecorator(object):

    """Used to decorate file-like objects with a handy :func:`writeln` method"""

    def __init__(self, stream):
        self.stream = stream

    def __getattr__(self, attr):
        if attr in ('stream', '__getstate__'):
            raise AttributeError(attr)
        return getattr(self.stream, attr)

    def write(self, arg):
        if sys.version_info[0] == 2:
            arg = safe_encode(arg, getattr(self.stream, 'encoding', 'utf-8'))
        self.stream.write(arg)

    def writeln(self, arg=None):
        if arg:
            self.write(arg)
        self.write('\n')  # text-mode streams translate to \r\n if needed


def ancestry(layer):
    layers = [[layer]]
    bases = [base for base in bases_and_mixins(layer)
             if base is not object]
    while bases:
        layers.append(bases)
        newbases = []
        for b in bases:
            for bb in bases_and_mixins(b):
                if bb is not object:
                    newbases.append(bb)
        bases = newbases
    layers.reverse()
    return layers


def bases_and_mixins(layer):
    return (layer.__bases__ + getattr(layer, 'mixins', ()))


def num_expected_args(func):
    """Return the number of arguments that :func: expects"""
    if six.PY2:
        return len(inspect.getargspec(func)[0])
    else:
        return len(inspect.getfullargspec(func)[0])


def call_with_args_if_expected(func, *args):
    """Take :func: and call it with supplied :args:, in case that signature expects any.
    Otherwise call the function without any arguments.
    """
    if num_expected_args(func) > 0:
        func(*args)
    else:
        func()