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

3 4 5 6 7 8 9
import os
import sys
import re
import codecs
import shutil
import unittest
import doctest
10
import operator
11 12 13 14
try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO
15 16 17 18 19 20

try:
    import cPickle as pickle
except ImportError:
    import pickle

21

22
WITH_CYTHON = True
Robert Bradshaw's avatar
merge  
Robert Bradshaw committed
23

24
from distutils.dist import Distribution
25
from distutils.core import Extension
26
from distutils.command.build_ext import build_ext as _build_ext
27 28
distutils_distro = Distribution()

29
TEST_DIRS = ['compile', 'errors', 'run', 'pyregr']
30
TEST_RUN_DIRS = ['run', 'pyregr']
31

32 33 34 35 36 37
# Lists external modules, and a matcher matching tests
# which should be excluded if the module is not present.
EXT_DEP_MODULES = {
    'numpy' : re.compile('.*\.numpy_.*').match
}

38 39 40 41 42 43 44 45 46
def get_numpy_include_dirs():
    import numpy
    return [numpy.get_include()]

EXT_DEP_INCLUDES = [
    # test name matcher , callable returning list
    (re.compile('numpy_.*').match, get_numpy_include_dirs),
]

47
VER_DEP_MODULES = {
48
# such as:
49 50
#    (2,4) : (operator.le, lambda x: x in ['run.set']),
    (3,): (operator.ge, lambda x: x in ['run.non_future_division',
Stefan Behnel's avatar
Stefan Behnel committed
51 52
                                        'compile.extsetslice',
                                        'compile.extdelslice']),
53 54
}

55
INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
56 57
CFLAGS = os.getenv('CFLAGS', '').split()

58 59 60 61
class build_ext(_build_ext):
    def build_extension(self, ext):
        if ext.language == 'c++':
            try:
62 63 64 65 66
                try: # Py2.7+ & Py3.2+ 
                    compiler_obj = self.compiler_obj
                except AttributeError:
                    compiler_obj = self.compiler
                compiler_obj.compiler_so.remove('-Wstrict-prototypes')
67 68 69
            except Exception:
                pass
        _build_ext.build_extension(self, ext)
70 71

class ErrorWriter(object):
72
    match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
73 74 75 76
    def __init__(self):
        self.output = []
        self.write = self.output.append

77
    def _collect(self, collect_errors, collect_warnings):
78
        s = ''.join(self.output)
79
        result = []
80 81 82
        for line in s.split('\n'):
            match = self.match_error(line)
            if match:
83 84 85
                is_warning, line, column, message = match.groups()
                if (is_warning and collect_warnings) or \
                        (not is_warning and collect_errors):
86 87
                    result.append( (int(line), int(column), message.strip()) )
        result.sort()
Stefan Behnel's avatar
Stefan Behnel committed
88
        return [ "%d:%d: %s" % values for values in result ]
89 90 91 92 93 94 95 96 97

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

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

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

99
class TestBuilder(object):
100
    def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
101
                 cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
102
                 languages, test_bugs):
103 104
        self.rootdir = rootdir
        self.workdir = workdir
105
        self.selectors = selectors
106
        self.exclude_selectors = exclude_selectors
107
        self.annotate = annotate
108
        self.cleanup_workdir = cleanup_workdir
109
        self.cleanup_sharedlibs = cleanup_sharedlibs
110
        self.with_pyregr = with_pyregr
111 112
        self.cython_only = cython_only
        self.languages = languages
113
        self.test_bugs = test_bugs
114 115 116

    def build_suite(self):
        suite = unittest.TestSuite()
117
        test_dirs = TEST_DIRS
118 119 120
        filenames = os.listdir(self.rootdir)
        filenames.sort()
        for filename in filenames:
121 122 123
            if not WITH_CYTHON and filename == "errors":
                # we won't get any errors without running Cython
                continue
124
            path = os.path.join(self.rootdir, filename)
125
            if os.path.isdir(path) and filename in test_dirs:
126 127
                if filename == 'pyregr' and not self.with_pyregr:
                    continue
128
                suite.addTest(
129
                    self.handle_directory(path, filename))
130 131
        return suite

132
    def handle_directory(self, path, context):
133 134 135 136
        workdir = os.path.join(self.workdir, context)
        if not os.path.exists(workdir):
            os.makedirs(workdir)

137
        expect_errors = (context == 'errors')
138
        suite = unittest.TestSuite()
139 140 141
        filenames = os.listdir(path)
        filenames.sort()
        for filename in filenames:
142
            if not (filename.endswith(".pyx") or filename.endswith(".py")):
143
                continue
144
            if filename.startswith('.'): continue # certain emacs backup files
145 146
            if context == 'pyregr' and not filename.startswith('test_'):
                continue
147
            module = os.path.splitext(filename)[0]
148 149 150 151
            fqmodule = "%s.%s" % (context, module)
            if not [ 1 for match in self.selectors
                     if match(fqmodule) ]:
                continue
152 153 154
            if self.exclude_selectors:
                if [1 for match in self.exclude_selectors if match(fqmodule)]:
                    continue
155
            if context in TEST_RUN_DIRS:
156
                if module.startswith("test_"):
157
                    test_class = CythonUnitTestCase
158
                else:
159
                    test_class = CythonRunTestCase
160
            else:
161 162 163 164
                test_class = CythonCompileTestCase
            for test in self.build_tests(test_class, path, workdir,
                                         module, expect_errors):
                suite.addTest(test)
165 166
        return suite

167
    def build_tests(self, test_class, path, workdir, module, expect_errors):
168 169 170 171
        if expect_errors:
            languages = self.languages[:1]
        else:
            languages = self.languages
172 173 174
        if 'cpp' in module and 'c' in languages:
            languages = list(languages)
            languages.remove('c')
175 176
        tests = [ self.build_test(test_class, path, workdir, module,
                                  language, expect_errors)
177
                  for language in languages ]
178 179 180 181
        return tests

    def build_test(self, test_class, path, workdir, module,
                   language, expect_errors):
Stefan Behnel's avatar
Stefan Behnel committed
182 183 184
        workdir = os.path.join(workdir, language)
        if not os.path.exists(workdir):
            os.makedirs(workdir)
185 186 187 188 189 190 191 192
        return test_class(path, workdir, module,
                          language=language,
                          expect_errors=expect_errors,
                          annotate=self.annotate,
                          cleanup_workdir=self.cleanup_workdir,
                          cleanup_sharedlibs=self.cleanup_sharedlibs,
                          cython_only=self.cython_only)

193
class CythonCompileTestCase(unittest.TestCase):
194
    def __init__(self, directory, workdir, module, language='c',
195
                 expect_errors=False, annotate=False, cleanup_workdir=True,
196
                 cleanup_sharedlibs=True, cython_only=False):
197 198 199
        self.directory = directory
        self.workdir = workdir
        self.module = module
200
        self.language = language
201
        self.expect_errors = expect_errors
202
        self.annotate = annotate
203
        self.cleanup_workdir = cleanup_workdir
204
        self.cleanup_sharedlibs = cleanup_sharedlibs
205
        self.cython_only = cython_only
206 207 208
        unittest.TestCase.__init__(self)

    def shortDescription(self):
209
        return "compiling (%s) %s" % (self.language, self.module)
210

Stefan Behnel's avatar
Stefan Behnel committed
211 212 213 214
    def setUp(self):
        if self.workdir not in sys.path:
            sys.path.insert(0, self.workdir)

215
    def tearDown(self):
Stefan Behnel's avatar
Stefan Behnel committed
216 217 218 219 220 221 222 223
        try:
            sys.path.remove(self.workdir)
        except ValueError:
            pass
        try:
            del sys.modules[self.module]
        except KeyError:
            pass
224
        cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
225
        cleanup_lib_files = self.cleanup_sharedlibs
226
        if os.path.exists(self.workdir):
227
            for rmfile in os.listdir(self.workdir):
228 229 230
                if not cleanup_c_files:
                    if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
                        continue
231 232
                if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
                    continue
233 234 235 236 237 238 239 240 241 242 243 244
                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)
245

246
    def runTest(self):
247 248 249
        self.runCompileTest()

    def runCompileTest(self):
250
        self.compile(self.directory, self.module, self.workdir,
251
                     self.directory, self.expect_errors, self.annotate)
252

253 254 255 256 257
    def find_module_source_file(self, source_file):
        if not os.path.exists(source_file):
            source_file = source_file[:-1]
        return source_file

Stefan Behnel's avatar
Stefan Behnel committed
258 259 260 261
    def build_target_filename(self, module_name):
        target = '%s.%s' % (module_name, self.language)
        return target

262
    def split_source_and_output(self, directory, module, workdir):
263
        source_file = os.path.join(directory, module) + '.pyx'
264 265 266 267
        source_and_output = codecs.open(
            self.find_module_source_file(source_file), 'rU', 'ISO-8859-1')
        out = codecs.open(os.path.join(workdir, module + '.pyx'),
                          'w', 'ISO-8859-1')
268 269 270 271 272 273 274 275 276 277 278 279 280 281
        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()

282
    def run_cython(self, directory, module, targetdir, incdir, annotate):
283 284 285
        include_dirs = INCLUDE_DIRS[:]
        if incdir:
            include_dirs.append(incdir)
286 287
        source = self.find_module_source_file(
            os.path.join(directory, module + '.pyx'))
Stefan Behnel's avatar
Stefan Behnel committed
288
        target = os.path.join(targetdir, self.build_target_filename(module))
289 290 291 292
        options = CompilationOptions(
            pyrex_default_options,
            include_path = include_dirs,
            output_file = target,
293
            annotate = annotate,
294 295
            use_listing_file = False,
            cplus = self.language == 'cpp',
296 297 298
            generate_pxi = False,
            evaluate_tree_assertions = True,
            )
299 300 301 302
        cython_compile(source, options=options,
                       full_module_name=module)

    def run_distutils(self, module, workdir, incdir):
303 304 305 306 307 308 309 310
        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()
311 312 313 314
            ext_include_dirs = []
            for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
                if match(module):
                    ext_include_dirs += get_additional_include_dirs()
315 316
            extension = Extension(
                module,
Stefan Behnel's avatar
Stefan Behnel committed
317
                sources = [self.build_target_filename(module)],
318
                include_dirs = ext_include_dirs,
319 320
                extra_compile_args = CFLAGS,
                )
321 322
            if self.language == 'cpp':
                extension.language = 'c++'
323 324 325 326 327 328
            build_extension.extensions = [extension]
            build_extension.build_temp = workdir
            build_extension.build_lib  = workdir
            build_extension.run()
        finally:
            os.chdir(cwd)
329

330 331
    def compile(self, directory, module, workdir, incdir,
                expect_errors, annotate):
332 333 334 335 336
        expected_errors = errors = ()
        if expect_errors:
            expected_errors = self.split_source_and_output(
                directory, module, workdir)
            directory = workdir
337

338 339 340 341 342 343 344 345
        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
346 347

        if errors or expected_errors:
348 349 350 351 352 353 354 355 356 357 358 359
            try:
                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)
            except AssertionError:
                print("\n=== Expected errors: ===")
                print('\n'.join(expected_errors))
Stefan Behnel's avatar
Stefan Behnel committed
360
                print("\n\n=== Got errors: ===")
361 362 363
                print('\n'.join(errors))
                print('\n')
                raise
364
        else:
365
            if not self.cython_only:
366
                self.run_distutils(module, workdir, incdir)
367 368

class CythonRunTestCase(CythonCompileTestCase):
369
    def shortDescription(self):
370
        return "compiling (%s) and running %s" % (self.language, self.module)
371 372

    def run(self, result=None):
373 374
        if result is None:
            result = self.defaultTestResult()
Stefan Behnel's avatar
Stefan Behnel committed
375
        result.startTest(self)
376
        try:
Stefan Behnel's avatar
Stefan Behnel committed
377
            self.setUp()
378
            self.runCompileTest()
379
            if not self.cython_only:
380
                self.run_doctests(self.module, result)
381 382 383
        except Exception:
            result.addError(self, sys.exc_info())
            result.stopTest(self)
384 385 386 387
        try:
            self.tearDown()
        except Exception:
            pass
388

389
    def run_doctests(self, module_name, result):
390
        if sys.version_info[0] >= 3 or not hasattr(os, 'fork'):
391 392 393 394 395 396 397 398 399 400
            doctest.DocTestSuite(module_name).run(result)
            return

        # fork to make sure we do not keep the tested module loaded
        input, output = os.pipe()
        child_id = os.fork()
        if not child_id:
            result_code = 0
            try:
                output = os.fdopen(output, 'wb')
401
                tests = None
402 403
                try:
                    partial_result = PartialTestResult(result)
404 405
                    tests = doctest.DocTestSuite(module_name)
                    tests.run(partial_result)
406
                except Exception:
407 408 409 410 411 412
                    if tests is None:
                        # importing failed, try to fake a test class
                        tests = _FakeClass(
                            failureException=None,
                            **{module_name: None})
                    partial_result.addError(tests, sys.exc_info())
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
                    result_code = 1
                pickle.dump(partial_result.data(), output)
            finally:
                try: output.close()
                except: pass
                os._exit(result_code)

        input = os.fdopen(input, 'rb')
        PartialTestResult.join_results(result, pickle.load(input))
        cid, result_code = os.waitpid(child_id, 0)
        if result_code:
            raise Exception("Tests in module '%s' exited with status %d" %
                            (module_name, result_code >> 8))


428 429 430 431 432 433
is_private_field = re.compile('^_[^_]').match

class _FakeClass(object):
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

434 435 436 437 438 439
try: # Py2.7+ and Py3.2+
    from unittest.runner import _TextTestResult
except ImportError:
    from unittest import _TextTestResult

class PartialTestResult(_TextTestResult):
440
    def __init__(self, base_result):
441
        _TextTestResult.__init__(
442 443 444
            self, self._StringIO(), True,
            base_result.dots + base_result.showAll*2)

445 446 447 448 449 450 451 452 453
    def strip_error_results(self, results):
        for test_case, error in results:
            for attr_name in filter(is_private_field, dir(test_case)):
                if attr_name == '_dt_test':
                    test_case._dt_test = _FakeClass(
                        name=test_case._dt_test.name)
                else:
                    setattr(test_case, attr_name, None)

454
    def data(self):
455 456
        self.strip_error_results(self.failures)
        self.strip_error_results(self.errors)
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
        return (self.failures, self.errors, self.testsRun,
                self.stream.getvalue())

    def join_results(result, data):
        """Static method for merging the result back into the main
        result object.
        """
        errors, failures, tests_run, output = data
        if output:
            result.stream.write(output)
        result.errors.extend(errors)
        result.failures.extend(failures)
        result.testsRun += tests_run

    join_results = staticmethod(join_results)

    class _StringIO(StringIO):
        def writeln(self, line):
            self.write("%s\n" % line)


478 479
class CythonUnitTestCase(CythonCompileTestCase):
    def shortDescription(self):
480
        return "compiling (%s) tests in %s" % (self.language, self.module)
481 482 483 484 485 486

    def run(self, result=None):
        if result is None:
            result = self.defaultTestResult()
        result.startTest(self)
        try:
Stefan Behnel's avatar
Stefan Behnel committed
487
            self.setUp()
488
            self.runCompileTest()
489
            unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
490 491 492 493 494 495 496 497
        except Exception:
            result.addError(self, sys.exc_info())
            result.stopTest(self)
        try:
            self.tearDown()
        except Exception:
            pass

498
def collect_unittests(path, module_prefix, suite, selectors):
499 500 501 502 503 504 505 506
    def file_matches(filename):
        return filename.startswith("Test") and filename.endswith(".py")

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

    loader = unittest.TestLoader()

507 508
    skipped_dirs = []

509
    for dirpath, dirnames, filenames in os.walk(path):
510 511 512 513 514 515 516 517 518
        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
519 520 521 522 523
        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")]
524
                    modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
525 526
                    if not [ 1 for match in selectors if match(modulename) ]:
                        continue
527 528 529
                    module = __import__(modulename)
                    for x in modulename.split('.')[1:]:
                        module = getattr(module, x)
Robert Bradshaw's avatar
Robert Bradshaw committed
530
                    suite.addTests([loader.loadTestsFromModule(module)])
531

532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
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:
554
                            suite.addTest(doctest.DocTestSuite(module))
555 556 557
                        except ValueError: # no tests
                            pass

558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
class MissingDependencyExcluder:
    def __init__(self, deps):
        # deps: { module name : matcher func }
        self.exclude_matchers = []
        for mod, matcher in deps.items():
            try:
                __import__(mod)
            except ImportError:
                self.exclude_matchers.append(matcher)
        self.tests_missing_deps = []
    def __call__(self, testname):
        for matcher in self.exclude_matchers:
            if matcher(testname):
                self.tests_missing_deps.append(testname)
                return True
        return False

575 576 577 578 579
class VersionDependencyExcluder:
    def __init__(self, deps):
        # deps: { version : matcher func }
        from sys import version_info
        self.exclude_matchers = []
580 581
        for ver, (compare, matcher) in deps.items():
            if compare(version_info, ver):
582 583 584 585 586 587 588 589 590
                self.exclude_matchers.append(matcher)
        self.tests_missing_deps = []
    def __call__(self, testname):
        for matcher in self.exclude_matchers:
            if matcher(testname):
                self.tests_missing_deps.append(testname)
                return True
        return False

591 592 593 594 595 596 597 598 599 600 601 602
class FileListExcluder:

    def __init__(self, list_file):
        self.excludes = {}
        for line in open(list_file).readlines():
            line = line.strip()
            if line and line[0] != '#':
                self.excludes[line.split()[0]] = True
                
    def __call__(self, testname):
        return testname.split('.')[-1] in self.excludes

603
if __name__ == '__main__':
604 605 606
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option("--no-cleanup", dest="cleanup_workdir",
Stefan Behnel's avatar
Stefan Behnel committed
607 608
                      action="store_false", default=True,
                      help="do not delete the generated C files (allows passing --no-cython on next run)")
609 610 611
    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
612 613 614
    parser.add_option("--no-cython", dest="with_cython",
                      action="store_false", default=True,
                      help="do not run the Cython compiler, only the C compiler")
615 616 617 618 619 620
    parser.add_option("--no-c", dest="use_c",
                      action="store_false", default=True,
                      help="do not test C compilation")
    parser.add_option("--no-cpp", dest="use_cpp",
                      action="store_false", default=True,
                      help="do not test C++ compilation")
621 622 623
    parser.add_option("--no-unit", dest="unittests",
                      action="store_false", default=True,
                      help="do not run the unit tests")
624 625 626
    parser.add_option("--no-doctest", dest="doctests",
                      action="store_false", default=True,
                      help="do not run the doctests")
627 628 629
    parser.add_option("--no-file", dest="filetests",
                      action="store_false", default=True,
                      help="do not run the file based tests")
630 631
    parser.add_option("--no-pyregr", dest="pyregr",
                      action="store_false", default=True,
632
                      help="do not run the regression tests of CPython in tests/pyregr/")    
633
    parser.add_option("--cython-only", dest="cython_only",
634 635
                      action="store_true", default=False,
                      help="only compile pyx to c, do not run C compiler or run the tests")
636
    parser.add_option("--no-refnanny", dest="with_refnanny",
Stefan Behnel's avatar
Stefan Behnel committed
637
                      action="store_false", default=True,
638
                      help="do not regression test reference counting")
639 640 641
    parser.add_option("--sys-pyregr", dest="system_pyregr",
                      action="store_true", default=False,
                      help="run the regression tests of the CPython installation")
642 643 644
    parser.add_option("-x", "--exclude", dest="exclude",
                      action="append", metavar="PATTERN",
                      help="exclude tests matching the PATTERN")
645
    parser.add_option("-C", "--coverage", dest="coverage",
Stefan Behnel's avatar
Stefan Behnel committed
646 647 648
                      action="store_true", default=False,
                      help="collect source coverage data for the Compiler")
    parser.add_option("-A", "--annotate", dest="annotate_source",
649
                      action="store_true", default=True,
Stefan Behnel's avatar
Stefan Behnel committed
650
                      help="generate annotated HTML versions of the test source files")
651 652 653
    parser.add_option("--no-annotate", dest="annotate_source",
                      action="store_false",
                      help="do not generate annotated HTML versions of the test source files")
654
    parser.add_option("-v", "--verbose", dest="verbosity",
Stefan Behnel's avatar
Stefan Behnel committed
655 656
                      action="count", default=0,
                      help="display test progress, pass twice to print test names")
657 658 659
    parser.add_option("-T", "--ticket", dest="tickets",
                      action="append",
                      help="a bug ticket number to run the respective test in 'tests/bugs'")
660 661 662

    options, cmd_args = parser.parse_args()

663 664 665 666 667
    DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
    ROOTDIR = os.path.join(DISTDIR, 'tests')
    WORKDIR = os.path.join(os.getcwd(), 'BUILD')

    if sys.version_info >= (3,1):
668
        options.doctests    = False
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
        options.unittests   = False
        options.pyregr      = False
        if options.with_cython:
            # need to convert Cython sources first
            import lib2to3.refactor
            from distutils.util import copydir_run_2to3
            fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
                       if fix.split('fix_')[-1] not in ('next',)
                       ]
            cy3_dir = os.path.join(WORKDIR, 'Cy3')
            if not os.path.exists(cy3_dir):
                os.makedirs(cy3_dir)
            import distutils.log as dlog
            dlog.set_threshold(dlog.DEBUG)
            copydir_run_2to3(DISTDIR, cy3_dir, fixer_names=fixers,
                             template = '''
                             global-exclude *
                             graft Cython
                             recursive-exclude Cython *
                             recursive-include Cython *.py *.pyx *.pxd
                             ''')
            sys.path.insert(0, cy3_dir)
    elif sys.version_info[0] >= 3:
        # make sure we do not import (or run) Cython itself
693
        options.with_cython = False
694
        options.doctests    = False
695 696 697
        options.unittests   = False
        options.pyregr      = False

698 699 700 701 702
    if options.coverage:
        import coverage
        coverage.erase()
        coverage.start()

703
    WITH_CYTHON = options.with_cython
704 705 706 707 708 709

    if WITH_CYTHON:
        from Cython.Compiler.Main import \
            CompilationOptions, \
            default_options as pyrex_default_options, \
            compile as cython_compile
710 711
        from Cython.Compiler import Errors
        Errors.LEVEL = 0 # show all warnings
Stefan Behnel's avatar
Stefan Behnel committed
712
        from Cython.Compiler import Options
713
        Options.generate_cleanup_code = 3   # complete cleanup code
Stefan Behnel's avatar
Stefan Behnel committed
714 715
        from Cython.Compiler import DebugFlags
        DebugFlags.debug_temp_code_comments = 1
716

717
    # RUN ALL TESTS!
718 719
    UNITTEST_MODULE = "Cython"
    UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
720 721
    if WITH_CYTHON:
        if os.path.exists(WORKDIR):
722
            for path in os.listdir(WORKDIR):
723
                if path in ("support", "Cy3"): continue
724
                shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
725 726
    if not os.path.exists(WORKDIR):
        os.makedirs(WORKDIR)
727

728 729
    if WITH_CYTHON:
        from Cython.Compiler.Version import version
730
        sys.stderr.write("Running tests against Cython %s\n" % version)
731
    else:
732 733 734
        sys.stderr.write("Running tests without Cython.\n")
    sys.stderr.write("Python %s\n" % sys.version)
    sys.stderr.write("\n")
735

736 737 738 739 740
    if options.with_refnanny:
        from pyximport.pyxbuild import pyx_to_dll
        libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
                             build_in_temp=True,
                             pyxbuild_dir=os.path.join(WORKDIR, "support"))
741
        sys.path.insert(0, os.path.split(libpath)[0])
742
        CFLAGS.append("-DCYTHON_REFNANNY=1")
743

744
    test_bugs = False
Stefan Behnel's avatar
Stefan Behnel committed
745 746 747
    if options.tickets:
        for ticket_number in options.tickets:
            test_bugs = True
748
            cmd_args.append('.*T%s$' % ticket_number)
749 750 751 752
    if not test_bugs:
        for selector in cmd_args:
            if selector.startswith('bugs'):
                test_bugs = True
753

754
    import re
755
    selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
756 757 758
    if not selectors:
        selectors = [ lambda x:True ]

759 760 761 762
    # Chech which external modules are not present and exclude tests
    # which depends on them (by prefix)

    missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES) 
763 764
    version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES) 
    exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
765

766 767
    if options.exclude:
        exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
768 769 770
    
    if not test_bugs:
        exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
771

772 773 774 775 776 777
    languages = []
    if options.use_c:
        languages.append('c')
    if options.use_cpp:
        languages.append('cpp')

778 779 780
    test_suite = unittest.TestSuite()

    if options.unittests:
781
        collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
782

783 784
    if options.doctests:
        collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
785

786
    if options.filetests and languages:
787
        filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
788
                                options.annotate_source, options.cleanup_workdir,
Stefan Behnel's avatar
Stefan Behnel committed
789
                                options.cleanup_sharedlibs, options.pyregr,
790
                                options.cython_only, languages, test_bugs)
791 792
        test_suite.addTest(filetests.build_suite())

793
    if options.system_pyregr and languages:
Stefan Behnel's avatar
Stefan Behnel committed
794
        filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
795
                                options.annotate_source, options.cleanup_workdir,
Stefan Behnel's avatar
Stefan Behnel committed
796
                                options.cleanup_sharedlibs, True,
797
                                options.cython_only, languages, test_bugs)
798 799 800 801
        test_suite.addTest(
            filetests.handle_directory(
                os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
                'pyregr'))
802

803
    unittest.TextTestRunner(verbosity=options.verbosity).run(test_suite)
804

805
    if options.coverage:
806
        coverage.stop()
807
        ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
808 809 810 811 812
        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)
813 814 815 816 817

    if missing_dep_excluder.tests_missing_deps:
        sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
        for test in missing_dep_excluder.tests_missing_deps:
            sys.stderr.write("   %s\n" % test)
818

819
    if options.with_refnanny:
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
820
        import refnanny
821
        sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))