This file is indexed.

/usr/lib/python2.7/dist-packages/reportlab/lib/testutils.py is in python-reportlab 3.3.0-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
#Copyright ReportLab Europe Ltd. 2000-2016
#see license.txt for license details
import reportlab
reportlab._rl_testing=True
del reportlab
__version__='3.3.0'
__doc__="""Provides support for the test suite.

The test suite as a whole, and individual tests, need to share
certain support functions.  We have to put these in here so they
can always be imported, and so that individual tests need to import
nothing more than "reportlab.whatever..."
"""

import sys, os, fnmatch, re
try:
    from configparser import ConfigParser
except ImportError:
    from ConfigParser import ConfigParser
import unittest
from reportlab.lib.utils import isCompactDistro, __loader__, rl_isdir, asUnicode

# Helper functions.
def isWritable(D):
    try:
        fn = '00DELETE.ME'
        f = open(fn, 'w')
        f.write('test of writability - can be deleted')
        f.close()
        if os.path.isfile(fn):
            os.remove(fn)
            return 1
    except:
        return 0

_OUTDIR = None
RL_HOME = None
testsFolder = None
def setOutDir(name):
    """Is it a writable file system distro being invoked within
    test directory?  If so, can write test output here.  If not,
    it had better go in a temp directory.  Only do this once per
    process"""
    global _OUTDIR, RL_HOME, testsFolder
    if _OUTDIR: return _OUTDIR
    D = [d[9:] for d in sys.argv if d.startswith('--outdir=')]
    if D:
        _OUTDIR = D[-1]
        try:
            os.makedirs(_OUTDIR)
        except:
            pass
        for d in D: sys.argv.remove(d)
    else:
        assert name=='__main__',"setOutDir should only be called in the main script"
        scriptDir=os.path.dirname(sys.argv[0])
        if not scriptDir: scriptDir=os.getcwd()
        _OUTDIR = scriptDir

    if not isWritable(_OUTDIR):
        _OUTDIR = get_rl_tempdir('reportlab_test')

    import reportlab
    RL_HOME=reportlab.__path__[0]
    if not os.path.isabs(RL_HOME): RL_HOME=os.path.normpath(os.path.abspath(RL_HOME))
    topDir = os.path.dirname(RL_HOME)
    testsFolder = os.path.join(topDir,'tests')
    if not os.path.isdir(testsFolder):
        testsFolder = os.path.join(os.path.dirname(topDir),'tests')
    if not os.path.isdir(testsFolder):
        if name=='__main__':
            scriptDir=os.path.dirname(sys.argv[0])
            if not scriptDir: scriptDir=os.getcwd()
            testsFolder = os.path.abspath(scriptDir)
        else:
            testsFolder = None
    if testsFolder:
        sys.path.insert(0,os.path.dirname(testsFolder))
    return _OUTDIR

def outputfile(fn):
    """This works out where to write test output.  If running
    code in a locked down file system, this will be a
    temp directory; otherwise, the output of 'test_foo.py' will
    normally be a file called 'test_foo.pdf', next door.
    """
    D = setOutDir(__name__)
    if fn: D = os.path.join(D,fn)
    return D

def printLocation(depth=1):
    if sys._getframe(depth).f_locals.get('__name__')=='__main__':
        outDir = outputfile('')
        if outDir!=_OUTDIR:
            print('Logs and output files written to folder "%s"' % outDir)

def makeSuiteForClasses(*classes):
    "Return a test suite with tests loaded from provided classes."

    suite = unittest.TestSuite()
    loader = unittest.TestLoader()
    for C in classes:
        suite.addTest(loader.loadTestsFromTestCase(C))
    return suite

def getCVSEntries(folder, files=1, folders=0):
    """Returns a list of filenames as listed in the CVS/Entries file.

    'folder' is the folder that should contain the CVS subfolder.
    If there is no such subfolder an empty list is returned.
    'files' is a boolean; 1 and 0 means to return files or not.
    'folders' is a boolean; 1 and 0 means to return folders or not.
    """

    join = os.path.join

    # If CVS subfolder doesn't exist return empty list.
    try:
        f = open(join(folder, 'CVS', 'Entries'))
    except IOError:
        return []

    # Return names of files and/or folders in CVS/Entries files.
    allEntries = []
    for line in f.readlines():
        if folders and line[0] == 'D' \
           or files and line[0] != 'D':
            entry = line.split('/')[1]
            if entry:
                allEntries.append(join(folder, entry))

    return allEntries


# Still experimental class extending ConfigParser's behaviour.
class ExtConfigParser(ConfigParser):
    "A slightly extended version to return lists of strings."

    pat = re.compile('\s*\[.*\]\s*')

    def getstringlist(self, section, option):
        "Coerce option to a list of strings or return unchanged if that fails."

        value = ConfigParser.get(self, section, option)

        # This seems to allow for newlines inside values
        # of the config file, but be careful!!
        val = value.replace('\n', '')

        if self.pat.match(val):
            return eval(val)
        else:
            return value


# This class as suggested by /F with an additional hook
# to be able to filter filenames.

class GlobDirectoryWalker:
    "A forward iterator that traverses files in a directory tree."

    def __init__(self, directory, pattern='*'):
        self.index = 0
        self.pattern = pattern
        directory.replace('/',os.sep)
        if os.path.isdir(directory):
            self.stack = [directory]
            self.files = []
        else:
            if not isCompactDistro() or not __loader__ or not rl_isdir(directory):
                raise ValueError('"%s" is not a directory' % directory)
            self.directory = directory[len(__loader__.archive)+len(os.sep):]
            pfx = self.directory+os.sep
            n = len(pfx)
            self.files = list(map(lambda x, n=n: x[n:],list(filter(lambda x,pfx=pfx: x.startswith(pfx),list(__loader__._files.keys())))))
            self.stack = []

    def __getitem__(self, index):
        while 1:
            try:
                file = self.files[self.index]
                self.index = self.index + 1
            except IndexError:
                # pop next directory from stack
                self.directory = self.stack.pop()
                self.files = os.listdir(self.directory)
                # now call the hook
                self.files = self.filterFiles(self.directory, self.files)
                self.index = 0
            else:
                # got a filename
                fullname = os.path.join(self.directory, file)
                if os.path.isdir(fullname) and not os.path.islink(fullname):
                    self.stack.append(fullname)
                if fnmatch.fnmatch(file, self.pattern):
                    return fullname

    def filterFiles(self, folder, files):
        "Filter hook, overwrite in subclasses as needed."

        return files


class RestrictedGlobDirectoryWalker(GlobDirectoryWalker):
    "An restricted directory tree iterator."

    def __init__(self, directory, pattern='*', ignore=None):
        GlobDirectoryWalker.__init__(self, directory, pattern)

        if ignore == None:
            ignore = []
        self.ignoredPatterns = []
        if type(ignore) == type([]):
            for p in ignore:
                self.ignoredPatterns.append(p)
        elif type(ignore) == type(''):
            self.ignoredPatterns.append(ignore)


    def filterFiles(self, folder, files):
        "Filters all items from files matching patterns to ignore."

        indicesToDelete = []
        for i in range(len(files)):
            f = files[i]
            for p in self.ignoredPatterns:
                if fnmatch.fnmatch(f, p):
                    indicesToDelete.append(i)
        indicesToDelete.reverse()
        for i in indicesToDelete:
            del files[i]

        return files


class CVSGlobDirectoryWalker(GlobDirectoryWalker):
    "An directory tree iterator that checks for CVS data."

    def filterFiles(self, folder, files):
        """Filters files not listed in CVS subfolder.

        This will look in the CVS subfolder of 'folder' for
        a file named 'Entries' and filter all elements from
        the 'files' list that are not listed in 'Entries'.
        """

        join = os.path.join
        cvsFiles = getCVSEntries(folder)
        if cvsFiles:
            indicesToDelete = []
            for i in range(len(files)):
                f = files[i]
                if join(folder, f) not in cvsFiles:
                    indicesToDelete.append(i)
            indicesToDelete.reverse()
            for i in indicesToDelete:
                del files[i]

        return files


# An experimental untested base class with additional 'security'.

class SecureTestCase(unittest.TestCase):
    """Secure testing base class with additional pre- and postconditions.

    We try to ensure that each test leaves the environment it has
    found unchanged after the test is performed, successful or not.

    Currently we restore sys.path and the working directory, but more
    of this could be added easily, like removing temporary files or
    similar things.

    Use this as a base class replacing unittest.TestCase and call
    these methods in subclassed versions before doing your own
    business!
    """

    def setUp(self):
        "Remember sys.path and current working directory."
        self._initialPath = sys.path[:]
        self._initialWorkDir = os.getcwd()

    def tearDown(self):
        "Restore previous sys.path and working directory."
        sys.path = self._initialPath
        os.chdir(self._initialWorkDir)

class NearTestCase(unittest.TestCase):
    def assertNear(a,b,accuracy=1e-5):
        if isinstance(a,(float,int)):
            if abs(a-b)>accuracy:
                raise AssertionError("%s not near %s" % (a, b))
        else:
            for ae,be in zip(a,b):
                if abs(ae-be)>accuracy:
                    raise AssertionError("%s not near %s" % (a, b))
    assertNear = staticmethod(assertNear)

class ScriptThatMakesFileTest(unittest.TestCase):
    """Runs a Python script at OS level, expecting it to produce a file.

    It CDs to the working directory to run the script."""
    def __init__(self, scriptDir, scriptName, outFileName, verbose=0):
        self.scriptDir = scriptDir
        self.scriptName = scriptName
        self.outFileName = outFileName
        self.verbose = verbose
        # normally, each instance is told which method to run)
        unittest.TestCase.__init__(self)

    def setUp(self):
        self.cwd = os.getcwd()
        global testsFolder
        scriptDir=self.scriptDir
        if not os.path.isabs(scriptDir):
            scriptDir=os.path.join(testsFolder,scriptDir)

        os.chdir(scriptDir)
        assert os.path.isfile(self.scriptName), "Script %s not found!" % self.scriptName
        if os.path.isfile(self.outFileName):
            os.remove(self.outFileName)

    def tearDown(self):
        os.chdir(self.cwd)

    def runTest(self):
        fmt = sys.platform=='win32' and '"%s" %s' or '%s %s'
        p = os.popen(fmt % (sys.executable,self.scriptName),'r')
        out = p.read()
        if self.verbose:
            print(out)
        status = p.close()
        assert os.path.isfile(self.outFileName), "File %s not created!" % self.outFileName

def equalStrings(a,b,enc='utf8'):
    return a==b if type(a)==type(b) else asUnicode(a,enc)==asUnicode(b,enc)

def eqCheck(r,x):
    if r!=x:
        print('Strings unequal\nexp: %s\ngot: %s' % (ascii(x),ascii(r)))