runtests.py 15.2 KB
Newer Older
1 2
#!/usr/bin/python

3
import os, sys, re, shutil, unittest, doctest
4

5
WITH_CYTHON = True
Robert Bradshaw's avatar
merge  
Robert Bradshaw committed
6

7
from distutils.dist import Distribution
8 9
from distutils.core import Extension
from distutils.command.build_ext import build_ext
10 11
distutils_distro = Distribution()

12 13
TEST_DIRS = ['compile', 'errors', 'run', 'pyregr']
TEST_RUN_DIRS = ['run', 'pyregr']
14

15
INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
16 17
CFLAGS = os.getenv('CFLAGS', '').split()

18 19

class ErrorWriter(object):
20
    match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
21 22 23 24
    def __init__(self):
        self.output = []
        self.write = self.output.append

25
    def _collect(self, collect_errors, collect_warnings):
26
        s = ''.join(self.output)
27
        result = []
28 29 30
        for line in s.split('\n'):
            match = self.match_error(line)
            if match:
31 32 33
                is_warning, line, column, message = match.groups()
                if (is_warning and collect_warnings) or \
                        (not is_warning and collect_errors):
34 35
                    result.append( (int(line), int(column), message.strip()) )
        result.sort()
Stefan Behnel's avatar
Stefan Behnel committed
36
        return [ "%d:%d: %s" % values for values in result ]
37 38 39 40 41 42 43 44 45

    def geterrors(self):
        return self._collect(True, False)

    def getwarnings(self):
        return self._collect(False, True)

    def getall(self):
        return self._collect(True, True)
46

47
class TestBuilder(object):
48
    def __init__(self, rootdir, workdir, selectors, annotate,
49
                 cleanup_workdir, cleanup_sharedlibs, with_pyregr):
50 51
        self.rootdir = rootdir
        self.workdir = workdir
52
        self.selectors = selectors
53
        self.annotate = annotate
54
        self.cleanup_workdir = cleanup_workdir
55
        self.cleanup_sharedlibs = cleanup_sharedlibs
56
        self.with_pyregr = with_pyregr
57 58 59

    def build_suite(self):
        suite = unittest.TestSuite()
60 61 62
        filenames = os.listdir(self.rootdir)
        filenames.sort()
        for filename in filenames:
63 64 65
            if not WITH_CYTHON and filename == "errors":
                # we won't get any errors without running Cython
                continue
66 67
            path = os.path.join(self.rootdir, filename)
            if os.path.isdir(path) and filename in TEST_DIRS:
68 69
                if filename == 'pyregr' and not self.with_pyregr:
                    continue
70
                suite.addTest(
71
                    self.handle_directory(path, filename))
72 73
        return suite

74
    def handle_directory(self, path, context):
75 76 77 78 79 80
        workdir = os.path.join(self.workdir, context)
        if not os.path.exists(workdir):
            os.makedirs(workdir)
        if workdir not in sys.path:
            sys.path.insert(0, workdir)

81
        expect_errors = (context == 'errors')
82
        suite = unittest.TestSuite()
83 84 85
        filenames = os.listdir(path)
        filenames.sort()
        for filename in filenames:
86
            if not (filename.endswith(".pyx") or filename.endswith(".py")):
87
                continue
88 89
            if context == 'pyregr' and not filename.startswith('test_'):
                continue
90
            module = os.path.splitext(filename)[0]
91 92 93 94 95
            fqmodule = "%s.%s" % (context, module)
            if not [ 1 for match in self.selectors
                     if match(fqmodule) ]:
                continue
            if context in TEST_RUN_DIRS:
96 97 98 99 100
                if module.startswith("test_"):
                    build_test = CythonUnitTestCase
                else:
                    build_test = CythonRunTestCase
                test = build_test(
101 102
                    path, workdir, module,
                    annotate=self.annotate,
103 104
                    cleanup_workdir=self.cleanup_workdir,
                    cleanup_sharedlibs=self.cleanup_sharedlibs)
105 106
            else:
                test = CythonCompileTestCase(
107 108 109
                    path, workdir, module,
                    expect_errors=expect_errors,
                    annotate=self.annotate,
110 111
                    cleanup_workdir=self.cleanup_workdir,
                    cleanup_sharedlibs=self.cleanup_sharedlibs)
112
            suite.addTest(test)
113 114 115
        return suite

class CythonCompileTestCase(unittest.TestCase):
116
    def __init__(self, directory, workdir, module,
117 118
                 expect_errors=False, annotate=False, cleanup_workdir=True,
                 cleanup_sharedlibs=True):
119 120 121
        self.directory = directory
        self.workdir = workdir
        self.module = module
122
        self.expect_errors = expect_errors
123
        self.annotate = annotate
124
        self.cleanup_workdir = cleanup_workdir
125
        self.cleanup_sharedlibs = cleanup_sharedlibs
126 127 128 129 130
        unittest.TestCase.__init__(self)

    def shortDescription(self):
        return "compiling " + self.module

131
    def tearDown(self):
132
        cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
133
        cleanup_lib_files = self.cleanup_sharedlibs
134
        if os.path.exists(self.workdir):
135
            for rmfile in os.listdir(self.workdir):
136 137
                if not cleanup_c_files and rmfile[-2:] in (".c", ".h"):
                    continue
138 139
                if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
                    continue
140 141 142 143 144 145 146 147 148 149 150 151
                if self.annotate and rmfile.endswith(".html"):
                    continue
                try:
                    rmfile = os.path.join(self.workdir, rmfile)
                    if os.path.isdir(rmfile):
                        shutil.rmtree(rmfile, ignore_errors=True)
                    else:
                        os.remove(rmfile)
                except IOError:
                    pass
        else:
            os.makedirs(self.workdir)
152

153
    def runTest(self):
154 155 156
        self.runCompileTest()

    def runCompileTest(self):
157
        self.compile(self.directory, self.module, self.workdir,
158
                     self.directory, self.expect_errors, self.annotate)
159

160 161 162 163 164
    def find_module_source_file(self, source_file):
        if not os.path.exists(source_file):
            source_file = source_file[:-1]
        return source_file

165
    def split_source_and_output(self, directory, module, workdir):
166
        source_file = os.path.join(directory, module) + '.pyx'
167
        source_and_output = open(
168
            self.find_module_source_file(source_file), 'rU')
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
        out = open(os.path.join(workdir, module + '.pyx'), 'w')
        for line in source_and_output:
            last_line = line
            if line.startswith("_ERRORS"):
                out.close()
                out = ErrorWriter()
            else:
                out.write(line)
        try:
            geterrors = out.geterrors
        except AttributeError:
            return []
        else:
            return geterrors()

184
    def run_cython(self, directory, module, targetdir, incdir, annotate):
185 186 187
        include_dirs = INCLUDE_DIRS[:]
        if incdir:
            include_dirs.append(incdir)
188 189
        source = self.find_module_source_file(
            os.path.join(directory, module + '.pyx'))
190 191 192 193 194
        target = os.path.join(targetdir, module + '.c')
        options = CompilationOptions(
            pyrex_default_options,
            include_path = include_dirs,
            output_file = target,
195
            annotate = annotate,
196 197 198 199 200
            use_listing_file = False, cplus = False, generate_pxi = False)
        cython_compile(source, options=options,
                       full_module_name=module)

    def run_distutils(self, module, workdir, incdir):
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
        cwd = os.getcwd()
        os.chdir(workdir)
        try:
            build_extension = build_ext(distutils_distro)
            build_extension.include_dirs = INCLUDE_DIRS[:]
            if incdir:
                build_extension.include_dirs.append(incdir)
            build_extension.finalize_options()

            extension = Extension(
                module,
                sources = [module + '.c'],
                extra_compile_args = CFLAGS,
                )
            build_extension.extensions = [extension]
            build_extension.build_temp = workdir
            build_extension.build_lib  = workdir
            build_extension.run()
        finally:
            os.chdir(cwd)
221

222 223
    def compile(self, directory, module, workdir, incdir,
                expect_errors, annotate):
224 225 226 227 228
        expected_errors = errors = ()
        if expect_errors:
            expected_errors = self.split_source_and_output(
                directory, module, workdir)
            directory = workdir
229

230 231 232 233 234 235 236 237
        if WITH_CYTHON:
            old_stderr = sys.stderr
            try:
                sys.stderr = ErrorWriter()
                self.run_cython(directory, module, workdir, incdir, annotate)
                errors = sys.stderr.geterrors()
            finally:
                sys.stderr = old_stderr
238 239 240 241 242 243 244 245 246 247 248 249 250 251

        if errors or expected_errors:
            for expected, error in zip(expected_errors, errors):
                self.assertEquals(expected, error)
            if len(errors) < len(expected_errors):
                expected_error = expected_errors[len(errors)]
                self.assertEquals(expected_error, None)
            elif len(errors) > len(expected_errors):
                unexpected_error = errors[len(expected_errors)]
                self.assertEquals(None, unexpected_error)
        else:
            self.run_distutils(module, workdir, incdir)

class CythonRunTestCase(CythonCompileTestCase):
252 253
    def shortDescription(self):
        return "compiling and running " + self.module
254 255

    def run(self, result=None):
256 257
        if result is None:
            result = self.defaultTestResult()
Stefan Behnel's avatar
Stefan Behnel committed
258
        result.startTest(self)
259
        try:
260
            self.runCompileTest()
261
            doctest.DocTestSuite(self.module).run(result)
262 263 264
        except Exception:
            result.addError(self, sys.exc_info())
            result.stopTest(self)
265 266 267 268
        try:
            self.tearDown()
        except Exception:
            pass
269

270 271 272 273 274 275 276 277 278 279
class CythonUnitTestCase(CythonCompileTestCase):
    def shortDescription(self):
        return "compiling and running unit tests in " + self.module

    def run(self, result=None):
        if result is None:
            result = self.defaultTestResult()
        result.startTest(self)
        try:
            self.runCompileTest()
280
            unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
281 282 283 284 285 286 287 288
        except Exception:
            result.addError(self, sys.exc_info())
            result.stopTest(self)
        try:
            self.tearDown()
        except Exception:
            pass

289
def collect_unittests(path, suite, selectors):
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
    def file_matches(filename):
        return filename.startswith("Test") and filename.endswith(".py")

    def package_matches(dirname):
        return dirname == "Tests"

    loader = unittest.TestLoader()

    for dirpath, dirnames, filenames in os.walk(path):
        parentname = os.path.split(dirpath)[-1]
        if package_matches(parentname):
            for f in filenames:
                if file_matches(f):
                    filepath = os.path.join(dirpath, f)[:-len(".py")]
                    modulename = filepath[len(path)+1:].replace(os.path.sep, '.')
305 306
                    if not [ 1 for match in selectors if match(modulename) ]:
                        continue
307 308 309
                    module = __import__(modulename)
                    for x in modulename.split('.')[1:]:
                        module = getattr(module, x)
Robert Bradshaw's avatar
Robert Bradshaw committed
310
                    suite.addTests([loader.loadTestsFromModule(module)])
311

312
if __name__ == '__main__':
313 314 315
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option("--no-cleanup", dest="cleanup_workdir",
Stefan Behnel's avatar
Stefan Behnel committed
316 317
                      action="store_false", default=True,
                      help="do not delete the generated C files (allows passing --no-cython on next run)")
318 319 320
    parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
                      action="store_false", default=True,
                      help="do not delete the generated shared libary files (allows manual module experimentation)")
Stefan Behnel's avatar
Stefan Behnel committed
321 322 323
    parser.add_option("--no-cython", dest="with_cython",
                      action="store_false", default=True,
                      help="do not run the Cython compiler, only the C compiler")
324 325 326 327 328 329
    parser.add_option("--no-unit", dest="unittests",
                      action="store_false", default=True,
                      help="do not run the unit tests")
    parser.add_option("--no-file", dest="filetests",
                      action="store_false", default=True,
                      help="do not run the file based tests")
330 331 332
    parser.add_option("--no-pyregr", dest="pyregr",
                      action="store_false", default=True,
                      help="do not run the regression tests of CPython in tests/pyregr/")
333
    parser.add_option("-C", "--coverage", dest="coverage",
Stefan Behnel's avatar
Stefan Behnel committed
334 335 336 337 338
                      action="store_true", default=False,
                      help="collect source coverage data for the Compiler")
    parser.add_option("-A", "--annotate", dest="annotate_source",
                      action="store_true", default=False,
                      help="generate annotated HTML versions of the test source files")
339
    parser.add_option("-v", "--verbose", dest="verbosity",
Stefan Behnel's avatar
Stefan Behnel committed
340 341
                      action="count", default=0,
                      help="display test progress, pass twice to print test names")
342 343 344

    options, cmd_args = parser.parse_args()

345 346 347 348 349
    if options.coverage:
        import coverage
        coverage.erase()
        coverage.start()

350
    WITH_CYTHON = options.with_cython
351 352 353 354 355 356

    if WITH_CYTHON:
        from Cython.Compiler.Main import \
            CompilationOptions, \
            default_options as pyrex_default_options, \
            compile as cython_compile
357 358
        from Cython.Compiler import Errors
        Errors.LEVEL = 0 # show all warnings
359

360 361 362
    # RUN ALL TESTS!
    ROOTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]), 'tests')
    WORKDIR = os.path.join(os.getcwd(), 'BUILD')
363 364 365 366 367
    if WITH_CYTHON:
        if os.path.exists(WORKDIR):
            shutil.rmtree(WORKDIR, ignore_errors=True)
    if not os.path.exists(WORKDIR):
        os.makedirs(WORKDIR)
368

369 370 371 372 373
    if WITH_CYTHON:
        from Cython.Compiler.Version import version
        print("Running tests against Cython %s" % version)
    else:
        print("Running tests without Cython.")
Stefan Behnel's avatar
Stefan Behnel committed
374
    print("Python %s" % sys.version)
375
    print("")
376

377
    import re
378
    selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
379 380 381
    if not selectors:
        selectors = [ lambda x:True ]

382 383 384
    test_suite = unittest.TestSuite()

    if options.unittests:
385
        collect_unittests(os.getcwd(), test_suite, selectors)
386 387 388

    if options.filetests:
        filetests = TestBuilder(ROOTDIR, WORKDIR, selectors,
389
                                options.annotate_source, options.cleanup_workdir,
390
                                options.cleanup_sharedlibs, options.pyregr)
Robert Bradshaw's avatar
Robert Bradshaw committed
391
        test_suite.addTests([filetests.build_suite()])
392

393
    unittest.TextTestRunner(verbosity=options.verbosity).run(test_suite)
394

395
    if options.coverage:
396 397 398 399 400 401 402
        coverage.stop()
        ignored_modules = ('Options', 'Version', 'DebugFlags')
        modules = [ module for name, module in sys.modules.items()
                    if module is not None and
                    name.startswith('Cython.Compiler.') and 
                    name[len('Cython.Compiler.'):] not in ignored_modules ]
        coverage.report(modules, show_missing=0)