runtests.py 17.5 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
            if filename.startswith('.'): continue # certain emacs backup files
89 90
            if context == 'pyregr' and not filename.startswith('test_'):
                continue
91
            module = os.path.splitext(filename)[0]
92 93 94 95 96
            fqmodule = "%s.%s" % (context, module)
            if not [ 1 for match in self.selectors
                     if match(fqmodule) ]:
                continue
            if context in TEST_RUN_DIRS:
97 98 99 100 101
                if module.startswith("test_"):
                    build_test = CythonUnitTestCase
                else:
                    build_test = CythonRunTestCase
                test = build_test(
102 103
                    path, workdir, module,
                    annotate=self.annotate,
104 105
                    cleanup_workdir=self.cleanup_workdir,
                    cleanup_sharedlibs=self.cleanup_sharedlibs)
106 107
            else:
                test = CythonCompileTestCase(
108 109 110
                    path, workdir, module,
                    expect_errors=expect_errors,
                    annotate=self.annotate,
111 112
                    cleanup_workdir=self.cleanup_workdir,
                    cleanup_sharedlibs=self.cleanup_sharedlibs)
113
            suite.addTest(test)
114 115 116
        return suite

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

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

132
    def tearDown(self):
133
        cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
134
        cleanup_lib_files = self.cleanup_sharedlibs
135
        if os.path.exists(self.workdir):
136
            for rmfile in os.listdir(self.workdir):
137 138
                if not cleanup_c_files and rmfile[-2:] in (".c", ".h"):
                    continue
139 140
                if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
                    continue
141 142 143 144 145 146 147 148 149 150 151 152
                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)
153

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

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

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

166
    def split_source_and_output(self, directory, module, workdir):
167
        source_file = os.path.join(directory, module) + '.pyx'
168
        source_and_output = open(
169
            self.find_module_source_file(source_file), 'rU')
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
        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()

185
    def run_cython(self, directory, module, targetdir, incdir, annotate):
186 187 188
        include_dirs = INCLUDE_DIRS[:]
        if incdir:
            include_dirs.append(incdir)
189 190
        source = self.find_module_source_file(
            os.path.join(directory, module + '.pyx'))
191 192 193 194 195
        target = os.path.join(targetdir, module + '.c')
        options = CompilationOptions(
            pyrex_default_options,
            include_path = include_dirs,
            output_file = target,
196
            annotate = annotate,
197 198 199 200 201
            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):
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
        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)
222

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

231 232 233 234 235 236 237 238
        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
239 240 241 242 243 244 245 246 247 248 249 250 251 252

        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):
253 254
    def shortDescription(self):
        return "compiling and running " + self.module
255 256

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

271 272 273 274 275 276 277 278 279 280
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()
281
            unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
282 283 284 285 286 287 288 289
        except Exception:
            result.addError(self, sys.exc_info())
            result.stopTest(self)
        try:
            self.tearDown()
        except Exception:
            pass

290
def collect_unittests(path, module_prefix, suite, selectors):
291 292 293 294 295 296 297 298
    def file_matches(filename):
        return filename.startswith("Test") and filename.endswith(".py")

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

    loader = unittest.TestLoader()

299 300
    skipped_dirs = []

301
    for dirpath, dirnames, filenames in os.walk(path):
302 303 304 305 306 307 308 309 310
        if dirpath != path and "__init__.py" not in filenames:
            skipped_dirs.append(dirpath + os.path.sep)
            continue
        skip = False
        for dir in skipped_dirs:
            if dirpath.startswith(dir):
                skip = True
        if skip:
            continue
311 312 313 314 315
        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")]
316
                    modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
317 318
                    if not [ 1 for match in selectors if match(modulename) ]:
                        continue
319 320 321
                    module = __import__(modulename)
                    for x in modulename.split('.')[1:]:
                        module = getattr(module, x)
Robert Bradshaw's avatar
Robert Bradshaw committed
322
                    suite.addTests([loader.loadTestsFromModule(module)])
323

324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
def collect_doctests(path, module_prefix, suite, selectors):
    def package_matches(dirname):
        return dirname not in ("Mac", "Distutils", "Plex")
    def file_matches(filename):
        return (filename.endswith(".py") and not ('~' in filename
                or '#' in filename or filename.startswith('.')))
    import doctest, types
    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):
                    if not f.endswith('.py'): continue
                    filepath = os.path.join(dirpath, f)[:-len(".py")]
                    modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
                    if not [ 1 for match in selectors if match(modulename) ]:
                        continue
                    module = __import__(modulename)
                    for x in modulename.split('.')[1:]:
                        module = getattr(module, x)
                    if hasattr(module, "__doc__") or hasattr(module, "__test__"):
                        try:
346
                            suite.addTest(doctest.DocTestSuite(module))
347 348 349
                        except ValueError: # no tests
                            pass

350
if __name__ == '__main__':
351 352 353
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option("--no-cleanup", dest="cleanup_workdir",
Stefan Behnel's avatar
Stefan Behnel committed
354 355
                      action="store_false", default=True,
                      help="do not delete the generated C files (allows passing --no-cython on next run)")
356 357 358
    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
359 360 361
    parser.add_option("--no-cython", dest="with_cython",
                      action="store_false", default=True,
                      help="do not run the Cython compiler, only the C compiler")
362 363 364
    parser.add_option("--no-unit", dest="unittests",
                      action="store_false", default=True,
                      help="do not run the unit tests")
365 366 367
    parser.add_option("--no-doctest", dest="doctests",
                      action="store_false", default=True,
                      help="do not run the doctests")
368 369 370
    parser.add_option("--no-file", dest="filetests",
                      action="store_false", default=True,
                      help="do not run the file based tests")
371 372 373
    parser.add_option("--no-pyregr", dest="pyregr",
                      action="store_false", default=True,
                      help="do not run the regression tests of CPython in tests/pyregr/")
374
    parser.add_option("-C", "--coverage", dest="coverage",
Stefan Behnel's avatar
Stefan Behnel committed
375 376 377 378 379
                      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")
380
    parser.add_option("-v", "--verbose", dest="verbosity",
Stefan Behnel's avatar
Stefan Behnel committed
381 382
                      action="count", default=0,
                      help="display test progress, pass twice to print test names")
383 384 385

    options, cmd_args = parser.parse_args()

386 387 388 389 390 391 392
    if sys.version_info[0] >= 3:
        # make sure we do not import (or run) Cython itself
        options.doctests    = False
        options.with_cython = False
        options.unittests   = False
        options.pyregr      = False

393 394 395 396 397
    if options.coverage:
        import coverage
        coverage.erase()
        coverage.start()

398
    WITH_CYTHON = options.with_cython
399 400 401 402 403 404

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

408 409 410
    # RUN ALL TESTS!
    ROOTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]), 'tests')
    WORKDIR = os.path.join(os.getcwd(), 'BUILD')
411 412
    UNITTEST_MODULE = "Cython"
    UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
413 414 415 416 417
    if WITH_CYTHON:
        if os.path.exists(WORKDIR):
            shutil.rmtree(WORKDIR, ignore_errors=True)
    if not os.path.exists(WORKDIR):
        os.makedirs(WORKDIR)
418

419 420 421 422 423
    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
424
    print("Python %s" % sys.version)
425
    print("")
426

427
    import re
428
    selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
429 430 431
    if not selectors:
        selectors = [ lambda x:True ]

432 433 434
    test_suite = unittest.TestSuite()

    if options.unittests:
435
        collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
436

437 438
    if options.doctests:
        collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
439 440 441

    if options.filetests:
        filetests = TestBuilder(ROOTDIR, WORKDIR, selectors,
442
                                options.annotate_source, options.cleanup_workdir,
443
                                options.cleanup_sharedlibs, options.pyregr)
Robert Bradshaw's avatar
Robert Bradshaw committed
444
        test_suite.addTests([filetests.build_suite()])
445

446
    unittest.TextTestRunner(verbosity=options.verbosity).run(test_suite)
447

448
    if options.coverage:
449 450 451 452 453 454 455
        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)